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