MediaWiki  master
ApiMain.php
Go to the documentation of this file.
1 <?php
28 
42 class ApiMain extends ApiBase {
46  const API_DEFAULT_FORMAT = 'jsonfm';
47 
51  const API_DEFAULT_USELANG = 'user';
52 
56  private static $Modules = [
57  'login' => ApiLogin::class,
58  'clientlogin' => ApiClientLogin::class,
59  'logout' => ApiLogout::class,
60  'createaccount' => ApiAMCreateAccount::class,
61  'linkaccount' => ApiLinkAccount::class,
62  'unlinkaccount' => ApiRemoveAuthenticationData::class,
63  'changeauthenticationdata' => ApiChangeAuthenticationData::class,
64  'removeauthenticationdata' => ApiRemoveAuthenticationData::class,
65  'resetpassword' => ApiResetPassword::class,
66  'query' => ApiQuery::class,
67  'expandtemplates' => ApiExpandTemplates::class,
68  'parse' => ApiParse::class,
69  'stashedit' => ApiStashEdit::class,
70  'opensearch' => ApiOpenSearch::class,
71  'feedcontributions' => ApiFeedContributions::class,
72  'feedrecentchanges' => ApiFeedRecentChanges::class,
73  'feedwatchlist' => ApiFeedWatchlist::class,
74  'help' => ApiHelp::class,
75  'paraminfo' => ApiParamInfo::class,
76  'rsd' => ApiRsd::class,
77  'compare' => ApiComparePages::class,
78  'tokens' => ApiTokens::class,
79  'checktoken' => ApiCheckToken::class,
80  'cspreport' => ApiCSPReport::class,
81  'validatepassword' => ApiValidatePassword::class,
82 
83  // Write modules
84  'purge' => ApiPurge::class,
85  'setnotificationtimestamp' => ApiSetNotificationTimestamp::class,
86  'rollback' => ApiRollback::class,
87  'delete' => ApiDelete::class,
88  'undelete' => ApiUndelete::class,
89  'protect' => ApiProtect::class,
90  'block' => ApiBlock::class,
91  'unblock' => ApiUnblock::class,
92  'move' => ApiMove::class,
93  'edit' => ApiEditPage::class,
94  'upload' => ApiUpload::class,
95  'filerevert' => ApiFileRevert::class,
96  'emailuser' => ApiEmailUser::class,
97  'watch' => ApiWatch::class,
98  'patrol' => ApiPatrol::class,
99  'import' => ApiImport::class,
100  'clearhasmsg' => ApiClearHasMsg::class,
101  'userrights' => ApiUserrights::class,
102  'options' => ApiOptions::class,
103  'imagerotate' => ApiImageRotate::class,
104  'revisiondelete' => ApiRevisionDelete::class,
105  'managetags' => ApiManageTags::class,
106  'tag' => ApiTag::class,
107  'mergehistory' => ApiMergeHistory::class,
108  'setpagelanguage' => ApiSetPageLanguage::class,
109  ];
110 
114  private static $Formats = [
115  'json' => ApiFormatJson::class,
116  'jsonfm' => ApiFormatJson::class,
117  'php' => ApiFormatPhp::class,
118  'phpfm' => ApiFormatPhp::class,
119  'xml' => ApiFormatXml::class,
120  'xmlfm' => ApiFormatXml::class,
121  'rawfm' => ApiFormatJson::class,
122  'none' => ApiFormatNone::class,
123  ];
124 
131  private static $mRights = [
132  'writeapi' => [
133  'msg' => 'right-writeapi',
134  'params' => []
135  ],
136  'apihighlimits' => [
137  'msg' => 'api-help-right-apihighlimits',
139  ]
140  ];
141 
145  private $mPrinter;
146 
150  private $mAction;
151  private $mEnableWrite;
154  private $mModule;
155 
156  private $mCacheMode = 'private';
158  private $mCacheControl = [];
159  private $mParamsUsed = [];
160  private $mParamsSensitive = [];
161 
163  private $lacksSameOriginSecurity = null;
164 
173  public function __construct( $context = null, $enableWrite = false ) {
174  if ( $context === null ) {
176  } elseif ( $context instanceof WebRequest ) {
177  // BC for pre-1.19
178  $request = $context;
180  }
181  // We set a derivative context so we can change stuff later
182  $this->setContext( new DerivativeContext( $context ) );
183 
184  if ( isset( $request ) ) {
185  $this->getContext()->setRequest( $request );
186  } else {
187  $request = $this->getRequest();
188  }
189 
190  $this->mInternalMode = ( $request instanceof FauxRequest );
191 
192  // Special handling for the main module: $parent === $this
193  parent::__construct( $this, $this->mInternalMode ? 'main_int' : 'main' );
194 
195  $config = $this->getConfig();
196 
197  if ( !$this->mInternalMode ) {
198  // Log if a request with a non-whitelisted Origin header is seen
199  // with session cookies.
200  $originHeader = $request->getHeader( 'Origin' );
201  if ( $originHeader === false ) {
202  $origins = [];
203  } else {
204  $originHeader = trim( $originHeader );
205  $origins = preg_split( '/\s+/', $originHeader );
206  }
207  $sessionCookies = array_intersect(
208  array_keys( $_COOKIE ),
209  SessionManager::singleton()->getVaryCookies()
210  );
211  if ( $origins && $sessionCookies && (
212  count( $origins ) !== 1 || !self::matchOrigin(
213  $origins[0],
214  $config->get( 'CrossSiteAJAXdomains' ),
215  $config->get( 'CrossSiteAJAXdomainExceptions' )
216  )
217  ) ) {
218  LoggerFactory::getInstance( 'cors' )->warning(
219  'Non-whitelisted CORS request with session cookies', [
220  'origin' => $originHeader,
221  'cookies' => $sessionCookies,
222  'ip' => $request->getIP(),
223  'userAgent' => $this->getUserAgent(),
224  'wiki' => WikiMap::getCurrentWikiDbDomain()->getId(),
225  ]
226  );
227  }
228 
229  // If we're in a mode that breaks the same-origin policy, strip
230  // user credentials for security.
231  if ( $this->lacksSameOriginSecurity() ) {
232  global $wgUser;
233  wfDebug( "API: stripping user credentials when the same-origin policy is not applied\n" );
234  $wgUser = new User();
235  $this->getContext()->setUser( $wgUser );
236  $request->response()->header( 'MediaWiki-Login-Suppressed: true' );
237  }
238  }
239 
240  $this->mResult = new ApiResult( $this->getConfig()->get( 'APIMaxResultSize' ) );
241 
242  // Setup uselang. This doesn't use $this->getParameter()
243  // because we're not ready to handle errors yet.
244  // Optimisation: Avoid slow getVal(), this isn't user-generated content.
245  $uselang = $request->getRawVal( 'uselang', self::API_DEFAULT_USELANG );
246  if ( $uselang === 'user' ) {
247  // Assume the parent context is going to return the user language
248  // for uselang=user (see T85635).
249  } else {
250  if ( $uselang === 'content' ) {
251  $uselang = MediaWikiServices::getInstance()->getContentLanguage()->getCode();
252  }
253  $code = RequestContext::sanitizeLangCode( $uselang );
254  $this->getContext()->setLanguage( $code );
255  if ( !$this->mInternalMode ) {
256  global $wgLang;
257  $wgLang = $this->getContext()->getLanguage();
258  RequestContext::getMain()->setLanguage( $wgLang );
259  }
260  }
261 
262  // Set up the error formatter. This doesn't use $this->getParameter()
263  // because we're not ready to handle errors yet.
264  // Optimisation: Avoid slow getVal(), this isn't user-generated content.
265  $errorFormat = $request->getRawVal( 'errorformat', 'bc' );
266  $errorLangCode = $request->getRawVal( 'errorlang', 'uselang' );
267  $errorsUseDB = $request->getCheck( 'errorsuselocal' );
268  if ( in_array( $errorFormat, [ 'plaintext', 'wikitext', 'html', 'raw', 'none' ], true ) ) {
269  if ( $errorLangCode === 'uselang' ) {
270  $errorLang = $this->getLanguage();
271  } elseif ( $errorLangCode === 'content' ) {
272  $errorLang = MediaWikiServices::getInstance()->getContentLanguage();
273  } else {
274  $errorLangCode = RequestContext::sanitizeLangCode( $errorLangCode );
275  $errorLang = MediaWikiServices::getInstance()->getLanguageFactory()
276  ->getLanguage( $errorLangCode );
277  }
278  $this->mErrorFormatter = new ApiErrorFormatter(
279  $this->mResult, $errorLang, $errorFormat, $errorsUseDB
280  );
281  } else {
282  $this->mErrorFormatter = new ApiErrorFormatter_BackCompat( $this->mResult );
283  }
284  $this->mResult->setErrorFormatter( $this->getErrorFormatter() );
285 
286  $this->mModuleMgr = new ApiModuleManager(
287  $this,
288  MediaWikiServices::getInstance()->getObjectFactory()
289  );
290  $this->mModuleMgr->addModules( self::$Modules, 'action' );
291  $this->mModuleMgr->addModules( $config->get( 'APIModules' ), 'action' );
292  $this->mModuleMgr->addModules( self::$Formats, 'format' );
293  $this->mModuleMgr->addModules( $config->get( 'APIFormatModules' ), 'format' );
294 
295  Hooks::run( 'ApiMain::moduleManager', [ $this->mModuleMgr ] );
296 
297  $this->mContinuationManager = null;
298  $this->mEnableWrite = $enableWrite;
299 
300  $this->mCdnMaxAge = -1; // flag for executeActionWithErrorHandling()
301  }
302 
307  public function isInternalMode() {
308  return $this->mInternalMode;
309  }
310 
316  public function getResult() {
317  return $this->mResult;
318  }
319 
324  public function lacksSameOriginSecurity() {
325  if ( $this->lacksSameOriginSecurity !== null ) {
327  }
328 
329  $request = $this->getRequest();
330 
331  // JSONP mode
332  if ( $request->getCheck( 'callback' ) ) {
333  $this->lacksSameOriginSecurity = true;
334  return true;
335  }
336 
337  // Anonymous CORS
338  if ( $request->getVal( 'origin' ) === '*' ) {
339  $this->lacksSameOriginSecurity = true;
340  return true;
341  }
342 
343  // Header to be used from XMLHTTPRequest when the request might
344  // otherwise be used for XSS.
345  if ( $request->getHeader( 'Treat-as-Untrusted' ) !== false ) {
346  $this->lacksSameOriginSecurity = true;
347  return true;
348  }
349 
350  // Allow extensions to override.
351  $this->lacksSameOriginSecurity = !Hooks::run( 'RequestHasSameOriginSecurity', [ $request ] );
353  }
354 
359  public function getErrorFormatter() {
360  return $this->mErrorFormatter;
361  }
362 
367  public function getContinuationManager() {
369  }
370 
375  public function setContinuationManager( ApiContinuationManager $manager = null ) {
376  if ( $manager !== null && $this->mContinuationManager !== null ) {
377  throw new UnexpectedValueException(
378  __METHOD__ . ': tried to set manager from ' . $manager->getSource() .
379  ' when a manager is already set from ' . $this->mContinuationManager->getSource()
380  );
381  }
382  $this->mContinuationManager = $manager;
383  }
384 
390  public function getModule() {
391  return $this->mModule;
392  }
393 
399  public function getPrinter() {
400  return $this->mPrinter;
401  }
402 
408  public function setCacheMaxAge( $maxage ) {
409  $this->setCacheControl( [
410  'max-age' => $maxage,
411  's-maxage' => $maxage
412  ] );
413  }
414 
440  public function setCacheMode( $mode ) {
441  if ( !in_array( $mode, [ 'private', 'public', 'anon-public-user-private' ] ) ) {
442  wfDebug( __METHOD__ . ": unrecognised cache mode \"$mode\"\n" );
443 
444  // Ignore for forwards-compatibility
445  return;
446  }
447 
448  if ( !$this->getPermissionManager()->isEveryoneAllowed( 'read' ) ) {
449  // Private wiki, only private headers
450  if ( $mode !== 'private' ) {
451  wfDebug( __METHOD__ . ": ignoring request for $mode cache mode, private wiki\n" );
452 
453  return;
454  }
455  }
456 
457  if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) {
458  // User language is used for i18n, so we don't want to publicly
459  // cache. Anons are ok, because if they have non-default language
460  // then there's an appropriate Vary header set by whatever set
461  // their non-default language.
462  wfDebug( __METHOD__ . ": downgrading cache mode 'public' to " .
463  "'anon-public-user-private' due to uselang=user\n" );
464  $mode = 'anon-public-user-private';
465  }
466 
467  wfDebug( __METHOD__ . ": setting cache mode $mode\n" );
468  $this->mCacheMode = $mode;
469  }
470 
481  public function setCacheControl( $directives ) {
482  $this->mCacheControl = $directives + $this->mCacheControl;
483  }
484 
492  public function createPrinterByName( $format ) {
493  $printer = $this->mModuleMgr->getModule( $format, 'format', /* $ignoreCache */ true );
494  if ( $printer === null ) {
495  $this->dieWithError(
496  [ 'apierror-unknownformat', wfEscapeWikiText( $format ) ], 'unknown_format'
497  );
498  }
499 
500  return $printer;
501  }
502 
506  public function execute() {
507  if ( $this->mInternalMode ) {
508  $this->executeAction();
509  } else {
511  }
512  }
513 
518  protected function executeActionWithErrorHandling() {
519  // Verify the CORS header before executing the action
520  if ( !$this->handleCORS() ) {
521  // handleCORS() has sent a 403, abort
522  return;
523  }
524 
525  // Exit here if the request method was OPTIONS
526  // (assume there will be a followup GET or POST)
527  if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
528  return;
529  }
530 
531  // In case an error occurs during data output,
532  // clear the output buffer and print just the error information
533  $obLevel = ob_get_level();
534  ob_start();
535 
536  $t = microtime( true );
537  $isError = false;
538  try {
539  $this->executeAction();
540  $runTime = microtime( true ) - $t;
541  $this->logRequest( $runTime );
542  MediaWikiServices::getInstance()->getStatsdDataFactory()->timing(
543  'api.' . $this->mModule->getModuleName() . '.executeTiming', 1000 * $runTime
544  );
545  } catch ( Throwable $e ) {
546  $this->handleException( $e );
547  $this->logRequest( microtime( true ) - $t, $e );
548  $isError = true;
549  }
550 
551  // Disable the client cache on the output so that BlockManager::trackBlockWithCookie is executed
552  // as part of MediaWiki::preOutputCommit().
553  if (
554  $this->mCacheMode === 'private'
555  || (
556  $this->mCacheMode === 'anon-public-user-private'
557  && SessionManager::getGlobalSession()->isPersistent()
558  )
559  ) {
560  $this->getContext()->getOutput()->enableClientCache( false );
561  $this->getContext()->getOutput()->considerCacheSettingsFinal();
562  }
563 
564  // Commit DBs and send any related cookies and headers
566 
567  // Send cache headers after any code which might generate an error, to
568  // avoid sending public cache headers for errors.
569  $this->sendCacheHeaders( $isError );
570 
571  // Executing the action might have already messed with the output
572  // buffers.
573  while ( ob_get_level() > $obLevel ) {
574  ob_end_flush();
575  }
576  }
577 
584  protected function handleException( $e ) {
585  // T65145: Rollback any open database transactions
586  if ( !$e instanceof ApiUsageException ) {
587  // ApiUsageExceptions are intentional, so don't rollback if that's the case
589  }
590 
591  // Allow extra cleanup and logging
592  Hooks::run( 'ApiMain::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( $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  $matchedOrigin = false;
698  $allowTiming = false;
699  $varyOrigin = true;
700 
701  if ( $originParam === '*' ) {
702  // Request for anonymous CORS
703  // Technically we should check for the presence of an Origin header
704  // and not process it as CORS if it's not set, but that would
705  // require us to vary on Origin for all 'origin=*' requests which
706  // we don't want to do.
707  $matchedOrigin = true;
708  $allowOrigin = '*';
709  $allowCredentials = 'false';
710  $varyOrigin = false; // No need to vary
711  } else {
712  // Non-anonymous CORS, check we allow the domain
713 
714  // Origin: header is a space-separated list of origins, check all of them
715  $originHeader = $request->getHeader( 'Origin' );
716  if ( $originHeader === false ) {
717  $origins = [];
718  } else {
719  $originHeader = trim( $originHeader );
720  $origins = preg_split( '/\s+/', $originHeader );
721  }
722 
723  if ( !in_array( $originParam, $origins ) ) {
724  // origin parameter set but incorrect
725  // Send a 403 response
726  $response->statusHeader( 403 );
727  $response->header( 'Cache-Control: no-cache' );
728  echo "'origin' parameter does not match Origin header\n";
729 
730  return false;
731  }
732 
733  $config = $this->getConfig();
734  $matchedOrigin = count( $origins ) === 1 && self::matchOrigin(
735  $originParam,
736  $config->get( 'CrossSiteAJAXdomains' ),
737  $config->get( 'CrossSiteAJAXdomainExceptions' )
738  );
739 
740  $allowOrigin = $originHeader;
741  $allowCredentials = 'true';
742  $allowTiming = $originHeader;
743  }
744 
745  if ( $matchedOrigin ) {
746  $requestedMethod = $request->getHeader( 'Access-Control-Request-Method' );
747  $preflight = $request->getMethod() === 'OPTIONS' && $requestedMethod !== false;
748  if ( $preflight ) {
749  // This is a CORS preflight request
750  if ( $requestedMethod !== 'POST' && $requestedMethod !== 'GET' ) {
751  // If method is not a case-sensitive match, do not set any additional headers and terminate.
752  $response->header( 'MediaWiki-CORS-Rejection: Unsupported method requested in preflight' );
753  return true;
754  }
755  // We allow the actual request to send the following headers
756  $requestedHeaders = $request->getHeader( 'Access-Control-Request-Headers' );
757  if ( $requestedHeaders !== false ) {
758  if ( !self::matchRequestedHeaders( $requestedHeaders ) ) {
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 
831  protected static function matchRequestedHeaders( $requestedHeaders ) {
832  if ( trim( $requestedHeaders ) === '' ) {
833  return true;
834  }
835  $requestedHeaders = explode( ',', $requestedHeaders );
836  $allowedAuthorHeaders = array_flip( [
837  /* simple headers (see spec) */
838  'accept',
839  'accept-language',
840  'content-language',
841  'content-type',
842  /* non-authorable headers in XHR, which are however requested by some UAs */
843  'accept-encoding',
844  'dnt',
845  'origin',
846  /* MediaWiki whitelist */
847  'user-agent',
848  'api-user-agent',
849  ] );
850  foreach ( $requestedHeaders as $rHeader ) {
851  $rHeader = strtolower( trim( $rHeader ) );
852  if ( !isset( $allowedAuthorHeaders[$rHeader] ) ) {
853  LoggerFactory::getInstance( 'api-warning' )->warning(
854  'CORS preflight failed on requested header: {header}', [
855  'header' => $rHeader
856  ]
857  );
858  return false;
859  }
860  }
861  return true;
862  }
863 
872  protected static function wildcardToRegex( $wildcard ) {
873  $wildcard = preg_quote( $wildcard, '/' );
874  $wildcard = str_replace(
875  [ '\*', '\?' ],
876  [ '.*?', '.' ],
877  $wildcard
878  );
879 
880  return "/^https?:\/\/$wildcard$/";
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( $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( $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  Hooks::runWithoutAbort( 'ApiMaxLagInfo', [ &$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  if ( $ifNoneMatch === [ '*' ] ) {
1338  // API responses always "exist"
1339  $etag = '*';
1340  } else {
1341  $etag = $module->getConditionalRequestData( 'etag' );
1342  }
1343  }
1344  if ( $ifNoneMatch && $etag !== null ) {
1345  $test = substr( $etag, 0, 2 ) === 'W/' ? substr( $etag, 2 ) : $etag;
1346  $match = array_map( function ( $s ) {
1347  return substr( $s, 0, 2 ) === 'W/' ? substr( $s, 2 ) : $s;
1348  }, $ifNoneMatch );
1349  $return304 = in_array( $test, $match, true );
1350  } else {
1351  $value = trim( $this->getRequest()->getHeader( 'If-Modified-Since' ) );
1352 
1353  // Some old browsers sends sizes after the date, like this:
1354  // Wed, 20 Aug 2003 06:51:19 GMT; length=5202
1355  // Ignore that.
1356  $i = strpos( $value, ';' );
1357  if ( $i !== false ) {
1358  $value = trim( substr( $value, 0, $i ) );
1359  }
1360 
1361  if ( $value !== '' ) {
1362  try {
1363  $ts = new MWTimestamp( $value );
1364  if (
1365  // RFC 7231 IMF-fixdate
1366  $ts->getTimestamp( TS_RFC2822 ) === $value ||
1367  // RFC 850
1368  $ts->format( 'l, d-M-y H:i:s' ) . ' GMT' === $value ||
1369  // asctime (with and without space-padded day)
1370  $ts->format( 'D M j H:i:s Y' ) === $value ||
1371  $ts->format( 'D M j H:i:s Y' ) === $value
1372  ) {
1373  $config = $this->getConfig();
1374  $lastMod = $module->getConditionalRequestData( 'last-modified' );
1375  if ( $lastMod !== null ) {
1376  // Mix in some MediaWiki modification times
1377  $modifiedTimes = [
1378  'page' => $lastMod,
1379  'user' => $this->getUser()->getTouched(),
1380  'epoch' => $config->get( 'CacheEpoch' ),
1381  ];
1382 
1383  if ( $config->get( 'UseCdn' ) ) {
1384  // T46570: the core page itself may not change, but resources might
1385  $modifiedTimes['sepoch'] = wfTimestamp(
1386  TS_MW, time() - $config->get( 'CdnMaxAge' )
1387  );
1388  }
1389  Hooks::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this->getOutput() ] );
1390  $lastMod = max( $modifiedTimes );
1391  $return304 = wfTimestamp( TS_MW, $lastMod ) <= $ts->getTimestamp( TS_MW );
1392  }
1393  }
1394  } catch ( TimestampException $e ) {
1395  // Invalid timestamp, ignore it
1396  }
1397  }
1398  }
1399 
1400  if ( $return304 ) {
1401  $this->getRequest()->response()->statusHeader( 304 );
1402 
1403  // Avoid outputting the compressed representation of a zero-length body
1404  Wikimedia\suppressWarnings();
1405  ini_set( 'zlib.output_compression', 0 );
1406  Wikimedia\restoreWarnings();
1408 
1409  return false;
1410  }
1411 
1412  return true;
1413  }
1414 
1419  protected function checkExecutePermissions( $module ) {
1420  $user = $this->getUser();
1421  if ( $module->isReadMode() && !$this->getPermissionManager()->isEveryoneAllowed( 'read' ) &&
1422  !$this->getPermissionManager()->userHasRight( $user, 'read' )
1423  ) {
1424  $this->dieWithError( 'apierror-readapidenied' );
1425  }
1426 
1427  if ( $module->isWriteMode() ) {
1428  if ( !$this->mEnableWrite ) {
1429  $this->dieWithError( 'apierror-noapiwrite' );
1430  } elseif ( !$this->getPermissionManager()->userHasRight( $user, 'writeapi' ) ) {
1431  $this->dieWithError( 'apierror-writeapidenied' );
1432  } elseif ( $this->getRequest()->getHeader( 'Promise-Non-Write-API-Action' ) ) {
1433  $this->dieWithError( 'apierror-promised-nonwrite-api' );
1434  }
1435 
1436  $this->checkReadOnly( $module );
1437  }
1438 
1439  // Allow extensions to stop execution for arbitrary reasons.
1440  $message = 'hookaborted';
1441  if ( !Hooks::run( 'ApiCheckCanExecute', [ $module, $user, &$message ] ) ) {
1442  $this->dieWithError( $message );
1443  }
1444  }
1445 
1450  protected function checkReadOnly( $module ) {
1451  if ( wfReadOnly() ) {
1452  $this->dieReadOnly();
1453  }
1454 
1455  if ( $module->isWriteMode()
1456  && $this->getUser()->isBot()
1457  && MediaWikiServices::getInstance()->getDBLoadBalancer()->getServerCount() > 1
1458  ) {
1459  $this->checkBotReadOnly();
1460  }
1461  }
1462 
1466  private function checkBotReadOnly() {
1467  // Figure out how many servers have passed the lag threshold
1468  $numLagged = 0;
1469  $lagLimit = $this->getConfig()->get( 'APIMaxLagThreshold' );
1470  $laggedServers = [];
1471  $loadBalancer = MediaWikiServices::getInstance()->getDBLoadBalancer();
1472  foreach ( $loadBalancer->getLagTimes() as $serverIndex => $lag ) {
1473  if ( $lag > $lagLimit ) {
1474  ++$numLagged;
1475  $laggedServers[] = $loadBalancer->getServerName( $serverIndex ) . " ({$lag}s)";
1476  }
1477  }
1478 
1479  // If a majority of replica DBs are too lagged then disallow writes
1480  $replicaCount = $loadBalancer->getServerCount() - 1;
1481  if ( $numLagged >= ceil( $replicaCount / 2 ) ) {
1482  $laggedServers = implode( ', ', $laggedServers );
1483  wfDebugLog(
1484  'api-readonly', // Deprecate this channel in favor of api-warning?
1485  "Api request failed as read only because the following DBs are lagged: $laggedServers"
1486  );
1487  LoggerFactory::getInstance( 'api-warning' )->warning(
1488  "Api request failed as read only because the following DBs are lagged: {laggeddbs}", [
1489  'laggeddbs' => $laggedServers,
1490  ]
1491  );
1492 
1493  $this->dieWithError(
1494  'readonly_lag',
1495  'readonly',
1496  [ 'readonlyreason' => "Waiting for $numLagged lagged database(s)" ]
1497  );
1498  }
1499  }
1500 
1505  protected function checkAsserts( $params ) {
1506  if ( isset( $params['assert'] ) ) {
1507  $user = $this->getUser();
1508  switch ( $params['assert'] ) {
1509  case 'user':
1510  if ( $user->isAnon() ) {
1511  $this->dieWithError( 'apierror-assertuserfailed' );
1512  }
1513  break;
1514  case 'bot':
1515  if ( !$this->getPermissionManager()->userHasRight( $user, 'bot' ) ) {
1516  $this->dieWithError( 'apierror-assertbotfailed' );
1517  }
1518  break;
1519  }
1520  }
1521  if ( isset( $params['assertuser'] ) ) {
1522  $assertUser = User::newFromName( $params['assertuser'], false );
1523  if ( !$assertUser || !$this->getUser()->equals( $assertUser ) ) {
1524  $this->dieWithError(
1525  [ 'apierror-assertnameduserfailed', wfEscapeWikiText( $params['assertuser'] ) ]
1526  );
1527  }
1528  }
1529  }
1530 
1536  protected function setupExternalResponse( $module, $params ) {
1537  $validMethods = [ 'GET', 'HEAD', 'POST', 'OPTIONS' ];
1538  $request = $this->getRequest();
1539 
1540  if ( !in_array( $request->getMethod(), $validMethods ) ) {
1541  $this->dieWithError( 'apierror-invalidmethod', null, null, 405 );
1542  }
1543 
1544  if ( !$request->wasPosted() && $module->mustBePosted() ) {
1545  // Module requires POST. GET request might still be allowed
1546  // if $wgDebugApi is true, otherwise fail.
1547  $this->dieWithErrorOrDebug( [ 'apierror-mustbeposted', $this->mAction ] );
1548  }
1549 
1550  if ( $request->wasPosted() && !$request->getHeader( 'Content-Type' ) ) {
1551  $this->addDeprecation(
1552  'apiwarn-deprecation-post-without-content-type', 'post-without-content-type'
1553  );
1554  }
1555 
1556  // See if custom printer is used
1557  $this->mPrinter = $module->getCustomPrinter();
1558  if ( is_null( $this->mPrinter ) ) {
1559  // Create an appropriate printer
1560  $this->mPrinter = $this->createPrinterByName( $params['format'] );
1561  }
1562 
1563  if ( $request->getProtocol() === 'http' && (
1564  $request->getSession()->shouldForceHTTPS() ||
1565  ( $this->getUser()->isLoggedIn() &&
1566  $this->getUser()->requiresHTTPS() )
1567  ) ) {
1568  $this->addDeprecation( 'apiwarn-deprecation-httpsexpected', 'https-expected' );
1569  }
1570  }
1571 
1575  protected function executeAction() {
1576  $params = $this->setupExecuteAction();
1577 
1578  // Check asserts early so e.g. errors in parsing a module's parameters due to being
1579  // logged out don't override the client's intended "am I logged in?" check.
1580  $this->checkAsserts( $params );
1581 
1582  $module = $this->setupModule();
1583  $this->mModule = $module;
1584 
1585  if ( !$this->mInternalMode ) {
1586  $this->setRequestExpectations( $module );
1587  }
1588 
1589  $this->checkExecutePermissions( $module );
1590 
1591  if ( !$this->checkMaxLag( $module, $params ) ) {
1592  return;
1593  }
1594 
1595  if ( !$this->checkConditionalRequestHeaders( $module ) ) {
1596  return;
1597  }
1598 
1599  if ( !$this->mInternalMode ) {
1600  $this->setupExternalResponse( $module, $params );
1601  }
1602 
1603  $module->execute();
1604  Hooks::run( 'APIAfterExecute', [ &$module ] );
1605 
1606  $this->reportUnusedParams();
1607 
1608  if ( !$this->mInternalMode ) {
1610 
1611  $this->printResult();
1612  }
1613  }
1614 
1619  protected function setRequestExpectations( ApiBase $module ) {
1620  $limits = $this->getConfig()->get( 'TrxProfilerLimits' );
1621  $trxProfiler = Profiler::instance()->getTransactionProfiler();
1622  $trxProfiler->setLogger( LoggerFactory::getInstance( 'DBPerformance' ) );
1623  if ( $this->getRequest()->hasSafeMethod() ) {
1624  $trxProfiler->setExpectations( $limits['GET'], __METHOD__ );
1625  } elseif ( $this->getRequest()->wasPosted() && !$module->isWriteMode() ) {
1626  $trxProfiler->setExpectations( $limits['POST-nonwrite'], __METHOD__ );
1627  $this->getRequest()->markAsSafeRequest();
1628  } else {
1629  $trxProfiler->setExpectations( $limits['POST'], __METHOD__ );
1630  }
1631  }
1632 
1638  protected function logRequest( $time, $e = null ) {
1639  $request = $this->getRequest();
1640 
1641  $logCtx = [
1642  // https://gerrit.wikimedia.org/r/plugins/gitiles/mediawiki/event-schemas/+/master/jsonschema/mediawiki/api/request
1643  '$schema' => '/mediawiki/api/request/0.0.1',
1644  'meta' => [
1645  'request_id' => WebRequest::getRequestId(),
1646  'id' => UIDGenerator::newUUIDv4(),
1647  'dt' => wfTimestamp( TS_ISO_8601 ),
1648  'domain' => $this->getConfig()->get( 'ServerName' ),
1649  // If using the EventBus extension (as intended) with this log channel,
1650  // this stream name will map to a Kafka topic.
1651  'stream' => 'mediawiki.api-request'
1652  ],
1653  'http' => [
1654  'method' => $request->getMethod(),
1655  'client_ip' => $request->getIP()
1656  ],
1657  'database' => WikiMap::getCurrentWikiDbDomain()->getId(),
1658  'backend_time_ms' => (int)round( $time * 1000 ),
1659  ];
1660 
1661  // If set, these headers will be logged in http.request_headers.
1662  $httpRequestHeadersToLog = [ 'accept-language', 'referer', 'user-agent' ];
1663  foreach ( $httpRequestHeadersToLog as $header ) {
1664  if ( $request->getHeader( $header ) ) {
1665  // Set the header in http.request_headers
1666  $logCtx['http']['request_headers'][$header] = $request->getHeader( $header );
1667  }
1668  }
1669 
1670  if ( $e ) {
1671  $logCtx['api_error_codes'] = [];
1672  foreach ( $this->errorMessagesFromException( $e ) as $msg ) {
1673  $logCtx['api_error_codes'][] = $msg->getApiCode();
1674  }
1675  }
1676 
1677  // Construct space separated message for 'api' log channel
1678  $msg = "API {$request->getMethod()} " .
1679  wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
1680  " {$logCtx['http']['client_ip']} " .
1681  "T={$logCtx['backend_time_ms']}ms";
1682 
1683  $sensitive = array_flip( $this->getSensitiveParams() );
1684  foreach ( $this->getParamsUsed() as $name ) {
1685  $value = $request->getVal( $name );
1686  if ( $value === null ) {
1687  continue;
1688  }
1689 
1690  if ( isset( $sensitive[$name] ) ) {
1691  $value = '[redacted]';
1692  $encValue = '[redacted]';
1693  } elseif ( strlen( $value ) > 256 ) {
1694  $value = substr( $value, 0, 256 );
1695  $encValue = $this->encodeRequestLogValue( $value ) . '[...]';
1696  } else {
1697  $encValue = $this->encodeRequestLogValue( $value );
1698  }
1699 
1700  $logCtx['params'][$name] = $value;
1701  $msg .= " {$name}={$encValue}";
1702  }
1703 
1704  // Log an unstructured message to the api channel.
1705  wfDebugLog( 'api', $msg, 'private' );
1706 
1707  // The api-request channel a structured data log channel.
1708  wfDebugLog( 'api-request', '', 'private', $logCtx );
1709  }
1710 
1716  protected function encodeRequestLogValue( $s ) {
1717  static $table = [];
1718  if ( !$table ) {
1719  $chars = ';@$!*(),/:';
1720  $numChars = strlen( $chars );
1721  for ( $i = 0; $i < $numChars; $i++ ) {
1722  $table[rawurlencode( $chars[$i] )] = $chars[$i];
1723  }
1724  }
1725 
1726  return strtr( rawurlencode( $s ), $table );
1727  }
1728 
1733  protected function getParamsUsed() {
1734  return array_keys( $this->mParamsUsed );
1735  }
1736 
1741  public function markParamsUsed( $params ) {
1742  $this->mParamsUsed += array_fill_keys( (array)$params, true );
1743  }
1744 
1750  protected function getSensitiveParams() {
1751  return array_keys( $this->mParamsSensitive );
1752  }
1753 
1759  public function markParamsSensitive( $params ) {
1760  $this->mParamsSensitive += array_fill_keys( (array)$params, true );
1761  }
1762 
1769  public function getVal( $name, $default = null ) {
1770  $this->mParamsUsed[$name] = true;
1771 
1772  $ret = $this->getRequest()->getVal( $name );
1773  if ( $ret === null ) {
1774  if ( $this->getRequest()->getArray( $name ) !== null ) {
1775  // See T12262 for why we don't just implode( '|', ... ) the
1776  // array.
1777  $this->addWarning( [ 'apiwarn-unsupportedarray', $name ] );
1778  }
1779  $ret = $default;
1780  }
1781  return $ret;
1782  }
1783 
1790  public function getCheck( $name ) {
1791  return $this->getVal( $name, null ) !== null;
1792  }
1793 
1801  public function getUpload( $name ) {
1802  $this->mParamsUsed[$name] = true;
1803 
1804  return $this->getRequest()->getUpload( $name );
1805  }
1806 
1811  protected function reportUnusedParams() {
1812  $paramsUsed = $this->getParamsUsed();
1813  $allParams = $this->getRequest()->getValueNames();
1814 
1815  if ( !$this->mInternalMode ) {
1816  // Printer has not yet executed; don't warn that its parameters are unused
1817  $printerParams = $this->mPrinter->encodeParamName(
1818  array_keys( $this->mPrinter->getFinalParams() ?: [] )
1819  );
1820  $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1821  } else {
1822  $unusedParams = array_diff( $allParams, $paramsUsed );
1823  }
1824 
1825  if ( count( $unusedParams ) ) {
1826  $this->addWarning( [
1827  'apierror-unrecognizedparams',
1828  Message::listParam( array_map( 'wfEscapeWikiText', $unusedParams ), 'comma' ),
1829  count( $unusedParams )
1830  ] );
1831  }
1832  }
1833 
1839  protected function printResult( $httpCode = 0 ) {
1840  if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
1841  $this->addWarning( 'apiwarn-wgdebugapi' );
1842  }
1843 
1844  $printer = $this->mPrinter;
1845  $printer->initPrinter( false );
1846  if ( $httpCode ) {
1847  $printer->setHttpStatus( $httpCode );
1848  }
1849  $printer->execute();
1850  $printer->closePrinter();
1851  }
1852 
1856  public function isReadMode() {
1857  return false;
1858  }
1859 
1865  public function getAllowedParams() {
1866  return [
1867  'action' => [
1868  ApiBase::PARAM_DFLT => 'help',
1869  ApiBase::PARAM_TYPE => 'submodule',
1870  ],
1871  'format' => [
1872  ApiBase::PARAM_DFLT => self::API_DEFAULT_FORMAT,
1873  ApiBase::PARAM_TYPE => 'submodule',
1874  ],
1875  'maxlag' => [
1876  ApiBase::PARAM_TYPE => 'integer'
1877  ],
1878  'smaxage' => [
1879  ApiBase::PARAM_TYPE => 'integer',
1880  ApiBase::PARAM_DFLT => 0
1881  ],
1882  'maxage' => [
1883  ApiBase::PARAM_TYPE => 'integer',
1884  ApiBase::PARAM_DFLT => 0
1885  ],
1886  'assert' => [
1887  ApiBase::PARAM_TYPE => [ 'user', 'bot' ]
1888  ],
1889  'assertuser' => [
1890  ApiBase::PARAM_TYPE => 'user',
1891  ],
1892  'requestid' => null,
1893  'servedby' => false,
1894  'curtimestamp' => false,
1895  'responselanginfo' => false,
1896  'origin' => null,
1897  'uselang' => [
1898  ApiBase::PARAM_DFLT => self::API_DEFAULT_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' )->parseAsBlock();
1994  if ( !isset( $tocData['main/datatypes'] ) ) {
1995  $tocnumber[$level]++;
1996  $tocData['main/datatypes'] = [
1997  'toclevel' => count( $tocnumber ),
1998  'level' => $level,
1999  'anchor' => 'main/datatypes',
2000  'line' => $header,
2001  'number' => implode( '.', $tocnumber ),
2002  'index' => false,
2003  ];
2004  }
2005 
2006  $header = $this->msg( 'api-help-templatedparams-header' )->parse();
2007 
2008  $id = Sanitizer::escapeIdForAttribute( 'main/templatedparams', Sanitizer::ID_PRIMARY );
2009  $idFallback = Sanitizer::escapeIdForAttribute( 'main/templatedparams', Sanitizer::ID_FALLBACK );
2010  $headline = Linker::makeHeadline( min( 6, $level ),
2011  ' class="apihelp-header">',
2012  $id,
2013  $header,
2014  '',
2015  $idFallback
2016  );
2017  // Ensure we have a sane anchor
2018  if ( $id !== 'main/templatedparams' && $idFallback !== 'main/templatedparams' ) {
2019  $headline = '<div id="main/templatedparams"></div>' . $headline;
2020  }
2021  $help['templatedparams'] .= $headline;
2022  $help['templatedparams'] .= $this->msg( 'api-help-templatedparams' )->parseAsBlock();
2023  if ( !isset( $tocData['main/templatedparams'] ) ) {
2024  $tocnumber[$level]++;
2025  $tocData['main/templatedparams'] = [
2026  'toclevel' => count( $tocnumber ),
2027  'level' => $level,
2028  'anchor' => 'main/templatedparams',
2029  'line' => $header,
2030  'number' => implode( '.', $tocnumber ),
2031  'index' => false,
2032  ];
2033  }
2034 
2035  $header = $this->msg( 'api-credits-header' )->parse();
2036  $id = Sanitizer::escapeIdForAttribute( 'main/credits', Sanitizer::ID_PRIMARY );
2037  $idFallback = Sanitizer::escapeIdForAttribute( 'main/credits', Sanitizer::ID_FALLBACK );
2038  $headline = Linker::makeHeadline( min( 6, $level ),
2039  ' class="apihelp-header">',
2040  $id,
2041  $header,
2042  '',
2043  $idFallback
2044  );
2045  // Ensure we have a sane anchor
2046  if ( $id !== 'main/credits' && $idFallback !== 'main/credits' ) {
2047  $headline = '<div id="main/credits"></div>' . $headline;
2048  }
2049  $help['credits'] .= $headline;
2050  $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
2051  if ( !isset( $tocData['main/credits'] ) ) {
2052  $tocnumber[$level]++;
2053  $tocData['main/credits'] = [
2054  'toclevel' => count( $tocnumber ),
2055  'level' => $level,
2056  'anchor' => 'main/credits',
2057  'line' => $header,
2058  'number' => implode( '.', $tocnumber ),
2059  'index' => false,
2060  ];
2061  }
2062  }
2063  }
2064 
2065  private $mCanApiHighLimits = null;
2066 
2071  public function canApiHighLimits() {
2072  if ( !isset( $this->mCanApiHighLimits ) ) {
2073  $this->mCanApiHighLimits = $this->getPermissionManager()
2074  ->userHasRight( $this->getUser(), 'apihighlimits' );
2075  }
2076 
2077  return $this->mCanApiHighLimits;
2078  }
2079 
2084  public function getModuleManager() {
2085  return $this->mModuleMgr;
2086  }
2087 
2096  public function getUserAgent() {
2097  return trim(
2098  $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
2099  $this->getRequest()->getHeader( 'User-agent' )
2100  );
2101  }
2102 }
2103 
setContext(IContextSource $context)
getAllowedParams()
See ApiBase for description.
Definition: ApiMain.php:1865
getModuleManager()
Overrides to return this instance&#39;s module manager.
Definition: ApiMain.php:2084
const PARAM_TYPE
(string|string[]) Either an array of allowed value strings, or a string type as described below...
Definition: ApiBase.php:94
static matchRequestedHeaders( $requestedHeaders)
Attempt to validate the value of Access-Control-Request-Headers against a list of headers that we all...
Definition: ApiMain.php:831
$response
getUserAgent()
Fetches the user agent used for this request.
Definition: ApiMain.php:2096
const LIMIT_BIG2
Fast query, apihighlimits limit.
Definition: ApiBase.php:261
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking, formatting, etc.
setCacheMaxAge( $maxage)
Set how long the response should be cached.
Definition: ApiMain.php:408
getContinuationManager()
Get the continuation manager.
Definition: ApiMain.php:367
static $Modules
List of available modules: action name => module class.
Definition: ApiMain.php:56
$mEnableWrite
Definition: ApiMain.php:151
static element( $element, $attribs=[], $contents='')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
Definition: Html.php:231
Formats errors and warnings for the API, and add them to the associated ApiResult.
addRequestedFields( $force=[])
Add requested fields to the result.
Definition: ApiMain.php:1147
static getRequestId()
Get the unique request ID.
Definition: WebRequest.php:309
executeActionWithErrorHandling()
Execute an action, and in case of an error, erase whatever partial results have been accumulated...
Definition: ApiMain.php:518
modifyHelp(array &$help, array $options, array &$tocData)
-param array{nolead?:bool,headerlevel?:int,tocnumber?:int[]} $options
Definition: ApiMain.php:1927
const ID_PRIMARY
Tells escapeUrlForHtml() to encode the ID using the wiki&#39;s primary encoding.
Definition: Sanitizer.php:66
This class holds a list of modules and handles instantiation.
bool null $lacksSameOriginSecurity
Cached return value from self::lacksSameOriginSecurity()
Definition: ApiMain.php:163
$mCdnMaxAge
Definition: ApiMain.php:152
addDeprecation( $msg, $feature, $data=[])
Add a deprecation warning for this module.
Definition: ApiBase.php:1939
initPrinter( $unused=false)
Initialize the printer function and prepare the output headers.
checkExecutePermissions( $module)
Check for sufficient permissions to execute.
Definition: ApiMain.php:1419
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
Definition: ApiBase.php:55
static instance()
Singleton.
Definition: Profiler.php:63
wfExpandUrl( $url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.
getMaxLag()
Definition: ApiMain.php:1239
wfHostname()
Fetch server name for use in error reporting etc.
Exception used to abort API execution with an error.
static openElement( $element, $attribs=[])
Identical to rawElement(), but has no third parameter and omits the end tag (and the self-closing &#39;/&#39;...
Definition: Html.php:251
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
Definition: Html.php:209
An IContextSource implementation which will inherit context from another source but allow individual ...
static static static ApiFormatBase $mPrinter
Definition: ApiMain.php:134
checkReadOnly( $module)
Check if the DB is read-only for this user.
Definition: ApiMain.php:1450
static isValidApiCode( $code)
Test whether a code is a valid API error code.
getModulePath()
Fetch the responsible module name.
This manages continuation state.
isInternalMode()
Return true if the API was started by other PHP code using FauxRequest.
Definition: ApiMain.php:307
setCacheControl( $directives)
Set directives (key/value pairs) for the Cache-Control header.
Definition: ApiMain.php:481
dieWithError( $msg, $code=null, $data=null, $httpCode=null)
Abort execution with an error.
Definition: ApiBase.php:2006
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user...
Definition: ApiBase.php:761
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:649
const GETHEADER_LIST
Flag to make WebRequest::getHeader return an array of values.
Definition: WebRequest.php:71
canApiHighLimits()
Check whether the current user is allowed to use high limits.
Definition: ApiMain.php:2071
errorMessagesFromException( $e, $type='error')
Create an error message for the given exception.
Definition: ApiMain.php:1025
static rollbackMasterChangesAndLog( $e)
Roll back any open database transactions and log the stack trace of the exception.
const API_DEFAULT_FORMAT
When no format parameter is given, this format will be used.
Definition: ApiMain.php:46
IContextSource $context
ApiBase $mModule
Definition: ApiMain.php:154
static static static $mRights
List of user roles that are specifically relevant to the API.
Definition: ApiMain.php:131
getParameter( $paramName, $parseLimit=true)
Get a value for the given parameter.
Definition: ApiBase.php:876
setupModule()
Set up the module for response.
Definition: ApiMain.php:1192
__construct( $context=null, $enableWrite=false)
Constructs an instance of ApiMain that utilizes the module and format specified by $request...
Definition: ApiMain.php:173
const ID_FALLBACK
Tells escapeUrlForHtml() to encode the ID using the fallback encoding, or return false if no fallback...
Definition: Sanitizer.php:74
The User object encapsulates all of the user-specific settings (user_id, name, rights, email address, options, last login time).
Definition: User.php:51
wfScript( $script='index')
Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScri...
const API_DEFAULT_USELANG
When no uselang parameter is given, this language will be used.
Definition: ApiMain.php:51
checkMaxLag( $module, $params)
Check the max lag if necessary.
Definition: ApiMain.php:1273
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
createPrinterByName( $format)
Create an instance of an output formatter by its name.
Definition: ApiMain.php:492
setRequestExpectations(ApiBase $module)
Set database connection, query, and write expectations given this module request. ...
Definition: ApiMain.php:1619
setupExternalResponse( $module, $params)
Check POST for external response and setup result printer.
Definition: ApiMain.php:1536
wfReadOnly()
Check whether the wiki is in read-only mode.
wfUrlencode( $s)
We want some things to be included as literal characters in our title URLs for prettiness, which urlencode encodes by default.
$wgLang
Definition: Setup.php:858
printResult( $httpCode=0)
Print results using the current printer.
Definition: ApiMain.php:1839
static getMain()
Get the RequestContext object associated with the main request.
static getRedactedTraceAsString( $e)
Generate a string representation of an exception&#39;s stack trace.
setCacheMode( $mode)
Set the type of caching headers which will be sent.
Definition: ApiMain.php:440
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:1257
static newUUIDv4( $flags=0)
Return an RFC4122 compliant v4 UUID.
checkAsserts( $params)
Check asserts of the user&#39;s rights.
Definition: ApiMain.php:1505
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
handleException( $e)
Handle an exception as an API response.
Definition: ApiMain.php:584
const LIMIT_SML2
Slow query, apihighlimits limit.
Definition: ApiBase.php:265
getContext()
Get the base IContextSource object.
This is the main API class, used for both external and internal processing.
Definition: ApiMain.php:42
executeAction()
Execute the actual module, without any error handling.
Definition: ApiMain.php:1575
isReadMode()
Definition: ApiMain.php:1856
static closeElement( $element)
Returns "</$element>".
Definition: Html.php:315
handleCORS()
Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
Definition: ApiMain.php:687
setupExecuteAction()
Set up for the execution.
Definition: ApiMain.php:1177
getSensitiveParams()
Get the request parameters that should be considered sensitive.
Definition: ApiMain.php:1750
$mCacheMode
Definition: ApiMain.php:156
Format errors and warnings in the old style, for backwards compatibility.
$mErrorFormatter
Definition: ApiMain.php:147
lacksSameOriginSecurity()
Get the security flag for the current request.
Definition: ApiMain.php:324
static runWithoutAbort( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:231
static wildcardToRegex( $wildcard)
Helper function to convert wildcard string into a regex &#39;*&#39; => &#39;.
Definition: ApiMain.php:872
const NO_SIZE_CHECK
For addValue() and similar functions, do not check size while adding a value Don&#39;t use this unless yo...
Definition: ApiResult.php:58
This class represents the result of the API operations.
Definition: ApiResult.php:35
markParamsSensitive( $params)
Mark parameters as sensitive.
Definition: ApiMain.php:1759
$help
Definition: mcc.php:32
$mParamsSensitive
Definition: ApiMain.php:160
$header
$mCanApiHighLimits
Definition: ApiMain.php:2065
static static $Formats
List of available formats: format name => format class.
Definition: ApiMain.php:114
getParamsUsed()
Get the request parameters used in the course of the preceding execute() request. ...
Definition: ApiMain.php:1733
getExamplesMessages()
Definition: ApiMain.php:1914
getErrorFormatter()
Get the ApiErrorFormatter object associated with current request.
Definition: ApiMain.php:359
getCheck( $name)
Get a boolean request value, and register the fact that the parameter was used, for logging...
Definition: ApiMain.php:1790
logRequest( $time, $e=null)
Log the preceding request.
Definition: ApiMain.php:1638
static getCurrentWikiDbDomain()
Definition: WikiMap.php:293
sendCacheHeaders( $isError)
Send caching headers.
Definition: ApiMain.php:888
checkBotReadOnly()
Check whether we are readonly for bots.
Definition: ApiMain.php:1466
getModule()
Get the API module object.
Definition: ApiMain.php:390
checkConditionalRequestHeaders( $module)
Check selected RFC 7232 precondition headers.
Definition: ApiMain.php:1319
static makeHeadline( $level, $attribs, $anchor, $html, $link, $fallbackAnchor=false)
Create a headline for content.
Definition: Linker.php:1750
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:2183
static appendDebugInfoToApiResult(IContextSource $context, ApiResult $result)
Append the debug info to given ApiResult.
Definition: MWDebug.php:504
dieReadOnly()
Helper function for readonly errors.
Definition: ApiBase.php:2106
static newFromSpecifier( $value)
Transform a MessageSpecifier or a primitive value used interchangeably with specifiers (a message key...
Definition: Message.php:430
msg( $key,... $params)
Get a Message object with context set Parameters are the same as wfMessage()
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not...
$mParamsUsed
Definition: ApiMain.php:159
addWarning( $msg, $code=null, $data=null)
Add a warning for this module.
Definition: ApiBase.php:1925
static sanitizeLangCode( $code)
Accepts a language code and ensures it&#39;s sane.
static handleApiBeforeMainException( $e)
Handle an exception from the ApiBeforeMain hook.
Definition: ApiMain.php:655
reportUnusedParams()
Report unused parameters, so the client gets a hint in case it gave us parameters we don&#39;t know...
Definition: ApiMain.php:1811
wfClearOutputBuffers()
More legible than passing a &#39;false&#39; parameter to wfResetOutputBuffers():
getPermissionManager()
Obtain a PermissionManager instance that subclasses may use in their authorization checks...
Definition: ApiBase.php:710
array $mCacheControl
Definition: ApiMain.php:158
This abstract class implements many basic API functions, and is the base of all API classes...
Definition: ApiBase.php:42
static singleton( $domain=false)
substituteResultWithError( $e)
Replace the result data with the information about an exception.
Definition: ApiMain.php:1063
getPrinter()
Get the result formatter object.
Definition: ApiMain.php:399
getStatusValue()
Fetch the error status.
static newFromName( $name, $validate='valid')
Static factory method for creation from username.
Definition: User.php:536
markParamsUsed( $params)
Mark parameters as used.
Definition: ApiMain.php:1741
getUpload( $name)
Get a request upload, and register the fact that it was used, for logging.
Definition: ApiMain.php:1801
setContinuationManager(ApiContinuationManager $manager=null)
Set the continuation manager.
Definition: ApiMain.php:375
$mInternalMode
Definition: ApiMain.php:152
return true
Definition: router.php:92
Interface for MediaWiki-localized exceptions.
$mModuleMgr
Definition: ApiMain.php:147
encodeRequestLogValue( $s)
Encode a value in a format suitable for a space-separated log line.
Definition: ApiMain.php:1716
execute()
Execute api request.
Definition: ApiMain.php:506
static listParam(array $list, $type='text')
Definition: Message.php:1119
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:200
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
static create( $msg, $code=null, array $data=null)
Create an IApiMessage for the message.
Definition: ApiMessage.php:40
getResult()
Get the ApiResult object associated with current request.
Definition: ApiMain.php:316
createErrorPrinter()
Create the printer for error output.
Definition: ApiMain.php:994
isWriteMode()
Indicates whether this module requires write mode.
Definition: ApiBase.php:427
ApiContinuationManager null $mContinuationManager
Definition: ApiMain.php:149
getVal( $name, $default=null)
Get a request value, and register the fact that it was used, for logging.
Definition: ApiMain.php:1769