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