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