MediaWiki  1.34.0
ApiMain.php
Go to the documentation of this file.
1 <?php
26 use Wikimedia\Timestamp\TimestampException;
27 
41 class ApiMain extends ApiBase {
45  const API_DEFAULT_FORMAT = 'jsonfm';
46 
50  const API_DEFAULT_USELANG = 'user';
51 
55  private static $Modules = [
56  'login' => ApiLogin::class,
57  'clientlogin' => ApiClientLogin::class,
58  'logout' => ApiLogout::class,
59  'createaccount' => ApiAMCreateAccount::class,
60  'linkaccount' => ApiLinkAccount::class,
61  'unlinkaccount' => ApiRemoveAuthenticationData::class,
62  'changeauthenticationdata' => ApiChangeAuthenticationData::class,
63  'removeauthenticationdata' => ApiRemoveAuthenticationData::class,
64  'resetpassword' => ApiResetPassword::class,
65  'query' => ApiQuery::class,
66  'expandtemplates' => ApiExpandTemplates::class,
67  'parse' => ApiParse::class,
68  'stashedit' => ApiStashEdit::class,
69  'opensearch' => ApiOpenSearch::class,
70  'feedcontributions' => ApiFeedContributions::class,
71  'feedrecentchanges' => ApiFeedRecentChanges::class,
72  'feedwatchlist' => ApiFeedWatchlist::class,
73  'help' => ApiHelp::class,
74  'paraminfo' => ApiParamInfo::class,
75  'rsd' => ApiRsd::class,
76  'compare' => ApiComparePages::class,
77  'tokens' => ApiTokens::class,
78  'checktoken' => ApiCheckToken::class,
79  'cspreport' => ApiCSPReport::class,
80  'validatepassword' => ApiValidatePassword::class,
81 
82  // Write modules
83  'purge' => ApiPurge::class,
84  'setnotificationtimestamp' => ApiSetNotificationTimestamp::class,
85  'rollback' => ApiRollback::class,
86  'delete' => ApiDelete::class,
87  'undelete' => ApiUndelete::class,
88  'protect' => ApiProtect::class,
89  'block' => ApiBlock::class,
90  'unblock' => ApiUnblock::class,
91  'move' => ApiMove::class,
92  'edit' => ApiEditPage::class,
93  'upload' => ApiUpload::class,
94  'filerevert' => ApiFileRevert::class,
95  'emailuser' => ApiEmailUser::class,
96  'watch' => ApiWatch::class,
97  'patrol' => ApiPatrol::class,
98  'import' => ApiImport::class,
99  'clearhasmsg' => ApiClearHasMsg::class,
100  'userrights' => ApiUserrights::class,
101  'options' => ApiOptions::class,
102  'imagerotate' => ApiImageRotate::class,
103  'revisiondelete' => ApiRevisionDelete::class,
104  'managetags' => ApiManageTags::class,
105  'tag' => ApiTag::class,
106  'mergehistory' => ApiMergeHistory::class,
107  'setpagelanguage' => ApiSetPageLanguage::class,
108  ];
109 
113  private static $Formats = [
114  'json' => ApiFormatJson::class,
115  'jsonfm' => ApiFormatJson::class,
116  'php' => ApiFormatPhp::class,
117  'phpfm' => ApiFormatPhp::class,
118  'xml' => ApiFormatXml::class,
119  'xmlfm' => ApiFormatXml::class,
120  'rawfm' => ApiFormatJson::class,
121  'none' => ApiFormatNone::class,
122  ];
123 
130  private static $mRights = [
131  'writeapi' => [
132  'msg' => 'right-writeapi',
133  'params' => []
134  ],
135  'apihighlimits' => [
136  'msg' => 'api-help-right-apihighlimits',
138  ]
139  ];
140 
144  private $mPrinter;
145 
149  private $mAction;
150  private $mEnableWrite;
153  private $mModule;
154 
155  private $mCacheMode = 'private';
157  private $mCacheControl = [];
158  private $mParamsUsed = [];
159  private $mParamsSensitive = [];
160 
162  private $lacksSameOriginSecurity = null;
163 
172  public function __construct( $context = null, $enableWrite = false ) {
173  if ( $context === null ) {
175  } elseif ( $context instanceof WebRequest ) {
176  // BC for pre-1.19
177  $request = $context;
179  }
180  // We set a derivative context so we can change stuff later
181  $this->setContext( new DerivativeContext( $context ) );
182 
183  if ( isset( $request ) ) {
184  $this->getContext()->setRequest( $request );
185  } else {
186  $request = $this->getRequest();
187  }
188 
189  $this->mInternalMode = ( $request instanceof FauxRequest );
190 
191  // Special handling for the main module: $parent === $this
192  parent::__construct( $this, $this->mInternalMode ? 'main_int' : 'main' );
193 
194  $config = $this->getConfig();
195 
196  if ( !$this->mInternalMode ) {
197  // Log if a request with a non-whitelisted Origin header is seen
198  // with session cookies.
199  $originHeader = $request->getHeader( 'Origin' );
200  if ( $originHeader === false ) {
201  $origins = [];
202  } else {
203  $originHeader = trim( $originHeader );
204  $origins = preg_split( '/\s+/', $originHeader );
205  }
206  $sessionCookies = array_intersect(
207  array_keys( $_COOKIE ),
208  MediaWiki\Session\SessionManager::singleton()->getVaryCookies()
209  );
210  if ( $origins && $sessionCookies && (
211  count( $origins ) !== 1 || !self::matchOrigin(
212  $origins[0],
213  $config->get( 'CrossSiteAJAXdomains' ),
214  $config->get( 'CrossSiteAJAXdomainExceptions' )
215  )
216  ) ) {
217  LoggerFactory::getInstance( 'cors' )->warning(
218  'Non-whitelisted CORS request with session cookies', [
219  'origin' => $originHeader,
220  'cookies' => $sessionCookies,
221  'ip' => $request->getIP(),
222  'userAgent' => $this->getUserAgent(),
223  'wiki' => WikiMap::getCurrentWikiDbDomain()->getId(),
224  ]
225  );
226  }
227 
228  // If we're in a mode that breaks the same-origin policy, strip
229  // user credentials for security.
230  if ( $this->lacksSameOriginSecurity() ) {
231  global $wgUser;
232  wfDebug( "API: stripping user credentials when the same-origin policy is not applied\n" );
233  $wgUser = new User();
234  $this->getContext()->setUser( $wgUser );
235  $request->response()->header( 'MediaWiki-Login-Suppressed: true' );
236  }
237  }
238 
239  $this->mResult = new ApiResult( $this->getConfig()->get( 'APIMaxResultSize' ) );
240 
241  // Setup uselang. This doesn't use $this->getParameter()
242  // because we're not ready to handle errors yet.
243  // Optimisation: Avoid slow getVal(), this isn't user-generated content.
244  $uselang = $request->getRawVal( 'uselang', self::API_DEFAULT_USELANG );
245  if ( $uselang === 'user' ) {
246  // Assume the parent context is going to return the user language
247  // for uselang=user (see T85635).
248  } else {
249  if ( $uselang === 'content' ) {
250  $uselang = MediaWikiServices::getInstance()->getContentLanguage()->getCode();
251  }
252  $code = RequestContext::sanitizeLangCode( $uselang );
253  $this->getContext()->setLanguage( $code );
254  if ( !$this->mInternalMode ) {
255  global $wgLang;
256  $wgLang = $this->getContext()->getLanguage();
257  RequestContext::getMain()->setLanguage( $wgLang );
258  }
259  }
260 
261  // Set up the error formatter. This doesn't use $this->getParameter()
262  // because we're not ready to handle errors yet.
263  // Optimisation: Avoid slow getVal(), this isn't user-generated content.
264  $errorFormat = $request->getRawVal( 'errorformat', 'bc' );
265  $errorLangCode = $request->getRawVal( 'errorlang', 'uselang' );
266  $errorsUseDB = $request->getCheck( 'errorsuselocal' );
267  if ( in_array( $errorFormat, [ 'plaintext', 'wikitext', 'html', 'raw', 'none' ], true ) ) {
268  if ( $errorLangCode === 'uselang' ) {
269  $errorLang = $this->getLanguage();
270  } elseif ( $errorLangCode === 'content' ) {
271  $errorLang = MediaWikiServices::getInstance()->getContentLanguage();
272  } else {
273  $errorLangCode = RequestContext::sanitizeLangCode( $errorLangCode );
274  $errorLang = Language::factory( $errorLangCode );
275  }
276  $this->mErrorFormatter = new ApiErrorFormatter(
277  $this->mResult, $errorLang, $errorFormat, $errorsUseDB
278  );
279  } else {
280  $this->mErrorFormatter = new ApiErrorFormatter_BackCompat( $this->mResult );
281  }
282  $this->mResult->setErrorFormatter( $this->getErrorFormatter() );
283 
284  $this->mModuleMgr = new ApiModuleManager(
285  $this,
286  MediaWikiServices::getInstance()->getObjectFactory()
287  );
288  $this->mModuleMgr->addModules( self::$Modules, 'action' );
289  $this->mModuleMgr->addModules( $config->get( 'APIModules' ), 'action' );
290  $this->mModuleMgr->addModules( self::$Formats, 'format' );
291  $this->mModuleMgr->addModules( $config->get( 'APIFormatModules' ), 'format' );
292 
293  Hooks::run( 'ApiMain::moduleManager', [ $this->mModuleMgr ] );
294 
295  $this->mContinuationManager = null;
296  $this->mEnableWrite = $enableWrite;
297 
298  $this->mCdnMaxAge = -1; // flag for executeActionWithErrorHandling()
299  }
300 
305  public function isInternalMode() {
306  return $this->mInternalMode;
307  }
308 
314  public function getResult() {
315  return $this->mResult;
316  }
317 
322  public function lacksSameOriginSecurity() {
323  if ( $this->lacksSameOriginSecurity !== null ) {
325  }
326 
327  $request = $this->getRequest();
328 
329  // JSONP mode
330  if ( $request->getCheck( 'callback' ) ) {
331  $this->lacksSameOriginSecurity = true;
332  return true;
333  }
334 
335  // Anonymous CORS
336  if ( $request->getVal( 'origin' ) === '*' ) {
337  $this->lacksSameOriginSecurity = true;
338  return true;
339  }
340 
341  // Header to be used from XMLHTTPRequest when the request might
342  // otherwise be used for XSS.
343  if ( $request->getHeader( 'Treat-as-Untrusted' ) !== false ) {
344  $this->lacksSameOriginSecurity = true;
345  return true;
346  }
347 
348  // Allow extensions to override.
349  $this->lacksSameOriginSecurity = !Hooks::run( 'RequestHasSameOriginSecurity', [ $request ] );
351  }
352 
357  public function getErrorFormatter() {
358  return $this->mErrorFormatter;
359  }
360 
365  public function getContinuationManager() {
367  }
368 
373  public function setContinuationManager( ApiContinuationManager $manager = null ) {
374  if ( $manager !== null && $this->mContinuationManager !== null ) {
375  throw new UnexpectedValueException(
376  __METHOD__ . ': tried to set manager from ' . $manager->getSource() .
377  ' when a manager is already set from ' . $this->mContinuationManager->getSource()
378  );
379  }
380  $this->mContinuationManager = $manager;
381  }
382 
388  public function getModule() {
389  return $this->mModule;
390  }
391 
397  public function getPrinter() {
398  return $this->mPrinter;
399  }
400 
406  public function setCacheMaxAge( $maxage ) {
407  $this->setCacheControl( [
408  'max-age' => $maxage,
409  's-maxage' => $maxage
410  ] );
411  }
412 
438  public function setCacheMode( $mode ) {
439  if ( !in_array( $mode, [ 'private', 'public', 'anon-public-user-private' ] ) ) {
440  wfDebug( __METHOD__ . ": unrecognised cache mode \"$mode\"\n" );
441 
442  // Ignore for forwards-compatibility
443  return;
444  }
445 
446  if ( !User::isEveryoneAllowed( 'read' ) ) {
447  // Private wiki, only private headers
448  if ( $mode !== 'private' ) {
449  wfDebug( __METHOD__ . ": ignoring request for $mode cache mode, private wiki\n" );
450 
451  return;
452  }
453  }
454 
455  if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) {
456  // User language is used for i18n, so we don't want to publicly
457  // cache. Anons are ok, because if they have non-default language
458  // then there's an appropriate Vary header set by whatever set
459  // their non-default language.
460  wfDebug( __METHOD__ . ": downgrading cache mode 'public' to " .
461  "'anon-public-user-private' due to uselang=user\n" );
462  $mode = 'anon-public-user-private';
463  }
464 
465  wfDebug( __METHOD__ . ": setting cache mode $mode\n" );
466  $this->mCacheMode = $mode;
467  }
468 
479  public function setCacheControl( $directives ) {
480  $this->mCacheControl = $directives + $this->mCacheControl;
481  }
482 
490  public function createPrinterByName( $format ) {
491  $printer = $this->mModuleMgr->getModule( $format, 'format', /* $ignoreCache */ true );
492  if ( $printer === null ) {
493  $this->dieWithError(
494  [ 'apierror-unknownformat', wfEscapeWikiText( $format ) ], 'unknown_format'
495  );
496  }
497 
498  return $printer;
499  }
500 
504  public function execute() {
505  if ( $this->mInternalMode ) {
506  $this->executeAction();
507  } else {
509  }
510  }
511 
516  protected function executeActionWithErrorHandling() {
517  // Verify the CORS header before executing the action
518  if ( !$this->handleCORS() ) {
519  // handleCORS() has sent a 403, abort
520  return;
521  }
522 
523  // Exit here if the request method was OPTIONS
524  // (assume there will be a followup GET or POST)
525  if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
526  return;
527  }
528 
529  // In case an error occurs during data output,
530  // clear the output buffer and print just the error information
531  $obLevel = ob_get_level();
532  ob_start();
533 
534  $t = microtime( true );
535  $isError = false;
536  try {
537  $this->executeAction();
538  $runTime = microtime( true ) - $t;
539  $this->logRequest( $runTime );
540  MediaWikiServices::getInstance()->getStatsdDataFactory()->timing(
541  'api.' . $this->mModule->getModuleName() . '.executeTiming', 1000 * $runTime
542  );
543  } catch ( Exception $e ) { // @todo Remove this block when HHVM is no longer supported
544  $this->handleException( $e );
545  $this->logRequest( microtime( true ) - $t, $e );
546  $isError = true;
547  } catch ( Throwable $e ) {
548  $this->handleException( $e );
549  $this->logRequest( microtime( true ) - $t, $e );
550  $isError = true;
551  }
552 
553  // Commit DBs and send any related cookies and headers
555 
556  // Send cache headers after any code which might generate an error, to
557  // avoid sending public cache headers for errors.
558  $this->sendCacheHeaders( $isError );
559 
560  // Executing the action might have already messed with the output
561  // buffers.
562  while ( ob_get_level() > $obLevel ) {
563  ob_end_flush();
564  }
565  }
566 
573  protected function handleException( $e ) {
574  // T65145: Rollback any open database transactions
575  if ( !$e instanceof ApiUsageException ) {
576  // ApiUsageExceptions are intentional, so don't rollback if that's the case
578  }
579 
580  // Allow extra cleanup and logging
581  Hooks::run( 'ApiMain::onException', [ $this, $e ] );
582 
583  // Handle any kind of exception by outputting properly formatted error message.
584  // If this fails, an unhandled exception should be thrown so that global error
585  // handler will process and log it.
586 
587  $errCodes = $this->substituteResultWithError( $e );
588 
589  // Error results should not be cached
590  $this->setCacheMode( 'private' );
591 
592  $response = $this->getRequest()->response();
593  $headerStr = 'MediaWiki-API-Error: ' . implode( ', ', $errCodes );
594  $response->header( $headerStr );
595 
596  // Reset and print just the error message
597  ob_clean();
598 
599  // Printer may not be initialized if the extractRequestParams() fails for the main module
600  $this->createErrorPrinter();
601 
602  // Get desired HTTP code from an ApiUsageException. Don't use codes from other
603  // exception types, as they are unlikely to be intended as an HTTP code.
604  $httpCode = $e instanceof ApiUsageException ? $e->getCode() : 0;
605 
606  $failed = false;
607  try {
608  $this->printResult( $httpCode );
609  } catch ( ApiUsageException $ex ) {
610  // The error printer itself is failing. Try suppressing its request
611  // parameters and redo.
612  $failed = true;
613  $this->addWarning( 'apiwarn-errorprinterfailed' );
614  foreach ( $ex->getStatusValue()->getErrors() as $error ) {
615  try {
616  $this->mPrinter->addWarning( $error );
617  } catch ( Exception $ex2 ) { // @todo Remove this block when HHVM is no longer supported
618  // WTF?
619  $this->addWarning( $error );
620  } catch ( Throwable $ex2 ) {
621  // WTF?
622  $this->addWarning( $error );
623  }
624  }
625  }
626  if ( $failed ) {
627  $this->mPrinter = null;
628  $this->createErrorPrinter();
629  $this->mPrinter->forceDefaultParams();
630  if ( $httpCode ) {
631  $response->statusHeader( 200 ); // Reset in case the fallback doesn't want a non-200
632  }
633  $this->printResult( $httpCode );
634  }
635  }
636 
647  public static function handleApiBeforeMainException( $e ) {
648  ob_start();
649 
650  try {
651  $main = new self( RequestContext::getMain(), false );
652  $main->handleException( $e );
653  $main->logRequest( 0, $e );
654  } catch ( Exception $e2 ) { // @todo Remove this block when HHVM is no longer supported
655  // Nope, even that didn't work. Punt.
656  throw $e;
657  } catch ( Throwable $e2 ) {
658  // Nope, even that didn't work. Punt.
659  throw $e;
660  }
661 
662  // Reset cache headers
663  $main->sendCacheHeaders( true );
664 
665  ob_end_flush();
666  }
667 
682  protected function handleCORS() {
683  $originParam = $this->getParameter( 'origin' ); // defaults to null
684  if ( $originParam === null ) {
685  // No origin parameter, nothing to do
686  return true;
687  }
688 
689  $request = $this->getRequest();
690  $response = $request->response();
691 
692  $matchedOrigin = false;
693  $allowTiming = false;
694  $varyOrigin = true;
695 
696  if ( $originParam === '*' ) {
697  // Request for anonymous CORS
698  // Technically we should check for the presence of an Origin header
699  // and not process it as CORS if it's not set, but that would
700  // require us to vary on Origin for all 'origin=*' requests which
701  // we don't want to do.
702  $matchedOrigin = true;
703  $allowOrigin = '*';
704  $allowCredentials = 'false';
705  $varyOrigin = false; // No need to vary
706  } else {
707  // Non-anonymous CORS, check we allow the domain
708 
709  // Origin: header is a space-separated list of origins, check all of them
710  $originHeader = $request->getHeader( 'Origin' );
711  if ( $originHeader === false ) {
712  $origins = [];
713  } else {
714  $originHeader = trim( $originHeader );
715  $origins = preg_split( '/\s+/', $originHeader );
716  }
717 
718  if ( !in_array( $originParam, $origins ) ) {
719  // origin parameter set but incorrect
720  // Send a 403 response
721  $response->statusHeader( 403 );
722  $response->header( 'Cache-Control: no-cache' );
723  echo "'origin' parameter does not match Origin header\n";
724 
725  return false;
726  }
727 
728  $config = $this->getConfig();
729  $matchedOrigin = count( $origins ) === 1 && self::matchOrigin(
730  $originParam,
731  $config->get( 'CrossSiteAJAXdomains' ),
732  $config->get( 'CrossSiteAJAXdomainExceptions' )
733  );
734 
735  $allowOrigin = $originHeader;
736  $allowCredentials = 'true';
737  $allowTiming = $originHeader;
738  }
739 
740  if ( $matchedOrigin ) {
741  $requestedMethod = $request->getHeader( 'Access-Control-Request-Method' );
742  $preflight = $request->getMethod() === 'OPTIONS' && $requestedMethod !== false;
743  if ( $preflight ) {
744  // This is a CORS preflight request
745  if ( $requestedMethod !== 'POST' && $requestedMethod !== 'GET' ) {
746  // If method is not a case-sensitive match, do not set any additional headers and terminate.
747  $response->header( 'MediaWiki-CORS-Rejection: Unsupported method requested in preflight' );
748  return true;
749  }
750  // We allow the actual request to send the following headers
751  $requestedHeaders = $request->getHeader( 'Access-Control-Request-Headers' );
752  if ( $requestedHeaders !== false ) {
753  if ( !self::matchRequestedHeaders( $requestedHeaders ) ) {
754  $response->header( 'MediaWiki-CORS-Rejection: Unsupported header requested in preflight' );
755  return true;
756  }
757  $response->header( 'Access-Control-Allow-Headers: ' . $requestedHeaders );
758  }
759 
760  // We only allow the actual request to be GET or POST
761  $response->header( 'Access-Control-Allow-Methods: POST, GET' );
762  } elseif ( $request->getMethod() !== 'POST' && $request->getMethod() !== 'GET' ) {
763  // Unsupported non-preflight method, don't handle it as CORS
764  $response->header(
765  'MediaWiki-CORS-Rejection: Unsupported method for simple request or actual request'
766  );
767  return true;
768  }
769 
770  $response->header( "Access-Control-Allow-Origin: $allowOrigin" );
771  $response->header( "Access-Control-Allow-Credentials: $allowCredentials" );
772  // https://www.w3.org/TR/resource-timing/#timing-allow-origin
773  if ( $allowTiming !== false ) {
774  $response->header( "Timing-Allow-Origin: $allowTiming" );
775  }
776 
777  if ( !$preflight ) {
778  $response->header(
779  'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag, '
780  . 'MediaWiki-Login-Suppressed'
781  );
782  }
783  } else {
784  $response->header( 'MediaWiki-CORS-Rejection: Origin mismatch' );
785  }
786 
787  if ( $varyOrigin ) {
788  $this->getOutput()->addVaryHeader( 'Origin' );
789  }
790 
791  return true;
792  }
793 
802  protected static function matchOrigin( $value, $rules, $exceptions ) {
803  foreach ( $rules as $rule ) {
804  if ( preg_match( self::wildcardToRegex( $rule ), $value ) ) {
805  // Rule matches, check exceptions
806  foreach ( $exceptions as $exc ) {
807  if ( preg_match( self::wildcardToRegex( $exc ), $value ) ) {
808  return false;
809  }
810  }
811 
812  return true;
813  }
814  }
815 
816  return false;
817  }
818 
826  protected static function matchRequestedHeaders( $requestedHeaders ) {
827  if ( trim( $requestedHeaders ) === '' ) {
828  return true;
829  }
830  $requestedHeaders = explode( ',', $requestedHeaders );
831  $allowedAuthorHeaders = array_flip( [
832  /* simple headers (see spec) */
833  'accept',
834  'accept-language',
835  'content-language',
836  'content-type',
837  /* non-authorable headers in XHR, which are however requested by some UAs */
838  'accept-encoding',
839  'dnt',
840  'origin',
841  /* MediaWiki whitelist */
842  'user-agent',
843  'api-user-agent',
844  ] );
845  foreach ( $requestedHeaders as $rHeader ) {
846  $rHeader = strtolower( trim( $rHeader ) );
847  if ( !isset( $allowedAuthorHeaders[$rHeader] ) ) {
848  LoggerFactory::getInstance( 'api-warning' )->warning(
849  'CORS preflight failed on requested header: {header}', [
850  'header' => $rHeader
851  ]
852  );
853  return false;
854  }
855  }
856  return true;
857  }
858 
867  protected static function wildcardToRegex( $wildcard ) {
868  $wildcard = preg_quote( $wildcard, '/' );
869  $wildcard = str_replace(
870  [ '\*', '\?' ],
871  [ '.*?', '.' ],
872  $wildcard
873  );
874 
875  return "/^https?:\/\/$wildcard$/";
876  }
877 
883  protected function sendCacheHeaders( $isError ) {
884  $response = $this->getRequest()->response();
885  $out = $this->getOutput();
886 
887  $out->addVaryHeader( 'Treat-as-Untrusted' );
888 
889  $config = $this->getConfig();
890 
891  if ( $config->get( 'VaryOnXFP' ) ) {
892  $out->addVaryHeader( 'X-Forwarded-Proto' );
893  }
894 
895  if ( !$isError && $this->mModule &&
896  ( $this->getRequest()->getMethod() === 'GET' || $this->getRequest()->getMethod() === 'HEAD' )
897  ) {
898  $etag = $this->mModule->getConditionalRequestData( 'etag' );
899  if ( $etag !== null ) {
900  $response->header( "ETag: $etag" );
901  }
902  $lastMod = $this->mModule->getConditionalRequestData( 'last-modified' );
903  if ( $lastMod !== null ) {
904  $response->header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822, $lastMod ) );
905  }
906  }
907 
908  // The logic should be:
909  // $this->mCacheControl['max-age'] is set?
910  // Use it, the module knows better than our guess.
911  // !$this->mModule || $this->mModule->isWriteMode(), and mCacheMode is private?
912  // Use 0 because we can guess caching is probably the wrong thing to do.
913  // Use $this->getParameter( 'maxage' ), which already defaults to 0.
914  $maxage = 0;
915  if ( isset( $this->mCacheControl['max-age'] ) ) {
916  $maxage = $this->mCacheControl['max-age'];
917  } elseif ( ( $this->mModule && !$this->mModule->isWriteMode() ) ||
918  $this->mCacheMode !== 'private'
919  ) {
920  $maxage = $this->getParameter( 'maxage' );
921  }
922  $privateCache = 'private, must-revalidate, max-age=' . $maxage;
923 
924  if ( $this->mCacheMode == 'private' ) {
925  $response->header( "Cache-Control: $privateCache" );
926  return;
927  }
928 
929  if ( $this->mCacheMode == 'anon-public-user-private' ) {
930  $out->addVaryHeader( 'Cookie' );
931  $response->header( $out->getVaryHeader() );
932  if ( MediaWiki\Session\SessionManager::getGlobalSession()->isPersistent() ) {
933  // Logged in or otherwise has session (e.g. anonymous users who have edited)
934  // Mark request private
935  $response->header( "Cache-Control: $privateCache" );
936 
937  return;
938  } // else anonymous, send public headers below
939  }
940 
941  // Send public headers
942  $response->header( $out->getVaryHeader() );
943 
944  // If nobody called setCacheMaxAge(), use the (s)maxage parameters
945  if ( !isset( $this->mCacheControl['s-maxage'] ) ) {
946  $this->mCacheControl['s-maxage'] = $this->getParameter( 'smaxage' );
947  }
948  if ( !isset( $this->mCacheControl['max-age'] ) ) {
949  $this->mCacheControl['max-age'] = $this->getParameter( 'maxage' );
950  }
951 
952  if ( !$this->mCacheControl['s-maxage'] && !$this->mCacheControl['max-age'] ) {
953  // Public cache not requested
954  // Sending a Vary header in this case is harmless, and protects us
955  // against conditional calls of setCacheMaxAge().
956  $response->header( "Cache-Control: $privateCache" );
957 
958  return;
959  }
960 
961  $this->mCacheControl['public'] = true;
962 
963  // Send an Expires header
964  $maxAge = min( $this->mCacheControl['s-maxage'], $this->mCacheControl['max-age'] );
965  $expiryUnixTime = ( $maxAge == 0 ? 1 : time() + $maxAge );
966  $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822, $expiryUnixTime ) );
967 
968  // Construct the Cache-Control header
969  $ccHeader = '';
970  $separator = '';
971  foreach ( $this->mCacheControl as $name => $value ) {
972  if ( is_bool( $value ) ) {
973  if ( $value ) {
974  $ccHeader .= $separator . $name;
975  $separator = ', ';
976  }
977  } else {
978  $ccHeader .= $separator . "$name=$value";
979  $separator = ', ';
980  }
981  }
982 
983  $response->header( "Cache-Control: $ccHeader" );
984  }
985 
989  private function createErrorPrinter() {
990  if ( !isset( $this->mPrinter ) ) {
991  $value = $this->getRequest()->getVal( 'format', self::API_DEFAULT_FORMAT );
992  if ( !$this->mModuleMgr->isDefined( $value, 'format' ) ) {
993  $value = self::API_DEFAULT_FORMAT;
994  }
995  $this->mPrinter = $this->createPrinterByName( $value );
996  }
997 
998  // Printer may not be able to handle errors. This is particularly
999  // likely if the module returns something for getCustomPrinter().
1000  if ( !$this->mPrinter->canPrintErrors() ) {
1001  $this->mPrinter = $this->createPrinterByName( self::API_DEFAULT_FORMAT );
1002  }
1003  }
1004 
1020  protected function errorMessagesFromException( $e, $type = 'error' ) {
1021  $messages = [];
1022  if ( $e instanceof ApiUsageException ) {
1023  foreach ( $e->getStatusValue()->getErrorsByType( $type ) as $error ) {
1024  $messages[] = ApiMessage::create( $error );
1025  }
1026  } elseif ( $type !== 'error' ) {
1027  // None of the rest have any messages for non-error types
1028  } else {
1029  // Something is seriously wrong
1030  $config = $this->getConfig();
1031  // TODO: Avoid embedding arbitrary class names in the error code.
1032  $class = preg_replace( '#^Wikimedia\\\Rdbms\\\#', '', get_class( $e ) );
1033  $code = 'internal_api_error_' . $class;
1034  $data = [ 'errorclass' => get_class( $e ) ];
1035  if ( $config->get( 'ShowExceptionDetails' ) ) {
1036  if ( $e instanceof ILocalizedException ) {
1037  $msg = $e->getMessageObject();
1038  } elseif ( $e instanceof MessageSpecifier ) {
1039  $msg = Message::newFromSpecifier( $e );
1040  } else {
1041  $msg = wfEscapeWikiText( $e->getMessage() );
1042  }
1043  $params = [ 'apierror-exceptioncaught', WebRequest::getRequestId(), $msg ];
1044  } else {
1045  $params = [ 'apierror-exceptioncaughttype', WebRequest::getRequestId(), get_class( $e ) ];
1046  }
1047 
1048  $messages[] = ApiMessage::create( $params, $code, $data );
1049  }
1050  return $messages;
1051  }
1052 
1058  protected function substituteResultWithError( $e ) {
1059  $result = $this->getResult();
1060  $formatter = $this->getErrorFormatter();
1061  $config = $this->getConfig();
1062  $errorCodes = [];
1063 
1064  // Remember existing warnings and errors across the reset
1065  $errors = $result->getResultData( [ 'errors' ] );
1066  $warnings = $result->getResultData( [ 'warnings' ] );
1067  $result->reset();
1068  if ( $warnings !== null ) {
1069  $result->addValue( null, 'warnings', $warnings, ApiResult::NO_SIZE_CHECK );
1070  }
1071  if ( $errors !== null ) {
1072  $result->addValue( null, 'errors', $errors, ApiResult::NO_SIZE_CHECK );
1073 
1074  // Collect the copied error codes for the return value
1075  foreach ( $errors as $error ) {
1076  if ( isset( $error['code'] ) ) {
1077  $errorCodes[$error['code']] = true;
1078  }
1079  }
1080  }
1081 
1082  // Add errors from the exception
1083  $modulePath = $e instanceof ApiUsageException ? $e->getModulePath() : null;
1084  foreach ( $this->errorMessagesFromException( $e, 'error' ) as $msg ) {
1085  if ( ApiErrorFormatter::isValidApiCode( $msg->getApiCode() ) ) {
1086  $errorCodes[$msg->getApiCode()] = true;
1087  } else {
1088  LoggerFactory::getInstance( 'api-warning' )->error( 'Invalid API error code "{code}"', [
1089  'code' => $msg->getApiCode(),
1090  'exception' => $e,
1091  ] );
1092  $errorCodes['<invalid-code>'] = true;
1093  }
1094  $formatter->addError( $modulePath, $msg );
1095  }
1096  foreach ( $this->errorMessagesFromException( $e, 'warning' ) as $msg ) {
1097  $formatter->addWarning( $modulePath, $msg );
1098  }
1099 
1100  // Add additional data. Path depends on whether we're in BC mode or not.
1101  // Data depends on the type of exception.
1102  if ( $formatter instanceof ApiErrorFormatter_BackCompat ) {
1103  $path = [ 'error' ];
1104  } else {
1105  $path = null;
1106  }
1107  if ( $e instanceof ApiUsageException ) {
1108  $link = wfExpandUrl( wfScript( 'api' ) );
1109  $result->addContentValue(
1110  $path,
1111  'docref',
1112  trim(
1113  $this->msg( 'api-usage-docref', $link )->inLanguage( $formatter->getLanguage() )->text()
1114  . ' '
1115  . $this->msg( 'api-usage-mailinglist-ref' )->inLanguage( $formatter->getLanguage() )->text()
1116  )
1117  );
1118  } elseif ( $config->get( 'ShowExceptionDetails' ) ) {
1119  $result->addContentValue(
1120  $path,
1121  'trace',
1122  $this->msg( 'api-exception-trace',
1123  get_class( $e ),
1124  $e->getFile(),
1125  $e->getLine(),
1127  )->inLanguage( $formatter->getLanguage() )->text()
1128  );
1129  }
1130 
1131  // Add the id and such
1132  $this->addRequestedFields( [ 'servedby' ] );
1133 
1134  return array_keys( $errorCodes );
1135  }
1136 
1142  protected function addRequestedFields( $force = [] ) {
1143  $result = $this->getResult();
1144 
1145  $requestid = $this->getParameter( 'requestid' );
1146  if ( $requestid !== null ) {
1147  $result->addValue( null, 'requestid', $requestid, ApiResult::NO_SIZE_CHECK );
1148  }
1149 
1150  if ( $this->getConfig()->get( 'ShowHostnames' ) && (
1151  in_array( 'servedby', $force, true ) || $this->getParameter( 'servedby' )
1152  ) ) {
1153  $result->addValue( null, 'servedby', wfHostname(), ApiResult::NO_SIZE_CHECK );
1154  }
1155 
1156  if ( $this->getParameter( 'curtimestamp' ) ) {
1157  $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601 ), ApiResult::NO_SIZE_CHECK );
1158  }
1159 
1160  if ( $this->getParameter( 'responselanginfo' ) ) {
1161  $result->addValue( null, 'uselang', $this->getLanguage()->getCode(),
1163  $result->addValue( null, 'errorlang', $this->getErrorFormatter()->getLanguage()->getCode(),
1165  }
1166  }
1167 
1172  protected function setupExecuteAction() {
1173  $this->addRequestedFields();
1174 
1175  $params = $this->extractRequestParams();
1176  $this->mAction = $params['action'];
1177 
1178  return $params;
1179  }
1180 
1187  protected function setupModule() {
1188  // Instantiate the module requested by the user
1189  $module = $this->mModuleMgr->getModule( $this->mAction, 'action' );
1190  if ( $module === null ) {
1191  // Probably can't happen
1192  // @codeCoverageIgnoreStart
1193  $this->dieWithError(
1194  [ 'apierror-unknownaction', wfEscapeWikiText( $this->mAction ) ], 'unknown_action'
1195  );
1196  // @codeCoverageIgnoreEnd
1197  }
1198  $moduleParams = $module->extractRequestParams();
1199 
1200  // Check token, if necessary
1201  if ( $module->needsToken() === true ) {
1202  throw new MWException(
1203  "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
1204  'See documentation for ApiBase::needsToken for details.'
1205  );
1206  }
1207  if ( $module->needsToken() ) {
1208  if ( !$module->mustBePosted() ) {
1209  throw new MWException(
1210  "Module '{$module->getModuleName()}' must require POST to use tokens."
1211  );
1212  }
1213 
1214  if ( !isset( $moduleParams['token'] ) ) {
1215  // Probably can't happen
1216  // @codeCoverageIgnoreStart
1217  $module->dieWithError( [ 'apierror-missingparam', 'token' ] );
1218  // @codeCoverageIgnoreEnd
1219  }
1220 
1221  $module->requirePostedParameters( [ 'token' ] );
1222 
1223  if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) {
1224  $module->dieWithError( 'apierror-badtoken' );
1225  }
1226  }
1227 
1228  return $module;
1229  }
1230 
1234  private function getMaxLag() {
1235  $dbLag = MediaWikiServices::getInstance()->getDBLoadBalancer()->getMaxLag();
1236  $lagInfo = [
1237  'host' => $dbLag[0],
1238  'lag' => $dbLag[1],
1239  'type' => 'db'
1240  ];
1241 
1242  $jobQueueLagFactor = $this->getConfig()->get( 'JobQueueIncludeInMaxLagFactor' );
1243  if ( $jobQueueLagFactor ) {
1244  // Turn total number of jobs into seconds by using the configured value
1245  $totalJobs = array_sum( JobQueueGroup::singleton()->getQueueSizes() );
1246  $jobQueueLag = $totalJobs / (float)$jobQueueLagFactor;
1247  if ( $jobQueueLag > $lagInfo['lag'] ) {
1248  $lagInfo = [
1249  'host' => wfHostname(), // XXX: Is there a better value that could be used?
1250  'lag' => $jobQueueLag,
1251  'type' => 'jobqueue',
1252  'jobs' => $totalJobs,
1253  ];
1254  }
1255  }
1256 
1257  Hooks::runWithoutAbort( 'ApiMaxLagInfo', [ &$lagInfo ] );
1258 
1259  return $lagInfo;
1260  }
1261 
1268  protected function checkMaxLag( $module, $params ) {
1269  if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
1270  $maxLag = $params['maxlag'];
1271  $lagInfo = $this->getMaxLag();
1272  if ( $lagInfo['lag'] > $maxLag ) {
1273  $response = $this->getRequest()->response();
1274 
1275  $response->header( 'Retry-After: ' . max( (int)$maxLag, 5 ) );
1276  $response->header( 'X-Database-Lag: ' . (int)$lagInfo['lag'] );
1277 
1278  if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
1279  $this->dieWithError(
1280  [ 'apierror-maxlag', $lagInfo['lag'], $lagInfo['host'] ],
1281  'maxlag',
1282  $lagInfo
1283  );
1284  }
1285 
1286  $this->dieWithError( [ 'apierror-maxlag-generic', $lagInfo['lag'] ], 'maxlag', $lagInfo );
1287  }
1288  }
1289 
1290  return true;
1291  }
1292 
1314  protected function checkConditionalRequestHeaders( $module ) {
1315  if ( $this->mInternalMode ) {
1316  // No headers to check in internal mode
1317  return true;
1318  }
1319 
1320  if ( $this->getRequest()->getMethod() !== 'GET' && $this->getRequest()->getMethod() !== 'HEAD' ) {
1321  // Don't check POSTs
1322  return true;
1323  }
1324 
1325  $return304 = false;
1326 
1327  $ifNoneMatch = array_diff(
1328  $this->getRequest()->getHeader( 'If-None-Match', WebRequest::GETHEADER_LIST ) ?: [],
1329  [ '' ]
1330  );
1331  if ( $ifNoneMatch ) {
1332  if ( $ifNoneMatch === [ '*' ] ) {
1333  // API responses always "exist"
1334  $etag = '*';
1335  } else {
1336  $etag = $module->getConditionalRequestData( 'etag' );
1337  }
1338  }
1339  if ( $ifNoneMatch && $etag !== null ) {
1340  $test = substr( $etag, 0, 2 ) === 'W/' ? substr( $etag, 2 ) : $etag;
1341  $match = array_map( function ( $s ) {
1342  return substr( $s, 0, 2 ) === 'W/' ? substr( $s, 2 ) : $s;
1343  }, $ifNoneMatch );
1344  $return304 = in_array( $test, $match, true );
1345  } else {
1346  $value = trim( $this->getRequest()->getHeader( 'If-Modified-Since' ) );
1347 
1348  // Some old browsers sends sizes after the date, like this:
1349  // Wed, 20 Aug 2003 06:51:19 GMT; length=5202
1350  // Ignore that.
1351  $i = strpos( $value, ';' );
1352  if ( $i !== false ) {
1353  $value = trim( substr( $value, 0, $i ) );
1354  }
1355 
1356  if ( $value !== '' ) {
1357  try {
1358  $ts = new MWTimestamp( $value );
1359  if (
1360  // RFC 7231 IMF-fixdate
1361  $ts->getTimestamp( TS_RFC2822 ) === $value ||
1362  // RFC 850
1363  $ts->format( 'l, d-M-y H:i:s' ) . ' GMT' === $value ||
1364  // asctime (with and without space-padded day)
1365  $ts->format( 'D M j H:i:s Y' ) === $value ||
1366  $ts->format( 'D M j H:i:s Y' ) === $value
1367  ) {
1368  $config = $this->getConfig();
1369  $lastMod = $module->getConditionalRequestData( 'last-modified' );
1370  if ( $lastMod !== null ) {
1371  // Mix in some MediaWiki modification times
1372  $modifiedTimes = [
1373  'page' => $lastMod,
1374  'user' => $this->getUser()->getTouched(),
1375  'epoch' => $config->get( 'CacheEpoch' ),
1376  ];
1377 
1378  if ( $config->get( 'UseCdn' ) ) {
1379  // T46570: the core page itself may not change, but resources might
1380  $modifiedTimes['sepoch'] = wfTimestamp(
1381  TS_MW, time() - $config->get( 'CdnMaxAge' )
1382  );
1383  }
1384  Hooks::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this->getOutput() ] );
1385  $lastMod = max( $modifiedTimes );
1386  $return304 = wfTimestamp( TS_MW, $lastMod ) <= $ts->getTimestamp( TS_MW );
1387  }
1388  }
1389  } catch ( TimestampException $e ) {
1390  // Invalid timestamp, ignore it
1391  }
1392  }
1393  }
1394 
1395  if ( $return304 ) {
1396  $this->getRequest()->response()->statusHeader( 304 );
1397 
1398  // Avoid outputting the compressed representation of a zero-length body
1399  Wikimedia\suppressWarnings();
1400  ini_set( 'zlib.output_compression', 0 );
1401  Wikimedia\restoreWarnings();
1403 
1404  return false;
1405  }
1406 
1407  return true;
1408  }
1409 
1414  protected function checkExecutePermissions( $module ) {
1415  $user = $this->getUser();
1416  if ( $module->isReadMode() && !$this->getPermissionManager()->isEveryoneAllowed( 'read' ) &&
1417  !$this->getPermissionManager()->userHasRight( $user, 'read' )
1418  ) {
1419  $this->dieWithError( 'apierror-readapidenied' );
1420  }
1421 
1422  if ( $module->isWriteMode() ) {
1423  if ( !$this->mEnableWrite ) {
1424  $this->dieWithError( 'apierror-noapiwrite' );
1425  } elseif ( !$this->getPermissionManager()->userHasRight( $user, 'writeapi' ) ) {
1426  $this->dieWithError( 'apierror-writeapidenied' );
1427  } elseif ( $this->getRequest()->getHeader( 'Promise-Non-Write-API-Action' ) ) {
1428  $this->dieWithError( 'apierror-promised-nonwrite-api' );
1429  }
1430 
1431  $this->checkReadOnly( $module );
1432  }
1433 
1434  // Allow extensions to stop execution for arbitrary reasons.
1435  $message = 'hookaborted';
1436  if ( !Hooks::run( 'ApiCheckCanExecute', [ $module, $user, &$message ] ) ) {
1437  $this->dieWithError( $message );
1438  }
1439  }
1440 
1445  protected function checkReadOnly( $module ) {
1446  if ( wfReadOnly() ) {
1447  $this->dieReadOnly();
1448  }
1449 
1450  if ( $module->isWriteMode()
1451  && $this->getUser()->isBot()
1452  && MediaWikiServices::getInstance()->getDBLoadBalancer()->getServerCount() > 1
1453  ) {
1454  $this->checkBotReadOnly();
1455  }
1456  }
1457 
1461  private function checkBotReadOnly() {
1462  // Figure out how many servers have passed the lag threshold
1463  $numLagged = 0;
1464  $lagLimit = $this->getConfig()->get( 'APIMaxLagThreshold' );
1465  $laggedServers = [];
1466  $loadBalancer = MediaWikiServices::getInstance()->getDBLoadBalancer();
1467  foreach ( $loadBalancer->getLagTimes() as $serverIndex => $lag ) {
1468  if ( $lag > $lagLimit ) {
1469  ++$numLagged;
1470  $laggedServers[] = $loadBalancer->getServerName( $serverIndex ) . " ({$lag}s)";
1471  }
1472  }
1473 
1474  // If a majority of replica DBs are too lagged then disallow writes
1475  $replicaCount = $loadBalancer->getServerCount() - 1;
1476  if ( $numLagged >= ceil( $replicaCount / 2 ) ) {
1477  $laggedServers = implode( ', ', $laggedServers );
1478  wfDebugLog(
1479  'api-readonly', // Deprecate this channel in favor of api-warning?
1480  "Api request failed as read only because the following DBs are lagged: $laggedServers"
1481  );
1482  LoggerFactory::getInstance( 'api-warning' )->warning(
1483  "Api request failed as read only because the following DBs are lagged: {laggeddbs}", [
1484  'laggeddbs' => $laggedServers,
1485  ]
1486  );
1487 
1488  $this->dieWithError(
1489  'readonly_lag',
1490  'readonly',
1491  [ 'readonlyreason' => "Waiting for $numLagged lagged database(s)" ]
1492  );
1493  }
1494  }
1495 
1500  protected function checkAsserts( $params ) {
1501  if ( isset( $params['assert'] ) ) {
1502  $user = $this->getUser();
1503  switch ( $params['assert'] ) {
1504  case 'user':
1505  if ( $user->isAnon() ) {
1506  $this->dieWithError( 'apierror-assertuserfailed' );
1507  }
1508  break;
1509  case 'bot':
1510  if ( !$this->getPermissionManager()->userHasRight( $user, 'bot' ) ) {
1511  $this->dieWithError( 'apierror-assertbotfailed' );
1512  }
1513  break;
1514  }
1515  }
1516  if ( isset( $params['assertuser'] ) ) {
1517  $assertUser = User::newFromName( $params['assertuser'], false );
1518  if ( !$assertUser || !$this->getUser()->equals( $assertUser ) ) {
1519  $this->dieWithError(
1520  [ 'apierror-assertnameduserfailed', wfEscapeWikiText( $params['assertuser'] ) ]
1521  );
1522  }
1523  }
1524  }
1525 
1531  protected function setupExternalResponse( $module, $params ) {
1532  $validMethods = [ 'GET', 'HEAD', 'POST', 'OPTIONS' ];
1533  $request = $this->getRequest();
1534 
1535  if ( !in_array( $request->getMethod(), $validMethods ) ) {
1536  $this->dieWithError( 'apierror-invalidmethod', null, null, 405 );
1537  }
1538 
1539  if ( !$request->wasPosted() && $module->mustBePosted() ) {
1540  // Module requires POST. GET request might still be allowed
1541  // if $wgDebugApi is true, otherwise fail.
1542  $this->dieWithErrorOrDebug( [ 'apierror-mustbeposted', $this->mAction ] );
1543  }
1544 
1545  if ( $request->wasPosted() && !$request->getHeader( 'Content-Type' ) ) {
1546  $this->addDeprecation(
1547  'apiwarn-deprecation-post-without-content-type', 'post-without-content-type'
1548  );
1549  }
1550 
1551  // See if custom printer is used
1552  $this->mPrinter = $module->getCustomPrinter();
1553  if ( is_null( $this->mPrinter ) ) {
1554  // Create an appropriate printer
1555  $this->mPrinter = $this->createPrinterByName( $params['format'] );
1556  }
1557 
1558  if ( $request->getProtocol() === 'http' && (
1559  $request->getSession()->shouldForceHTTPS() ||
1560  ( $this->getUser()->isLoggedIn() &&
1561  $this->getUser()->requiresHTTPS() )
1562  ) ) {
1563  $this->addDeprecation( 'apiwarn-deprecation-httpsexpected', 'https-expected' );
1564  }
1565  }
1566 
1570  protected function executeAction() {
1571  $params = $this->setupExecuteAction();
1572 
1573  // Check asserts early so e.g. errors in parsing a module's parameters due to being
1574  // logged out don't override the client's intended "am I logged in?" check.
1575  $this->checkAsserts( $params );
1576 
1577  $module = $this->setupModule();
1578  $this->mModule = $module;
1579 
1580  if ( !$this->mInternalMode ) {
1581  $this->setRequestExpectations( $module );
1582  }
1583 
1584  $this->checkExecutePermissions( $module );
1585 
1586  if ( !$this->checkMaxLag( $module, $params ) ) {
1587  return;
1588  }
1589 
1590  if ( !$this->checkConditionalRequestHeaders( $module ) ) {
1591  return;
1592  }
1593 
1594  if ( !$this->mInternalMode ) {
1595  $this->setupExternalResponse( $module, $params );
1596  }
1597 
1598  $module->execute();
1599  Hooks::run( 'APIAfterExecute', [ &$module ] );
1600 
1601  $this->reportUnusedParams();
1602 
1603  if ( !$this->mInternalMode ) {
1605 
1606  $this->printResult();
1607  }
1608  }
1609 
1614  protected function setRequestExpectations( ApiBase $module ) {
1615  $limits = $this->getConfig()->get( 'TrxProfilerLimits' );
1616  $trxProfiler = Profiler::instance()->getTransactionProfiler();
1617  $trxProfiler->setLogger( LoggerFactory::getInstance( 'DBPerformance' ) );
1618  if ( $this->getRequest()->hasSafeMethod() ) {
1619  $trxProfiler->setExpectations( $limits['GET'], __METHOD__ );
1620  } elseif ( $this->getRequest()->wasPosted() && !$module->isWriteMode() ) {
1621  $trxProfiler->setExpectations( $limits['POST-nonwrite'], __METHOD__ );
1622  $this->getRequest()->markAsSafeRequest();
1623  } else {
1624  $trxProfiler->setExpectations( $limits['POST'], __METHOD__ );
1625  }
1626  }
1627 
1633  protected function logRequest( $time, $e = null ) {
1634  $request = $this->getRequest();
1635 
1636  $logCtx = [
1637  // https://gerrit.wikimedia.org/r/plugins/gitiles/mediawiki/event-schemas/+/master/jsonschema/mediawiki/api/request
1638  '$schema' => '/mediawiki/api/request/0.0.1',
1639  'meta' => [
1640  'request_id' => WebRequest::getRequestId(),
1641  'id' => UIDGenerator::newUUIDv4(),
1642  'dt' => wfTimestamp( TS_ISO_8601 ),
1643  'domain' => $this->getConfig()->get( 'ServerName' ),
1644  // If using the EventBus extension (as intended) with this log channel,
1645  // this stream name will map to a Kafka topic.
1646  'stream' => 'mediawiki.api-request'
1647  ],
1648  'http' => [
1649  'method' => $request->getMethod(),
1650  'client_ip' => $request->getIP()
1651  ],
1652  'database' => WikiMap::getCurrentWikiDbDomain()->getId(),
1653  'backend_time_ms' => (int)round( $time * 1000 ),
1654  ];
1655 
1656  // If set, these headers will be logged in http.request_headers.
1657  $httpRequestHeadersToLog = [ 'accept-language', 'referer', 'user-agent' ];
1658  foreach ( $httpRequestHeadersToLog as $header ) {
1659  if ( $request->getHeader( $header ) ) {
1660  // Set the header in http.request_headers
1661  $logCtx['http']['request_headers'][$header] = $request->getHeader( $header );
1662  }
1663  }
1664 
1665  if ( $e ) {
1666  $logCtx['api_error_codes'] = [];
1667  foreach ( $this->errorMessagesFromException( $e ) as $msg ) {
1668  $logCtx['api_error_codes'][] = $msg->getApiCode();
1669  }
1670  }
1671 
1672  // Construct space separated message for 'api' log channel
1673  $msg = "API {$request->getMethod()} " .
1674  wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
1675  " {$logCtx['http']['client_ip']} " .
1676  "T={$logCtx['backend_time_ms']}ms";
1677 
1678  $sensitive = array_flip( $this->getSensitiveParams() );
1679  foreach ( $this->getParamsUsed() as $name ) {
1680  $value = $request->getVal( $name );
1681  if ( $value === null ) {
1682  continue;
1683  }
1684 
1685  if ( isset( $sensitive[$name] ) ) {
1686  $value = '[redacted]';
1687  $encValue = '[redacted]';
1688  } elseif ( strlen( $value ) > 256 ) {
1689  $value = substr( $value, 0, 256 );
1690  $encValue = $this->encodeRequestLogValue( $value ) . '[...]';
1691  } else {
1692  $encValue = $this->encodeRequestLogValue( $value );
1693  }
1694 
1695  $logCtx['params'][$name] = $value;
1696  $msg .= " {$name}={$encValue}";
1697  }
1698 
1699  // Log an unstructured message to the api channel.
1700  wfDebugLog( 'api', $msg, 'private' );
1701 
1702  // The api-request channel a structured data log channel.
1703  wfDebugLog( 'api-request', '', 'private', $logCtx );
1704  }
1705 
1711  protected function encodeRequestLogValue( $s ) {
1712  static $table = [];
1713  if ( !$table ) {
1714  $chars = ';@$!*(),/:';
1715  $numChars = strlen( $chars );
1716  for ( $i = 0; $i < $numChars; $i++ ) {
1717  $table[rawurlencode( $chars[$i] )] = $chars[$i];
1718  }
1719  }
1720 
1721  return strtr( rawurlencode( $s ), $table );
1722  }
1723 
1728  protected function getParamsUsed() {
1729  return array_keys( $this->mParamsUsed );
1730  }
1731 
1736  public function markParamsUsed( $params ) {
1737  $this->mParamsUsed += array_fill_keys( (array)$params, true );
1738  }
1739 
1745  protected function getSensitiveParams() {
1746  return array_keys( $this->mParamsSensitive );
1747  }
1748 
1754  public function markParamsSensitive( $params ) {
1755  $this->mParamsSensitive += array_fill_keys( (array)$params, true );
1756  }
1757 
1764  public function getVal( $name, $default = null ) {
1765  $this->mParamsUsed[$name] = true;
1766 
1767  $ret = $this->getRequest()->getVal( $name );
1768  if ( $ret === null ) {
1769  if ( $this->getRequest()->getArray( $name ) !== null ) {
1770  // See T12262 for why we don't just implode( '|', ... ) the
1771  // array.
1772  $this->addWarning( [ 'apiwarn-unsupportedarray', $name ] );
1773  }
1774  $ret = $default;
1775  }
1776  return $ret;
1777  }
1778 
1785  public function getCheck( $name ) {
1786  return $this->getVal( $name, null ) !== null;
1787  }
1788 
1796  public function getUpload( $name ) {
1797  $this->mParamsUsed[$name] = true;
1798 
1799  return $this->getRequest()->getUpload( $name );
1800  }
1801 
1806  protected function reportUnusedParams() {
1807  $paramsUsed = $this->getParamsUsed();
1808  $allParams = $this->getRequest()->getValueNames();
1809 
1810  if ( !$this->mInternalMode ) {
1811  // Printer has not yet executed; don't warn that its parameters are unused
1812  $printerParams = $this->mPrinter->encodeParamName(
1813  array_keys( $this->mPrinter->getFinalParams() ?: [] )
1814  );
1815  $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1816  } else {
1817  $unusedParams = array_diff( $allParams, $paramsUsed );
1818  }
1819 
1820  if ( count( $unusedParams ) ) {
1821  $this->addWarning( [
1822  'apierror-unrecognizedparams',
1823  Message::listParam( array_map( 'wfEscapeWikiText', $unusedParams ), 'comma' ),
1824  count( $unusedParams )
1825  ] );
1826  }
1827  }
1828 
1834  protected function printResult( $httpCode = 0 ) {
1835  if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
1836  $this->addWarning( 'apiwarn-wgdebugapi' );
1837  }
1838 
1839  $printer = $this->mPrinter;
1840  $printer->initPrinter( false );
1841  if ( $httpCode ) {
1842  $printer->setHttpStatus( $httpCode );
1843  }
1844  $printer->execute();
1845  $printer->closePrinter();
1846  }
1847 
1851  public function isReadMode() {
1852  return false;
1853  }
1854 
1860  public function getAllowedParams() {
1861  return [
1862  'action' => [
1863  ApiBase::PARAM_DFLT => 'help',
1864  ApiBase::PARAM_TYPE => 'submodule',
1865  ],
1866  'format' => [
1868  ApiBase::PARAM_TYPE => 'submodule',
1869  ],
1870  'maxlag' => [
1871  ApiBase::PARAM_TYPE => 'integer'
1872  ],
1873  'smaxage' => [
1874  ApiBase::PARAM_TYPE => 'integer',
1875  ApiBase::PARAM_DFLT => 0
1876  ],
1877  'maxage' => [
1878  ApiBase::PARAM_TYPE => 'integer',
1879  ApiBase::PARAM_DFLT => 0
1880  ],
1881  'assert' => [
1882  ApiBase::PARAM_TYPE => [ 'user', 'bot' ]
1883  ],
1884  'assertuser' => [
1885  ApiBase::PARAM_TYPE => 'user',
1886  ],
1887  'requestid' => null,
1888  'servedby' => false,
1889  'curtimestamp' => false,
1890  'responselanginfo' => false,
1891  'origin' => null,
1892  'uselang' => [
1894  ],
1895  'errorformat' => [
1896  ApiBase::PARAM_TYPE => [ 'plaintext', 'wikitext', 'html', 'raw', 'none', 'bc' ],
1897  ApiBase::PARAM_DFLT => 'bc',
1898  ],
1899  'errorlang' => [
1900  ApiBase::PARAM_DFLT => 'uselang',
1901  ],
1902  'errorsuselocal' => [
1903  ApiBase::PARAM_DFLT => false,
1904  ],
1905  ];
1906  }
1907 
1909  protected function getExamplesMessages() {
1910  return [
1911  'action=help'
1912  => 'apihelp-help-example-main',
1913  'action=help&recursivesubmodules=1'
1914  => 'apihelp-help-example-recursive',
1915  ];
1916  }
1917 
1922  public function modifyHelp( array &$help, array $options, array &$tocData ) {
1923  // Wish PHP had an "array_insert_before". Instead, we have to manually
1924  // reindex the array to get 'permissions' in the right place.
1925  $oldHelp = $help;
1926  $help = [];
1927  foreach ( $oldHelp as $k => $v ) {
1928  if ( $k === 'submodules' ) {
1929  $help['permissions'] = '';
1930  }
1931  $help[$k] = $v;
1932  }
1933  $help['datatypes'] = '';
1934  $help['templatedparams'] = '';
1935  $help['credits'] = '';
1936 
1937  // Fill 'permissions'
1938  $help['permissions'] .= Html::openElement( 'div',
1939  [ 'class' => 'apihelp-block apihelp-permissions' ] );
1940  $m = $this->msg( 'api-help-permissions' );
1941  if ( !$m->isDisabled() ) {
1942  $help['permissions'] .= Html::rawElement( 'div', [ 'class' => 'apihelp-block-head' ],
1943  $m->numParams( count( self::$mRights ) )->parse()
1944  );
1945  }
1946  $help['permissions'] .= Html::openElement( 'dl' );
1947  foreach ( self::$mRights as $right => $rightMsg ) {
1948  $help['permissions'] .= Html::element( 'dt', null, $right );
1949 
1950  $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse();
1951  $help['permissions'] .= Html::rawElement( 'dd', null, $rightMsg );
1952 
1953  $groups = array_map( function ( $group ) {
1954  return $group == '*' ? 'all' : $group;
1955  }, $this->getPermissionManager()->getGroupsWithPermission( $right ) );
1956 
1957  $help['permissions'] .= Html::rawElement( 'dd', null,
1958  $this->msg( 'api-help-permissions-granted-to' )
1959  ->numParams( count( $groups ) )
1960  ->params( Message::listParam( $groups ) )
1961  ->parse()
1962  );
1963  }
1964  $help['permissions'] .= Html::closeElement( 'dl' );
1965  $help['permissions'] .= Html::closeElement( 'div' );
1966 
1967  // Fill 'datatypes', 'templatedparams', and 'credits', if applicable
1968  if ( empty( $options['nolead'] ) ) {
1969  $level = $options['headerlevel'];
1970  $tocnumber = &$options['tocnumber'];
1971 
1972  $header = $this->msg( 'api-help-datatypes-header' )->parse();
1973 
1974  $id = Sanitizer::escapeIdForAttribute( 'main/datatypes', Sanitizer::ID_PRIMARY );
1975  $idFallback = Sanitizer::escapeIdForAttribute( 'main/datatypes', Sanitizer::ID_FALLBACK );
1976  $headline = Linker::makeHeadline( min( 6, $level ),
1977  ' class="apihelp-header">',
1978  $id,
1979  $header,
1980  '',
1981  $idFallback
1982  );
1983  // Ensure we have a sane anchor
1984  if ( $id !== 'main/datatypes' && $idFallback !== 'main/datatypes' ) {
1985  $headline = '<div id="main/datatypes"></div>' . $headline;
1986  }
1987  $help['datatypes'] .= $headline;
1988  $help['datatypes'] .= $this->msg( 'api-help-datatypes' )->parseAsBlock();
1989  if ( !isset( $tocData['main/datatypes'] ) ) {
1990  $tocnumber[$level]++;
1991  $tocData['main/datatypes'] = [
1992  'toclevel' => count( $tocnumber ),
1993  'level' => $level,
1994  'anchor' => 'main/datatypes',
1995  'line' => $header,
1996  'number' => implode( '.', $tocnumber ),
1997  'index' => false,
1998  ];
1999  }
2000 
2001  $header = $this->msg( 'api-help-templatedparams-header' )->parse();
2002 
2003  $id = Sanitizer::escapeIdForAttribute( 'main/templatedparams', Sanitizer::ID_PRIMARY );
2004  $idFallback = Sanitizer::escapeIdForAttribute( 'main/templatedparams', Sanitizer::ID_FALLBACK );
2005  $headline = Linker::makeHeadline( min( 6, $level ),
2006  ' class="apihelp-header">',
2007  $id,
2008  $header,
2009  '',
2010  $idFallback
2011  );
2012  // Ensure we have a sane anchor
2013  if ( $id !== 'main/templatedparams' && $idFallback !== 'main/templatedparams' ) {
2014  $headline = '<div id="main/templatedparams"></div>' . $headline;
2015  }
2016  $help['templatedparams'] .= $headline;
2017  $help['templatedparams'] .= $this->msg( 'api-help-templatedparams' )->parseAsBlock();
2018  if ( !isset( $tocData['main/templatedparams'] ) ) {
2019  $tocnumber[$level]++;
2020  $tocData['main/templatedparams'] = [
2021  'toclevel' => count( $tocnumber ),
2022  'level' => $level,
2023  'anchor' => 'main/templatedparams',
2024  'line' => $header,
2025  'number' => implode( '.', $tocnumber ),
2026  'index' => false,
2027  ];
2028  }
2029 
2030  $header = $this->msg( 'api-credits-header' )->parse();
2031  $id = Sanitizer::escapeIdForAttribute( 'main/credits', Sanitizer::ID_PRIMARY );
2032  $idFallback = Sanitizer::escapeIdForAttribute( 'main/credits', Sanitizer::ID_FALLBACK );
2033  $headline = Linker::makeHeadline( min( 6, $level ),
2034  ' class="apihelp-header">',
2035  $id,
2036  $header,
2037  '',
2038  $idFallback
2039  );
2040  // Ensure we have a sane anchor
2041  if ( $id !== 'main/credits' && $idFallback !== 'main/credits' ) {
2042  $headline = '<div id="main/credits"></div>' . $headline;
2043  }
2044  $help['credits'] .= $headline;
2045  $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
2046  if ( !isset( $tocData['main/credits'] ) ) {
2047  $tocnumber[$level]++;
2048  $tocData['main/credits'] = [
2049  'toclevel' => count( $tocnumber ),
2050  'level' => $level,
2051  'anchor' => 'main/credits',
2052  'line' => $header,
2053  'number' => implode( '.', $tocnumber ),
2054  'index' => false,
2055  ];
2056  }
2057  }
2058  }
2059 
2060  private $mCanApiHighLimits = null;
2061 
2066  public function canApiHighLimits() {
2067  if ( !isset( $this->mCanApiHighLimits ) ) {
2068  $this->mCanApiHighLimits = $this->getPermissionManager()
2069  ->userHasRight( $this->getUser(), 'apihighlimits' );
2070  }
2071 
2072  return $this->mCanApiHighLimits;
2073  }
2074 
2079  public function getModuleManager() {
2080  return $this->mModuleMgr;
2081  }
2082 
2091  public function getUserAgent() {
2092  return trim(
2093  $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
2094  $this->getRequest()->getHeader( 'User-agent' )
2095  );
2096  }
2097 }
2098 
ApiUsageException\getStatusValue
getStatusValue()
Fetch the error status.
Definition: ApiUsageException.php:101
ApiMain\executeActionWithErrorHandling
executeActionWithErrorHandling()
Execute an action, and in case of an error, erase whatever partial results have been accumulated,...
Definition: ApiMain.php:516
MWTimestamp
Library for creating and parsing MW-style timestamps.
Definition: MWTimestamp.php:32
ApiMain
This is the main API class, used for both external and internal processing.
Definition: ApiMain.php:41
ContextSource\$context
IContextSource $context
Definition: ContextSource.php:33
ContextSource\getConfig
getConfig()
Definition: ContextSource.php:63
FauxRequest
WebRequest clone which takes values from a provided array.
Definition: FauxRequest.php:33
ApiUsageException
Exception used to abort API execution with an error.
Definition: ApiUsageException.php:28
ContextSource\getContext
getContext()
Get the base IContextSource object.
Definition: ContextSource.php:40
ApiMain\checkReadOnly
checkReadOnly( $module)
Check if the DB is read-only for this user.
Definition: ApiMain.php:1445
ApiBase\addWarning
addWarning( $msg, $code=null, $data=null)
Add a warning for this module.
Definition: ApiBase.php:1933
RequestContext\sanitizeLangCode
static sanitizeLangCode( $code)
Accepts a language code and ensures it's sane.
Definition: RequestContext.php:288
ApiMain\$mParamsSensitive
$mParamsSensitive
Definition: ApiMain.php:159
WikiMap\getCurrentWikiDbDomain
static getCurrentWikiDbDomain()
Definition: WikiMap.php:292
ApiMain\$mAction
$mAction
Definition: ApiMain.php:149
ApiErrorFormatter_BackCompat
Format errors and warnings in the old style, for backwards compatibility.
Definition: ApiErrorFormatter_BackCompat.php:28
ApiErrorFormatter\isValidApiCode
static isValidApiCode( $code)
Test whether a code is a valid API error code.
Definition: ApiErrorFormatter.php:74
$response
$response
Definition: opensearch_desc.php:38
ApiMain\getParamsUsed
getParamsUsed()
Get the request parameters used in the course of the preceding execute() request.
Definition: ApiMain.php:1728
Profiler\instance
static instance()
Singleton.
Definition: Profiler.php:63
ApiMain\createErrorPrinter
createErrorPrinter()
Create the printer for error output.
Definition: ApiMain.php:989
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:117
ApiMain\getErrorFormatter
getErrorFormatter()
Get the ApiErrorFormatter object associated with current request.
Definition: ApiMain.php:357
ApiMain\getVal
getVal( $name, $default=null)
Get a request value, and register the fact that it was used, for logging.
Definition: ApiMain.php:1764
ApiUsageException\getModulePath
getModulePath()
Fetch the responsible module name.
Definition: ApiUsageException.php:93
ApiContinuationManager
This manages continuation state.
Definition: ApiContinuationManager.php:26
ApiBase\dieWithError
dieWithError( $msg, $code=null, $data=null, $httpCode=null)
Abort execution with an error.
Definition: ApiBase.php:2014
true
return true
Definition: router.php:92
ApiMain\sendCacheHeaders
sendCacheHeaders( $isError)
Send caching headers.
Definition: ApiMain.php:883
ApiMain\$Modules
static $Modules
List of available modules: action name => module class.
Definition: ApiMain.php:55
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1869
ApiBase\PARAM_TYPE
const PARAM_TYPE
(string|string[]) Either an array of allowed value strings, or a string type as described below.
Definition: ApiBase.php:94
ApiFormatBase
This is the abstract base class for API formatters.
Definition: ApiFormatBase.php:30
ApiMain\logRequest
logRequest( $time, $e=null)
Log the preceding request.
Definition: ApiMain.php:1633
MessageSpecifier
Definition: MessageSpecifier.php:21
wfUrlencode
wfUrlencode( $s)
We want some things to be included as literal characters in our title URLs for prettiness,...
Definition: GlobalFunctions.php:309
ApiMain\isReadMode
isReadMode()
Definition: ApiMain.php:1851
ApiMain\handleCORS
handleCORS()
Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
Definition: ApiMain.php:682
ApiMain\checkConditionalRequestHeaders
checkConditionalRequestHeaders( $module)
Check selected RFC 7232 precondition headers.
Definition: ApiMain.php:1314
ApiBase\dieWithErrorOrDebug
dieWithErrorOrDebug( $msg, $code=null, $data=null, $httpCode=null)
Will only set a warning instead of failing if the global $wgDebugAPI is set to true.
Definition: ApiBase.php:2191
ApiMain\lacksSameOriginSecurity
lacksSameOriginSecurity()
Get the security flag for the current request.
Definition: ApiMain.php:322
wfHostname
wfHostname()
Fetch server name for use in error reporting etc.
Definition: GlobalFunctions.php:1326
wfReadOnly
wfReadOnly()
Check whether the wiki is in read-only mode.
Definition: GlobalFunctions.php:1171
User\newFromName
static newFromName( $name, $validate='valid')
Static factory method for creation from username.
Definition: User.php:515
$s
$s
Definition: mergeMessageFileList.php:185
ApiResult\NO_SIZE_CHECK
const NO_SIZE_CHECK
For addValue() and similar functions, do not check size while adding a value Don't use this unless yo...
Definition: ApiResult.php:58
ContextSource\getRequest
getRequest()
Definition: ContextSource.php:71
ApiMain\$mCacheControl
array $mCacheControl
Definition: ApiMain.php:157
ApiMain\encodeRequestLogValue
encodeRequestLogValue( $s)
Encode a value in a format suitable for a space-separated log line.
Definition: ApiMain.php:1711
ContextSource\getUser
getUser()
Definition: ContextSource.php:120
ApiMain\getMaxLag
getMaxLag()
Definition: ApiMain.php:1234
ApiMain\$mContinuationManager
ApiContinuationManager null $mContinuationManager
Definition: ApiMain.php:148
ApiMain\matchOrigin
static matchOrigin( $value, $rules, $exceptions)
Attempt to match an Origin header against a set of rules and a set of exceptions.
Definition: ApiMain.php:802
wfDebugLog
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
Definition: GlobalFunctions.php:1007
ApiMain\$mRights
static $mRights
List of user roles that are specifically relevant to the API.
Definition: ApiMain.php:130
ApiBase
This abstract class implements many basic API functions, and is the base of all API classes.
Definition: ApiBase.php:42
ContextSource\getLanguage
getLanguage()
Definition: ContextSource.php:128
ApiMain\getModule
getModule()
Get the API module object.
Definition: ApiMain.php:388
DerivativeContext
An IContextSource implementation which will inherit context from another source but allow individual ...
Definition: DerivativeContext.php:30
ApiMain\markParamsUsed
markParamsUsed( $params)
Mark parameters as used.
Definition: ApiMain.php:1736
MWException
MediaWiki exception.
Definition: MWException.php:26
MediaWiki\Logger\LoggerFactory
PSR-3 logger instance factory.
Definition: LoggerFactory.php:45
ApiMain\setupExecuteAction
setupExecuteAction()
Set up for the execution.
Definition: ApiMain.php:1172
wfScript
wfScript( $script='index')
Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScri...
Definition: GlobalFunctions.php:2642
ApiResult
This class represents the result of the API operations.
Definition: ApiResult.php:35
ApiMain\$mResult
$mResult
Definition: ApiMain.php:146
ApiMain\$lacksSameOriginSecurity
bool null $lacksSameOriginSecurity
Cached return value from self::lacksSameOriginSecurity()
Definition: ApiMain.php:162
ContextSource\getOutput
getOutput()
Definition: ContextSource.php:112
$chars
if(PHP_SAPI !=='cli' &&PHP_SAPI !=='phpdbg') $chars
Definition: make-tables.php:8
$wgLang
$wgLang
Definition: Setup.php:881
MWExceptionHandler\rollbackMasterChangesAndLog
static rollbackMasterChangesAndLog( $e)
Roll back any open database transactions and log the stack trace of the exception.
Definition: MWExceptionHandler.php:139
Linker\makeHeadline
static makeHeadline( $level, $attribs, $anchor, $html, $link, $fallbackAnchor=false)
Create a headline for content.
Definition: Linker.php:1754
ApiMain\getResult
getResult()
Get the ApiResult object associated with current request.
Definition: ApiMain.php:314
ApiMain\getSensitiveParams
getSensitiveParams()
Get the request parameters that should be considered sensitive.
Definition: ApiMain.php:1745
MediaWiki
This class serves as a utility class for this extension.
ApiMain\checkMaxLag
checkMaxLag( $module, $params)
Check the max lag if necessary.
Definition: ApiMain.php:1268
ApiMain\API_DEFAULT_USELANG
const API_DEFAULT_USELANG
When no uselang parameter is given, this language will be used.
Definition: ApiMain.php:50
$t
$t
Definition: make-normalization-table.php:143
ApiBase\extractRequestParams
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition: ApiBase.php:761
ApiMain\getExamplesMessages
getExamplesMessages()
Returns usage examples for this module.Return value has query strings as keys, with values being eith...
Definition: ApiMain.php:1909
ApiMain\setCacheControl
setCacheControl( $directives)
Set directives (key/value pairs) for the Cache-Control header.
Definition: ApiMain.php:479
ApiMain\getAllowedParams
getAllowedParams()
See ApiBase for description.
Definition: ApiMain.php:1860
ApiMain\setupExternalResponse
setupExternalResponse( $module, $params)
Check POST for external response and setup result printer.
Definition: ApiMain.php:1531
ApiMain\createPrinterByName
createPrinterByName( $format)
Create an instance of an output formatter by its name.
Definition: ApiMain.php:490
ApiMain\getModuleManager
getModuleManager()
Overrides to return this instance's module manager.
Definition: ApiMain.php:2079
ApiMain\$mCanApiHighLimits
$mCanApiHighLimits
Definition: ApiMain.php:2060
ApiMessage\create
static create( $msg, $code=null, array $data=null)
Create an IApiMessage for the message.
Definition: ApiMessage.php:40
ApiMain\matchRequestedHeaders
static matchRequestedHeaders( $requestedHeaders)
Attempt to validate the value of Access-Control-Request-Headers against a list of headers that we all...
Definition: ApiMain.php:826
wfDebug
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
Definition: GlobalFunctions.php:913
ApiMain\addRequestedFields
addRequestedFields( $force=[])
Add requested fields to the result.
Definition: ApiMain.php:1142
ContextSource\setContext
setContext(IContextSource $context)
Definition: ContextSource.php:55
ILocalizedException
Interface for MediaWiki-localized exceptions.
Definition: ILocalizedException.php:27
ApiMain\canApiHighLimits
canApiHighLimits()
Check whether the current user is allowed to use high limits.
Definition: ApiMain.php:2066
ApiMain\$mPrinter
ApiFormatBase $mPrinter
Definition: ApiMain.php:144
ApiMain\checkBotReadOnly
checkBotReadOnly()
Check whether we are readonly for bots.
Definition: ApiMain.php:1461
ApiMain\getContinuationManager
getContinuationManager()
Get the continuation manager.
Definition: ApiMain.php:365
ApiModuleManager
This class holds a list of modules and handles instantiation.
Definition: ApiModuleManager.php:33
ContextSource\msg
msg( $key,... $params)
Get a Message object with context set Parameters are the same as wfMessage()
Definition: ContextSource.php:168
ApiMain\checkAsserts
checkAsserts( $params)
Check asserts of the user's rights.
Definition: ApiMain.php:1500
Hooks\runWithoutAbort
static runWithoutAbort( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:231
ApiMain\$mCacheMode
$mCacheMode
Definition: ApiMain.php:155
MWDebug\appendDebugInfoToApiResult
static appendDebugInfoToApiResult(IContextSource $context, ApiResult $result)
Append the debug info to given ApiResult.
Definition: MWDebug.php:504
ApiMain\handleException
handleException( $e)
Handle an exception as an API response.
Definition: ApiMain.php:573
wfClearOutputBuffers
wfClearOutputBuffers()
More legible than passing a 'false' parameter to wfResetOutputBuffers():
Definition: GlobalFunctions.php:1748
ApiMain\$mErrorFormatter
$mErrorFormatter
Definition: ApiMain.php:146
UIDGenerator\newUUIDv4
static newUUIDv4( $flags=0)
Return an RFC4122 compliant v4 UUID.
Definition: UIDGenerator.php:287
ApiMain\$mInternalMode
$mInternalMode
Definition: ApiMain.php:151
ApiMain\setContinuationManager
setContinuationManager(ApiContinuationManager $manager=null)
Set the continuation manager.
Definition: ApiMain.php:373
MediaWiki\preOutputCommit
static preOutputCommit(IContextSource $context, callable $postCommitWork=null)
This function commits all DB and session changes as needed before the client can receive a response (...
Definition: MediaWiki.php:596
ApiMain\wildcardToRegex
static wildcardToRegex( $wildcard)
Helper function to convert wildcard string into a regex '*' => '.
Definition: ApiMain.php:867
ApiMain\checkExecutePermissions
checkExecutePermissions( $module)
Check for sufficient permissions to execute.
Definition: ApiMain.php:1414
ApiBase\addDeprecation
addDeprecation( $msg, $feature, $data=[])
Add a deprecation warning for this module.
Definition: ApiBase.php:1947
$header
$header
Definition: updateCredits.php:41
ApiBase\LIMIT_SML2
const LIMIT_SML2
Slow query, apihighlimits limit.
Definition: ApiBase.php:265
ApiBase\dieReadOnly
dieReadOnly()
Helper function for readonly errors.
Definition: ApiBase.php:2114
ApiMain\__construct
__construct( $context=null, $enableWrite=false)
Constructs an instance of ApiMain that utilizes the module and format specified by $request.
Definition: ApiMain.php:172
ApiMain\reportUnusedParams
reportUnusedParams()
Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,...
Definition: ApiMain.php:1806
ApiBase\getPermissionManager
getPermissionManager()
Obtain a PermissionManager instance that subclasses may use in their authorization checks.
Definition: ApiBase.php:710
ApiMain\execute
execute()
Execute api request.
Definition: ApiMain.php:504
ApiBase\isWriteMode
isWriteMode()
Indicates whether this module requires write mode.
Definition: ApiBase.php:427
wfEscapeWikiText
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
Definition: GlobalFunctions.php:1551
ApiMain\$Formats
static $Formats
List of available formats: format name => format class.
Definition: ApiMain.php:113
ApiMain\markParamsSensitive
markParamsSensitive( $params)
Mark parameters as sensitive.
Definition: ApiMain.php:1754
ApiMain\setRequestExpectations
setRequestExpectations(ApiBase $module)
Set database connection, query, and write expectations given this module request.
Definition: ApiMain.php:1614
ApiMain\substituteResultWithError
substituteResultWithError( $e)
Replace the result data with the information about an exception.
Definition: ApiMain.php:1058
RequestContext\getMain
static getMain()
Get the RequestContext object associated with the main request.
Definition: RequestContext.php:431
ApiMain\getCheck
getCheck( $name)
Get a boolean request value, and register the fact that the parameter was used, for logging.
Definition: ApiMain.php:1785
ApiMain\printResult
printResult( $httpCode=0)
Print results using the current printer.
Definition: ApiMain.php:1834
WebRequest
The WebRequest class encapsulates getting at data passed in the URL or via a POSTed form stripping il...
Definition: WebRequest.php:42
ApiErrorFormatter
Formats errors and warnings for the API, and add them to the associated ApiResult.
Definition: ApiErrorFormatter.php:31
ApiMain\$mEnableWrite
$mEnableWrite
Definition: ApiMain.php:150
User\isEveryoneAllowed
static isEveryoneAllowed( $right)
Check if all users may be assumed to have the given permission.
Definition: User.php:4798
JobQueueGroup\singleton
static singleton( $domain=false)
Definition: JobQueueGroup.php:70
ApiBase\LIMIT_BIG2
const LIMIT_BIG2
Fast query, apihighlimits limit.
Definition: ApiBase.php:261
ApiMain\API_DEFAULT_FORMAT
const API_DEFAULT_FORMAT
When no format parameter is given, this format will be used.
Definition: ApiMain.php:45
WebRequest\GETHEADER_LIST
const GETHEADER_LIST
Flag to make WebRequest::getHeader return an array of values.
Definition: WebRequest.php:71
ApiMain\getUpload
getUpload( $name)
Get a request upload, and register the fact that it was used, for logging.
Definition: ApiMain.php:1796
ApiMain\modifyHelp
modifyHelp(array &$help, array $options, array &$tocData)
Called from ApiHelp before the pieces are joined together and returned.This exists mainly for ApiMain...
Definition: ApiMain.php:1922
WebRequest\getRequestId
static getRequestId()
Get the unique request ID.
Definition: WebRequest.php:303
$path
$path
Definition: NoLocalSettings.php:25
ApiBase\PARAM_DFLT
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
Definition: ApiBase.php:55
ApiBase\getParameter
getParameter( $paramName, $parseLimit=true)
Get a value for the given parameter.
Definition: ApiBase.php:876
ApiMain\executeAction
executeAction()
Execute the actual module, without any error handling.
Definition: ApiMain.php:1570
ApiMain\setupModule
setupModule()
Set up the module for response.
Definition: ApiMain.php:1187
$help
$help
Definition: mcc.php:32
Language\factory
static factory( $code)
Get a cached or new language object for a given language code.
Definition: Language.php:217
ApiMain\handleApiBeforeMainException
static handleApiBeforeMainException( $e)
Handle an exception from the ApiBeforeMain hook.
Definition: ApiMain.php:647
ApiMain\isInternalMode
isInternalMode()
Return true if the API was started by other PHP code using FauxRequest.
Definition: ApiMain.php:305
ApiMain\$mParamsUsed
$mParamsUsed
Definition: ApiMain.php:158
ApiMain\$mModuleMgr
$mModuleMgr
Definition: ApiMain.php:146
ApiMain\getUserAgent
getUserAgent()
Fetches the user agent used for this request.
Definition: ApiMain.php:2091
ApiMain\setCacheMaxAge
setCacheMaxAge( $maxage)
Set how long the response should be cached.
Definition: ApiMain.php:406
User
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:51
Hooks\run
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:200
ApiMain\errorMessagesFromException
errorMessagesFromException( $e, $type='error')
Create an error message for the given exception.
Definition: ApiMain.php:1020
ApiFormatBase\initPrinter
initPrinter( $unused=false)
Initialize the printer function and prepare the output headers.
Definition: ApiFormatBase.php:189
MWExceptionHandler\getRedactedTraceAsString
static getRedactedTraceAsString( $e)
Generate a string representation of an exception's stack trace.
Definition: MWExceptionHandler.php:404
ApiMain\setCacheMode
setCacheMode( $mode)
Set the type of caching headers which will be sent.
Definition: ApiMain.php:438
ApiMain\getPrinter
getPrinter()
Get the result formatter object.
Definition: ApiMain.php:397
wfExpandUrl
wfExpandUrl( $url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.
Definition: GlobalFunctions.php:491
ApiMain\$mCdnMaxAge
$mCdnMaxAge
Definition: ApiMain.php:151
$type
$type
Definition: testCompression.php:48
ApiMain\$mModule
ApiBase $mModule
Definition: ApiMain.php:153