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