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