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