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