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