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