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' => [
97  'class' => ApiUnblock::class,
98  'services' => [
99  'BlockPermissionCheckerFactory',
100  'UnblockUserFactory',
101  'PermissionManager'
102  ]
103  ],
104  'move' => ApiMove::class,
105  'edit' => ApiEditPage::class,
106  'upload' => ApiUpload::class,
107  'filerevert' => ApiFileRevert::class,
108  'emailuser' => ApiEmailUser::class,
109  'watch' => ApiWatch::class,
110  'patrol' => ApiPatrol::class,
111  'import' => ApiImport::class,
112  'clearhasmsg' => ApiClearHasMsg::class,
113  'userrights' => ApiUserrights::class,
114  'options' => ApiOptions::class,
115  'imagerotate' => ApiImageRotate::class,
116  'revisiondelete' => ApiRevisionDelete::class,
117  'managetags' => ApiManageTags::class,
118  'tag' => ApiTag::class,
119  'mergehistory' => ApiMergeHistory::class,
120  'setpagelanguage' => ApiSetPageLanguage::class,
121  'changecontentmodel' => ApiChangeContentModel::class,
122  ];
123 
127  private static $Formats = [
128  'json' => ApiFormatJson::class,
129  'jsonfm' => ApiFormatJson::class,
130  'php' => ApiFormatPhp::class,
131  'phpfm' => ApiFormatPhp::class,
132  'xml' => ApiFormatXml::class,
133  'xmlfm' => ApiFormatXml::class,
134  'rawfm' => ApiFormatJson::class,
135  'none' => ApiFormatNone::class,
136  ];
137 
144  private static $mRights = [
145  'writeapi' => [
146  'msg' => 'right-writeapi',
147  'params' => []
148  ],
149  'apihighlimits' => [
150  'msg' => 'api-help-right-apihighlimits',
152  ]
153  ];
154 
158  private $mPrinter;
159 
163  private $mAction;
164  private $mEnableWrite;
167  private $mModule;
168 
169  private $mCacheMode = 'private';
171  private $mCacheControl = [];
172  private $mParamsUsed = [];
173  private $mParamsSensitive = [];
174 
176  private $lacksSameOriginSecurity = null;
177 
186  public function __construct( $context = null, $enableWrite = false ) {
187  if ( $context === null ) {
189  } elseif ( $context instanceof WebRequest ) {
190  // BC for pre-1.19
191  $request = $context;
193  }
194  // We set a derivative context so we can change stuff later
195  $derivativeContext = new DerivativeContext( $context );
196  $this->setContext( $derivativeContext );
197 
198  if ( isset( $request ) ) {
199  $derivativeContext->setRequest( $request );
200  } else {
201  $request = $this->getRequest();
202  }
203 
204  $this->mInternalMode = ( $request instanceof FauxRequest );
205 
206  // Special handling for the main module: $parent === $this
207  parent::__construct( $this, $this->mInternalMode ? 'main_int' : 'main' );
208 
209  $config = $this->getConfig();
210 
211  if ( !$this->mInternalMode ) {
212  // If we're in a mode that breaks the same-origin policy, strip
213  // user credentials for security.
214  if ( $this->lacksSameOriginSecurity() ) {
215  global $wgUser;
216  wfDebug( "API: stripping user credentials when the same-origin policy is not applied" );
217  $user = new User();
218  $wgUser = $user;
219  $derivativeContext->setUser( $user );
220  $request->response()->header( 'MediaWiki-Login-Suppressed: true' );
221  }
222  }
223 
224  $this->mParamValidator = new ApiParamValidator(
225  $this, MediaWikiServices::getInstance()->getObjectFactory()
226  );
227 
228  $this->mResult = new ApiResult( $this->getConfig()->get( 'APIMaxResultSize' ) );
229 
230  // Setup uselang. This doesn't use $this->getParameter()
231  // because we're not ready to handle errors yet.
232  // Optimisation: Avoid slow getVal(), this isn't user-generated content.
233  $uselang = $request->getRawVal( 'uselang', self::API_DEFAULT_USELANG );
234  if ( $uselang === 'user' ) {
235  // Assume the parent context is going to return the user language
236  // for uselang=user (see T85635).
237  } else {
238  if ( $uselang === 'content' ) {
239  $uselang = MediaWikiServices::getInstance()->getContentLanguage()->getCode();
240  }
241  $code = RequestContext::sanitizeLangCode( $uselang );
242  $derivativeContext->setLanguage( $code );
243  if ( !$this->mInternalMode ) {
244  global $wgLang;
245  $wgLang = $derivativeContext->getLanguage();
246  RequestContext::getMain()->setLanguage( $wgLang );
247  }
248  }
249 
250  // Set up the error formatter. This doesn't use $this->getParameter()
251  // because we're not ready to handle errors yet.
252  // Optimisation: Avoid slow getVal(), this isn't user-generated content.
253  $errorFormat = $request->getRawVal( 'errorformat', 'bc' );
254  $errorLangCode = $request->getRawVal( 'errorlang', 'uselang' );
255  $errorsUseDB = $request->getCheck( 'errorsuselocal' );
256  if ( in_array( $errorFormat, [ 'plaintext', 'wikitext', 'html', 'raw', 'none' ], true ) ) {
257  if ( $errorLangCode === 'uselang' ) {
258  $errorLang = $this->getLanguage();
259  } elseif ( $errorLangCode === 'content' ) {
260  $errorLang = MediaWikiServices::getInstance()->getContentLanguage();
261  } else {
262  $errorLangCode = RequestContext::sanitizeLangCode( $errorLangCode );
263  $errorLang = MediaWikiServices::getInstance()->getLanguageFactory()
264  ->getLanguage( $errorLangCode );
265  }
266  $this->mErrorFormatter = new ApiErrorFormatter(
267  $this->mResult, $errorLang, $errorFormat, $errorsUseDB
268  );
269  } else {
270  $this->mErrorFormatter = new ApiErrorFormatter_BackCompat( $this->mResult );
271  }
272  $this->mResult->setErrorFormatter( $this->getErrorFormatter() );
273 
274  $this->mModuleMgr = new ApiModuleManager(
275  $this,
276  MediaWikiServices::getInstance()->getObjectFactory()
277  );
278  $this->mModuleMgr->addModules( self::$Modules, 'action' );
279  $this->mModuleMgr->addModules( $config->get( 'APIModules' ), 'action' );
280  $this->mModuleMgr->addModules( self::$Formats, 'format' );
281  $this->mModuleMgr->addModules( $config->get( 'APIFormatModules' ), 'format' );
282 
283  $this->getHookRunner()->onApiMain__moduleManager( $this->mModuleMgr );
284 
285  $this->mContinuationManager = null;
286  $this->mEnableWrite = $enableWrite;
287 
288  $this->mCdnMaxAge = -1; // flag for executeActionWithErrorHandling()
289  }
290 
295  public function isInternalMode() {
296  return $this->mInternalMode;
297  }
298 
304  public function getResult() {
305  return $this->mResult;
306  }
307 
312  public function lacksSameOriginSecurity() {
313  if ( $this->lacksSameOriginSecurity !== null ) {
315  }
316 
317  $request = $this->getRequest();
318 
319  // JSONP mode
320  if ( $request->getCheck( 'callback' ) ) {
321  $this->lacksSameOriginSecurity = true;
322  return true;
323  }
324 
325  // Anonymous CORS
326  if ( $request->getVal( 'origin' ) === '*' ) {
327  $this->lacksSameOriginSecurity = true;
328  return true;
329  }
330 
331  // Header to be used from XMLHTTPRequest when the request might
332  // otherwise be used for XSS.
333  if ( $request->getHeader( 'Treat-as-Untrusted' ) !== false ) {
334  $this->lacksSameOriginSecurity = true;
335  return true;
336  }
337 
338  // Allow extensions to override.
339  $this->lacksSameOriginSecurity = !$this->getHookRunner()
340  ->onRequestHasSameOriginSecurity( $request );
342  }
343 
348  public function getErrorFormatter() {
349  return $this->mErrorFormatter;
350  }
351 
356  public function getContinuationManager() {
358  }
359 
364  public function setContinuationManager( ApiContinuationManager $manager = null ) {
365  if ( $manager !== null && $this->mContinuationManager !== null ) {
366  throw new UnexpectedValueException(
367  __METHOD__ . ': tried to set manager from ' . $manager->getSource() .
368  ' when a manager is already set from ' . $this->mContinuationManager->getSource()
369  );
370  }
371  $this->mContinuationManager = $manager;
372  }
373 
378  public function getParamValidator() : ApiParamValidator {
379  return $this->mParamValidator;
380  }
381 
387  public function getModule() {
388  return $this->mModule;
389  }
390 
396  public function getPrinter() {
397  return $this->mPrinter;
398  }
399 
405  public function setCacheMaxAge( $maxage ) {
406  $this->setCacheControl( [
407  'max-age' => $maxage,
408  's-maxage' => $maxage
409  ] );
410  }
411 
437  public function setCacheMode( $mode ) {
438  if ( !in_array( $mode, [ 'private', 'public', 'anon-public-user-private' ] ) ) {
439  wfDebug( __METHOD__ . ": unrecognised cache mode \"$mode\"" );
440 
441  // Ignore for forwards-compatibility
442  return;
443  }
444 
445  if ( !$this->getPermissionManager()->isEveryoneAllowed( 'read' ) ) {
446  // Private wiki, only private headers
447  if ( $mode !== 'private' ) {
448  wfDebug( __METHOD__ . ": ignoring request for $mode cache mode, private wiki" );
449 
450  return;
451  }
452  }
453 
454  if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) {
455  // User language is used for i18n, so we don't want to publicly
456  // cache. Anons are ok, because if they have non-default language
457  // then there's an appropriate Vary header set by whatever set
458  // their non-default language.
459  wfDebug( __METHOD__ . ": downgrading cache mode 'public' to " .
460  "'anon-public-user-private' due to uselang=user" );
461  $mode = 'anon-public-user-private';
462  }
463 
464  wfDebug( __METHOD__ . ": setting cache mode $mode" );
465  $this->mCacheMode = $mode;
466  }
467 
478  public function setCacheControl( $directives ) {
479  $this->mCacheControl = $directives + $this->mCacheControl;
480  }
481 
489  public function createPrinterByName( $format ) {
490  $printer = $this->mModuleMgr->getModule( $format, 'format', /* $ignoreCache */ true );
491  if ( $printer === null ) {
492  $this->dieWithError(
493  [ 'apierror-unknownformat', wfEscapeWikiText( $format ) ], 'unknown_format'
494  );
495  }
496 
497  return $printer;
498  }
499 
503  public function execute() {
504  if ( $this->mInternalMode ) {
505  $this->executeAction();
506  } else {
508  }
509  }
510 
515  protected function executeActionWithErrorHandling() {
516  // Verify the CORS header before executing the action
517  if ( !$this->handleCORS() ) {
518  // handleCORS() has sent a 403, abort
519  return;
520  }
521 
522  // Exit here if the request method was OPTIONS
523  // (assume there will be a followup GET or POST)
524  if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
525  return;
526  }
527 
528  // In case an error occurs during data output,
529  // clear the output buffer and print just the error information
530  $obLevel = ob_get_level();
531  ob_start();
532 
533  $t = microtime( true );
534  $isError = false;
535  try {
536  $this->executeAction();
537  $runTime = microtime( true ) - $t;
538  $this->logRequest( $runTime );
539  MediaWikiServices::getInstance()->getStatsdDataFactory()->timing(
540  'api.' . $this->mModule->getModuleName() . '.executeTiming', 1000 * $runTime
541  );
542  } catch ( Throwable $e ) {
543  $this->handleException( $e );
544  $this->logRequest( microtime( true ) - $t, $e );
545  $isError = true;
546  }
547 
548  // Disable the client cache on the output so that BlockManager::trackBlockWithCookie is executed
549  // as part of MediaWiki::preOutputCommit().
550  if (
551  $this->mCacheMode === 'private'
552  || (
553  $this->mCacheMode === 'anon-public-user-private'
554  && SessionManager::getGlobalSession()->isPersistent()
555  )
556  ) {
557  $this->getContext()->getOutput()->enableClientCache( false );
558  $this->getContext()->getOutput()->considerCacheSettingsFinal();
559  }
560 
561  // Commit DBs and send any related cookies and headers
563 
564  // Send cache headers after any code which might generate an error, to
565  // avoid sending public cache headers for errors.
566  $this->sendCacheHeaders( $isError );
567 
568  // Executing the action might have already messed with the output
569  // buffers.
570  while ( ob_get_level() > $obLevel ) {
571  ob_end_flush();
572  }
573  }
574 
581  protected function handleException( Throwable $e ) {
582  // T65145: Rollback any open database transactions
583  if ( !$e instanceof ApiUsageException ) {
584  // ApiUsageExceptions are intentional, so don't rollback if that's the case
586  $e,
587  MWExceptionHandler::CAUGHT_BY_ENTRYPOINT
588  );
589  }
590 
591  // Allow extra cleanup and logging
592  $this->getHookRunner()->onApiMain__onException( $this, $e );
593 
594  // Handle any kind of exception by outputting properly formatted error message.
595  // If this fails, an unhandled exception should be thrown so that global error
596  // handler will process and log it.
597 
598  $errCodes = $this->substituteResultWithError( $e );
599 
600  // Error results should not be cached
601  $this->setCacheMode( 'private' );
602 
603  $response = $this->getRequest()->response();
604  $headerStr = 'MediaWiki-API-Error: ' . implode( ', ', $errCodes );
605  $response->header( $headerStr );
606 
607  // Reset and print just the error message
608  ob_clean();
609 
610  // Printer may not be initialized if the extractRequestParams() fails for the main module
611  $this->createErrorPrinter();
612 
613  // Get desired HTTP code from an ApiUsageException. Don't use codes from other
614  // exception types, as they are unlikely to be intended as an HTTP code.
615  $httpCode = $e instanceof ApiUsageException ? $e->getCode() : 0;
616 
617  $failed = false;
618  try {
619  $this->printResult( $httpCode );
620  } catch ( ApiUsageException $ex ) {
621  // The error printer itself is failing. Try suppressing its request
622  // parameters and redo.
623  $failed = true;
624  $this->addWarning( 'apiwarn-errorprinterfailed' );
625  foreach ( $ex->getStatusValue()->getErrors() as $error ) {
626  try {
627  $this->mPrinter->addWarning( $error );
628  } catch ( Throwable $ex2 ) {
629  // WTF?
630  $this->addWarning( $error );
631  }
632  }
633  }
634  if ( $failed ) {
635  $this->mPrinter = null;
636  $this->createErrorPrinter();
637  $this->mPrinter->forceDefaultParams();
638  if ( $httpCode ) {
639  $response->statusHeader( 200 ); // Reset in case the fallback doesn't want a non-200
640  }
641  $this->printResult( $httpCode );
642  }
643  }
644 
655  public static function handleApiBeforeMainException( Throwable $e ) {
656  ob_start();
657 
658  try {
659  $main = new self( RequestContext::getMain(), false );
660  $main->handleException( $e );
661  $main->logRequest( 0, $e );
662  } catch ( Throwable $e2 ) {
663  // Nope, even that didn't work. Punt.
664  throw $e;
665  }
666 
667  // Reset cache headers
668  $main->sendCacheHeaders( true );
669 
670  ob_end_flush();
671  }
672 
687  protected function handleCORS() {
688  $originParam = $this->getParameter( 'origin' ); // defaults to null
689  if ( $originParam === null ) {
690  // No origin parameter, nothing to do
691  return true;
692  }
693 
694  $request = $this->getRequest();
695  $response = $request->response();
696 
697  $allowTiming = false;
698  $varyOrigin = true;
699 
700  if ( $originParam === '*' ) {
701  // Request for anonymous CORS
702  // Technically we should check for the presence of an Origin header
703  // and not process it as CORS if it's not set, but that would
704  // require us to vary on Origin for all 'origin=*' requests which
705  // we don't want to do.
706  $matchedOrigin = true;
707  $allowOrigin = '*';
708  $allowCredentials = 'false';
709  $varyOrigin = false; // No need to vary
710  } else {
711  // Non-anonymous CORS, check we allow the domain
712 
713  // Origin: header is a space-separated list of origins, check all of them
714  $originHeader = $request->getHeader( 'Origin' );
715  if ( $originHeader === false ) {
716  $origins = [];
717  } else {
718  $originHeader = trim( $originHeader );
719  $origins = preg_split( '/\s+/', $originHeader );
720  }
721 
722  if ( !in_array( $originParam, $origins ) ) {
723  // origin parameter set but incorrect
724  // Send a 403 response
725  $response->statusHeader( 403 );
726  $response->header( 'Cache-Control: no-cache' );
727  echo "'origin' parameter does not match Origin header\n";
728 
729  return false;
730  }
731 
732  $config = $this->getConfig();
733  $matchedOrigin = count( $origins ) === 1 && self::matchOrigin(
734  $originParam,
735  $config->get( 'CrossSiteAJAXdomains' ),
736  $config->get( 'CrossSiteAJAXdomainExceptions' )
737  );
738 
739  $allowOrigin = $originHeader;
740  $allowCredentials = 'true';
741  $allowTiming = $originHeader;
742  }
743 
744  if ( $matchedOrigin ) {
745  $requestedMethod = $request->getHeader( 'Access-Control-Request-Method' );
746  $preflight = $request->getMethod() === 'OPTIONS' && $requestedMethod !== false;
747  if ( $preflight ) {
748  // This is a CORS preflight request
749  if ( $requestedMethod !== 'POST' && $requestedMethod !== 'GET' ) {
750  // If method is not a case-sensitive match, do not set any additional headers and terminate.
751  $response->header( 'MediaWiki-CORS-Rejection: Unsupported method requested in preflight' );
752  return true;
753  }
754  // We allow the actual request to send the following headers
755  $requestedHeaders = $request->getHeader( 'Access-Control-Request-Headers' );
756  $allowedHeaders = $this->getConfig()->get( 'AllowedCorsHeaders' );
757  if ( $requestedHeaders !== false ) {
758  if ( !self::matchRequestedHeaders( $requestedHeaders, $allowedHeaders ) ) {
759  $response->header( 'MediaWiki-CORS-Rejection: Unsupported header requested in preflight' );
760  return true;
761  }
762  $response->header( 'Access-Control-Allow-Headers: ' . $requestedHeaders );
763  }
764 
765  // We only allow the actual request to be GET or POST
766  $response->header( 'Access-Control-Allow-Methods: POST, GET' );
767  } elseif ( $request->getMethod() !== 'POST' && $request->getMethod() !== 'GET' ) {
768  // Unsupported non-preflight method, don't handle it as CORS
769  $response->header(
770  'MediaWiki-CORS-Rejection: Unsupported method for simple request or actual request'
771  );
772  return true;
773  }
774 
775  $response->header( "Access-Control-Allow-Origin: $allowOrigin" );
776  $response->header( "Access-Control-Allow-Credentials: $allowCredentials" );
777  // https://www.w3.org/TR/resource-timing/#timing-allow-origin
778  if ( $allowTiming !== false ) {
779  $response->header( "Timing-Allow-Origin: $allowTiming" );
780  }
781 
782  if ( !$preflight ) {
783  $response->header(
784  'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag, '
785  . 'MediaWiki-Login-Suppressed'
786  );
787  }
788  } else {
789  $response->header( 'MediaWiki-CORS-Rejection: Origin mismatch' );
790  }
791 
792  if ( $varyOrigin ) {
793  $this->getOutput()->addVaryHeader( 'Origin' );
794  }
795 
796  return true;
797  }
798 
807  protected static function matchOrigin( $value, $rules, $exceptions ) {
808  foreach ( $rules as $rule ) {
809  if ( preg_match( self::wildcardToRegex( $rule ), $value ) ) {
810  // Rule matches, check exceptions
811  foreach ( $exceptions as $exc ) {
812  if ( preg_match( self::wildcardToRegex( $exc ), $value ) ) {
813  return false;
814  }
815  }
816 
817  return true;
818  }
819  }
820 
821  return false;
822  }
823 
832  protected static function matchRequestedHeaders( $requestedHeaders, $allowedHeaders ) {
833  if ( trim( $requestedHeaders ) === '' ) {
834  return true;
835  }
836  $requestedHeaders = explode( ',', $requestedHeaders );
837  $allowedHeaders = array_change_key_case( array_flip( $allowedHeaders ), CASE_LOWER );
838  foreach ( $requestedHeaders as $rHeader ) {
839  $rHeader = strtolower( trim( $rHeader ) );
840  if ( !isset( $allowedHeaders[$rHeader] ) ) {
841  LoggerFactory::getInstance( 'api-warning' )->warning(
842  'CORS preflight failed on requested header: {header}', [
843  'header' => $rHeader
844  ]
845  );
846  return false;
847  }
848  }
849  return true;
850  }
851 
860  protected static function wildcardToRegex( $wildcard ) {
861  $wildcard = preg_quote( $wildcard, '/' );
862  $wildcard = str_replace(
863  [ '\*', '\?' ],
864  [ '.*?', '.' ],
865  $wildcard
866  );
867 
868  return "/^https?:\/\/$wildcard$/";
869  }
870 
876  protected function sendCacheHeaders( $isError ) {
877  $response = $this->getRequest()->response();
878  $out = $this->getOutput();
879 
880  $out->addVaryHeader( 'Treat-as-Untrusted' );
881 
882  $config = $this->getConfig();
883 
884  if ( $config->get( 'VaryOnXFP' ) ) {
885  $out->addVaryHeader( 'X-Forwarded-Proto' );
886  }
887 
888  if ( !$isError && $this->mModule &&
889  ( $this->getRequest()->getMethod() === 'GET' || $this->getRequest()->getMethod() === 'HEAD' )
890  ) {
891  $etag = $this->mModule->getConditionalRequestData( 'etag' );
892  if ( $etag !== null ) {
893  $response->header( "ETag: $etag" );
894  }
895  $lastMod = $this->mModule->getConditionalRequestData( 'last-modified' );
896  if ( $lastMod !== null ) {
897  $response->header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822, $lastMod ) );
898  }
899  }
900 
901  // The logic should be:
902  // $this->mCacheControl['max-age'] is set?
903  // Use it, the module knows better than our guess.
904  // !$this->mModule || $this->mModule->isWriteMode(), and mCacheMode is private?
905  // Use 0 because we can guess caching is probably the wrong thing to do.
906  // Use $this->getParameter( 'maxage' ), which already defaults to 0.
907  $maxage = 0;
908  if ( isset( $this->mCacheControl['max-age'] ) ) {
909  $maxage = $this->mCacheControl['max-age'];
910  } elseif ( ( $this->mModule && !$this->mModule->isWriteMode() ) ||
911  $this->mCacheMode !== 'private'
912  ) {
913  $maxage = $this->getParameter( 'maxage' );
914  }
915  $privateCache = 'private, must-revalidate, max-age=' . $maxage;
916 
917  if ( $this->mCacheMode == 'private' ) {
918  $response->header( "Cache-Control: $privateCache" );
919  return;
920  }
921 
922  if ( $this->mCacheMode == 'anon-public-user-private' ) {
923  $out->addVaryHeader( 'Cookie' );
924  $response->header( $out->getVaryHeader() );
925  if ( SessionManager::getGlobalSession()->isPersistent() ) {
926  // Logged in or otherwise has session (e.g. anonymous users who have edited)
927  // Mark request private
928  $response->header( "Cache-Control: $privateCache" );
929 
930  return;
931  } // else anonymous, send public headers below
932  }
933 
934  // Send public headers
935  $response->header( $out->getVaryHeader() );
936 
937  // If nobody called setCacheMaxAge(), use the (s)maxage parameters
938  if ( !isset( $this->mCacheControl['s-maxage'] ) ) {
939  $this->mCacheControl['s-maxage'] = $this->getParameter( 'smaxage' );
940  }
941  if ( !isset( $this->mCacheControl['max-age'] ) ) {
942  $this->mCacheControl['max-age'] = $this->getParameter( 'maxage' );
943  }
944 
945  if ( !$this->mCacheControl['s-maxage'] && !$this->mCacheControl['max-age'] ) {
946  // Public cache not requested
947  // Sending a Vary header in this case is harmless, and protects us
948  // against conditional calls of setCacheMaxAge().
949  $response->header( "Cache-Control: $privateCache" );
950 
951  return;
952  }
953 
954  $this->mCacheControl['public'] = true;
955 
956  // Send an Expires header
957  $maxAge = min( $this->mCacheControl['s-maxage'], $this->mCacheControl['max-age'] );
958  $expiryUnixTime = ( $maxAge == 0 ? 1 : time() + $maxAge );
959  $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822, $expiryUnixTime ) );
960 
961  // Construct the Cache-Control header
962  $ccHeader = '';
963  $separator = '';
964  foreach ( $this->mCacheControl as $name => $value ) {
965  if ( is_bool( $value ) ) {
966  if ( $value ) {
967  $ccHeader .= $separator . $name;
968  $separator = ', ';
969  }
970  } else {
971  $ccHeader .= $separator . "$name=$value";
972  $separator = ', ';
973  }
974  }
975 
976  $response->header( "Cache-Control: $ccHeader" );
977  }
978 
982  private function createErrorPrinter() {
983  if ( !isset( $this->mPrinter ) ) {
984  $value = $this->getRequest()->getVal( 'format', self::API_DEFAULT_FORMAT );
985  if ( !$this->mModuleMgr->isDefined( $value, 'format' ) ) {
986  $value = self::API_DEFAULT_FORMAT;
987  }
988  $this->mPrinter = $this->createPrinterByName( $value );
989  }
990 
991  // Printer may not be able to handle errors. This is particularly
992  // likely if the module returns something for getCustomPrinter().
993  if ( !$this->mPrinter->canPrintErrors() ) {
994  $this->mPrinter = $this->createPrinterByName( self::API_DEFAULT_FORMAT );
995  }
996  }
997 
1013  protected function errorMessagesFromException( Throwable $e, $type = 'error' ) {
1014  $messages = [];
1015  if ( $e instanceof ApiUsageException ) {
1016  foreach ( $e->getStatusValue()->getErrorsByType( $type ) as $error ) {
1017  $messages[] = ApiMessage::create( $error );
1018  }
1019  } elseif ( $type !== 'error' ) {
1020  // None of the rest have any messages for non-error types
1021  } else {
1022  // Something is seriously wrong
1023  $config = $this->getConfig();
1024  // TODO: Avoid embedding arbitrary class names in the error code.
1025  $class = preg_replace( '#^Wikimedia\\\Rdbms\\\#', '', get_class( $e ) );
1026  $code = 'internal_api_error_' . $class;
1027  $data = [ 'errorclass' => get_class( $e ) ];
1028  if ( $config->get( 'ShowExceptionDetails' ) ) {
1029  if ( $e instanceof ILocalizedException ) {
1030  $msg = $e->getMessageObject();
1031  } elseif ( $e instanceof MessageSpecifier ) {
1032  $msg = Message::newFromSpecifier( $e );
1033  } else {
1034  $msg = wfEscapeWikiText( $e->getMessage() );
1035  }
1036  $params = [ 'apierror-exceptioncaught', WebRequest::getRequestId(), $msg ];
1037  } else {
1038  $params = [ 'apierror-exceptioncaughttype', WebRequest::getRequestId(), get_class( $e ) ];
1039  }
1040 
1041  $messages[] = ApiMessage::create( $params, $code, $data );
1042  }
1043  return $messages;
1044  }
1045 
1051  protected function substituteResultWithError( Throwable $e ) {
1052  $result = $this->getResult();
1053  $formatter = $this->getErrorFormatter();
1054  $config = $this->getConfig();
1055  $errorCodes = [];
1056 
1057  // Remember existing warnings and errors across the reset
1058  $errors = $result->getResultData( [ 'errors' ] );
1059  $warnings = $result->getResultData( [ 'warnings' ] );
1060  $result->reset();
1061  if ( $warnings !== null ) {
1062  $result->addValue( null, 'warnings', $warnings, ApiResult::NO_SIZE_CHECK );
1063  }
1064  if ( $errors !== null ) {
1065  $result->addValue( null, 'errors', $errors, ApiResult::NO_SIZE_CHECK );
1066 
1067  // Collect the copied error codes for the return value
1068  foreach ( $errors as $error ) {
1069  if ( isset( $error['code'] ) ) {
1070  $errorCodes[$error['code']] = true;
1071  }
1072  }
1073  }
1074 
1075  // Add errors from the exception
1076  $modulePath = $e instanceof ApiUsageException ? $e->getModulePath() : null;
1077  foreach ( $this->errorMessagesFromException( $e, 'error' ) as $msg ) {
1078  if ( ApiErrorFormatter::isValidApiCode( $msg->getApiCode() ) ) {
1079  $errorCodes[$msg->getApiCode()] = true;
1080  } else {
1081  LoggerFactory::getInstance( 'api-warning' )->error( 'Invalid API error code "{code}"', [
1082  'code' => $msg->getApiCode(),
1083  'exception' => $e,
1084  ] );
1085  $errorCodes['<invalid-code>'] = true;
1086  }
1087  $formatter->addError( $modulePath, $msg );
1088  }
1089  foreach ( $this->errorMessagesFromException( $e, 'warning' ) as $msg ) {
1090  $formatter->addWarning( $modulePath, $msg );
1091  }
1092 
1093  // Add additional data. Path depends on whether we're in BC mode or not.
1094  // Data depends on the type of exception.
1095  if ( $formatter instanceof ApiErrorFormatter_BackCompat ) {
1096  $path = [ 'error' ];
1097  } else {
1098  $path = null;
1099  }
1100  if ( $e instanceof ApiUsageException ) {
1101  $link = wfExpandUrl( wfScript( 'api' ) );
1102  $result->addContentValue(
1103  $path,
1104  'docref',
1105  trim(
1106  $this->msg( 'api-usage-docref', $link )->inLanguage( $formatter->getLanguage() )->text()
1107  . ' '
1108  . $this->msg( 'api-usage-mailinglist-ref' )->inLanguage( $formatter->getLanguage() )->text()
1109  )
1110  );
1111  } elseif ( $config->get( 'ShowExceptionDetails' ) ) {
1112  $result->addContentValue(
1113  $path,
1114  'trace',
1115  $this->msg( 'api-exception-trace',
1116  get_class( $e ),
1117  $e->getFile(),
1118  $e->getLine(),
1120  )->inLanguage( $formatter->getLanguage() )->text()
1121  );
1122  }
1123 
1124  // Add the id and such
1125  $this->addRequestedFields( [ 'servedby' ] );
1126 
1127  return array_keys( $errorCodes );
1128  }
1129 
1135  protected function addRequestedFields( $force = [] ) {
1136  $result = $this->getResult();
1137 
1138  $requestid = $this->getParameter( 'requestid' );
1139  if ( $requestid !== null ) {
1140  $result->addValue( null, 'requestid', $requestid, ApiResult::NO_SIZE_CHECK );
1141  }
1142 
1143  if ( $this->getConfig()->get( 'ShowHostnames' ) && (
1144  in_array( 'servedby', $force, true ) || $this->getParameter( 'servedby' )
1145  ) ) {
1146  $result->addValue( null, 'servedby', wfHostname(), ApiResult::NO_SIZE_CHECK );
1147  }
1148 
1149  if ( $this->getParameter( 'curtimestamp' ) ) {
1150  $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601 ), ApiResult::NO_SIZE_CHECK );
1151  }
1152 
1153  if ( $this->getParameter( 'responselanginfo' ) ) {
1154  $result->addValue( null, 'uselang', $this->getLanguage()->getCode(),
1156  $result->addValue( null, 'errorlang', $this->getErrorFormatter()->getLanguage()->getCode(),
1158  }
1159  }
1160 
1165  protected function setupExecuteAction() {
1166  $this->addRequestedFields();
1167 
1168  $params = $this->extractRequestParams();
1169  $this->mAction = $params['action'];
1170 
1171  return $params;
1172  }
1173 
1180  protected function setupModule() {
1181  // Instantiate the module requested by the user
1182  $module = $this->mModuleMgr->getModule( $this->mAction, 'action' );
1183  if ( $module === null ) {
1184  // Probably can't happen
1185  // @codeCoverageIgnoreStart
1186  $this->dieWithError(
1187  [ 'apierror-unknownaction', wfEscapeWikiText( $this->mAction ) ], 'unknown_action'
1188  );
1189  // @codeCoverageIgnoreEnd
1190  }
1191  $moduleParams = $module->extractRequestParams();
1192 
1193  // Check token, if necessary
1194  if ( $module->needsToken() === true ) {
1195  throw new MWException(
1196  "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
1197  'See documentation for ApiBase::needsToken for details.'
1198  );
1199  }
1200  if ( $module->needsToken() ) {
1201  if ( !$module->mustBePosted() ) {
1202  throw new MWException(
1203  "Module '{$module->getModuleName()}' must require POST to use tokens."
1204  );
1205  }
1206 
1207  if ( !isset( $moduleParams['token'] ) ) {
1208  // Probably can't happen
1209  // @codeCoverageIgnoreStart
1210  $module->dieWithError( [ 'apierror-missingparam', 'token' ] );
1211  // @codeCoverageIgnoreEnd
1212  }
1213 
1214  $module->requirePostedParameters( [ 'token' ] );
1215 
1216  if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) {
1217  $module->dieWithError( 'apierror-badtoken' );
1218  }
1219  }
1220 
1221  return $module;
1222  }
1223 
1227  private function getMaxLag() {
1228  $dbLag = MediaWikiServices::getInstance()->getDBLoadBalancer()->getMaxLag();
1229  $lagInfo = [
1230  'host' => $dbLag[0],
1231  'lag' => $dbLag[1],
1232  'type' => 'db'
1233  ];
1234 
1235  $jobQueueLagFactor = $this->getConfig()->get( 'JobQueueIncludeInMaxLagFactor' );
1236  if ( $jobQueueLagFactor ) {
1237  // Turn total number of jobs into seconds by using the configured value
1238  $totalJobs = array_sum( JobQueueGroup::singleton()->getQueueSizes() );
1239  $jobQueueLag = $totalJobs / (float)$jobQueueLagFactor;
1240  if ( $jobQueueLag > $lagInfo['lag'] ) {
1241  $lagInfo = [
1242  'host' => wfHostname(), // XXX: Is there a better value that could be used?
1243  'lag' => $jobQueueLag,
1244  'type' => 'jobqueue',
1245  'jobs' => $totalJobs,
1246  ];
1247  }
1248  }
1249 
1250  $this->getHookRunner()->onApiMaxLagInfo( $lagInfo );
1251 
1252  return $lagInfo;
1253  }
1254 
1261  protected function checkMaxLag( $module, $params ) {
1262  if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
1263  $maxLag = $params['maxlag'];
1264  $lagInfo = $this->getMaxLag();
1265  if ( $lagInfo['lag'] > $maxLag ) {
1266  $response = $this->getRequest()->response();
1267 
1268  $response->header( 'Retry-After: ' . max( (int)$maxLag, 5 ) );
1269  $response->header( 'X-Database-Lag: ' . (int)$lagInfo['lag'] );
1270 
1271  if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
1272  $this->dieWithError(
1273  [ 'apierror-maxlag', $lagInfo['lag'], $lagInfo['host'] ],
1274  'maxlag',
1275  $lagInfo
1276  );
1277  }
1278 
1279  $this->dieWithError( [ 'apierror-maxlag-generic', $lagInfo['lag'] ], 'maxlag', $lagInfo );
1280  }
1281  }
1282 
1283  return true;
1284  }
1285 
1307  protected function checkConditionalRequestHeaders( $module ) {
1308  if ( $this->mInternalMode ) {
1309  // No headers to check in internal mode
1310  return true;
1311  }
1312 
1313  if ( $this->getRequest()->getMethod() !== 'GET' && $this->getRequest()->getMethod() !== 'HEAD' ) {
1314  // Don't check POSTs
1315  return true;
1316  }
1317 
1318  $return304 = false;
1319 
1320  $ifNoneMatch = array_diff(
1321  $this->getRequest()->getHeader( 'If-None-Match', WebRequest::GETHEADER_LIST ) ?: [],
1322  [ '' ]
1323  );
1324  if ( $ifNoneMatch ) {
1325  // @phan-suppress-next-line PhanImpossibleTypeComparison
1326  if ( $ifNoneMatch === [ '*' ] ) {
1327  // API responses always "exist"
1328  $etag = '*';
1329  } else {
1330  $etag = $module->getConditionalRequestData( 'etag' );
1331  }
1332  }
1333  if ( $ifNoneMatch && $etag !== null ) {
1334  $test = substr( $etag, 0, 2 ) === 'W/' ? substr( $etag, 2 ) : $etag;
1335  $match = array_map( function ( $s ) {
1336  return substr( $s, 0, 2 ) === 'W/' ? substr( $s, 2 ) : $s;
1337  }, $ifNoneMatch );
1338  $return304 = in_array( $test, $match, true );
1339  } else {
1340  $value = trim( $this->getRequest()->getHeader( 'If-Modified-Since' ) );
1341 
1342  // Some old browsers sends sizes after the date, like this:
1343  // Wed, 20 Aug 2003 06:51:19 GMT; length=5202
1344  // Ignore that.
1345  $i = strpos( $value, ';' );
1346  if ( $i !== false ) {
1347  $value = trim( substr( $value, 0, $i ) );
1348  }
1349 
1350  if ( $value !== '' ) {
1351  try {
1352  $ts = new MWTimestamp( $value );
1353  if (
1354  // RFC 7231 IMF-fixdate
1355  $ts->getTimestamp( TS_RFC2822 ) === $value ||
1356  // RFC 850
1357  $ts->format( 'l, d-M-y H:i:s' ) . ' GMT' === $value ||
1358  // asctime (with and without space-padded day)
1359  $ts->format( 'D M j H:i:s Y' ) === $value ||
1360  $ts->format( 'D M j H:i:s Y' ) === $value
1361  ) {
1362  $config = $this->getConfig();
1363  $lastMod = $module->getConditionalRequestData( 'last-modified' );
1364  if ( $lastMod !== null ) {
1365  // Mix in some MediaWiki modification times
1366  $modifiedTimes = [
1367  'page' => $lastMod,
1368  'user' => $this->getUser()->getTouched(),
1369  'epoch' => $config->get( 'CacheEpoch' ),
1370  ];
1371 
1372  if ( $config->get( 'UseCdn' ) ) {
1373  // T46570: the core page itself may not change, but resources might
1374  $modifiedTimes['sepoch'] = wfTimestamp(
1375  TS_MW, time() - $config->get( 'CdnMaxAge' )
1376  );
1377  }
1378  $this->getHookRunner()->onOutputPageCheckLastModified( $modifiedTimes, $this->getOutput() );
1379  $lastMod = max( $modifiedTimes );
1380  $return304 = wfTimestamp( TS_MW, $lastMod ) <= $ts->getTimestamp( TS_MW );
1381  }
1382  }
1383  } catch ( TimestampException $e ) {
1384  // Invalid timestamp, ignore it
1385  }
1386  }
1387  }
1388 
1389  if ( $return304 ) {
1390  $this->getRequest()->response()->statusHeader( 304 );
1391 
1392  // Avoid outputting the compressed representation of a zero-length body
1393  Wikimedia\suppressWarnings();
1394  ini_set( 'zlib.output_compression', 0 );
1395  Wikimedia\restoreWarnings();
1397 
1398  return false;
1399  }
1400 
1401  return true;
1402  }
1403 
1408  protected function checkExecutePermissions( $module ) {
1409  $user = $this->getUser();
1410  if ( $module->isReadMode() && !$this->getPermissionManager()->isEveryoneAllowed( 'read' ) &&
1411  !$this->getPermissionManager()->userHasRight( $user, 'read' )
1412  ) {
1413  $this->dieWithError( 'apierror-readapidenied' );
1414  }
1415 
1416  if ( $module->isWriteMode() ) {
1417  if ( !$this->mEnableWrite ) {
1418  $this->dieWithError( 'apierror-noapiwrite' );
1419  } elseif ( !$this->getPermissionManager()->userHasRight( $user, 'writeapi' ) ) {
1420  $this->dieWithError( 'apierror-writeapidenied' );
1421  } elseif ( $this->getRequest()->getHeader( 'Promise-Non-Write-API-Action' ) ) {
1422  $this->dieWithError( 'apierror-promised-nonwrite-api' );
1423  }
1424 
1425  $this->checkReadOnly( $module );
1426  }
1427 
1428  // Allow extensions to stop execution for arbitrary reasons.
1429  $message = 'hookaborted';
1430  if ( !$this->getHookRunner()->onApiCheckCanExecute( $module, $user, $message ) ) {
1431  $this->dieWithError( $message );
1432  }
1433  }
1434 
1439  protected function checkReadOnly( $module ) {
1440  if ( wfReadOnly() ) {
1441  $this->dieReadOnly();
1442  }
1443 
1444  if ( $module->isWriteMode()
1445  && $this->getUser()->isBot()
1446  && MediaWikiServices::getInstance()->getDBLoadBalancer()->getServerCount() > 1
1447  ) {
1448  $this->checkBotReadOnly();
1449  }
1450  }
1451 
1455  private function checkBotReadOnly() {
1456  // Figure out how many servers have passed the lag threshold
1457  $numLagged = 0;
1458  $lagLimit = $this->getConfig()->get( 'APIMaxLagThreshold' );
1459  $laggedServers = [];
1460  $loadBalancer = MediaWikiServices::getInstance()->getDBLoadBalancer();
1461  foreach ( $loadBalancer->getLagTimes() as $serverIndex => $lag ) {
1462  if ( $lag > $lagLimit ) {
1463  ++$numLagged;
1464  $laggedServers[] = $loadBalancer->getServerName( $serverIndex ) . " ({$lag}s)";
1465  }
1466  }
1467 
1468  // If a majority of replica DBs are too lagged then disallow writes
1469  $replicaCount = $loadBalancer->getServerCount() - 1;
1470  if ( $numLagged >= ceil( $replicaCount / 2 ) ) {
1471  $laggedServers = implode( ', ', $laggedServers );
1472  wfDebugLog(
1473  'api-readonly', // Deprecate this channel in favor of api-warning?
1474  "Api request failed as read only because the following DBs are lagged: $laggedServers"
1475  );
1476  LoggerFactory::getInstance( 'api-warning' )->warning(
1477  "Api request failed as read only because the following DBs are lagged: {laggeddbs}", [
1478  'laggeddbs' => $laggedServers,
1479  ]
1480  );
1481 
1482  $this->dieWithError(
1483  'readonly_lag',
1484  'readonly',
1485  [ 'readonlyreason' => "Waiting for $numLagged lagged database(s)" ]
1486  );
1487  }
1488  }
1489 
1494  protected function checkAsserts( $params ) {
1495  if ( isset( $params['assert'] ) ) {
1496  $user = $this->getUser();
1497  switch ( $params['assert'] ) {
1498  case 'anon':
1499  if ( !$user->isAnon() ) {
1500  $this->dieWithError( 'apierror-assertanonfailed' );
1501  }
1502  break;
1503  case 'user':
1504  if ( $user->isAnon() ) {
1505  $this->dieWithError( 'apierror-assertuserfailed' );
1506  }
1507  break;
1508  case 'bot':
1509  if ( !$this->getPermissionManager()->userHasRight( $user, 'bot' ) ) {
1510  $this->dieWithError( 'apierror-assertbotfailed' );
1511  }
1512  break;
1513  }
1514  }
1515  if ( isset( $params['assertuser'] ) ) {
1516  $assertUser = User::newFromName( $params['assertuser'], false );
1517  if ( !$assertUser || !$this->getUser()->equals( $assertUser ) ) {
1518  $this->dieWithError(
1519  [ 'apierror-assertnameduserfailed', wfEscapeWikiText( $params['assertuser'] ) ]
1520  );
1521  }
1522  }
1523  }
1524 
1530  protected function setupExternalResponse( $module, $params ) {
1531  $validMethods = [ 'GET', 'HEAD', 'POST', 'OPTIONS' ];
1532  $request = $this->getRequest();
1533 
1534  if ( !in_array( $request->getMethod(), $validMethods ) ) {
1535  $this->dieWithError( 'apierror-invalidmethod', null, null, 405 );
1536  }
1537 
1538  if ( !$request->wasPosted() && $module->mustBePosted() ) {
1539  // Module requires POST. GET request might still be allowed
1540  // if $wgDebugApi is true, otherwise fail.
1541  $this->dieWithErrorOrDebug( [ 'apierror-mustbeposted', $this->mAction ] );
1542  }
1543 
1544  if ( $request->wasPosted() && !$request->getHeader( 'Content-Type' ) ) {
1545  $this->addDeprecation(
1546  'apiwarn-deprecation-post-without-content-type', 'post-without-content-type'
1547  );
1548  }
1549 
1550  // See if custom printer is used
1551  $this->mPrinter = $module->getCustomPrinter();
1552  if ( $this->mPrinter === null ) {
1553  // Create an appropriate printer
1554  $this->mPrinter = $this->createPrinterByName( $params['format'] );
1555  }
1556 
1557  if ( $request->getProtocol() === 'http' &&
1558  (
1559  $this->getConfig()->get( 'ForceHTTPS' ) ||
1560  $request->getSession()->shouldForceHTTPS() ||
1561  ( $this->getUser()->isLoggedIn() &&
1562  $this->getUser()->requiresHTTPS() )
1563  )
1564  ) {
1565  $this->addDeprecation( 'apiwarn-deprecation-httpsexpected', 'https-expected' );
1566  }
1567  }
1568 
1572  protected function executeAction() {
1573  $params = $this->setupExecuteAction();
1574 
1575  // Check asserts early so e.g. errors in parsing a module's parameters due to being
1576  // logged out don't override the client's intended "am I logged in?" check.
1577  $this->checkAsserts( $params );
1578 
1579  $module = $this->setupModule();
1580  $this->mModule = $module;
1581 
1582  if ( !$this->mInternalMode ) {
1583  $this->setRequestExpectations( $module );
1584  }
1585 
1586  $this->checkExecutePermissions( $module );
1587 
1588  if ( !$this->checkMaxLag( $module, $params ) ) {
1589  return;
1590  }
1591 
1592  if ( !$this->checkConditionalRequestHeaders( $module ) ) {
1593  return;
1594  }
1595 
1596  if ( !$this->mInternalMode ) {
1597  $this->setupExternalResponse( $module, $params );
1598  }
1599 
1600  $module->execute();
1601  $this->getHookRunner()->onAPIAfterExecute( $module );
1602 
1603  $this->reportUnusedParams();
1604 
1605  if ( !$this->mInternalMode ) {
1607 
1608  $this->printResult();
1609  }
1610  }
1611 
1616  protected function setRequestExpectations( ApiBase $module ) {
1617  $limits = $this->getConfig()->get( 'TrxProfilerLimits' );
1618  $trxProfiler = Profiler::instance()->getTransactionProfiler();
1619  $trxProfiler->setLogger( LoggerFactory::getInstance( 'DBPerformance' ) );
1620  if ( $this->getRequest()->hasSafeMethod() ) {
1621  $trxProfiler->setExpectations( $limits['GET'], __METHOD__ );
1622  } elseif ( $this->getRequest()->wasPosted() && !$module->isWriteMode() ) {
1623  $trxProfiler->setExpectations( $limits['POST-nonwrite'], __METHOD__ );
1624  $this->getRequest()->markAsSafeRequest();
1625  } else {
1626  $trxProfiler->setExpectations( $limits['POST'], __METHOD__ );
1627  }
1628  }
1629 
1635  protected function logRequest( $time, Throwable $e = null ) {
1636  $request = $this->getRequest();
1637 
1638  $logCtx = [
1639  // https://gerrit.wikimedia.org/r/plugins/gitiles/mediawiki/event-schemas/+/master/jsonschema/mediawiki/api/request
1640  '$schema' => '/mediawiki/api/request/0.0.1',
1641  'meta' => [
1642  'request_id' => WebRequest::getRequestId(),
1643  'id' => MediaWikiServices::getInstance()
1644  ->getGlobalIdGenerator()->newUUIDv4(),
1645  'dt' => wfTimestamp( TS_ISO_8601 ),
1646  'domain' => $this->getConfig()->get( 'ServerName' ),
1647  // If using the EventBus extension (as intended) with this log channel,
1648  // this stream name will map to a Kafka topic.
1649  'stream' => 'mediawiki.api-request'
1650  ],
1651  'http' => [
1652  'method' => $request->getMethod(),
1653  'client_ip' => $request->getIP()
1654  ],
1655  'database' => WikiMap::getCurrentWikiDbDomain()->getId(),
1656  'backend_time_ms' => (int)round( $time * 1000 ),
1657  ];
1658 
1659  // If set, these headers will be logged in http.request_headers.
1660  $httpRequestHeadersToLog = [ 'accept-language', 'referer', 'user-agent' ];
1661  foreach ( $httpRequestHeadersToLog as $header ) {
1662  if ( $request->getHeader( $header ) ) {
1663  // Set the header in http.request_headers
1664  $logCtx['http']['request_headers'][$header] = $request->getHeader( $header );
1665  }
1666  }
1667 
1668  if ( $e ) {
1669  $logCtx['api_error_codes'] = [];
1670  foreach ( $this->errorMessagesFromException( $e ) as $msg ) {
1671  $logCtx['api_error_codes'][] = $msg->getApiCode();
1672  }
1673  }
1674 
1675  // Construct space separated message for 'api' log channel
1676  $msg = "API {$request->getMethod()} " .
1677  wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
1678  " {$logCtx['http']['client_ip']} " .
1679  "T={$logCtx['backend_time_ms']}ms";
1680 
1681  $sensitive = array_flip( $this->getSensitiveParams() );
1682  foreach ( $this->getParamsUsed() as $name ) {
1683  $value = $request->getVal( $name );
1684  if ( $value === null ) {
1685  continue;
1686  }
1687 
1688  if ( isset( $sensitive[$name] ) ) {
1689  $value = '[redacted]';
1690  $encValue = '[redacted]';
1691  } elseif ( strlen( $value ) > 256 ) {
1692  $value = substr( $value, 0, 256 );
1693  $encValue = $this->encodeRequestLogValue( $value ) . '[...]';
1694  } else {
1695  $encValue = $this->encodeRequestLogValue( $value );
1696  }
1697 
1698  $logCtx['params'][$name] = $value;
1699  $msg .= " {$name}={$encValue}";
1700  }
1701 
1702  // Log an unstructured message to the api channel.
1703  wfDebugLog( 'api', $msg, 'private' );
1704 
1705  // The api-request channel a structured data log channel.
1706  wfDebugLog( 'api-request', '', 'private', $logCtx );
1707  }
1708 
1714  protected function encodeRequestLogValue( $s ) {
1715  static $table = [];
1716  if ( !$table ) {
1717  $chars = ';@$!*(),/:';
1718  $numChars = strlen( $chars );
1719  for ( $i = 0; $i < $numChars; $i++ ) {
1720  $table[rawurlencode( $chars[$i] )] = $chars[$i];
1721  }
1722  }
1723 
1724  return strtr( rawurlencode( $s ), $table );
1725  }
1726 
1731  protected function getParamsUsed() {
1732  return array_keys( $this->mParamsUsed );
1733  }
1734 
1739  public function markParamsUsed( $params ) {
1740  $this->mParamsUsed += array_fill_keys( (array)$params, true );
1741  }
1742 
1748  protected function getSensitiveParams() {
1749  return array_keys( $this->mParamsSensitive );
1750  }
1751 
1757  public function markParamsSensitive( $params ) {
1758  $this->mParamsSensitive += array_fill_keys( (array)$params, true );
1759  }
1760 
1767  public function getVal( $name, $default = null ) {
1768  $this->mParamsUsed[$name] = true;
1769 
1770  $ret = $this->getRequest()->getVal( $name );
1771  if ( $ret === null ) {
1772  if ( $this->getRequest()->getArray( $name ) !== null ) {
1773  // See T12262 for why we don't just implode( '|', ... ) the
1774  // array.
1775  $this->addWarning( [ 'apiwarn-unsupportedarray', $name ] );
1776  }
1777  $ret = $default;
1778  }
1779  return $ret;
1780  }
1781 
1788  public function getCheck( $name ) {
1789  $this->mParamsUsed[$name] = true;
1790  return $this->getRequest()->getCheck( $name );
1791  }
1792 
1800  public function getUpload( $name ) {
1801  $this->mParamsUsed[$name] = true;
1802 
1803  return $this->getRequest()->getUpload( $name );
1804  }
1805 
1810  protected function reportUnusedParams() {
1811  $paramsUsed = $this->getParamsUsed();
1812  $allParams = $this->getRequest()->getValueNames();
1813 
1814  if ( !$this->mInternalMode ) {
1815  // Printer has not yet executed; don't warn that its parameters are unused
1816  $printerParams = $this->mPrinter->encodeParamName(
1817  array_keys( $this->mPrinter->getFinalParams() ?: [] )
1818  );
1819  $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1820  } else {
1821  $unusedParams = array_diff( $allParams, $paramsUsed );
1822  }
1823 
1824  if ( count( $unusedParams ) ) {
1825  $this->addWarning( [
1826  'apierror-unrecognizedparams',
1827  Message::listParam( array_map( 'wfEscapeWikiText', $unusedParams ), 'comma' ),
1828  count( $unusedParams )
1829  ] );
1830  }
1831  }
1832 
1838  protected function printResult( $httpCode = 0 ) {
1839  if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
1840  $this->addWarning( 'apiwarn-wgdebugapi' );
1841  }
1842 
1843  $printer = $this->mPrinter;
1844  $printer->initPrinter( false );
1845  if ( $httpCode ) {
1846  $printer->setHttpStatus( $httpCode );
1847  }
1848  $printer->execute();
1849  $printer->closePrinter();
1850  }
1851 
1855  public function isReadMode() {
1856  return false;
1857  }
1858 
1864  public function getAllowedParams() {
1865  return [
1866  'action' => [
1867  ApiBase::PARAM_DFLT => 'help',
1868  ApiBase::PARAM_TYPE => 'submodule',
1869  ],
1870  'format' => [
1872  ApiBase::PARAM_TYPE => 'submodule',
1873  ],
1874  'maxlag' => [
1875  ApiBase::PARAM_TYPE => 'integer'
1876  ],
1877  'smaxage' => [
1878  ApiBase::PARAM_TYPE => 'integer',
1879  ApiBase::PARAM_DFLT => 0
1880  ],
1881  'maxage' => [
1882  ApiBase::PARAM_TYPE => 'integer',
1883  ApiBase::PARAM_DFLT => 0
1884  ],
1885  'assert' => [
1886  ApiBase::PARAM_TYPE => [ 'anon', 'user', 'bot' ]
1887  ],
1888  'assertuser' => [
1889  ApiBase::PARAM_TYPE => 'user',
1890  UserDef::PARAM_ALLOWED_USER_TYPES => [ 'name' ],
1891  ],
1892  'requestid' => null,
1893  'servedby' => false,
1894  'curtimestamp' => false,
1895  'responselanginfo' => false,
1896  'origin' => null,
1897  'uselang' => [
1899  ],
1900  'errorformat' => [
1901  ApiBase::PARAM_TYPE => [ 'plaintext', 'wikitext', 'html', 'raw', 'none', 'bc' ],
1902  ApiBase::PARAM_DFLT => 'bc',
1903  ],
1904  'errorlang' => [
1905  ApiBase::PARAM_DFLT => 'uselang',
1906  ],
1907  'errorsuselocal' => [
1908  ApiBase::PARAM_DFLT => false,
1909  ],
1910  ];
1911  }
1912 
1914  protected function getExamplesMessages() {
1915  return [
1916  'action=help'
1917  => 'apihelp-help-example-main',
1918  'action=help&recursivesubmodules=1'
1919  => 'apihelp-help-example-recursive',
1920  ];
1921  }
1922 
1927  public function modifyHelp( array &$help, array $options, array &$tocData ) {
1928  // Wish PHP had an "array_insert_before". Instead, we have to manually
1929  // reindex the array to get 'permissions' in the right place.
1930  $oldHelp = $help;
1931  $help = [];
1932  foreach ( $oldHelp as $k => $v ) {
1933  if ( $k === 'submodules' ) {
1934  $help['permissions'] = '';
1935  }
1936  $help[$k] = $v;
1937  }
1938  $help['datatypes'] = '';
1939  $help['templatedparams'] = '';
1940  $help['credits'] = '';
1941 
1942  // Fill 'permissions'
1943  $help['permissions'] .= Html::openElement( 'div',
1944  [ 'class' => 'apihelp-block apihelp-permissions' ] );
1945  $m = $this->msg( 'api-help-permissions' );
1946  if ( !$m->isDisabled() ) {
1947  $help['permissions'] .= Html::rawElement( 'div', [ 'class' => 'apihelp-block-head' ],
1948  $m->numParams( count( self::$mRights ) )->parse()
1949  );
1950  }
1951  $help['permissions'] .= Html::openElement( 'dl' );
1952  foreach ( self::$mRights as $right => $rightMsg ) {
1953  $help['permissions'] .= Html::element( 'dt', null, $right );
1954 
1955  $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse();
1956  $help['permissions'] .= Html::rawElement( 'dd', null, $rightMsg );
1957 
1958  $groups = array_map( function ( $group ) {
1959  return $group == '*' ? 'all' : $group;
1960  }, $this->getPermissionManager()->getGroupsWithPermission( $right ) );
1961 
1962  $help['permissions'] .= Html::rawElement( 'dd', null,
1963  $this->msg( 'api-help-permissions-granted-to' )
1964  ->numParams( count( $groups ) )
1965  ->params( Message::listParam( $groups ) )
1966  ->parse()
1967  );
1968  }
1969  $help['permissions'] .= Html::closeElement( 'dl' );
1970  $help['permissions'] .= Html::closeElement( 'div' );
1971 
1972  // Fill 'datatypes', 'templatedparams', and 'credits', if applicable
1973  if ( empty( $options['nolead'] ) ) {
1974  $level = $options['headerlevel'];
1975  $tocnumber = &$options['tocnumber'];
1976 
1977  $header = $this->msg( 'api-help-datatypes-header' )->parse();
1978 
1979  $id = Sanitizer::escapeIdForAttribute( 'main/datatypes', Sanitizer::ID_PRIMARY );
1980  $idFallback = Sanitizer::escapeIdForAttribute( 'main/datatypes', Sanitizer::ID_FALLBACK );
1981  $headline = Linker::makeHeadline( min( 6, $level ),
1982  ' class="apihelp-header">',
1983  $id,
1984  $header,
1985  '',
1986  $idFallback
1987  );
1988  // Ensure we have a sane anchor
1989  if ( $id !== 'main/datatypes' && $idFallback !== 'main/datatypes' ) {
1990  $headline = '<div id="main/datatypes"></div>' . $headline;
1991  }
1992  $help['datatypes'] .= $headline;
1993  $help['datatypes'] .= $this->msg( 'api-help-datatypes-top' )->parseAsBlock();
1994  $help['datatypes'] .= '<dl>';
1995  foreach ( $this->getParamValidator()->knownTypes() as $type ) {
1996  $m = $this->msg( "api-help-datatype-$type" );
1997  if ( !$m->isDisabled() ) {
1998  $id = "main/datatype/$type";
1999  $help['datatypes'] .= '<dt id="' . htmlspecialchars( $id ) . '">';
2001  if ( $encId !== $id ) {
2002  $help['datatypes'] .= '<span id="' . htmlspecialchars( $encId ) . '"></span>';
2003  }
2005  if ( $encId2 !== $id && $encId2 !== $encId ) {
2006  $help['datatypes'] .= '<span id="' . htmlspecialchars( $encId2 ) . '"></span>';
2007  }
2008  $help['datatypes'] .= htmlspecialchars( $type ) . '</dt><dd>' . $m->parseAsBlock() . "</dd>";
2009  }
2010  }
2011  $help['datatypes'] .= '</dl>';
2012  if ( !isset( $tocData['main/datatypes'] ) ) {
2013  $tocnumber[$level]++;
2014  $tocData['main/datatypes'] = [
2015  'toclevel' => count( $tocnumber ),
2016  'level' => $level,
2017  'anchor' => 'main/datatypes',
2018  'line' => $header,
2019  'number' => implode( '.', $tocnumber ),
2020  'index' => false,
2021  ];
2022  }
2023 
2024  $header = $this->msg( 'api-help-templatedparams-header' )->parse();
2025 
2026  $id = Sanitizer::escapeIdForAttribute( 'main/templatedparams', Sanitizer::ID_PRIMARY );
2027  $idFallback = Sanitizer::escapeIdForAttribute( 'main/templatedparams', Sanitizer::ID_FALLBACK );
2028  $headline = Linker::makeHeadline( min( 6, $level ),
2029  ' class="apihelp-header">',
2030  $id,
2031  $header,
2032  '',
2033  $idFallback
2034  );
2035  // Ensure we have a sane anchor
2036  if ( $id !== 'main/templatedparams' && $idFallback !== 'main/templatedparams' ) {
2037  $headline = '<div id="main/templatedparams"></div>' . $headline;
2038  }
2039  $help['templatedparams'] .= $headline;
2040  $help['templatedparams'] .= $this->msg( 'api-help-templatedparams' )->parseAsBlock();
2041  if ( !isset( $tocData['main/templatedparams'] ) ) {
2042  $tocnumber[$level]++;
2043  $tocData['main/templatedparams'] = [
2044  'toclevel' => count( $tocnumber ),
2045  'level' => $level,
2046  'anchor' => 'main/templatedparams',
2047  'line' => $header,
2048  'number' => implode( '.', $tocnumber ),
2049  'index' => false,
2050  ];
2051  }
2052 
2053  $header = $this->msg( 'api-credits-header' )->parse();
2054  $id = Sanitizer::escapeIdForAttribute( 'main/credits', Sanitizer::ID_PRIMARY );
2055  $idFallback = Sanitizer::escapeIdForAttribute( 'main/credits', Sanitizer::ID_FALLBACK );
2056  $headline = Linker::makeHeadline( min( 6, $level ),
2057  ' class="apihelp-header">',
2058  $id,
2059  $header,
2060  '',
2061  $idFallback
2062  );
2063  // Ensure we have a sane anchor
2064  if ( $id !== 'main/credits' && $idFallback !== 'main/credits' ) {
2065  $headline = '<div id="main/credits"></div>' . $headline;
2066  }
2067  $help['credits'] .= $headline;
2068  $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
2069  if ( !isset( $tocData['main/credits'] ) ) {
2070  $tocnumber[$level]++;
2071  $tocData['main/credits'] = [
2072  'toclevel' => count( $tocnumber ),
2073  'level' => $level,
2074  'anchor' => 'main/credits',
2075  'line' => $header,
2076  'number' => implode( '.', $tocnumber ),
2077  'index' => false,
2078  ];
2079  }
2080  }
2081  }
2082 
2083  private $mCanApiHighLimits = null;
2084 
2089  public function canApiHighLimits() {
2090  if ( !isset( $this->mCanApiHighLimits ) ) {
2091  $this->mCanApiHighLimits = $this->getPermissionManager()
2092  ->userHasRight( $this->getUser(), 'apihighlimits' );
2093  }
2094 
2095  return $this->mCanApiHighLimits;
2096  }
2097 
2102  public function getModuleManager() {
2103  return $this->mModuleMgr;
2104  }
2105 
2114  public function getUserAgent() {
2115  return trim(
2116  $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
2117  $this->getRequest()->getHeader( 'User-agent' )
2118  );
2119  }
2120 }
2121 
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:515
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:78
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:1051
ApiMain\checkReadOnly
checkReadOnly( $module)
Check if the DB is read-only for this user.
Definition: ApiMain.php:1439
ApiBase\addWarning
addWarning( $msg, $code=null, $data=null)
Add a warning for this module.
Definition: ApiBase.php:1300
RequestContext\sanitizeLangCode
static sanitizeLangCode( $code)
Accepts a language code and ensures it's sane.
Definition: RequestContext.php:294
ApiMain\$mParamsSensitive
$mParamsSensitive
Definition: ApiMain.php:173
WikiMap\getCurrentWikiDbDomain
static getCurrentWikiDbDomain()
Definition: WikiMap.php:293
ApiMain\$mAction
$mAction
Definition: ApiMain.php:163
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:1731
Profiler\instance
static instance()
Singleton.
Definition: Profiler.php:69
ApiMain\createErrorPrinter
createErrorPrinter()
Create the printer for error output.
Definition: ApiMain.php:982
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:157
ApiMain\getErrorFormatter
getErrorFormatter()
Get the ApiErrorFormatter object associated with current request.
Definition: ApiMain.php:348
ApiMain\getVal
getVal( $name, $default=null)
Get a request value, and register the fact that it was used, for logging.
Definition: ApiMain.php:1767
ApiMain\errorMessagesFromException
errorMessagesFromException(Throwable $e, $type='error')
Create an error message for the given throwable.
Definition: ApiMain.php:1013
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:815
ApiBase\dieWithError
dieWithError( $msg, $code=null, $data=null, $httpCode=null)
Abort execution with an error.
Definition: ApiBase.php:1381
ApiMain\sendCacheHeaders
sendCacheHeaders( $isError)
Send caching headers.
Definition: ApiMain.php:876
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:1809
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:581
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:1855
ApiMain\handleCORS
handleCORS()
Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
Definition: ApiMain.php:687
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:1307
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:1543
ApiMain\lacksSameOriginSecurity
lacksSameOriginSecurity()
Get the security flag for the current request.
Definition: ApiMain.php:312
wfHostname
wfHostname()
Get host name of the current machine, for use in error reporting.
Definition: GlobalFunctions.php:1283
wfReadOnly
wfReadOnly()
Check whether the wiki is in read-only mode.
Definition: GlobalFunctions.php:1126
User\newFromName
static newFromName( $name, $validate='valid')
Static factory method for creation from username.
Definition: User.php:538
$s
$s
Definition: mergeMessageFileList.php:185
ApiMain\getParamValidator
getParamValidator()
Get the parameter validator.
Definition: ApiMain.php:378
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:171
ApiMain\encodeRequestLogValue
encodeRequestLogValue( $s)
Encode a value in a format suitable for a space-separated log line.
Definition: ApiMain.php:1714
ContextSource\getUser
getUser()
Stable to override.
Definition: ContextSource.php:131
ApiMain\getMaxLag
getMaxLag()
Definition: ApiMain.php:1227
ApiMain\$mContinuationManager
ApiContinuationManager null $mContinuationManager
Definition: ApiMain.php:162
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:807
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:989
ApiMain\$mRights
static $mRights
List of user roles that are specifically relevant to the API.
Definition: ApiMain.php:144
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:25
ApiMain\$mParamValidator
$mParamValidator
Definition: ApiMain.php:160
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:832
Html\closeElement
static closeElement( $element)
Returns "</$element>".
Definition: Html.php:315
ApiMain\getModule
getModule()
Get the API module object.
Definition: ApiMain.php:387
MWExceptionHandler\getRedactedTraceAsString
static getRedactedTraceAsString(Throwable $e)
Generate a string representation of a throwable's stack trace.
Definition: MWExceptionHandler.php:364
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:1739
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:1165
wfScript
wfScript( $script='index')
Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScri...
Definition: GlobalFunctions.php:2536
ApiResult
This class represents the result of the API operations.
Definition: ApiResult.php:35
ApiMain\$mResult
$mResult
Definition: ApiMain.php:160
ApiMain\$lacksSameOriginSecurity
bool null $lacksSameOriginSecurity
Cached return value from self::lacksSameOriginSecurity()
Definition: ApiMain.php:176
ContextSource\getOutput
getOutput()
Definition: ContextSource.php:121
$wgLang
$wgLang
Definition: Setup.php:776
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:304
ApiMain\getSensitiveParams
getSensitiveParams()
Get the request parameters that should be considered sensitive.
Definition: ApiMain.php:1748
ApiMain\checkMaxLag
checkMaxLag( $module, $params)
Check the max lag if necessary.
Definition: ApiMain.php:1261
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:1914
ApiMain\setCacheControl
setCacheControl( $directives)
Set directives (key/value pairs) for the Cache-Control header.
Definition: ApiMain.php:478
ApiMain\getAllowedParams
getAllowedParams()
See ApiBase for description.
Definition: ApiMain.php:1864
ApiMain\setupExternalResponse
setupExternalResponse( $module, $params)
Check POST for external response and setup result printer.
Definition: ApiMain.php:1530
ApiMain\createPrinterByName
createPrinterByName( $format)
Create an instance of an output formatter by its name.
Definition: ApiMain.php:489
ApiMain\getModuleManager
getModuleManager()
Overrides to return this instance's module manager.
Definition: ApiMain.php:2102
ApiMain\$mCanApiHighLimits
$mCanApiHighLimits
Definition: ApiMain.php:2083
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:910
ApiMain\addRequestedFields
addRequestedFields( $force=[])
Add requested fields to the result.
Definition: ApiMain.php:1135
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:2089
ApiMain\$mPrinter
ApiFormatBase $mPrinter
Definition: ApiMain.php:158
ApiMain\checkBotReadOnly
checkBotReadOnly()
Check whether we are readonly for bots.
Definition: ApiMain.php:1455
ApiMain\getContinuationManager
getContinuationManager()
Get the continuation manager.
Definition: ApiMain.php:356
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:1494
ApiMain\$mCacheMode
$mCacheMode
Definition: ApiMain.php:169
MWDebug\appendDebugInfoToApiResult
static appendDebugInfoToApiResult(IContextSource $context, ApiResult $result)
Append the debug info to given ApiResult.
Definition: MWDebug.php:623
wfClearOutputBuffers
wfClearOutputBuffers()
More legible than passing a 'false' parameter to wfResetOutputBuffers():
Definition: GlobalFunctions.php:1688
ApiMain\$mErrorFormatter
$mErrorFormatter
Definition: ApiMain.php:160
ApiMain\$mInternalMode
$mInternalMode
Definition: ApiMain.php:165
ApiMain\setContinuationManager
setContinuationManager(ApiContinuationManager $manager=null)
Set the continuation manager.
Definition: ApiMain.php:364
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:860
ApiMain\checkExecutePermissions
checkExecutePermissions( $module)
Check for sufficient permissions to execute.
Definition: ApiMain.php:1408
ApiBase\addDeprecation
addDeprecation( $msg, $feature, $data=[])
Add a deprecation warning for this module.
Definition: ApiBase.php:1314
$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:1467
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:186
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:1810
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:503
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:1488
ApiMain\$Formats
static $Formats
List of available formats: format name => format class.
Definition: ApiMain.php:127
ApiMain\markParamsSensitive
markParamsSensitive( $params)
Mark parameters as sensitive.
Definition: ApiMain.php:1757
ApiMain\setRequestExpectations
setRequestExpectations(ApiBase $module)
Set database connection, query, and write expectations given this module request.
Definition: ApiMain.php:1616
RequestContext\getMain
static getMain()
Get the RequestContext object associated with the main request.
Definition: RequestContext.php:451
ApiMain\logRequest
logRequest( $time, Throwable $e=null)
Log the preceding request.
Definition: ApiMain.php:1635
ApiMain\getCheck
getCheck( $name)
Get a boolean request value, and register the fact that the parameter was used, for logging.
Definition: ApiMain.php:1788
ApiMain\printResult
printResult( $httpCode=0)
Print results using the current printer.
Definition: ApiMain.php:1838
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:655
ApiMain\$mEnableWrite
$mEnableWrite
Definition: ApiMain.php:164
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:1800
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:1927
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 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:1572
ApiMain\setupModule
setupModule()
Set up the module for response.
Definition: ApiMain.php:1180
$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:295
ApiMain\$mParamsUsed
$mParamsUsed
Definition: ApiMain.php:172
ApiMain\$mModuleMgr
$mModuleMgr
Definition: ApiMain.php:160
ApiMain\getUserAgent
getUserAgent()
Fetches the user agent used for this request.
Definition: ApiMain.php:2114
ApiMain\setCacheMaxAge
setCacheMaxAge( $maxage)
Set how long the response should be cached.
Definition: ApiMain.php:405
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:55
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:437
ApiMain\getPrinter
getPrinter()
Get the result formatter object.
Definition: ApiMain.php:396
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:165
$type
$type
Definition: testCompression.php:52
ApiMain\$mModule
ApiBase $mModule
Definition: ApiMain.php:167