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