MediaWiki  1.30.0
ApiMain.php
Go to the documentation of this file.
1 <?php
28 use Wikimedia\Timestamp\TimestampException;
31 
45 class ApiMain extends ApiBase {
49  const API_DEFAULT_FORMAT = 'jsonfm';
50 
54  const API_DEFAULT_USELANG = 'user';
55 
59  private static $Modules = [
60  'login' => 'ApiLogin',
61  'clientlogin' => 'ApiClientLogin',
62  'logout' => 'ApiLogout',
63  'createaccount' => 'ApiAMCreateAccount',
64  'linkaccount' => 'ApiLinkAccount',
65  'unlinkaccount' => 'ApiRemoveAuthenticationData',
66  'changeauthenticationdata' => 'ApiChangeAuthenticationData',
67  'removeauthenticationdata' => 'ApiRemoveAuthenticationData',
68  'resetpassword' => 'ApiResetPassword',
69  'query' => 'ApiQuery',
70  'expandtemplates' => 'ApiExpandTemplates',
71  'parse' => 'ApiParse',
72  'stashedit' => 'ApiStashEdit',
73  'opensearch' => 'ApiOpenSearch',
74  'feedcontributions' => 'ApiFeedContributions',
75  'feedrecentchanges' => 'ApiFeedRecentChanges',
76  'feedwatchlist' => 'ApiFeedWatchlist',
77  'help' => 'ApiHelp',
78  'paraminfo' => 'ApiParamInfo',
79  'rsd' => 'ApiRsd',
80  'compare' => 'ApiComparePages',
81  'tokens' => 'ApiTokens',
82  'checktoken' => 'ApiCheckToken',
83  'cspreport' => 'ApiCSPReport',
84  'validatepassword' => 'ApiValidatePassword',
85 
86  // Write modules
87  'purge' => 'ApiPurge',
88  'setnotificationtimestamp' => 'ApiSetNotificationTimestamp',
89  'rollback' => 'ApiRollback',
90  'delete' => 'ApiDelete',
91  'undelete' => 'ApiUndelete',
92  'protect' => 'ApiProtect',
93  'block' => 'ApiBlock',
94  'unblock' => 'ApiUnblock',
95  'move' => 'ApiMove',
96  'edit' => 'ApiEditPage',
97  'upload' => 'ApiUpload',
98  'filerevert' => 'ApiFileRevert',
99  'emailuser' => 'ApiEmailUser',
100  'watch' => 'ApiWatch',
101  'patrol' => 'ApiPatrol',
102  'import' => 'ApiImport',
103  'clearhasmsg' => 'ApiClearHasMsg',
104  'userrights' => 'ApiUserrights',
105  'options' => 'ApiOptions',
106  'imagerotate' => 'ApiImageRotate',
107  'revisiondelete' => 'ApiRevisionDelete',
108  'managetags' => 'ApiManageTags',
109  'tag' => 'ApiTag',
110  'mergehistory' => 'ApiMergeHistory',
111  'setpagelanguage' => 'ApiSetPageLanguage',
112  ];
113 
117  private static $Formats = [
118  'json' => 'ApiFormatJson',
119  'jsonfm' => 'ApiFormatJson',
120  'php' => 'ApiFormatPhp',
121  'phpfm' => 'ApiFormatPhp',
122  'xml' => 'ApiFormatXml',
123  'xmlfm' => 'ApiFormatXml',
124  'rawfm' => 'ApiFormatJson',
125  'none' => 'ApiFormatNone',
126  ];
127 
128  // @codingStandardsIgnoreStart String contenation on "msg" not allowed to break long line
135  private static $mRights = [
136  'writeapi' => [
137  'msg' => 'right-writeapi',
138  'params' => []
139  ],
140  'apihighlimits' => [
141  'msg' => 'api-help-right-apihighlimits',
143  ]
144  ];
145  // @codingStandardsIgnoreEnd
146 
150  private $mPrinter;
151 
155  private $mAction;
156  private $mEnableWrite;
159  private $mModule;
160 
161  private $mCacheMode = 'private';
162  private $mCacheControl = [];
163  private $mParamsUsed = [];
164  private $mParamsSensitive = [];
165 
167  private $lacksSameOriginSecurity = null;
168 
176  public function __construct( $context = null, $enableWrite = false ) {
177  if ( $context === null ) {
179  } elseif ( $context instanceof WebRequest ) {
180  // BC for pre-1.19
181  $request = $context;
183  }
184  // We set a derivative context so we can change stuff later
185  $this->setContext( new DerivativeContext( $context ) );
186 
187  if ( isset( $request ) ) {
188  $this->getContext()->setRequest( $request );
189  } else {
190  $request = $this->getRequest();
191  }
192 
193  $this->mInternalMode = ( $request instanceof FauxRequest );
194 
195  // Special handling for the main module: $parent === $this
196  parent::__construct( $this, $this->mInternalMode ? 'main_int' : 'main' );
197 
198  $config = $this->getConfig();
199 
200  if ( !$this->mInternalMode ) {
201  // Log if a request with a non-whitelisted Origin header is seen
202  // with session cookies.
203  $originHeader = $request->getHeader( 'Origin' );
204  if ( $originHeader === false ) {
205  $origins = [];
206  } else {
207  $originHeader = trim( $originHeader );
208  $origins = preg_split( '/\s+/', $originHeader );
209  }
210  $sessionCookies = array_intersect(
211  array_keys( $_COOKIE ),
212  MediaWiki\Session\SessionManager::singleton()->getVaryCookies()
213  );
214  if ( $origins && $sessionCookies && (
215  count( $origins ) !== 1 || !self::matchOrigin(
216  $origins[0],
217  $config->get( 'CrossSiteAJAXdomains' ),
218  $config->get( 'CrossSiteAJAXdomainExceptions' )
219  )
220  ) ) {
221  LoggerFactory::getInstance( 'cors' )->warning(
222  'Non-whitelisted CORS request with session cookies', [
223  'origin' => $originHeader,
224  'cookies' => $sessionCookies,
225  'ip' => $request->getIP(),
226  'userAgent' => $this->getUserAgent(),
227  'wiki' => wfWikiID(),
228  ]
229  );
230  }
231 
232  // If we're in a mode that breaks the same-origin policy, strip
233  // user credentials for security.
234  if ( $this->lacksSameOriginSecurity() ) {
235  global $wgUser;
236  wfDebug( "API: stripping user credentials when the same-origin policy is not applied\n" );
237  $wgUser = new User();
238  $this->getContext()->setUser( $wgUser );
239  $request->response()->header( 'MediaWiki-Login-Suppressed: true' );
240  }
241  }
242 
243  $this->mResult = new ApiResult( $this->getConfig()->get( 'APIMaxResultSize' ) );
244 
245  // Setup uselang. This doesn't use $this->getParameter()
246  // because we're not ready to handle errors yet.
247  $uselang = $request->getVal( 'uselang', self::API_DEFAULT_USELANG );
248  if ( $uselang === 'user' ) {
249  // Assume the parent context is going to return the user language
250  // for uselang=user (see T85635).
251  } else {
252  if ( $uselang === 'content' ) {
254  $uselang = $wgContLang->getCode();
255  }
257  $this->getContext()->setLanguage( $code );
258  if ( !$this->mInternalMode ) {
259  global $wgLang;
260  $wgLang = $this->getContext()->getLanguage();
261  RequestContext::getMain()->setLanguage( $wgLang );
262  }
263  }
264 
265  // Set up the error formatter. This doesn't use $this->getParameter()
266  // because we're not ready to handle errors yet.
267  $errorFormat = $request->getVal( 'errorformat', 'bc' );
268  $errorLangCode = $request->getVal( 'errorlang', 'uselang' );
269  $errorsUseDB = $request->getCheck( 'errorsuselocal' );
270  if ( in_array( $errorFormat, [ 'plaintext', 'wikitext', 'html', 'raw', 'none' ], true ) ) {
271  if ( $errorLangCode === 'uselang' ) {
272  $errorLang = $this->getLanguage();
273  } elseif ( $errorLangCode === 'content' ) {
275  $errorLang = $wgContLang;
276  } else {
277  $errorLangCode = RequestContext::sanitizeLangCode( $errorLangCode );
278  $errorLang = Language::factory( $errorLangCode );
279  }
280  $this->mErrorFormatter = new ApiErrorFormatter(
281  $this->mResult, $errorLang, $errorFormat, $errorsUseDB
282  );
283  } else {
284  $this->mErrorFormatter = new ApiErrorFormatter_BackCompat( $this->mResult );
285  }
286  $this->mResult->setErrorFormatter( $this->getErrorFormatter() );
287 
288  $this->mModuleMgr = new ApiModuleManager( $this );
289  $this->mModuleMgr->addModules( self::$Modules, 'action' );
290  $this->mModuleMgr->addModules( $config->get( 'APIModules' ), 'action' );
291  $this->mModuleMgr->addModules( self::$Formats, 'format' );
292  $this->mModuleMgr->addModules( $config->get( 'APIFormatModules' ), 'format' );
293 
294  Hooks::run( 'ApiMain::moduleManager', [ $this->mModuleMgr ] );
295 
296  $this->mContinuationManager = null;
297  $this->mEnableWrite = $enableWrite;
298 
299  $this->mSquidMaxage = -1; // flag for executeActionWithErrorHandling()
300  $this->mCommit = false;
301  }
302 
307  public function isInternalMode() {
308  return $this->mInternalMode;
309  }
310 
316  public function getResult() {
317  return $this->mResult;
318  }
319 
324  public function lacksSameOriginSecurity() {
325  if ( $this->lacksSameOriginSecurity !== null ) {
327  }
328 
329  $request = $this->getRequest();
330 
331  // JSONP mode
332  if ( $request->getVal( 'callback' ) !== null ) {
333  $this->lacksSameOriginSecurity = true;
334  return true;
335  }
336 
337  // Anonymous CORS
338  if ( $request->getVal( 'origin' ) === '*' ) {
339  $this->lacksSameOriginSecurity = true;
340  return true;
341  }
342 
343  // Header to be used from XMLHTTPRequest when the request might
344  // otherwise be used for XSS.
345  if ( $request->getHeader( 'Treat-as-Untrusted' ) !== false ) {
346  $this->lacksSameOriginSecurity = true;
347  return true;
348  }
349 
350  // Allow extensions to override.
351  $this->lacksSameOriginSecurity = !Hooks::run( 'RequestHasSameOriginSecurity', [ $request ] );
353  }
354 
359  public function getErrorFormatter() {
360  return $this->mErrorFormatter;
361  }
362 
367  public function getContinuationManager() {
369  }
370 
375  public function setContinuationManager( $manager ) {
376  if ( $manager !== null ) {
377  if ( !$manager instanceof ApiContinuationManager ) {
378  throw new InvalidArgumentException( __METHOD__ . ': Was passed ' .
379  is_object( $manager ) ? get_class( $manager ) : gettype( $manager )
380  );
381  }
382  if ( $this->mContinuationManager !== null ) {
383  throw new UnexpectedValueException(
384  __METHOD__ . ': tried to set manager from ' . $manager->getSource() .
385  ' when a manager is already set from ' . $this->mContinuationManager->getSource()
386  );
387  }
388  }
389  $this->mContinuationManager = $manager;
390  }
391 
397  public function getModule() {
398  return $this->mModule;
399  }
400 
406  public function getPrinter() {
407  return $this->mPrinter;
408  }
409 
415  public function setCacheMaxAge( $maxage ) {
416  $this->setCacheControl( [
417  'max-age' => $maxage,
418  's-maxage' => $maxage
419  ] );
420  }
421 
447  public function setCacheMode( $mode ) {
448  if ( !in_array( $mode, [ 'private', 'public', 'anon-public-user-private' ] ) ) {
449  wfDebug( __METHOD__ . ": unrecognised cache mode \"$mode\"\n" );
450 
451  // Ignore for forwards-compatibility
452  return;
453  }
454 
455  if ( !User::isEveryoneAllowed( 'read' ) ) {
456  // Private wiki, only private headers
457  if ( $mode !== 'private' ) {
458  wfDebug( __METHOD__ . ": ignoring request for $mode cache mode, private wiki\n" );
459 
460  return;
461  }
462  }
463 
464  if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) {
465  // User language is used for i18n, so we don't want to publicly
466  // cache. Anons are ok, because if they have non-default language
467  // then there's an appropriate Vary header set by whatever set
468  // their non-default language.
469  wfDebug( __METHOD__ . ": downgrading cache mode 'public' to " .
470  "'anon-public-user-private' due to uselang=user\n" );
471  $mode = 'anon-public-user-private';
472  }
473 
474  wfDebug( __METHOD__ . ": setting cache mode $mode\n" );
475  $this->mCacheMode = $mode;
476  }
477 
488  public function setCacheControl( $directives ) {
489  $this->mCacheControl = $directives + $this->mCacheControl;
490  }
491 
499  public function createPrinterByName( $format ) {
500  $printer = $this->mModuleMgr->getModule( $format, 'format' );
501  if ( $printer === null ) {
502  $this->dieWithError(
503  [ 'apierror-unknownformat', wfEscapeWikiText( $format ) ], 'unknown_format'
504  );
505  }
506 
507  return $printer;
508  }
509 
513  public function execute() {
514  if ( $this->mInternalMode ) {
515  $this->executeAction();
516  } else {
518  }
519  }
520 
525  protected function executeActionWithErrorHandling() {
526  // Verify the CORS header before executing the action
527  if ( !$this->handleCORS() ) {
528  // handleCORS() has sent a 403, abort
529  return;
530  }
531 
532  // Exit here if the request method was OPTIONS
533  // (assume there will be a followup GET or POST)
534  if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
535  return;
536  }
537 
538  // In case an error occurs during data output,
539  // clear the output buffer and print just the error information
540  $obLevel = ob_get_level();
541  ob_start();
542 
543  $t = microtime( true );
544  $isError = false;
545  try {
546  $this->executeAction();
547  $runTime = microtime( true ) - $t;
548  $this->logRequest( $runTime );
549  if ( $this->mModule->isWriteMode() && $this->getRequest()->wasPosted() ) {
550  MediaWikiServices::getInstance()->getStatsdDataFactory()->timing(
551  'api.' . $this->mModule->getModuleName() . '.executeTiming', 1000 * $runTime
552  );
553  }
554  } catch ( Exception $e ) {
555  $this->handleException( $e );
556  $this->logRequest( microtime( true ) - $t, $e );
557  $isError = true;
558  }
559 
560  // Commit DBs and send any related cookies and headers
562 
563  // Send cache headers after any code which might generate an error, to
564  // avoid sending public cache headers for errors.
565  $this->sendCacheHeaders( $isError );
566 
567  // Executing the action might have already messed with the output
568  // buffers.
569  while ( ob_get_level() > $obLevel ) {
570  ob_end_flush();
571  }
572  }
573 
580  protected function handleException( Exception $e ) {
581  // T65145: Rollback any open database transactions
582  if ( !( $e instanceof ApiUsageException || $e instanceof UsageException ) ) {
583  // UsageExceptions are intentional, so don't rollback if that's the case
585  }
586 
587  // Allow extra cleanup and logging
588  Hooks::run( 'ApiMain::onException', [ $this, $e ] );
589 
590  // Handle any kind of exception by outputting properly formatted error message.
591  // If this fails, an unhandled exception should be thrown so that global error
592  // handler will process and log it.
593 
594  $errCodes = $this->substituteResultWithError( $e );
595 
596  // Error results should not be cached
597  $this->setCacheMode( 'private' );
598 
599  $response = $this->getRequest()->response();
600  $headerStr = 'MediaWiki-API-Error: ' . join( ', ', $errCodes );
601  $response->header( $headerStr );
602 
603  // Reset and print just the error message
604  ob_clean();
605 
606  // Printer may not be initialized if the extractRequestParams() fails for the main module
607  $this->createErrorPrinter();
608 
609  $failed = false;
610  try {
611  $this->printResult( $e->getCode() );
612  } catch ( ApiUsageException $ex ) {
613  // The error printer itself is failing. Try suppressing its request
614  // parameters and redo.
615  $failed = true;
616  $this->addWarning( 'apiwarn-errorprinterfailed' );
617  foreach ( $ex->getStatusValue()->getErrors() as $error ) {
618  try {
619  $this->mPrinter->addWarning( $error );
620  } catch ( Exception $ex2 ) {
621  // WTF?
622  $this->addWarning( $error );
623  }
624  }
625  } catch ( UsageException $ex ) {
626  // The error printer itself is failing. Try suppressing its request
627  // parameters and redo.
628  $failed = true;
629  $this->addWarning(
630  [ 'apiwarn-errorprinterfailed-ex', $ex->getMessage() ], 'errorprinterfailed'
631  );
632  }
633  if ( $failed ) {
634  $this->mPrinter = null;
635  $this->createErrorPrinter();
636  $this->mPrinter->forceDefaultParams();
637  if ( $e->getCode() ) {
638  $response->statusHeader( 200 ); // Reset in case the fallback doesn't want a non-200
639  }
640  $this->printResult( $e->getCode() );
641  }
642  }
643 
654  public static function handleApiBeforeMainException( Exception $e ) {
655  ob_start();
656 
657  try {
658  $main = new self( RequestContext::getMain(), false );
659  $main->handleException( $e );
660  $main->logRequest( 0, $e );
661  } catch ( Exception $e2 ) {
662  // Nope, even that didn't work. Punt.
663  throw $e;
664  }
665 
666  // Reset cache headers
667  $main->sendCacheHeaders( true );
668 
669  ob_end_flush();
670  }
671 
686  protected function handleCORS() {
687  $originParam = $this->getParameter( 'origin' ); // defaults to null
688  if ( $originParam === null ) {
689  // No origin parameter, nothing to do
690  return true;
691  }
692 
693  $request = $this->getRequest();
694  $response = $request->response();
695 
696  $matchedOrigin = false;
697  $allowTiming = false;
698  $varyOrigin = true;
699 
700  if ( $originParam === '*' ) {
701  // Request for anonymous CORS
702  // Technically we should check for the presence of an Origin header
703  // and not process it as CORS if it's not set, but that would
704  // require us to vary on Origin for all 'origin=*' requests which
705  // we don't want to do.
706  $matchedOrigin = true;
707  $allowOrigin = '*';
708  $allowCredentials = 'false';
709  $varyOrigin = false; // No need to vary
710  } else {
711  // Non-anonymous CORS, check we allow the domain
712 
713  // Origin: header is a space-separated list of origins, check all of them
714  $originHeader = $request->getHeader( 'Origin' );
715  if ( $originHeader === false ) {
716  $origins = [];
717  } else {
718  $originHeader = trim( $originHeader );
719  $origins = preg_split( '/\s+/', $originHeader );
720  }
721 
722  if ( !in_array( $originParam, $origins ) ) {
723  // origin parameter set but incorrect
724  // Send a 403 response
725  $response->statusHeader( 403 );
726  $response->header( 'Cache-Control: no-cache' );
727  echo "'origin' parameter does not match Origin header\n";
728 
729  return false;
730  }
731 
732  $config = $this->getConfig();
733  $matchedOrigin = count( $origins ) === 1 && self::matchOrigin(
734  $originParam,
735  $config->get( 'CrossSiteAJAXdomains' ),
736  $config->get( 'CrossSiteAJAXdomainExceptions' )
737  );
738 
739  $allowOrigin = $originHeader;
740  $allowCredentials = 'true';
741  $allowTiming = $originHeader;
742  }
743 
744  if ( $matchedOrigin ) {
745  $requestedMethod = $request->getHeader( 'Access-Control-Request-Method' );
746  $preflight = $request->getMethod() === 'OPTIONS' && $requestedMethod !== false;
747  if ( $preflight ) {
748  // This is a CORS preflight request
749  if ( $requestedMethod !== 'POST' && $requestedMethod !== 'GET' ) {
750  // If method is not a case-sensitive match, do not set any additional headers and terminate.
751  $response->header( 'MediaWiki-CORS-Rejection: Unsupported method requested in preflight' );
752  return true;
753  }
754  // We allow the actual request to send the following headers
755  $requestedHeaders = $request->getHeader( 'Access-Control-Request-Headers' );
756  if ( $requestedHeaders !== false ) {
757  if ( !self::matchRequestedHeaders( $requestedHeaders ) ) {
758  $response->header( 'MediaWiki-CORS-Rejection: Unsupported header requested in preflight' );
759  return true;
760  }
761  $response->header( 'Access-Control-Allow-Headers: ' . $requestedHeaders );
762  }
763 
764  // We only allow the actual request to be GET or POST
765  $response->header( 'Access-Control-Allow-Methods: POST, GET' );
766  } elseif ( $request->getMethod() !== 'POST' && $request->getMethod() !== 'GET' ) {
767  // Unsupported non-preflight method, don't handle it as CORS
768  $response->header(
769  'MediaWiki-CORS-Rejection: Unsupported method for simple request or actual request'
770  );
771  return true;
772  }
773 
774  $response->header( "Access-Control-Allow-Origin: $allowOrigin" );
775  $response->header( "Access-Control-Allow-Credentials: $allowCredentials" );
776  // https://www.w3.org/TR/resource-timing/#timing-allow-origin
777  if ( $allowTiming !== false ) {
778  $response->header( "Timing-Allow-Origin: $allowTiming" );
779  }
780 
781  if ( !$preflight ) {
782  $response->header(
783  'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag, '
784  . 'MediaWiki-Login-Suppressed'
785  );
786  }
787  } else {
788  $response->header( 'MediaWiki-CORS-Rejection: Origin mismatch' );
789  }
790 
791  if ( $varyOrigin ) {
792  $this->getOutput()->addVaryHeader( 'Origin' );
793  }
794 
795  return true;
796  }
797 
806  protected static function matchOrigin( $value, $rules, $exceptions ) {
807  foreach ( $rules as $rule ) {
808  if ( preg_match( self::wildcardToRegex( $rule ), $value ) ) {
809  // Rule matches, check exceptions
810  foreach ( $exceptions as $exc ) {
811  if ( preg_match( self::wildcardToRegex( $exc ), $value ) ) {
812  return false;
813  }
814  }
815 
816  return true;
817  }
818  }
819 
820  return false;
821  }
822 
830  protected static function matchRequestedHeaders( $requestedHeaders ) {
831  if ( trim( $requestedHeaders ) === '' ) {
832  return true;
833  }
834  $requestedHeaders = explode( ',', $requestedHeaders );
835  $allowedAuthorHeaders = array_flip( [
836  /* simple headers (see spec) */
837  'accept',
838  'accept-language',
839  'content-language',
840  'content-type',
841  /* non-authorable headers in XHR, which are however requested by some UAs */
842  'accept-encoding',
843  'dnt',
844  'origin',
845  /* MediaWiki whitelist */
846  'api-user-agent',
847  ] );
848  foreach ( $requestedHeaders as $rHeader ) {
849  $rHeader = strtolower( trim( $rHeader ) );
850  if ( !isset( $allowedAuthorHeaders[$rHeader] ) ) {
851  wfDebugLog( 'api', 'CORS preflight failed on requested header: ' . $rHeader );
852  return false;
853  }
854  }
855  return true;
856  }
857 
866  protected static function wildcardToRegex( $wildcard ) {
867  $wildcard = preg_quote( $wildcard, '/' );
868  $wildcard = str_replace(
869  [ '\*', '\?' ],
870  [ '.*?', '.' ],
871  $wildcard
872  );
873 
874  return "/^https?:\/\/$wildcard$/";
875  }
876 
882  protected function sendCacheHeaders( $isError ) {
883  $response = $this->getRequest()->response();
884  $out = $this->getOutput();
885 
886  $out->addVaryHeader( 'Treat-as-Untrusted' );
887 
888  $config = $this->getConfig();
889 
890  if ( $config->get( 'VaryOnXFP' ) ) {
891  $out->addVaryHeader( 'X-Forwarded-Proto' );
892  }
893 
894  if ( !$isError && $this->mModule &&
895  ( $this->getRequest()->getMethod() === 'GET' || $this->getRequest()->getMethod() === 'HEAD' )
896  ) {
897  $etag = $this->mModule->getConditionalRequestData( 'etag' );
898  if ( $etag !== null ) {
899  $response->header( "ETag: $etag" );
900  }
901  $lastMod = $this->mModule->getConditionalRequestData( 'last-modified' );
902  if ( $lastMod !== null ) {
903  $response->header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822, $lastMod ) );
904  }
905  }
906 
907  // The logic should be:
908  // $this->mCacheControl['max-age'] is set?
909  // Use it, the module knows better than our guess.
910  // !$this->mModule || $this->mModule->isWriteMode(), and mCacheMode is private?
911  // Use 0 because we can guess caching is probably the wrong thing to do.
912  // Use $this->getParameter( 'maxage' ), which already defaults to 0.
913  $maxage = 0;
914  if ( isset( $this->mCacheControl['max-age'] ) ) {
915  $maxage = $this->mCacheControl['max-age'];
916  } elseif ( ( $this->mModule && !$this->mModule->isWriteMode() ) ||
917  $this->mCacheMode !== 'private'
918  ) {
919  $maxage = $this->getParameter( 'maxage' );
920  }
921  $privateCache = 'private, must-revalidate, max-age=' . $maxage;
922 
923  if ( $this->mCacheMode == 'private' ) {
924  $response->header( "Cache-Control: $privateCache" );
925  return;
926  }
927 
928  $useKeyHeader = $config->get( 'UseKeyHeader' );
929  if ( $this->mCacheMode == 'anon-public-user-private' ) {
930  $out->addVaryHeader( 'Cookie' );
931  $response->header( $out->getVaryHeader() );
932  if ( $useKeyHeader ) {
933  $response->header( $out->getKeyHeader() );
934  if ( $out->haveCacheVaryCookies() ) {
935  // Logged in, mark this request private
936  $response->header( "Cache-Control: $privateCache" );
937  return;
938  }
939  // Logged out, send normal public headers below
940  } elseif ( MediaWiki\Session\SessionManager::getGlobalSession()->isPersistent() ) {
941  // Logged in or otherwise has session (e.g. anonymous users who have edited)
942  // Mark request private
943  $response->header( "Cache-Control: $privateCache" );
944 
945  return;
946  } // else no Key and anonymous, send public headers below
947  }
948 
949  // Send public headers
950  $response->header( $out->getVaryHeader() );
951  if ( $useKeyHeader ) {
952  $response->header( $out->getKeyHeader() );
953  }
954 
955  // If nobody called setCacheMaxAge(), use the (s)maxage parameters
956  if ( !isset( $this->mCacheControl['s-maxage'] ) ) {
957  $this->mCacheControl['s-maxage'] = $this->getParameter( 'smaxage' );
958  }
959  if ( !isset( $this->mCacheControl['max-age'] ) ) {
960  $this->mCacheControl['max-age'] = $this->getParameter( 'maxage' );
961  }
962 
963  if ( !$this->mCacheControl['s-maxage'] && !$this->mCacheControl['max-age'] ) {
964  // Public cache not requested
965  // Sending a Vary header in this case is harmless, and protects us
966  // against conditional calls of setCacheMaxAge().
967  $response->header( "Cache-Control: $privateCache" );
968 
969  return;
970  }
971 
972  $this->mCacheControl['public'] = true;
973 
974  // Send an Expires header
975  $maxAge = min( $this->mCacheControl['s-maxage'], $this->mCacheControl['max-age'] );
976  $expiryUnixTime = ( $maxAge == 0 ? 1 : time() + $maxAge );
977  $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822, $expiryUnixTime ) );
978 
979  // Construct the Cache-Control header
980  $ccHeader = '';
981  $separator = '';
982  foreach ( $this->mCacheControl as $name => $value ) {
983  if ( is_bool( $value ) ) {
984  if ( $value ) {
985  $ccHeader .= $separator . $name;
986  $separator = ', ';
987  }
988  } else {
989  $ccHeader .= $separator . "$name=$value";
990  $separator = ', ';
991  }
992  }
993 
994  $response->header( "Cache-Control: $ccHeader" );
995  }
996 
1000  private function createErrorPrinter() {
1001  if ( !isset( $this->mPrinter ) ) {
1002  $value = $this->getRequest()->getVal( 'format', self::API_DEFAULT_FORMAT );
1003  if ( !$this->mModuleMgr->isDefined( $value, 'format' ) ) {
1005  }
1006  $this->mPrinter = $this->createPrinterByName( $value );
1007  }
1008 
1009  // Printer may not be able to handle errors. This is particularly
1010  // likely if the module returns something for getCustomPrinter().
1011  if ( !$this->mPrinter->canPrintErrors() ) {
1012  $this->mPrinter = $this->createPrinterByName( self::API_DEFAULT_FORMAT );
1013  }
1014  }
1015 
1034  protected function errorMessagesFromException( $e, $type = 'error' ) {
1035  $messages = [];
1036  if ( $e instanceof ApiUsageException ) {
1037  foreach ( $e->getStatusValue()->getErrorsByType( $type ) as $error ) {
1038  $messages[] = ApiMessage::create( $error );
1039  }
1040  } elseif ( $type !== 'error' ) {
1041  // None of the rest have any messages for non-error types
1042  } elseif ( $e instanceof UsageException ) {
1043  // User entered incorrect parameters - generate error response
1044  $data = MediaWiki\quietCall( [ $e, 'getMessageArray' ] );
1045  $code = $data['code'];
1046  $info = $data['info'];
1047  unset( $data['code'], $data['info'] );
1048  $messages[] = new ApiRawMessage( [ '$1', $info ], $code, $data );
1049  } else {
1050  // Something is seriously wrong
1051  $config = $this->getConfig();
1052  $class = preg_replace( '#^Wikimedia\\\Rdbms\\\#', '', get_class( $e ) );
1053  $code = 'internal_api_error_' . $class;
1054  if ( ( $e instanceof DBQueryError ) && !$config->get( 'ShowSQLErrors' ) ) {
1055  $params = [ 'apierror-databaseerror', WebRequest::getRequestId() ];
1056  } else {
1057  $params = [
1058  'apierror-exceptioncaught',
1060  $e instanceof ILocalizedException
1061  ? $e->getMessageObject()
1062  : wfEscapeWikiText( $e->getMessage() )
1063  ];
1064  }
1066  }
1067  return $messages;
1068  }
1069 
1075  protected function substituteResultWithError( $e ) {
1076  $result = $this->getResult();
1077  $formatter = $this->getErrorFormatter();
1078  $config = $this->getConfig();
1079  $errorCodes = [];
1080 
1081  // Remember existing warnings and errors across the reset
1082  $errors = $result->getResultData( [ 'errors' ] );
1083  $warnings = $result->getResultData( [ 'warnings' ] );
1084  $result->reset();
1085  if ( $warnings !== null ) {
1086  $result->addValue( null, 'warnings', $warnings, ApiResult::NO_SIZE_CHECK );
1087  }
1088  if ( $errors !== null ) {
1089  $result->addValue( null, 'errors', $errors, ApiResult::NO_SIZE_CHECK );
1090 
1091  // Collect the copied error codes for the return value
1092  foreach ( $errors as $error ) {
1093  if ( isset( $error['code'] ) ) {
1094  $errorCodes[$error['code']] = true;
1095  }
1096  }
1097  }
1098 
1099  // Add errors from the exception
1100  $modulePath = $e instanceof ApiUsageException ? $e->getModulePath() : null;
1101  foreach ( $this->errorMessagesFromException( $e, 'error' ) as $msg ) {
1102  $errorCodes[$msg->getApiCode()] = true;
1103  $formatter->addError( $modulePath, $msg );
1104  }
1105  foreach ( $this->errorMessagesFromException( $e, 'warning' ) as $msg ) {
1106  $formatter->addWarning( $modulePath, $msg );
1107  }
1108 
1109  // Add additional data. Path depends on whether we're in BC mode or not.
1110  // Data depends on the type of exception.
1111  if ( $formatter instanceof ApiErrorFormatter_BackCompat ) {
1112  $path = [ 'error' ];
1113  } else {
1114  $path = null;
1115  }
1116  if ( $e instanceof ApiUsageException || $e instanceof UsageException ) {
1117  $link = wfExpandUrl( wfScript( 'api' ) );
1118  $result->addContentValue(
1119  $path,
1120  'docref',
1121  trim(
1122  $this->msg( 'api-usage-docref', $link )->inLanguage( $formatter->getLanguage() )->text()
1123  . ' '
1124  . $this->msg( 'api-usage-mailinglist-ref' )->inLanguage( $formatter->getLanguage() )->text()
1125  )
1126  );
1127  } else {
1128  if ( $config->get( 'ShowExceptionDetails' ) &&
1129  ( !$e instanceof DBError || $config->get( 'ShowDBErrorBacktrace' ) )
1130  ) {
1131  $result->addContentValue(
1132  $path,
1133  'trace',
1134  $this->msg( 'api-exception-trace',
1135  get_class( $e ),
1136  $e->getFile(),
1137  $e->getLine(),
1139  )->inLanguage( $formatter->getLanguage() )->text()
1140  );
1141  }
1142  }
1143 
1144  // Add the id and such
1145  $this->addRequestedFields( [ 'servedby' ] );
1146 
1147  return array_keys( $errorCodes );
1148  }
1149 
1155  protected function addRequestedFields( $force = [] ) {
1156  $result = $this->getResult();
1157 
1158  $requestid = $this->getParameter( 'requestid' );
1159  if ( $requestid !== null ) {
1160  $result->addValue( null, 'requestid', $requestid, ApiResult::NO_SIZE_CHECK );
1161  }
1162 
1163  if ( $this->getConfig()->get( 'ShowHostnames' ) && (
1164  in_array( 'servedby', $force, true ) || $this->getParameter( 'servedby' )
1165  ) ) {
1166  $result->addValue( null, 'servedby', wfHostname(), ApiResult::NO_SIZE_CHECK );
1167  }
1168 
1169  if ( $this->getParameter( 'curtimestamp' ) ) {
1170  $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601, time() ),
1172  }
1173 
1174  if ( $this->getParameter( 'responselanginfo' ) ) {
1175  $result->addValue( null, 'uselang', $this->getLanguage()->getCode(),
1177  $result->addValue( null, 'errorlang', $this->getErrorFormatter()->getLanguage()->getCode(),
1179  }
1180  }
1181 
1186  protected function setupExecuteAction() {
1187  $this->addRequestedFields();
1188 
1189  $params = $this->extractRequestParams();
1190  $this->mAction = $params['action'];
1191 
1192  return $params;
1193  }
1194 
1201  protected function setupModule() {
1202  // Instantiate the module requested by the user
1203  $module = $this->mModuleMgr->getModule( $this->mAction, 'action' );
1204  if ( $module === null ) {
1205  $this->dieWithError(
1206  [ 'apierror-unknownaction', wfEscapeWikiText( $this->mAction ) ], 'unknown_action'
1207  );
1208  }
1209  $moduleParams = $module->extractRequestParams();
1210 
1211  // Check token, if necessary
1212  if ( $module->needsToken() === true ) {
1213  throw new MWException(
1214  "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
1215  'See documentation for ApiBase::needsToken for details.'
1216  );
1217  }
1218  if ( $module->needsToken() ) {
1219  if ( !$module->mustBePosted() ) {
1220  throw new MWException(
1221  "Module '{$module->getModuleName()}' must require POST to use tokens."
1222  );
1223  }
1224 
1225  if ( !isset( $moduleParams['token'] ) ) {
1226  $module->dieWithError( [ 'apierror-missingparam', 'token' ] );
1227  }
1228 
1229  $module->requirePostedParameters( [ 'token' ] );
1230 
1231  if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) {
1232  $module->dieWithError( 'apierror-badtoken' );
1233  }
1234  }
1235 
1236  return $module;
1237  }
1238 
1242  private function getMaxLag() {
1243  $dbLag = MediaWikiServices::getInstance()->getDBLoadBalancer()->getMaxLag();
1244  $lagInfo = [
1245  'host' => $dbLag[0],
1246  'lag' => $dbLag[1],
1247  'type' => 'db'
1248  ];
1249 
1250  $jobQueueLagFactor = $this->getConfig()->get( 'JobQueueIncludeInMaxLagFactor' );
1251  if ( $jobQueueLagFactor ) {
1252  // Turn total number of jobs into seconds by using the configured value
1253  $totalJobs = array_sum( JobQueueGroup::singleton()->getQueueSizes() );
1254  $jobQueueLag = $totalJobs / (float)$jobQueueLagFactor;
1255  if ( $jobQueueLag > $lagInfo['lag'] ) {
1256  $lagInfo = [
1257  'host' => wfHostname(), // XXX: Is there a better value that could be used?
1258  'lag' => $jobQueueLag,
1259  'type' => 'jobqueue',
1260  'jobs' => $totalJobs,
1261  ];
1262  }
1263  }
1264 
1265  return $lagInfo;
1266  }
1267 
1274  protected function checkMaxLag( $module, $params ) {
1275  if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
1276  $maxLag = $params['maxlag'];
1277  $lagInfo = $this->getMaxLag();
1278  if ( $lagInfo['lag'] > $maxLag ) {
1279  $response = $this->getRequest()->response();
1280 
1281  $response->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
1282  $response->header( 'X-Database-Lag: ' . intval( $lagInfo['lag'] ) );
1283 
1284  if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
1285  $this->dieWithError(
1286  [ 'apierror-maxlag', $lagInfo['lag'], $lagInfo['host'] ],
1287  'maxlag',
1288  $lagInfo
1289  );
1290  }
1291 
1292  $this->dieWithError( [ 'apierror-maxlag-generic', $lagInfo['lag'] ], 'maxlag', $lagInfo );
1293  }
1294  }
1295 
1296  return true;
1297  }
1298 
1320  protected function checkConditionalRequestHeaders( $module ) {
1321  if ( $this->mInternalMode ) {
1322  // No headers to check in internal mode
1323  return true;
1324  }
1325 
1326  if ( $this->getRequest()->getMethod() !== 'GET' && $this->getRequest()->getMethod() !== 'HEAD' ) {
1327  // Don't check POSTs
1328  return true;
1329  }
1330 
1331  $return304 = false;
1332 
1333  $ifNoneMatch = array_diff(
1334  $this->getRequest()->getHeader( 'If-None-Match', WebRequest::GETHEADER_LIST ) ?: [],
1335  [ '' ]
1336  );
1337  if ( $ifNoneMatch ) {
1338  if ( $ifNoneMatch === [ '*' ] ) {
1339  // API responses always "exist"
1340  $etag = '*';
1341  } else {
1342  $etag = $module->getConditionalRequestData( 'etag' );
1343  }
1344  }
1345  if ( $ifNoneMatch && $etag !== null ) {
1346  $test = substr( $etag, 0, 2 ) === 'W/' ? substr( $etag, 2 ) : $etag;
1347  $match = array_map( function ( $s ) {
1348  return substr( $s, 0, 2 ) === 'W/' ? substr( $s, 2 ) : $s;
1349  }, $ifNoneMatch );
1350  $return304 = in_array( $test, $match, true );
1351  } else {
1352  $value = trim( $this->getRequest()->getHeader( 'If-Modified-Since' ) );
1353 
1354  // Some old browsers sends sizes after the date, like this:
1355  // Wed, 20 Aug 2003 06:51:19 GMT; length=5202
1356  // Ignore that.
1357  $i = strpos( $value, ';' );
1358  if ( $i !== false ) {
1359  $value = trim( substr( $value, 0, $i ) );
1360  }
1361 
1362  if ( $value !== '' ) {
1363  try {
1364  $ts = new MWTimestamp( $value );
1365  if (
1366  // RFC 7231 IMF-fixdate
1367  $ts->getTimestamp( TS_RFC2822 ) === $value ||
1368  // RFC 850
1369  $ts->format( 'l, d-M-y H:i:s' ) . ' GMT' === $value ||
1370  // asctime (with and without space-padded day)
1371  $ts->format( 'D M j H:i:s Y' ) === $value ||
1372  $ts->format( 'D M j H:i:s Y' ) === $value
1373  ) {
1374  $lastMod = $module->getConditionalRequestData( 'last-modified' );
1375  if ( $lastMod !== null ) {
1376  // Mix in some MediaWiki modification times
1377  $modifiedTimes = [
1378  'page' => $lastMod,
1379  'user' => $this->getUser()->getTouched(),
1380  'epoch' => $this->getConfig()->get( 'CacheEpoch' ),
1381  ];
1382  if ( $this->getConfig()->get( 'UseSquid' ) ) {
1383  // T46570: the core page itself may not change, but resources might
1384  $modifiedTimes['sepoch'] = wfTimestamp(
1385  TS_MW, time() - $this->getConfig()->get( 'SquidMaxage' )
1386  );
1387  }
1388  Hooks::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this->getOutput() ] );
1389  $lastMod = max( $modifiedTimes );
1390  $return304 = wfTimestamp( TS_MW, $lastMod ) <= $ts->getTimestamp( TS_MW );
1391  }
1392  }
1393  } catch ( TimestampException $e ) {
1394  // Invalid timestamp, ignore it
1395  }
1396  }
1397  }
1398 
1399  if ( $return304 ) {
1400  $this->getRequest()->response()->statusHeader( 304 );
1401 
1402  // Avoid outputting the compressed representation of a zero-length body
1403  MediaWiki\suppressWarnings();
1404  ini_set( 'zlib.output_compression', 0 );
1405  MediaWiki\restoreWarnings();
1407 
1408  return false;
1409  }
1410 
1411  return true;
1412  }
1413 
1418  protected function checkExecutePermissions( $module ) {
1419  $user = $this->getUser();
1420  if ( $module->isReadMode() && !User::isEveryoneAllowed( 'read' ) &&
1421  !$user->isAllowed( 'read' )
1422  ) {
1423  $this->dieWithError( 'apierror-readapidenied' );
1424  }
1425 
1426  if ( $module->isWriteMode() ) {
1427  if ( !$this->mEnableWrite ) {
1428  $this->dieWithError( 'apierror-noapiwrite' );
1429  } elseif ( !$user->isAllowed( 'writeapi' ) ) {
1430  $this->dieWithError( 'apierror-writeapidenied' );
1431  } elseif ( $this->getRequest()->getHeader( 'Promise-Non-Write-API-Action' ) ) {
1432  $this->dieWithError( 'apierror-promised-nonwrite-api' );
1433  }
1434 
1435  $this->checkReadOnly( $module );
1436  }
1437 
1438  // Allow extensions to stop execution for arbitrary reasons.
1439  $message = false;
1440  if ( !Hooks::run( 'ApiCheckCanExecute', [ $module, $user, &$message ] ) ) {
1441  $this->dieWithError( $message );
1442  }
1443  }
1444 
1449  protected function checkReadOnly( $module ) {
1450  if ( wfReadOnly() ) {
1451  $this->dieReadOnly();
1452  }
1453 
1454  if ( $module->isWriteMode()
1455  && $this->getUser()->isBot()
1456  && wfGetLB()->getServerCount() > 1
1457  ) {
1458  $this->checkBotReadOnly();
1459  }
1460  }
1461 
1465  private function checkBotReadOnly() {
1466  // Figure out how many servers have passed the lag threshold
1467  $numLagged = 0;
1468  $lagLimit = $this->getConfig()->get( 'APIMaxLagThreshold' );
1469  $laggedServers = [];
1470  $loadBalancer = wfGetLB();
1471  foreach ( $loadBalancer->getLagTimes() as $serverIndex => $lag ) {
1472  if ( $lag > $lagLimit ) {
1473  ++$numLagged;
1474  $laggedServers[] = $loadBalancer->getServerName( $serverIndex ) . " ({$lag}s)";
1475  }
1476  }
1477 
1478  // If a majority of replica DBs are too lagged then disallow writes
1479  $replicaCount = wfGetLB()->getServerCount() - 1;
1480  if ( $numLagged >= ceil( $replicaCount / 2 ) ) {
1481  $laggedServers = implode( ', ', $laggedServers );
1482  wfDebugLog(
1483  'api-readonly',
1484  "Api request failed as read only because the following DBs are lagged: $laggedServers"
1485  );
1486 
1487  $this->dieWithError(
1488  'readonly_lag',
1489  'readonly',
1490  [ 'readonlyreason' => "Waiting for $numLagged lagged database(s)" ]
1491  );
1492  }
1493  }
1494 
1499  protected function checkAsserts( $params ) {
1500  if ( isset( $params['assert'] ) ) {
1501  $user = $this->getUser();
1502  switch ( $params['assert'] ) {
1503  case 'user':
1504  if ( $user->isAnon() ) {
1505  $this->dieWithError( 'apierror-assertuserfailed' );
1506  }
1507  break;
1508  case 'bot':
1509  if ( !$user->isAllowed( 'bot' ) ) {
1510  $this->dieWithError( 'apierror-assertbotfailed' );
1511  }
1512  break;
1513  }
1514  }
1515  if ( isset( $params['assertuser'] ) ) {
1516  $assertUser = User::newFromName( $params['assertuser'], false );
1517  if ( !$assertUser || !$this->getUser()->equals( $assertUser ) ) {
1518  $this->dieWithError(
1519  [ 'apierror-assertnameduserfailed', wfEscapeWikiText( $params['assertuser'] ) ]
1520  );
1521  }
1522  }
1523  }
1524 
1530  protected function setupExternalResponse( $module, $params ) {
1531  $request = $this->getRequest();
1532  if ( !$request->wasPosted() && $module->mustBePosted() ) {
1533  // Module requires POST. GET request might still be allowed
1534  // if $wgDebugApi is true, otherwise fail.
1535  $this->dieWithErrorOrDebug( [ 'apierror-mustbeposted', $this->mAction ] );
1536  }
1537 
1538  // See if custom printer is used
1539  $this->mPrinter = $module->getCustomPrinter();
1540  if ( is_null( $this->mPrinter ) ) {
1541  // Create an appropriate printer
1542  $this->mPrinter = $this->createPrinterByName( $params['format'] );
1543  }
1544 
1545  if ( $request->getProtocol() === 'http' && (
1546  $request->getSession()->shouldForceHTTPS() ||
1547  ( $this->getUser()->isLoggedIn() &&
1548  $this->getUser()->requiresHTTPS() )
1549  ) ) {
1550  $this->addDeprecation( 'apiwarn-deprecation-httpsexpected', 'https-expected' );
1551  }
1552  }
1553 
1557  protected function executeAction() {
1558  $params = $this->setupExecuteAction();
1559  $module = $this->setupModule();
1560  $this->mModule = $module;
1561 
1562  if ( !$this->mInternalMode ) {
1563  $this->setRequestExpectations( $module );
1564  }
1565 
1566  $this->checkExecutePermissions( $module );
1567 
1568  if ( !$this->checkMaxLag( $module, $params ) ) {
1569  return;
1570  }
1571 
1572  if ( !$this->checkConditionalRequestHeaders( $module ) ) {
1573  return;
1574  }
1575 
1576  if ( !$this->mInternalMode ) {
1577  $this->setupExternalResponse( $module, $params );
1578  }
1579 
1580  $this->checkAsserts( $params );
1581 
1582  // Execute
1583  $module->execute();
1584  Hooks::run( 'APIAfterExecute', [ &$module ] );
1585 
1586  $this->reportUnusedParams();
1587 
1588  if ( !$this->mInternalMode ) {
1589  // append Debug information
1591 
1592  // Print result data
1593  $this->printResult();
1594  }
1595  }
1596 
1601  protected function setRequestExpectations( ApiBase $module ) {
1602  $limits = $this->getConfig()->get( 'TrxProfilerLimits' );
1603  $trxProfiler = Profiler::instance()->getTransactionProfiler();
1604  $trxProfiler->setLogger( LoggerFactory::getInstance( 'DBPerformance' ) );
1605  if ( $this->getRequest()->hasSafeMethod() ) {
1606  $trxProfiler->setExpectations( $limits['GET'], __METHOD__ );
1607  } elseif ( $this->getRequest()->wasPosted() && !$module->isWriteMode() ) {
1608  $trxProfiler->setExpectations( $limits['POST-nonwrite'], __METHOD__ );
1609  $this->getRequest()->markAsSafeRequest();
1610  } else {
1611  $trxProfiler->setExpectations( $limits['POST'], __METHOD__ );
1612  }
1613  }
1614 
1620  protected function logRequest( $time, $e = null ) {
1621  $request = $this->getRequest();
1622  $logCtx = [
1623  'ts' => time(),
1624  'ip' => $request->getIP(),
1625  'userAgent' => $this->getUserAgent(),
1626  'wiki' => wfWikiID(),
1627  'timeSpentBackend' => (int)round( $time * 1000 ),
1628  'hadError' => $e !== null,
1629  'errorCodes' => [],
1630  'params' => [],
1631  ];
1632 
1633  if ( $e ) {
1634  foreach ( $this->errorMessagesFromException( $e ) as $msg ) {
1635  $logCtx['errorCodes'][] = $msg->getApiCode();
1636  }
1637  }
1638 
1639  // Construct space separated message for 'api' log channel
1640  $msg = "API {$request->getMethod()} " .
1641  wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
1642  " {$logCtx['ip']} " .
1643  "T={$logCtx['timeSpentBackend']}ms";
1644 
1645  $sensitive = array_flip( $this->getSensitiveParams() );
1646  foreach ( $this->getParamsUsed() as $name ) {
1647  $value = $request->getVal( $name );
1648  if ( $value === null ) {
1649  continue;
1650  }
1651 
1652  if ( isset( $sensitive[$name] ) ) {
1653  $value = '[redacted]';
1654  $encValue = '[redacted]';
1655  } elseif ( strlen( $value ) > 256 ) {
1656  $value = substr( $value, 0, 256 );
1657  $encValue = $this->encodeRequestLogValue( $value ) . '[...]';
1658  } else {
1659  $encValue = $this->encodeRequestLogValue( $value );
1660  }
1661 
1662  $logCtx['params'][$name] = $value;
1663  $msg .= " {$name}={$encValue}";
1664  }
1665 
1666  wfDebugLog( 'api', $msg, 'private' );
1667  // ApiAction channel is for structured data consumers
1668  wfDebugLog( 'ApiAction', '', 'private', $logCtx );
1669  }
1670 
1676  protected function encodeRequestLogValue( $s ) {
1677  static $table;
1678  if ( !$table ) {
1679  $chars = ';@$!*(),/:';
1680  $numChars = strlen( $chars );
1681  for ( $i = 0; $i < $numChars; $i++ ) {
1682  $table[rawurlencode( $chars[$i] )] = $chars[$i];
1683  }
1684  }
1685 
1686  return strtr( rawurlencode( $s ), $table );
1687  }
1688 
1693  protected function getParamsUsed() {
1694  return array_keys( $this->mParamsUsed );
1695  }
1696 
1701  public function markParamsUsed( $params ) {
1702  $this->mParamsUsed += array_fill_keys( (array)$params, true );
1703  }
1704 
1710  protected function getSensitiveParams() {
1711  return array_keys( $this->mParamsSensitive );
1712  }
1713 
1719  public function markParamsSensitive( $params ) {
1720  $this->mParamsSensitive += array_fill_keys( (array)$params, true );
1721  }
1722 
1729  public function getVal( $name, $default = null ) {
1730  $this->mParamsUsed[$name] = true;
1731 
1732  $ret = $this->getRequest()->getVal( $name );
1733  if ( $ret === null ) {
1734  if ( $this->getRequest()->getArray( $name ) !== null ) {
1735  // See T12262 for why we don't just implode( '|', ... ) the
1736  // array.
1737  $this->addWarning( [ 'apiwarn-unsupportedarray', $name ] );
1738  }
1739  $ret = $default;
1740  }
1741  return $ret;
1742  }
1743 
1750  public function getCheck( $name ) {
1751  return $this->getVal( $name, null ) !== null;
1752  }
1753 
1761  public function getUpload( $name ) {
1762  $this->mParamsUsed[$name] = true;
1763 
1764  return $this->getRequest()->getUpload( $name );
1765  }
1766 
1771  protected function reportUnusedParams() {
1772  $paramsUsed = $this->getParamsUsed();
1773  $allParams = $this->getRequest()->getValueNames();
1774 
1775  if ( !$this->mInternalMode ) {
1776  // Printer has not yet executed; don't warn that its parameters are unused
1777  $printerParams = $this->mPrinter->encodeParamName(
1778  array_keys( $this->mPrinter->getFinalParams() ?: [] )
1779  );
1780  $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1781  } else {
1782  $unusedParams = array_diff( $allParams, $paramsUsed );
1783  }
1784 
1785  if ( count( $unusedParams ) ) {
1786  $this->addWarning( [
1787  'apierror-unrecognizedparams',
1788  Message::listParam( array_map( 'wfEscapeWikiText', $unusedParams ), 'comma' ),
1789  count( $unusedParams )
1790  ] );
1791  }
1792  }
1793 
1799  protected function printResult( $httpCode = 0 ) {
1800  if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
1801  $this->addWarning( 'apiwarn-wgDebugAPI' );
1802  }
1803 
1804  $printer = $this->mPrinter;
1805  $printer->initPrinter( false );
1806  if ( $httpCode ) {
1807  $printer->setHttpStatus( $httpCode );
1808  }
1809  $printer->execute();
1810  $printer->closePrinter();
1811  }
1812 
1816  public function isReadMode() {
1817  return false;
1818  }
1819 
1825  public function getAllowedParams() {
1826  return [
1827  'action' => [
1828  ApiBase::PARAM_DFLT => 'help',
1829  ApiBase::PARAM_TYPE => 'submodule',
1830  ],
1831  'format' => [
1833  ApiBase::PARAM_TYPE => 'submodule',
1834  ],
1835  'maxlag' => [
1836  ApiBase::PARAM_TYPE => 'integer'
1837  ],
1838  'smaxage' => [
1839  ApiBase::PARAM_TYPE => 'integer',
1840  ApiBase::PARAM_DFLT => 0
1841  ],
1842  'maxage' => [
1843  ApiBase::PARAM_TYPE => 'integer',
1844  ApiBase::PARAM_DFLT => 0
1845  ],
1846  'assert' => [
1847  ApiBase::PARAM_TYPE => [ 'user', 'bot' ]
1848  ],
1849  'assertuser' => [
1850  ApiBase::PARAM_TYPE => 'user',
1851  ],
1852  'requestid' => null,
1853  'servedby' => false,
1854  'curtimestamp' => false,
1855  'responselanginfo' => false,
1856  'origin' => null,
1857  'uselang' => [
1859  ],
1860  'errorformat' => [
1861  ApiBase::PARAM_TYPE => [ 'plaintext', 'wikitext', 'html', 'raw', 'none', 'bc' ],
1862  ApiBase::PARAM_DFLT => 'bc',
1863  ],
1864  'errorlang' => [
1865  ApiBase::PARAM_DFLT => 'uselang',
1866  ],
1867  'errorsuselocal' => [
1868  ApiBase::PARAM_DFLT => false,
1869  ],
1870  ];
1871  }
1872 
1874  protected function getExamplesMessages() {
1875  return [
1876  'action=help'
1877  => 'apihelp-help-example-main',
1878  'action=help&recursivesubmodules=1'
1879  => 'apihelp-help-example-recursive',
1880  ];
1881  }
1882 
1883  public function modifyHelp( array &$help, array $options, array &$tocData ) {
1884  // Wish PHP had an "array_insert_before". Instead, we have to manually
1885  // reindex the array to get 'permissions' in the right place.
1886  $oldHelp = $help;
1887  $help = [];
1888  foreach ( $oldHelp as $k => $v ) {
1889  if ( $k === 'submodules' ) {
1890  $help['permissions'] = '';
1891  }
1892  $help[$k] = $v;
1893  }
1894  $help['datatypes'] = '';
1895  $help['credits'] = '';
1896 
1897  // Fill 'permissions'
1898  $help['permissions'] .= Html::openElement( 'div',
1899  [ 'class' => 'apihelp-block apihelp-permissions' ] );
1900  $m = $this->msg( 'api-help-permissions' );
1901  if ( !$m->isDisabled() ) {
1902  $help['permissions'] .= Html::rawElement( 'div', [ 'class' => 'apihelp-block-head' ],
1903  $m->numParams( count( self::$mRights ) )->parse()
1904  );
1905  }
1906  $help['permissions'] .= Html::openElement( 'dl' );
1907  foreach ( self::$mRights as $right => $rightMsg ) {
1908  $help['permissions'] .= Html::element( 'dt', null, $right );
1909 
1910  $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse();
1911  $help['permissions'] .= Html::rawElement( 'dd', null, $rightMsg );
1912 
1913  $groups = array_map( function ( $group ) {
1914  return $group == '*' ? 'all' : $group;
1915  }, User::getGroupsWithPermission( $right ) );
1916 
1917  $help['permissions'] .= Html::rawElement( 'dd', null,
1918  $this->msg( 'api-help-permissions-granted-to' )
1919  ->numParams( count( $groups ) )
1920  ->params( Message::listParam( $groups ) )
1921  ->parse()
1922  );
1923  }
1924  $help['permissions'] .= Html::closeElement( 'dl' );
1925  $help['permissions'] .= Html::closeElement( 'div' );
1926 
1927  // Fill 'datatypes' and 'credits', if applicable
1928  if ( empty( $options['nolead'] ) ) {
1929  $level = $options['headerlevel'];
1930  $tocnumber = &$options['tocnumber'];
1931 
1932  $header = $this->msg( 'api-help-datatypes-header' )->parse();
1933 
1934  $id = Sanitizer::escapeIdForAttribute( 'main/datatypes', Sanitizer::ID_PRIMARY );
1935  $idFallback = Sanitizer::escapeIdForAttribute( 'main/datatypes', Sanitizer::ID_FALLBACK );
1936  $headline = Linker::makeHeadline( min( 6, $level ),
1937  ' class="apihelp-header"',
1938  $id,
1939  $header,
1940  '',
1941  $idFallback
1942  );
1943  // Ensure we have a sane anchor
1944  if ( $id !== 'main/datatypes' && $idFallback !== 'main/datatypes' ) {
1945  $headline = '<div id="main/datatypes"></div>' . $headline;
1946  }
1947  $help['datatypes'] .= $headline;
1948  $help['datatypes'] .= $this->msg( 'api-help-datatypes' )->parseAsBlock();
1949  if ( !isset( $tocData['main/datatypes'] ) ) {
1950  $tocnumber[$level]++;
1951  $tocData['main/datatypes'] = [
1952  'toclevel' => count( $tocnumber ),
1953  'level' => $level,
1954  'anchor' => 'main/datatypes',
1955  'line' => $header,
1956  'number' => implode( '.', $tocnumber ),
1957  'index' => false,
1958  ];
1959  }
1960 
1961  $header = $this->msg( 'api-credits-header' )->parse();
1962  $id = Sanitizer::escapeIdForAttribute( 'main/credits', Sanitizer::ID_PRIMARY );
1963  $idFallback = Sanitizer::escapeIdForAttribute( 'main/credits', Sanitizer::ID_FALLBACK );
1964  $headline = Linker::makeHeadline( min( 6, $level ),
1965  ' class="apihelp-header"',
1966  $id,
1967  $header,
1968  '',
1969  $idFallback
1970  );
1971  // Ensure we have a sane anchor
1972  if ( $id !== 'main/credits' && $idFallback !== 'main/credits' ) {
1973  $headline = '<div id="main/credits"></div>' . $headline;
1974  }
1975  $help['credits'] .= $headline;
1976  $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
1977  if ( !isset( $tocData['main/credits'] ) ) {
1978  $tocnumber[$level]++;
1979  $tocData['main/credits'] = [
1980  'toclevel' => count( $tocnumber ),
1981  'level' => $level,
1982  'anchor' => 'main/credits',
1983  'line' => $header,
1984  'number' => implode( '.', $tocnumber ),
1985  'index' => false,
1986  ];
1987  }
1988  }
1989  }
1990 
1991  private $mCanApiHighLimits = null;
1992 
1997  public function canApiHighLimits() {
1998  if ( !isset( $this->mCanApiHighLimits ) ) {
1999  $this->mCanApiHighLimits = $this->getUser()->isAllowed( 'apihighlimits' );
2000  }
2001 
2002  return $this->mCanApiHighLimits;
2003  }
2004 
2009  public function getModuleManager() {
2010  return $this->mModuleMgr;
2011  }
2012 
2021  public function getUserAgent() {
2022  return trim(
2023  $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
2024  $this->getRequest()->getHeader( 'User-agent' )
2025  );
2026  }
2027 }
2028 
ApiUsageException\getStatusValue
getStatusValue()
Fetch the error status.
Definition: ApiUsageException.php:182
ApiMain\executeActionWithErrorHandling
executeActionWithErrorHandling()
Execute an action, and in case of an error, erase whatever partial results have been accumulated,...
Definition: ApiMain.php:525
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:45
ContextSource\$context
IContextSource $context
Definition: ContextSource.php:34
ContextSource\getConfig
getConfig()
Get the Config object.
Definition: ContextSource.php:68
$user
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a account $user
Definition: hooks.txt:244
$wgUser
$wgUser
Definition: Setup.php:809
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:104
ContextSource\getContext
getContext()
Get the base IContextSource object.
Definition: ContextSource.php:41
ApiMain\checkReadOnly
checkReadOnly( $module)
Check if the DB is read-only for this user.
Definition: ApiMain.php:1449
ApiBase\addWarning
addWarning( $msg, $code=null, $data=null)
Add a warning for this module.
Definition: ApiBase.php:1779
RequestContext\sanitizeLangCode
static sanitizeLangCode( $code)
Accepts a language code and ensures it's sane.
Definition: RequestContext.php:304
ApiMain\$mParamsSensitive
$mParamsSensitive
Definition: ApiMain.php:164
false
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:187
ApiMain\$mAction
$mAction
Definition: ApiMain.php:155
ApiErrorFormatter_BackCompat
Format errors and warnings in the old style, for backwards compatibility.
Definition: ApiErrorFormatter.php:362
ApiMain\$mSquidMaxage
$mSquidMaxage
Definition: ApiMain.php:157
ApiMain\getParamsUsed
getParamsUsed()
Get the request parameters used in the course of the preceding execute() request.
Definition: ApiMain.php:1693
Profiler\instance
static instance()
Singleton.
Definition: Profiler.php:62
ApiMain\createErrorPrinter
createErrorPrinter()
Create the printer for error output.
Definition: ApiMain.php:1000
ApiMain\getErrorFormatter
getErrorFormatter()
Get the ApiErrorFormatter object associated with current request.
Definition: ApiMain.php:359
ApiMain\getVal
getVal( $name, $default=null)
Get a request value, and register the fact that it was used, for logging.
Definition: ApiMain.php:1729
captcha-old.count
count
Definition: captcha-old.py:249
wfGetLB
wfGetLB( $wiki=false)
Get a load balancer object.
Definition: GlobalFunctions.php:2869
text
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add text
Definition: design.txt:12
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:1855
ContextSource\msg
msg( $key)
Get a Message object with context set Parameters are the same as wfMessage()
Definition: ContextSource.php:189
ApiMain\sendCacheHeaders
sendCacheHeaders( $isError)
Send caching headers.
Definition: ApiMain.php:882
$result
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 '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. 'LanguageGetMagic':DEPRECATED! Use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language & $magicExtensions:associative array of magic words synonyms $lang:language code(string) '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 'LanguageGetSpecialPageAliases':DEPRECATED! Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language & $specialPageAliases:associative array of magic words synonyms $lang:language code(string) '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! 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:1963
ApiMain\$Modules
static $Modules
List of available modules: action name => module class.
Definition: ApiMain.php:59
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:2040
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:91
ApiFormatBase
This is the abstract base class for API formatters.
Definition: ApiFormatBase.php:32
ApiMain\logRequest
logRequest( $time, $e=null)
Log the preceding request.
Definition: ApiMain.php:1620
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
wfUrlencode
wfUrlencode( $s)
We want some things to be included as literal characters in our title URLs for prettiness,...
Definition: GlobalFunctions.php:405
ApiMain\isReadMode
isReadMode()
Definition: ApiMain.php:1816
ApiMain\handleCORS
handleCORS()
Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
Definition: ApiMain.php:686
ApiMain\handleApiBeforeMainException
static handleApiBeforeMainException(Exception $e)
Handle an exception from the ApiBeforeMain hook.
Definition: ApiMain.php:654
ApiMain\checkConditionalRequestHeaders
checkConditionalRequestHeaders( $module)
Check selected RFC 7232 precondition headers.
Definition: ApiMain.php:1320
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:2009
$params
$params
Definition: styleTest.css.php:40
ApiMain\lacksSameOriginSecurity
lacksSameOriginSecurity()
Get the security flag for the current request.
Definition: ApiMain.php:324
wfHostname
wfHostname()
Fetch server name for use in error reporting etc.
Definition: GlobalFunctions.php:1482
wfReadOnly
wfReadOnly()
Check whether the wiki is in read-only mode.
Definition: GlobalFunctions.php:1324
User\newFromName
static newFromName( $name, $validate='valid')
Static factory method for creation from username.
Definition: User.php:550
$s
$s
Definition: mergeMessageFileList.php:188
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:56
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:302
ContextSource\getRequest
getRequest()
Get the WebRequest object.
Definition: ContextSource.php:78
User
User
Definition: All_system_messages.txt:425
ApiMain\encodeRequestLogValue
encodeRequestLogValue( $s)
Encode a value in a format suitable for a space-separated log line.
Definition: ApiMain.php:1676
ContextSource\getUser
getUser()
Get the User object.
Definition: ContextSource.php:133
ApiMain\getMaxLag
getMaxLag()
Definition: ApiMain.php:1242
$messages
$messages
Definition: LogTests.i18n.php:8
Wikimedia\Rdbms\DBError
Database error base class.
Definition: DBError.php:30
ApiMain\$mContinuationManager
ApiContinuationManager null $mContinuationManager
Definition: ApiMain.php:154
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:806
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:1140
ApiMain\$mRights
static $mRights
List of user roles that are specifically relevant to the API.
Definition: ApiMain.php:135
php
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
ApiBase
This abstract class implements many basic API functions, and is the base of all API classes.
Definition: ApiBase.php:41
ApiRawMessage
Extension of RawMessage implementing IApiMessage.
Definition: ApiMessage.php:268
ContextSource\getLanguage
getLanguage()
Get the Language object.
Definition: ContextSource.php:143
Html\closeElement
static closeElement( $element)
Returns "</$element>".
Definition: Html.php:309
ApiMain\getModule
getModule()
Get the API module object.
Definition: ApiMain.php:397
DerivativeContext
An IContextSource implementation which will inherit context from another source but allow individual ...
Definition: DerivativeContext.php:31
ApiMain\markParamsUsed
markParamsUsed( $params)
Mark parameters as used.
Definition: ApiMain.php:1701
MWException
MediaWiki exception.
Definition: MWException.php:26
ApiMain\setupExecuteAction
setupExecuteAction()
Set up for the execution.
Definition: ApiMain.php:1186
wfScript
wfScript( $script='index')
Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScri...
Definition: GlobalFunctions.php:2934
ApiResult
This class represents the result of the API operations.
Definition: ApiResult.php:33
ApiMain\setContinuationManager
setContinuationManager( $manager)
Set the continuation manager.
Definition: ApiMain.php:375
ApiMain\$mResult
$mResult
Definition: ApiMain.php:152
UsageException
This exception will be thrown when dieUsage is called to stop module execution.
Definition: ApiUsageException.php:28
ApiMain\$lacksSameOriginSecurity
bool null $lacksSameOriginSecurity
Cached return value from self::lacksSameOriginSecurity()
Definition: ApiMain.php:167
ContextSource\getOutput
getOutput()
Get the OutputPage object.
Definition: ContextSource.php:123
MWExceptionHandler\rollbackMasterChangesAndLog
static rollbackMasterChangesAndLog( $e)
Roll back any open database transactions and log the stack trace of the exception.
Definition: MWExceptionHandler.php:93
Linker\makeHeadline
static makeHeadline( $level, $attribs, $anchor, $html, $link, $fallbackAnchor=false)
Create a headline for content.
Definition: Linker.php:1627
ApiMain\getResult
getResult()
Get the ApiResult object associated with current request.
Definition: ApiMain.php:316
ApiMain\getSensitiveParams
getSensitiveParams()
Get the request parameters that should be considered sensitive.
Definition: ApiMain.php:1710
MediaWiki
A helper class for throttling authentication attempts.
ApiMain\checkMaxLag
checkMaxLag( $module, $params)
Check the max lag if necessary.
Definition: ApiMain.php:1274
ApiMain\API_DEFAULT_USELANG
const API_DEFAULT_USELANG
When no uselang parameter is given, this language will be used.
Definition: ApiMain.php:54
ApiMain\getExamplesMessages
getExamplesMessages()
@inheritDoc
Definition: ApiMain.php:1874
ApiMain\setCacheControl
setCacheControl( $directives)
Set directives (key/value pairs) for the Cache-Control header.
Definition: ApiMain.php:488
$wgLang
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as $wgLang
Definition: design.txt:56
ApiMain\getAllowedParams
getAllowedParams()
See ApiBase for description.
Definition: ApiMain.php:1825
ApiMain\setupExternalResponse
setupExternalResponse( $module, $params)
Check POST for external response and setup result printer.
Definition: ApiMain.php:1530
$time
see documentation in includes Linker php for Linker::makeImageLink & $time
Definition: hooks.txt:1778
ApiMain\createPrinterByName
createPrinterByName( $format)
Create an instance of an output formatter by its name.
Definition: ApiMain.php:499
ApiMain\getModuleManager
getModuleManager()
Overrides to return this instance's module manager.
Definition: ApiMain.php:2009
global
when a variable name is used in a it is silently declared as a new masking the global
Definition: design.txt:93
ApiMain\$mCanApiHighLimits
$mCanApiHighLimits
Definition: ApiMain.php:1991
ApiMessage\create
static create( $msg, $code=null, array $data=null)
Create an IApiMessage for the message.
Definition: ApiMessage.php:212
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:830
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:1047
ApiMain\addRequestedFields
addRequestedFields( $force=[])
Add requested fields to the result.
Definition: ApiMain.php:1155
ContextSource\setContext
setContext(IContextSource $context)
Set the IContextSource object.
Definition: ContextSource.php:58
ILocalizedException
Interface for MediaWiki-localized exceptions.
Definition: LocalizedException.php:27
ApiMain\canApiHighLimits
canApiHighLimits()
Check whether the current user is allowed to use high limits.
Definition: ApiMain.php:1997
ApiMain\$mPrinter
ApiFormatBase $mPrinter
Definition: ApiMain.php:150
Wikimedia\Rdbms\DBQueryError
Definition: DBQueryError.php:27
ApiMain\checkBotReadOnly
checkBotReadOnly()
Check whether we are readonly for bots.
Definition: ApiMain.php:1465
ApiMain\getContinuationManager
getContinuationManager()
Get the continuation manager.
Definition: ApiMain.php:367
$request
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:2581
ApiModuleManager
This class holds a list of modules and handles instantiation.
Definition: ApiModuleManager.php:34
ApiMain\checkAsserts
checkAsserts( $params)
Check asserts of the user's rights.
Definition: ApiMain.php:1499
wfWikiID
wfWikiID()
Get an ASCII string identifying this wiki This is used as a prefix in memcached keys.
Definition: GlobalFunctions.php:2807
ApiBase\extractRequestParams
extractRequestParams( $parseLimit=true)
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition: ApiBase.php:740
ApiMain\$mCacheMode
$mCacheMode
Definition: ApiMain.php:161
$e
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2141
MWDebug\appendDebugInfoToApiResult
static appendDebugInfoToApiResult(IContextSource $context, ApiResult $result)
Append the debug info to given ApiResult.
Definition: MWDebug.php:481
wfClearOutputBuffers
wfClearOutputBuffers()
More legible than passing a 'false' parameter to wfResetOutputBuffers():
Definition: GlobalFunctions.php:1902
ApiMain\$mErrorFormatter
$mErrorFormatter
Definition: ApiMain.php:152
ApiMain\$mInternalMode
$mInternalMode
Definition: ApiMain.php:157
$value
$value
Definition: styleTest.css.php:45
MediaWiki\preOutputCommit
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:582
ApiMain\wildcardToRegex
static wildcardToRegex( $wildcard)
Helper function to convert wildcard string into a regex '*' => '.
Definition: ApiMain.php:866
ApiMain\checkExecutePermissions
checkExecutePermissions( $module)
Check for sufficient permissions to execute.
Definition: ApiMain.php:1418
ApiBase\addDeprecation
addDeprecation( $msg, $feature, $data=[])
Add a deprecation warning for this module.
Definition: ApiBase.php:1793
$header
$header
Definition: updateCredits.php:35
ApiBase\LIMIT_SML2
const LIMIT_SML2
Slow query, apihighlimits limit.
Definition: ApiBase.php:231
ApiBase\dieReadOnly
dieReadOnly()
Helper function for readonly errors.
Definition: ApiBase.php:1950
ApiMain\__construct
__construct( $context=null, $enableWrite=false)
Constructs an instance of ApiMain that utilizes the module and format specified by $request.
Definition: ApiMain.php:176
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:1771
ApiMain\execute
execute()
Execute api request.
Definition: ApiMain.php:513
ApiBase\isWriteMode
isWriteMode()
Indicates whether this module requires write mode.
Definition: ApiBase.php:419
wfEscapeWikiText
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
Definition: GlobalFunctions.php:1703
$ret
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:1965
ApiMain\$Formats
static $Formats
List of available formats: format name => format class.
Definition: ApiMain.php:117
ApiMain\markParamsSensitive
markParamsSensitive( $params)
Mark parameters as sensitive.
Definition: ApiMain.php:1719
ApiMain\setRequestExpectations
setRequestExpectations(ApiBase $module)
Set database connection, query, and write expectations given this module request.
Definition: ApiMain.php:1601
ApiMain\substituteResultWithError
substituteResultWithError( $e)
Replace the result data with the information about an exception.
Definition: ApiMain.php:1075
RequestContext\getMain
static getMain()
Static methods.
Definition: RequestContext.php:470
ApiMain\getCheck
getCheck( $name)
Get a boolean request value, and register the fact that the parameter was used, for logging.
Definition: ApiMain.php:1750
ApiMain\printResult
printResult( $httpCode=0)
Print results using the current printer.
Definition: ApiMain.php:1799
$response
this hook is for auditing only $response
Definition: hooks.txt:781
WebRequest
The WebRequest class encapsulates getting at data passed in the URL or via a POSTed form stripping il...
Definition: WebRequest.php:38
ApiErrorFormatter
Formats errors and warnings for the API, and add them to the associated ApiResult.
Definition: ApiErrorFormatter.php:30
ApiMain\$mEnableWrite
$mEnableWrite
Definition: ApiMain.php:156
User\isEveryoneAllowed
static isEveryoneAllowed( $right)
Check if all users may be assumed to have the given permission.
Definition: User.php:4811
ApiBase\LIMIT_BIG2
const LIMIT_BIG2
Fast query, apihighlimits limit.
Definition: ApiBase.php:227
ApiMain\API_DEFAULT_FORMAT
const API_DEFAULT_FORMAT
When no format parameter is given, this format will be used.
Definition: ApiMain.php:49
WebRequest\GETHEADER_LIST
const GETHEADER_LIST
Flag to make WebRequest::getHeader return an array of values.
Definition: WebRequest.php:45
$options
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:1965
ApiMain\getUpload
getUpload( $name)
Get a request upload, and register the fact that it was used, for logging.
Definition: ApiMain.php:1761
$code
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:781
ApiMain\modifyHelp
modifyHelp(array &$help, array $options, array &$tocData)
Called from ApiHelp before the pieces are joined together and returned.
Definition: ApiMain.php:1883
WebRequest\getRequestId
static getRequestId()
Get the unique request ID.
Definition: WebRequest.php:272
JobQueueGroup\singleton
static singleton( $wiki=false)
Definition: JobQueueGroup.php:72
$path
$path
Definition: NoLocalSettings.php:26
ApiBase\PARAM_DFLT
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
Definition: ApiBase.php:52
ApiBase\getParameter
getParameter( $paramName, $parseLimit=true)
Get a value for the given parameter.
Definition: ApiBase.php:764
as
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
Html\openElement
static openElement( $element, $attribs=[])
Identical to rawElement(), but has no third parameter and omits the end tag (and the self-closing '/'...
Definition: Html.php:251
Html\rawElement
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
Definition: Html.php:209
ApiMain\executeAction
executeAction()
Execute the actual module, without any error handling.
Definition: ApiMain.php:1557
$link
usually copyright or history_copyright This message must be in HTML not wikitext & $link
Definition: hooks.txt:2981
LoggerFactory
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
ApiMain\setupModule
setupModule()
Set up the module for response.
Definition: ApiMain.php:1201
true
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:1965
$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:183
ApiMain\$mCacheControl
$mCacheControl
Definition: ApiMain.php:162
$t
$t
Definition: testCompression.php:67
ApiMain\handleException
handleException(Exception $e)
Handle an exception as an API response.
Definition: ApiMain.php:580
Html\element
static element( $element, $attribs=[], $contents='')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
Definition: Html.php:231
ApiMain\isInternalMode
isInternalMode()
Return true if the API was started by other PHP code using FauxRequest.
Definition: ApiMain.php:307
ApiMain\$mParamsUsed
$mParamsUsed
Definition: ApiMain.php:163
MediaWikiServices
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
ApiMain\$mModuleMgr
$mModuleMgr
Definition: ApiMain.php:152
ApiMain\getUserAgent
getUserAgent()
Fetches the user agent used for this request.
Definition: ApiMain.php:2021
ApiMain\setCacheMaxAge
setCacheMaxAge( $maxage)
Set how long the response should be cached.
Definition: ApiMain.php:415
Hooks\run
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:203
ApiMain\errorMessagesFromException
errorMessagesFromException( $e, $type='error')
Create an error message for the given exception.
Definition: ApiMain.php:1034
ApiFormatBase\initPrinter
initPrinter( $unused=false)
Initialize the printer function and prepare the output headers.
Definition: ApiFormatBase.php:193
MWExceptionHandler\getRedactedTraceAsString
static getRedactedTraceAsString( $e)
Generate a string representation of an exception's stack trace.
Definition: MWExceptionHandler.php:311
ApiMain\setCacheMode
setCacheMode( $mode)
Set the type of caching headers which will be sent.
Definition: ApiMain.php:447
ApiMain\getPrinter
getPrinter()
Get the result formatter object.
Definition: ApiMain.php:406
wfExpandUrl
wfExpandUrl( $url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.
Definition: GlobalFunctions.php:586
array
the array() calling protocol came about after MediaWiki 1.4rc1.
User\getGroupsWithPermission
static getGroupsWithPermission( $role)
Get all the groups who have a given permission.
Definition: User.php:4768
$wgContLang
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as and the content language as $wgContLang
Definition: design.txt:56
$out
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:781
$type
$type
Definition: testCompression.php:48
ApiMain\$mModule
ApiBase $mModule
Definition: ApiMain.php:159