MediaWiki  master
ApiMain.php
Go to the documentation of this file.
1 <?php
30 use Wikimedia\Timestamp\TimestampException;
31 
48 class ApiMain extends ApiBase {
52  private const API_DEFAULT_FORMAT = 'jsonfm';
53 
57  private const API_DEFAULT_USELANG = 'user';
58 
62  private const MODULES = [
63  'login' => ApiLogin::class,
64  'clientlogin' => ApiClientLogin::class,
65  'logout' => ApiLogout::class,
66  'createaccount' => ApiAMCreateAccount::class,
67  'linkaccount' => ApiLinkAccount::class,
68  'unlinkaccount' => ApiRemoveAuthenticationData::class,
69  'changeauthenticationdata' => ApiChangeAuthenticationData::class,
70  'removeauthenticationdata' => ApiRemoveAuthenticationData::class,
71  'resetpassword' => [
72  'class' => ApiResetPassword::class,
73  'services' => [
74  'PasswordReset',
75  ]
76  ],
77  'query' => ApiQuery::class,
78  'expandtemplates' => ApiExpandTemplates::class,
79  'parse' => ApiParse::class,
80  'stashedit' => [
81  'class' => ApiStashEdit::class,
82  'services' => [
83  'ContentHandlerFactory',
84  'PageEditStash',
85  'RevisionLookup',
86  'StatsdDataFactory',
87  ]
88  ],
89  'opensearch' => ApiOpenSearch::class,
90  'feedcontributions' => ApiFeedContributions::class,
91  'feedrecentchanges' => [
92  'class' => ApiFeedRecentChanges::class,
93  'services' => [
94  'SpecialPageFactory',
95  ]
96  ],
97  'feedwatchlist' => ApiFeedWatchlist::class,
98  'help' => ApiHelp::class,
99  'paraminfo' => ApiParamInfo::class,
100  'rsd' => ApiRsd::class,
101  'compare' => ApiComparePages::class,
102  'tokens' => ApiTokens::class,
103  'checktoken' => ApiCheckToken::class,
104  'cspreport' => ApiCSPReport::class,
105  'validatepassword' => [
106  'class' => ApiValidatePassword::class,
107  'services' => [
108  'AuthManager',
109  'UserFactory',
110  ]
111  ],
112 
113  // Write modules
114  'purge' => ApiPurge::class,
115  'setnotificationtimestamp' => [
116  'class' => ApiSetNotificationTimestamp::class,
117  'services' => [
118  'DBLoadBalancer',
119  'RevisionStore',
120  'WatchedItemStore',
121  ]
122  ],
123  'rollback' => ApiRollback::class,
124  'delete' => ApiDelete::class,
125  'undelete' => ApiUndelete::class,
126  'protect' => ApiProtect::class,
127  'block' => [
128  'class' => ApiBlock::class,
129  'services' => [
130  'BlockPermissionCheckerFactory',
131  'BlockUserFactory',
132  'TitleFactory',
133  'UserFactory',
134  'WatchedItemStore',
135  'BlockUtils'
136  ]
137  ],
138  'unblock' => [
139  'class' => ApiUnblock::class,
140  'services' => [
141  'BlockPermissionCheckerFactory',
142  'UnblockUserFactory',
143  'UserCache',
144  ]
145  ],
146  'move' => [
147  'class' => ApiMove::class,
148  'services' => [
149  'MovePageFactory',
150  ]
151  ],
152  'edit' => ApiEditPage::class,
153  'upload' => ApiUpload::class,
154  'filerevert' => ApiFileRevert::class,
155  'emailuser' => ApiEmailUser::class,
156  'watch' => ApiWatch::class,
157  'patrol' => ApiPatrol::class,
158  'import' => ApiImport::class,
159  'clearhasmsg' => [
160  'class' => ApiClearHasMsg::class,
161  'services' => [
162  'TalkPageNotificationManager',
163  ]
164  ],
165  'userrights' => ApiUserrights::class,
166  'options' => ApiOptions::class,
167  'imagerotate' => ApiImageRotate::class,
168  'revisiondelete' => ApiRevisionDelete::class,
169  'managetags' => ApiManageTags::class,
170  'tag' => ApiTag::class,
171  'mergehistory' => ApiMergeHistory::class,
172  'setpagelanguage' => ApiSetPageLanguage::class,
173  'changecontentmodel' => [
174  'class' => ApiChangeContentModel::class,
175  'services' => [
176  'ContentHandlerFactory',
177  'ContentModelChangeFactory',
178  ]
179  ],
180  ];
181 
185  private const FORMATS = [
186  'json' => ApiFormatJson::class,
187  'jsonfm' => ApiFormatJson::class,
188  'php' => ApiFormatPhp::class,
189  'phpfm' => ApiFormatPhp::class,
190  'xml' => ApiFormatXml::class,
191  'xmlfm' => ApiFormatXml::class,
192  'rawfm' => ApiFormatJson::class,
193  'none' => ApiFormatNone::class,
194  ];
195 
202  private const RIGHTS_MAP = [
203  'writeapi' => [
204  'msg' => 'right-writeapi',
205  'params' => []
206  ],
207  'apihighlimits' => [
208  'msg' => 'api-help-right-apihighlimits',
210  ]
211  ];
212 
214  private $mPrinter;
215 
217  private $mModuleMgr;
218 
220  private $mResult;
221 
224 
227 
230 
232  private $mAction;
233 
235  private $mEnableWrite;
236 
238  private $mInternalMode;
239 
241  private $mModule;
242 
244  private $mCacheMode = 'private';
245 
247  private $mCacheControl = [];
248 
250  private $mParamsUsed = [];
251 
253  private $mParamsSensitive = [];
254 
256  private $lacksSameOriginSecurity = null;
257 
266  public function __construct( $context = null, $enableWrite = false ) {
267  if ( $context === null ) {
269  } elseif ( $context instanceof WebRequest ) {
270  // BC for pre-1.19
271  $request = $context;
273  }
274  // We set a derivative context so we can change stuff later
275  $derivativeContext = new DerivativeContext( $context );
276  $this->setContext( $derivativeContext );
277 
278  if ( isset( $request ) ) {
279  $derivativeContext->setRequest( $request );
280  } else {
281  $request = $this->getRequest();
282  }
283 
284  $this->mInternalMode = ( $request instanceof FauxRequest );
285 
286  // Special handling for the main module: $parent === $this
287  parent::__construct( $this, $this->mInternalMode ? 'main_int' : 'main' );
288 
289  $config = $this->getConfig();
290 
291  if ( !$this->mInternalMode ) {
292  // If we're in a mode that breaks the same-origin policy, strip
293  // user credentials for security.
294  if ( $this->lacksSameOriginSecurity() ) {
295  global $wgUser;
296  wfDebug( "API: stripping user credentials when the same-origin policy is not applied" );
297  $user = new User();
298  $wgUser = $user;
299  $derivativeContext->setUser( $user );
300  $request->response()->header( 'MediaWiki-Login-Suppressed: true' );
301  }
302  }
303 
304  // TODO inject stuff, see T265644
305  $services = MediaWikiServices::getInstance();
306  $this->mParamValidator = new ApiParamValidator(
307  $this,
308  $services->getObjectFactory()
309  );
310 
311  $this->mResult = new ApiResult( $this->getConfig()->get( 'APIMaxResultSize' ) );
312 
313  // Setup uselang. This doesn't use $this->getParameter()
314  // because we're not ready to handle errors yet.
315  // Optimisation: Avoid slow getVal(), this isn't user-generated content.
316  $uselang = $request->getRawVal( 'uselang', self::API_DEFAULT_USELANG );
317  if ( $uselang === 'user' ) {
318  // Assume the parent context is going to return the user language
319  // for uselang=user (see T85635).
320  } else {
321  if ( $uselang === 'content' ) {
322  $uselang = $services->getContentLanguage()->getCode();
323  }
324  $code = RequestContext::sanitizeLangCode( $uselang );
325  $derivativeContext->setLanguage( $code );
326  if ( !$this->mInternalMode ) {
327  global $wgLang;
328  $wgLang = $derivativeContext->getLanguage();
329  RequestContext::getMain()->setLanguage( $wgLang );
330  }
331  }
332 
333  // Set up the error formatter. This doesn't use $this->getParameter()
334  // because we're not ready to handle errors yet.
335  // Optimisation: Avoid slow getVal(), this isn't user-generated content.
336  $errorFormat = $request->getRawVal( 'errorformat', 'bc' );
337  $errorLangCode = $request->getRawVal( 'errorlang', 'uselang' );
338  $errorsUseDB = $request->getCheck( 'errorsuselocal' );
339  if ( in_array( $errorFormat, [ 'plaintext', 'wikitext', 'html', 'raw', 'none' ], true ) ) {
340  if ( $errorLangCode === 'uselang' ) {
341  $errorLang = $this->getLanguage();
342  } elseif ( $errorLangCode === 'content' ) {
343  $errorLang = $services->getContentLanguage();
344  } else {
345  $errorLangCode = RequestContext::sanitizeLangCode( $errorLangCode );
346  $errorLang = $services->getLanguageFactory()->getLanguage( $errorLangCode );
347  }
348  $this->mErrorFormatter = new ApiErrorFormatter(
349  $this->mResult,
350  $errorLang,
351  $errorFormat,
352  $errorsUseDB
353  );
354  } else {
355  $this->mErrorFormatter = new ApiErrorFormatter_BackCompat( $this->mResult );
356  }
357  $this->mResult->setErrorFormatter( $this->getErrorFormatter() );
358 
359  $this->mModuleMgr = new ApiModuleManager(
360  $this,
361  $services->getObjectFactory()
362  );
363  $this->mModuleMgr->addModules( self::MODULES, 'action' );
364  $this->mModuleMgr->addModules( $config->get( 'APIModules' ), 'action' );
365  $this->mModuleMgr->addModules( self::FORMATS, 'format' );
366  $this->mModuleMgr->addModules( $config->get( 'APIFormatModules' ), 'format' );
367 
368  $this->getHookRunner()->onApiMain__moduleManager( $this->mModuleMgr );
369 
370  $this->mContinuationManager = null;
371  $this->mEnableWrite = $enableWrite;
372  }
373 
378  public function isInternalMode() {
379  return $this->mInternalMode;
380  }
381 
387  public function getResult() {
388  return $this->mResult;
389  }
390 
395  public function lacksSameOriginSecurity() {
396  if ( $this->lacksSameOriginSecurity !== null ) {
398  }
399 
400  $request = $this->getRequest();
401 
402  // JSONP mode
403  if ( $request->getCheck( 'callback' ) ) {
404  $this->lacksSameOriginSecurity = true;
405  return true;
406  }
407 
408  // Anonymous CORS
409  if ( $request->getVal( 'origin' ) === '*' ) {
410  $this->lacksSameOriginSecurity = true;
411  return true;
412  }
413 
414  // Header to be used from XMLHTTPRequest when the request might
415  // otherwise be used for XSS.
416  if ( $request->getHeader( 'Treat-as-Untrusted' ) !== false ) {
417  $this->lacksSameOriginSecurity = true;
418  return true;
419  }
420 
421  // Allow extensions to override.
422  $this->lacksSameOriginSecurity = !$this->getHookRunner()
423  ->onRequestHasSameOriginSecurity( $request );
425  }
426 
431  public function getErrorFormatter() {
432  return $this->mErrorFormatter;
433  }
434 
438  public function getContinuationManager() {
440  }
441 
445  public function setContinuationManager( ApiContinuationManager $manager = null ) {
446  if ( $manager !== null && $this->mContinuationManager !== null ) {
447  throw new UnexpectedValueException(
448  __METHOD__ . ': tried to set manager from ' . $manager->getSource() .
449  ' when a manager is already set from ' . $this->mContinuationManager->getSource()
450  );
451  }
452  $this->mContinuationManager = $manager;
453  }
454 
459  public function getParamValidator() : ApiParamValidator {
460  return $this->mParamValidator;
461  }
462 
468  public function getModule() {
469  return $this->mModule;
470  }
471 
477  public function getPrinter() {
478  return $this->mPrinter;
479  }
480 
486  public function setCacheMaxAge( $maxage ) {
487  $this->setCacheControl( [
488  'max-age' => $maxage,
489  's-maxage' => $maxage
490  ] );
491  }
492 
518  public function setCacheMode( $mode ) {
519  if ( !in_array( $mode, [ 'private', 'public', 'anon-public-user-private' ] ) ) {
520  wfDebug( __METHOD__ . ": unrecognised cache mode \"$mode\"" );
521 
522  // Ignore for forwards-compatibility
523  return;
524  }
525 
526  if ( !$this->getPermissionManager()->isEveryoneAllowed( 'read' ) ) {
527  // Private wiki, only private headers
528  if ( $mode !== 'private' ) {
529  wfDebug( __METHOD__ . ": ignoring request for $mode cache mode, private wiki" );
530 
531  return;
532  }
533  }
534 
535  if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) {
536  // User language is used for i18n, so we don't want to publicly
537  // cache. Anons are ok, because if they have non-default language
538  // then there's an appropriate Vary header set by whatever set
539  // their non-default language.
540  wfDebug( __METHOD__ . ": downgrading cache mode 'public' to " .
541  "'anon-public-user-private' due to uselang=user" );
542  $mode = 'anon-public-user-private';
543  }
544 
545  wfDebug( __METHOD__ . ": setting cache mode $mode" );
546  $this->mCacheMode = $mode;
547  }
548 
559  public function setCacheControl( $directives ) {
560  $this->mCacheControl = $directives + $this->mCacheControl;
561  }
562 
570  public function createPrinterByName( $format ) {
571  $printer = $this->mModuleMgr->getModule( $format, 'format', /* $ignoreCache */ true );
572  if ( $printer === null ) {
573  $this->dieWithError(
574  [ 'apierror-unknownformat', wfEscapeWikiText( $format ) ], 'unknown_format'
575  );
576  }
577 
578  return $printer;
579  }
580 
584  public function execute() {
585  if ( $this->mInternalMode ) {
586  $this->executeAction();
587  } else {
589  }
590  }
591 
596  protected function executeActionWithErrorHandling() {
597  // Verify the CORS header before executing the action
598  if ( !$this->handleCORS() ) {
599  // handleCORS() has sent a 403, abort
600  return;
601  }
602 
603  // Exit here if the request method was OPTIONS
604  // (assume there will be a followup GET or POST)
605  if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
606  return;
607  }
608 
609  // In case an error occurs during data output,
610  // clear the output buffer and print just the error information
611  $obLevel = ob_get_level();
612  ob_start();
613 
614  $t = microtime( true );
615  $isError = false;
616  try {
617  $this->executeAction();
618  $runTime = microtime( true ) - $t;
619  $this->logRequest( $runTime );
620  MediaWikiServices::getInstance()->getStatsdDataFactory()->timing(
621  'api.' . $this->mModule->getModuleName() . '.executeTiming', 1000 * $runTime
622  );
623  } catch ( Throwable $e ) {
624  $this->handleException( $e );
625  $this->logRequest( microtime( true ) - $t, $e );
626  $isError = true;
627  }
628 
629  // Disable the client cache on the output so that BlockManager::trackBlockWithCookie is executed
630  // as part of MediaWiki::preOutputCommit().
631  if (
632  $this->mCacheMode === 'private'
633  || (
634  $this->mCacheMode === 'anon-public-user-private'
635  && SessionManager::getGlobalSession()->isPersistent()
636  )
637  ) {
638  $this->getContext()->getOutput()->enableClientCache( false );
639  $this->getContext()->getOutput()->considerCacheSettingsFinal();
640  }
641 
642  // Commit DBs and send any related cookies and headers
644 
645  // Send cache headers after any code which might generate an error, to
646  // avoid sending public cache headers for errors.
647  $this->sendCacheHeaders( $isError );
648 
649  // Executing the action might have already messed with the output
650  // buffers.
651  while ( ob_get_level() > $obLevel ) {
652  ob_end_flush();
653  }
654  }
655 
662  protected function handleException( Throwable $e ) {
663  // T65145: Rollback any open database transactions
664  if ( !$e instanceof ApiUsageException ) {
665  // ApiUsageExceptions are intentional, so don't rollback if that's the case
667  $e,
668  MWExceptionHandler::CAUGHT_BY_ENTRYPOINT
669  );
670  }
671 
672  // Allow extra cleanup and logging
673  $this->getHookRunner()->onApiMain__onException( $this, $e );
674 
675  // Handle any kind of exception by outputting properly formatted error message.
676  // If this fails, an unhandled exception should be thrown so that global error
677  // handler will process and log it.
678 
679  $errCodes = $this->substituteResultWithError( $e );
680 
681  // Error results should not be cached
682  $this->setCacheMode( 'private' );
683 
684  $response = $this->getRequest()->response();
685  $headerStr = 'MediaWiki-API-Error: ' . implode( ', ', $errCodes );
686  $response->header( $headerStr );
687 
688  // Reset and print just the error message
689  ob_clean();
690 
691  // Printer may not be initialized if the extractRequestParams() fails for the main module
692  $this->createErrorPrinter();
693 
694  // Get desired HTTP code from an ApiUsageException. Don't use codes from other
695  // exception types, as they are unlikely to be intended as an HTTP code.
696  $httpCode = $e instanceof ApiUsageException ? $e->getCode() : 0;
697 
698  $failed = false;
699  try {
700  $this->printResult( $httpCode );
701  } catch ( ApiUsageException $ex ) {
702  // The error printer itself is failing. Try suppressing its request
703  // parameters and redo.
704  $failed = true;
705  $this->addWarning( 'apiwarn-errorprinterfailed' );
706  foreach ( $ex->getStatusValue()->getErrors() as $error ) {
707  try {
708  $this->mPrinter->addWarning( $error );
709  } catch ( Throwable $ex2 ) {
710  // WTF?
711  $this->addWarning( $error );
712  }
713  }
714  }
715  if ( $failed ) {
716  $this->mPrinter = null;
717  $this->createErrorPrinter();
718  $this->mPrinter->forceDefaultParams();
719  if ( $httpCode ) {
720  $response->statusHeader( 200 ); // Reset in case the fallback doesn't want a non-200
721  }
722  $this->printResult( $httpCode );
723  }
724  }
725 
736  public static function handleApiBeforeMainException( Throwable $e ) {
737  ob_start();
738 
739  try {
740  $main = new self( RequestContext::getMain(), false );
741  $main->handleException( $e );
742  $main->logRequest( 0, $e );
743  } catch ( Throwable $e2 ) {
744  // Nope, even that didn't work. Punt.
745  throw $e;
746  }
747 
748  // Reset cache headers
749  $main->sendCacheHeaders( true );
750 
751  ob_end_flush();
752  }
753 
768  protected function handleCORS() {
769  $originParam = $this->getParameter( 'origin' ); // defaults to null
770  if ( $originParam === null ) {
771  // No origin parameter, nothing to do
772  return true;
773  }
774 
775  $request = $this->getRequest();
776  $response = $request->response();
777 
778  $allowTiming = false;
779  $varyOrigin = true;
780 
781  if ( $originParam === '*' ) {
782  // Request for anonymous CORS
783  // Technically we should check for the presence of an Origin header
784  // and not process it as CORS if it's not set, but that would
785  // require us to vary on Origin for all 'origin=*' requests which
786  // we don't want to do.
787  $matchedOrigin = true;
788  $allowOrigin = '*';
789  $allowCredentials = 'false';
790  $varyOrigin = false; // No need to vary
791  } else {
792  // Non-anonymous CORS, check we allow the domain
793 
794  // Origin: header is a space-separated list of origins, check all of them
795  $originHeader = $request->getHeader( 'Origin' );
796  if ( $originHeader === false ) {
797  $origins = [];
798  } else {
799  $originHeader = trim( $originHeader );
800  $origins = preg_split( '/\s+/', $originHeader );
801  }
802 
803  if ( !in_array( $originParam, $origins ) ) {
804  // origin parameter set but incorrect
805  // Send a 403 response
806  $response->statusHeader( 403 );
807  $response->header( 'Cache-Control: no-cache' );
808  echo "'origin' parameter does not match Origin header\n";
809 
810  return false;
811  }
812 
813  $config = $this->getConfig();
814  $origin = Origin::parseHeaderList( $origins );
815  $matchedOrigin = $origin->match(
816  $config->get( 'CrossSiteAJAXdomains' ),
817  $config->get( 'CrossSiteAJAXdomainExceptions' )
818  );
819 
820  $allowOrigin = $originHeader;
821  $allowCredentials = 'true';
822  $allowTiming = $originHeader;
823  }
824 
825  if ( $matchedOrigin ) {
826  $requestedMethod = $request->getHeader( 'Access-Control-Request-Method' );
827  $preflight = $request->getMethod() === 'OPTIONS' && $requestedMethod !== false;
828  if ( $preflight ) {
829  // This is a CORS preflight request
830  if ( $requestedMethod !== 'POST' && $requestedMethod !== 'GET' ) {
831  // If method is not a case-sensitive match, do not set any additional headers and terminate.
832  $response->header( 'MediaWiki-CORS-Rejection: Unsupported method requested in preflight' );
833  return true;
834  }
835  // We allow the actual request to send the following headers
836  $requestedHeaders = $request->getHeader( 'Access-Control-Request-Headers' );
837  $allowedHeaders = $this->getConfig()->get( 'AllowedCorsHeaders' );
838  if ( $requestedHeaders !== false ) {
839  if ( !self::matchRequestedHeaders( $requestedHeaders, $allowedHeaders ) ) {
840  $response->header( 'MediaWiki-CORS-Rejection: Unsupported header requested in preflight' );
841  return true;
842  }
843  $response->header( 'Access-Control-Allow-Headers: ' . $requestedHeaders );
844  }
845 
846  // We only allow the actual request to be GET or POST
847  $response->header( 'Access-Control-Allow-Methods: POST, GET' );
848  } elseif ( $request->getMethod() !== 'POST' && $request->getMethod() !== 'GET' ) {
849  // Unsupported non-preflight method, don't handle it as CORS
850  $response->header(
851  'MediaWiki-CORS-Rejection: Unsupported method for simple request or actual request'
852  );
853  return true;
854  }
855 
856  $response->header( "Access-Control-Allow-Origin: $allowOrigin" );
857  $response->header( "Access-Control-Allow-Credentials: $allowCredentials" );
858  // https://www.w3.org/TR/resource-timing/#timing-allow-origin
859  if ( $allowTiming !== false ) {
860  $response->header( "Timing-Allow-Origin: $allowTiming" );
861  }
862 
863  if ( !$preflight ) {
864  $response->header(
865  'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag, '
866  . 'MediaWiki-Login-Suppressed'
867  );
868  }
869  } else {
870  $response->header( 'MediaWiki-CORS-Rejection: Origin mismatch' );
871  }
872 
873  if ( $varyOrigin ) {
874  $this->getOutput()->addVaryHeader( 'Origin' );
875  }
876 
877  return true;
878  }
879 
888  protected static function matchRequestedHeaders( $requestedHeaders, $allowedHeaders ) {
889  if ( trim( $requestedHeaders ) === '' ) {
890  return true;
891  }
892  $requestedHeaders = explode( ',', $requestedHeaders );
893  $allowedHeaders = array_change_key_case( array_flip( $allowedHeaders ), CASE_LOWER );
894  foreach ( $requestedHeaders as $rHeader ) {
895  $rHeader = strtolower( trim( $rHeader ) );
896  if ( !isset( $allowedHeaders[$rHeader] ) ) {
897  LoggerFactory::getInstance( 'api-warning' )->warning(
898  'CORS preflight failed on requested header: {header}', [
899  'header' => $rHeader
900  ]
901  );
902  return false;
903  }
904  }
905  return true;
906  }
907 
913  protected function sendCacheHeaders( $isError ) {
914  $response = $this->getRequest()->response();
915  $out = $this->getOutput();
916 
917  $out->addVaryHeader( 'Treat-as-Untrusted' );
918 
919  $config = $this->getConfig();
920 
921  if ( $config->get( 'VaryOnXFP' ) ) {
922  $out->addVaryHeader( 'X-Forwarded-Proto' );
923  }
924 
925  if ( !$isError && $this->mModule &&
926  ( $this->getRequest()->getMethod() === 'GET' || $this->getRequest()->getMethod() === 'HEAD' )
927  ) {
928  $etag = $this->mModule->getConditionalRequestData( 'etag' );
929  if ( $etag !== null ) {
930  $response->header( "ETag: $etag" );
931  }
932  $lastMod = $this->mModule->getConditionalRequestData( 'last-modified' );
933  if ( $lastMod !== null ) {
934  $response->header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822, $lastMod ) );
935  }
936  }
937 
938  // The logic should be:
939  // $this->mCacheControl['max-age'] is set?
940  // Use it, the module knows better than our guess.
941  // !$this->mModule || $this->mModule->isWriteMode(), and mCacheMode is private?
942  // Use 0 because we can guess caching is probably the wrong thing to do.
943  // Use $this->getParameter( 'maxage' ), which already defaults to 0.
944  $maxage = 0;
945  if ( isset( $this->mCacheControl['max-age'] ) ) {
946  $maxage = $this->mCacheControl['max-age'];
947  } elseif ( ( $this->mModule && !$this->mModule->isWriteMode() ) ||
948  $this->mCacheMode !== 'private'
949  ) {
950  $maxage = $this->getParameter( 'maxage' );
951  }
952  $privateCache = 'private, must-revalidate, max-age=' . $maxage;
953 
954  if ( $this->mCacheMode == 'private' ) {
955  $response->header( "Cache-Control: $privateCache" );
956  return;
957  }
958 
959  if ( $this->mCacheMode == 'anon-public-user-private' ) {
960  $out->addVaryHeader( 'Cookie' );
961  $response->header( $out->getVaryHeader() );
962  if ( SessionManager::getGlobalSession()->isPersistent() ) {
963  // Logged in or otherwise has session (e.g. anonymous users who have edited)
964  // Mark request private
965  $response->header( "Cache-Control: $privateCache" );
966 
967  return;
968  } // else anonymous, send public headers below
969  }
970 
971  // Send public headers
972  $response->header( $out->getVaryHeader() );
973 
974  // If nobody called setCacheMaxAge(), use the (s)maxage parameters
975  if ( !isset( $this->mCacheControl['s-maxage'] ) ) {
976  $this->mCacheControl['s-maxage'] = $this->getParameter( 'smaxage' );
977  }
978  if ( !isset( $this->mCacheControl['max-age'] ) ) {
979  $this->mCacheControl['max-age'] = $this->getParameter( 'maxage' );
980  }
981 
982  if ( !$this->mCacheControl['s-maxage'] && !$this->mCacheControl['max-age'] ) {
983  // Public cache not requested
984  // Sending a Vary header in this case is harmless, and protects us
985  // against conditional calls of setCacheMaxAge().
986  $response->header( "Cache-Control: $privateCache" );
987 
988  return;
989  }
990 
991  $this->mCacheControl['public'] = true;
992 
993  // Send an Expires header
994  $maxAge = min( $this->mCacheControl['s-maxage'], $this->mCacheControl['max-age'] );
995  $expiryUnixTime = ( $maxAge == 0 ? 1 : time() + $maxAge );
996  $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822, $expiryUnixTime ) );
997 
998  // Construct the Cache-Control header
999  $ccHeader = '';
1000  $separator = '';
1001  foreach ( $this->mCacheControl as $name => $value ) {
1002  if ( is_bool( $value ) ) {
1003  if ( $value ) {
1004  $ccHeader .= $separator . $name;
1005  $separator = ', ';
1006  }
1007  } else {
1008  $ccHeader .= $separator . "$name=$value";
1009  $separator = ', ';
1010  }
1011  }
1012 
1013  $response->header( "Cache-Control: $ccHeader" );
1014  }
1015 
1019  private function createErrorPrinter() {
1020  if ( !isset( $this->mPrinter ) ) {
1021  $value = $this->getRequest()->getVal( 'format', self::API_DEFAULT_FORMAT );
1022  if ( !$this->mModuleMgr->isDefined( $value, 'format' ) ) {
1023  $value = self::API_DEFAULT_FORMAT;
1024  }
1025  $this->mPrinter = $this->createPrinterByName( $value );
1026  }
1027 
1028  // Printer may not be able to handle errors. This is particularly
1029  // likely if the module returns something for getCustomPrinter().
1030  if ( !$this->mPrinter->canPrintErrors() ) {
1031  $this->mPrinter = $this->createPrinterByName( self::API_DEFAULT_FORMAT );
1032  }
1033  }
1034 
1050  protected function errorMessagesFromException( Throwable $e, $type = 'error' ) {
1051  $messages = [];
1052  if ( $e instanceof ApiUsageException ) {
1053  foreach ( $e->getStatusValue()->getErrorsByType( $type ) as $error ) {
1054  $messages[] = ApiMessage::create( $error );
1055  }
1056  } elseif ( $type !== 'error' ) {
1057  // None of the rest have any messages for non-error types
1058  } else {
1059  // Something is seriously wrong
1060  $config = $this->getConfig();
1061  // TODO: Avoid embedding arbitrary class names in the error code.
1062  $class = preg_replace( '#^Wikimedia\\\Rdbms\\\#', '', get_class( $e ) );
1063  $code = 'internal_api_error_' . $class;
1064  $data = [ 'errorclass' => get_class( $e ) ];
1065  if ( $config->get( 'ShowExceptionDetails' ) ) {
1066  if ( $e instanceof ILocalizedException ) {
1067  $msg = $e->getMessageObject();
1068  } elseif ( $e instanceof MessageSpecifier ) {
1069  $msg = Message::newFromSpecifier( $e );
1070  } else {
1071  $msg = wfEscapeWikiText( $e->getMessage() );
1072  }
1073  $params = [ 'apierror-exceptioncaught', WebRequest::getRequestId(), $msg ];
1074  } else {
1075  $params = [ 'apierror-exceptioncaughttype', WebRequest::getRequestId(), get_class( $e ) ];
1076  }
1077 
1078  $messages[] = ApiMessage::create( $params, $code, $data );
1079  }
1080  return $messages;
1081  }
1082 
1088  protected function substituteResultWithError( Throwable $e ) {
1089  $result = $this->getResult();
1090  $formatter = $this->getErrorFormatter();
1091  $config = $this->getConfig();
1092  $errorCodes = [];
1093 
1094  // Remember existing warnings and errors across the reset
1095  $errors = $result->getResultData( [ 'errors' ] );
1096  $warnings = $result->getResultData( [ 'warnings' ] );
1097  $result->reset();
1098  if ( $warnings !== null ) {
1099  $result->addValue( null, 'warnings', $warnings, ApiResult::NO_SIZE_CHECK );
1100  }
1101  if ( $errors !== null ) {
1102  $result->addValue( null, 'errors', $errors, ApiResult::NO_SIZE_CHECK );
1103 
1104  // Collect the copied error codes for the return value
1105  foreach ( $errors as $error ) {
1106  if ( isset( $error['code'] ) ) {
1107  $errorCodes[$error['code']] = true;
1108  }
1109  }
1110  }
1111 
1112  // Add errors from the exception
1113  $modulePath = $e instanceof ApiUsageException ? $e->getModulePath() : null;
1114  foreach ( $this->errorMessagesFromException( $e, 'error' ) as $msg ) {
1115  if ( ApiErrorFormatter::isValidApiCode( $msg->getApiCode() ) ) {
1116  $errorCodes[$msg->getApiCode()] = true;
1117  } else {
1118  LoggerFactory::getInstance( 'api-warning' )->error( 'Invalid API error code "{code}"', [
1119  'code' => $msg->getApiCode(),
1120  'exception' => $e,
1121  ] );
1122  $errorCodes['<invalid-code>'] = true;
1123  }
1124  $formatter->addError( $modulePath, $msg );
1125  }
1126  foreach ( $this->errorMessagesFromException( $e, 'warning' ) as $msg ) {
1127  $formatter->addWarning( $modulePath, $msg );
1128  }
1129 
1130  // Add additional data. Path depends on whether we're in BC mode or not.
1131  // Data depends on the type of exception.
1132  if ( $formatter instanceof ApiErrorFormatter_BackCompat ) {
1133  $path = [ 'error' ];
1134  } else {
1135  $path = null;
1136  }
1137  if ( $e instanceof ApiUsageException ) {
1138  $link = wfExpandUrl( wfScript( 'api' ) );
1139  $result->addContentValue(
1140  $path,
1141  'docref',
1142  trim(
1143  $this->msg( 'api-usage-docref', $link )->inLanguage( $formatter->getLanguage() )->text()
1144  . ' '
1145  . $this->msg( 'api-usage-mailinglist-ref' )->inLanguage( $formatter->getLanguage() )->text()
1146  )
1147  );
1148  } elseif ( $config->get( 'ShowExceptionDetails' ) ) {
1149  $result->addContentValue(
1150  $path,
1151  'trace',
1152  $this->msg( 'api-exception-trace',
1153  get_class( $e ),
1154  $e->getFile(),
1155  $e->getLine(),
1157  )->inLanguage( $formatter->getLanguage() )->text()
1158  );
1159  }
1160 
1161  // Add the id and such
1162  $this->addRequestedFields( [ 'servedby' ] );
1163 
1164  return array_keys( $errorCodes );
1165  }
1166 
1172  protected function addRequestedFields( $force = [] ) {
1173  $result = $this->getResult();
1174 
1175  $requestid = $this->getParameter( 'requestid' );
1176  if ( $requestid !== null ) {
1177  $result->addValue( null, 'requestid', $requestid, ApiResult::NO_SIZE_CHECK );
1178  }
1179 
1180  if ( $this->getConfig()->get( 'ShowHostnames' ) && (
1181  in_array( 'servedby', $force, true ) || $this->getParameter( 'servedby' )
1182  ) ) {
1183  $result->addValue( null, 'servedby', wfHostname(), ApiResult::NO_SIZE_CHECK );
1184  }
1185 
1186  if ( $this->getParameter( 'curtimestamp' ) ) {
1187  $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601 ), ApiResult::NO_SIZE_CHECK );
1188  }
1189 
1190  if ( $this->getParameter( 'responselanginfo' ) ) {
1191  $result->addValue(
1192  null,
1193  'uselang',
1194  $this->getLanguage()->getCode(),
1196  );
1197  $result->addValue(
1198  null,
1199  'errorlang',
1200  $this->getErrorFormatter()->getLanguage()->getCode(),
1202  );
1203  }
1204  }
1205 
1210  protected function setupExecuteAction() {
1211  $this->addRequestedFields();
1212 
1213  $params = $this->extractRequestParams();
1214  $this->mAction = $params['action'];
1215 
1216  return $params;
1217  }
1218 
1225  protected function setupModule() {
1226  // Instantiate the module requested by the user
1227  $module = $this->mModuleMgr->getModule( $this->mAction, 'action' );
1228  if ( $module === null ) {
1229  // Probably can't happen
1230  // @codeCoverageIgnoreStart
1231  $this->dieWithError(
1232  [ 'apierror-unknownaction', wfEscapeWikiText( $this->mAction ) ],
1233  'unknown_action'
1234  );
1235  // @codeCoverageIgnoreEnd
1236  }
1237  $moduleParams = $module->extractRequestParams();
1238 
1239  // Check token, if necessary
1240  if ( $module->needsToken() === true ) {
1241  throw new MWException(
1242  "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
1243  'See documentation for ApiBase::needsToken for details.'
1244  );
1245  }
1246  if ( $module->needsToken() ) {
1247  if ( !$module->mustBePosted() ) {
1248  throw new MWException(
1249  "Module '{$module->getModuleName()}' must require POST to use tokens."
1250  );
1251  }
1252 
1253  if ( !isset( $moduleParams['token'] ) ) {
1254  // Probably can't happen
1255  // @codeCoverageIgnoreStart
1256  $module->dieWithError( [ 'apierror-missingparam', 'token' ] );
1257  // @codeCoverageIgnoreEnd
1258  }
1259 
1260  $module->requirePostedParameters( [ 'token' ] );
1261 
1262  if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) {
1263  $module->dieWithError( 'apierror-badtoken' );
1264  }
1265  }
1266 
1267  return $module;
1268  }
1269 
1273  private function getMaxLag() {
1274  $dbLag = MediaWikiServices::getInstance()->getDBLoadBalancer()->getMaxLag();
1275  $lagInfo = [
1276  'host' => $dbLag[0],
1277  'lag' => $dbLag[1],
1278  'type' => 'db'
1279  ];
1280 
1281  $jobQueueLagFactor = $this->getConfig()->get( 'JobQueueIncludeInMaxLagFactor' );
1282  if ( $jobQueueLagFactor ) {
1283  // Turn total number of jobs into seconds by using the configured value
1284  $totalJobs = array_sum( JobQueueGroup::singleton()->getQueueSizes() );
1285  $jobQueueLag = $totalJobs / (float)$jobQueueLagFactor;
1286  if ( $jobQueueLag > $lagInfo['lag'] ) {
1287  $lagInfo = [
1288  'host' => wfHostname(), // XXX: Is there a better value that could be used?
1289  'lag' => $jobQueueLag,
1290  'type' => 'jobqueue',
1291  'jobs' => $totalJobs,
1292  ];
1293  }
1294  }
1295 
1296  $this->getHookRunner()->onApiMaxLagInfo( $lagInfo );
1297 
1298  return $lagInfo;
1299  }
1300 
1307  protected function checkMaxLag( $module, $params ) {
1308  if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
1309  $maxLag = $params['maxlag'];
1310  $lagInfo = $this->getMaxLag();
1311  if ( $lagInfo['lag'] > $maxLag ) {
1312  $response = $this->getRequest()->response();
1313 
1314  $response->header( 'Retry-After: ' . max( (int)$maxLag, 5 ) );
1315  $response->header( 'X-Database-Lag: ' . (int)$lagInfo['lag'] );
1316 
1317  if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
1318  $this->dieWithError(
1319  [ 'apierror-maxlag', $lagInfo['lag'], $lagInfo['host'] ],
1320  'maxlag',
1321  $lagInfo
1322  );
1323  }
1324 
1325  $this->dieWithError( [ 'apierror-maxlag-generic', $lagInfo['lag'] ], 'maxlag', $lagInfo );
1326  }
1327  }
1328 
1329  return true;
1330  }
1331 
1353  protected function checkConditionalRequestHeaders( $module ) {
1354  if ( $this->mInternalMode ) {
1355  // No headers to check in internal mode
1356  return true;
1357  }
1358 
1359  if ( $this->getRequest()->getMethod() !== 'GET' && $this->getRequest()->getMethod() !== 'HEAD' ) {
1360  // Don't check POSTs
1361  return true;
1362  }
1363 
1364  $return304 = false;
1365 
1366  $ifNoneMatch = array_diff(
1367  $this->getRequest()->getHeader( 'If-None-Match', WebRequest::GETHEADER_LIST ) ?: [],
1368  [ '' ]
1369  );
1370  if ( $ifNoneMatch ) {
1371  // @phan-suppress-next-line PhanImpossibleTypeComparison
1372  if ( $ifNoneMatch === [ '*' ] ) {
1373  // API responses always "exist"
1374  $etag = '*';
1375  } else {
1376  $etag = $module->getConditionalRequestData( 'etag' );
1377  }
1378  }
1379  if ( $ifNoneMatch && $etag !== null ) {
1380  $test = substr( $etag, 0, 2 ) === 'W/' ? substr( $etag, 2 ) : $etag;
1381  $match = array_map( static function ( $s ) {
1382  return substr( $s, 0, 2 ) === 'W/' ? substr( $s, 2 ) : $s;
1383  }, $ifNoneMatch );
1384  $return304 = in_array( $test, $match, true );
1385  } else {
1386  $value = trim( $this->getRequest()->getHeader( 'If-Modified-Since' ) );
1387 
1388  // Some old browsers sends sizes after the date, like this:
1389  // Wed, 20 Aug 2003 06:51:19 GMT; length=5202
1390  // Ignore that.
1391  $i = strpos( $value, ';' );
1392  if ( $i !== false ) {
1393  $value = trim( substr( $value, 0, $i ) );
1394  }
1395 
1396  if ( $value !== '' ) {
1397  try {
1398  $ts = new MWTimestamp( $value );
1399  if (
1400  // RFC 7231 IMF-fixdate
1401  $ts->getTimestamp( TS_RFC2822 ) === $value ||
1402  // RFC 850
1403  $ts->format( 'l, d-M-y H:i:s' ) . ' GMT' === $value ||
1404  // asctime (with and without space-padded day)
1405  $ts->format( 'D M j H:i:s Y' ) === $value ||
1406  $ts->format( 'D M j H:i:s Y' ) === $value
1407  ) {
1408  $config = $this->getConfig();
1409  $lastMod = $module->getConditionalRequestData( 'last-modified' );
1410  if ( $lastMod !== null ) {
1411  // Mix in some MediaWiki modification times
1412  $modifiedTimes = [
1413  'page' => $lastMod,
1414  'user' => $this->getUser()->getTouched(),
1415  'epoch' => $config->get( 'CacheEpoch' ),
1416  ];
1417 
1418  if ( $config->get( 'UseCdn' ) ) {
1419  // T46570: the core page itself may not change, but resources might
1420  $modifiedTimes['sepoch'] = wfTimestamp(
1421  TS_MW, time() - $config->get( 'CdnMaxAge' )
1422  );
1423  }
1424  $this->getHookRunner()->onOutputPageCheckLastModified( $modifiedTimes, $this->getOutput() );
1425  $lastMod = max( $modifiedTimes );
1426  $return304 = wfTimestamp( TS_MW, $lastMod ) <= $ts->getTimestamp( TS_MW );
1427  }
1428  }
1429  } catch ( TimestampException $e ) {
1430  // Invalid timestamp, ignore it
1431  }
1432  }
1433  }
1434 
1435  if ( $return304 ) {
1436  $this->getRequest()->response()->statusHeader( 304 );
1437 
1438  // Avoid outputting the compressed representation of a zero-length body
1439  Wikimedia\suppressWarnings();
1440  ini_set( 'zlib.output_compression', 0 );
1441  Wikimedia\restoreWarnings();
1442  wfResetOutputBuffers( false );
1443 
1444  return false;
1445  }
1446 
1447  return true;
1448  }
1449 
1454  protected function checkExecutePermissions( $module ) {
1455  $user = $this->getUser();
1456  if ( $module->isReadMode() && !$this->getPermissionManager()->isEveryoneAllowed( 'read' ) &&
1457  !$this->getAuthority()->isAllowed( 'read' )
1458  ) {
1459  $this->dieWithError( 'apierror-readapidenied' );
1460  }
1461 
1462  if ( $module->isWriteMode() ) {
1463  if ( !$this->mEnableWrite ) {
1464  $this->dieWithError( 'apierror-noapiwrite' );
1465  } elseif ( !$this->getAuthority()->isAllowed( 'writeapi' ) ) {
1466  $this->dieWithError( 'apierror-writeapidenied' );
1467  } elseif ( $this->getRequest()->getHeader( 'Promise-Non-Write-API-Action' ) ) {
1468  $this->dieWithError( 'apierror-promised-nonwrite-api' );
1469  }
1470 
1471  $this->checkReadOnly( $module );
1472  }
1473 
1474  // Allow extensions to stop execution for arbitrary reasons.
1475  // TODO: change hook to accept Authority
1476  $message = 'hookaborted';
1477  if ( !$this->getHookRunner()->onApiCheckCanExecute( $module, $user, $message ) ) {
1478  $this->dieWithError( $message );
1479  }
1480  }
1481 
1486  protected function checkReadOnly( $module ) {
1487  if ( MediaWikiServices::getInstance()->getReadOnlyMode()->isReadOnly() ) {
1488  $this->dieReadOnly();
1489  }
1490 
1491  if ( $module->isWriteMode()
1492  && $this->getUser()->isBot()
1493  && MediaWikiServices::getInstance()->getDBLoadBalancer()->getServerCount() > 1
1494  ) {
1495  $this->checkBotReadOnly();
1496  }
1497  }
1498 
1502  private function checkBotReadOnly() {
1503  // Figure out how many servers have passed the lag threshold
1504  $numLagged = 0;
1505  $lagLimit = $this->getConfig()->get( 'APIMaxLagThreshold' );
1506  $laggedServers = [];
1507  $loadBalancer = MediaWikiServices::getInstance()->getDBLoadBalancer();
1508  foreach ( $loadBalancer->getLagTimes() as $serverIndex => $lag ) {
1509  if ( $lag > $lagLimit ) {
1510  ++$numLagged;
1511  $laggedServers[] = $loadBalancer->getServerName( $serverIndex ) . " ({$lag}s)";
1512  }
1513  }
1514 
1515  // If a majority of replica DBs are too lagged then disallow writes
1516  $replicaCount = $loadBalancer->getServerCount() - 1;
1517  if ( $numLagged >= ceil( $replicaCount / 2 ) ) {
1518  $laggedServers = implode( ', ', $laggedServers );
1519  wfDebugLog(
1520  'api-readonly', // Deprecate this channel in favor of api-warning?
1521  "Api request failed as read only because the following DBs are lagged: $laggedServers"
1522  );
1523  LoggerFactory::getInstance( 'api-warning' )->warning(
1524  "Api request failed as read only because the following DBs are lagged: {laggeddbs}", [
1525  'laggeddbs' => $laggedServers,
1526  ]
1527  );
1528 
1529  $this->dieWithError(
1530  'readonly_lag',
1531  'readonly',
1532  [ 'readonlyreason' => "Waiting for $numLagged lagged database(s)" ]
1533  );
1534  }
1535  }
1536 
1541  protected function checkAsserts( $params ) {
1542  if ( isset( $params['assert'] ) ) {
1543  $user = $this->getUser();
1544  switch ( $params['assert'] ) {
1545  case 'anon':
1546  if ( !$user->isAnon() ) {
1547  $this->dieWithError( 'apierror-assertanonfailed' );
1548  }
1549  break;
1550  case 'user':
1551  if ( $user->isAnon() ) {
1552  $this->dieWithError( 'apierror-assertuserfailed' );
1553  }
1554  break;
1555  case 'bot':
1556  if ( !$this->getAuthority()->isAllowed( 'bot' ) ) {
1557  $this->dieWithError( 'apierror-assertbotfailed' );
1558  }
1559  break;
1560  }
1561  }
1562  if ( isset( $params['assertuser'] ) ) {
1563  $assertUser = User::newFromName( $params['assertuser'], false );
1564  if ( !$assertUser || !$this->getUser()->equals( $assertUser ) ) {
1565  $this->dieWithError(
1566  [ 'apierror-assertnameduserfailed', wfEscapeWikiText( $params['assertuser'] ) ]
1567  );
1568  }
1569  }
1570  }
1571 
1577  protected function setupExternalResponse( $module, $params ) {
1578  $validMethods = [ 'GET', 'HEAD', 'POST', 'OPTIONS' ];
1579  $request = $this->getRequest();
1580 
1581  if ( !in_array( $request->getMethod(), $validMethods ) ) {
1582  $this->dieWithError( 'apierror-invalidmethod', null, null, 405 );
1583  }
1584 
1585  if ( !$request->wasPosted() && $module->mustBePosted() ) {
1586  // Module requires POST. GET request might still be allowed
1587  // if $wgDebugApi is true, otherwise fail.
1588  $this->dieWithErrorOrDebug( [ 'apierror-mustbeposted', $this->mAction ] );
1589  }
1590 
1591  if ( $request->wasPosted() && !$request->getHeader( 'Content-Type' ) ) {
1592  $this->addDeprecation(
1593  'apiwarn-deprecation-post-without-content-type', 'post-without-content-type'
1594  );
1595  }
1596 
1597  // See if custom printer is used
1598  $this->mPrinter = $module->getCustomPrinter();
1599  if ( $this->mPrinter === null ) {
1600  // Create an appropriate printer
1601  $this->mPrinter = $this->createPrinterByName( $params['format'] );
1602  }
1603 
1604  if ( $request->getProtocol() === 'http' &&
1605  (
1606  $this->getConfig()->get( 'ForceHTTPS' ) ||
1607  $request->getSession()->shouldForceHTTPS() ||
1608  ( $this->getUser()->isRegistered() &&
1609  $this->getUser()->requiresHTTPS() )
1610  )
1611  ) {
1612  $this->addDeprecation( 'apiwarn-deprecation-httpsexpected', 'https-expected' );
1613  }
1614  }
1615 
1619  protected function executeAction() {
1620  $params = $this->setupExecuteAction();
1621 
1622  // Check asserts early so e.g. errors in parsing a module's parameters due to being
1623  // logged out don't override the client's intended "am I logged in?" check.
1624  $this->checkAsserts( $params );
1625 
1626  $module = $this->setupModule();
1627  $this->mModule = $module;
1628 
1629  if ( !$this->mInternalMode ) {
1630  $this->setRequestExpectations( $module );
1631  }
1632 
1633  $this->checkExecutePermissions( $module );
1634 
1635  if ( !$this->checkMaxLag( $module, $params ) ) {
1636  return;
1637  }
1638 
1639  if ( !$this->checkConditionalRequestHeaders( $module ) ) {
1640  return;
1641  }
1642 
1643  if ( !$this->mInternalMode ) {
1644  $this->setupExternalResponse( $module, $params );
1645  }
1646 
1647  $module->execute();
1648  $this->getHookRunner()->onAPIAfterExecute( $module );
1649 
1650  $this->reportUnusedParams();
1651 
1652  if ( !$this->mInternalMode ) {
1654 
1655  $this->printResult();
1656  }
1657  }
1658 
1663  protected function setRequestExpectations( ApiBase $module ) {
1664  $limits = $this->getConfig()->get( 'TrxProfilerLimits' );
1665  $trxProfiler = Profiler::instance()->getTransactionProfiler();
1666  $trxProfiler->setLogger( LoggerFactory::getInstance( 'DBPerformance' ) );
1667  if ( $this->getRequest()->hasSafeMethod() ) {
1668  $trxProfiler->setExpectations( $limits['GET'], __METHOD__ );
1669  } elseif ( $this->getRequest()->wasPosted() && !$module->isWriteMode() ) {
1670  $trxProfiler->setExpectations( $limits['POST-nonwrite'], __METHOD__ );
1671  $this->getRequest()->markAsSafeRequest();
1672  } else {
1673  $trxProfiler->setExpectations( $limits['POST'], __METHOD__ );
1674  }
1675  }
1676 
1682  protected function logRequest( $time, Throwable $e = null ) {
1683  $request = $this->getRequest();
1684 
1685  $logCtx = [
1686  // https://gerrit.wikimedia.org/g/mediawiki/event-schemas/+/master/jsonschema/mediawiki/api/request
1687  '$schema' => '/mediawiki/api/request/0.0.1',
1688  'meta' => [
1689  'request_id' => WebRequest::getRequestId(),
1690  'id' => MediaWikiServices::getInstance()
1691  ->getGlobalIdGenerator()->newUUIDv4(),
1692  'dt' => wfTimestamp( TS_ISO_8601 ),
1693  'domain' => $this->getConfig()->get( 'ServerName' ),
1694  // If using the EventBus extension (as intended) with this log channel,
1695  // this stream name will map to a Kafka topic.
1696  'stream' => 'mediawiki.api-request'
1697  ],
1698  'http' => [
1699  'method' => $request->getMethod(),
1700  'client_ip' => $request->getIP()
1701  ],
1702  'database' => WikiMap::getCurrentWikiDbDomain()->getId(),
1703  'backend_time_ms' => (int)round( $time * 1000 ),
1704  ];
1705 
1706  // If set, these headers will be logged in http.request_headers.
1707  $httpRequestHeadersToLog = [ 'accept-language', 'referer', 'user-agent' ];
1708  foreach ( $httpRequestHeadersToLog as $header ) {
1709  if ( $request->getHeader( $header ) ) {
1710  // Set the header in http.request_headers
1711  $logCtx['http']['request_headers'][$header] = $request->getHeader( $header );
1712  }
1713  }
1714 
1715  if ( $e ) {
1716  $logCtx['api_error_codes'] = [];
1717  foreach ( $this->errorMessagesFromException( $e ) as $msg ) {
1718  $logCtx['api_error_codes'][] = $msg->getApiCode();
1719  }
1720  }
1721 
1722  // Construct space separated message for 'api' log channel
1723  $msg = "API {$request->getMethod()} " .
1724  wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
1725  " {$logCtx['http']['client_ip']} " .
1726  "T={$logCtx['backend_time_ms']}ms";
1727 
1728  $sensitive = array_flip( $this->getSensitiveParams() );
1729  foreach ( $this->getParamsUsed() as $name ) {
1730  $value = $request->getVal( $name );
1731  if ( $value === null ) {
1732  continue;
1733  }
1734 
1735  if ( isset( $sensitive[$name] ) ) {
1736  $value = '[redacted]';
1737  $encValue = '[redacted]';
1738  } elseif ( strlen( $value ) > 256 ) {
1739  $value = substr( $value, 0, 256 );
1740  $encValue = $this->encodeRequestLogValue( $value ) . '[...]';
1741  } else {
1742  $encValue = $this->encodeRequestLogValue( $value );
1743  }
1744 
1745  $logCtx['params'][$name] = $value;
1746  $msg .= " {$name}={$encValue}";
1747  }
1748 
1749  // Log an unstructured message to the api channel.
1750  wfDebugLog( 'api', $msg, 'private' );
1751 
1752  // The api-request channel a structured data log channel.
1753  wfDebugLog( 'api-request', '', 'private', $logCtx );
1754  }
1755 
1761  protected function encodeRequestLogValue( $s ) {
1762  static $table = [];
1763  if ( !$table ) {
1764  $chars = ';@$!*(),/:';
1765  $numChars = strlen( $chars );
1766  for ( $i = 0; $i < $numChars; $i++ ) {
1767  $table[rawurlencode( $chars[$i] )] = $chars[$i];
1768  }
1769  }
1770 
1771  return strtr( rawurlencode( $s ), $table );
1772  }
1773 
1778  protected function getParamsUsed() {
1779  return array_keys( $this->mParamsUsed );
1780  }
1781 
1786  public function markParamsUsed( $params ) {
1787  $this->mParamsUsed += array_fill_keys( (array)$params, true );
1788  }
1789 
1795  protected function getSensitiveParams() {
1796  return array_keys( $this->mParamsSensitive );
1797  }
1798 
1808  public function markParamsSensitive( $params ) {
1809  $this->mParamsSensitive += array_fill_keys( (array)$params, true );
1810  }
1811 
1818  public function getVal( $name, $default = null ) {
1819  $this->mParamsUsed[$name] = true;
1820 
1821  $ret = $this->getRequest()->getVal( $name );
1822  if ( $ret === null ) {
1823  if ( $this->getRequest()->getArray( $name ) !== null ) {
1824  // See T12262 for why we don't just implode( '|', ... ) the
1825  // array.
1826  $this->addWarning( [ 'apiwarn-unsupportedarray', $name ] );
1827  }
1828  $ret = $default;
1829  }
1830  return $ret;
1831  }
1832 
1839  public function getCheck( $name ) {
1840  $this->mParamsUsed[$name] = true;
1841  return $this->getRequest()->getCheck( $name );
1842  }
1843 
1851  public function getUpload( $name ) {
1852  $this->mParamsUsed[$name] = true;
1853 
1854  return $this->getRequest()->getUpload( $name );
1855  }
1856 
1861  protected function reportUnusedParams() {
1862  $paramsUsed = $this->getParamsUsed();
1863  $allParams = $this->getRequest()->getValueNames();
1864 
1865  if ( !$this->mInternalMode ) {
1866  // Printer has not yet executed; don't warn that its parameters are unused
1867  $printerParams = $this->mPrinter->encodeParamName(
1868  array_keys( $this->mPrinter->getFinalParams() ?: [] )
1869  );
1870  $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1871  } else {
1872  $unusedParams = array_diff( $allParams, $paramsUsed );
1873  }
1874 
1875  if ( count( $unusedParams ) ) {
1876  $this->addWarning( [
1877  'apierror-unrecognizedparams',
1878  Message::listParam( array_map( 'wfEscapeWikiText', $unusedParams ), 'comma' ),
1879  count( $unusedParams )
1880  ] );
1881  }
1882  }
1883 
1889  protected function printResult( $httpCode = 0 ) {
1890  if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
1891  $this->addWarning( 'apiwarn-wgdebugapi' );
1892  }
1893 
1894  $printer = $this->mPrinter;
1895  $printer->initPrinter( false );
1896  if ( $httpCode ) {
1897  $printer->setHttpStatus( $httpCode );
1898  }
1899  $printer->execute();
1900  $printer->closePrinter();
1901  }
1902 
1906  public function isReadMode() {
1907  return false;
1908  }
1909 
1915  public function getAllowedParams() {
1916  return [
1917  'action' => [
1918  ApiBase::PARAM_DFLT => 'help',
1919  ApiBase::PARAM_TYPE => 'submodule',
1920  ],
1921  'format' => [
1923  ApiBase::PARAM_TYPE => 'submodule',
1924  ],
1925  'maxlag' => [
1926  ApiBase::PARAM_TYPE => 'integer'
1927  ],
1928  'smaxage' => [
1929  ApiBase::PARAM_TYPE => 'integer',
1930  ApiBase::PARAM_DFLT => 0
1931  ],
1932  'maxage' => [
1933  ApiBase::PARAM_TYPE => 'integer',
1934  ApiBase::PARAM_DFLT => 0
1935  ],
1936  'assert' => [
1937  ApiBase::PARAM_TYPE => [ 'anon', 'user', 'bot' ]
1938  ],
1939  'assertuser' => [
1940  ApiBase::PARAM_TYPE => 'user',
1941  UserDef::PARAM_ALLOWED_USER_TYPES => [ 'name' ],
1942  ],
1943  'requestid' => null,
1944  'servedby' => false,
1945  'curtimestamp' => false,
1946  'responselanginfo' => false,
1947  'origin' => null,
1948  'uselang' => [
1950  ],
1951  'errorformat' => [
1952  ApiBase::PARAM_TYPE => [ 'plaintext', 'wikitext', 'html', 'raw', 'none', 'bc' ],
1953  ApiBase::PARAM_DFLT => 'bc',
1954  ],
1955  'errorlang' => [
1956  ApiBase::PARAM_DFLT => 'uselang',
1957  ],
1958  'errorsuselocal' => [
1959  ApiBase::PARAM_DFLT => false,
1960  ],
1961  ];
1962  }
1963 
1965  protected function getExamplesMessages() {
1966  return [
1967  'action=help'
1968  => 'apihelp-help-example-main',
1969  'action=help&recursivesubmodules=1'
1970  => 'apihelp-help-example-recursive',
1971  ];
1972  }
1973 
1978  public function modifyHelp( array &$help, array $options, array &$tocData ) {
1979  // Wish PHP had an "array_insert_before". Instead, we have to manually
1980  // reindex the array to get 'permissions' in the right place.
1981  $oldHelp = $help;
1982  $help = [];
1983  foreach ( $oldHelp as $k => $v ) {
1984  if ( $k === 'submodules' ) {
1985  $help['permissions'] = '';
1986  }
1987  $help[$k] = $v;
1988  }
1989  $help['datatypes'] = '';
1990  $help['templatedparams'] = '';
1991  $help['credits'] = '';
1992 
1993  // Fill 'permissions'
1994  $help['permissions'] .= Html::openElement( 'div',
1995  [ 'class' => 'apihelp-block apihelp-permissions' ] );
1996  $m = $this->msg( 'api-help-permissions' );
1997  if ( !$m->isDisabled() ) {
1998  $help['permissions'] .= Html::rawElement( 'div', [ 'class' => 'apihelp-block-head' ],
1999  $m->numParams( count( self::RIGHTS_MAP ) )->parse()
2000  );
2001  }
2002  $help['permissions'] .= Html::openElement( 'dl' );
2003  foreach ( self::RIGHTS_MAP as $right => $rightMsg ) {
2004  $help['permissions'] .= Html::element( 'dt', null, $right );
2005 
2006  $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse();
2007  $help['permissions'] .= Html::rawElement( 'dd', null, $rightMsg );
2008 
2009  $groups = array_map( static function ( $group ) {
2010  return $group == '*' ? 'all' : $group;
2011  }, $this->getGroupPermissionsLookup()->getGroupsWithPermission( $right ) );
2012 
2013  $help['permissions'] .= Html::rawElement( 'dd', null,
2014  $this->msg( 'api-help-permissions-granted-to' )
2015  ->numParams( count( $groups ) )
2016  ->params( Message::listParam( $groups ) )
2017  ->parse()
2018  );
2019  }
2020  $help['permissions'] .= Html::closeElement( 'dl' );
2021  $help['permissions'] .= Html::closeElement( 'div' );
2022 
2023  // Fill 'datatypes', 'templatedparams', and 'credits', if applicable
2024  if ( empty( $options['nolead'] ) ) {
2025  $level = $options['headerlevel'];
2026  $tocnumber = &$options['tocnumber'];
2027 
2028  $header = $this->msg( 'api-help-datatypes-header' )->parse();
2029 
2030  $id = Sanitizer::escapeIdForAttribute( 'main/datatypes', Sanitizer::ID_PRIMARY );
2031  $idFallback = Sanitizer::escapeIdForAttribute( 'main/datatypes', Sanitizer::ID_FALLBACK );
2032  $headline = Linker::makeHeadline( min( 6, $level ),
2033  ' class="apihelp-header">',
2034  $id,
2035  $header,
2036  '',
2037  $idFallback
2038  );
2039  // Ensure we have a sane anchor
2040  if ( $id !== 'main/datatypes' && $idFallback !== 'main/datatypes' ) {
2041  $headline = '<div id="main/datatypes"></div>' . $headline;
2042  }
2043  $help['datatypes'] .= $headline;
2044  $help['datatypes'] .= $this->msg( 'api-help-datatypes-top' )->parseAsBlock();
2045  $help['datatypes'] .= '<dl>';
2046  foreach ( $this->getParamValidator()->knownTypes() as $type ) {
2047  $m = $this->msg( "api-help-datatype-$type" );
2048  if ( !$m->isDisabled() ) {
2049  $id = "main/datatype/$type";
2050  $help['datatypes'] .= '<dt id="' . htmlspecialchars( $id ) . '">';
2052  if ( $encId !== $id ) {
2053  $help['datatypes'] .= '<span id="' . htmlspecialchars( $encId ) . '"></span>';
2054  }
2056  if ( $encId2 !== $id && $encId2 !== $encId ) {
2057  $help['datatypes'] .= '<span id="' . htmlspecialchars( $encId2 ) . '"></span>';
2058  }
2059  $help['datatypes'] .= htmlspecialchars( $type ) . '</dt><dd>' . $m->parseAsBlock() . "</dd>";
2060  }
2061  }
2062  $help['datatypes'] .= '</dl>';
2063  if ( !isset( $tocData['main/datatypes'] ) ) {
2064  $tocnumber[$level]++;
2065  $tocData['main/datatypes'] = [
2066  'toclevel' => count( $tocnumber ),
2067  'level' => $level,
2068  'anchor' => 'main/datatypes',
2069  'line' => $header,
2070  'number' => implode( '.', $tocnumber ),
2071  'index' => false,
2072  ];
2073  }
2074 
2075  $header = $this->msg( 'api-help-templatedparams-header' )->parse();
2076 
2077  $id = Sanitizer::escapeIdForAttribute( 'main/templatedparams', Sanitizer::ID_PRIMARY );
2078  $idFallback = Sanitizer::escapeIdForAttribute( 'main/templatedparams', Sanitizer::ID_FALLBACK );
2079  $headline = Linker::makeHeadline( min( 6, $level ),
2080  ' class="apihelp-header">',
2081  $id,
2082  $header,
2083  '',
2084  $idFallback
2085  );
2086  // Ensure we have a sane anchor
2087  if ( $id !== 'main/templatedparams' && $idFallback !== 'main/templatedparams' ) {
2088  $headline = '<div id="main/templatedparams"></div>' . $headline;
2089  }
2090  $help['templatedparams'] .= $headline;
2091  $help['templatedparams'] .= $this->msg( 'api-help-templatedparams' )->parseAsBlock();
2092  if ( !isset( $tocData['main/templatedparams'] ) ) {
2093  $tocnumber[$level]++;
2094  $tocData['main/templatedparams'] = [
2095  'toclevel' => count( $tocnumber ),
2096  'level' => $level,
2097  'anchor' => 'main/templatedparams',
2098  'line' => $header,
2099  'number' => implode( '.', $tocnumber ),
2100  'index' => false,
2101  ];
2102  }
2103 
2104  $header = $this->msg( 'api-credits-header' )->parse();
2105  $id = Sanitizer::escapeIdForAttribute( 'main/credits', Sanitizer::ID_PRIMARY );
2106  $idFallback = Sanitizer::escapeIdForAttribute( 'main/credits', Sanitizer::ID_FALLBACK );
2107  $headline = Linker::makeHeadline( min( 6, $level ),
2108  ' class="apihelp-header">',
2109  $id,
2110  $header,
2111  '',
2112  $idFallback
2113  );
2114  // Ensure we have a sane anchor
2115  if ( $id !== 'main/credits' && $idFallback !== 'main/credits' ) {
2116  $headline = '<div id="main/credits"></div>' . $headline;
2117  }
2118  $help['credits'] .= $headline;
2119  $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
2120  if ( !isset( $tocData['main/credits'] ) ) {
2121  $tocnumber[$level]++;
2122  $tocData['main/credits'] = [
2123  'toclevel' => count( $tocnumber ),
2124  'level' => $level,
2125  'anchor' => 'main/credits',
2126  'line' => $header,
2127  'number' => implode( '.', $tocnumber ),
2128  'index' => false,
2129  ];
2130  }
2131  }
2132  }
2133 
2134  private $mCanApiHighLimits = null;
2135 
2140  public function canApiHighLimits() {
2141  if ( !isset( $this->mCanApiHighLimits ) ) {
2142  $this->mCanApiHighLimits = $this->getAuthority()->isAllowed( 'apihighlimits' );
2143  }
2144 
2145  return $this->mCanApiHighLimits;
2146  }
2147 
2152  public function getModuleManager() {
2153  return $this->mModuleMgr;
2154  }
2155 
2164  public function getUserAgent() {
2165  return trim(
2166  $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
2167  $this->getRequest()->getHeader( 'User-agent' )
2168  );
2169  }
2170 }
2171 
ApiUsageException\getStatusValue
getStatusValue()
Fetch the error status.
Definition: ApiUsageException.php:107
ApiMain\$mModuleMgr
ApiModuleManager $mModuleMgr
Definition: ApiMain.php:217
ApiMain\executeActionWithErrorHandling
executeActionWithErrorHandling()
Execute an action, and in case of an error, erase whatever partial results have been accumulated,...
Definition: ApiMain.php:596
MWTimestamp
Library for creating and parsing MW-style timestamps.
Definition: MWTimestamp.php:37
ApiMain
This is the main API class, used for both external and internal processing.
Definition: ApiMain.php:48
ContextSource\$context
IContextSource $context
Definition: ContextSource.php:38
ContextSource\getConfig
getConfig()
Definition: ContextSource.php:71
Sanitizer\ID_FALLBACK
const ID_FALLBACK
Tells escapeUrlForHtml() to encode the ID using the fallback encoding, or return false if no fallback...
Definition: Sanitizer.php:78
Message\newFromSpecifier
static newFromSpecifier( $value)
Transform a MessageSpecifier or a primitive value used interchangeably with specifiers (a message key...
Definition: Message.php:424
FauxRequest
WebRequest clone which takes values from a provided array.
Definition: FauxRequest.php:35
ApiUsageException
Exception used to abort API execution with an error.
Definition: ApiUsageException.php:29
ContextSource\getContext
getContext()
Get the base IContextSource object.
Definition: ContextSource.php:46
wfResetOutputBuffers
wfResetOutputBuffers( $resetGzipEncoding=true)
Clear away any user-level output buffers, discarding contents.
Definition: GlobalFunctions.php:1653
ApiMain\substituteResultWithError
substituteResultWithError(Throwable $e)
Replace the result data with the information about a throwable.
Definition: ApiMain.php:1088
ApiMain\checkReadOnly
checkReadOnly( $module)
Check if the DB is read-only for this user.
Definition: ApiMain.php:1486
ApiBase\addWarning
addWarning( $msg, $code=null, $data=null)
Add a warning for this module.
Definition: ApiBase.php:1303
RequestContext\sanitizeLangCode
static sanitizeLangCode( $code)
Accepts a language code and ensures it's sane.
Definition: RequestContext.php:319
WikiMap\getCurrentWikiDbDomain
static getCurrentWikiDbDomain()
Definition: WikiMap.php:293
ApiErrorFormatter_BackCompat
Format errors and warnings in the old style, for backwards compatibility.
Definition: ApiErrorFormatter_BackCompat.php:30
ApiErrorFormatter\isValidApiCode
static isValidApiCode( $code)
Test whether a code is a valid API error code.
Definition: ApiErrorFormatter.php:74
ApiMain\getParamsUsed
getParamsUsed()
Get the request parameters used in the course of the preceding execute() request.
Definition: ApiMain.php:1778
Profiler\instance
static instance()
Singleton.
Definition: Profiler.php:69
ApiMain\MODULES
const MODULES
List of available modules: action name => module class.
Definition: ApiMain.php:62
ApiMain\createErrorPrinter
createErrorPrinter()
Create the printer for error output.
Definition: ApiMain.php:1019
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:173
ApiMain\getErrorFormatter
getErrorFormatter()
Get the ApiErrorFormatter object associated with current request.
Definition: ApiMain.php:431
ApiMain\getVal
getVal( $name, $default=null)
Get a request value, and register the fact that it was used, for logging.
Definition: ApiMain.php:1818
ApiMain\errorMessagesFromException
errorMessagesFromException(Throwable $e, $type='error')
Create an error message for the given throwable.
Definition: ApiMain.php:1050
ApiUsageException\getModulePath
getModulePath()
Fetch the responsible module name.
Definition: ApiUsageException.php:99
ApiContinuationManager
This manages continuation state.
Definition: ApiContinuationManager.php:26
Sanitizer\escapeIdForAttribute
static escapeIdForAttribute( $id, $mode=self::ID_PRIMARY)
Given a section name or other user-generated or otherwise unsafe string, escapes it to be a valid HTM...
Definition: Sanitizer.php:811
ApiBase\dieWithError
dieWithError( $msg, $code=null, $data=null, $httpCode=null)
Abort execution with an error.
Definition: ApiBase.php:1384
ApiMain\$mEnableWrite
bool $mEnableWrite
Definition: ApiMain.php:235
ApiMain\sendCacheHeaders
sendCacheHeaders( $isError)
Send caching headers.
Definition: ApiMain.php:913
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1832
ApiBase\PARAM_TYPE
const PARAM_TYPE
Definition: ApiBase.php:72
ApiFormatBase
This is the abstract base class for API formatters.
Definition: ApiFormatBase.php:30
ApiMain\handleException
handleException(Throwable $e)
Handle a throwable as an API response.
Definition: ApiMain.php:662
MessageSpecifier
Definition: MessageSpecifier.php:24
wfUrlencode
wfUrlencode( $s)
We want some things to be included as literal characters in our title URLs for prettiness,...
Definition: GlobalFunctions.php:313
ApiMain\isReadMode
isReadMode()
Definition: ApiMain.php:1906
ApiMain\handleCORS
handleCORS()
Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
Definition: ApiMain.php:768
MediaWiki\Api\Validator\ApiParamValidator
This wraps a bunch of the API-specific parameter validation logic.
Definition: ApiParamValidator.php:38
ApiMain\checkConditionalRequestHeaders
checkConditionalRequestHeaders( $module)
Check selected RFC 7232 precondition headers.
Definition: ApiMain.php:1353
ApiBase\dieWithErrorOrDebug
dieWithErrorOrDebug( $msg, $code=null, $data=null, $httpCode=null)
Will only set a warning instead of failing if the global $wgDebugAPI is set to true.
Definition: ApiBase.php:1549
ApiMain\lacksSameOriginSecurity
lacksSameOriginSecurity()
Get the security flag for the current request.
Definition: ApiMain.php:395
wfHostname
wfHostname()
Get host name of the current machine, for use in error reporting.
Definition: GlobalFunctions.php:1294
User\newFromName
static newFromName( $name, $validate='valid')
Definition: User.php:586
ApiMain\getParamValidator
getParamValidator()
Get the parameter validator.
Definition: ApiMain.php:459
ApiResult\NO_SIZE_CHECK
const NO_SIZE_CHECK
For addValue() and similar functions, do not check size while adding a value Don't use this unless yo...
Definition: ApiResult.php:58
ContextSource\getRequest
getRequest()
Definition: ContextSource.php:80
ApiMain\$mCacheControl
array $mCacheControl
Definition: ApiMain.php:247
ApiMain\encodeRequestLogValue
encodeRequestLogValue( $s)
Encode a value in a format suitable for a space-separated log line.
Definition: ApiMain.php:1761
ApiMain\$mResult
ApiResult $mResult
Definition: ApiMain.php:220
ContextSource\getUser
getUser()
Definition: ContextSource.php:135
ApiMain\getMaxLag
getMaxLag()
Definition: ApiMain.php:1273
ApiMain\$mContinuationManager
ApiContinuationManager null $mContinuationManager
Definition: ApiMain.php:229
$wgLang
$wgLang
Definition: Setup.php:782
wfDebugLog
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
Definition: GlobalFunctions.php:996
Message\listParam
static listParam(array $list, $type='text')
Definition: Message.php:1115
ApiMain\FORMATS
const FORMATS
List of available formats: format name => format class.
Definition: ApiMain.php:185
ApiBase
This abstract class implements many basic API functions, and is the base of all API classes.
Definition: ApiBase.php:55
ApiMain\$mErrorFormatter
ApiErrorFormatter $mErrorFormatter
Definition: ApiMain.php:223
Wikimedia\ParamValidator\ParamValidator::TypeDef\UserDef
Type definition for user types.
Definition: UserDef.php:25
ContextSource\getLanguage
getLanguage()
Definition: ContextSource.php:151
ApiMain\matchRequestedHeaders
static matchRequestedHeaders( $requestedHeaders, $allowedHeaders)
Attempt to validate the value of Access-Control-Request-Headers against a list of headers that we all...
Definition: ApiMain.php:888
Html\closeElement
static closeElement( $element)
Returns "</$element>".
Definition: Html.php:318
ApiMain\getModule
getModule()
Get the API module object.
Definition: ApiMain.php:468
MWExceptionHandler\getRedactedTraceAsString
static getRedactedTraceAsString(Throwable $e)
Generate a string representation of a throwable's stack trace.
Definition: MWExceptionHandler.php:359
DerivativeContext
An IContextSource implementation which will inherit context from another source but allow individual ...
Definition: DerivativeContext.php:32
ApiMain\markParamsUsed
markParamsUsed( $params)
Mark parameters as used.
Definition: ApiMain.php:1786
MWException
MediaWiki exception.
Definition: MWException.php:29
MediaWiki\Logger\LoggerFactory
PSR-3 logger instance factory.
Definition: LoggerFactory.php:45
ApiMain\setupExecuteAction
setupExecuteAction()
Set up for the execution.
Definition: ApiMain.php:1210
wfScript
wfScript( $script='index')
Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScri...
Definition: GlobalFunctions.php:2534
ApiResult
This class represents the result of the API operations.
Definition: ApiResult.php:35
ApiMain\$lacksSameOriginSecurity
bool null $lacksSameOriginSecurity
Cached return value from self::lacksSameOriginSecurity()
Definition: ApiMain.php:256
ApiMain\$mParamsSensitive
array $mParamsSensitive
Definition: ApiMain.php:253
ContextSource\getOutput
getOutput()
Definition: ContextSource.php:125
Linker\makeHeadline
static makeHeadline( $level, $attribs, $anchor, $html, $link, $fallbackAnchor=false)
Create a headline for content.
Definition: Linker.php:1790
ApiMain\getResult
getResult()
Get the ApiResult object associated with current request.
Definition: ApiMain.php:387
ApiMain\getSensitiveParams
getSensitiveParams()
Get the request parameters that should be considered sensitive.
Definition: ApiMain.php:1795
ApiBase\getGroupPermissionsLookup
getGroupPermissionsLookup()
Obtain a GroupPermissionsLookup instance that subclasses may use to access group permissions.
Definition: ApiBase.php:641
ApiMain\checkMaxLag
checkMaxLag( $module, $params)
Check the max lag if necessary.
Definition: ApiMain.php:1307
ApiMain\API_DEFAULT_USELANG
const API_DEFAULT_USELANG
When no uselang parameter is given, this language will be used.
Definition: ApiMain.php:57
ApiBase\extractRequestParams
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition: ApiBase.php:720
ApiMain\getExamplesMessages
getExamplesMessages()
Returns usage examples for this module.Return value has query strings as keys, with values being eith...
Definition: ApiMain.php:1965
ApiMain\setCacheControl
setCacheControl( $directives)
Set directives (key/value pairs) for the Cache-Control header.
Definition: ApiMain.php:559
ApiMain\getAllowedParams
getAllowedParams()
See ApiBase for description.
Definition: ApiMain.php:1915
ApiMain\setupExternalResponse
setupExternalResponse( $module, $params)
Check POST for external response and setup result printer.
Definition: ApiMain.php:1577
ApiMain\createPrinterByName
createPrinterByName( $format)
Create an instance of an output formatter by its name.
Definition: ApiMain.php:570
ApiMain\getModuleManager
getModuleManager()
Overrides to return this instance's module manager.
Definition: ApiMain.php:2152
ApiMain\$mCanApiHighLimits
$mCanApiHighLimits
Definition: ApiMain.php:2134
ApiMessage\create
static create( $msg, $code=null, array $data=null)
Create an IApiMessage for the message.
Definition: ApiMessage.php:43
wfDebug
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
Definition: GlobalFunctions.php:915
ApiMain\addRequestedFields
addRequestedFields( $force=[])
Add requested fields to the result.
Definition: ApiMain.php:1172
ContextSource\setContext
setContext(IContextSource $context)
Definition: ContextSource.php:62
ILocalizedException
Interface for MediaWiki-localized exceptions.
Definition: ILocalizedException.php:29
ApiMain\canApiHighLimits
canApiHighLimits()
Check whether the current user is allowed to use high limits.
Definition: ApiMain.php:2140
ApiMain\$mPrinter
ApiFormatBase $mPrinter
Definition: ApiMain.php:214
ApiMain\checkBotReadOnly
checkBotReadOnly()
Check whether we are readonly for bots.
Definition: ApiMain.php:1502
ApiMain\getContinuationManager
getContinuationManager()
Definition: ApiMain.php:438
ApiModuleManager
This class holds a list of modules and handles instantiation.
Definition: ApiModuleManager.php:33
ContextSource\msg
msg( $key,... $params)
Get a Message object with context set Parameters are the same as wfMessage()
Definition: ContextSource.php:195
ApiMain\RIGHTS_MAP
const RIGHTS_MAP
List of user roles that are specifically relevant to the API.
Definition: ApiMain.php:202
ApiMain\checkAsserts
checkAsserts( $params)
Check asserts of the user's rights.
Definition: ApiMain.php:1541
MWDebug\appendDebugInfoToApiResult
static appendDebugInfoToApiResult(IContextSource $context, ApiResult $result)
Append the debug info to given ApiResult.
Definition: MWDebug.php:670
$s
foreach( $mmfl['setupFiles'] as $fileName) if( $queue) if(empty( $mmfl['quiet'])) $s
Definition: mergeMessageFileList.php:206
ApiMain\setContinuationManager
setContinuationManager(ApiContinuationManager $manager=null)
Definition: ApiMain.php:445
MediaWiki\preOutputCommit
static preOutputCommit(IContextSource $context, callable $postCommitWork=null)
This function commits all DB and session changes as needed before the client can receive a response (...
Definition: MediaWiki.php:664
ApiMain\checkExecutePermissions
checkExecutePermissions( $module)
Check for sufficient permissions to execute.
Definition: ApiMain.php:1454
ApiBase\addDeprecation
addDeprecation( $msg, $feature, $data=[])
Add a deprecation warning for this module.
Definition: ApiBase.php:1317
ContextSource\getAuthority
getAuthority()
Definition: ContextSource.php:142
$header
$header
Definition: updateCredits.php:37
ApiBase\LIMIT_SML2
const LIMIT_SML2
Slow query, apihighlimits limit.
Definition: ApiBase.php:169
ApiBase\dieReadOnly
dieReadOnly()
Helper function for readonly errors.
Definition: ApiBase.php:1470
MediaWiki\Session\SessionManager
This serves as the entry point to the MediaWiki session handling system.
Definition: SessionManager.php:53
ApiMain\__construct
__construct( $context=null, $enableWrite=false)
Constructs an instance of ApiMain that utilizes the module and format specified by $request.
Definition: ApiMain.php:266
ApiMain\reportUnusedParams
reportUnusedParams()
Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,...
Definition: ApiMain.php:1861
ApiBase\getPermissionManager
getPermissionManager()
Obtain a PermissionManager instance that subclasses may use in their authorization checks.
Definition: ApiBase.php:630
ApiMain\execute
execute()
Execute api request.
Definition: ApiMain.php:584
ApiBase\isWriteMode
isWriteMode()
Indicates whether this module requires write mode.
Definition: ApiBase.php:342
wfEscapeWikiText
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
Definition: GlobalFunctions.php:1505
ApiMain\$mInternalMode
bool $mInternalMode
Definition: ApiMain.php:238
ApiMain\markParamsSensitive
markParamsSensitive( $params)
Mark parameters as sensitive.
Definition: ApiMain.php:1808
ApiMain\setRequestExpectations
setRequestExpectations(ApiBase $module)
Set database connection, query, and write expectations given this module request.
Definition: ApiMain.php:1663
ApiMain\$mParamValidator
ApiParamValidator $mParamValidator
Definition: ApiMain.php:226
RequestContext\getMain
static getMain()
Get the RequestContext object associated with the main request.
Definition: RequestContext.php:476
ApiMain\logRequest
logRequest( $time, Throwable $e=null)
Log the preceding request.
Definition: ApiMain.php:1682
ApiMain\getCheck
getCheck( $name)
Get a boolean request value, and register the fact that the parameter was used, for logging.
Definition: ApiMain.php:1839
ApiMain\printResult
printResult( $httpCode=0)
Print results using the current printer.
Definition: ApiMain.php:1889
WebRequest
The WebRequest class encapsulates getting at data passed in the URL or via a POSTed form stripping il...
Definition: WebRequest.php:42
ApiErrorFormatter
Formats errors and warnings for the API, and add them to the associated ApiResult.
Definition: ApiErrorFormatter.php:31
ApiMain\handleApiBeforeMainException
static handleApiBeforeMainException(Throwable $e)
Handle a throwable from the ApiBeforeMain hook.
Definition: ApiMain.php:736
MWExceptionHandler\rollbackMasterChangesAndLog
static rollbackMasterChangesAndLog(Throwable $e, $catcher=self::CAUGHT_BY_OTHER)
Roll back any open database transactions and log the stack trace of the throwable.
Definition: MWExceptionHandler.php:125
JobQueueGroup\singleton
static singleton( $domain=false)
Definition: JobQueueGroup.php:70
ApiBase\LIMIT_BIG2
const LIMIT_BIG2
Fast query, apihighlimits limit.
Definition: ApiBase.php:165
ApiMain\API_DEFAULT_FORMAT
const API_DEFAULT_FORMAT
When no format parameter is given, this format will be used.
Definition: ApiMain.php:52
WebRequest\GETHEADER_LIST
const GETHEADER_LIST
Flag to make WebRequest::getHeader return an array of values.
Definition: WebRequest.php:72
ApiMain\getUpload
getUpload( $name)
Get a request upload, and register the fact that it was used, for logging.
Definition: ApiMain.php:1851
ApiMain\$mAction
string null $mAction
Definition: ApiMain.php:232
ApiMain\modifyHelp
modifyHelp(array &$help, array $options, array &$tocData)
Called from ApiHelp before the pieces are joined together and returned.This exists mainly for ApiMain...
Definition: ApiMain.php:1978
Sanitizer\ID_PRIMARY
const ID_PRIMARY
Tells escapeUrlForHtml() to encode the ID using the wiki's primary encoding.
Definition: Sanitizer.php:70
WebRequest\getRequestId
static getRequestId()
Get the current request ID.
Definition: WebRequest.php:330
$path
$path
Definition: NoLocalSettings.php:25
ApiBase\PARAM_DFLT
const PARAM_DFLT
Definition: ApiBase.php:70
ApiBase\getParameter
getParameter( $paramName, $parseLimit=true)
Get a value for the given parameter.
Definition: ApiBase.php:840
Html\openElement
static openElement( $element, $attribs=[])
Identical to rawElement(), but has no third parameter and omits the end tag (and the self-closing '/'...
Definition: Html.php:254
Html\rawElement
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
Definition: Html.php:212
ApiMain\executeAction
executeAction()
Execute the actual module, without any error handling.
Definition: ApiMain.php:1619
ApiMain\setupModule
setupModule()
Set up the module for response.
Definition: ApiMain.php:1225
$help
$help
Definition: mcc.php:32
ApiMain\$mCacheMode
string $mCacheMode
Definition: ApiMain.php:244
$t
$t
Definition: testCompression.php:74
Html\element
static element( $element, $attribs=[], $contents='')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
Definition: Html.php:234
ApiMain\isInternalMode
isInternalMode()
Return true if the API was started by other PHP code using FauxRequest.
Definition: ApiMain.php:378
ApiMain\getUserAgent
getUserAgent()
Fetches the user agent used for this request.
Definition: ApiMain.php:2164
ApiMain\setCacheMaxAge
setCacheMaxAge( $maxage)
Set how long the response should be cached.
Definition: ApiMain.php:486
ApiBase\getHookRunner
getHookRunner()
Get an ApiHookRunner for running core API hooks.
Definition: ApiBase.php:666
User
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:66
MediaWiki\Rest\HeaderParser\Origin
A class to assist with the parsing of Origin header according to the RFC 6454 https://tools....
Definition: Origin.php:12
ApiFormatBase\initPrinter
initPrinter( $unused=false)
Initialize the printer function and prepare the output headers.
Definition: ApiFormatBase.php:189
ApiMain\setCacheMode
setCacheMode( $mode)
Set the type of caching headers which will be sent.
Definition: ApiMain.php:518
ApiMain\getPrinter
getPrinter()
Get the result formatter object.
Definition: ApiMain.php:477
wfExpandUrl
wfExpandUrl( $url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.
Definition: GlobalFunctions.php:495
ApiMain\$mParamsUsed
array $mParamsUsed
Definition: ApiMain.php:250
$type
$type
Definition: testCompression.php:52
ApiMain\$mModule
ApiBase $mModule
Definition: ApiMain.php:241