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