MediaWiki  master
ApiMain.php
Go to the documentation of this file.
1 <?php
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';
156  private $mCacheControl = [];
157  private $mParamsUsed = [];
158  private $mParamsSensitive = [];
159 
161  private $lacksSameOriginSecurity = null;
162 
170  public function __construct( $context = null, $enableWrite = false ) {
171  if ( $context === null ) {
173  } elseif ( $context instanceof WebRequest ) {
174  // BC for pre-1.19
175  $request = $context;
177  }
178  // We set a derivative context so we can change stuff later
179  $this->setContext( new DerivativeContext( $context ) );
180 
181  if ( isset( $request ) ) {
182  $this->getContext()->setRequest( $request );
183  } else {
184  $request = $this->getRequest();
185  }
186 
187  $this->mInternalMode = ( $request instanceof FauxRequest );
188 
189  // Special handling for the main module: $parent === $this
190  parent::__construct( $this, $this->mInternalMode ? 'main_int' : 'main' );
191 
192  $config = $this->getConfig();
193 
194  if ( !$this->mInternalMode ) {
195  // Log if a request with a non-whitelisted Origin header is seen
196  // with session cookies.
197  $originHeader = $request->getHeader( 'Origin' );
198  if ( $originHeader === false ) {
199  $origins = [];
200  } else {
201  $originHeader = trim( $originHeader );
202  $origins = preg_split( '/\s+/', $originHeader );
203  }
204  $sessionCookies = array_intersect(
205  array_keys( $_COOKIE ),
206  MediaWiki\Session\SessionManager::singleton()->getVaryCookies()
207  );
208  if ( $origins && $sessionCookies && (
209  count( $origins ) !== 1 || !self::matchOrigin(
210  $origins[0],
211  $config->get( 'CrossSiteAJAXdomains' ),
212  $config->get( 'CrossSiteAJAXdomainExceptions' )
213  )
214  ) ) {
215  LoggerFactory::getInstance( 'cors' )->warning(
216  'Non-whitelisted CORS request with session cookies', [
217  'origin' => $originHeader,
218  'cookies' => $sessionCookies,
219  'ip' => $request->getIP(),
220  'userAgent' => $this->getUserAgent(),
221  'wiki' => wfWikiID(),
222  ]
223  );
224  }
225 
226  // If we're in a mode that breaks the same-origin policy, strip
227  // user credentials for security.
228  if ( $this->lacksSameOriginSecurity() ) {
229  global $wgUser;
230  wfDebug( "API: stripping user credentials when the same-origin policy is not applied\n" );
231  $wgUser = new User();
232  $this->getContext()->setUser( $wgUser );
233  $request->response()->header( 'MediaWiki-Login-Suppressed: true' );
234  }
235  }
236 
237  $this->mResult = new ApiResult( $this->getConfig()->get( 'APIMaxResultSize' ) );
238 
239  // Setup uselang. This doesn't use $this->getParameter()
240  // because we're not ready to handle errors yet.
241  $uselang = $request->getVal( 'uselang', self::API_DEFAULT_USELANG );
242  if ( $uselang === 'user' ) {
243  // Assume the parent context is going to return the user language
244  // for uselang=user (see T85635).
245  } else {
246  if ( $uselang === 'content' ) {
247  $uselang = MediaWikiServices::getInstance()->getContentLanguage()->getCode();
248  }
250  $this->getContext()->setLanguage( $code );
251  if ( !$this->mInternalMode ) {
252  global $wgLang;
253  $wgLang = $this->getContext()->getLanguage();
254  RequestContext::getMain()->setLanguage( $wgLang );
255  }
256  }
257 
258  // Set up the error formatter. This doesn't use $this->getParameter()
259  // because we're not ready to handle errors yet.
260  $errorFormat = $request->getVal( 'errorformat', 'bc' );
261  $errorLangCode = $request->getVal( 'errorlang', 'uselang' );
262  $errorsUseDB = $request->getCheck( 'errorsuselocal' );
263  if ( in_array( $errorFormat, [ 'plaintext', 'wikitext', 'html', 'raw', 'none' ], true ) ) {
264  if ( $errorLangCode === 'uselang' ) {
265  $errorLang = $this->getLanguage();
266  } elseif ( $errorLangCode === 'content' ) {
267  $errorLang = MediaWikiServices::getInstance()->getContentLanguage();
268  } else {
269  $errorLangCode = RequestContext::sanitizeLangCode( $errorLangCode );
270  $errorLang = Language::factory( $errorLangCode );
271  }
272  $this->mErrorFormatter = new ApiErrorFormatter(
273  $this->mResult, $errorLang, $errorFormat, $errorsUseDB
274  );
275  } else {
276  $this->mErrorFormatter = new ApiErrorFormatter_BackCompat( $this->mResult );
277  }
278  $this->mResult->setErrorFormatter( $this->getErrorFormatter() );
279 
280  $this->mModuleMgr = new ApiModuleManager( $this );
281  $this->mModuleMgr->addModules( self::$Modules, 'action' );
282  $this->mModuleMgr->addModules( $config->get( 'APIModules' ), 'action' );
283  $this->mModuleMgr->addModules( self::$Formats, 'format' );
284  $this->mModuleMgr->addModules( $config->get( 'APIFormatModules' ), 'format' );
285 
286  Hooks::run( 'ApiMain::moduleManager', [ $this->mModuleMgr ] );
287 
288  $this->mContinuationManager = null;
289  $this->mEnableWrite = $enableWrite;
290 
291  $this->mSquidMaxage = -1; // flag for executeActionWithErrorHandling()
292  $this->mCommit = false;
293  }
294 
299  public function isInternalMode() {
300  return $this->mInternalMode;
301  }
302 
308  public function getResult() {
309  return $this->mResult;
310  }
311 
316  public function lacksSameOriginSecurity() {
317  if ( $this->lacksSameOriginSecurity !== null ) {
319  }
320 
321  $request = $this->getRequest();
322 
323  // JSONP mode
324  if ( $request->getVal( 'callback' ) !== null ) {
325  $this->lacksSameOriginSecurity = true;
326  return true;
327  }
328 
329  // Anonymous CORS
330  if ( $request->getVal( 'origin' ) === '*' ) {
331  $this->lacksSameOriginSecurity = true;
332  return true;
333  }
334 
335  // Header to be used from XMLHTTPRequest when the request might
336  // otherwise be used for XSS.
337  if ( $request->getHeader( 'Treat-as-Untrusted' ) !== false ) {
338  $this->lacksSameOriginSecurity = true;
339  return true;
340  }
341 
342  // Allow extensions to override.
343  $this->lacksSameOriginSecurity = !Hooks::run( 'RequestHasSameOriginSecurity', [ $request ] );
345  }
346 
351  public function getErrorFormatter() {
352  return $this->mErrorFormatter;
353  }
354 
359  public function getContinuationManager() {
361  }
362 
367  public function setContinuationManager( ApiContinuationManager $manager = null ) {
368  if ( $manager !== null && $this->mContinuationManager !== null ) {
369  throw new UnexpectedValueException(
370  __METHOD__ . ': tried to set manager from ' . $manager->getSource() .
371  ' when a manager is already set from ' . $this->mContinuationManager->getSource()
372  );
373  }
374  $this->mContinuationManager = $manager;
375  }
376 
382  public function getModule() {
383  return $this->mModule;
384  }
385 
391  public function getPrinter() {
392  return $this->mPrinter;
393  }
394 
400  public function setCacheMaxAge( $maxage ) {
401  $this->setCacheControl( [
402  'max-age' => $maxage,
403  's-maxage' => $maxage
404  ] );
405  }
406 
432  public function setCacheMode( $mode ) {
433  if ( !in_array( $mode, [ 'private', 'public', 'anon-public-user-private' ] ) ) {
434  wfDebug( __METHOD__ . ": unrecognised cache mode \"$mode\"\n" );
435 
436  // Ignore for forwards-compatibility
437  return;
438  }
439 
440  if ( !User::isEveryoneAllowed( 'read' ) ) {
441  // Private wiki, only private headers
442  if ( $mode !== 'private' ) {
443  wfDebug( __METHOD__ . ": ignoring request for $mode cache mode, private wiki\n" );
444 
445  return;
446  }
447  }
448 
449  if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) {
450  // User language is used for i18n, so we don't want to publicly
451  // cache. Anons are ok, because if they have non-default language
452  // then there's an appropriate Vary header set by whatever set
453  // their non-default language.
454  wfDebug( __METHOD__ . ": downgrading cache mode 'public' to " .
455  "'anon-public-user-private' due to uselang=user\n" );
456  $mode = 'anon-public-user-private';
457  }
458 
459  wfDebug( __METHOD__ . ": setting cache mode $mode\n" );
460  $this->mCacheMode = $mode;
461  }
462 
473  public function setCacheControl( $directives ) {
474  $this->mCacheControl = $directives + $this->mCacheControl;
475  }
476 
484  public function createPrinterByName( $format ) {
485  $printer = $this->mModuleMgr->getModule( $format, 'format', /* $ignoreCache */ true );
486  if ( $printer === null ) {
487  $this->dieWithError(
488  [ 'apierror-unknownformat', wfEscapeWikiText( $format ) ], 'unknown_format'
489  );
490  }
491 
492  return $printer;
493  }
494 
498  public function execute() {
499  if ( $this->mInternalMode ) {
500  $this->executeAction();
501  } else {
503  }
504  }
505 
510  protected function executeActionWithErrorHandling() {
511  // Verify the CORS header before executing the action
512  if ( !$this->handleCORS() ) {
513  // handleCORS() has sent a 403, abort
514  return;
515  }
516 
517  // Exit here if the request method was OPTIONS
518  // (assume there will be a followup GET or POST)
519  if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
520  return;
521  }
522 
523  // In case an error occurs during data output,
524  // clear the output buffer and print just the error information
525  $obLevel = ob_get_level();
526  ob_start();
527 
528  $t = microtime( true );
529  $isError = false;
530  try {
531  $this->executeAction();
532  $runTime = microtime( true ) - $t;
533  $this->logRequest( $runTime );
534  MediaWikiServices::getInstance()->getStatsdDataFactory()->timing(
535  'api.' . $this->mModule->getModuleName() . '.executeTiming', 1000 * $runTime
536  );
537  } catch ( Exception $e ) { // @todo Remove this block when HHVM is no longer supported
538  $this->handleException( $e );
539  $this->logRequest( microtime( true ) - $t, $e );
540  $isError = true;
541  } catch ( Throwable $e ) {
542  $this->handleException( $e );
543  $this->logRequest( microtime( true ) - $t, $e );
544  $isError = true;
545  }
546 
547  // Commit DBs and send any related cookies and headers
549 
550  // Send cache headers after any code which might generate an error, to
551  // avoid sending public cache headers for errors.
552  $this->sendCacheHeaders( $isError );
553 
554  // Executing the action might have already messed with the output
555  // buffers.
556  while ( ob_get_level() > $obLevel ) {
557  ob_end_flush();
558  }
559  }
560 
567  protected function handleException( $e ) {
568  // T65145: Rollback any open database transactions
569  if ( !$e instanceof ApiUsageException ) {
570  // ApiUsageExceptions are intentional, so don't rollback if that's the case
572  }
573 
574  // Allow extra cleanup and logging
575  Hooks::run( 'ApiMain::onException', [ $this, $e ] );
576 
577  // Handle any kind of exception by outputting properly formatted error message.
578  // If this fails, an unhandled exception should be thrown so that global error
579  // handler will process and log it.
580 
581  $errCodes = $this->substituteResultWithError( $e );
582 
583  // Error results should not be cached
584  $this->setCacheMode( 'private' );
585 
586  $response = $this->getRequest()->response();
587  $headerStr = 'MediaWiki-API-Error: ' . implode( ', ', $errCodes );
588  $response->header( $headerStr );
589 
590  // Reset and print just the error message
591  ob_clean();
592 
593  // Printer may not be initialized if the extractRequestParams() fails for the main module
594  $this->createErrorPrinter();
595 
596  $failed = false;
597  try {
598  $this->printResult( $e->getCode() );
599  } catch ( ApiUsageException $ex ) {
600  // The error printer itself is failing. Try suppressing its request
601  // parameters and redo.
602  $failed = true;
603  $this->addWarning( 'apiwarn-errorprinterfailed' );
604  foreach ( $ex->getStatusValue()->getErrors() as $error ) {
605  try {
606  $this->mPrinter->addWarning( $error );
607  } catch ( Exception $ex2 ) { // @todo Remove this block when HHVM is no longer supported
608  // WTF?
609  $this->addWarning( $error );
610  } catch ( Throwable $ex2 ) {
611  // WTF?
612  $this->addWarning( $error );
613  }
614  }
615  }
616  if ( $failed ) {
617  $this->mPrinter = null;
618  $this->createErrorPrinter();
619  $this->mPrinter->forceDefaultParams();
620  if ( $e->getCode() ) {
621  $response->statusHeader( 200 ); // Reset in case the fallback doesn't want a non-200
622  }
623  $this->printResult( $e->getCode() );
624  }
625  }
626 
637  public static function handleApiBeforeMainException( $e ) {
638  ob_start();
639 
640  try {
641  $main = new self( RequestContext::getMain(), false );
642  $main->handleException( $e );
643  $main->logRequest( 0, $e );
644  } catch ( Exception $e2 ) { // @todo Remove this block when HHVM is no longer supported
645  // Nope, even that didn't work. Punt.
646  throw $e;
647  } catch ( Throwable $e2 ) {
648  // Nope, even that didn't work. Punt.
649  throw $e;
650  }
651 
652  // Reset cache headers
653  $main->sendCacheHeaders( true );
654 
655  ob_end_flush();
656  }
657 
672  protected function handleCORS() {
673  $originParam = $this->getParameter( 'origin' ); // defaults to null
674  if ( $originParam === null ) {
675  // No origin parameter, nothing to do
676  return true;
677  }
678 
679  $request = $this->getRequest();
680  $response = $request->response();
681 
682  $matchedOrigin = false;
683  $allowTiming = false;
684  $varyOrigin = true;
685 
686  if ( $originParam === '*' ) {
687  // Request for anonymous CORS
688  // Technically we should check for the presence of an Origin header
689  // and not process it as CORS if it's not set, but that would
690  // require us to vary on Origin for all 'origin=*' requests which
691  // we don't want to do.
692  $matchedOrigin = true;
693  $allowOrigin = '*';
694  $allowCredentials = 'false';
695  $varyOrigin = false; // No need to vary
696  } else {
697  // Non-anonymous CORS, check we allow the domain
698 
699  // Origin: header is a space-separated list of origins, check all of them
700  $originHeader = $request->getHeader( 'Origin' );
701  if ( $originHeader === false ) {
702  $origins = [];
703  } else {
704  $originHeader = trim( $originHeader );
705  $origins = preg_split( '/\s+/', $originHeader );
706  }
707 
708  if ( !in_array( $originParam, $origins ) ) {
709  // origin parameter set but incorrect
710  // Send a 403 response
711  $response->statusHeader( 403 );
712  $response->header( 'Cache-Control: no-cache' );
713  echo "'origin' parameter does not match Origin header\n";
714 
715  return false;
716  }
717 
718  $config = $this->getConfig();
719  $matchedOrigin = count( $origins ) === 1 && self::matchOrigin(
720  $originParam,
721  $config->get( 'CrossSiteAJAXdomains' ),
722  $config->get( 'CrossSiteAJAXdomainExceptions' )
723  );
724 
725  $allowOrigin = $originHeader;
726  $allowCredentials = 'true';
727  $allowTiming = $originHeader;
728  }
729 
730  if ( $matchedOrigin ) {
731  $requestedMethod = $request->getHeader( 'Access-Control-Request-Method' );
732  $preflight = $request->getMethod() === 'OPTIONS' && $requestedMethod !== false;
733  if ( $preflight ) {
734  // This is a CORS preflight request
735  if ( $requestedMethod !== 'POST' && $requestedMethod !== 'GET' ) {
736  // If method is not a case-sensitive match, do not set any additional headers and terminate.
737  $response->header( 'MediaWiki-CORS-Rejection: Unsupported method requested in preflight' );
738  return true;
739  }
740  // We allow the actual request to send the following headers
741  $requestedHeaders = $request->getHeader( 'Access-Control-Request-Headers' );
742  if ( $requestedHeaders !== false ) {
743  if ( !self::matchRequestedHeaders( $requestedHeaders ) ) {
744  $response->header( 'MediaWiki-CORS-Rejection: Unsupported header requested in preflight' );
745  return true;
746  }
747  $response->header( 'Access-Control-Allow-Headers: ' . $requestedHeaders );
748  }
749 
750  // We only allow the actual request to be GET or POST
751  $response->header( 'Access-Control-Allow-Methods: POST, GET' );
752  } elseif ( $request->getMethod() !== 'POST' && $request->getMethod() !== 'GET' ) {
753  // Unsupported non-preflight method, don't handle it as CORS
754  $response->header(
755  'MediaWiki-CORS-Rejection: Unsupported method for simple request or actual request'
756  );
757  return true;
758  }
759 
760  $response->header( "Access-Control-Allow-Origin: $allowOrigin" );
761  $response->header( "Access-Control-Allow-Credentials: $allowCredentials" );
762  // https://www.w3.org/TR/resource-timing/#timing-allow-origin
763  if ( $allowTiming !== false ) {
764  $response->header( "Timing-Allow-Origin: $allowTiming" );
765  }
766 
767  if ( !$preflight ) {
768  $response->header(
769  'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag, '
770  . 'MediaWiki-Login-Suppressed'
771  );
772  }
773  } else {
774  $response->header( 'MediaWiki-CORS-Rejection: Origin mismatch' );
775  }
776 
777  if ( $varyOrigin ) {
778  $this->getOutput()->addVaryHeader( 'Origin' );
779  }
780 
781  return true;
782  }
783 
792  protected static function matchOrigin( $value, $rules, $exceptions ) {
793  foreach ( $rules as $rule ) {
794  if ( preg_match( self::wildcardToRegex( $rule ), $value ) ) {
795  // Rule matches, check exceptions
796  foreach ( $exceptions as $exc ) {
797  if ( preg_match( self::wildcardToRegex( $exc ), $value ) ) {
798  return false;
799  }
800  }
801 
802  return true;
803  }
804  }
805 
806  return false;
807  }
808 
816  protected static function matchRequestedHeaders( $requestedHeaders ) {
817  if ( trim( $requestedHeaders ) === '' ) {
818  return true;
819  }
820  $requestedHeaders = explode( ',', $requestedHeaders );
821  $allowedAuthorHeaders = array_flip( [
822  /* simple headers (see spec) */
823  'accept',
824  'accept-language',
825  'content-language',
826  'content-type',
827  /* non-authorable headers in XHR, which are however requested by some UAs */
828  'accept-encoding',
829  'dnt',
830  'origin',
831  /* MediaWiki whitelist */
832  'api-user-agent',
833  ] );
834  foreach ( $requestedHeaders as $rHeader ) {
835  $rHeader = strtolower( trim( $rHeader ) );
836  if ( !isset( $allowedAuthorHeaders[$rHeader] ) ) {
837  LoggerFactory::getInstance( 'api-warning' )->warning(
838  'CORS preflight failed on requested header: {header}', [
839  'header' => $rHeader
840  ]
841  );
842  return false;
843  }
844  }
845  return true;
846  }
847 
856  protected static function wildcardToRegex( $wildcard ) {
857  $wildcard = preg_quote( $wildcard, '/' );
858  $wildcard = str_replace(
859  [ '\*', '\?' ],
860  [ '.*?', '.' ],
861  $wildcard
862  );
863 
864  return "/^https?:\/\/$wildcard$/";
865  }
866 
872  protected function sendCacheHeaders( $isError ) {
873  $response = $this->getRequest()->response();
874  $out = $this->getOutput();
875 
876  $out->addVaryHeader( 'Treat-as-Untrusted' );
877 
878  $config = $this->getConfig();
879 
880  if ( $config->get( 'VaryOnXFP' ) ) {
881  $out->addVaryHeader( 'X-Forwarded-Proto' );
882  }
883 
884  if ( !$isError && $this->mModule &&
885  ( $this->getRequest()->getMethod() === 'GET' || $this->getRequest()->getMethod() === 'HEAD' )
886  ) {
887  $etag = $this->mModule->getConditionalRequestData( 'etag' );
888  if ( $etag !== null ) {
889  $response->header( "ETag: $etag" );
890  }
891  $lastMod = $this->mModule->getConditionalRequestData( 'last-modified' );
892  if ( $lastMod !== null ) {
893  $response->header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822, $lastMod ) );
894  }
895  }
896 
897  // The logic should be:
898  // $this->mCacheControl['max-age'] is set?
899  // Use it, the module knows better than our guess.
900  // !$this->mModule || $this->mModule->isWriteMode(), and mCacheMode is private?
901  // Use 0 because we can guess caching is probably the wrong thing to do.
902  // Use $this->getParameter( 'maxage' ), which already defaults to 0.
903  $maxage = 0;
904  if ( isset( $this->mCacheControl['max-age'] ) ) {
905  $maxage = $this->mCacheControl['max-age'];
906  } elseif ( ( $this->mModule && !$this->mModule->isWriteMode() ) ||
907  $this->mCacheMode !== 'private'
908  ) {
909  $maxage = $this->getParameter( 'maxage' );
910  }
911  $privateCache = 'private, must-revalidate, max-age=' . $maxage;
912 
913  if ( $this->mCacheMode == 'private' ) {
914  $response->header( "Cache-Control: $privateCache" );
915  return;
916  }
917 
918  $useKeyHeader = $config->get( 'UseKeyHeader' );
919  if ( $this->mCacheMode == 'anon-public-user-private' ) {
920  $out->addVaryHeader( 'Cookie' );
921  $response->header( $out->getVaryHeader() );
922  if ( $useKeyHeader ) {
923  $response->header( $out->getKeyHeader() );
924  if ( $out->haveCacheVaryCookies() ) {
925  // Logged in, mark this request private
926  $response->header( "Cache-Control: $privateCache" );
927  return;
928  }
929  // Logged out, send normal public headers below
930  } elseif ( MediaWiki\Session\SessionManager::getGlobalSession()->isPersistent() ) {
931  // Logged in or otherwise has session (e.g. anonymous users who have edited)
932  // Mark request private
933  $response->header( "Cache-Control: $privateCache" );
934 
935  return;
936  } // else no Key and anonymous, send public headers below
937  }
938 
939  // Send public headers
940  $response->header( $out->getVaryHeader() );
941  if ( $useKeyHeader ) {
942  $response->header( $out->getKeyHeader() );
943  }
944 
945  // If nobody called setCacheMaxAge(), use the (s)maxage parameters
946  if ( !isset( $this->mCacheControl['s-maxage'] ) ) {
947  $this->mCacheControl['s-maxage'] = $this->getParameter( 'smaxage' );
948  }
949  if ( !isset( $this->mCacheControl['max-age'] ) ) {
950  $this->mCacheControl['max-age'] = $this->getParameter( 'maxage' );
951  }
952 
953  if ( !$this->mCacheControl['s-maxage'] && !$this->mCacheControl['max-age'] ) {
954  // Public cache not requested
955  // Sending a Vary header in this case is harmless, and protects us
956  // against conditional calls of setCacheMaxAge().
957  $response->header( "Cache-Control: $privateCache" );
958 
959  return;
960  }
961 
962  $this->mCacheControl['public'] = true;
963 
964  // Send an Expires header
965  $maxAge = min( $this->mCacheControl['s-maxage'], $this->mCacheControl['max-age'] );
966  $expiryUnixTime = ( $maxAge == 0 ? 1 : time() + $maxAge );
967  $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822, $expiryUnixTime ) );
968 
969  // Construct the Cache-Control header
970  $ccHeader = '';
971  $separator = '';
972  foreach ( $this->mCacheControl as $name => $value ) {
973  if ( is_bool( $value ) ) {
974  if ( $value ) {
975  $ccHeader .= $separator . $name;
976  $separator = ', ';
977  }
978  } else {
979  $ccHeader .= $separator . "$name=$value";
980  $separator = ', ';
981  }
982  }
983 
984  $response->header( "Cache-Control: $ccHeader" );
985  }
986 
990  private function createErrorPrinter() {
991  if ( !isset( $this->mPrinter ) ) {
992  $value = $this->getRequest()->getVal( 'format', self::API_DEFAULT_FORMAT );
993  if ( !$this->mModuleMgr->isDefined( $value, 'format' ) ) {
994  $value = self::API_DEFAULT_FORMAT;
995  }
996  $this->mPrinter = $this->createPrinterByName( $value );
997  }
998 
999  // Printer may not be able to handle errors. This is particularly
1000  // likely if the module returns something for getCustomPrinter().
1001  if ( !$this->mPrinter->canPrintErrors() ) {
1002  $this->mPrinter = $this->createPrinterByName( self::API_DEFAULT_FORMAT );
1003  }
1004  }
1005 
1021  protected function errorMessagesFromException( $e, $type = 'error' ) {
1022  $messages = [];
1023  if ( $e instanceof ApiUsageException ) {
1024  foreach ( $e->getStatusValue()->getErrorsByType( $type ) as $error ) {
1025  $messages[] = ApiMessage::create( $error );
1026  }
1027  } elseif ( $type !== 'error' ) {
1028  // None of the rest have any messages for non-error types
1029  } else {
1030  // Something is seriously wrong
1031  $config = $this->getConfig();
1032  // TODO: Avoid embedding arbitrary class names in the error code.
1033  $class = preg_replace( '#^Wikimedia\\\Rdbms\\\#', '', get_class( $e ) );
1034  $code = 'internal_api_error_' . $class;
1035  $data = [ 'errorclass' => get_class( $e ) ];
1036  if ( $config->get( 'ShowExceptionDetails' ) ) {
1037  if ( $e instanceof ILocalizedException ) {
1038  $msg = $e->getMessageObject();
1039  } elseif ( $e instanceof MessageSpecifier ) {
1040  $msg = Message::newFromSpecifier( $e );
1041  } else {
1042  $msg = wfEscapeWikiText( $e->getMessage() );
1043  }
1044  $params = [ 'apierror-exceptioncaught', WebRequest::getRequestId(), $msg ];
1045  } else {
1046  $params = [ 'apierror-exceptioncaughttype', WebRequest::getRequestId(), get_class( $e ) ];
1047  }
1048 
1049  $messages[] = ApiMessage::create( $params, $code, $data );
1050  }
1051  return $messages;
1052  }
1053 
1059  protected function substituteResultWithError( $e ) {
1060  $result = $this->getResult();
1061  $formatter = $this->getErrorFormatter();
1062  $config = $this->getConfig();
1063  $errorCodes = [];
1064 
1065  // Remember existing warnings and errors across the reset
1066  $errors = $result->getResultData( [ 'errors' ] );
1067  $warnings = $result->getResultData( [ 'warnings' ] );
1068  $result->reset();
1069  if ( $warnings !== null ) {
1070  $result->addValue( null, 'warnings', $warnings, ApiResult::NO_SIZE_CHECK );
1071  }
1072  if ( $errors !== null ) {
1073  $result->addValue( null, 'errors', $errors, ApiResult::NO_SIZE_CHECK );
1074 
1075  // Collect the copied error codes for the return value
1076  foreach ( $errors as $error ) {
1077  if ( isset( $error['code'] ) ) {
1078  $errorCodes[$error['code']] = true;
1079  }
1080  }
1081  }
1082 
1083  // Add errors from the exception
1084  $modulePath = $e instanceof ApiUsageException ? $e->getModulePath() : null;
1085  foreach ( $this->errorMessagesFromException( $e, 'error' ) as $msg ) {
1086  if ( ApiErrorFormatter::isValidApiCode( $msg->getApiCode() ) ) {
1087  $errorCodes[$msg->getApiCode()] = true;
1088  } else {
1089  LoggerFactory::getInstance( 'api-warning' )->error( 'Invalid API error code "{code}"', [
1090  'code' => $msg->getApiCode(),
1091  'exception' => $e,
1092  ] );
1093  $errorCodes['<invalid-code>'] = true;
1094  }
1095  $formatter->addError( $modulePath, $msg );
1096  }
1097  foreach ( $this->errorMessagesFromException( $e, 'warning' ) as $msg ) {
1098  $formatter->addWarning( $modulePath, $msg );
1099  }
1100 
1101  // Add additional data. Path depends on whether we're in BC mode or not.
1102  // Data depends on the type of exception.
1103  if ( $formatter instanceof ApiErrorFormatter_BackCompat ) {
1104  $path = [ 'error' ];
1105  } else {
1106  $path = null;
1107  }
1108  if ( $e instanceof ApiUsageException ) {
1109  $link = wfExpandUrl( wfScript( 'api' ) );
1110  $result->addContentValue(
1111  $path,
1112  'docref',
1113  trim(
1114  $this->msg( 'api-usage-docref', $link )->inLanguage( $formatter->getLanguage() )->text()
1115  . ' '
1116  . $this->msg( 'api-usage-mailinglist-ref' )->inLanguage( $formatter->getLanguage() )->text()
1117  )
1118  );
1119  } else {
1120  if ( $config->get( 'ShowExceptionDetails' ) ) {
1121  $result->addContentValue(
1122  $path,
1123  'trace',
1124  $this->msg( 'api-exception-trace',
1125  get_class( $e ),
1126  $e->getFile(),
1127  $e->getLine(),
1129  )->inLanguage( $formatter->getLanguage() )->text()
1130  );
1131  }
1132  }
1133 
1134  // Add the id and such
1135  $this->addRequestedFields( [ 'servedby' ] );
1136 
1137  return array_keys( $errorCodes );
1138  }
1139 
1145  protected function addRequestedFields( $force = [] ) {
1146  $result = $this->getResult();
1147 
1148  $requestid = $this->getParameter( 'requestid' );
1149  if ( $requestid !== null ) {
1150  $result->addValue( null, 'requestid', $requestid, ApiResult::NO_SIZE_CHECK );
1151  }
1152 
1153  if ( $this->getConfig()->get( 'ShowHostnames' ) && (
1154  in_array( 'servedby', $force, true ) || $this->getParameter( 'servedby' )
1155  ) ) {
1156  $result->addValue( null, 'servedby', wfHostname(), ApiResult::NO_SIZE_CHECK );
1157  }
1158 
1159  if ( $this->getParameter( 'curtimestamp' ) ) {
1160  $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601, time() ),
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( intval( $maxLag ), 5 ) );
1280  $response->header( 'X-Database-Lag: ' . intval( $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  $lastMod = $module->getConditionalRequestData( 'last-modified' );
1373  if ( $lastMod !== null ) {
1374  // Mix in some MediaWiki modification times
1375  $modifiedTimes = [
1376  'page' => $lastMod,
1377  'user' => $this->getUser()->getTouched(),
1378  'epoch' => $this->getConfig()->get( 'CacheEpoch' ),
1379  ];
1380  if ( $this->getConfig()->get( 'UseSquid' ) ) {
1381  // T46570: the core page itself may not change, but resources might
1382  $modifiedTimes['sepoch'] = wfTimestamp(
1383  TS_MW, time() - $this->getConfig()->get( 'SquidMaxage' )
1384  );
1385  }
1386  Hooks::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this->getOutput() ] );
1387  $lastMod = max( $modifiedTimes );
1388  $return304 = wfTimestamp( TS_MW, $lastMod ) <= $ts->getTimestamp( TS_MW );
1389  }
1390  }
1391  } catch ( TimestampException $e ) {
1392  // Invalid timestamp, ignore it
1393  }
1394  }
1395  }
1396 
1397  if ( $return304 ) {
1398  $this->getRequest()->response()->statusHeader( 304 );
1399 
1400  // Avoid outputting the compressed representation of a zero-length body
1401  Wikimedia\suppressWarnings();
1402  ini_set( 'zlib.output_compression', 0 );
1403  Wikimedia\restoreWarnings();
1405 
1406  return false;
1407  }
1408 
1409  return true;
1410  }
1411 
1416  protected function checkExecutePermissions( $module ) {
1417  $user = $this->getUser();
1418  if ( $module->isReadMode() && !User::isEveryoneAllowed( 'read' ) &&
1419  !$user->isAllowed( 'read' )
1420  ) {
1421  $this->dieWithError( 'apierror-readapidenied' );
1422  }
1423 
1424  if ( $module->isWriteMode() ) {
1425  if ( !$this->mEnableWrite ) {
1426  $this->dieWithError( 'apierror-noapiwrite' );
1427  } elseif ( !$user->isAllowed( 'writeapi' ) ) {
1428  $this->dieWithError( 'apierror-writeapidenied' );
1429  } elseif ( $this->getRequest()->getHeader( 'Promise-Non-Write-API-Action' ) ) {
1430  $this->dieWithError( 'apierror-promised-nonwrite-api' );
1431  }
1432 
1433  $this->checkReadOnly( $module );
1434  }
1435 
1436  // Allow extensions to stop execution for arbitrary reasons.
1437  $message = 'hookaborted';
1438  if ( !Hooks::run( 'ApiCheckCanExecute', [ $module, $user, &$message ] ) ) {
1439  $this->dieWithError( $message );
1440  }
1441  }
1442 
1447  protected function checkReadOnly( $module ) {
1448  if ( wfReadOnly() ) {
1449  $this->dieReadOnly();
1450  }
1451 
1452  if ( $module->isWriteMode()
1453  && $this->getUser()->isBot()
1454  && MediaWikiServices::getInstance()->getDBLoadBalancer()->getServerCount() > 1
1455  ) {
1456  $this->checkBotReadOnly();
1457  }
1458  }
1459 
1463  private function checkBotReadOnly() {
1464  // Figure out how many servers have passed the lag threshold
1465  $numLagged = 0;
1466  $lagLimit = $this->getConfig()->get( 'APIMaxLagThreshold' );
1467  $laggedServers = [];
1468  $loadBalancer = MediaWikiServices::getInstance()->getDBLoadBalancer();
1469  foreach ( $loadBalancer->getLagTimes() as $serverIndex => $lag ) {
1470  if ( $lag > $lagLimit ) {
1471  ++$numLagged;
1472  $laggedServers[] = $loadBalancer->getServerName( $serverIndex ) . " ({$lag}s)";
1473  }
1474  }
1475 
1476  // If a majority of replica DBs are too lagged then disallow writes
1477  $replicaCount = $loadBalancer->getServerCount() - 1;
1478  if ( $numLagged >= ceil( $replicaCount / 2 ) ) {
1479  $laggedServers = implode( ', ', $laggedServers );
1480  wfDebugLog(
1481  'api-readonly', // Deprecate this channel in favor of api-warning?
1482  "Api request failed as read only because the following DBs are lagged: $laggedServers"
1483  );
1484  LoggerFactory::getInstance( 'api-warning' )->warning(
1485  "Api request failed as read only because the following DBs are lagged: {laggeddbs}", [
1486  'laggeddbs' => $laggedServers,
1487  ]
1488  );
1489 
1490  $this->dieWithError(
1491  'readonly_lag',
1492  'readonly',
1493  [ 'readonlyreason' => "Waiting for $numLagged lagged database(s)" ]
1494  );
1495  }
1496  }
1497 
1502  protected function checkAsserts( $params ) {
1503  if ( isset( $params['assert'] ) ) {
1504  $user = $this->getUser();
1505  switch ( $params['assert'] ) {
1506  case 'user':
1507  if ( $user->isAnon() ) {
1508  $this->dieWithError( 'apierror-assertuserfailed' );
1509  }
1510  break;
1511  case 'bot':
1512  if ( !$user->isAllowed( 'bot' ) ) {
1513  $this->dieWithError( 'apierror-assertbotfailed' );
1514  }
1515  break;
1516  }
1517  }
1518  if ( isset( $params['assertuser'] ) ) {
1519  $assertUser = User::newFromName( $params['assertuser'], false );
1520  if ( !$assertUser || !$this->getUser()->equals( $assertUser ) ) {
1521  $this->dieWithError(
1522  [ 'apierror-assertnameduserfailed', wfEscapeWikiText( $params['assertuser'] ) ]
1523  );
1524  }
1525  }
1526  }
1527 
1533  protected function setupExternalResponse( $module, $params ) {
1534  $validMethods = [ 'GET', 'HEAD', 'POST', 'OPTIONS' ];
1535  $request = $this->getRequest();
1536 
1537  if ( !in_array( $request->getMethod(), $validMethods ) ) {
1538  $this->dieWithError( 'apierror-invalidmethod', null, null, 405 );
1539  }
1540 
1541  if ( !$request->wasPosted() && $module->mustBePosted() ) {
1542  // Module requires POST. GET request might still be allowed
1543  // if $wgDebugApi is true, otherwise fail.
1544  $this->dieWithErrorOrDebug( [ 'apierror-mustbeposted', $this->mAction ] );
1545  }
1546 
1547  // See if custom printer is used
1548  $this->mPrinter = $module->getCustomPrinter();
1549  if ( is_null( $this->mPrinter ) ) {
1550  // Create an appropriate printer
1551  $this->mPrinter = $this->createPrinterByName( $params['format'] );
1552  }
1553 
1554  if ( $request->getProtocol() === 'http' && (
1555  $request->getSession()->shouldForceHTTPS() ||
1556  ( $this->getUser()->isLoggedIn() &&
1557  $this->getUser()->requiresHTTPS() )
1558  ) ) {
1559  $this->addDeprecation( 'apiwarn-deprecation-httpsexpected', 'https-expected' );
1560  }
1561  }
1562 
1566  protected function executeAction() {
1567  $params = $this->setupExecuteAction();
1568 
1569  // Check asserts early so e.g. errors in parsing a module's parameters due to being
1570  // logged out don't override the client's intended "am I logged in?" check.
1571  $this->checkAsserts( $params );
1572 
1573  $module = $this->setupModule();
1574  $this->mModule = $module;
1575 
1576  if ( !$this->mInternalMode ) {
1577  $this->setRequestExpectations( $module );
1578  }
1579 
1580  $this->checkExecutePermissions( $module );
1581 
1582  if ( !$this->checkMaxLag( $module, $params ) ) {
1583  return;
1584  }
1585 
1586  if ( !$this->checkConditionalRequestHeaders( $module ) ) {
1587  return;
1588  }
1589 
1590  if ( !$this->mInternalMode ) {
1591  $this->setupExternalResponse( $module, $params );
1592  }
1593 
1594  // Execute
1595  $module->execute();
1596  Hooks::run( 'APIAfterExecute', [ &$module ] );
1597 
1598  $this->reportUnusedParams();
1599 
1600  if ( !$this->mInternalMode ) {
1601  // append Debug information
1603 
1604  // Print result data
1605  $this->printResult();
1606  }
1607  }
1608 
1613  protected function setRequestExpectations( ApiBase $module ) {
1614  $limits = $this->getConfig()->get( 'TrxProfilerLimits' );
1615  $trxProfiler = Profiler::instance()->getTransactionProfiler();
1616  $trxProfiler->setLogger( LoggerFactory::getInstance( 'DBPerformance' ) );
1617  if ( $this->getRequest()->hasSafeMethod() ) {
1618  $trxProfiler->setExpectations( $limits['GET'], __METHOD__ );
1619  } elseif ( $this->getRequest()->wasPosted() && !$module->isWriteMode() ) {
1620  $trxProfiler->setExpectations( $limits['POST-nonwrite'], __METHOD__ );
1621  $this->getRequest()->markAsSafeRequest();
1622  } else {
1623  $trxProfiler->setExpectations( $limits['POST'], __METHOD__ );
1624  }
1625  }
1626 
1632  protected function logRequest( $time, $e = null ) {
1633  $request = $this->getRequest();
1634  $logCtx = [
1635  'ts' => time(),
1636  'ip' => $request->getIP(),
1637  'userAgent' => $this->getUserAgent(),
1638  'wiki' => wfWikiID(),
1639  'timeSpentBackend' => (int)round( $time * 1000 ),
1640  'hadError' => $e !== null,
1641  'errorCodes' => [],
1642  'params' => [],
1643  ];
1644 
1645  if ( $e ) {
1646  foreach ( $this->errorMessagesFromException( $e ) as $msg ) {
1647  $logCtx['errorCodes'][] = $msg->getApiCode();
1648  }
1649  }
1650 
1651  // Construct space separated message for 'api' log channel
1652  $msg = "API {$request->getMethod()} " .
1653  wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
1654  " {$logCtx['ip']} " .
1655  "T={$logCtx['timeSpentBackend']}ms";
1656 
1657  $sensitive = array_flip( $this->getSensitiveParams() );
1658  foreach ( $this->getParamsUsed() as $name ) {
1659  $value = $request->getVal( $name );
1660  if ( $value === null ) {
1661  continue;
1662  }
1663 
1664  if ( isset( $sensitive[$name] ) ) {
1665  $value = '[redacted]';
1666  $encValue = '[redacted]';
1667  } elseif ( strlen( $value ) > 256 ) {
1668  $value = substr( $value, 0, 256 );
1669  $encValue = $this->encodeRequestLogValue( $value ) . '[...]';
1670  } else {
1671  $encValue = $this->encodeRequestLogValue( $value );
1672  }
1673 
1674  $logCtx['params'][$name] = $value;
1675  $msg .= " {$name}={$encValue}";
1676  }
1677 
1678  wfDebugLog( 'api', $msg, 'private' );
1679  // ApiAction channel is for structured data consumers
1680  wfDebugLog( 'ApiAction', '', 'private', $logCtx );
1681  }
1682 
1688  protected function encodeRequestLogValue( $s ) {
1689  static $table;
1690  if ( !$table ) {
1691  $chars = ';@$!*(),/:';
1692  $numChars = strlen( $chars );
1693  for ( $i = 0; $i < $numChars; $i++ ) {
1694  $table[rawurlencode( $chars[$i] )] = $chars[$i];
1695  }
1696  }
1697 
1698  return strtr( rawurlencode( $s ), $table );
1699  }
1700 
1705  protected function getParamsUsed() {
1706  return array_keys( $this->mParamsUsed );
1707  }
1708 
1713  public function markParamsUsed( $params ) {
1714  $this->mParamsUsed += array_fill_keys( (array)$params, true );
1715  }
1716 
1722  protected function getSensitiveParams() {
1723  return array_keys( $this->mParamsSensitive );
1724  }
1725 
1731  public function markParamsSensitive( $params ) {
1732  $this->mParamsSensitive += array_fill_keys( (array)$params, true );
1733  }
1734 
1741  public function getVal( $name, $default = null ) {
1742  $this->mParamsUsed[$name] = true;
1743 
1744  $ret = $this->getRequest()->getVal( $name );
1745  if ( $ret === null ) {
1746  if ( $this->getRequest()->getArray( $name ) !== null ) {
1747  // See T12262 for why we don't just implode( '|', ... ) the
1748  // array.
1749  $this->addWarning( [ 'apiwarn-unsupportedarray', $name ] );
1750  }
1751  $ret = $default;
1752  }
1753  return $ret;
1754  }
1755 
1762  public function getCheck( $name ) {
1763  return $this->getVal( $name, null ) !== null;
1764  }
1765 
1773  public function getUpload( $name ) {
1774  $this->mParamsUsed[$name] = true;
1775 
1776  return $this->getRequest()->getUpload( $name );
1777  }
1778 
1783  protected function reportUnusedParams() {
1784  $paramsUsed = $this->getParamsUsed();
1785  $allParams = $this->getRequest()->getValueNames();
1786 
1787  if ( !$this->mInternalMode ) {
1788  // Printer has not yet executed; don't warn that its parameters are unused
1789  $printerParams = $this->mPrinter->encodeParamName(
1790  array_keys( $this->mPrinter->getFinalParams() ?: [] )
1791  );
1792  $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1793  } else {
1794  $unusedParams = array_diff( $allParams, $paramsUsed );
1795  }
1796 
1797  if ( count( $unusedParams ) ) {
1798  $this->addWarning( [
1799  'apierror-unrecognizedparams',
1800  Message::listParam( array_map( 'wfEscapeWikiText', $unusedParams ), 'comma' ),
1801  count( $unusedParams )
1802  ] );
1803  }
1804  }
1805 
1811  protected function printResult( $httpCode = 0 ) {
1812  if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
1813  $this->addWarning( 'apiwarn-wgDebugAPI' );
1814  }
1815 
1816  $printer = $this->mPrinter;
1817  $printer->initPrinter( false );
1818  if ( $httpCode ) {
1819  $printer->setHttpStatus( $httpCode );
1820  }
1821  $printer->execute();
1822  $printer->closePrinter();
1823  }
1824 
1828  public function isReadMode() {
1829  return false;
1830  }
1831 
1837  public function getAllowedParams() {
1838  return [
1839  'action' => [
1840  ApiBase::PARAM_DFLT => 'help',
1841  ApiBase::PARAM_TYPE => 'submodule',
1842  ],
1843  'format' => [
1844  ApiBase::PARAM_DFLT => self::API_DEFAULT_FORMAT,
1845  ApiBase::PARAM_TYPE => 'submodule',
1846  ],
1847  'maxlag' => [
1848  ApiBase::PARAM_TYPE => 'integer'
1849  ],
1850  'smaxage' => [
1851  ApiBase::PARAM_TYPE => 'integer',
1852  ApiBase::PARAM_DFLT => 0
1853  ],
1854  'maxage' => [
1855  ApiBase::PARAM_TYPE => 'integer',
1856  ApiBase::PARAM_DFLT => 0
1857  ],
1858  'assert' => [
1859  ApiBase::PARAM_TYPE => [ 'user', 'bot' ]
1860  ],
1861  'assertuser' => [
1862  ApiBase::PARAM_TYPE => 'user',
1863  ],
1864  'requestid' => null,
1865  'servedby' => false,
1866  'curtimestamp' => false,
1867  'responselanginfo' => false,
1868  'origin' => null,
1869  'uselang' => [
1870  ApiBase::PARAM_DFLT => self::API_DEFAULT_USELANG,
1871  ],
1872  'errorformat' => [
1873  ApiBase::PARAM_TYPE => [ 'plaintext', 'wikitext', 'html', 'raw', 'none', 'bc' ],
1874  ApiBase::PARAM_DFLT => 'bc',
1875  ],
1876  'errorlang' => [
1877  ApiBase::PARAM_DFLT => 'uselang',
1878  ],
1879  'errorsuselocal' => [
1880  ApiBase::PARAM_DFLT => false,
1881  ],
1882  ];
1883  }
1884 
1886  protected function getExamplesMessages() {
1887  return [
1888  'action=help'
1889  => 'apihelp-help-example-main',
1890  'action=help&recursivesubmodules=1'
1891  => 'apihelp-help-example-recursive',
1892  ];
1893  }
1894 
1895  public function modifyHelp( array &$help, array $options, array &$tocData ) {
1896  // Wish PHP had an "array_insert_before". Instead, we have to manually
1897  // reindex the array to get 'permissions' in the right place.
1898  $oldHelp = $help;
1899  $help = [];
1900  foreach ( $oldHelp as $k => $v ) {
1901  if ( $k === 'submodules' ) {
1902  $help['permissions'] = '';
1903  }
1904  $help[$k] = $v;
1905  }
1906  $help['datatypes'] = '';
1907  $help['templatedparams'] = '';
1908  $help['credits'] = '';
1909 
1910  // Fill 'permissions'
1911  $help['permissions'] .= Html::openElement( 'div',
1912  [ 'class' => 'apihelp-block apihelp-permissions' ] );
1913  $m = $this->msg( 'api-help-permissions' );
1914  if ( !$m->isDisabled() ) {
1915  $help['permissions'] .= Html::rawElement( 'div', [ 'class' => 'apihelp-block-head' ],
1916  $m->numParams( count( self::$mRights ) )->parse()
1917  );
1918  }
1919  $help['permissions'] .= Html::openElement( 'dl' );
1920  foreach ( self::$mRights as $right => $rightMsg ) {
1921  $help['permissions'] .= Html::element( 'dt', null, $right );
1922 
1923  $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse();
1924  $help['permissions'] .= Html::rawElement( 'dd', null, $rightMsg );
1925 
1926  $groups = array_map( function ( $group ) {
1927  return $group == '*' ? 'all' : $group;
1928  }, User::getGroupsWithPermission( $right ) );
1929 
1930  $help['permissions'] .= Html::rawElement( 'dd', null,
1931  $this->msg( 'api-help-permissions-granted-to' )
1932  ->numParams( count( $groups ) )
1933  ->params( Message::listParam( $groups ) )
1934  ->parse()
1935  );
1936  }
1937  $help['permissions'] .= Html::closeElement( 'dl' );
1938  $help['permissions'] .= Html::closeElement( 'div' );
1939 
1940  // Fill 'datatypes', 'templatedparams', and 'credits', if applicable
1941  if ( empty( $options['nolead'] ) ) {
1942  $level = $options['headerlevel'];
1943  $tocnumber = &$options['tocnumber'];
1944 
1945  $header = $this->msg( 'api-help-datatypes-header' )->parse();
1946 
1947  $id = Sanitizer::escapeIdForAttribute( 'main/datatypes', Sanitizer::ID_PRIMARY );
1948  $idFallback = Sanitizer::escapeIdForAttribute( 'main/datatypes', Sanitizer::ID_FALLBACK );
1949  $headline = Linker::makeHeadline( min( 6, $level ),
1950  ' class="apihelp-header">',
1951  $id,
1952  $header,
1953  '',
1954  $idFallback
1955  );
1956  // Ensure we have a sane anchor
1957  if ( $id !== 'main/datatypes' && $idFallback !== 'main/datatypes' ) {
1958  $headline = '<div id="main/datatypes"></div>' . $headline;
1959  }
1960  $help['datatypes'] .= $headline;
1961  $help['datatypes'] .= $this->msg( 'api-help-datatypes' )->parseAsBlock();
1962  if ( !isset( $tocData['main/datatypes'] ) ) {
1963  $tocnumber[$level]++;
1964  $tocData['main/datatypes'] = [
1965  'toclevel' => count( $tocnumber ),
1966  'level' => $level,
1967  'anchor' => 'main/datatypes',
1968  'line' => $header,
1969  'number' => implode( '.', $tocnumber ),
1970  'index' => false,
1971  ];
1972  }
1973 
1974  $header = $this->msg( 'api-help-templatedparams-header' )->parse();
1975 
1976  $id = Sanitizer::escapeIdForAttribute( 'main/templatedparams', Sanitizer::ID_PRIMARY );
1977  $idFallback = Sanitizer::escapeIdForAttribute( 'main/templatedparams', Sanitizer::ID_FALLBACK );
1978  $headline = Linker::makeHeadline( min( 6, $level ),
1979  ' class="apihelp-header">',
1980  $id,
1981  $header,
1982  '',
1983  $idFallback
1984  );
1985  // Ensure we have a sane anchor
1986  if ( $id !== 'main/templatedparams' && $idFallback !== 'main/templatedparams' ) {
1987  $headline = '<div id="main/templatedparams"></div>' . $headline;
1988  }
1989  $help['templatedparams'] .= $headline;
1990  $help['templatedparams'] .= $this->msg( 'api-help-templatedparams' )->parseAsBlock();
1991  if ( !isset( $tocData['main/templatedparams'] ) ) {
1992  $tocnumber[$level]++;
1993  $tocData['main/templatedparams'] = [
1994  'toclevel' => count( $tocnumber ),
1995  'level' => $level,
1996  'anchor' => 'main/templatedparams',
1997  'line' => $header,
1998  'number' => implode( '.', $tocnumber ),
1999  'index' => false,
2000  ];
2001  }
2002 
2003  $header = $this->msg( 'api-credits-header' )->parse();
2004  $id = Sanitizer::escapeIdForAttribute( 'main/credits', Sanitizer::ID_PRIMARY );
2005  $idFallback = Sanitizer::escapeIdForAttribute( 'main/credits', Sanitizer::ID_FALLBACK );
2006  $headline = Linker::makeHeadline( min( 6, $level ),
2007  ' class="apihelp-header">',
2008  $id,
2009  $header,
2010  '',
2011  $idFallback
2012  );
2013  // Ensure we have a sane anchor
2014  if ( $id !== 'main/credits' && $idFallback !== 'main/credits' ) {
2015  $headline = '<div id="main/credits"></div>' . $headline;
2016  }
2017  $help['credits'] .= $headline;
2018  $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
2019  if ( !isset( $tocData['main/credits'] ) ) {
2020  $tocnumber[$level]++;
2021  $tocData['main/credits'] = [
2022  'toclevel' => count( $tocnumber ),
2023  'level' => $level,
2024  'anchor' => 'main/credits',
2025  'line' => $header,
2026  'number' => implode( '.', $tocnumber ),
2027  'index' => false,
2028  ];
2029  }
2030  }
2031  }
2032 
2033  private $mCanApiHighLimits = null;
2034 
2039  public function canApiHighLimits() {
2040  if ( !isset( $this->mCanApiHighLimits ) ) {
2041  $this->mCanApiHighLimits = $this->getUser()->isAllowed( 'apihighlimits' );
2042  }
2043 
2044  return $this->mCanApiHighLimits;
2045  }
2046 
2051  public function getModuleManager() {
2052  return $this->mModuleMgr;
2053  }
2054 
2063  public function getUserAgent() {
2064  return trim(
2065  $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
2066  $this->getRequest()->getHeader( 'User-agent' )
2067  );
2068  }
2069 }
2070 
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
setContext(IContextSource $context)
getAllowedParams()
See ApiBase for description.
Definition: ApiMain.php:1837
getModuleManager()
Overrides to return this instance&#39;s module manager.
Definition: ApiMain.php:2051
const PARAM_TYPE
(string|string[]) Either an array of allowed value strings, or a string type as described below...
Definition: ApiBase.php:88
static matchRequestedHeaders( $requestedHeaders)
Attempt to validate the value of Access-Control-Request-Headers against a list of headers that we all...
Definition: ApiMain.php:816
getUserAgent()
Fetches the user agent used for this request.
Definition: ApiMain.php:2063
const LIMIT_BIG2
Fast query, apihighlimits limit.
Definition: ApiBase.php:255
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:400
getContinuationManager()
Get the continuation manager.
Definition: ApiMain.php:359
static $Modules
List of available modules: action name => module class.
Definition: ApiMain.php:55
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output $out
Definition: hooks.txt:785
$mEnableWrite
Definition: ApiMain.php:150
static element( $element, $attribs=[], $contents='')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
Definition: Html.php:232
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:1145
static getRequestId()
Get the unique request ID.
Definition: WebRequest.php:275
executeActionWithErrorHandling()
Execute an action, and in case of an error, erase whatever partial results have been accumulated...
Definition: ApiMain.php:510
modifyHelp(array &$help, array $options, array &$tocData)
Definition: ApiMain.php:1895
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:187
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.
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses & $ret
Definition: hooks.txt:1996
bool null $lacksSameOriginSecurity
Cached return value from self::lacksSameOriginSecurity()
Definition: ApiMain.php:161
static isEveryoneAllowed( $right)
Check if all users may be assumed to have the given permission.
Definition: User.php:5058
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
addDeprecation( $msg, $feature, $data=[])
Add a deprecation warning for this module.
Definition: ApiBase.php:1908
initPrinter( $unused=false)
Initialize the printer function and prepare the output headers.
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2173
checkExecutePermissions( $module)
Check for sufficient permissions to execute.
Definition: ApiMain.php:1416
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
Definition: ApiBase.php:49
static instance()
Singleton.
Definition: Profiler.php:62
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.
$mCacheControl
Definition: ApiMain.php:156
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:252
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
Definition: Html.php:210
An IContextSource implementation which will inherit context from another source but allow individual ...
static static static ApiFormatBase $mPrinter
Definition: ApiMain.php:133
checkReadOnly( $module)
Check if the DB is read-only for this user.
Definition: ApiMain.php:1447
static isValidApiCode( $code)
Test whether a code is a valid API error code.
This manages continuation state.
isInternalMode()
Return true if the API was started by other PHP code using FauxRequest.
Definition: ApiMain.php:299
$value
setCacheControl( $directives)
Set directives (key/value pairs) for the Cache-Control header.
Definition: ApiMain.php:473
dieWithError( $msg, $code=null, $data=null, $httpCode=null)
Abort execution with an error.
Definition: ApiBase.php:1970
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user...
Definition: ApiBase.php:736
static preOutputCommit(IContextSource $context, callable $postCommitWork=null)
This function commits all DB changes as needed before the user can receive a response (in case commit...
Definition: MediaWiki.php:579
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency MediaWikiServices
Definition: injection.txt:23
const GETHEADER_LIST
Flag to make WebRequest::getHeader return an array of values.
Definition: WebRequest.php:48
msg( $key)
Get a Message object with context set Parameters are the same as wfMessage()
canApiHighLimits()
Check whether the current user is allowed to use high limits.
Definition: ApiMain.php:2039
errorMessagesFromException( $e, $type='error')
Create an error message for the given exception.
Definition: ApiMain.php:1021
static rollbackMasterChangesAndLog( $e)
Roll back any open database transactions and log the stack trace of the exception.
A helper class for throttling authentication attempts.
this hook is for auditing only $response
Definition: hooks.txt:785
const API_DEFAULT_FORMAT
When no format parameter is given, this format will be used.
Definition: ApiMain.php:45
see documentation in includes Linker php for Linker::makeImageLink & $time
Definition: hooks.txt:1813
IContextSource $context
This list may contain false positives That usually means there is additional text with links below the first Each row contains links to the first and second as well as the first line of the second redirect text
ApiBase $mModule
Definition: ApiMain.php:153
static static static $mRights
List of user roles that are specifically relevant to the API.
Definition: ApiMain.php:130
getParameter( $paramName, $parseLimit=true)
Get a value for the given parameter.
Definition: ApiBase.php:850
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED since 1.28! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:1994
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:170
const ID_FALLBACK
Tells escapeUrlForHtml() to encode the ID using the fallback encoding, or return false if no fallback...
Definition: Sanitizer.php:74
usually copyright or history_copyright This message must be in HTML not wikitext & $link
Definition: hooks.txt:3043
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:50
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return true
Definition: hooks.txt:1996
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:484
setRequestExpectations(ApiBase $module)
Set database connection, query, and write expectations given this module request. ...
Definition: ApiMain.php:1613
setupExternalResponse( $module, $params)
Check POST for external response and setup result printer.
Definition: ApiMain.php:1533
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:902
printResult( $httpCode=0)
Print results using the current printer.
Definition: ApiMain.php:1811
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.
static getGroupsWithPermission( $role)
Get all the groups who have a given permission.
Definition: User.php:5015
setCacheMode( $mode)
Set the type of caching headers which will be sent.
Definition: ApiMain.php:432
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:1289
checkAsserts( $params)
Check asserts of the user&#39;s rights.
Definition: ApiMain.php:1502
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:567
const LIMIT_SML2
Slow query, apihighlimits limit.
Definition: ApiBase.php:259
getContext()
Get the base IContextSource object.
$params
This is the main API class, used for both external and internal processing.
Definition: ApiMain.php:41
executeAction()
Execute the actual module, without any error handling.
Definition: ApiMain.php:1566
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
Definition: hooks.txt:1996
isReadMode()
Definition: ApiMain.php:1828
static closeElement( $element)
Returns "</$element>".
Definition: Html.php:310
handleCORS()
Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
Definition: ApiMain.php:672
setupExecuteAction()
Set up for the execution.
Definition: ApiMain.php:1176
getSensitiveParams()
Get the request parameters that should be considered sensitive.
Definition: ApiMain.php:1722
$mCacheMode
Definition: ApiMain.php:155
Format errors and warnings in the old style, for backwards compatibility.
$mErrorFormatter
Definition: ApiMain.php:146
lacksSameOriginSecurity()
Get the security flag for the current request.
Definition: ApiMain.php:316
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:856
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:214
This class represents the result of the API operations.
Definition: ApiResult.php:35
markParamsSensitive( $params)
Mark parameters as sensitive.
Definition: ApiMain.php:1731
$help
Definition: mcc.php:32
wfWikiID()
Get an ASCII string identifying this wiki This is used as a prefix in memcached keys.
$mParamsSensitive
Definition: ApiMain.php:158
$header
$mCanApiHighLimits
Definition: ApiMain.php:2033
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable & $code
Definition: hooks.txt:785
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
static static $Formats
List of available formats: format name => format class.
Definition: ApiMain.php:113
getParamsUsed()
Get the request parameters used in the course of the preceding execute() request. ...
Definition: ApiMain.php:1705
getExamplesMessages()
Definition: ApiMain.php:1886
getErrorFormatter()
Get the ApiErrorFormatter object associated with current request.
Definition: ApiMain.php:351
getCheck( $name)
Get a boolean request value, and register the fact that the parameter was used, for logging...
Definition: ApiMain.php:1762
logRequest( $time, $e=null)
Log the preceding request.
Definition: ApiMain.php:1632
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
sendCacheHeaders( $isError)
Send caching headers.
Definition: ApiMain.php:872
checkBotReadOnly()
Check whether we are readonly for bots.
Definition: ApiMain.php:1463
getModule()
Get the API module object.
Definition: ApiMain.php:382
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:1655
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:2157
static appendDebugInfoToApiResult(IContextSource $context, ApiResult $result)
Append the debug info to given ApiResult.
Definition: MWDebug.php:481
dieReadOnly()
Helper function for readonly errors.
Definition: ApiBase.php:2068
static newFromSpecifier( $value)
Transform a MessageSpecifier or a primitive value used interchangeably with specifiers (a message key...
Definition: Message.php:428
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
Definition: maintenance.txt:52
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not...
$mSquidMaxage
Definition: ApiMain.php:151
$mParamsUsed
Definition: ApiMain.php:157
addWarning( $msg, $code=null, $data=null)
Add a warning for this module.
Definition: ApiBase.php:1894
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:637
reportUnusedParams()
Report unused parameters, so the client gets a hint in case it gave us parameters we don&#39;t know...
Definition: ApiMain.php:1783
wfClearOutputBuffers()
More legible than passing a &#39;false&#39; parameter to wfResetOutputBuffers():
MediaWiki Logger LoggerFactory implements a PSR [0] compatible message logging system Named Psr Log LoggerInterface instances can be obtained from the MediaWiki Logger LoggerFactory::getInstance() static method. MediaWiki\Logger\LoggerFactory expects a class implementing the MediaWiki\Logger\Spi interface to act as a factory for new Psr\Log\LoggerInterface instances. The "Spi" in MediaWiki\Logger\Spi stands for "service provider interface". An SPI is an API intended to be implemented or extended by a third party. This software design pattern is intended to enable framework extension and replaceable components. It is specifically used in the MediaWiki\Logger\LoggerFactory service to allow alternate PSR-3 logging implementations to be easily integrated with MediaWiki. The service provider interface allows the backend logging library to be implemented in multiple ways. The $wgMWLoggerDefaultSpi global provides the classname of the default MediaWiki\Logger\Spi implementation to be loaded at runtime. This can either be the name of a class implementing the MediaWiki\Logger\Spi with a zero argument const ructor or a callable that will return an MediaWiki\Logger\Spi instance. Alternately the MediaWiki\Logger\LoggerFactory MediaWiki Logger LoggerFactory
Definition: logger.txt:5
This abstract class implements many basic API functions, and is the base of all API classes...
Definition: ApiBase.php:38
static singleton( $domain=false)
substituteResultWithError( $e)
Replace the result data with the information about an exception.
Definition: ApiMain.php:1059
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:276
getPrinter()
Get the result formatter object.
Definition: ApiMain.php:391
$messages
getStatusValue()
Fetch the error status.
static newFromName( $name, $validate='valid')
Static factory method for creation from username.
Definition: User.php:585
markParamsUsed( $params)
Mark parameters as used.
Definition: ApiMain.php:1713
getUpload( $name)
Get a request upload, and register the fact that it was used, for logging.
Definition: ApiMain.php:1773
setContinuationManager(ApiContinuationManager $manager=null)
Set the continuation manager.
Definition: ApiMain.php:367
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on $request
Definition: hooks.txt:2626
$mInternalMode
Definition: ApiMain.php:151
Interface for MediaWiki-localized exceptions.
$mModuleMgr
Definition: ApiMain.php:146
encodeRequestLogValue( $s)
Encode a value in a format suitable for a space-separated log line.
Definition: ApiMain.php:1688
execute()
Execute api request.
Definition: ApiMain.php:498
return true to allow those checks to and false if checking is done & $user
Definition: hooks.txt:1487
static listParam(array $list, $type='text')
Definition: Message.php:1127
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:792
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:308
createErrorPrinter()
Create the printer for error output.
Definition: ApiMain.php:990
isWriteMode()
Indicates whether this module requires write mode.
Definition: ApiBase.php:412
ApiContinuationManager null $mContinuationManager
Definition: ApiMain.php:148
getVal( $name, $default=null)
Get a request value, and register the fact that it was used, for logging.
Definition: ApiMain.php:1741