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