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