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