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 = Language::factory( $errorLangCode );
276  }
277  $this->mErrorFormatter = new ApiErrorFormatter(
278  $this->mResult, $errorLang, $errorFormat, $errorsUseDB
279  );
280  } else {
281  $this->mErrorFormatter = new ApiErrorFormatter_BackCompat( $this->mResult );
282  }
283  $this->mResult->setErrorFormatter( $this->getErrorFormatter() );
284 
285  $this->mModuleMgr = new ApiModuleManager(
286  $this,
287  MediaWikiServices::getInstance()->getObjectFactory()
288  );
289  $this->mModuleMgr->addModules( self::$Modules, 'action' );
290  $this->mModuleMgr->addModules( $config->get( 'APIModules' ), 'action' );
291  $this->mModuleMgr->addModules( self::$Formats, 'format' );
292  $this->mModuleMgr->addModules( $config->get( 'APIFormatModules' ), 'format' );
293 
294  Hooks::run( 'ApiMain::moduleManager', [ $this->mModuleMgr ] );
295 
296  $this->mContinuationManager = null;
297  $this->mEnableWrite = $enableWrite;
298 
299  $this->mCdnMaxAge = -1; // flag for executeActionWithErrorHandling()
300  }
301 
306  public function isInternalMode() {
307  return $this->mInternalMode;
308  }
309 
315  public function getResult() {
316  return $this->mResult;
317  }
318 
323  public function lacksSameOriginSecurity() {
324  if ( $this->lacksSameOriginSecurity !== null ) {
326  }
327 
328  $request = $this->getRequest();
329 
330  // JSONP mode
331  if ( $request->getCheck( 'callback' ) ) {
332  $this->lacksSameOriginSecurity = true;
333  return true;
334  }
335 
336  // Anonymous CORS
337  if ( $request->getVal( 'origin' ) === '*' ) {
338  $this->lacksSameOriginSecurity = true;
339  return true;
340  }
341 
342  // Header to be used from XMLHTTPRequest when the request might
343  // otherwise be used for XSS.
344  if ( $request->getHeader( 'Treat-as-Untrusted' ) !== false ) {
345  $this->lacksSameOriginSecurity = true;
346  return true;
347  }
348 
349  // Allow extensions to override.
350  $this->lacksSameOriginSecurity = !Hooks::run( 'RequestHasSameOriginSecurity', [ $request ] );
352  }
353 
358  public function getErrorFormatter() {
359  return $this->mErrorFormatter;
360  }
361 
366  public function getContinuationManager() {
368  }
369 
374  public function setContinuationManager( ApiContinuationManager $manager = null ) {
375  if ( $manager !== null && $this->mContinuationManager !== null ) {
376  throw new UnexpectedValueException(
377  __METHOD__ . ': tried to set manager from ' . $manager->getSource() .
378  ' when a manager is already set from ' . $this->mContinuationManager->getSource()
379  );
380  }
381  $this->mContinuationManager = $manager;
382  }
383 
389  public function getModule() {
390  return $this->mModule;
391  }
392 
398  public function getPrinter() {
399  return $this->mPrinter;
400  }
401 
407  public function setCacheMaxAge( $maxage ) {
408  $this->setCacheControl( [
409  'max-age' => $maxage,
410  's-maxage' => $maxage
411  ] );
412  }
413 
439  public function setCacheMode( $mode ) {
440  if ( !in_array( $mode, [ 'private', 'public', 'anon-public-user-private' ] ) ) {
441  wfDebug( __METHOD__ . ": unrecognised cache mode \"$mode\"\n" );
442 
443  // Ignore for forwards-compatibility
444  return;
445  }
446 
447  if ( !User::isEveryoneAllowed( 'read' ) ) {
448  // Private wiki, only private headers
449  if ( $mode !== 'private' ) {
450  wfDebug( __METHOD__ . ": ignoring request for $mode cache mode, private wiki\n" );
451 
452  return;
453  }
454  }
455 
456  if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) {
457  // User language is used for i18n, so we don't want to publicly
458  // cache. Anons are ok, because if they have non-default language
459  // then there's an appropriate Vary header set by whatever set
460  // their non-default language.
461  wfDebug( __METHOD__ . ": downgrading cache mode 'public' to " .
462  "'anon-public-user-private' due to uselang=user\n" );
463  $mode = 'anon-public-user-private';
464  }
465 
466  wfDebug( __METHOD__ . ": setting cache mode $mode\n" );
467  $this->mCacheMode = $mode;
468  }
469 
480  public function setCacheControl( $directives ) {
481  $this->mCacheControl = $directives + $this->mCacheControl;
482  }
483 
491  public function createPrinterByName( $format ) {
492  $printer = $this->mModuleMgr->getModule( $format, 'format', /* $ignoreCache */ true );
493  if ( $printer === null ) {
494  $this->dieWithError(
495  [ 'apierror-unknownformat', wfEscapeWikiText( $format ) ], 'unknown_format'
496  );
497  }
498 
499  return $printer;
500  }
501 
505  public function execute() {
506  if ( $this->mInternalMode ) {
507  $this->executeAction();
508  } else {
510  }
511  }
512 
517  protected function executeActionWithErrorHandling() {
518  // Verify the CORS header before executing the action
519  if ( !$this->handleCORS() ) {
520  // handleCORS() has sent a 403, abort
521  return;
522  }
523 
524  // Exit here if the request method was OPTIONS
525  // (assume there will be a followup GET or POST)
526  if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
527  return;
528  }
529 
530  // In case an error occurs during data output,
531  // clear the output buffer and print just the error information
532  $obLevel = ob_get_level();
533  ob_start();
534 
535  $t = microtime( true );
536  $isError = false;
537  try {
538  $this->executeAction();
539  $runTime = microtime( true ) - $t;
540  $this->logRequest( $runTime );
541  MediaWikiServices::getInstance()->getStatsdDataFactory()->timing(
542  'api.' . $this->mModule->getModuleName() . '.executeTiming', 1000 * $runTime
543  );
544  } catch ( Throwable $e ) {
545  $this->handleException( $e );
546  $this->logRequest( microtime( true ) - $t, $e );
547  $isError = true;
548  }
549 
550  // Disable the client cache on the output so that BlockManager::trackBlockWithCookie is executed
551  // as part of MediaWiki::preOutputCommit().
552  if (
553  $this->mCacheMode === 'private'
554  || (
555  $this->mCacheMode === 'anon-public-user-private'
556  && SessionManager::getGlobalSession()->isPersistent()
557  )
558  ) {
559  $this->getContext()->getOutput()->enableClientCache( false );
560  $this->getContext()->getOutput()->considerCacheSettingsFinal();
561  }
562 
563  // Commit DBs and send any related cookies and headers
565 
566  // Send cache headers after any code which might generate an error, to
567  // avoid sending public cache headers for errors.
568  $this->sendCacheHeaders( $isError );
569 
570  // Executing the action might have already messed with the output
571  // buffers.
572  while ( ob_get_level() > $obLevel ) {
573  ob_end_flush();
574  }
575  }
576 
583  protected function handleException( $e ) {
584  // T65145: Rollback any open database transactions
585  if ( !$e instanceof ApiUsageException ) {
586  // ApiUsageExceptions are intentional, so don't rollback if that's the case
588  }
589 
590  // Allow extra cleanup and logging
591  Hooks::run( 'ApiMain::onException', [ $this, $e ] );
592 
593  // Handle any kind of exception by outputting properly formatted error message.
594  // If this fails, an unhandled exception should be thrown so that global error
595  // handler will process and log it.
596 
597  $errCodes = $this->substituteResultWithError( $e );
598 
599  // Error results should not be cached
600  $this->setCacheMode( 'private' );
601 
602  $response = $this->getRequest()->response();
603  $headerStr = 'MediaWiki-API-Error: ' . implode( ', ', $errCodes );
604  $response->header( $headerStr );
605 
606  // Reset and print just the error message
607  ob_clean();
608 
609  // Printer may not be initialized if the extractRequestParams() fails for the main module
610  $this->createErrorPrinter();
611 
612  // Get desired HTTP code from an ApiUsageException. Don't use codes from other
613  // exception types, as they are unlikely to be intended as an HTTP code.
614  $httpCode = $e instanceof ApiUsageException ? $e->getCode() : 0;
615 
616  $failed = false;
617  try {
618  $this->printResult( $httpCode );
619  } catch ( ApiUsageException $ex ) {
620  // The error printer itself is failing. Try suppressing its request
621  // parameters and redo.
622  $failed = true;
623  $this->addWarning( 'apiwarn-errorprinterfailed' );
624  foreach ( $ex->getStatusValue()->getErrors() as $error ) {
625  try {
626  $this->mPrinter->addWarning( $error );
627  } catch ( Throwable $ex2 ) {
628  // WTF?
629  $this->addWarning( $error );
630  }
631  }
632  }
633  if ( $failed ) {
634  $this->mPrinter = null;
635  $this->createErrorPrinter();
636  $this->mPrinter->forceDefaultParams();
637  if ( $httpCode ) {
638  $response->statusHeader( 200 ); // Reset in case the fallback doesn't want a non-200
639  }
640  $this->printResult( $httpCode );
641  }
642  }
643 
654  public static function handleApiBeforeMainException( $e ) {
655  ob_start();
656 
657  try {
658  $main = new self( RequestContext::getMain(), false );
659  $main->handleException( $e );
660  $main->logRequest( 0, $e );
661  } catch ( Throwable $e2 ) {
662  // Nope, even that didn't work. Punt.
663  throw $e;
664  }
665 
666  // Reset cache headers
667  $main->sendCacheHeaders( true );
668 
669  ob_end_flush();
670  }
671 
686  protected function handleCORS() {
687  $originParam = $this->getParameter( 'origin' ); // defaults to null
688  if ( $originParam === null ) {
689  // No origin parameter, nothing to do
690  return true;
691  }
692 
693  $request = $this->getRequest();
694  $response = $request->response();
695 
696  $matchedOrigin = false;
697  $allowTiming = false;
698  $varyOrigin = true;
699 
700  if ( $originParam === '*' ) {
701  // Request for anonymous CORS
702  // Technically we should check for the presence of an Origin header
703  // and not process it as CORS if it's not set, but that would
704  // require us to vary on Origin for all 'origin=*' requests which
705  // we don't want to do.
706  $matchedOrigin = true;
707  $allowOrigin = '*';
708  $allowCredentials = 'false';
709  $varyOrigin = false; // No need to vary
710  } else {
711  // Non-anonymous CORS, check we allow the domain
712 
713  // Origin: header is a space-separated list of origins, check all of them
714  $originHeader = $request->getHeader( 'Origin' );
715  if ( $originHeader === false ) {
716  $origins = [];
717  } else {
718  $originHeader = trim( $originHeader );
719  $origins = preg_split( '/\s+/', $originHeader );
720  }
721 
722  if ( !in_array( $originParam, $origins ) ) {
723  // origin parameter set but incorrect
724  // Send a 403 response
725  $response->statusHeader( 403 );
726  $response->header( 'Cache-Control: no-cache' );
727  echo "'origin' parameter does not match Origin header\n";
728 
729  return false;
730  }
731 
732  $config = $this->getConfig();
733  $matchedOrigin = count( $origins ) === 1 && self::matchOrigin(
734  $originParam,
735  $config->get( 'CrossSiteAJAXdomains' ),
736  $config->get( 'CrossSiteAJAXdomainExceptions' )
737  );
738 
739  $allowOrigin = $originHeader;
740  $allowCredentials = 'true';
741  $allowTiming = $originHeader;
742  }
743 
744  if ( $matchedOrigin ) {
745  $requestedMethod = $request->getHeader( 'Access-Control-Request-Method' );
746  $preflight = $request->getMethod() === 'OPTIONS' && $requestedMethod !== false;
747  if ( $preflight ) {
748  // This is a CORS preflight request
749  if ( $requestedMethod !== 'POST' && $requestedMethod !== 'GET' ) {
750  // If method is not a case-sensitive match, do not set any additional headers and terminate.
751  $response->header( 'MediaWiki-CORS-Rejection: Unsupported method requested in preflight' );
752  return true;
753  }
754  // We allow the actual request to send the following headers
755  $requestedHeaders = $request->getHeader( 'Access-Control-Request-Headers' );
756  if ( $requestedHeaders !== false ) {
757  if ( !self::matchRequestedHeaders( $requestedHeaders ) ) {
758  $response->header( 'MediaWiki-CORS-Rejection: Unsupported header requested in preflight' );
759  return true;
760  }
761  $response->header( 'Access-Control-Allow-Headers: ' . $requestedHeaders );
762  }
763 
764  // We only allow the actual request to be GET or POST
765  $response->header( 'Access-Control-Allow-Methods: POST, GET' );
766  } elseif ( $request->getMethod() !== 'POST' && $request->getMethod() !== 'GET' ) {
767  // Unsupported non-preflight method, don't handle it as CORS
768  $response->header(
769  'MediaWiki-CORS-Rejection: Unsupported method for simple request or actual request'
770  );
771  return true;
772  }
773 
774  $response->header( "Access-Control-Allow-Origin: $allowOrigin" );
775  $response->header( "Access-Control-Allow-Credentials: $allowCredentials" );
776  // https://www.w3.org/TR/resource-timing/#timing-allow-origin
777  if ( $allowTiming !== false ) {
778  $response->header( "Timing-Allow-Origin: $allowTiming" );
779  }
780 
781  if ( !$preflight ) {
782  $response->header(
783  'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag, '
784  . 'MediaWiki-Login-Suppressed'
785  );
786  }
787  } else {
788  $response->header( 'MediaWiki-CORS-Rejection: Origin mismatch' );
789  }
790 
791  if ( $varyOrigin ) {
792  $this->getOutput()->addVaryHeader( 'Origin' );
793  }
794 
795  return true;
796  }
797 
806  protected static function matchOrigin( $value, $rules, $exceptions ) {
807  foreach ( $rules as $rule ) {
808  if ( preg_match( self::wildcardToRegex( $rule ), $value ) ) {
809  // Rule matches, check exceptions
810  foreach ( $exceptions as $exc ) {
811  if ( preg_match( self::wildcardToRegex( $exc ), $value ) ) {
812  return false;
813  }
814  }
815 
816  return true;
817  }
818  }
819 
820  return false;
821  }
822 
830  protected static function matchRequestedHeaders( $requestedHeaders ) {
831  if ( trim( $requestedHeaders ) === '' ) {
832  return true;
833  }
834  $requestedHeaders = explode( ',', $requestedHeaders );
835  $allowedAuthorHeaders = array_flip( [
836  /* simple headers (see spec) */
837  'accept',
838  'accept-language',
839  'content-language',
840  'content-type',
841  /* non-authorable headers in XHR, which are however requested by some UAs */
842  'accept-encoding',
843  'dnt',
844  'origin',
845  /* MediaWiki whitelist */
846  'user-agent',
847  'api-user-agent',
848  ] );
849  foreach ( $requestedHeaders as $rHeader ) {
850  $rHeader = strtolower( trim( $rHeader ) );
851  if ( !isset( $allowedAuthorHeaders[$rHeader] ) ) {
852  LoggerFactory::getInstance( 'api-warning' )->warning(
853  'CORS preflight failed on requested header: {header}', [
854  'header' => $rHeader
855  ]
856  );
857  return false;
858  }
859  }
860  return true;
861  }
862 
871  protected static function wildcardToRegex( $wildcard ) {
872  $wildcard = preg_quote( $wildcard, '/' );
873  $wildcard = str_replace(
874  [ '\*', '\?' ],
875  [ '.*?', '.' ],
876  $wildcard
877  );
878 
879  return "/^https?:\/\/$wildcard$/";
880  }
881 
887  protected function sendCacheHeaders( $isError ) {
888  $response = $this->getRequest()->response();
889  $out = $this->getOutput();
890 
891  $out->addVaryHeader( 'Treat-as-Untrusted' );
892 
893  $config = $this->getConfig();
894 
895  if ( $config->get( 'VaryOnXFP' ) ) {
896  $out->addVaryHeader( 'X-Forwarded-Proto' );
897  }
898 
899  if ( !$isError && $this->mModule &&
900  ( $this->getRequest()->getMethod() === 'GET' || $this->getRequest()->getMethod() === 'HEAD' )
901  ) {
902  $etag = $this->mModule->getConditionalRequestData( 'etag' );
903  if ( $etag !== null ) {
904  $response->header( "ETag: $etag" );
905  }
906  $lastMod = $this->mModule->getConditionalRequestData( 'last-modified' );
907  if ( $lastMod !== null ) {
908  $response->header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822, $lastMod ) );
909  }
910  }
911 
912  // The logic should be:
913  // $this->mCacheControl['max-age'] is set?
914  // Use it, the module knows better than our guess.
915  // !$this->mModule || $this->mModule->isWriteMode(), and mCacheMode is private?
916  // Use 0 because we can guess caching is probably the wrong thing to do.
917  // Use $this->getParameter( 'maxage' ), which already defaults to 0.
918  $maxage = 0;
919  if ( isset( $this->mCacheControl['max-age'] ) ) {
920  $maxage = $this->mCacheControl['max-age'];
921  } elseif ( ( $this->mModule && !$this->mModule->isWriteMode() ) ||
922  $this->mCacheMode !== 'private'
923  ) {
924  $maxage = $this->getParameter( 'maxage' );
925  }
926  $privateCache = 'private, must-revalidate, max-age=' . $maxage;
927 
928  if ( $this->mCacheMode == 'private' ) {
929  $response->header( "Cache-Control: $privateCache" );
930  return;
931  }
932 
933  if ( $this->mCacheMode == 'anon-public-user-private' ) {
934  $out->addVaryHeader( 'Cookie' );
935  $response->header( $out->getVaryHeader() );
936  if ( SessionManager::getGlobalSession()->isPersistent() ) {
937  // Logged in or otherwise has session (e.g. anonymous users who have edited)
938  // Mark request private
939  $response->header( "Cache-Control: $privateCache" );
940 
941  return;
942  } // else anonymous, send public headers below
943  }
944 
945  // Send public headers
946  $response->header( $out->getVaryHeader() );
947 
948  // If nobody called setCacheMaxAge(), use the (s)maxage parameters
949  if ( !isset( $this->mCacheControl['s-maxage'] ) ) {
950  $this->mCacheControl['s-maxage'] = $this->getParameter( 'smaxage' );
951  }
952  if ( !isset( $this->mCacheControl['max-age'] ) ) {
953  $this->mCacheControl['max-age'] = $this->getParameter( 'maxage' );
954  }
955 
956  if ( !$this->mCacheControl['s-maxage'] && !$this->mCacheControl['max-age'] ) {
957  // Public cache not requested
958  // Sending a Vary header in this case is harmless, and protects us
959  // against conditional calls of setCacheMaxAge().
960  $response->header( "Cache-Control: $privateCache" );
961 
962  return;
963  }
964 
965  $this->mCacheControl['public'] = true;
966 
967  // Send an Expires header
968  $maxAge = min( $this->mCacheControl['s-maxage'], $this->mCacheControl['max-age'] );
969  $expiryUnixTime = ( $maxAge == 0 ? 1 : time() + $maxAge );
970  $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822, $expiryUnixTime ) );
971 
972  // Construct the Cache-Control header
973  $ccHeader = '';
974  $separator = '';
975  foreach ( $this->mCacheControl as $name => $value ) {
976  if ( is_bool( $value ) ) {
977  if ( $value ) {
978  $ccHeader .= $separator . $name;
979  $separator = ', ';
980  }
981  } else {
982  $ccHeader .= $separator . "$name=$value";
983  $separator = ', ';
984  }
985  }
986 
987  $response->header( "Cache-Control: $ccHeader" );
988  }
989 
993  private function createErrorPrinter() {
994  if ( !isset( $this->mPrinter ) ) {
995  $value = $this->getRequest()->getVal( 'format', self::API_DEFAULT_FORMAT );
996  if ( !$this->mModuleMgr->isDefined( $value, 'format' ) ) {
997  $value = self::API_DEFAULT_FORMAT;
998  }
999  $this->mPrinter = $this->createPrinterByName( $value );
1000  }
1001 
1002  // Printer may not be able to handle errors. This is particularly
1003  // likely if the module returns something for getCustomPrinter().
1004  if ( !$this->mPrinter->canPrintErrors() ) {
1005  $this->mPrinter = $this->createPrinterByName( self::API_DEFAULT_FORMAT );
1006  }
1007  }
1008 
1024  protected function errorMessagesFromException( $e, $type = 'error' ) {
1025  $messages = [];
1026  if ( $e instanceof ApiUsageException ) {
1027  foreach ( $e->getStatusValue()->getErrorsByType( $type ) as $error ) {
1028  $messages[] = ApiMessage::create( $error );
1029  }
1030  } elseif ( $type !== 'error' ) {
1031  // None of the rest have any messages for non-error types
1032  } else {
1033  // Something is seriously wrong
1034  $config = $this->getConfig();
1035  // TODO: Avoid embedding arbitrary class names in the error code.
1036  $class = preg_replace( '#^Wikimedia\\\Rdbms\\\#', '', get_class( $e ) );
1037  $code = 'internal_api_error_' . $class;
1038  $data = [ 'errorclass' => get_class( $e ) ];
1039  if ( $config->get( 'ShowExceptionDetails' ) ) {
1040  if ( $e instanceof ILocalizedException ) {
1041  $msg = $e->getMessageObject();
1042  } elseif ( $e instanceof MessageSpecifier ) {
1043  $msg = Message::newFromSpecifier( $e );
1044  } else {
1045  $msg = wfEscapeWikiText( $e->getMessage() );
1046  }
1047  $params = [ 'apierror-exceptioncaught', WebRequest::getRequestId(), $msg ];
1048  } else {
1049  $params = [ 'apierror-exceptioncaughttype', WebRequest::getRequestId(), get_class( $e ) ];
1050  }
1051 
1052  $messages[] = ApiMessage::create( $params, $code, $data );
1053  }
1054  return $messages;
1055  }
1056 
1062  protected function substituteResultWithError( $e ) {
1063  $result = $this->getResult();
1064  $formatter = $this->getErrorFormatter();
1065  $config = $this->getConfig();
1066  $errorCodes = [];
1067 
1068  // Remember existing warnings and errors across the reset
1069  $errors = $result->getResultData( [ 'errors' ] );
1070  $warnings = $result->getResultData( [ 'warnings' ] );
1071  $result->reset();
1072  if ( $warnings !== null ) {
1073  $result->addValue( null, 'warnings', $warnings, ApiResult::NO_SIZE_CHECK );
1074  }
1075  if ( $errors !== null ) {
1076  $result->addValue( null, 'errors', $errors, ApiResult::NO_SIZE_CHECK );
1077 
1078  // Collect the copied error codes for the return value
1079  foreach ( $errors as $error ) {
1080  if ( isset( $error['code'] ) ) {
1081  $errorCodes[$error['code']] = true;
1082  }
1083  }
1084  }
1085 
1086  // Add errors from the exception
1087  $modulePath = $e instanceof ApiUsageException ? $e->getModulePath() : null;
1088  foreach ( $this->errorMessagesFromException( $e, 'error' ) as $msg ) {
1089  if ( ApiErrorFormatter::isValidApiCode( $msg->getApiCode() ) ) {
1090  $errorCodes[$msg->getApiCode()] = true;
1091  } else {
1092  LoggerFactory::getInstance( 'api-warning' )->error( 'Invalid API error code "{code}"', [
1093  'code' => $msg->getApiCode(),
1094  'exception' => $e,
1095  ] );
1096  $errorCodes['<invalid-code>'] = true;
1097  }
1098  $formatter->addError( $modulePath, $msg );
1099  }
1100  foreach ( $this->errorMessagesFromException( $e, 'warning' ) as $msg ) {
1101  $formatter->addWarning( $modulePath, $msg );
1102  }
1103 
1104  // Add additional data. Path depends on whether we're in BC mode or not.
1105  // Data depends on the type of exception.
1106  if ( $formatter instanceof ApiErrorFormatter_BackCompat ) {
1107  $path = [ 'error' ];
1108  } else {
1109  $path = null;
1110  }
1111  if ( $e instanceof ApiUsageException ) {
1112  $link = wfExpandUrl( wfScript( 'api' ) );
1113  $result->addContentValue(
1114  $path,
1115  'docref',
1116  trim(
1117  $this->msg( 'api-usage-docref', $link )->inLanguage( $formatter->getLanguage() )->text()
1118  . ' '
1119  . $this->msg( 'api-usage-mailinglist-ref' )->inLanguage( $formatter->getLanguage() )->text()
1120  )
1121  );
1122  } elseif ( $config->get( 'ShowExceptionDetails' ) ) {
1123  $result->addContentValue(
1124  $path,
1125  'trace',
1126  $this->msg( 'api-exception-trace',
1127  get_class( $e ),
1128  $e->getFile(),
1129  $e->getLine(),
1131  )->inLanguage( $formatter->getLanguage() )->text()
1132  );
1133  }
1134 
1135  // Add the id and such
1136  $this->addRequestedFields( [ 'servedby' ] );
1137 
1138  return array_keys( $errorCodes );
1139  }
1140 
1146  protected function addRequestedFields( $force = [] ) {
1147  $result = $this->getResult();
1148 
1149  $requestid = $this->getParameter( 'requestid' );
1150  if ( $requestid !== null ) {
1151  $result->addValue( null, 'requestid', $requestid, ApiResult::NO_SIZE_CHECK );
1152  }
1153 
1154  if ( $this->getConfig()->get( 'ShowHostnames' ) && (
1155  in_array( 'servedby', $force, true ) || $this->getParameter( 'servedby' )
1156  ) ) {
1157  $result->addValue( null, 'servedby', wfHostname(), ApiResult::NO_SIZE_CHECK );
1158  }
1159 
1160  if ( $this->getParameter( 'curtimestamp' ) ) {
1161  $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601 ), ApiResult::NO_SIZE_CHECK );
1162  }
1163 
1164  if ( $this->getParameter( 'responselanginfo' ) ) {
1165  $result->addValue( null, 'uselang', $this->getLanguage()->getCode(),
1167  $result->addValue( null, 'errorlang', $this->getErrorFormatter()->getLanguage()->getCode(),
1169  }
1170  }
1171 
1176  protected function setupExecuteAction() {
1177  $this->addRequestedFields();
1178 
1179  $params = $this->extractRequestParams();
1180  $this->mAction = $params['action'];
1181 
1182  return $params;
1183  }
1184 
1191  protected function setupModule() {
1192  // Instantiate the module requested by the user
1193  $module = $this->mModuleMgr->getModule( $this->mAction, 'action' );
1194  if ( $module === null ) {
1195  // Probably can't happen
1196  // @codeCoverageIgnoreStart
1197  $this->dieWithError(
1198  [ 'apierror-unknownaction', wfEscapeWikiText( $this->mAction ) ], 'unknown_action'
1199  );
1200  // @codeCoverageIgnoreEnd
1201  }
1202  $moduleParams = $module->extractRequestParams();
1203 
1204  // Check token, if necessary
1205  if ( $module->needsToken() === true ) {
1206  throw new MWException(
1207  "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
1208  'See documentation for ApiBase::needsToken for details.'
1209  );
1210  }
1211  if ( $module->needsToken() ) {
1212  if ( !$module->mustBePosted() ) {
1213  throw new MWException(
1214  "Module '{$module->getModuleName()}' must require POST to use tokens."
1215  );
1216  }
1217 
1218  if ( !isset( $moduleParams['token'] ) ) {
1219  // Probably can't happen
1220  // @codeCoverageIgnoreStart
1221  $module->dieWithError( [ 'apierror-missingparam', 'token' ] );
1222  // @codeCoverageIgnoreEnd
1223  }
1224 
1225  $module->requirePostedParameters( [ 'token' ] );
1226 
1227  if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) {
1228  $module->dieWithError( 'apierror-badtoken' );
1229  }
1230  }
1231 
1232  return $module;
1233  }
1234 
1238  private function getMaxLag() {
1239  $dbLag = MediaWikiServices::getInstance()->getDBLoadBalancer()->getMaxLag();
1240  $lagInfo = [
1241  'host' => $dbLag[0],
1242  'lag' => $dbLag[1],
1243  'type' => 'db'
1244  ];
1245 
1246  $jobQueueLagFactor = $this->getConfig()->get( 'JobQueueIncludeInMaxLagFactor' );
1247  if ( $jobQueueLagFactor ) {
1248  // Turn total number of jobs into seconds by using the configured value
1249  $totalJobs = array_sum( JobQueueGroup::singleton()->getQueueSizes() );
1250  $jobQueueLag = $totalJobs / (float)$jobQueueLagFactor;
1251  if ( $jobQueueLag > $lagInfo['lag'] ) {
1252  $lagInfo = [
1253  'host' => wfHostname(), // XXX: Is there a better value that could be used?
1254  'lag' => $jobQueueLag,
1255  'type' => 'jobqueue',
1256  'jobs' => $totalJobs,
1257  ];
1258  }
1259  }
1260 
1261  Hooks::runWithoutAbort( 'ApiMaxLagInfo', [ &$lagInfo ] );
1262 
1263  return $lagInfo;
1264  }
1265 
1272  protected function checkMaxLag( $module, $params ) {
1273  if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
1274  $maxLag = $params['maxlag'];
1275  $lagInfo = $this->getMaxLag();
1276  if ( $lagInfo['lag'] > $maxLag ) {
1277  $response = $this->getRequest()->response();
1278 
1279  $response->header( 'Retry-After: ' . max( (int)$maxLag, 5 ) );
1280  $response->header( 'X-Database-Lag: ' . (int)$lagInfo['lag'] );
1281 
1282  if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
1283  $this->dieWithError(
1284  [ 'apierror-maxlag', $lagInfo['lag'], $lagInfo['host'] ],
1285  'maxlag',
1286  $lagInfo
1287  );
1288  }
1289 
1290  $this->dieWithError( [ 'apierror-maxlag-generic', $lagInfo['lag'] ], 'maxlag', $lagInfo );
1291  }
1292  }
1293 
1294  return true;
1295  }
1296 
1318  protected function checkConditionalRequestHeaders( $module ) {
1319  if ( $this->mInternalMode ) {
1320  // No headers to check in internal mode
1321  return true;
1322  }
1323 
1324  if ( $this->getRequest()->getMethod() !== 'GET' && $this->getRequest()->getMethod() !== 'HEAD' ) {
1325  // Don't check POSTs
1326  return true;
1327  }
1328 
1329  $return304 = false;
1330 
1331  $ifNoneMatch = array_diff(
1332  $this->getRequest()->getHeader( 'If-None-Match', WebRequest::GETHEADER_LIST ) ?: [],
1333  [ '' ]
1334  );
1335  if ( $ifNoneMatch ) {
1336  if ( $ifNoneMatch === [ '*' ] ) {
1337  // API responses always "exist"
1338  $etag = '*';
1339  } else {
1340  $etag = $module->getConditionalRequestData( 'etag' );
1341  }
1342  }
1343  if ( $ifNoneMatch && $etag !== null ) {
1344  $test = substr( $etag, 0, 2 ) === 'W/' ? substr( $etag, 2 ) : $etag;
1345  $match = array_map( function ( $s ) {
1346  return substr( $s, 0, 2 ) === 'W/' ? substr( $s, 2 ) : $s;
1347  }, $ifNoneMatch );
1348  $return304 = in_array( $test, $match, true );
1349  } else {
1350  $value = trim( $this->getRequest()->getHeader( 'If-Modified-Since' ) );
1351 
1352  // Some old browsers sends sizes after the date, like this:
1353  // Wed, 20 Aug 2003 06:51:19 GMT; length=5202
1354  // Ignore that.
1355  $i = strpos( $value, ';' );
1356  if ( $i !== false ) {
1357  $value = trim( substr( $value, 0, $i ) );
1358  }
1359 
1360  if ( $value !== '' ) {
1361  try {
1362  $ts = new MWTimestamp( $value );
1363  if (
1364  // RFC 7231 IMF-fixdate
1365  $ts->getTimestamp( TS_RFC2822 ) === $value ||
1366  // RFC 850
1367  $ts->format( 'l, d-M-y H:i:s' ) . ' GMT' === $value ||
1368  // asctime (with and without space-padded day)
1369  $ts->format( 'D M j H:i:s Y' ) === $value ||
1370  $ts->format( 'D M j H:i:s Y' ) === $value
1371  ) {
1372  $config = $this->getConfig();
1373  $lastMod = $module->getConditionalRequestData( 'last-modified' );
1374  if ( $lastMod !== null ) {
1375  // Mix in some MediaWiki modification times
1376  $modifiedTimes = [
1377  'page' => $lastMod,
1378  'user' => $this->getUser()->getTouched(),
1379  'epoch' => $config->get( 'CacheEpoch' ),
1380  ];
1381 
1382  if ( $config->get( 'UseCdn' ) ) {
1383  // T46570: the core page itself may not change, but resources might
1384  $modifiedTimes['sepoch'] = wfTimestamp(
1385  TS_MW, time() - $config->get( 'CdnMaxAge' )
1386  );
1387  }
1388  Hooks::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this->getOutput() ] );
1389  $lastMod = max( $modifiedTimes );
1390  $return304 = wfTimestamp( TS_MW, $lastMod ) <= $ts->getTimestamp( TS_MW );
1391  }
1392  }
1393  } catch ( TimestampException $e ) {
1394  // Invalid timestamp, ignore it
1395  }
1396  }
1397  }
1398 
1399  if ( $return304 ) {
1400  $this->getRequest()->response()->statusHeader( 304 );
1401 
1402  // Avoid outputting the compressed representation of a zero-length body
1403  Wikimedia\suppressWarnings();
1404  ini_set( 'zlib.output_compression', 0 );
1405  Wikimedia\restoreWarnings();
1407 
1408  return false;
1409  }
1410 
1411  return true;
1412  }
1413 
1418  protected function checkExecutePermissions( $module ) {
1419  $user = $this->getUser();
1420  if ( $module->isReadMode() && !$this->getPermissionManager()->isEveryoneAllowed( 'read' ) &&
1421  !$this->getPermissionManager()->userHasRight( $user, 'read' )
1422  ) {
1423  $this->dieWithError( 'apierror-readapidenied' );
1424  }
1425 
1426  if ( $module->isWriteMode() ) {
1427  if ( !$this->mEnableWrite ) {
1428  $this->dieWithError( 'apierror-noapiwrite' );
1429  } elseif ( !$this->getPermissionManager()->userHasRight( $user, 'writeapi' ) ) {
1430  $this->dieWithError( 'apierror-writeapidenied' );
1431  } elseif ( $this->getRequest()->getHeader( 'Promise-Non-Write-API-Action' ) ) {
1432  $this->dieWithError( 'apierror-promised-nonwrite-api' );
1433  }
1434 
1435  $this->checkReadOnly( $module );
1436  }
1437 
1438  // Allow extensions to stop execution for arbitrary reasons.
1439  $message = 'hookaborted';
1440  if ( !Hooks::run( 'ApiCheckCanExecute', [ $module, $user, &$message ] ) ) {
1441  $this->dieWithError( $message );
1442  }
1443  }
1444 
1449  protected function checkReadOnly( $module ) {
1450  if ( wfReadOnly() ) {
1451  $this->dieReadOnly();
1452  }
1453 
1454  if ( $module->isWriteMode()
1455  && $this->getUser()->isBot()
1456  && MediaWikiServices::getInstance()->getDBLoadBalancer()->getServerCount() > 1
1457  ) {
1458  $this->checkBotReadOnly();
1459  }
1460  }
1461 
1465  private function checkBotReadOnly() {
1466  // Figure out how many servers have passed the lag threshold
1467  $numLagged = 0;
1468  $lagLimit = $this->getConfig()->get( 'APIMaxLagThreshold' );
1469  $laggedServers = [];
1470  $loadBalancer = MediaWikiServices::getInstance()->getDBLoadBalancer();
1471  foreach ( $loadBalancer->getLagTimes() as $serverIndex => $lag ) {
1472  if ( $lag > $lagLimit ) {
1473  ++$numLagged;
1474  $laggedServers[] = $loadBalancer->getServerName( $serverIndex ) . " ({$lag}s)";
1475  }
1476  }
1477 
1478  // If a majority of replica DBs are too lagged then disallow writes
1479  $replicaCount = $loadBalancer->getServerCount() - 1;
1480  if ( $numLagged >= ceil( $replicaCount / 2 ) ) {
1481  $laggedServers = implode( ', ', $laggedServers );
1482  wfDebugLog(
1483  'api-readonly', // Deprecate this channel in favor of api-warning?
1484  "Api request failed as read only because the following DBs are lagged: $laggedServers"
1485  );
1486  LoggerFactory::getInstance( 'api-warning' )->warning(
1487  "Api request failed as read only because the following DBs are lagged: {laggeddbs}", [
1488  'laggeddbs' => $laggedServers,
1489  ]
1490  );
1491 
1492  $this->dieWithError(
1493  'readonly_lag',
1494  'readonly',
1495  [ 'readonlyreason' => "Waiting for $numLagged lagged database(s)" ]
1496  );
1497  }
1498  }
1499 
1504  protected function checkAsserts( $params ) {
1505  if ( isset( $params['assert'] ) ) {
1506  $user = $this->getUser();
1507  switch ( $params['assert'] ) {
1508  case 'user':
1509  if ( $user->isAnon() ) {
1510  $this->dieWithError( 'apierror-assertuserfailed' );
1511  }
1512  break;
1513  case 'bot':
1514  if ( !$this->getPermissionManager()->userHasRight( $user, 'bot' ) ) {
1515  $this->dieWithError( 'apierror-assertbotfailed' );
1516  }
1517  break;
1518  }
1519  }
1520  if ( isset( $params['assertuser'] ) ) {
1521  $assertUser = User::newFromName( $params['assertuser'], false );
1522  if ( !$assertUser || !$this->getUser()->equals( $assertUser ) ) {
1523  $this->dieWithError(
1524  [ 'apierror-assertnameduserfailed', wfEscapeWikiText( $params['assertuser'] ) ]
1525  );
1526  }
1527  }
1528  }
1529 
1535  protected function setupExternalResponse( $module, $params ) {
1536  $validMethods = [ 'GET', 'HEAD', 'POST', 'OPTIONS' ];
1537  $request = $this->getRequest();
1538 
1539  if ( !in_array( $request->getMethod(), $validMethods ) ) {
1540  $this->dieWithError( 'apierror-invalidmethod', null, null, 405 );
1541  }
1542 
1543  if ( !$request->wasPosted() && $module->mustBePosted() ) {
1544  // Module requires POST. GET request might still be allowed
1545  // if $wgDebugApi is true, otherwise fail.
1546  $this->dieWithErrorOrDebug( [ 'apierror-mustbeposted', $this->mAction ] );
1547  }
1548 
1549  if ( $request->wasPosted() && !$request->getHeader( 'Content-Type' ) ) {
1550  $this->addDeprecation(
1551  'apiwarn-deprecation-post-without-content-type', 'post-without-content-type'
1552  );
1553  }
1554 
1555  // See if custom printer is used
1556  $this->mPrinter = $module->getCustomPrinter();
1557  if ( is_null( $this->mPrinter ) ) {
1558  // Create an appropriate printer
1559  $this->mPrinter = $this->createPrinterByName( $params['format'] );
1560  }
1561 
1562  if ( $request->getProtocol() === 'http' && (
1563  $request->getSession()->shouldForceHTTPS() ||
1564  ( $this->getUser()->isLoggedIn() &&
1565  $this->getUser()->requiresHTTPS() )
1566  ) ) {
1567  $this->addDeprecation( 'apiwarn-deprecation-httpsexpected', 'https-expected' );
1568  }
1569  }
1570 
1574  protected function executeAction() {
1575  $params = $this->setupExecuteAction();
1576 
1577  // Check asserts early so e.g. errors in parsing a module's parameters due to being
1578  // logged out don't override the client's intended "am I logged in?" check.
1579  $this->checkAsserts( $params );
1580 
1581  $module = $this->setupModule();
1582  $this->mModule = $module;
1583 
1584  if ( !$this->mInternalMode ) {
1585  $this->setRequestExpectations( $module );
1586  }
1587 
1588  $this->checkExecutePermissions( $module );
1589 
1590  if ( !$this->checkMaxLag( $module, $params ) ) {
1591  return;
1592  }
1593 
1594  if ( !$this->checkConditionalRequestHeaders( $module ) ) {
1595  return;
1596  }
1597 
1598  if ( !$this->mInternalMode ) {
1599  $this->setupExternalResponse( $module, $params );
1600  }
1601 
1602  $module->execute();
1603  Hooks::run( 'APIAfterExecute', [ &$module ] );
1604 
1605  $this->reportUnusedParams();
1606 
1607  if ( !$this->mInternalMode ) {
1609 
1610  $this->printResult();
1611  }
1612  }
1613 
1618  protected function setRequestExpectations( ApiBase $module ) {
1619  $limits = $this->getConfig()->get( 'TrxProfilerLimits' );
1620  $trxProfiler = Profiler::instance()->getTransactionProfiler();
1621  $trxProfiler->setLogger( LoggerFactory::getInstance( 'DBPerformance' ) );
1622  if ( $this->getRequest()->hasSafeMethod() ) {
1623  $trxProfiler->setExpectations( $limits['GET'], __METHOD__ );
1624  } elseif ( $this->getRequest()->wasPosted() && !$module->isWriteMode() ) {
1625  $trxProfiler->setExpectations( $limits['POST-nonwrite'], __METHOD__ );
1626  $this->getRequest()->markAsSafeRequest();
1627  } else {
1628  $trxProfiler->setExpectations( $limits['POST'], __METHOD__ );
1629  }
1630  }
1631 
1637  protected function logRequest( $time, $e = null ) {
1638  $request = $this->getRequest();
1639 
1640  $logCtx = [
1641  // https://gerrit.wikimedia.org/r/plugins/gitiles/mediawiki/event-schemas/+/master/jsonschema/mediawiki/api/request
1642  '$schema' => '/mediawiki/api/request/0.0.1',
1643  'meta' => [
1644  'request_id' => WebRequest::getRequestId(),
1645  'id' => UIDGenerator::newUUIDv4(),
1646  'dt' => wfTimestamp( TS_ISO_8601 ),
1647  'domain' => $this->getConfig()->get( 'ServerName' ),
1648  // If using the EventBus extension (as intended) with this log channel,
1649  // this stream name will map to a Kafka topic.
1650  'stream' => 'mediawiki.api-request'
1651  ],
1652  'http' => [
1653  'method' => $request->getMethod(),
1654  'client_ip' => $request->getIP()
1655  ],
1656  'database' => WikiMap::getCurrentWikiDbDomain()->getId(),
1657  'backend_time_ms' => (int)round( $time * 1000 ),
1658  ];
1659 
1660  // If set, these headers will be logged in http.request_headers.
1661  $httpRequestHeadersToLog = [ 'accept-language', 'referer', 'user-agent' ];
1662  foreach ( $httpRequestHeadersToLog as $header ) {
1663  if ( $request->getHeader( $header ) ) {
1664  // Set the header in http.request_headers
1665  $logCtx['http']['request_headers'][$header] = $request->getHeader( $header );
1666  }
1667  }
1668 
1669  if ( $e ) {
1670  $logCtx['api_error_codes'] = [];
1671  foreach ( $this->errorMessagesFromException( $e ) as $msg ) {
1672  $logCtx['api_error_codes'][] = $msg->getApiCode();
1673  }
1674  }
1675 
1676  // Construct space separated message for 'api' log channel
1677  $msg = "API {$request->getMethod()} " .
1678  wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
1679  " {$logCtx['http']['client_ip']} " .
1680  "T={$logCtx['backend_time_ms']}ms";
1681 
1682  $sensitive = array_flip( $this->getSensitiveParams() );
1683  foreach ( $this->getParamsUsed() as $name ) {
1684  $value = $request->getVal( $name );
1685  if ( $value === null ) {
1686  continue;
1687  }
1688 
1689  if ( isset( $sensitive[$name] ) ) {
1690  $value = '[redacted]';
1691  $encValue = '[redacted]';
1692  } elseif ( strlen( $value ) > 256 ) {
1693  $value = substr( $value, 0, 256 );
1694  $encValue = $this->encodeRequestLogValue( $value ) . '[...]';
1695  } else {
1696  $encValue = $this->encodeRequestLogValue( $value );
1697  }
1698 
1699  $logCtx['params'][$name] = $value;
1700  $msg .= " {$name}={$encValue}";
1701  }
1702 
1703  // Log an unstructured message to the api channel.
1704  wfDebugLog( 'api', $msg, 'private' );
1705 
1706  // The api-request channel a structured data log channel.
1707  wfDebugLog( 'api-request', '', 'private', $logCtx );
1708  }
1709 
1715  protected function encodeRequestLogValue( $s ) {
1716  static $table = [];
1717  if ( !$table ) {
1718  $chars = ';@$!*(),/:';
1719  $numChars = strlen( $chars );
1720  for ( $i = 0; $i < $numChars; $i++ ) {
1721  $table[rawurlencode( $chars[$i] )] = $chars[$i];
1722  }
1723  }
1724 
1725  return strtr( rawurlencode( $s ), $table );
1726  }
1727 
1732  protected function getParamsUsed() {
1733  return array_keys( $this->mParamsUsed );
1734  }
1735 
1740  public function markParamsUsed( $params ) {
1741  $this->mParamsUsed += array_fill_keys( (array)$params, true );
1742  }
1743 
1749  protected function getSensitiveParams() {
1750  return array_keys( $this->mParamsSensitive );
1751  }
1752 
1758  public function markParamsSensitive( $params ) {
1759  $this->mParamsSensitive += array_fill_keys( (array)$params, true );
1760  }
1761 
1768  public function getVal( $name, $default = null ) {
1769  $this->mParamsUsed[$name] = true;
1770 
1771  $ret = $this->getRequest()->getVal( $name );
1772  if ( $ret === null ) {
1773  if ( $this->getRequest()->getArray( $name ) !== null ) {
1774  // See T12262 for why we don't just implode( '|', ... ) the
1775  // array.
1776  $this->addWarning( [ 'apiwarn-unsupportedarray', $name ] );
1777  }
1778  $ret = $default;
1779  }
1780  return $ret;
1781  }
1782 
1789  public function getCheck( $name ) {
1790  return $this->getVal( $name, null ) !== null;
1791  }
1792 
1800  public function getUpload( $name ) {
1801  $this->mParamsUsed[$name] = true;
1802 
1803  return $this->getRequest()->getUpload( $name );
1804  }
1805 
1810  protected function reportUnusedParams() {
1811  $paramsUsed = $this->getParamsUsed();
1812  $allParams = $this->getRequest()->getValueNames();
1813 
1814  if ( !$this->mInternalMode ) {
1815  // Printer has not yet executed; don't warn that its parameters are unused
1816  $printerParams = $this->mPrinter->encodeParamName(
1817  array_keys( $this->mPrinter->getFinalParams() ?: [] )
1818  );
1819  $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1820  } else {
1821  $unusedParams = array_diff( $allParams, $paramsUsed );
1822  }
1823 
1824  if ( count( $unusedParams ) ) {
1825  $this->addWarning( [
1826  'apierror-unrecognizedparams',
1827  Message::listParam( array_map( 'wfEscapeWikiText', $unusedParams ), 'comma' ),
1828  count( $unusedParams )
1829  ] );
1830  }
1831  }
1832 
1838  protected function printResult( $httpCode = 0 ) {
1839  if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
1840  $this->addWarning( 'apiwarn-wgdebugapi' );
1841  }
1842 
1843  $printer = $this->mPrinter;
1844  $printer->initPrinter( false );
1845  if ( $httpCode ) {
1846  $printer->setHttpStatus( $httpCode );
1847  }
1848  $printer->execute();
1849  $printer->closePrinter();
1850  }
1851 
1855  public function isReadMode() {
1856  return false;
1857  }
1858 
1864  public function getAllowedParams() {
1865  return [
1866  'action' => [
1867  ApiBase::PARAM_DFLT => 'help',
1868  ApiBase::PARAM_TYPE => 'submodule',
1869  ],
1870  'format' => [
1871  ApiBase::PARAM_DFLT => self::API_DEFAULT_FORMAT,
1872  ApiBase::PARAM_TYPE => 'submodule',
1873  ],
1874  'maxlag' => [
1875  ApiBase::PARAM_TYPE => 'integer'
1876  ],
1877  'smaxage' => [
1878  ApiBase::PARAM_TYPE => 'integer',
1879  ApiBase::PARAM_DFLT => 0
1880  ],
1881  'maxage' => [
1882  ApiBase::PARAM_TYPE => 'integer',
1883  ApiBase::PARAM_DFLT => 0
1884  ],
1885  'assert' => [
1886  ApiBase::PARAM_TYPE => [ 'user', 'bot' ]
1887  ],
1888  'assertuser' => [
1889  ApiBase::PARAM_TYPE => 'user',
1890  ],
1891  'requestid' => null,
1892  'servedby' => false,
1893  'curtimestamp' => false,
1894  'responselanginfo' => false,
1895  'origin' => null,
1896  'uselang' => [
1897  ApiBase::PARAM_DFLT => self::API_DEFAULT_USELANG,
1898  ],
1899  'errorformat' => [
1900  ApiBase::PARAM_TYPE => [ 'plaintext', 'wikitext', 'html', 'raw', 'none', 'bc' ],
1901  ApiBase::PARAM_DFLT => 'bc',
1902  ],
1903  'errorlang' => [
1904  ApiBase::PARAM_DFLT => 'uselang',
1905  ],
1906  'errorsuselocal' => [
1907  ApiBase::PARAM_DFLT => false,
1908  ],
1909  ];
1910  }
1911 
1913  protected function getExamplesMessages() {
1914  return [
1915  'action=help'
1916  => 'apihelp-help-example-main',
1917  'action=help&recursivesubmodules=1'
1918  => 'apihelp-help-example-recursive',
1919  ];
1920  }
1921 
1926  public function modifyHelp( array &$help, array $options, array &$tocData ) {
1927  // Wish PHP had an "array_insert_before". Instead, we have to manually
1928  // reindex the array to get 'permissions' in the right place.
1929  $oldHelp = $help;
1930  $help = [];
1931  foreach ( $oldHelp as $k => $v ) {
1932  if ( $k === 'submodules' ) {
1933  $help['permissions'] = '';
1934  }
1935  $help[$k] = $v;
1936  }
1937  $help['datatypes'] = '';
1938  $help['templatedparams'] = '';
1939  $help['credits'] = '';
1940 
1941  // Fill 'permissions'
1942  $help['permissions'] .= Html::openElement( 'div',
1943  [ 'class' => 'apihelp-block apihelp-permissions' ] );
1944  $m = $this->msg( 'api-help-permissions' );
1945  if ( !$m->isDisabled() ) {
1946  $help['permissions'] .= Html::rawElement( 'div', [ 'class' => 'apihelp-block-head' ],
1947  $m->numParams( count( self::$mRights ) )->parse()
1948  );
1949  }
1950  $help['permissions'] .= Html::openElement( 'dl' );
1951  foreach ( self::$mRights as $right => $rightMsg ) {
1952  $help['permissions'] .= Html::element( 'dt', null, $right );
1953 
1954  $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse();
1955  $help['permissions'] .= Html::rawElement( 'dd', null, $rightMsg );
1956 
1957  $groups = array_map( function ( $group ) {
1958  return $group == '*' ? 'all' : $group;
1959  }, $this->getPermissionManager()->getGroupsWithPermission( $right ) );
1960 
1961  $help['permissions'] .= Html::rawElement( 'dd', null,
1962  $this->msg( 'api-help-permissions-granted-to' )
1963  ->numParams( count( $groups ) )
1964  ->params( Message::listParam( $groups ) )
1965  ->parse()
1966  );
1967  }
1968  $help['permissions'] .= Html::closeElement( 'dl' );
1969  $help['permissions'] .= Html::closeElement( 'div' );
1970 
1971  // Fill 'datatypes', 'templatedparams', and 'credits', if applicable
1972  if ( empty( $options['nolead'] ) ) {
1973  $level = $options['headerlevel'];
1974  $tocnumber = &$options['tocnumber'];
1975 
1976  $header = $this->msg( 'api-help-datatypes-header' )->parse();
1977 
1978  $id = Sanitizer::escapeIdForAttribute( 'main/datatypes', Sanitizer::ID_PRIMARY );
1979  $idFallback = Sanitizer::escapeIdForAttribute( 'main/datatypes', Sanitizer::ID_FALLBACK );
1980  $headline = Linker::makeHeadline( min( 6, $level ),
1981  ' class="apihelp-header">',
1982  $id,
1983  $header,
1984  '',
1985  $idFallback
1986  );
1987  // Ensure we have a sane anchor
1988  if ( $id !== 'main/datatypes' && $idFallback !== 'main/datatypes' ) {
1989  $headline = '<div id="main/datatypes"></div>' . $headline;
1990  }
1991  $help['datatypes'] .= $headline;
1992  $help['datatypes'] .= $this->msg( 'api-help-datatypes' )->parseAsBlock();
1993  if ( !isset( $tocData['main/datatypes'] ) ) {
1994  $tocnumber[$level]++;
1995  $tocData['main/datatypes'] = [
1996  'toclevel' => count( $tocnumber ),
1997  'level' => $level,
1998  'anchor' => 'main/datatypes',
1999  'line' => $header,
2000  'number' => implode( '.', $tocnumber ),
2001  'index' => false,
2002  ];
2003  }
2004 
2005  $header = $this->msg( 'api-help-templatedparams-header' )->parse();
2006 
2007  $id = Sanitizer::escapeIdForAttribute( 'main/templatedparams', Sanitizer::ID_PRIMARY );
2008  $idFallback = Sanitizer::escapeIdForAttribute( 'main/templatedparams', Sanitizer::ID_FALLBACK );
2009  $headline = Linker::makeHeadline( min( 6, $level ),
2010  ' class="apihelp-header">',
2011  $id,
2012  $header,
2013  '',
2014  $idFallback
2015  );
2016  // Ensure we have a sane anchor
2017  if ( $id !== 'main/templatedparams' && $idFallback !== 'main/templatedparams' ) {
2018  $headline = '<div id="main/templatedparams"></div>' . $headline;
2019  }
2020  $help['templatedparams'] .= $headline;
2021  $help['templatedparams'] .= $this->msg( 'api-help-templatedparams' )->parseAsBlock();
2022  if ( !isset( $tocData['main/templatedparams'] ) ) {
2023  $tocnumber[$level]++;
2024  $tocData['main/templatedparams'] = [
2025  'toclevel' => count( $tocnumber ),
2026  'level' => $level,
2027  'anchor' => 'main/templatedparams',
2028  'line' => $header,
2029  'number' => implode( '.', $tocnumber ),
2030  'index' => false,
2031  ];
2032  }
2033 
2034  $header = $this->msg( 'api-credits-header' )->parse();
2035  $id = Sanitizer::escapeIdForAttribute( 'main/credits', Sanitizer::ID_PRIMARY );
2036  $idFallback = Sanitizer::escapeIdForAttribute( 'main/credits', Sanitizer::ID_FALLBACK );
2037  $headline = Linker::makeHeadline( min( 6, $level ),
2038  ' class="apihelp-header">',
2039  $id,
2040  $header,
2041  '',
2042  $idFallback
2043  );
2044  // Ensure we have a sane anchor
2045  if ( $id !== 'main/credits' && $idFallback !== 'main/credits' ) {
2046  $headline = '<div id="main/credits"></div>' . $headline;
2047  }
2048  $help['credits'] .= $headline;
2049  $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
2050  if ( !isset( $tocData['main/credits'] ) ) {
2051  $tocnumber[$level]++;
2052  $tocData['main/credits'] = [
2053  'toclevel' => count( $tocnumber ),
2054  'level' => $level,
2055  'anchor' => 'main/credits',
2056  'line' => $header,
2057  'number' => implode( '.', $tocnumber ),
2058  'index' => false,
2059  ];
2060  }
2061  }
2062  }
2063 
2064  private $mCanApiHighLimits = null;
2065 
2070  public function canApiHighLimits() {
2071  if ( !isset( $this->mCanApiHighLimits ) ) {
2072  $this->mCanApiHighLimits = $this->getPermissionManager()
2073  ->userHasRight( $this->getUser(), 'apihighlimits' );
2074  }
2075 
2076  return $this->mCanApiHighLimits;
2077  }
2078 
2083  public function getModuleManager() {
2084  return $this->mModuleMgr;
2085  }
2086 
2095  public function getUserAgent() {
2096  return trim(
2097  $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
2098  $this->getRequest()->getHeader( 'User-agent' )
2099  );
2100  }
2101 }
2102 
setContext(IContextSource $context)
getAllowedParams()
See ApiBase for description.
Definition: ApiMain.php:1864
getModuleManager()
Overrides to return this instance&#39;s module manager.
Definition: ApiMain.php:2083
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:830
$response
getUserAgent()
Fetches the user agent used for this request.
Definition: ApiMain.php:2095
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:407
getContinuationManager()
Get the continuation manager.
Definition: ApiMain.php:366
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:1146
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:517
modifyHelp(array &$help, array $options, array &$tocData)
-param array{nolead?:bool,headerlevel?:int,tocnumber?:int[]} $options
Definition: ApiMain.php:1926
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
static isEveryoneAllowed( $right)
Check if all users may be assumed to have the given permission.
Definition: User.php:4795
addDeprecation( $msg, $feature, $data=[])
Add a deprecation warning for this module.
Definition: ApiBase.php:1938
initPrinter( $unused=false)
Initialize the printer function and prepare the output headers.
checkExecutePermissions( $module)
Check for sufficient permissions to execute.
Definition: ApiMain.php:1418
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:1238
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:1449
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:306
setCacheControl( $directives)
Set directives (key/value pairs) for the Cache-Control header.
Definition: ApiMain.php:480
dieWithError( $msg, $code=null, $data=null, $httpCode=null)
Abort execution with an error.
Definition: ApiBase.php:2005
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:2070
errorMessagesFromException( $e, $type='error')
Create an error message for the given exception.
Definition: ApiMain.php:1024
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:1191
__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:1272
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:491
setRequestExpectations(ApiBase $module)
Set database connection, query, and write expectations given this module request. ...
Definition: ApiMain.php:1618
setupExternalResponse( $module, $params)
Check POST for external response and setup result printer.
Definition: ApiMain.php:1535
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:857
printResult( $httpCode=0)
Print results using the current printer.
Definition: ApiMain.php:1838
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:439
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:1295
static newUUIDv4( $flags=0)
Return an RFC4122 compliant v4 UUID.
checkAsserts( $params)
Check asserts of the user&#39;s rights.
Definition: ApiMain.php:1504
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:583
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:1574
isReadMode()
Definition: ApiMain.php:1855
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:686
setupExecuteAction()
Set up for the execution.
Definition: ApiMain.php:1176
getSensitiveParams()
Get the request parameters that should be considered sensitive.
Definition: ApiMain.php:1749
$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:323
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:871
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
static factory( $code)
Get a cached or new language object for a given language code.
Definition: Language.php:212
This class represents the result of the API operations.
Definition: ApiResult.php:35
markParamsSensitive( $params)
Mark parameters as sensitive.
Definition: ApiMain.php:1758
$help
Definition: mcc.php:32
$mParamsSensitive
Definition: ApiMain.php:160
$header
$mCanApiHighLimits
Definition: ApiMain.php:2064
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:1732
getExamplesMessages()
Definition: ApiMain.php:1913
getErrorFormatter()
Get the ApiErrorFormatter object associated with current request.
Definition: ApiMain.php:358
getCheck( $name)
Get a boolean request value, and register the fact that the parameter was used, for logging...
Definition: ApiMain.php:1789
logRequest( $time, $e=null)
Log the preceding request.
Definition: ApiMain.php:1637
static getCurrentWikiDbDomain()
Definition: WikiMap.php:293
sendCacheHeaders( $isError)
Send caching headers.
Definition: ApiMain.php:887
checkBotReadOnly()
Check whether we are readonly for bots.
Definition: ApiMain.php:1465
getModule()
Get the API module object.
Definition: ApiMain.php:389
checkConditionalRequestHeaders( $module)
Check selected RFC 7232 precondition headers.
Definition: ApiMain.php:1318
static makeHeadline( $level, $attribs, $anchor, $html, $link, $fallbackAnchor=false)
Create a headline for content.
Definition: Linker.php:1749
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:2182
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:2105
static newFromSpecifier( $value)
Transform a MessageSpecifier or a primitive value used interchangeably with specifiers (a message key...
Definition: Message.php:427
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:1924
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:654
reportUnusedParams()
Report unused parameters, so the client gets a hint in case it gave us parameters we don&#39;t know...
Definition: ApiMain.php:1810
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:1062
getPrinter()
Get the result formatter object.
Definition: ApiMain.php:398
getStatusValue()
Fetch the error status.
static newFromName( $name, $validate='valid')
Static factory method for creation from username.
Definition: User.php:515
markParamsUsed( $params)
Mark parameters as used.
Definition: ApiMain.php:1740
getUpload( $name)
Get a request upload, and register the fact that it was used, for logging.
Definition: ApiMain.php:1800
setContinuationManager(ApiContinuationManager $manager=null)
Set the continuation manager.
Definition: ApiMain.php:374
$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:1715
execute()
Execute api request.
Definition: ApiMain.php:505
static listParam(array $list, $type='text')
Definition: Message.php:1115
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:806
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:315
createErrorPrinter()
Create the printer for error output.
Definition: ApiMain.php:993
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:1768