MediaWiki  master
ApiMain.php
Go to the documentation of this file.
1 <?php
29 use Wikimedia\Timestamp\TimestampException;
30 
47 class ApiMain extends ApiBase {
51  private const API_DEFAULT_FORMAT = 'jsonfm';
52 
56  private const API_DEFAULT_USELANG = 'user';
57 
61  private static $Modules = [
62  'login' => ApiLogin::class,
63  'clientlogin' => ApiClientLogin::class,
64  'logout' => ApiLogout::class,
65  'createaccount' => ApiAMCreateAccount::class,
66  'linkaccount' => ApiLinkAccount::class,
67  'unlinkaccount' => ApiRemoveAuthenticationData::class,
68  'changeauthenticationdata' => ApiChangeAuthenticationData::class,
69  'removeauthenticationdata' => ApiRemoveAuthenticationData::class,
70  'resetpassword' => ApiResetPassword::class,
71  'query' => ApiQuery::class,
72  'expandtemplates' => ApiExpandTemplates::class,
73  'parse' => ApiParse::class,
74  'stashedit' => ApiStashEdit::class,
75  'opensearch' => ApiOpenSearch::class,
76  'feedcontributions' => ApiFeedContributions::class,
77  'feedrecentchanges' => ApiFeedRecentChanges::class,
78  'feedwatchlist' => ApiFeedWatchlist::class,
79  'help' => ApiHelp::class,
80  'paraminfo' => ApiParamInfo::class,
81  'rsd' => ApiRsd::class,
82  'compare' => ApiComparePages::class,
83  'tokens' => ApiTokens::class,
84  'checktoken' => ApiCheckToken::class,
85  'cspreport' => ApiCSPReport::class,
86  'validatepassword' => ApiValidatePassword::class,
87 
88  // Write modules
89  'purge' => ApiPurge::class,
90  'setnotificationtimestamp' => ApiSetNotificationTimestamp::class,
91  'rollback' => ApiRollback::class,
92  'delete' => ApiDelete::class,
93  'undelete' => ApiUndelete::class,
94  'protect' => ApiProtect::class,
95  'block' => ApiBlock::class,
96  'unblock' => ApiUnblock::class,
97  'move' => ApiMove::class,
98  'edit' => ApiEditPage::class,
99  'upload' => ApiUpload::class,
100  'filerevert' => ApiFileRevert::class,
101  'emailuser' => ApiEmailUser::class,
102  'watch' => ApiWatch::class,
103  'patrol' => ApiPatrol::class,
104  'import' => ApiImport::class,
105  'clearhasmsg' => ApiClearHasMsg::class,
106  'userrights' => ApiUserrights::class,
107  'options' => ApiOptions::class,
108  'imagerotate' => ApiImageRotate::class,
109  'revisiondelete' => ApiRevisionDelete::class,
110  'managetags' => ApiManageTags::class,
111  'tag' => ApiTag::class,
112  'mergehistory' => ApiMergeHistory::class,
113  'setpagelanguage' => ApiSetPageLanguage::class,
114  'changecontentmodel' => ApiChangeContentModel::class,
115  ];
116 
120  private static $Formats = [
121  'json' => ApiFormatJson::class,
122  'jsonfm' => ApiFormatJson::class,
123  'php' => ApiFormatPhp::class,
124  'phpfm' => ApiFormatPhp::class,
125  'xml' => ApiFormatXml::class,
126  'xmlfm' => ApiFormatXml::class,
127  'rawfm' => ApiFormatJson::class,
128  'none' => ApiFormatNone::class,
129  ];
130 
137  private static $mRights = [
138  'writeapi' => [
139  'msg' => 'right-writeapi',
140  'params' => []
141  ],
142  'apihighlimits' => [
143  'msg' => 'api-help-right-apihighlimits',
145  ]
146  ];
147 
151  private $mPrinter;
152 
156  private $mAction;
157  private $mEnableWrite;
160  private $mModule;
161 
162  private $mCacheMode = 'private';
164  private $mCacheControl = [];
165  private $mParamsUsed = [];
166  private $mParamsSensitive = [];
167 
169  private $lacksSameOriginSecurity = null;
170 
179  public function __construct( $context = null, $enableWrite = false ) {
180  if ( $context === null ) {
182  } elseif ( $context instanceof WebRequest ) {
183  // BC for pre-1.19
184  $request = $context;
186  }
187  // We set a derivative context so we can change stuff later
188  $derivativeContext = new DerivativeContext( $context );
189  $this->setContext( $derivativeContext );
190 
191  if ( isset( $request ) ) {
192  $derivativeContext->setRequest( $request );
193  } else {
194  $request = $this->getRequest();
195  }
196 
197  $this->mInternalMode = ( $request instanceof FauxRequest );
198 
199  // Special handling for the main module: $parent === $this
200  parent::__construct( $this, $this->mInternalMode ? 'main_int' : 'main' );
201 
202  $config = $this->getConfig();
203 
204  if ( !$this->mInternalMode ) {
205  // If we're in a mode that breaks the same-origin policy, strip
206  // user credentials for security.
207  if ( $this->lacksSameOriginSecurity() ) {
208  global $wgUser;
209  wfDebug( "API: stripping user credentials when the same-origin policy is not applied" );
210  $user = new User();
211  $wgUser = $user;
212  $derivativeContext->setUser( $user );
213  $request->response()->header( 'MediaWiki-Login-Suppressed: true' );
214  }
215  }
216 
217  $this->mParamValidator = new ApiParamValidator(
218  $this, MediaWikiServices::getInstance()->getObjectFactory()
219  );
220 
221  $this->mResult = new ApiResult( $this->getConfig()->get( 'APIMaxResultSize' ) );
222 
223  // Setup uselang. This doesn't use $this->getParameter()
224  // because we're not ready to handle errors yet.
225  // Optimisation: Avoid slow getVal(), this isn't user-generated content.
226  $uselang = $request->getRawVal( 'uselang', self::API_DEFAULT_USELANG );
227  if ( $uselang === 'user' ) {
228  // Assume the parent context is going to return the user language
229  // for uselang=user (see T85635).
230  } else {
231  if ( $uselang === 'content' ) {
232  $uselang = MediaWikiServices::getInstance()->getContentLanguage()->getCode();
233  }
234  $code = RequestContext::sanitizeLangCode( $uselang );
235  $derivativeContext->setLanguage( $code );
236  if ( !$this->mInternalMode ) {
237  global $wgLang;
238  $wgLang = $derivativeContext->getLanguage();
239  RequestContext::getMain()->setLanguage( $wgLang );
240  }
241  }
242 
243  // Set up the error formatter. This doesn't use $this->getParameter()
244  // because we're not ready to handle errors yet.
245  // Optimisation: Avoid slow getVal(), this isn't user-generated content.
246  $errorFormat = $request->getRawVal( 'errorformat', 'bc' );
247  $errorLangCode = $request->getRawVal( 'errorlang', 'uselang' );
248  $errorsUseDB = $request->getCheck( 'errorsuselocal' );
249  if ( in_array( $errorFormat, [ 'plaintext', 'wikitext', 'html', 'raw', 'none' ], true ) ) {
250  if ( $errorLangCode === 'uselang' ) {
251  $errorLang = $this->getLanguage();
252  } elseif ( $errorLangCode === 'content' ) {
253  $errorLang = MediaWikiServices::getInstance()->getContentLanguage();
254  } else {
255  $errorLangCode = RequestContext::sanitizeLangCode( $errorLangCode );
256  $errorLang = MediaWikiServices::getInstance()->getLanguageFactory()
257  ->getLanguage( $errorLangCode );
258  }
259  $this->mErrorFormatter = new ApiErrorFormatter(
260  $this->mResult, $errorLang, $errorFormat, $errorsUseDB
261  );
262  } else {
263  $this->mErrorFormatter = new ApiErrorFormatter_BackCompat( $this->mResult );
264  }
265  $this->mResult->setErrorFormatter( $this->getErrorFormatter() );
266 
267  $this->mModuleMgr = new ApiModuleManager(
268  $this,
269  MediaWikiServices::getInstance()->getObjectFactory()
270  );
271  $this->mModuleMgr->addModules( self::$Modules, 'action' );
272  $this->mModuleMgr->addModules( $config->get( 'APIModules' ), 'action' );
273  $this->mModuleMgr->addModules( self::$Formats, 'format' );
274  $this->mModuleMgr->addModules( $config->get( 'APIFormatModules' ), 'format' );
275 
276  $this->getHookRunner()->onApiMain__moduleManager( $this->mModuleMgr );
277 
278  $this->mContinuationManager = null;
279  $this->mEnableWrite = $enableWrite;
280 
281  $this->mCdnMaxAge = -1; // flag for executeActionWithErrorHandling()
282  }
283 
288  public function isInternalMode() {
289  return $this->mInternalMode;
290  }
291 
297  public function getResult() {
298  return $this->mResult;
299  }
300 
305  public function lacksSameOriginSecurity() {
306  if ( $this->lacksSameOriginSecurity !== null ) {
308  }
309 
310  $request = $this->getRequest();
311 
312  // JSONP mode
313  if ( $request->getCheck( 'callback' ) ) {
314  $this->lacksSameOriginSecurity = true;
315  return true;
316  }
317 
318  // Anonymous CORS
319  if ( $request->getVal( 'origin' ) === '*' ) {
320  $this->lacksSameOriginSecurity = true;
321  return true;
322  }
323 
324  // Header to be used from XMLHTTPRequest when the request might
325  // otherwise be used for XSS.
326  if ( $request->getHeader( 'Treat-as-Untrusted' ) !== false ) {
327  $this->lacksSameOriginSecurity = true;
328  return true;
329  }
330 
331  // Allow extensions to override.
332  $this->lacksSameOriginSecurity = !$this->getHookRunner()
333  ->onRequestHasSameOriginSecurity( $request );
335  }
336 
341  public function getErrorFormatter() {
342  return $this->mErrorFormatter;
343  }
344 
349  public function getContinuationManager() {
351  }
352 
357  public function setContinuationManager( ApiContinuationManager $manager = null ) {
358  if ( $manager !== null && $this->mContinuationManager !== null ) {
359  throw new UnexpectedValueException(
360  __METHOD__ . ': tried to set manager from ' . $manager->getSource() .
361  ' when a manager is already set from ' . $this->mContinuationManager->getSource()
362  );
363  }
364  $this->mContinuationManager = $manager;
365  }
366 
371  public function getParamValidator() : ApiParamValidator {
372  return $this->mParamValidator;
373  }
374 
380  public function getModule() {
381  return $this->mModule;
382  }
383 
389  public function getPrinter() {
390  return $this->mPrinter;
391  }
392 
398  public function setCacheMaxAge( $maxage ) {
399  $this->setCacheControl( [
400  'max-age' => $maxage,
401  's-maxage' => $maxage
402  ] );
403  }
404 
430  public function setCacheMode( $mode ) {
431  if ( !in_array( $mode, [ 'private', 'public', 'anon-public-user-private' ] ) ) {
432  wfDebug( __METHOD__ . ": unrecognised cache mode \"$mode\"" );
433 
434  // Ignore for forwards-compatibility
435  return;
436  }
437 
438  if ( !$this->getPermissionManager()->isEveryoneAllowed( 'read' ) ) {
439  // Private wiki, only private headers
440  if ( $mode !== 'private' ) {
441  wfDebug( __METHOD__ . ": ignoring request for $mode cache mode, private wiki" );
442 
443  return;
444  }
445  }
446 
447  if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) {
448  // User language is used for i18n, so we don't want to publicly
449  // cache. Anons are ok, because if they have non-default language
450  // then there's an appropriate Vary header set by whatever set
451  // their non-default language.
452  wfDebug( __METHOD__ . ": downgrading cache mode 'public' to " .
453  "'anon-public-user-private' due to uselang=user" );
454  $mode = 'anon-public-user-private';
455  }
456 
457  wfDebug( __METHOD__ . ": setting cache mode $mode" );
458  $this->mCacheMode = $mode;
459  }
460 
471  public function setCacheControl( $directives ) {
472  $this->mCacheControl = $directives + $this->mCacheControl;
473  }
474 
482  public function createPrinterByName( $format ) {
483  $printer = $this->mModuleMgr->getModule( $format, 'format', /* $ignoreCache */ true );
484  if ( $printer === null ) {
485  $this->dieWithError(
486  [ 'apierror-unknownformat', wfEscapeWikiText( $format ) ], 'unknown_format'
487  );
488  }
489 
490  return $printer;
491  }
492 
496  public function execute() {
497  if ( $this->mInternalMode ) {
498  $this->executeAction();
499  } else {
501  }
502  }
503 
508  protected function executeActionWithErrorHandling() {
509  // Verify the CORS header before executing the action
510  if ( !$this->handleCORS() ) {
511  // handleCORS() has sent a 403, abort
512  return;
513  }
514 
515  // Exit here if the request method was OPTIONS
516  // (assume there will be a followup GET or POST)
517  if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
518  return;
519  }
520 
521  // In case an error occurs during data output,
522  // clear the output buffer and print just the error information
523  $obLevel = ob_get_level();
524  ob_start();
525 
526  $t = microtime( true );
527  $isError = false;
528  try {
529  $this->executeAction();
530  $runTime = microtime( true ) - $t;
531  $this->logRequest( $runTime );
532  MediaWikiServices::getInstance()->getStatsdDataFactory()->timing(
533  'api.' . $this->mModule->getModuleName() . '.executeTiming', 1000 * $runTime
534  );
535  } catch ( Throwable $e ) {
536  $this->handleException( $e );
537  $this->logRequest( microtime( true ) - $t, $e );
538  $isError = true;
539  }
540 
541  // Disable the client cache on the output so that BlockManager::trackBlockWithCookie is executed
542  // as part of MediaWiki::preOutputCommit().
543  if (
544  $this->mCacheMode === 'private'
545  || (
546  $this->mCacheMode === 'anon-public-user-private'
547  && SessionManager::getGlobalSession()->isPersistent()
548  )
549  ) {
550  $this->getContext()->getOutput()->enableClientCache( false );
551  $this->getContext()->getOutput()->considerCacheSettingsFinal();
552  }
553 
554  // Commit DBs and send any related cookies and headers
556 
557  // Send cache headers after any code which might generate an error, to
558  // avoid sending public cache headers for errors.
559  $this->sendCacheHeaders( $isError );
560 
561  // Executing the action might have already messed with the output
562  // buffers.
563  while ( ob_get_level() > $obLevel ) {
564  ob_end_flush();
565  }
566  }
567 
574  protected function handleException( Throwable $e ) {
575  // T65145: Rollback any open database transactions
576  if ( !$e instanceof ApiUsageException ) {
577  // ApiUsageExceptions are intentional, so don't rollback if that's the case
579  $e,
580  MWExceptionHandler::CAUGHT_BY_ENTRYPOINT
581  );
582  }
583 
584  // Allow extra cleanup and logging
585  $this->getHookRunner()->onApiMain__onException( $this, $e );
586 
587  // Handle any kind of exception by outputting properly formatted error message.
588  // If this fails, an unhandled exception should be thrown so that global error
589  // handler will process and log it.
590 
591  $errCodes = $this->substituteResultWithError( $e );
592 
593  // Error results should not be cached
594  $this->setCacheMode( 'private' );
595 
596  $response = $this->getRequest()->response();
597  $headerStr = 'MediaWiki-API-Error: ' . implode( ', ', $errCodes );
598  $response->header( $headerStr );
599 
600  // Reset and print just the error message
601  ob_clean();
602 
603  // Printer may not be initialized if the extractRequestParams() fails for the main module
604  $this->createErrorPrinter();
605 
606  // Get desired HTTP code from an ApiUsageException. Don't use codes from other
607  // exception types, as they are unlikely to be intended as an HTTP code.
608  $httpCode = $e instanceof ApiUsageException ? $e->getCode() : 0;
609 
610  $failed = false;
611  try {
612  $this->printResult( $httpCode );
613  } catch ( ApiUsageException $ex ) {
614  // The error printer itself is failing. Try suppressing its request
615  // parameters and redo.
616  $failed = true;
617  $this->addWarning( 'apiwarn-errorprinterfailed' );
618  foreach ( $ex->getStatusValue()->getErrors() as $error ) {
619  try {
620  $this->mPrinter->addWarning( $error );
621  } catch ( Throwable $ex2 ) {
622  // WTF?
623  $this->addWarning( $error );
624  }
625  }
626  }
627  if ( $failed ) {
628  $this->mPrinter = null;
629  $this->createErrorPrinter();
630  $this->mPrinter->forceDefaultParams();
631  if ( $httpCode ) {
632  $response->statusHeader( 200 ); // Reset in case the fallback doesn't want a non-200
633  }
634  $this->printResult( $httpCode );
635  }
636  }
637 
648  public static function handleApiBeforeMainException( Throwable $e ) {
649  ob_start();
650 
651  try {
652  $main = new self( RequestContext::getMain(), false );
653  $main->handleException( $e );
654  $main->logRequest( 0, $e );
655  } catch ( Throwable $e2 ) {
656  // Nope, even that didn't work. Punt.
657  throw $e;
658  }
659 
660  // Reset cache headers
661  $main->sendCacheHeaders( true );
662 
663  ob_end_flush();
664  }
665 
680  protected function handleCORS() {
681  $originParam = $this->getParameter( 'origin' ); // defaults to null
682  if ( $originParam === null ) {
683  // No origin parameter, nothing to do
684  return true;
685  }
686 
687  $request = $this->getRequest();
688  $response = $request->response();
689 
690  $allowTiming = false;
691  $varyOrigin = true;
692 
693  if ( $originParam === '*' ) {
694  // Request for anonymous CORS
695  // Technically we should check for the presence of an Origin header
696  // and not process it as CORS if it's not set, but that would
697  // require us to vary on Origin for all 'origin=*' requests which
698  // we don't want to do.
699  $matchedOrigin = true;
700  $allowOrigin = '*';
701  $allowCredentials = 'false';
702  $varyOrigin = false; // No need to vary
703  } else {
704  // Non-anonymous CORS, check we allow the domain
705 
706  // Origin: header is a space-separated list of origins, check all of them
707  $originHeader = $request->getHeader( 'Origin' );
708  if ( $originHeader === false ) {
709  $origins = [];
710  } else {
711  $originHeader = trim( $originHeader );
712  $origins = preg_split( '/\s+/', $originHeader );
713  }
714 
715  if ( !in_array( $originParam, $origins ) ) {
716  // origin parameter set but incorrect
717  // Send a 403 response
718  $response->statusHeader( 403 );
719  $response->header( 'Cache-Control: no-cache' );
720  echo "'origin' parameter does not match Origin header\n";
721 
722  return false;
723  }
724 
725  $config = $this->getConfig();
726  $matchedOrigin = count( $origins ) === 1 && self::matchOrigin(
727  $originParam,
728  $config->get( 'CrossSiteAJAXdomains' ),
729  $config->get( 'CrossSiteAJAXdomainExceptions' )
730  );
731 
732  $allowOrigin = $originHeader;
733  $allowCredentials = 'true';
734  $allowTiming = $originHeader;
735  }
736 
737  if ( $matchedOrigin ) {
738  $requestedMethod = $request->getHeader( 'Access-Control-Request-Method' );
739  $preflight = $request->getMethod() === 'OPTIONS' && $requestedMethod !== false;
740  if ( $preflight ) {
741  // This is a CORS preflight request
742  if ( $requestedMethod !== 'POST' && $requestedMethod !== 'GET' ) {
743  // If method is not a case-sensitive match, do not set any additional headers and terminate.
744  $response->header( 'MediaWiki-CORS-Rejection: Unsupported method requested in preflight' );
745  return true;
746  }
747  // We allow the actual request to send the following headers
748  $requestedHeaders = $request->getHeader( 'Access-Control-Request-Headers' );
749  $allowedHeaders = $this->getConfig()->get( 'AllowedCorsHeaders' );
750  if ( $requestedHeaders !== false ) {
751  if ( !self::matchRequestedHeaders( $requestedHeaders, $allowedHeaders ) ) {
752  $response->header( 'MediaWiki-CORS-Rejection: Unsupported header requested in preflight' );
753  return true;
754  }
755  $response->header( 'Access-Control-Allow-Headers: ' . $requestedHeaders );
756  }
757 
758  // We only allow the actual request to be GET or POST
759  $response->header( 'Access-Control-Allow-Methods: POST, GET' );
760  } elseif ( $request->getMethod() !== 'POST' && $request->getMethod() !== 'GET' ) {
761  // Unsupported non-preflight method, don't handle it as CORS
762  $response->header(
763  'MediaWiki-CORS-Rejection: Unsupported method for simple request or actual request'
764  );
765  return true;
766  }
767 
768  $response->header( "Access-Control-Allow-Origin: $allowOrigin" );
769  $response->header( "Access-Control-Allow-Credentials: $allowCredentials" );
770  // https://www.w3.org/TR/resource-timing/#timing-allow-origin
771  if ( $allowTiming !== false ) {
772  $response->header( "Timing-Allow-Origin: $allowTiming" );
773  }
774 
775  if ( !$preflight ) {
776  $response->header(
777  'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag, '
778  . 'MediaWiki-Login-Suppressed'
779  );
780  }
781  } else {
782  $response->header( 'MediaWiki-CORS-Rejection: Origin mismatch' );
783  }
784 
785  if ( $varyOrigin ) {
786  $this->getOutput()->addVaryHeader( 'Origin' );
787  }
788 
789  return true;
790  }
791 
800  protected static function matchOrigin( $value, $rules, $exceptions ) {
801  foreach ( $rules as $rule ) {
802  if ( preg_match( self::wildcardToRegex( $rule ), $value ) ) {
803  // Rule matches, check exceptions
804  foreach ( $exceptions as $exc ) {
805  if ( preg_match( self::wildcardToRegex( $exc ), $value ) ) {
806  return false;
807  }
808  }
809 
810  return true;
811  }
812  }
813 
814  return false;
815  }
816 
825  protected static function matchRequestedHeaders( $requestedHeaders, $allowedHeaders ) {
826  if ( trim( $requestedHeaders ) === '' ) {
827  return true;
828  }
829  $requestedHeaders = explode( ',', $requestedHeaders );
830  $allowedHeaders = array_change_key_case( array_flip( $allowedHeaders ), CASE_LOWER );
831  foreach ( $requestedHeaders as $rHeader ) {
832  $rHeader = strtolower( trim( $rHeader ) );
833  if ( !isset( $allowedHeaders[$rHeader] ) ) {
834  LoggerFactory::getInstance( 'api-warning' )->warning(
835  'CORS preflight failed on requested header: {header}', [
836  'header' => $rHeader
837  ]
838  );
839  return false;
840  }
841  }
842  return true;
843  }
844 
853  protected static function wildcardToRegex( $wildcard ) {
854  $wildcard = preg_quote( $wildcard, '/' );
855  $wildcard = str_replace(
856  [ '\*', '\?' ],
857  [ '.*?', '.' ],
858  $wildcard
859  );
860 
861  return "/^https?:\/\/$wildcard$/";
862  }
863 
869  protected function sendCacheHeaders( $isError ) {
870  $response = $this->getRequest()->response();
871  $out = $this->getOutput();
872 
873  $out->addVaryHeader( 'Treat-as-Untrusted' );
874 
875  $config = $this->getConfig();
876 
877  if ( $config->get( 'VaryOnXFP' ) ) {
878  $out->addVaryHeader( 'X-Forwarded-Proto' );
879  }
880 
881  if ( !$isError && $this->mModule &&
882  ( $this->getRequest()->getMethod() === 'GET' || $this->getRequest()->getMethod() === 'HEAD' )
883  ) {
884  $etag = $this->mModule->getConditionalRequestData( 'etag' );
885  if ( $etag !== null ) {
886  $response->header( "ETag: $etag" );
887  }
888  $lastMod = $this->mModule->getConditionalRequestData( 'last-modified' );
889  if ( $lastMod !== null ) {
890  $response->header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822, $lastMod ) );
891  }
892  }
893 
894  // The logic should be:
895  // $this->mCacheControl['max-age'] is set?
896  // Use it, the module knows better than our guess.
897  // !$this->mModule || $this->mModule->isWriteMode(), and mCacheMode is private?
898  // Use 0 because we can guess caching is probably the wrong thing to do.
899  // Use $this->getParameter( 'maxage' ), which already defaults to 0.
900  $maxage = 0;
901  if ( isset( $this->mCacheControl['max-age'] ) ) {
902  $maxage = $this->mCacheControl['max-age'];
903  } elseif ( ( $this->mModule && !$this->mModule->isWriteMode() ) ||
904  $this->mCacheMode !== 'private'
905  ) {
906  $maxage = $this->getParameter( 'maxage' );
907  }
908  $privateCache = 'private, must-revalidate, max-age=' . $maxage;
909 
910  if ( $this->mCacheMode == 'private' ) {
911  $response->header( "Cache-Control: $privateCache" );
912  return;
913  }
914 
915  if ( $this->mCacheMode == 'anon-public-user-private' ) {
916  $out->addVaryHeader( 'Cookie' );
917  $response->header( $out->getVaryHeader() );
918  if ( SessionManager::getGlobalSession()->isPersistent() ) {
919  // Logged in or otherwise has session (e.g. anonymous users who have edited)
920  // Mark request private
921  $response->header( "Cache-Control: $privateCache" );
922 
923  return;
924  } // else anonymous, send public headers below
925  }
926 
927  // Send public headers
928  $response->header( $out->getVaryHeader() );
929 
930  // If nobody called setCacheMaxAge(), use the (s)maxage parameters
931  if ( !isset( $this->mCacheControl['s-maxage'] ) ) {
932  $this->mCacheControl['s-maxage'] = $this->getParameter( 'smaxage' );
933  }
934  if ( !isset( $this->mCacheControl['max-age'] ) ) {
935  $this->mCacheControl['max-age'] = $this->getParameter( 'maxage' );
936  }
937 
938  if ( !$this->mCacheControl['s-maxage'] && !$this->mCacheControl['max-age'] ) {
939  // Public cache not requested
940  // Sending a Vary header in this case is harmless, and protects us
941  // against conditional calls of setCacheMaxAge().
942  $response->header( "Cache-Control: $privateCache" );
943 
944  return;
945  }
946 
947  $this->mCacheControl['public'] = true;
948 
949  // Send an Expires header
950  $maxAge = min( $this->mCacheControl['s-maxage'], $this->mCacheControl['max-age'] );
951  $expiryUnixTime = ( $maxAge == 0 ? 1 : time() + $maxAge );
952  $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822, $expiryUnixTime ) );
953 
954  // Construct the Cache-Control header
955  $ccHeader = '';
956  $separator = '';
957  foreach ( $this->mCacheControl as $name => $value ) {
958  if ( is_bool( $value ) ) {
959  if ( $value ) {
960  $ccHeader .= $separator . $name;
961  $separator = ', ';
962  }
963  } else {
964  $ccHeader .= $separator . "$name=$value";
965  $separator = ', ';
966  }
967  }
968 
969  $response->header( "Cache-Control: $ccHeader" );
970  }
971 
975  private function createErrorPrinter() {
976  if ( !isset( $this->mPrinter ) ) {
977  $value = $this->getRequest()->getVal( 'format', self::API_DEFAULT_FORMAT );
978  if ( !$this->mModuleMgr->isDefined( $value, 'format' ) ) {
979  $value = self::API_DEFAULT_FORMAT;
980  }
981  $this->mPrinter = $this->createPrinterByName( $value );
982  }
983 
984  // Printer may not be able to handle errors. This is particularly
985  // likely if the module returns something for getCustomPrinter().
986  if ( !$this->mPrinter->canPrintErrors() ) {
987  $this->mPrinter = $this->createPrinterByName( self::API_DEFAULT_FORMAT );
988  }
989  }
990 
1006  protected function errorMessagesFromException( Throwable $e, $type = 'error' ) {
1007  $messages = [];
1008  if ( $e instanceof ApiUsageException ) {
1009  foreach ( $e->getStatusValue()->getErrorsByType( $type ) as $error ) {
1010  $messages[] = ApiMessage::create( $error );
1011  }
1012  } elseif ( $type !== 'error' ) {
1013  // None of the rest have any messages for non-error types
1014  } else {
1015  // Something is seriously wrong
1016  $config = $this->getConfig();
1017  // TODO: Avoid embedding arbitrary class names in the error code.
1018  $class = preg_replace( '#^Wikimedia\\\Rdbms\\\#', '', get_class( $e ) );
1019  $code = 'internal_api_error_' . $class;
1020  $data = [ 'errorclass' => get_class( $e ) ];
1021  if ( $config->get( 'ShowExceptionDetails' ) ) {
1022  if ( $e instanceof ILocalizedException ) {
1023  $msg = $e->getMessageObject();
1024  } elseif ( $e instanceof MessageSpecifier ) {
1025  $msg = Message::newFromSpecifier( $e );
1026  } else {
1027  $msg = wfEscapeWikiText( $e->getMessage() );
1028  }
1029  $params = [ 'apierror-exceptioncaught', WebRequest::getRequestId(), $msg ];
1030  } else {
1031  $params = [ 'apierror-exceptioncaughttype', WebRequest::getRequestId(), get_class( $e ) ];
1032  }
1033 
1034  $messages[] = ApiMessage::create( $params, $code, $data );
1035  }
1036  return $messages;
1037  }
1038 
1044  protected function substituteResultWithError( Throwable $e ) {
1045  $result = $this->getResult();
1046  $formatter = $this->getErrorFormatter();
1047  $config = $this->getConfig();
1048  $errorCodes = [];
1049 
1050  // Remember existing warnings and errors across the reset
1051  $errors = $result->getResultData( [ 'errors' ] );
1052  $warnings = $result->getResultData( [ 'warnings' ] );
1053  $result->reset();
1054  if ( $warnings !== null ) {
1055  $result->addValue( null, 'warnings', $warnings, ApiResult::NO_SIZE_CHECK );
1056  }
1057  if ( $errors !== null ) {
1058  $result->addValue( null, 'errors', $errors, ApiResult::NO_SIZE_CHECK );
1059 
1060  // Collect the copied error codes for the return value
1061  foreach ( $errors as $error ) {
1062  if ( isset( $error['code'] ) ) {
1063  $errorCodes[$error['code']] = true;
1064  }
1065  }
1066  }
1067 
1068  // Add errors from the exception
1069  $modulePath = $e instanceof ApiUsageException ? $e->getModulePath() : null;
1070  foreach ( $this->errorMessagesFromException( $e, 'error' ) as $msg ) {
1071  if ( ApiErrorFormatter::isValidApiCode( $msg->getApiCode() ) ) {
1072  $errorCodes[$msg->getApiCode()] = true;
1073  } else {
1074  LoggerFactory::getInstance( 'api-warning' )->error( 'Invalid API error code "{code}"', [
1075  'code' => $msg->getApiCode(),
1076  'exception' => $e,
1077  ] );
1078  $errorCodes['<invalid-code>'] = true;
1079  }
1080  $formatter->addError( $modulePath, $msg );
1081  }
1082  foreach ( $this->errorMessagesFromException( $e, 'warning' ) as $msg ) {
1083  $formatter->addWarning( $modulePath, $msg );
1084  }
1085 
1086  // Add additional data. Path depends on whether we're in BC mode or not.
1087  // Data depends on the type of exception.
1088  if ( $formatter instanceof ApiErrorFormatter_BackCompat ) {
1089  $path = [ 'error' ];
1090  } else {
1091  $path = null;
1092  }
1093  if ( $e instanceof ApiUsageException ) {
1094  $link = wfExpandUrl( wfScript( 'api' ) );
1095  $result->addContentValue(
1096  $path,
1097  'docref',
1098  trim(
1099  $this->msg( 'api-usage-docref', $link )->inLanguage( $formatter->getLanguage() )->text()
1100  . ' '
1101  . $this->msg( 'api-usage-mailinglist-ref' )->inLanguage( $formatter->getLanguage() )->text()
1102  )
1103  );
1104  } elseif ( $config->get( 'ShowExceptionDetails' ) ) {
1105  $result->addContentValue(
1106  $path,
1107  'trace',
1108  $this->msg( 'api-exception-trace',
1109  get_class( $e ),
1110  $e->getFile(),
1111  $e->getLine(),
1113  )->inLanguage( $formatter->getLanguage() )->text()
1114  );
1115  }
1116 
1117  // Add the id and such
1118  $this->addRequestedFields( [ 'servedby' ] );
1119 
1120  return array_keys( $errorCodes );
1121  }
1122 
1128  protected function addRequestedFields( $force = [] ) {
1129  $result = $this->getResult();
1130 
1131  $requestid = $this->getParameter( 'requestid' );
1132  if ( $requestid !== null ) {
1133  $result->addValue( null, 'requestid', $requestid, ApiResult::NO_SIZE_CHECK );
1134  }
1135 
1136  if ( $this->getConfig()->get( 'ShowHostnames' ) && (
1137  in_array( 'servedby', $force, true ) || $this->getParameter( 'servedby' )
1138  ) ) {
1139  $result->addValue( null, 'servedby', wfHostname(), ApiResult::NO_SIZE_CHECK );
1140  }
1141 
1142  if ( $this->getParameter( 'curtimestamp' ) ) {
1143  $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601 ), ApiResult::NO_SIZE_CHECK );
1144  }
1145 
1146  if ( $this->getParameter( 'responselanginfo' ) ) {
1147  $result->addValue( null, 'uselang', $this->getLanguage()->getCode(),
1149  $result->addValue( null, 'errorlang', $this->getErrorFormatter()->getLanguage()->getCode(),
1151  }
1152  }
1153 
1158  protected function setupExecuteAction() {
1159  $this->addRequestedFields();
1160 
1161  $params = $this->extractRequestParams();
1162  $this->mAction = $params['action'];
1163 
1164  return $params;
1165  }
1166 
1173  protected function setupModule() {
1174  // Instantiate the module requested by the user
1175  $module = $this->mModuleMgr->getModule( $this->mAction, 'action' );
1176  if ( $module === null ) {
1177  // Probably can't happen
1178  // @codeCoverageIgnoreStart
1179  $this->dieWithError(
1180  [ 'apierror-unknownaction', wfEscapeWikiText( $this->mAction ) ], 'unknown_action'
1181  );
1182  // @codeCoverageIgnoreEnd
1183  }
1184  $moduleParams = $module->extractRequestParams();
1185 
1186  // Check token, if necessary
1187  if ( $module->needsToken() === true ) {
1188  throw new MWException(
1189  "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
1190  'See documentation for ApiBase::needsToken for details.'
1191  );
1192  }
1193  if ( $module->needsToken() ) {
1194  if ( !$module->mustBePosted() ) {
1195  throw new MWException(
1196  "Module '{$module->getModuleName()}' must require POST to use tokens."
1197  );
1198  }
1199 
1200  if ( !isset( $moduleParams['token'] ) ) {
1201  // Probably can't happen
1202  // @codeCoverageIgnoreStart
1203  $module->dieWithError( [ 'apierror-missingparam', 'token' ] );
1204  // @codeCoverageIgnoreEnd
1205  }
1206 
1207  $module->requirePostedParameters( [ 'token' ] );
1208 
1209  if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) {
1210  $module->dieWithError( 'apierror-badtoken' );
1211  }
1212  }
1213 
1214  return $module;
1215  }
1216 
1220  private function getMaxLag() {
1221  $dbLag = MediaWikiServices::getInstance()->getDBLoadBalancer()->getMaxLag();
1222  $lagInfo = [
1223  'host' => $dbLag[0],
1224  'lag' => $dbLag[1],
1225  'type' => 'db'
1226  ];
1227 
1228  $jobQueueLagFactor = $this->getConfig()->get( 'JobQueueIncludeInMaxLagFactor' );
1229  if ( $jobQueueLagFactor ) {
1230  // Turn total number of jobs into seconds by using the configured value
1231  $totalJobs = array_sum( JobQueueGroup::singleton()->getQueueSizes() );
1232  $jobQueueLag = $totalJobs / (float)$jobQueueLagFactor;
1233  if ( $jobQueueLag > $lagInfo['lag'] ) {
1234  $lagInfo = [
1235  'host' => wfHostname(), // XXX: Is there a better value that could be used?
1236  'lag' => $jobQueueLag,
1237  'type' => 'jobqueue',
1238  'jobs' => $totalJobs,
1239  ];
1240  }
1241  }
1242 
1243  $this->getHookRunner()->onApiMaxLagInfo( $lagInfo );
1244 
1245  return $lagInfo;
1246  }
1247 
1254  protected function checkMaxLag( $module, $params ) {
1255  if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
1256  $maxLag = $params['maxlag'];
1257  $lagInfo = $this->getMaxLag();
1258  if ( $lagInfo['lag'] > $maxLag ) {
1259  $response = $this->getRequest()->response();
1260 
1261  $response->header( 'Retry-After: ' . max( (int)$maxLag, 5 ) );
1262  $response->header( 'X-Database-Lag: ' . (int)$lagInfo['lag'] );
1263 
1264  if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
1265  $this->dieWithError(
1266  [ 'apierror-maxlag', $lagInfo['lag'], $lagInfo['host'] ],
1267  'maxlag',
1268  $lagInfo
1269  );
1270  }
1271 
1272  $this->dieWithError( [ 'apierror-maxlag-generic', $lagInfo['lag'] ], 'maxlag', $lagInfo );
1273  }
1274  }
1275 
1276  return true;
1277  }
1278 
1300  protected function checkConditionalRequestHeaders( $module ) {
1301  if ( $this->mInternalMode ) {
1302  // No headers to check in internal mode
1303  return true;
1304  }
1305 
1306  if ( $this->getRequest()->getMethod() !== 'GET' && $this->getRequest()->getMethod() !== 'HEAD' ) {
1307  // Don't check POSTs
1308  return true;
1309  }
1310 
1311  $return304 = false;
1312 
1313  $ifNoneMatch = array_diff(
1314  $this->getRequest()->getHeader( 'If-None-Match', WebRequest::GETHEADER_LIST ) ?: [],
1315  [ '' ]
1316  );
1317  if ( $ifNoneMatch ) {
1318  // @phan-suppress-next-line PhanImpossibleTypeComparison
1319  if ( $ifNoneMatch === [ '*' ] ) {
1320  // API responses always "exist"
1321  $etag = '*';
1322  } else {
1323  $etag = $module->getConditionalRequestData( 'etag' );
1324  }
1325  }
1326  if ( $ifNoneMatch && $etag !== null ) {
1327  $test = substr( $etag, 0, 2 ) === 'W/' ? substr( $etag, 2 ) : $etag;
1328  $match = array_map( function ( $s ) {
1329  return substr( $s, 0, 2 ) === 'W/' ? substr( $s, 2 ) : $s;
1330  }, $ifNoneMatch );
1331  $return304 = in_array( $test, $match, true );
1332  } else {
1333  $value = trim( $this->getRequest()->getHeader( 'If-Modified-Since' ) );
1334 
1335  // Some old browsers sends sizes after the date, like this:
1336  // Wed, 20 Aug 2003 06:51:19 GMT; length=5202
1337  // Ignore that.
1338  $i = strpos( $value, ';' );
1339  if ( $i !== false ) {
1340  $value = trim( substr( $value, 0, $i ) );
1341  }
1342 
1343  if ( $value !== '' ) {
1344  try {
1345  $ts = new MWTimestamp( $value );
1346  if (
1347  // RFC 7231 IMF-fixdate
1348  $ts->getTimestamp( TS_RFC2822 ) === $value ||
1349  // RFC 850
1350  $ts->format( 'l, d-M-y H:i:s' ) . ' GMT' === $value ||
1351  // asctime (with and without space-padded day)
1352  $ts->format( 'D M j H:i:s Y' ) === $value ||
1353  $ts->format( 'D M j H:i:s Y' ) === $value
1354  ) {
1355  $config = $this->getConfig();
1356  $lastMod = $module->getConditionalRequestData( 'last-modified' );
1357  if ( $lastMod !== null ) {
1358  // Mix in some MediaWiki modification times
1359  $modifiedTimes = [
1360  'page' => $lastMod,
1361  'user' => $this->getUser()->getTouched(),
1362  'epoch' => $config->get( 'CacheEpoch' ),
1363  ];
1364 
1365  if ( $config->get( 'UseCdn' ) ) {
1366  // T46570: the core page itself may not change, but resources might
1367  $modifiedTimes['sepoch'] = wfTimestamp(
1368  TS_MW, time() - $config->get( 'CdnMaxAge' )
1369  );
1370  }
1371  $this->getHookRunner()->onOutputPageCheckLastModified( $modifiedTimes, $this->getOutput() );
1372  $lastMod = max( $modifiedTimes );
1373  $return304 = wfTimestamp( TS_MW, $lastMod ) <= $ts->getTimestamp( TS_MW );
1374  }
1375  }
1376  } catch ( TimestampException $e ) {
1377  // Invalid timestamp, ignore it
1378  }
1379  }
1380  }
1381 
1382  if ( $return304 ) {
1383  $this->getRequest()->response()->statusHeader( 304 );
1384 
1385  // Avoid outputting the compressed representation of a zero-length body
1386  Wikimedia\suppressWarnings();
1387  ini_set( 'zlib.output_compression', 0 );
1388  Wikimedia\restoreWarnings();
1390 
1391  return false;
1392  }
1393 
1394  return true;
1395  }
1396 
1401  protected function checkExecutePermissions( $module ) {
1402  $user = $this->getUser();
1403  if ( $module->isReadMode() && !$this->getPermissionManager()->isEveryoneAllowed( 'read' ) &&
1404  !$this->getPermissionManager()->userHasRight( $user, 'read' )
1405  ) {
1406  $this->dieWithError( 'apierror-readapidenied' );
1407  }
1408 
1409  if ( $module->isWriteMode() ) {
1410  if ( !$this->mEnableWrite ) {
1411  $this->dieWithError( 'apierror-noapiwrite' );
1412  } elseif ( !$this->getPermissionManager()->userHasRight( $user, 'writeapi' ) ) {
1413  $this->dieWithError( 'apierror-writeapidenied' );
1414  } elseif ( $this->getRequest()->getHeader( 'Promise-Non-Write-API-Action' ) ) {
1415  $this->dieWithError( 'apierror-promised-nonwrite-api' );
1416  }
1417 
1418  $this->checkReadOnly( $module );
1419  }
1420 
1421  // Allow extensions to stop execution for arbitrary reasons.
1422  $message = 'hookaborted';
1423  if ( !$this->getHookRunner()->onApiCheckCanExecute( $module, $user, $message ) ) {
1424  $this->dieWithError( $message );
1425  }
1426  }
1427 
1432  protected function checkReadOnly( $module ) {
1433  if ( wfReadOnly() ) {
1434  $this->dieReadOnly();
1435  }
1436 
1437  if ( $module->isWriteMode()
1438  && $this->getUser()->isBot()
1439  && MediaWikiServices::getInstance()->getDBLoadBalancer()->getServerCount() > 1
1440  ) {
1441  $this->checkBotReadOnly();
1442  }
1443  }
1444 
1448  private function checkBotReadOnly() {
1449  // Figure out how many servers have passed the lag threshold
1450  $numLagged = 0;
1451  $lagLimit = $this->getConfig()->get( 'APIMaxLagThreshold' );
1452  $laggedServers = [];
1453  $loadBalancer = MediaWikiServices::getInstance()->getDBLoadBalancer();
1454  foreach ( $loadBalancer->getLagTimes() as $serverIndex => $lag ) {
1455  if ( $lag > $lagLimit ) {
1456  ++$numLagged;
1457  $laggedServers[] = $loadBalancer->getServerName( $serverIndex ) . " ({$lag}s)";
1458  }
1459  }
1460 
1461  // If a majority of replica DBs are too lagged then disallow writes
1462  $replicaCount = $loadBalancer->getServerCount() - 1;
1463  if ( $numLagged >= ceil( $replicaCount / 2 ) ) {
1464  $laggedServers = implode( ', ', $laggedServers );
1465  wfDebugLog(
1466  'api-readonly', // Deprecate this channel in favor of api-warning?
1467  "Api request failed as read only because the following DBs are lagged: $laggedServers"
1468  );
1469  LoggerFactory::getInstance( 'api-warning' )->warning(
1470  "Api request failed as read only because the following DBs are lagged: {laggeddbs}", [
1471  'laggeddbs' => $laggedServers,
1472  ]
1473  );
1474 
1475  $this->dieWithError(
1476  'readonly_lag',
1477  'readonly',
1478  [ 'readonlyreason' => "Waiting for $numLagged lagged database(s)" ]
1479  );
1480  }
1481  }
1482 
1487  protected function checkAsserts( $params ) {
1488  if ( isset( $params['assert'] ) ) {
1489  $user = $this->getUser();
1490  switch ( $params['assert'] ) {
1491  case 'anon':
1492  if ( !$user->isAnon() ) {
1493  $this->dieWithError( 'apierror-assertanonfailed' );
1494  }
1495  break;
1496  case 'user':
1497  if ( $user->isAnon() ) {
1498  $this->dieWithError( 'apierror-assertuserfailed' );
1499  }
1500  break;
1501  case 'bot':
1502  if ( !$this->getPermissionManager()->userHasRight( $user, 'bot' ) ) {
1503  $this->dieWithError( 'apierror-assertbotfailed' );
1504  }
1505  break;
1506  }
1507  }
1508  if ( isset( $params['assertuser'] ) ) {
1509  $assertUser = User::newFromName( $params['assertuser'], false );
1510  if ( !$assertUser || !$this->getUser()->equals( $assertUser ) ) {
1511  $this->dieWithError(
1512  [ 'apierror-assertnameduserfailed', wfEscapeWikiText( $params['assertuser'] ) ]
1513  );
1514  }
1515  }
1516  }
1517 
1523  protected function setupExternalResponse( $module, $params ) {
1524  $validMethods = [ 'GET', 'HEAD', 'POST', 'OPTIONS' ];
1525  $request = $this->getRequest();
1526 
1527  if ( !in_array( $request->getMethod(), $validMethods ) ) {
1528  $this->dieWithError( 'apierror-invalidmethod', null, null, 405 );
1529  }
1530 
1531  if ( !$request->wasPosted() && $module->mustBePosted() ) {
1532  // Module requires POST. GET request might still be allowed
1533  // if $wgDebugApi is true, otherwise fail.
1534  $this->dieWithErrorOrDebug( [ 'apierror-mustbeposted', $this->mAction ] );
1535  }
1536 
1537  if ( $request->wasPosted() && !$request->getHeader( 'Content-Type' ) ) {
1538  $this->addDeprecation(
1539  'apiwarn-deprecation-post-without-content-type', 'post-without-content-type'
1540  );
1541  }
1542 
1543  // See if custom printer is used
1544  $this->mPrinter = $module->getCustomPrinter();
1545  if ( $this->mPrinter === null ) {
1546  // Create an appropriate printer
1547  $this->mPrinter = $this->createPrinterByName( $params['format'] );
1548  }
1549 
1550  if ( $request->getProtocol() === 'http' &&
1551  (
1552  $this->getConfig()->get( 'ForceHTTPS' ) ||
1553  $request->getSession()->shouldForceHTTPS() ||
1554  ( $this->getUser()->isLoggedIn() &&
1555  $this->getUser()->requiresHTTPS() )
1556  )
1557  ) {
1558  $this->addDeprecation( 'apiwarn-deprecation-httpsexpected', 'https-expected' );
1559  }
1560  }
1561 
1565  protected function executeAction() {
1566  $params = $this->setupExecuteAction();
1567 
1568  // Check asserts early so e.g. errors in parsing a module's parameters due to being
1569  // logged out don't override the client's intended "am I logged in?" check.
1570  $this->checkAsserts( $params );
1571 
1572  $module = $this->setupModule();
1573  $this->mModule = $module;
1574 
1575  if ( !$this->mInternalMode ) {
1576  $this->setRequestExpectations( $module );
1577  }
1578 
1579  $this->checkExecutePermissions( $module );
1580 
1581  if ( !$this->checkMaxLag( $module, $params ) ) {
1582  return;
1583  }
1584 
1585  if ( !$this->checkConditionalRequestHeaders( $module ) ) {
1586  return;
1587  }
1588 
1589  if ( !$this->mInternalMode ) {
1590  $this->setupExternalResponse( $module, $params );
1591  }
1592 
1593  $module->execute();
1594  $this->getHookRunner()->onAPIAfterExecute( $module );
1595 
1596  $this->reportUnusedParams();
1597 
1598  if ( !$this->mInternalMode ) {
1600 
1601  $this->printResult();
1602  }
1603  }
1604 
1609  protected function setRequestExpectations( ApiBase $module ) {
1610  $limits = $this->getConfig()->get( 'TrxProfilerLimits' );
1611  $trxProfiler = Profiler::instance()->getTransactionProfiler();
1612  $trxProfiler->setLogger( LoggerFactory::getInstance( 'DBPerformance' ) );
1613  if ( $this->getRequest()->hasSafeMethod() ) {
1614  $trxProfiler->setExpectations( $limits['GET'], __METHOD__ );
1615  } elseif ( $this->getRequest()->wasPosted() && !$module->isWriteMode() ) {
1616  $trxProfiler->setExpectations( $limits['POST-nonwrite'], __METHOD__ );
1617  $this->getRequest()->markAsSafeRequest();
1618  } else {
1619  $trxProfiler->setExpectations( $limits['POST'], __METHOD__ );
1620  }
1621  }
1622 
1628  protected function logRequest( $time, Throwable $e = null ) {
1629  $request = $this->getRequest();
1630 
1631  $logCtx = [
1632  // https://gerrit.wikimedia.org/r/plugins/gitiles/mediawiki/event-schemas/+/master/jsonschema/mediawiki/api/request
1633  '$schema' => '/mediawiki/api/request/0.0.1',
1634  'meta' => [
1635  'request_id' => WebRequest::getRequestId(),
1636  'id' => MediaWikiServices::getInstance()
1637  ->getGlobalIdGenerator()->newUUIDv4(),
1638  'dt' => wfTimestamp( TS_ISO_8601 ),
1639  'domain' => $this->getConfig()->get( 'ServerName' ),
1640  // If using the EventBus extension (as intended) with this log channel,
1641  // this stream name will map to a Kafka topic.
1642  'stream' => 'mediawiki.api-request'
1643  ],
1644  'http' => [
1645  'method' => $request->getMethod(),
1646  'client_ip' => $request->getIP()
1647  ],
1648  'database' => WikiMap::getCurrentWikiDbDomain()->getId(),
1649  'backend_time_ms' => (int)round( $time * 1000 ),
1650  ];
1651 
1652  // If set, these headers will be logged in http.request_headers.
1653  $httpRequestHeadersToLog = [ 'accept-language', 'referer', 'user-agent' ];
1654  foreach ( $httpRequestHeadersToLog as $header ) {
1655  if ( $request->getHeader( $header ) ) {
1656  // Set the header in http.request_headers
1657  $logCtx['http']['request_headers'][$header] = $request->getHeader( $header );
1658  }
1659  }
1660 
1661  if ( $e ) {
1662  $logCtx['api_error_codes'] = [];
1663  foreach ( $this->errorMessagesFromException( $e ) as $msg ) {
1664  $logCtx['api_error_codes'][] = $msg->getApiCode();
1665  }
1666  }
1667 
1668  // Construct space separated message for 'api' log channel
1669  $msg = "API {$request->getMethod()} " .
1670  wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
1671  " {$logCtx['http']['client_ip']} " .
1672  "T={$logCtx['backend_time_ms']}ms";
1673 
1674  $sensitive = array_flip( $this->getSensitiveParams() );
1675  foreach ( $this->getParamsUsed() as $name ) {
1676  $value = $request->getVal( $name );
1677  if ( $value === null ) {
1678  continue;
1679  }
1680 
1681  if ( isset( $sensitive[$name] ) ) {
1682  $value = '[redacted]';
1683  $encValue = '[redacted]';
1684  } elseif ( strlen( $value ) > 256 ) {
1685  $value = substr( $value, 0, 256 );
1686  $encValue = $this->encodeRequestLogValue( $value ) . '[...]';
1687  } else {
1688  $encValue = $this->encodeRequestLogValue( $value );
1689  }
1690 
1691  $logCtx['params'][$name] = $value;
1692  $msg .= " {$name}={$encValue}";
1693  }
1694 
1695  // Log an unstructured message to the api channel.
1696  wfDebugLog( 'api', $msg, 'private' );
1697 
1698  // The api-request channel a structured data log channel.
1699  wfDebugLog( 'api-request', '', 'private', $logCtx );
1700  }
1701 
1707  protected function encodeRequestLogValue( $s ) {
1708  static $table = [];
1709  if ( !$table ) {
1710  $chars = ';@$!*(),/:';
1711  $numChars = strlen( $chars );
1712  for ( $i = 0; $i < $numChars; $i++ ) {
1713  $table[rawurlencode( $chars[$i] )] = $chars[$i];
1714  }
1715  }
1716 
1717  return strtr( rawurlencode( $s ), $table );
1718  }
1719 
1724  protected function getParamsUsed() {
1725  return array_keys( $this->mParamsUsed );
1726  }
1727 
1732  public function markParamsUsed( $params ) {
1733  $this->mParamsUsed += array_fill_keys( (array)$params, true );
1734  }
1735 
1741  protected function getSensitiveParams() {
1742  return array_keys( $this->mParamsSensitive );
1743  }
1744 
1750  public function markParamsSensitive( $params ) {
1751  $this->mParamsSensitive += array_fill_keys( (array)$params, true );
1752  }
1753 
1760  public function getVal( $name, $default = null ) {
1761  $this->mParamsUsed[$name] = true;
1762 
1763  $ret = $this->getRequest()->getVal( $name );
1764  if ( $ret === null ) {
1765  if ( $this->getRequest()->getArray( $name ) !== null ) {
1766  // See T12262 for why we don't just implode( '|', ... ) the
1767  // array.
1768  $this->addWarning( [ 'apiwarn-unsupportedarray', $name ] );
1769  }
1770  $ret = $default;
1771  }
1772  return $ret;
1773  }
1774 
1781  public function getCheck( $name ) {
1782  $this->mParamsUsed[$name] = true;
1783  return $this->getRequest()->getCheck( $name );
1784  }
1785 
1793  public function getUpload( $name ) {
1794  $this->mParamsUsed[$name] = true;
1795 
1796  return $this->getRequest()->getUpload( $name );
1797  }
1798 
1803  protected function reportUnusedParams() {
1804  $paramsUsed = $this->getParamsUsed();
1805  $allParams = $this->getRequest()->getValueNames();
1806 
1807  if ( !$this->mInternalMode ) {
1808  // Printer has not yet executed; don't warn that its parameters are unused
1809  $printerParams = $this->mPrinter->encodeParamName(
1810  array_keys( $this->mPrinter->getFinalParams() ?: [] )
1811  );
1812  $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1813  } else {
1814  $unusedParams = array_diff( $allParams, $paramsUsed );
1815  }
1816 
1817  if ( count( $unusedParams ) ) {
1818  $this->addWarning( [
1819  'apierror-unrecognizedparams',
1820  Message::listParam( array_map( 'wfEscapeWikiText', $unusedParams ), 'comma' ),
1821  count( $unusedParams )
1822  ] );
1823  }
1824  }
1825 
1831  protected function printResult( $httpCode = 0 ) {
1832  if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
1833  $this->addWarning( 'apiwarn-wgdebugapi' );
1834  }
1835 
1836  $printer = $this->mPrinter;
1837  $printer->initPrinter( false );
1838  if ( $httpCode ) {
1839  $printer->setHttpStatus( $httpCode );
1840  }
1841  $printer->execute();
1842  $printer->closePrinter();
1843  }
1844 
1848  public function isReadMode() {
1849  return false;
1850  }
1851 
1857  public function getAllowedParams() {
1858  return [
1859  'action' => [
1860  ApiBase::PARAM_DFLT => 'help',
1861  ApiBase::PARAM_TYPE => 'submodule',
1862  ],
1863  'format' => [
1865  ApiBase::PARAM_TYPE => 'submodule',
1866  ],
1867  'maxlag' => [
1868  ApiBase::PARAM_TYPE => 'integer'
1869  ],
1870  'smaxage' => [
1871  ApiBase::PARAM_TYPE => 'integer',
1872  ApiBase::PARAM_DFLT => 0
1873  ],
1874  'maxage' => [
1875  ApiBase::PARAM_TYPE => 'integer',
1876  ApiBase::PARAM_DFLT => 0
1877  ],
1878  'assert' => [
1879  ApiBase::PARAM_TYPE => [ 'anon', 'user', 'bot' ]
1880  ],
1881  'assertuser' => [
1882  ApiBase::PARAM_TYPE => 'user',
1883  UserDef::PARAM_ALLOWED_USER_TYPES => [ 'name' ],
1884  ],
1885  'requestid' => null,
1886  'servedby' => false,
1887  'curtimestamp' => false,
1888  'responselanginfo' => false,
1889  'origin' => null,
1890  'uselang' => [
1892  ],
1893  'errorformat' => [
1894  ApiBase::PARAM_TYPE => [ 'plaintext', 'wikitext', 'html', 'raw', 'none', 'bc' ],
1895  ApiBase::PARAM_DFLT => 'bc',
1896  ],
1897  'errorlang' => [
1898  ApiBase::PARAM_DFLT => 'uselang',
1899  ],
1900  'errorsuselocal' => [
1901  ApiBase::PARAM_DFLT => false,
1902  ],
1903  ];
1904  }
1905 
1907  protected function getExamplesMessages() {
1908  return [
1909  'action=help'
1910  => 'apihelp-help-example-main',
1911  'action=help&recursivesubmodules=1'
1912  => 'apihelp-help-example-recursive',
1913  ];
1914  }
1915 
1920  public function modifyHelp( array &$help, array $options, array &$tocData ) {
1921  // Wish PHP had an "array_insert_before". Instead, we have to manually
1922  // reindex the array to get 'permissions' in the right place.
1923  $oldHelp = $help;
1924  $help = [];
1925  foreach ( $oldHelp as $k => $v ) {
1926  if ( $k === 'submodules' ) {
1927  $help['permissions'] = '';
1928  }
1929  $help[$k] = $v;
1930  }
1931  $help['datatypes'] = '';
1932  $help['templatedparams'] = '';
1933  $help['credits'] = '';
1934 
1935  // Fill 'permissions'
1936  $help['permissions'] .= Html::openElement( 'div',
1937  [ 'class' => 'apihelp-block apihelp-permissions' ] );
1938  $m = $this->msg( 'api-help-permissions' );
1939  if ( !$m->isDisabled() ) {
1940  $help['permissions'] .= Html::rawElement( 'div', [ 'class' => 'apihelp-block-head' ],
1941  $m->numParams( count( self::$mRights ) )->parse()
1942  );
1943  }
1944  $help['permissions'] .= Html::openElement( 'dl' );
1945  foreach ( self::$mRights as $right => $rightMsg ) {
1946  $help['permissions'] .= Html::element( 'dt', null, $right );
1947 
1948  $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse();
1949  $help['permissions'] .= Html::rawElement( 'dd', null, $rightMsg );
1950 
1951  $groups = array_map( function ( $group ) {
1952  return $group == '*' ? 'all' : $group;
1953  }, $this->getPermissionManager()->getGroupsWithPermission( $right ) );
1954 
1955  $help['permissions'] .= Html::rawElement( 'dd', null,
1956  $this->msg( 'api-help-permissions-granted-to' )
1957  ->numParams( count( $groups ) )
1958  ->params( Message::listParam( $groups ) )
1959  ->parse()
1960  );
1961  }
1962  $help['permissions'] .= Html::closeElement( 'dl' );
1963  $help['permissions'] .= Html::closeElement( 'div' );
1964 
1965  // Fill 'datatypes', 'templatedparams', and 'credits', if applicable
1966  if ( empty( $options['nolead'] ) ) {
1967  $level = $options['headerlevel'];
1968  $tocnumber = &$options['tocnumber'];
1969 
1970  $header = $this->msg( 'api-help-datatypes-header' )->parse();
1971 
1972  $id = Sanitizer::escapeIdForAttribute( 'main/datatypes', Sanitizer::ID_PRIMARY );
1973  $idFallback = Sanitizer::escapeIdForAttribute( 'main/datatypes', Sanitizer::ID_FALLBACK );
1974  $headline = Linker::makeHeadline( min( 6, $level ),
1975  ' class="apihelp-header">',
1976  $id,
1977  $header,
1978  '',
1979  $idFallback
1980  );
1981  // Ensure we have a sane anchor
1982  if ( $id !== 'main/datatypes' && $idFallback !== 'main/datatypes' ) {
1983  $headline = '<div id="main/datatypes"></div>' . $headline;
1984  }
1985  $help['datatypes'] .= $headline;
1986  $help['datatypes'] .= $this->msg( 'api-help-datatypes-top' )->parseAsBlock();
1987  $help['datatypes'] .= '<dl>';
1988  foreach ( $this->getParamValidator()->knownTypes() as $type ) {
1989  $m = $this->msg( "api-help-datatype-$type" );
1990  if ( !$m->isDisabled() ) {
1991  $id = "main/datatype/$type";
1992  $help['datatypes'] .= '<dt id="' . htmlspecialchars( $id ) . '">';
1994  if ( $encId !== $id ) {
1995  $help['datatypes'] .= '<span id="' . htmlspecialchars( $encId ) . '"></span>';
1996  }
1998  if ( $encId2 !== $id && $encId2 !== $encId ) {
1999  $help['datatypes'] .= '<span id="' . htmlspecialchars( $encId2 ) . '"></span>';
2000  }
2001  $help['datatypes'] .= htmlspecialchars( $type ) . '</dt><dd>' . $m->parseAsBlock() . "</dd>";
2002  }
2003  }
2004  $help['datatypes'] .= '</dl>';
2005  if ( !isset( $tocData['main/datatypes'] ) ) {
2006  $tocnumber[$level]++;
2007  $tocData['main/datatypes'] = [
2008  'toclevel' => count( $tocnumber ),
2009  'level' => $level,
2010  'anchor' => 'main/datatypes',
2011  'line' => $header,
2012  'number' => implode( '.', $tocnumber ),
2013  'index' => false,
2014  ];
2015  }
2016 
2017  $header = $this->msg( 'api-help-templatedparams-header' )->parse();
2018 
2019  $id = Sanitizer::escapeIdForAttribute( 'main/templatedparams', Sanitizer::ID_PRIMARY );
2020  $idFallback = Sanitizer::escapeIdForAttribute( 'main/templatedparams', Sanitizer::ID_FALLBACK );
2021  $headline = Linker::makeHeadline( min( 6, $level ),
2022  ' class="apihelp-header">',
2023  $id,
2024  $header,
2025  '',
2026  $idFallback
2027  );
2028  // Ensure we have a sane anchor
2029  if ( $id !== 'main/templatedparams' && $idFallback !== 'main/templatedparams' ) {
2030  $headline = '<div id="main/templatedparams"></div>' . $headline;
2031  }
2032  $help['templatedparams'] .= $headline;
2033  $help['templatedparams'] .= $this->msg( 'api-help-templatedparams' )->parseAsBlock();
2034  if ( !isset( $tocData['main/templatedparams'] ) ) {
2035  $tocnumber[$level]++;
2036  $tocData['main/templatedparams'] = [
2037  'toclevel' => count( $tocnumber ),
2038  'level' => $level,
2039  'anchor' => 'main/templatedparams',
2040  'line' => $header,
2041  'number' => implode( '.', $tocnumber ),
2042  'index' => false,
2043  ];
2044  }
2045 
2046  $header = $this->msg( 'api-credits-header' )->parse();
2047  $id = Sanitizer::escapeIdForAttribute( 'main/credits', Sanitizer::ID_PRIMARY );
2048  $idFallback = Sanitizer::escapeIdForAttribute( 'main/credits', Sanitizer::ID_FALLBACK );
2049  $headline = Linker::makeHeadline( min( 6, $level ),
2050  ' class="apihelp-header">',
2051  $id,
2052  $header,
2053  '',
2054  $idFallback
2055  );
2056  // Ensure we have a sane anchor
2057  if ( $id !== 'main/credits' && $idFallback !== 'main/credits' ) {
2058  $headline = '<div id="main/credits"></div>' . $headline;
2059  }
2060  $help['credits'] .= $headline;
2061  $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
2062  if ( !isset( $tocData['main/credits'] ) ) {
2063  $tocnumber[$level]++;
2064  $tocData['main/credits'] = [
2065  'toclevel' => count( $tocnumber ),
2066  'level' => $level,
2067  'anchor' => 'main/credits',
2068  'line' => $header,
2069  'number' => implode( '.', $tocnumber ),
2070  'index' => false,
2071  ];
2072  }
2073  }
2074  }
2075 
2076  private $mCanApiHighLimits = null;
2077 
2082  public function canApiHighLimits() {
2083  if ( !isset( $this->mCanApiHighLimits ) ) {
2084  $this->mCanApiHighLimits = $this->getPermissionManager()
2085  ->userHasRight( $this->getUser(), 'apihighlimits' );
2086  }
2087 
2088  return $this->mCanApiHighLimits;
2089  }
2090 
2095  public function getModuleManager() {
2096  return $this->mModuleMgr;
2097  }
2098 
2107  public function getUserAgent() {
2108  return trim(
2109  $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
2110  $this->getRequest()->getHeader( 'User-agent' )
2111  );
2112  }
2113 }
2114 
ApiUsageException\getStatusValue
getStatusValue()
Fetch the error status.
Definition: ApiUsageException.php:107
ApiMain\executeActionWithErrorHandling
executeActionWithErrorHandling()
Execute an action, and in case of an error, erase whatever partial results have been accumulated,...
Definition: ApiMain.php:508
MWTimestamp
Library for creating and parsing MW-style timestamps.
Definition: MWTimestamp.php:34
ApiMain
This is the main API class, used for both external and internal processing.
Definition: ApiMain.php:47
ContextSource\$context
IContextSource $context
Definition: ContextSource.php:34
ContextSource\getConfig
getConfig()
Definition: ContextSource.php:67
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:75
Message\newFromSpecifier
static newFromSpecifier( $value)
Transform a MessageSpecifier or a primitive value used interchangeably with specifiers (a message key...
Definition: Message.php:436
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:42
ApiMain\substituteResultWithError
substituteResultWithError(Throwable $e)
Replace the result data with the information about a throwable.
Definition: ApiMain.php:1044
ApiMain\checkReadOnly
checkReadOnly( $module)
Check if the DB is read-only for this user.
Definition: ApiMain.php:1432
ApiBase\addWarning
addWarning( $msg, $code=null, $data=null)
Add a warning for this module.
Definition: ApiBase.php:1355
RequestContext\sanitizeLangCode
static sanitizeLangCode( $code)
Accepts a language code and ensures it's sane.
Definition: RequestContext.php:294
ApiMain\$mParamsSensitive
$mParamsSensitive
Definition: ApiMain.php:166
WikiMap\getCurrentWikiDbDomain
static getCurrentWikiDbDomain()
Definition: WikiMap.php:293
ApiMain\$mAction
$mAction
Definition: ApiMain.php:156
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:1724
Profiler\instance
static instance()
Singleton.
Definition: Profiler.php:63
ApiMain\createErrorPrinter
createErrorPrinter()
Create the printer for error output.
Definition: ApiMain.php:975
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:152
ApiMain\getErrorFormatter
getErrorFormatter()
Get the ApiErrorFormatter object associated with current request.
Definition: ApiMain.php:341
ApiMain\getVal
getVal( $name, $default=null)
Get a request value, and register the fact that it was used, for logging.
Definition: ApiMain.php:1760
ApiMain\errorMessagesFromException
errorMessagesFromException(Throwable $e, $type='error')
Create an error message for the given throwable.
Definition: ApiMain.php:1006
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:1120
ApiBase\dieWithError
dieWithError( $msg, $code=null, $data=null, $httpCode=null)
Abort execution with an error.
Definition: ApiBase.php:1436
ApiMain\sendCacheHeaders
sendCacheHeaders( $isError)
Send caching headers.
Definition: ApiMain.php:869
ApiMain\$Modules
static $Modules
List of available modules: action name => module class.
Definition: ApiMain.php:61
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1808
ApiBase\PARAM_TYPE
const PARAM_TYPE
(boolean) Inverse of IntegerDef::PARAM_IGNORE_RANGE
Definition: ApiBase.php:70
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:574
MessageSpecifier
Stable for implementing.
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:308
ApiMain\isReadMode
isReadMode()
Definition: ApiMain.php:1848
ApiMain\handleCORS
handleCORS()
Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
Definition: ApiMain.php:680
MediaWiki\Api\Validator\ApiParamValidator
This wraps a bunch of the API-specific parameter validation logic.
Definition: ApiParamValidator.php:37
ApiMain\checkConditionalRequestHeaders
checkConditionalRequestHeaders( $module)
Check selected RFC 7232 precondition headers.
Definition: ApiMain.php:1300
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:1598
ApiMain\lacksSameOriginSecurity
lacksSameOriginSecurity()
Get the security flag for the current request.
Definition: ApiMain.php:305
wfHostname
wfHostname()
Get host name of the current machine, for use in error reporting.
Definition: GlobalFunctions.php:1282
wfReadOnly
wfReadOnly()
Check whether the wiki is in read-only mode.
Definition: GlobalFunctions.php:1125
User\newFromName
static newFromName( $name, $validate='valid')
Static factory method for creation from username.
Definition: User.php:540
$s
$s
Definition: mergeMessageFileList.php:185
ApiMain\getParamValidator
getParamValidator()
Get the parameter validator.
Definition: ApiMain.php:371
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:76
ApiMain\$mCacheControl
array $mCacheControl
Definition: ApiMain.php:164
ApiMain\encodeRequestLogValue
encodeRequestLogValue( $s)
Encode a value in a format suitable for a space-separated log line.
Definition: ApiMain.php:1707
ContextSource\getUser
getUser()
Stable for overriding.
Definition: ContextSource.php:131
ApiMain\getMaxLag
getMaxLag()
Definition: ApiMain.php:1220
ApiMain\$mContinuationManager
ApiContinuationManager null $mContinuationManager
Definition: ApiMain.php:155
ApiMain\matchOrigin
static matchOrigin( $value, $rules, $exceptions)
Attempt to match an Origin header against a set of rules and a set of exceptions.
Definition: ApiMain.php:800
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:988
ApiMain\$mRights
static $mRights
List of user roles that are specifically relevant to the API.
Definition: ApiMain.php:137
Message\listParam
static listParam(array $list, $type='text')
Definition: Message.php:1125
ApiBase
This abstract class implements many basic API functions, and is the base of all API classes.
Definition: ApiBase.php:52
Wikimedia\ParamValidator\ParamValidator::TypeDef\UserDef
Type definition for user types.
Definition: UserDef.php:23
ApiMain\$mParamValidator
$mParamValidator
Definition: ApiMain.php:153
ContextSource\getLanguage
getLanguage()
Definition: ContextSource.php:140
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:825
Html\closeElement
static closeElement( $element)
Returns "</$element>".
Definition: Html.php:315
ApiMain\getModule
getModule()
Get the API module object.
Definition: ApiMain.php:380
MWExceptionHandler\getRedactedTraceAsString
static getRedactedTraceAsString(Throwable $e)
Generate a string representation of a throwable's stack trace.
Definition: MWExceptionHandler.php:352
DerivativeContext
An IContextSource implementation which will inherit context from another source but allow individual ...
Definition: DerivativeContext.php:31
ApiMain\markParamsUsed
markParamsUsed( $params)
Mark parameters as used.
Definition: ApiMain.php:1732
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:1158
wfScript
wfScript( $script='index')
Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScri...
Definition: GlobalFunctions.php:2528
ApiResult
This class represents the result of the API operations.
Definition: ApiResult.php:35
ApiMain\$mResult
$mResult
Definition: ApiMain.php:153
ApiMain\$lacksSameOriginSecurity
bool null $lacksSameOriginSecurity
Cached return value from self::lacksSameOriginSecurity()
Definition: ApiMain.php:169
ContextSource\getOutput
getOutput()
Definition: ContextSource.php:121
$wgLang
$wgLang
Definition: Setup.php:782
Linker\makeHeadline
static makeHeadline( $level, $attribs, $anchor, $html, $link, $fallbackAnchor=false)
Create a headline for content.
Definition: Linker.php:1802
ApiMain\getResult
getResult()
Get the ApiResult object associated with current request.
Definition: ApiMain.php:297
ApiMain\getSensitiveParams
getSensitiveParams()
Get the request parameters that should be considered sensitive.
Definition: ApiMain.php:1741
ApiMain\checkMaxLag
checkMaxLag( $module, $params)
Check the max lag if necessary.
Definition: ApiMain.php:1254
ApiMain\API_DEFAULT_USELANG
const API_DEFAULT_USELANG
When no uselang parameter is given, this language will be used.
Definition: ApiMain.php:56
ApiBase\extractRequestParams
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition: ApiBase.php:716
ApiMain\getExamplesMessages
getExamplesMessages()
Returns usage examples for this module.Return value has query strings as keys, with values being eith...
Definition: ApiMain.php:1907
ApiMain\setCacheControl
setCacheControl( $directives)
Set directives (key/value pairs) for the Cache-Control header.
Definition: ApiMain.php:471
ApiMain\getAllowedParams
getAllowedParams()
See ApiBase for description.
Definition: ApiMain.php:1857
ApiMain\setupExternalResponse
setupExternalResponse( $module, $params)
Check POST for external response and setup result printer.
Definition: ApiMain.php:1523
ApiMain\createPrinterByName
createPrinterByName( $format)
Create an instance of an output formatter by its name.
Definition: ApiMain.php:482
ApiMain\getModuleManager
getModuleManager()
Overrides to return this instance's module manager.
Definition: ApiMain.php:2095
ApiMain\$mCanApiHighLimits
$mCanApiHighLimits
Definition: ApiMain.php:2076
ApiMessage\create
static create( $msg, $code=null, array $data=null)
Create an IApiMessage for the message.
Definition: ApiMessage.php:42
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:909
ApiMain\addRequestedFields
addRequestedFields( $force=[])
Add requested fields to the result.
Definition: ApiMain.php:1128
ContextSource\setContext
setContext(IContextSource $context)
Definition: ContextSource.php:58
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:2082
ApiMain\$mPrinter
ApiFormatBase $mPrinter
Definition: ApiMain.php:151
ApiMain\checkBotReadOnly
checkBotReadOnly()
Check whether we are readonly for bots.
Definition: ApiMain.php:1448
ApiMain\getContinuationManager
getContinuationManager()
Get the continuation manager.
Definition: ApiMain.php:349
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:184
ApiMain\checkAsserts
checkAsserts( $params)
Check asserts of the user's rights.
Definition: ApiMain.php:1487
ApiMain\$mCacheMode
$mCacheMode
Definition: ApiMain.php:162
MWDebug\appendDebugInfoToApiResult
static appendDebugInfoToApiResult(IContextSource $context, ApiResult $result)
Append the debug info to given ApiResult.
Definition: MWDebug.php:601
wfClearOutputBuffers
wfClearOutputBuffers()
More legible than passing a 'false' parameter to wfResetOutputBuffers():
Definition: GlobalFunctions.php:1687
ApiMain\$mErrorFormatter
$mErrorFormatter
Definition: ApiMain.php:153
ApiMain\$mInternalMode
$mInternalMode
Definition: ApiMain.php:158
ApiMain\setContinuationManager
setContinuationManager(ApiContinuationManager $manager=null)
Set the continuation manager.
Definition: ApiMain.php:357
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:662
ApiMain\wildcardToRegex
static wildcardToRegex( $wildcard)
Helper function to convert wildcard string into a regex '*' => '.
Definition: ApiMain.php:853
ApiMain\checkExecutePermissions
checkExecutePermissions( $module)
Check for sufficient permissions to execute.
Definition: ApiMain.php:1401
ApiBase\addDeprecation
addDeprecation( $msg, $feature, $data=[])
Add a deprecation warning for this module.
Definition: ApiBase.php:1369
$header
$header
Definition: updateCredits.php:41
ApiBase\LIMIT_SML2
const LIMIT_SML2
Slow query, apihighlimits limit.
Definition: ApiBase.php:170
ApiBase\dieReadOnly
dieReadOnly()
Helper function for readonly errors.
Definition: ApiBase.php:1522
MediaWiki\Session\SessionManager
This serves as the entry point to the MediaWiki session handling system.
Definition: SessionManager.php:52
ApiMain\__construct
__construct( $context=null, $enableWrite=false)
Constructs an instance of ApiMain that utilizes the module and format specified by $request.
Definition: ApiMain.php:179
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:1803
ApiBase\getPermissionManager
getPermissionManager()
Obtain a PermissionManager instance that subclasses may use in their authorization checks.
Definition: ApiBase.php:636
ApiMain\execute
execute()
Execute api request.
Definition: ApiMain.php:496
ApiBase\isWriteMode
isWriteMode()
Indicates whether this module requires write mode.
Definition: ApiBase.php:344
wfEscapeWikiText
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
Definition: GlobalFunctions.php:1487
ApiMain\$Formats
static $Formats
List of available formats: format name => format class.
Definition: ApiMain.php:120
ApiMain\markParamsSensitive
markParamsSensitive( $params)
Mark parameters as sensitive.
Definition: ApiMain.php:1750
ApiMain\setRequestExpectations
setRequestExpectations(ApiBase $module)
Set database connection, query, and write expectations given this module request.
Definition: ApiMain.php:1609
RequestContext\getMain
static getMain()
Get the RequestContext object associated with the main request.
Definition: RequestContext.php:455
ApiMain\logRequest
logRequest( $time, Throwable $e=null)
Log the preceding request.
Definition: ApiMain.php:1628
ApiMain\getCheck
getCheck( $name)
Get a boolean request value, and register the fact that the parameter was used, for logging.
Definition: ApiMain.php:1781
ApiMain\printResult
printResult( $httpCode=0)
Print results using the current printer.
Definition: ApiMain.php:1831
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:648
ApiMain\$mEnableWrite
$mEnableWrite
Definition: ApiMain.php:157
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:166
ApiMain\API_DEFAULT_FORMAT
const API_DEFAULT_FORMAT
When no format parameter is given, this format will be used.
Definition: ApiMain.php:51
WebRequest\GETHEADER_LIST
const GETHEADER_LIST
Flag to make WebRequest::getHeader return an array of values.
Definition: WebRequest.php:71
ApiMain\getUpload
getUpload( $name)
Get a request upload, and register the fact that it was used, for logging.
Definition: ApiMain.php:1793
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:1920
Sanitizer\ID_PRIMARY
const ID_PRIMARY
Tells escapeUrlForHtml() to encode the ID using the wiki's primary encoding.
Definition: Sanitizer.php:67
WebRequest\getRequestId
static getRequestId()
Get the unique request ID.
Definition: WebRequest.php:327
$path
$path
Definition: NoLocalSettings.php:25
ApiBase\PARAM_DFLT
const PARAM_DFLT
(boolean) Inverse of IntegerDef::PARAM_IGNORE_RANGE
Definition: ApiBase.php:68
ApiBase\getParameter
getParameter( $paramName, $parseLimit=true)
Get a value for the given parameter.
Definition: ApiBase.php:836
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:251
Html\rawElement
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
Definition: Html.php:209
ApiMain\executeAction
executeAction()
Execute the actual module, without any error handling.
Definition: ApiMain.php:1565
ApiMain\setupModule
setupModule()
Set up the module for response.
Definition: ApiMain.php:1173
$help
$help
Definition: mcc.php:32
$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:231
ApiMain\isInternalMode
isInternalMode()
Return true if the API was started by other PHP code using FauxRequest.
Definition: ApiMain.php:288
ApiMain\$mParamsUsed
$mParamsUsed
Definition: ApiMain.php:165
ApiMain\$mModuleMgr
$mModuleMgr
Definition: ApiMain.php:153
ApiMain\getUserAgent
getUserAgent()
Fetches the user agent used for this request.
Definition: ApiMain.php:2107
ApiMain\setCacheMaxAge
setCacheMaxAge( $maxage)
Set how long the response should be cached.
Definition: ApiMain.php:398
ApiBase\getHookRunner
getHookRunner()
Get an ApiHookRunner for running core API hooks.
Definition: ApiBase.php:661
User
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:59
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:430
ApiMain\getPrinter
getPrinter()
Get the result formatter object.
Definition: ApiMain.php:389
wfExpandUrl
wfExpandUrl( $url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.
Definition: GlobalFunctions.php:490
ApiMain\$mCdnMaxAge
$mCdnMaxAge
Definition: ApiMain.php:158
$type
$type
Definition: testCompression.php:52
ApiMain\$mModule
ApiBase $mModule
Definition: ApiMain.php:160