Merge "Add CollationFa"
[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 wfEscapeWikiText( $e->getMessage() )
1050 ];
1051 }
1052 $messages[] = ApiMessage::create( $params, $code );
1053 }
1054 return $messages;
1055 }
1056
1057 /**
1058 * Replace the result data with the information about an exception.
1059 * @param Exception $e
1060 * @return string[] Error codes
1061 */
1062 protected function substituteResultWithError( $e ) {
1063 $result = $this->getResult();
1064 $formatter = $this->getErrorFormatter();
1065 $config = $this->getConfig();
1066 $errorCodes = [];
1067
1068 // Remember existing warnings and errors across the reset
1069 $errors = $result->getResultData( [ 'errors' ] );
1070 $warnings = $result->getResultData( [ 'warnings' ] );
1071 $result->reset();
1072 if ( $warnings !== null ) {
1073 $result->addValue( null, 'warnings', $warnings, ApiResult::NO_SIZE_CHECK );
1074 }
1075 if ( $errors !== null ) {
1076 $result->addValue( null, 'errors', $errors, ApiResult::NO_SIZE_CHECK );
1077
1078 // Collect the copied error codes for the return value
1079 foreach ( $errors as $error ) {
1080 if ( isset( $error['code'] ) ) {
1081 $errorCodes[$error['code']] = true;
1082 }
1083 }
1084 }
1085
1086 // Add errors from the exception
1087 $modulePath = $e instanceof ApiUsageException ? $e->getModulePath() : null;
1088 foreach ( $this->errorMessagesFromException( $e, 'error' ) as $msg ) {
1089 $errorCodes[$msg->getApiCode()] = true;
1090 $formatter->addError( $modulePath, $msg );
1091 }
1092 foreach ( $this->errorMessagesFromException( $e, 'warning' ) as $msg ) {
1093 $formatter->addWarning( $modulePath, $msg );
1094 }
1095
1096 // Add additional data. Path depends on whether we're in BC mode or not.
1097 // Data depends on the type of exception.
1098 if ( $formatter instanceof ApiErrorFormatter_BackCompat ) {
1099 $path = [ 'error' ];
1100 } else {
1101 $path = null;
1102 }
1103 if ( $e instanceof ApiUsageException || $e instanceof UsageException ) {
1104 $link = wfExpandUrl( wfScript( 'api' ) );
1105 $result->addContentValue(
1106 $path,
1107 'docref',
1108 $this->msg( 'api-usage-docref', $link )->inLanguage( $formatter->getLanguage() )->text()
1109 );
1110 } else {
1111 if ( $config->get( 'ShowExceptionDetails' ) ) {
1112 $result->addContentValue(
1113 $path,
1114 'trace',
1115 $this->msg( 'api-exception-trace',
1116 get_class( $e ),
1117 $e->getFile(),
1118 $e->getLine(),
1119 MWExceptionHandler::getRedactedTraceAsString( $e )
1120 )->inLanguage( $formatter->getLanguage() )->text()
1121 );
1122 }
1123 }
1124
1125 // Add the id and such
1126 $this->addRequestedFields( [ 'servedby' ] );
1127
1128 return array_keys( $errorCodes );
1129 }
1130
1131 /**
1132 * Add requested fields to the result
1133 * @param string[] $force Which fields to force even if not requested. Accepted values are:
1134 * - servedby
1135 */
1136 protected function addRequestedFields( $force = [] ) {
1137 $result = $this->getResult();
1138
1139 $requestid = $this->getParameter( 'requestid' );
1140 if ( $requestid !== null ) {
1141 $result->addValue( null, 'requestid', $requestid, ApiResult::NO_SIZE_CHECK );
1142 }
1143
1144 if ( $this->getConfig()->get( 'ShowHostnames' ) && (
1145 in_array( 'servedby', $force, true ) || $this->getParameter( 'servedby' )
1146 ) ) {
1147 $result->addValue( null, 'servedby', wfHostname(), ApiResult::NO_SIZE_CHECK );
1148 }
1149
1150 if ( $this->getParameter( 'curtimestamp' ) ) {
1151 $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601, time() ),
1152 ApiResult::NO_SIZE_CHECK );
1153 }
1154
1155 if ( $this->getParameter( 'responselanginfo' ) ) {
1156 $result->addValue( null, 'uselang', $this->getLanguage()->getCode(),
1157 ApiResult::NO_SIZE_CHECK );
1158 $result->addValue( null, 'errorlang', $this->getErrorFormatter()->getLanguage()->getCode(),
1159 ApiResult::NO_SIZE_CHECK );
1160 }
1161 }
1162
1163 /**
1164 * Set up for the execution.
1165 * @return array
1166 */
1167 protected function setupExecuteAction() {
1168 $this->addRequestedFields();
1169
1170 $params = $this->extractRequestParams();
1171 $this->mAction = $params['action'];
1172
1173 return $params;
1174 }
1175
1176 /**
1177 * Set up the module for response
1178 * @return ApiBase The module that will handle this action
1179 * @throws MWException
1180 * @throws ApiUsageException
1181 */
1182 protected function setupModule() {
1183 // Instantiate the module requested by the user
1184 $module = $this->mModuleMgr->getModule( $this->mAction, 'action' );
1185 if ( $module === null ) {
1186 $this->dieWithError(
1187 [ 'apierror-unknownaction', wfEscapeWikiText( $this->mAction ) ], 'unknown_action'
1188 );
1189 }
1190 $moduleParams = $module->extractRequestParams();
1191
1192 // Check token, if necessary
1193 if ( $module->needsToken() === true ) {
1194 throw new MWException(
1195 "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
1196 'See documentation for ApiBase::needsToken for details.'
1197 );
1198 }
1199 if ( $module->needsToken() ) {
1200 if ( !$module->mustBePosted() ) {
1201 throw new MWException(
1202 "Module '{$module->getModuleName()}' must require POST to use tokens."
1203 );
1204 }
1205
1206 if ( !isset( $moduleParams['token'] ) ) {
1207 $module->dieWithError( [ 'apierror-missingparam', 'token' ] );
1208 }
1209
1210 $module->requirePostedParameters( [ 'token' ] );
1211
1212 if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) {
1213 $module->dieWithError( 'apierror-badtoken' );
1214 }
1215 }
1216
1217 return $module;
1218 }
1219
1220 /**
1221 * Check the max lag if necessary
1222 * @param ApiBase $module Api module being used
1223 * @param array $params Array an array containing the request parameters.
1224 * @return bool True on success, false should exit immediately
1225 */
1226 protected function checkMaxLag( $module, $params ) {
1227 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
1228 $maxLag = $params['maxlag'];
1229 list( $host, $lag ) = wfGetLB()->getMaxLag();
1230 if ( $lag > $maxLag ) {
1231 $response = $this->getRequest()->response();
1232
1233 $response->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
1234 $response->header( 'X-Database-Lag: ' . intval( $lag ) );
1235
1236 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
1237 $this->dieWithError( [ 'apierror-maxlag', $lag, $host ] );
1238 }
1239
1240 $this->dieWithError( [ 'apierror-maxlag-generic', $lag ], 'maxlag' );
1241 }
1242 }
1243
1244 return true;
1245 }
1246
1247 /**
1248 * Check selected RFC 7232 precondition headers
1249 *
1250 * RFC 7232 envisions a particular model where you send your request to "a
1251 * resource", and for write requests that you can read "the resource" by
1252 * changing the method to GET. When the API receives a GET request, it
1253 * works out even though "the resource" from RFC 7232's perspective might
1254 * be many resources from MediaWiki's perspective. But it totally fails for
1255 * a POST, since what HTTP sees as "the resource" is probably just
1256 * "/api.php" with all the interesting bits in the body.
1257 *
1258 * Therefore, we only support RFC 7232 precondition headers for GET (and
1259 * HEAD). That means we don't need to bother with If-Match and
1260 * If-Unmodified-Since since they only apply to modification requests.
1261 *
1262 * And since we don't support Range, If-Range is ignored too.
1263 *
1264 * @since 1.26
1265 * @param ApiBase $module Api module being used
1266 * @return bool True on success, false should exit immediately
1267 */
1268 protected function checkConditionalRequestHeaders( $module ) {
1269 if ( $this->mInternalMode ) {
1270 // No headers to check in internal mode
1271 return true;
1272 }
1273
1274 if ( $this->getRequest()->getMethod() !== 'GET' && $this->getRequest()->getMethod() !== 'HEAD' ) {
1275 // Don't check POSTs
1276 return true;
1277 }
1278
1279 $return304 = false;
1280
1281 $ifNoneMatch = array_diff(
1282 $this->getRequest()->getHeader( 'If-None-Match', WebRequest::GETHEADER_LIST ) ?: [],
1283 [ '' ]
1284 );
1285 if ( $ifNoneMatch ) {
1286 if ( $ifNoneMatch === [ '*' ] ) {
1287 // API responses always "exist"
1288 $etag = '*';
1289 } else {
1290 $etag = $module->getConditionalRequestData( 'etag' );
1291 }
1292 }
1293 if ( $ifNoneMatch && $etag !== null ) {
1294 $test = substr( $etag, 0, 2 ) === 'W/' ? substr( $etag, 2 ) : $etag;
1295 $match = array_map( function ( $s ) {
1296 return substr( $s, 0, 2 ) === 'W/' ? substr( $s, 2 ) : $s;
1297 }, $ifNoneMatch );
1298 $return304 = in_array( $test, $match, true );
1299 } else {
1300 $value = trim( $this->getRequest()->getHeader( 'If-Modified-Since' ) );
1301
1302 // Some old browsers sends sizes after the date, like this:
1303 // Wed, 20 Aug 2003 06:51:19 GMT; length=5202
1304 // Ignore that.
1305 $i = strpos( $value, ';' );
1306 if ( $i !== false ) {
1307 $value = trim( substr( $value, 0, $i ) );
1308 }
1309
1310 if ( $value !== '' ) {
1311 try {
1312 $ts = new MWTimestamp( $value );
1313 if (
1314 // RFC 7231 IMF-fixdate
1315 $ts->getTimestamp( TS_RFC2822 ) === $value ||
1316 // RFC 850
1317 $ts->format( 'l, d-M-y H:i:s' ) . ' GMT' === $value ||
1318 // asctime (with and without space-padded day)
1319 $ts->format( 'D M j H:i:s Y' ) === $value ||
1320 $ts->format( 'D M j H:i:s Y' ) === $value
1321 ) {
1322 $lastMod = $module->getConditionalRequestData( 'last-modified' );
1323 if ( $lastMod !== null ) {
1324 // Mix in some MediaWiki modification times
1325 $modifiedTimes = [
1326 'page' => $lastMod,
1327 'user' => $this->getUser()->getTouched(),
1328 'epoch' => $this->getConfig()->get( 'CacheEpoch' ),
1329 ];
1330 if ( $this->getConfig()->get( 'UseSquid' ) ) {
1331 // T46570: the core page itself may not change, but resources might
1332 $modifiedTimes['sepoch'] = wfTimestamp(
1333 TS_MW, time() - $this->getConfig()->get( 'SquidMaxage' )
1334 );
1335 }
1336 Hooks::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this->getOutput() ] );
1337 $lastMod = max( $modifiedTimes );
1338 $return304 = wfTimestamp( TS_MW, $lastMod ) <= $ts->getTimestamp( TS_MW );
1339 }
1340 }
1341 } catch ( TimestampException $e ) {
1342 // Invalid timestamp, ignore it
1343 }
1344 }
1345 }
1346
1347 if ( $return304 ) {
1348 $this->getRequest()->response()->statusHeader( 304 );
1349
1350 // Avoid outputting the compressed representation of a zero-length body
1351 MediaWiki\suppressWarnings();
1352 ini_set( 'zlib.output_compression', 0 );
1353 MediaWiki\restoreWarnings();
1354 wfClearOutputBuffers();
1355
1356 return false;
1357 }
1358
1359 return true;
1360 }
1361
1362 /**
1363 * Check for sufficient permissions to execute
1364 * @param ApiBase $module An Api module
1365 */
1366 protected function checkExecutePermissions( $module ) {
1367 $user = $this->getUser();
1368 if ( $module->isReadMode() && !User::isEveryoneAllowed( 'read' ) &&
1369 !$user->isAllowed( 'read' )
1370 ) {
1371 $this->dieWithError( 'apierror-readapidenied' );
1372 }
1373
1374 if ( $module->isWriteMode() ) {
1375 if ( !$this->mEnableWrite ) {
1376 $this->dieWithError( 'apierror-noapiwrite' );
1377 } elseif ( !$user->isAllowed( 'writeapi' ) ) {
1378 $this->dieWithError( 'apierror-writeapidenied' );
1379 } elseif ( $this->getRequest()->getHeader( 'Promise-Non-Write-API-Action' ) ) {
1380 $this->dieWithError( 'apierror-promised-nonwrite-api' );
1381 }
1382
1383 $this->checkReadOnly( $module );
1384 }
1385
1386 // Allow extensions to stop execution for arbitrary reasons.
1387 $message = false;
1388 if ( !Hooks::run( 'ApiCheckCanExecute', [ $module, $user, &$message ] ) ) {
1389 $this->dieWithError( $message );
1390 }
1391 }
1392
1393 /**
1394 * Check if the DB is read-only for this user
1395 * @param ApiBase $module An Api module
1396 */
1397 protected function checkReadOnly( $module ) {
1398 if ( wfReadOnly() ) {
1399 $this->dieReadOnly();
1400 }
1401
1402 if ( $module->isWriteMode()
1403 && $this->getUser()->isBot()
1404 && wfGetLB()->getServerCount() > 1
1405 ) {
1406 $this->checkBotReadOnly();
1407 }
1408 }
1409
1410 /**
1411 * Check whether we are readonly for bots
1412 */
1413 private function checkBotReadOnly() {
1414 // Figure out how many servers have passed the lag threshold
1415 $numLagged = 0;
1416 $lagLimit = $this->getConfig()->get( 'APIMaxLagThreshold' );
1417 $laggedServers = [];
1418 $loadBalancer = wfGetLB();
1419 foreach ( $loadBalancer->getLagTimes() as $serverIndex => $lag ) {
1420 if ( $lag > $lagLimit ) {
1421 ++$numLagged;
1422 $laggedServers[] = $loadBalancer->getServerName( $serverIndex ) . " ({$lag}s)";
1423 }
1424 }
1425
1426 // If a majority of replica DBs are too lagged then disallow writes
1427 $replicaCount = wfGetLB()->getServerCount() - 1;
1428 if ( $numLagged >= ceil( $replicaCount / 2 ) ) {
1429 $laggedServers = implode( ', ', $laggedServers );
1430 wfDebugLog(
1431 'api-readonly',
1432 "Api request failed as read only because the following DBs are lagged: $laggedServers"
1433 );
1434
1435 $this->dieWithError(
1436 'readonly_lag',
1437 'readonly',
1438 [ 'readonlyreason' => "Waiting for $numLagged lagged database(s)" ]
1439 );
1440 }
1441 }
1442
1443 /**
1444 * Check asserts of the user's rights
1445 * @param array $params
1446 */
1447 protected function checkAsserts( $params ) {
1448 if ( isset( $params['assert'] ) ) {
1449 $user = $this->getUser();
1450 switch ( $params['assert'] ) {
1451 case 'user':
1452 if ( $user->isAnon() ) {
1453 $this->dieWithError( 'apierror-assertuserfailed' );
1454 }
1455 break;
1456 case 'bot':
1457 if ( !$user->isAllowed( 'bot' ) ) {
1458 $this->dieWithError( 'apierror-assertbotfailed' );
1459 }
1460 break;
1461 }
1462 }
1463 if ( isset( $params['assertuser'] ) ) {
1464 $assertUser = User::newFromName( $params['assertuser'], false );
1465 if ( !$assertUser || !$this->getUser()->equals( $assertUser ) ) {
1466 $this->dieWithError(
1467 [ 'apierror-assertnameduserfailed', wfEscapeWikiText( $params['assertuser'] ) ]
1468 );
1469 }
1470 }
1471 }
1472
1473 /**
1474 * Check POST for external response and setup result printer
1475 * @param ApiBase $module An Api module
1476 * @param array $params An array with the request parameters
1477 */
1478 protected function setupExternalResponse( $module, $params ) {
1479 $request = $this->getRequest();
1480 if ( !$request->wasPosted() && $module->mustBePosted() ) {
1481 // Module requires POST. GET request might still be allowed
1482 // if $wgDebugApi is true, otherwise fail.
1483 $this->dieWithErrorOrDebug( [ 'apierror-mustbeposted', $this->mAction ] );
1484 }
1485
1486 // See if custom printer is used
1487 $this->mPrinter = $module->getCustomPrinter();
1488 if ( is_null( $this->mPrinter ) ) {
1489 // Create an appropriate printer
1490 $this->mPrinter = $this->createPrinterByName( $params['format'] );
1491 }
1492
1493 if ( $request->getProtocol() === 'http' && (
1494 $request->getSession()->shouldForceHTTPS() ||
1495 ( $this->getUser()->isLoggedIn() &&
1496 $this->getUser()->requiresHTTPS() )
1497 ) ) {
1498 $this->addDeprecation( 'apiwarn-deprecation-httpsexpected', 'https-expected' );
1499 }
1500 }
1501
1502 /**
1503 * Execute the actual module, without any error handling
1504 */
1505 protected function executeAction() {
1506 $params = $this->setupExecuteAction();
1507 $module = $this->setupModule();
1508 $this->mModule = $module;
1509
1510 if ( !$this->mInternalMode ) {
1511 $this->setRequestExpectations( $module );
1512 }
1513
1514 $this->checkExecutePermissions( $module );
1515
1516 if ( !$this->checkMaxLag( $module, $params ) ) {
1517 return;
1518 }
1519
1520 if ( !$this->checkConditionalRequestHeaders( $module ) ) {
1521 return;
1522 }
1523
1524 if ( !$this->mInternalMode ) {
1525 $this->setupExternalResponse( $module, $params );
1526 }
1527
1528 $this->checkAsserts( $params );
1529
1530 // Execute
1531 $module->execute();
1532 Hooks::run( 'APIAfterExecute', [ &$module ] );
1533
1534 $this->reportUnusedParams();
1535
1536 if ( !$this->mInternalMode ) {
1537 // append Debug information
1538 MWDebug::appendDebugInfoToApiResult( $this->getContext(), $this->getResult() );
1539
1540 // Print result data
1541 $this->printResult();
1542 }
1543 }
1544
1545 /**
1546 * Set database connection, query, and write expectations given this module request
1547 * @param ApiBase $module
1548 */
1549 protected function setRequestExpectations( ApiBase $module ) {
1550 $limits = $this->getConfig()->get( 'TrxProfilerLimits' );
1551 $trxProfiler = Profiler::instance()->getTransactionProfiler();
1552 $trxProfiler->setLogger( LoggerFactory::getInstance( 'DBPerformance' ) );
1553 if ( $this->getRequest()->hasSafeMethod() ) {
1554 $trxProfiler->setExpectations( $limits['GET'], __METHOD__ );
1555 } elseif ( $this->getRequest()->wasPosted() && !$module->isWriteMode() ) {
1556 $trxProfiler->setExpectations( $limits['POST-nonwrite'], __METHOD__ );
1557 $this->getRequest()->markAsSafeRequest();
1558 } else {
1559 $trxProfiler->setExpectations( $limits['POST'], __METHOD__ );
1560 }
1561 }
1562
1563 /**
1564 * Log the preceding request
1565 * @param float $time Time in seconds
1566 * @param Exception $e Exception caught while processing the request
1567 */
1568 protected function logRequest( $time, $e = null ) {
1569 $request = $this->getRequest();
1570 $logCtx = [
1571 'ts' => time(),
1572 'ip' => $request->getIP(),
1573 'userAgent' => $this->getUserAgent(),
1574 'wiki' => wfWikiID(),
1575 'timeSpentBackend' => (int)round( $time * 1000 ),
1576 'hadError' => $e !== null,
1577 'errorCodes' => [],
1578 'params' => [],
1579 ];
1580
1581 if ( $e ) {
1582 foreach ( $this->errorMessagesFromException( $e ) as $msg ) {
1583 $logCtx['errorCodes'][] = $msg->getApiCode();
1584 }
1585 }
1586
1587 // Construct space separated message for 'api' log channel
1588 $msg = "API {$request->getMethod()} " .
1589 wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
1590 " {$logCtx['ip']} " .
1591 "T={$logCtx['timeSpentBackend']}ms";
1592
1593 foreach ( $this->getParamsUsed() as $name ) {
1594 $value = $request->getVal( $name );
1595 if ( $value === null ) {
1596 continue;
1597 }
1598
1599 if ( strlen( $value ) > 256 ) {
1600 $value = substr( $value, 0, 256 );
1601 $encValue = $this->encodeRequestLogValue( $value ) . '[...]';
1602 } else {
1603 $encValue = $this->encodeRequestLogValue( $value );
1604 }
1605
1606 $logCtx['params'][$name] = $value;
1607 $msg .= " {$name}={$encValue}";
1608 }
1609
1610 wfDebugLog( 'api', $msg, 'private' );
1611 // ApiAction channel is for structured data consumers
1612 wfDebugLog( 'ApiAction', '', 'private', $logCtx );
1613 }
1614
1615 /**
1616 * Encode a value in a format suitable for a space-separated log line.
1617 * @param string $s
1618 * @return string
1619 */
1620 protected function encodeRequestLogValue( $s ) {
1621 static $table;
1622 if ( !$table ) {
1623 $chars = ';@$!*(),/:';
1624 $numChars = strlen( $chars );
1625 for ( $i = 0; $i < $numChars; $i++ ) {
1626 $table[rawurlencode( $chars[$i] )] = $chars[$i];
1627 }
1628 }
1629
1630 return strtr( rawurlencode( $s ), $table );
1631 }
1632
1633 /**
1634 * Get the request parameters used in the course of the preceding execute() request
1635 * @return array
1636 */
1637 protected function getParamsUsed() {
1638 return array_keys( $this->mParamsUsed );
1639 }
1640
1641 /**
1642 * Mark parameters as used
1643 * @param string|string[] $params
1644 */
1645 public function markParamsUsed( $params ) {
1646 $this->mParamsUsed += array_fill_keys( (array)$params, true );
1647 }
1648
1649 /**
1650 * Get a request value, and register the fact that it was used, for logging.
1651 * @param string $name
1652 * @param mixed $default
1653 * @return mixed
1654 */
1655 public function getVal( $name, $default = null ) {
1656 $this->mParamsUsed[$name] = true;
1657
1658 $ret = $this->getRequest()->getVal( $name );
1659 if ( $ret === null ) {
1660 if ( $this->getRequest()->getArray( $name ) !== null ) {
1661 // See bug 10262 for why we don't just implode( '|', ... ) the
1662 // array.
1663 $this->addWarning( [ 'apiwarn-unsupportedarray', $name ] );
1664 }
1665 $ret = $default;
1666 }
1667 return $ret;
1668 }
1669
1670 /**
1671 * Get a boolean request value, and register the fact that the parameter
1672 * was used, for logging.
1673 * @param string $name
1674 * @return bool
1675 */
1676 public function getCheck( $name ) {
1677 return $this->getVal( $name, null ) !== null;
1678 }
1679
1680 /**
1681 * Get a request upload, and register the fact that it was used, for logging.
1682 *
1683 * @since 1.21
1684 * @param string $name Parameter name
1685 * @return WebRequestUpload
1686 */
1687 public function getUpload( $name ) {
1688 $this->mParamsUsed[$name] = true;
1689
1690 return $this->getRequest()->getUpload( $name );
1691 }
1692
1693 /**
1694 * Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,
1695 * for example in case of spelling mistakes or a missing 'g' prefix for generators.
1696 */
1697 protected function reportUnusedParams() {
1698 $paramsUsed = $this->getParamsUsed();
1699 $allParams = $this->getRequest()->getValueNames();
1700
1701 if ( !$this->mInternalMode ) {
1702 // Printer has not yet executed; don't warn that its parameters are unused
1703 $printerParams = $this->mPrinter->encodeParamName(
1704 array_keys( $this->mPrinter->getFinalParams() ?: [] )
1705 );
1706 $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1707 } else {
1708 $unusedParams = array_diff( $allParams, $paramsUsed );
1709 }
1710
1711 if ( count( $unusedParams ) ) {
1712 $this->addWarning( [
1713 'apierror-unrecognizedparams',
1714 Message::listParam( array_map( 'wfEscapeWikiText', $unusedParams ), 'comma' ),
1715 count( $unusedParams )
1716 ] );
1717 }
1718 }
1719
1720 /**
1721 * Print results using the current printer
1722 *
1723 * @param int $httpCode HTTP status code, or 0 to not change
1724 */
1725 protected function printResult( $httpCode = 0 ) {
1726 if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
1727 $this->addWarning( 'apiwarn-wgDebugAPI' );
1728 }
1729
1730 $printer = $this->mPrinter;
1731 $printer->initPrinter( false );
1732 if ( $httpCode ) {
1733 $printer->setHttpStatus( $httpCode );
1734 }
1735 $printer->execute();
1736 $printer->closePrinter();
1737 }
1738
1739 /**
1740 * @return bool
1741 */
1742 public function isReadMode() {
1743 return false;
1744 }
1745
1746 /**
1747 * See ApiBase for description.
1748 *
1749 * @return array
1750 */
1751 public function getAllowedParams() {
1752 return [
1753 'action' => [
1754 ApiBase::PARAM_DFLT => 'help',
1755 ApiBase::PARAM_TYPE => 'submodule',
1756 ],
1757 'format' => [
1758 ApiBase::PARAM_DFLT => ApiMain::API_DEFAULT_FORMAT,
1759 ApiBase::PARAM_TYPE => 'submodule',
1760 ],
1761 'maxlag' => [
1762 ApiBase::PARAM_TYPE => 'integer'
1763 ],
1764 'smaxage' => [
1765 ApiBase::PARAM_TYPE => 'integer',
1766 ApiBase::PARAM_DFLT => 0
1767 ],
1768 'maxage' => [
1769 ApiBase::PARAM_TYPE => 'integer',
1770 ApiBase::PARAM_DFLT => 0
1771 ],
1772 'assert' => [
1773 ApiBase::PARAM_TYPE => [ 'user', 'bot' ]
1774 ],
1775 'assertuser' => [
1776 ApiBase::PARAM_TYPE => 'user',
1777 ],
1778 'requestid' => null,
1779 'servedby' => false,
1780 'curtimestamp' => false,
1781 'responselanginfo' => false,
1782 'origin' => null,
1783 'uselang' => [
1784 ApiBase::PARAM_DFLT => self::API_DEFAULT_USELANG,
1785 ],
1786 'errorformat' => [
1787 ApiBase::PARAM_TYPE => [ 'plaintext', 'wikitext', 'html', 'raw', 'none', 'bc' ],
1788 ApiBase::PARAM_DFLT => 'bc',
1789 ],
1790 'errorlang' => [
1791 ApiBase::PARAM_DFLT => 'uselang',
1792 ],
1793 'errorsuselocal' => [
1794 ApiBase::PARAM_DFLT => false,
1795 ],
1796 ];
1797 }
1798
1799 /** @see ApiBase::getExamplesMessages() */
1800 protected function getExamplesMessages() {
1801 return [
1802 'action=help'
1803 => 'apihelp-help-example-main',
1804 'action=help&recursivesubmodules=1'
1805 => 'apihelp-help-example-recursive',
1806 ];
1807 }
1808
1809 public function modifyHelp( array &$help, array $options, array &$tocData ) {
1810 // Wish PHP had an "array_insert_before". Instead, we have to manually
1811 // reindex the array to get 'permissions' in the right place.
1812 $oldHelp = $help;
1813 $help = [];
1814 foreach ( $oldHelp as $k => $v ) {
1815 if ( $k === 'submodules' ) {
1816 $help['permissions'] = '';
1817 }
1818 $help[$k] = $v;
1819 }
1820 $help['datatypes'] = '';
1821 $help['credits'] = '';
1822
1823 // Fill 'permissions'
1824 $help['permissions'] .= Html::openElement( 'div',
1825 [ 'class' => 'apihelp-block apihelp-permissions' ] );
1826 $m = $this->msg( 'api-help-permissions' );
1827 if ( !$m->isDisabled() ) {
1828 $help['permissions'] .= Html::rawElement( 'div', [ 'class' => 'apihelp-block-head' ],
1829 $m->numParams( count( self::$mRights ) )->parse()
1830 );
1831 }
1832 $help['permissions'] .= Html::openElement( 'dl' );
1833 foreach ( self::$mRights as $right => $rightMsg ) {
1834 $help['permissions'] .= Html::element( 'dt', null, $right );
1835
1836 $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse();
1837 $help['permissions'] .= Html::rawElement( 'dd', null, $rightMsg );
1838
1839 $groups = array_map( function ( $group ) {
1840 return $group == '*' ? 'all' : $group;
1841 }, User::getGroupsWithPermission( $right ) );
1842
1843 $help['permissions'] .= Html::rawElement( 'dd', null,
1844 $this->msg( 'api-help-permissions-granted-to' )
1845 ->numParams( count( $groups ) )
1846 ->params( Message::listParam( $groups ) )
1847 ->parse()
1848 );
1849 }
1850 $help['permissions'] .= Html::closeElement( 'dl' );
1851 $help['permissions'] .= Html::closeElement( 'div' );
1852
1853 // Fill 'datatypes' and 'credits', if applicable
1854 if ( empty( $options['nolead'] ) ) {
1855 $level = $options['headerlevel'];
1856 $tocnumber = &$options['tocnumber'];
1857
1858 $header = $this->msg( 'api-help-datatypes-header' )->parse();
1859
1860 // Add an additional span with sanitized ID
1861 if ( !$this->getConfig()->get( 'ExperimentalHtmlIds' ) ) {
1862 $header = Html::element( 'span', [ 'id' => Sanitizer::escapeId( 'main/datatypes' ) ] ) .
1863 $header;
1864 }
1865 $help['datatypes'] .= Html::rawElement( 'h' . min( 6, $level ),
1866 [ 'id' => 'main/datatypes', 'class' => 'apihelp-header' ],
1867 $header
1868 );
1869 $help['datatypes'] .= $this->msg( 'api-help-datatypes' )->parseAsBlock();
1870 if ( !isset( $tocData['main/datatypes'] ) ) {
1871 $tocnumber[$level]++;
1872 $tocData['main/datatypes'] = [
1873 'toclevel' => count( $tocnumber ),
1874 'level' => $level,
1875 'anchor' => 'main/datatypes',
1876 'line' => $header,
1877 'number' => implode( '.', $tocnumber ),
1878 'index' => false,
1879 ];
1880 }
1881
1882 // Add an additional span with sanitized ID
1883 if ( !$this->getConfig()->get( 'ExperimentalHtmlIds' ) ) {
1884 $header = Html::element( 'span', [ 'id' => Sanitizer::escapeId( 'main/credits' ) ] ) .
1885 $header;
1886 }
1887 $header = $this->msg( 'api-credits-header' )->parse();
1888 $help['credits'] .= Html::rawElement( 'h' . min( 6, $level ),
1889 [ 'id' => 'main/credits', 'class' => 'apihelp-header' ],
1890 $header
1891 );
1892 $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
1893 if ( !isset( $tocData['main/credits'] ) ) {
1894 $tocnumber[$level]++;
1895 $tocData['main/credits'] = [
1896 'toclevel' => count( $tocnumber ),
1897 'level' => $level,
1898 'anchor' => 'main/credits',
1899 'line' => $header,
1900 'number' => implode( '.', $tocnumber ),
1901 'index' => false,
1902 ];
1903 }
1904 }
1905 }
1906
1907 private $mCanApiHighLimits = null;
1908
1909 /**
1910 * Check whether the current user is allowed to use high limits
1911 * @return bool
1912 */
1913 public function canApiHighLimits() {
1914 if ( !isset( $this->mCanApiHighLimits ) ) {
1915 $this->mCanApiHighLimits = $this->getUser()->isAllowed( 'apihighlimits' );
1916 }
1917
1918 return $this->mCanApiHighLimits;
1919 }
1920
1921 /**
1922 * Overrides to return this instance's module manager.
1923 * @return ApiModuleManager
1924 */
1925 public function getModuleManager() {
1926 return $this->mModuleMgr;
1927 }
1928
1929 /**
1930 * Fetches the user agent used for this request
1931 *
1932 * The value will be the combination of the 'Api-User-Agent' header (if
1933 * any) and the standard User-Agent header (if any).
1934 *
1935 * @return string
1936 */
1937 public function getUserAgent() {
1938 return trim(
1939 $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
1940 $this->getRequest()->getHeader( 'User-agent' )
1941 );
1942 }
1943 }
1944
1945 /**
1946 * For really cool vim folding this needs to be at the end:
1947 * vim: foldmarker=@{,@} foldmethod=marker
1948 */