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