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