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