MediaWiki  master
ApiMain.php
Go to the documentation of this file.
1 <?php
31 use Wikimedia\Timestamp\TimestampException;
32 
49 class ApiMain extends ApiBase {
53  private const API_DEFAULT_FORMAT = 'jsonfm';
54 
58  private const API_DEFAULT_USELANG = 'user';
59 
63  private const MODULES = [
64  'login' => [
65  'class' => ApiLogin::class,
66  'services' => [
67  'AuthManager',
68  ],
69  ],
70  'clientlogin' => [
71  'class' => ApiClientLogin::class,
72  'services' => [
73  'AuthManager',
74  ],
75  ],
76  'logout' => [
77  'class' => ApiLogout::class,
78  ],
79  'createaccount' => [
80  'class' => ApiAMCreateAccount::class,
81  'services' => [
82  'AuthManager',
83  ],
84  ],
85  'linkaccount' => [
86  'class' => ApiLinkAccount::class,
87  'services' => [
88  'AuthManager',
89  ],
90  ],
91  'unlinkaccount' => [
92  'class' => ApiRemoveAuthenticationData::class,
93  'services' => [
94  'AuthManager',
95  ],
96  ],
97  'changeauthenticationdata' => [
98  'class' => ApiChangeAuthenticationData::class,
99  'services' => [
100  'AuthManager',
101  ],
102  ],
103  'removeauthenticationdata' => [
104  'class' => ApiRemoveAuthenticationData::class,
105  'services' => [
106  'AuthManager',
107  ],
108  ],
109  'resetpassword' => [
110  'class' => ApiResetPassword::class,
111  'services' => [
112  'PasswordReset',
113  ]
114  ],
115  'query' => [
116  'class' => ApiQuery::class,
117  'services' => [
118  'ObjectFactory',
119  'DBLoadBalancer',
120  'WikiExporterFactory',
121  ]
122  ],
123  'expandtemplates' => [
124  'class' => ApiExpandTemplates::class,
125  'services' => [
126  'RevisionStore',
127  'Parser',
128  ]
129  ],
130  'parse' => [
131  'class' => ApiParse::class,
132  'services' => [
133  'RevisionLookup',
134  'SkinFactory',
135  'LanguageNameUtils',
136  'LinkBatchFactory',
137  'LinkCache',
138  'ContentHandlerFactory',
139  'Parser',
140  'WikiPageFactory',
141  'ContentRenderer',
142  'ContentTransformer',
143  'CommentFormatter',
144  ]
145  ],
146  'stashedit' => [
147  'class' => ApiStashEdit::class,
148  'services' => [
149  'ContentHandlerFactory',
150  'PageEditStash',
151  'RevisionLookup',
152  'StatsdDataFactory',
153  'WikiPageFactory',
154  ]
155  ],
156  'opensearch' => [
157  'class' => ApiOpenSearch::class,
158  'services' => [
159  'LinkBatchFactory',
160  'SearchEngineConfig',
161  'SearchEngineFactory',
162  ]
163  ],
164  'feedcontributions' => [
165  'class' => ApiFeedContributions::class,
166  'services' => [
167  'RevisionStore',
168  'TitleParser',
169  'LinkRenderer',
170  'LinkBatchFactory',
171  'HookContainer',
172  'DBLoadBalancer',
173  'NamespaceInfo',
174  'ActorMigration',
175  'UserFactory',
176  'CommentFormatter',
177  ]
178  ],
179  'feedrecentchanges' => [
180  'class' => ApiFeedRecentChanges::class,
181  'services' => [
182  'SpecialPageFactory',
183  ]
184  ],
185  'feedwatchlist' => [
186  'class' => ApiFeedWatchlist::class,
187  'services' => [
188  'Parser',
189  ]
190  ],
191  'help' => [
192  'class' => ApiHelp::class,
193  'services' => [
194  'SkinFactory',
195  ]
196  ],
197  'paraminfo' => [
198  'class' => ApiParamInfo::class,
199  'services' => [
200  'UserFactory',
201  ],
202  ],
203  'rsd' => [
204  'class' => ApiRsd::class,
205  ],
206  'compare' => [
207  'class' => ApiComparePages::class,
208  'services' => [
209  'RevisionStore',
210  'SlotRoleRegistry',
211  'ContentHandlerFactory',
212  'ContentTransformer',
213  'CommentFormatter',
214  ]
215  ],
216  'checktoken' => [
217  'class' => ApiCheckToken::class,
218  ],
219  'cspreport' => [
220  'class' => ApiCSPReport::class,
221  ],
222  'validatepassword' => [
223  'class' => ApiValidatePassword::class,
224  'services' => [
225  'AuthManager',
226  'UserFactory',
227  ]
228  ],
229 
230  // Write modules
231  'purge' => [
232  'class' => ApiPurge::class,
233  'services' => [
234  'WikiPageFactory',
235  ],
236  ],
237  'setnotificationtimestamp' => [
238  'class' => ApiSetNotificationTimestamp::class,
239  'services' => [
240  'DBLoadBalancer',
241  'RevisionStore',
242  'WatchedItemStore',
243  ]
244  ],
245  'rollback' => [
246  'class' => ApiRollback::class,
247  'services' => [
248  'RollbackPageFactory',
249  'WatchlistManager',
250  'UserOptionsLookup',
251  ]
252  ],
253  'delete' => [
254  'class' => ApiDelete::class,
255  'services' => [
256  'RepoGroup',
257  'WatchlistManager',
258  'UserOptionsLookup',
259  'DeletePageFactory',
260  ]
261  ],
262  'undelete' => [
263  'class' => ApiUndelete::class,
264  'services' => [
265  'WatchlistManager',
266  'UserOptionsLookup',
267  'UndeletePageFactory',
268  'WikiPageFactory',
269  ]
270  ],
271  'protect' => [
272  'class' => ApiProtect::class,
273  'services' => [
274  'WatchlistManager',
275  'UserOptionsLookup',
276  ]
277  ],
278  'block' => [
279  'class' => ApiBlock::class,
280  'services' => [
281  'BlockPermissionCheckerFactory',
282  'BlockUserFactory',
283  'TitleFactory',
284  'UserIdentityLookup',
285  'WatchedItemStore',
286  'BlockUtils',
287  'BlockActionInfo',
288  'WatchlistManager',
289  'UserOptionsLookup',
290  ]
291  ],
292  'unblock' => [
293  'class' => ApiUnblock::class,
294  'services' => [
295  'BlockPermissionCheckerFactory',
296  'UnblockUserFactory',
297  'UserIdentityLookup',
298  ]
299  ],
300  'move' => [
301  'class' => ApiMove::class,
302  'services' => [
303  'MovePageFactory',
304  'RepoGroup',
305  'WatchlistManager',
306  'UserOptionsLookup',
307  ]
308  ],
309  'edit' => [
310  'class' => ApiEditPage::class,
311  'services' => [
312  'ContentHandlerFactory',
313  'RevisionLookup',
314  'WatchedItemStore',
315  'WikiPageFactory',
316  'WatchlistManager',
317  'UserOptionsLookup',
318  'RedirectLookup',
319  ]
320  ],
321  'upload' => [
322  'class' => ApiUpload::class,
323  'services' => [
324  'JobQueueGroup',
325  'WatchlistManager',
326  'UserOptionsLookup',
327  ]
328  ],
329  'filerevert' => [
330  'class' => ApiFileRevert::class,
331  'services' => [
332  'RepoGroup',
333  ]
334  ],
335  'emailuser' => [
336  'class' => ApiEmailUser::class,
337  ],
338  'watch' => [
339  'class' => ApiWatch::class,
340  'services' => [
341  'WatchlistManager',
342  ]
343  ],
344  'patrol' => [
345  'class' => ApiPatrol::class,
346  'services' => [
347  'RevisionStore',
348  ]
349  ],
350  'import' => [
351  'class' => ApiImport::class,
352  'services' => [
353  'WikiImporterFactory',
354  ]
355  ],
356  'clearhasmsg' => [
357  'class' => ApiClearHasMsg::class,
358  'services' => [
359  'TalkPageNotificationManager',
360  ]
361  ],
362  'userrights' => [
363  'class' => ApiUserrights::class,
364  'services' => [
365  'UserGroupManager',
366  ]
367  ],
368  'options' => [
369  'class' => ApiOptions::class,
370  'services' => [
371  'UserOptionsManager',
372  'PreferencesFactory',
373  ],
374  ],
375  'imagerotate' => [
376  'class' => ApiImageRotate::class,
377  'services' => [
378  'RepoGroup',
379  'TempFSFileFactory',
380  ]
381  ],
382  'revisiondelete' => [
383  'class' => ApiRevisionDelete::class,
384  ],
385  'managetags' => [
386  'class' => ApiManageTags::class,
387  ],
388  'tag' => [
389  'class' => ApiTag::class,
390  'services' => [
391  'DBLoadBalancer',
392  'RevisionStore',
393  ]
394  ],
395  'mergehistory' => [
396  'class' => ApiMergeHistory::class,
397  'services' => [
398  'MergeHistoryFactory',
399  ],
400  ],
401  'setpagelanguage' => [
402  'class' => ApiSetPageLanguage::class,
403  'services' => [
404  'DBLoadBalancer',
405  'LanguageNameUtils',
406  ]
407  ],
408  'changecontentmodel' => [
409  'class' => ApiChangeContentModel::class,
410  'services' => [
411  'ContentHandlerFactory',
412  'ContentModelChangeFactory',
413  ]
414  ],
415  ];
416 
420  private const FORMATS = [
421  'json' => [
422  'class' => ApiFormatJson::class,
423  ],
424  'jsonfm' => [
425  'class' => ApiFormatJson::class,
426  ],
427  'php' => [
428  'class' => ApiFormatPhp::class,
429  ],
430  'phpfm' => [
431  'class' => ApiFormatPhp::class,
432  ],
433  'xml' => [
434  'class' => ApiFormatXml::class,
435  ],
436  'xmlfm' => [
437  'class' => ApiFormatXml::class,
438  ],
439  'rawfm' => [
440  'class' => ApiFormatJson::class,
441  ],
442  'none' => [
443  'class' => ApiFormatNone::class,
444  ],
445  ];
446 
453  private const RIGHTS_MAP = [
454  'writeapi' => [
455  'msg' => 'right-writeapi',
456  'params' => []
457  ],
458  'apihighlimits' => [
459  'msg' => 'api-help-right-apihighlimits',
461  ]
462  ];
463 
465  private $mPrinter;
466 
468  private $mModuleMgr;
469 
471  private $mResult;
472 
475 
478 
481 
483  private $mAction;
484 
486  private $mEnableWrite;
487 
489  private $mInternalMode;
490 
492  private $mModule;
493 
495  private $mCacheMode = 'private';
496 
498  private $mCacheControl = [];
499 
501  private $mParamsUsed = [];
502 
504  private $mParamsSensitive = [];
505 
507  private $lacksSameOriginSecurity = null;
508 
517  public function __construct( $context = null, $enableWrite = false ) {
518  if ( $context === null ) {
520  } elseif ( $context instanceof WebRequest ) {
521  // BC for pre-1.19
522  $request = $context;
524  }
525  // We set a derivative context so we can change stuff later
526  $derivativeContext = new DerivativeContext( $context );
527  $this->setContext( $derivativeContext );
528 
529  if ( isset( $request ) ) {
530  $derivativeContext->setRequest( $request );
531  } else {
532  $request = $this->getRequest();
533  }
534 
535  $this->mInternalMode = ( $request instanceof FauxRequest );
536 
537  // Special handling for the main module: $parent === $this
538  parent::__construct( $this, $this->mInternalMode ? 'main_int' : 'main' );
539 
540  $config = $this->getConfig();
541 
542  if ( !$this->mInternalMode ) {
543  // If we're in a mode that breaks the same-origin policy, strip
544  // user credentials for security.
545  if ( $this->lacksSameOriginSecurity() ) {
546  wfDebug( "API: stripping user credentials when the same-origin policy is not applied" );
547  $user = new User();
548  StubGlobalUser::setUser( $user );
549  $derivativeContext->setUser( $user );
550  $request->response()->header( 'MediaWiki-Login-Suppressed: true' );
551  }
552  }
553 
554  // TODO inject stuff, see T265644
555  $services = MediaWikiServices::getInstance();
556  $this->mParamValidator = new ApiParamValidator(
557  $this,
558  $services->getObjectFactory()
559  );
560 
561  $this->mResult = new ApiResult( $this->getConfig()->get( 'APIMaxResultSize' ) );
562 
563  // Setup uselang. This doesn't use $this->getParameter()
564  // because we're not ready to handle errors yet.
565  // Optimisation: Avoid slow getVal(), this isn't user-generated content.
566  $uselang = $request->getRawVal( 'uselang', self::API_DEFAULT_USELANG );
567  if ( $uselang === 'user' ) {
568  // Assume the parent context is going to return the user language
569  // for uselang=user (see T85635).
570  } else {
571  if ( $uselang === 'content' ) {
572  $uselang = $services->getContentLanguage()->getCode();
573  }
574  $code = RequestContext::sanitizeLangCode( $uselang );
575  $derivativeContext->setLanguage( $code );
576  if ( !$this->mInternalMode ) {
577  global $wgLang;
578  $wgLang = $derivativeContext->getLanguage();
579  RequestContext::getMain()->setLanguage( $wgLang );
580  }
581  }
582 
583  // Set up the error formatter. This doesn't use $this->getParameter()
584  // because we're not ready to handle errors yet.
585  // Optimisation: Avoid slow getVal(), this isn't user-generated content.
586  $errorFormat = $request->getRawVal( 'errorformat', 'bc' );
587  $errorLangCode = $request->getRawVal( 'errorlang', 'uselang' );
588  $errorsUseDB = $request->getCheck( 'errorsuselocal' );
589  if ( in_array( $errorFormat, [ 'plaintext', 'wikitext', 'html', 'raw', 'none' ], true ) ) {
590  if ( $errorLangCode === 'uselang' ) {
591  $errorLang = $this->getLanguage();
592  } elseif ( $errorLangCode === 'content' ) {
593  $errorLang = $services->getContentLanguage();
594  } else {
595  $errorLangCode = RequestContext::sanitizeLangCode( $errorLangCode );
596  $errorLang = $services->getLanguageFactory()->getLanguage( $errorLangCode );
597  }
598  $this->mErrorFormatter = new ApiErrorFormatter(
599  $this->mResult,
600  $errorLang,
601  $errorFormat,
602  $errorsUseDB
603  );
604  } else {
605  $this->mErrorFormatter = new ApiErrorFormatter_BackCompat( $this->mResult );
606  }
607  $this->mResult->setErrorFormatter( $this->getErrorFormatter() );
608 
609  $this->mModuleMgr = new ApiModuleManager(
610  $this,
611  $services->getObjectFactory()
612  );
613  $this->mModuleMgr->addModules( self::MODULES, 'action' );
614  $this->mModuleMgr->addModules( $config->get( 'APIModules' ), 'action' );
615  $this->mModuleMgr->addModules( self::FORMATS, 'format' );
616  $this->mModuleMgr->addModules( $config->get( 'APIFormatModules' ), 'format' );
617 
618  $this->getHookRunner()->onApiMain__moduleManager( $this->mModuleMgr );
619 
620  $this->mContinuationManager = null;
621  $this->mEnableWrite = $enableWrite;
622  }
623 
628  public function isInternalMode() {
629  return $this->mInternalMode;
630  }
631 
637  public function getResult() {
638  return $this->mResult;
639  }
640 
645  public function lacksSameOriginSecurity() {
646  if ( $this->lacksSameOriginSecurity !== null ) {
648  }
649 
650  $request = $this->getRequest();
651 
652  // JSONP mode
653  if ( $request->getCheck( 'callback' ) ) {
654  $this->lacksSameOriginSecurity = true;
655  return true;
656  }
657 
658  // Anonymous CORS
659  if ( $request->getVal( 'origin' ) === '*' ) {
660  $this->lacksSameOriginSecurity = true;
661  return true;
662  }
663 
664  // Header to be used from XMLHTTPRequest when the request might
665  // otherwise be used for XSS.
666  if ( $request->getHeader( 'Treat-as-Untrusted' ) !== false ) {
667  $this->lacksSameOriginSecurity = true;
668  return true;
669  }
670 
671  // Allow extensions to override.
672  $this->lacksSameOriginSecurity = !$this->getHookRunner()
673  ->onRequestHasSameOriginSecurity( $request );
675  }
676 
681  public function getErrorFormatter() {
682  return $this->mErrorFormatter;
683  }
684 
688  public function getContinuationManager() {
690  }
691 
695  public function setContinuationManager( ApiContinuationManager $manager = null ) {
696  if ( $manager !== null && $this->mContinuationManager !== null ) {
697  throw new UnexpectedValueException(
698  __METHOD__ . ': tried to set manager from ' . $manager->getSource() .
699  ' when a manager is already set from ' . $this->mContinuationManager->getSource()
700  );
701  }
702  $this->mContinuationManager = $manager;
703  }
704 
710  return $this->mParamValidator;
711  }
712 
718  public function getModule() {
719  return $this->mModule;
720  }
721 
727  public function getPrinter() {
728  return $this->mPrinter;
729  }
730 
736  public function setCacheMaxAge( $maxage ) {
737  $this->setCacheControl( [
738  'max-age' => $maxage,
739  's-maxage' => $maxage
740  ] );
741  }
742 
768  public function setCacheMode( $mode ) {
769  if ( !in_array( $mode, [ 'private', 'public', 'anon-public-user-private' ] ) ) {
770  wfDebug( __METHOD__ . ": unrecognised cache mode \"$mode\"" );
771 
772  // Ignore for forwards-compatibility
773  return;
774  }
775 
776  if ( !$this->getPermissionManager()->isEveryoneAllowed( 'read' ) ) {
777  // Private wiki, only private headers
778  if ( $mode !== 'private' ) {
779  wfDebug( __METHOD__ . ": ignoring request for $mode cache mode, private wiki" );
780 
781  return;
782  }
783  }
784 
785  if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) {
786  // User language is used for i18n, so we don't want to publicly
787  // cache. Anons are ok, because if they have non-default language
788  // then there's an appropriate Vary header set by whatever set
789  // their non-default language.
790  wfDebug( __METHOD__ . ": downgrading cache mode 'public' to " .
791  "'anon-public-user-private' due to uselang=user" );
792  $mode = 'anon-public-user-private';
793  }
794 
795  wfDebug( __METHOD__ . ": setting cache mode $mode" );
796  $this->mCacheMode = $mode;
797  }
798 
809  public function setCacheControl( $directives ) {
810  $this->mCacheControl = $directives + $this->mCacheControl;
811  }
812 
820  public function createPrinterByName( $format ) {
821  $printer = $this->mModuleMgr->getModule( $format, 'format', /* $ignoreCache */ true );
822  if ( $printer === null ) {
823  $this->dieWithError(
824  [ 'apierror-unknownformat', wfEscapeWikiText( $format ) ], 'unknown_format'
825  );
826  }
827 
828  // @phan-suppress-next-line PhanTypeMismatchReturnSuperType
829  return $printer;
830  }
831 
835  public function execute() {
836  if ( $this->mInternalMode ) {
837  $this->executeAction();
838  } else {
840  }
841  }
842 
847  protected function executeActionWithErrorHandling() {
848  // Verify the CORS header before executing the action
849  if ( !$this->handleCORS() ) {
850  // handleCORS() has sent a 403, abort
851  return;
852  }
853 
854  // Exit here if the request method was OPTIONS
855  // (assume there will be a followup GET or POST)
856  if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
857  return;
858  }
859 
860  // In case an error occurs during data output,
861  // clear the output buffer and print just the error information
862  $obLevel = ob_get_level();
863  ob_start();
864 
865  $t = microtime( true );
866  $isError = false;
867  try {
868  $this->executeAction();
869  $runTime = microtime( true ) - $t;
870  $this->logRequest( $runTime );
871  MediaWikiServices::getInstance()->getStatsdDataFactory()->timing(
872  'api.' . $this->mModule->getModuleName() . '.executeTiming', 1000 * $runTime
873  );
874  } catch ( Throwable $e ) {
875  $this->handleException( $e );
876  $this->logRequest( microtime( true ) - $t, $e );
877  $isError = true;
878  }
879 
880  // Disable the client cache on the output so that BlockManager::trackBlockWithCookie is executed
881  // as part of MediaWiki::preOutputCommit().
882  if (
883  $this->mCacheMode === 'private'
884  || (
885  $this->mCacheMode === 'anon-public-user-private'
886  && SessionManager::getGlobalSession()->isPersistent()
887  )
888  ) {
889  $this->getContext()->getOutput()->enableClientCache( false );
890  $this->getContext()->getOutput()->considerCacheSettingsFinal();
891  }
892 
893  // Commit DBs and send any related cookies and headers
895 
896  // Send cache headers after any code which might generate an error, to
897  // avoid sending public cache headers for errors.
898  $this->sendCacheHeaders( $isError );
899 
900  // Executing the action might have already messed with the output
901  // buffers.
902  while ( ob_get_level() > $obLevel ) {
903  ob_end_flush();
904  }
905  }
906 
913  protected function handleException( Throwable $e ) {
914  // T65145: Rollback any open database transactions
915  if ( !$e instanceof ApiUsageException ) {
916  // ApiUsageExceptions are intentional, so don't rollback if that's the case
918  $e,
919  MWExceptionHandler::CAUGHT_BY_ENTRYPOINT
920  );
921  }
922 
923  // Allow extra cleanup and logging
924  $this->getHookRunner()->onApiMain__onException( $this, $e );
925 
926  // Handle any kind of exception by outputting properly formatted error message.
927  // If this fails, an unhandled exception should be thrown so that global error
928  // handler will process and log it.
929 
930  $errCodes = $this->substituteResultWithError( $e );
931 
932  // Error results should not be cached
933  $this->setCacheMode( 'private' );
934 
935  $response = $this->getRequest()->response();
936  $headerStr = 'MediaWiki-API-Error: ' . implode( ', ', $errCodes );
937  $response->header( $headerStr );
938 
939  // Reset and print just the error message
940  ob_clean();
941 
942  // Printer may not be initialized if the extractRequestParams() fails for the main module
943  $this->createErrorPrinter();
944 
945  // Get desired HTTP code from an ApiUsageException. Don't use codes from other
946  // exception types, as they are unlikely to be intended as an HTTP code.
947  $httpCode = $e instanceof ApiUsageException ? $e->getCode() : 0;
948 
949  $failed = false;
950  try {
951  $this->printResult( $httpCode );
952  } catch ( ApiUsageException $ex ) {
953  // The error printer itself is failing. Try suppressing its request
954  // parameters and redo.
955  $failed = true;
956  $this->addWarning( 'apiwarn-errorprinterfailed' );
957  foreach ( $ex->getStatusValue()->getErrors() as $error ) {
958  try {
959  $this->mPrinter->addWarning( $error );
960  } catch ( Throwable $ex2 ) {
961  // WTF?
962  $this->addWarning( $error );
963  }
964  }
965  }
966  if ( $failed ) {
967  $this->mPrinter = null;
968  $this->createErrorPrinter();
969  $this->mPrinter->forceDefaultParams();
970  if ( $httpCode ) {
971  $response->statusHeader( 200 ); // Reset in case the fallback doesn't want a non-200
972  }
973  $this->printResult( $httpCode );
974  }
975  }
976 
987  public static function handleApiBeforeMainException( Throwable $e ) {
988  ob_start();
989 
990  try {
991  $main = new self( RequestContext::getMain(), false );
992  $main->handleException( $e );
993  $main->logRequest( 0, $e );
994  } catch ( Throwable $e2 ) {
995  // Nope, even that didn't work. Punt.
996  throw $e;
997  }
998 
999  // Reset cache headers
1000  $main->sendCacheHeaders( true );
1001 
1002  ob_end_flush();
1003  }
1004 
1019  protected function handleCORS() {
1020  $originParam = $this->getParameter( 'origin' ); // defaults to null
1021  if ( $originParam === null ) {
1022  // No origin parameter, nothing to do
1023  return true;
1024  }
1025 
1026  $request = $this->getRequest();
1027  $response = $request->response();
1028 
1029  $allowTiming = false;
1030  $varyOrigin = true;
1031 
1032  if ( $originParam === '*' ) {
1033  // Request for anonymous CORS
1034  // Technically we should check for the presence of an Origin header
1035  // and not process it as CORS if it's not set, but that would
1036  // require us to vary on Origin for all 'origin=*' requests which
1037  // we don't want to do.
1038  $matchedOrigin = true;
1039  $allowOrigin = '*';
1040  $allowCredentials = 'false';
1041  $varyOrigin = false; // No need to vary
1042  } else {
1043  // Non-anonymous CORS, check we allow the domain
1044 
1045  // Origin: header is a space-separated list of origins, check all of them
1046  $originHeader = $request->getHeader( 'Origin' );
1047  if ( $originHeader === false ) {
1048  $origins = [];
1049  } else {
1050  $originHeader = trim( $originHeader );
1051  $origins = preg_split( '/\s+/', $originHeader );
1052  }
1053 
1054  if ( !in_array( $originParam, $origins ) ) {
1055  // origin parameter set but incorrect
1056  // Send a 403 response
1057  $response->statusHeader( 403 );
1058  $response->header( 'Cache-Control: no-cache' );
1059  echo "'origin' parameter does not match Origin header\n";
1060 
1061  return false;
1062  }
1063 
1064  $config = $this->getConfig();
1065  $origin = Origin::parseHeaderList( $origins );
1066  $matchedOrigin = $origin->match(
1067  $config->get( 'CrossSiteAJAXdomains' ),
1068  $config->get( 'CrossSiteAJAXdomainExceptions' )
1069  );
1070 
1071  $allowOrigin = $originHeader;
1072  $allowCredentials = 'true';
1073  $allowTiming = $originHeader;
1074  }
1075 
1076  if ( $matchedOrigin ) {
1077  $requestedMethod = $request->getHeader( 'Access-Control-Request-Method' );
1078  $preflight = $request->getMethod() === 'OPTIONS' && $requestedMethod !== false;
1079  if ( $preflight ) {
1080  // We allow the actual request to send the following headers
1081  $requestedHeaders = $request->getHeader( 'Access-Control-Request-Headers' );
1082  $allowedHeaders = $this->getConfig()->get( 'AllowedCorsHeaders' );
1083  if ( $requestedHeaders !== false ) {
1084  if ( !self::matchRequestedHeaders( $requestedHeaders, $allowedHeaders ) ) {
1085  $response->header( 'MediaWiki-CORS-Rejection: Unsupported header requested in preflight' );
1086  return true;
1087  }
1088  $response->header( 'Access-Control-Allow-Headers: ' . $requestedHeaders );
1089  }
1090 
1091  // We only allow the actual request to be GET, POST, or HEAD
1092  $response->header( 'Access-Control-Allow-Methods: POST, GET, HEAD' );
1093  }
1094 
1095  $response->header( "Access-Control-Allow-Origin: $allowOrigin" );
1096  $response->header( "Access-Control-Allow-Credentials: $allowCredentials" );
1097  // https://www.w3.org/TR/resource-timing/#timing-allow-origin
1098  if ( $allowTiming !== false ) {
1099  $response->header( "Timing-Allow-Origin: $allowTiming" );
1100  }
1101 
1102  if ( !$preflight ) {
1103  $response->header(
1104  'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag, '
1105  . 'MediaWiki-Login-Suppressed'
1106  );
1107  }
1108  } else {
1109  $response->header( 'MediaWiki-CORS-Rejection: Origin mismatch' );
1110  }
1111 
1112  if ( $varyOrigin ) {
1113  $this->getOutput()->addVaryHeader( 'Origin' );
1114  }
1115 
1116  return true;
1117  }
1118 
1127  protected static function matchRequestedHeaders( $requestedHeaders, $allowedHeaders ) {
1128  if ( trim( $requestedHeaders ) === '' ) {
1129  return true;
1130  }
1131  $requestedHeaders = explode( ',', $requestedHeaders );
1132  $allowedHeaders = array_change_key_case(
1133  array_fill_keys( $allowedHeaders, true ), CASE_LOWER );
1134  foreach ( $requestedHeaders as $rHeader ) {
1135  $rHeader = strtolower( trim( $rHeader ) );
1136  if ( !isset( $allowedHeaders[$rHeader] ) ) {
1137  LoggerFactory::getInstance( 'api-warning' )->warning(
1138  'CORS preflight failed on requested header: {header}', [
1139  'header' => $rHeader
1140  ]
1141  );
1142  return false;
1143  }
1144  }
1145  return true;
1146  }
1147 
1153  protected function sendCacheHeaders( $isError ) {
1154  $response = $this->getRequest()->response();
1155  $out = $this->getOutput();
1156 
1157  $out->addVaryHeader( 'Treat-as-Untrusted' );
1158 
1159  $config = $this->getConfig();
1160 
1161  if ( $config->get( 'VaryOnXFP' ) ) {
1162  $out->addVaryHeader( 'X-Forwarded-Proto' );
1163  }
1164 
1165  if ( !$isError && $this->mModule &&
1166  ( $this->getRequest()->getMethod() === 'GET' || $this->getRequest()->getMethod() === 'HEAD' )
1167  ) {
1168  $etag = $this->mModule->getConditionalRequestData( 'etag' );
1169  if ( $etag !== null ) {
1170  $response->header( "ETag: $etag" );
1171  }
1172  $lastMod = $this->mModule->getConditionalRequestData( 'last-modified' );
1173  if ( $lastMod !== null ) {
1174  $response->header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822, $lastMod ) );
1175  }
1176  }
1177 
1178  // The logic should be:
1179  // $this->mCacheControl['max-age'] is set?
1180  // Use it, the module knows better than our guess.
1181  // !$this->mModule || $this->mModule->isWriteMode(), and mCacheMode is private?
1182  // Use 0 because we can guess caching is probably the wrong thing to do.
1183  // Use $this->getParameter( 'maxage' ), which already defaults to 0.
1184  $maxage = 0;
1185  if ( isset( $this->mCacheControl['max-age'] ) ) {
1186  $maxage = $this->mCacheControl['max-age'];
1187  } elseif ( ( $this->mModule && !$this->mModule->isWriteMode() ) ||
1188  $this->mCacheMode !== 'private'
1189  ) {
1190  $maxage = $this->getParameter( 'maxage' );
1191  }
1192  $privateCache = 'private, must-revalidate, max-age=' . $maxage;
1193 
1194  if ( $this->mCacheMode == 'private' ) {
1195  $response->header( "Cache-Control: $privateCache" );
1196  return;
1197  }
1198 
1199  if ( $this->mCacheMode == 'anon-public-user-private' ) {
1200  $out->addVaryHeader( 'Cookie' );
1201  $response->header( $out->getVaryHeader() );
1202  if ( SessionManager::getGlobalSession()->isPersistent() ) {
1203  // Logged in or otherwise has session (e.g. anonymous users who have edited)
1204  // Mark request private
1205  $response->header( "Cache-Control: $privateCache" );
1206 
1207  return;
1208  } // else anonymous, send public headers below
1209  }
1210 
1211  // Send public headers
1212  $response->header( $out->getVaryHeader() );
1213 
1214  // If nobody called setCacheMaxAge(), use the (s)maxage parameters
1215  if ( !isset( $this->mCacheControl['s-maxage'] ) ) {
1216  $this->mCacheControl['s-maxage'] = $this->getParameter( 'smaxage' );
1217  }
1218  if ( !isset( $this->mCacheControl['max-age'] ) ) {
1219  $this->mCacheControl['max-age'] = $this->getParameter( 'maxage' );
1220  }
1221 
1222  if ( !$this->mCacheControl['s-maxage'] && !$this->mCacheControl['max-age'] ) {
1223  // Public cache not requested
1224  // Sending a Vary header in this case is harmless, and protects us
1225  // against conditional calls of setCacheMaxAge().
1226  $response->header( "Cache-Control: $privateCache" );
1227 
1228  return;
1229  }
1230 
1231  $this->mCacheControl['public'] = true;
1232 
1233  // Send an Expires header
1234  $maxAge = min( $this->mCacheControl['s-maxage'], $this->mCacheControl['max-age'] );
1235  $expiryUnixTime = ( $maxAge == 0 ? 1 : time() + $maxAge );
1236  $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822, $expiryUnixTime ) );
1237 
1238  // Construct the Cache-Control header
1239  $ccHeader = '';
1240  $separator = '';
1241  foreach ( $this->mCacheControl as $name => $value ) {
1242  if ( is_bool( $value ) ) {
1243  if ( $value ) {
1244  $ccHeader .= $separator . $name;
1245  $separator = ', ';
1246  }
1247  } else {
1248  $ccHeader .= $separator . "$name=$value";
1249  $separator = ', ';
1250  }
1251  }
1252 
1253  $response->header( "Cache-Control: $ccHeader" );
1254  }
1255 
1259  private function createErrorPrinter() {
1260  if ( !isset( $this->mPrinter ) ) {
1261  $value = $this->getRequest()->getVal( 'format', self::API_DEFAULT_FORMAT );
1262  if ( !$this->mModuleMgr->isDefined( $value, 'format' ) ) {
1263  $value = self::API_DEFAULT_FORMAT;
1264  }
1265  $this->mPrinter = $this->createPrinterByName( $value );
1266  }
1267 
1268  // Printer may not be able to handle errors. This is particularly
1269  // likely if the module returns something for getCustomPrinter().
1270  if ( !$this->mPrinter->canPrintErrors() ) {
1271  $this->mPrinter = $this->createPrinterByName( self::API_DEFAULT_FORMAT );
1272  }
1273  }
1274 
1290  protected function errorMessagesFromException( Throwable $e, $type = 'error' ) {
1291  $messages = [];
1292  if ( $e instanceof ApiUsageException ) {
1293  foreach ( $e->getStatusValue()->getErrorsByType( $type ) as $error ) {
1294  $messages[] = ApiMessage::create( $error );
1295  }
1296  } elseif ( $type !== 'error' ) {
1297  // None of the rest have any messages for non-error types
1298  } else {
1299  // Something is seriously wrong
1300  $config = $this->getConfig();
1301  // TODO: Avoid embedding arbitrary class names in the error code.
1302  $class = preg_replace( '#^Wikimedia\\\Rdbms\\\#', '', get_class( $e ) );
1303  $code = 'internal_api_error_' . $class;
1304  $data = [ 'errorclass' => get_class( $e ) ];
1305  if ( $config->get( 'ShowExceptionDetails' ) ) {
1306  if ( $e instanceof ILocalizedException ) {
1307  $msg = $e->getMessageObject();
1308  } elseif ( $e instanceof MessageSpecifier ) {
1309  $msg = Message::newFromSpecifier( $e );
1310  } else {
1311  $msg = wfEscapeWikiText( $e->getMessage() );
1312  }
1313  $params = [ 'apierror-exceptioncaught', WebRequest::getRequestId(), $msg ];
1314  } else {
1315  $params = [ 'apierror-exceptioncaughttype', WebRequest::getRequestId(), get_class( $e ) ];
1316  }
1317 
1318  $messages[] = ApiMessage::create( $params, $code, $data );
1319  }
1320  return $messages;
1321  }
1322 
1328  protected function substituteResultWithError( Throwable $e ) {
1329  $result = $this->getResult();
1330  $formatter = $this->getErrorFormatter();
1331  $config = $this->getConfig();
1332  $errorCodes = [];
1333 
1334  // Remember existing warnings and errors across the reset
1335  $errors = $result->getResultData( [ 'errors' ] );
1336  $warnings = $result->getResultData( [ 'warnings' ] );
1337  $result->reset();
1338  if ( $warnings !== null ) {
1339  $result->addValue( null, 'warnings', $warnings, ApiResult::NO_SIZE_CHECK );
1340  }
1341  if ( $errors !== null ) {
1342  $result->addValue( null, 'errors', $errors, ApiResult::NO_SIZE_CHECK );
1343 
1344  // Collect the copied error codes for the return value
1345  foreach ( $errors as $error ) {
1346  if ( isset( $error['code'] ) ) {
1347  $errorCodes[$error['code']] = true;
1348  }
1349  }
1350  }
1351 
1352  // Add errors from the exception
1353  $modulePath = $e instanceof ApiUsageException ? $e->getModulePath() : null;
1354  foreach ( $this->errorMessagesFromException( $e, 'error' ) as $msg ) {
1355  if ( ApiErrorFormatter::isValidApiCode( $msg->getApiCode() ) ) {
1356  $errorCodes[$msg->getApiCode()] = true;
1357  } else {
1358  LoggerFactory::getInstance( 'api-warning' )->error( 'Invalid API error code "{code}"', [
1359  'code' => $msg->getApiCode(),
1360  'exception' => $e,
1361  ] );
1362  $errorCodes['<invalid-code>'] = true;
1363  }
1364  $formatter->addError( $modulePath, $msg );
1365  }
1366  foreach ( $this->errorMessagesFromException( $e, 'warning' ) as $msg ) {
1367  $formatter->addWarning( $modulePath, $msg );
1368  }
1369 
1370  // Add additional data. Path depends on whether we're in BC mode or not.
1371  // Data depends on the type of exception.
1372  if ( $formatter instanceof ApiErrorFormatter_BackCompat ) {
1373  $path = [ 'error' ];
1374  } else {
1375  $path = null;
1376  }
1377  if ( $e instanceof ApiUsageException ) {
1378  $link = wfExpandUrl( wfScript( 'api' ) );
1379  $result->addContentValue(
1380  $path,
1381  'docref',
1382  trim(
1383  $this->msg( 'api-usage-docref', $link )->inLanguage( $formatter->getLanguage() )->text()
1384  . ' '
1385  . $this->msg( 'api-usage-mailinglist-ref' )->inLanguage( $formatter->getLanguage() )->text()
1386  )
1387  );
1388  } elseif ( $config->get( 'ShowExceptionDetails' ) ) {
1389  $result->addContentValue(
1390  $path,
1391  'trace',
1392  $this->msg( 'api-exception-trace',
1393  get_class( $e ),
1394  $e->getFile(),
1395  $e->getLine(),
1397  )->inLanguage( $formatter->getLanguage() )->text()
1398  );
1399  }
1400 
1401  // Add the id and such
1402  $this->addRequestedFields( [ 'servedby' ] );
1403 
1404  return array_keys( $errorCodes );
1405  }
1406 
1412  protected function addRequestedFields( $force = [] ) {
1413  $result = $this->getResult();
1414 
1415  $requestid = $this->getParameter( 'requestid' );
1416  if ( $requestid !== null ) {
1417  $result->addValue( null, 'requestid', $requestid, ApiResult::NO_SIZE_CHECK );
1418  }
1419 
1420  if ( $this->getConfig()->get( 'ShowHostnames' ) && (
1421  in_array( 'servedby', $force, true ) || $this->getParameter( 'servedby' )
1422  ) ) {
1423  $result->addValue( null, 'servedby', wfHostname(), ApiResult::NO_SIZE_CHECK );
1424  }
1425 
1426  if ( $this->getParameter( 'curtimestamp' ) ) {
1427  $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601 ), ApiResult::NO_SIZE_CHECK );
1428  }
1429 
1430  if ( $this->getParameter( 'responselanginfo' ) ) {
1431  $result->addValue(
1432  null,
1433  'uselang',
1434  $this->getLanguage()->getCode(),
1436  );
1437  $result->addValue(
1438  null,
1439  'errorlang',
1440  $this->getErrorFormatter()->getLanguage()->getCode(),
1442  );
1443  }
1444  }
1445 
1450  protected function setupExecuteAction() {
1451  $this->addRequestedFields();
1452 
1453  $params = $this->extractRequestParams();
1454  $this->mAction = $params['action'];
1455 
1456  return $params;
1457  }
1458 
1465  protected function setupModule() {
1466  // Instantiate the module requested by the user
1467  $module = $this->mModuleMgr->getModule( $this->mAction, 'action' );
1468  if ( $module === null ) {
1469  // Probably can't happen
1470  // @codeCoverageIgnoreStart
1471  $this->dieWithError(
1472  [ 'apierror-unknownaction', wfEscapeWikiText( $this->mAction ) ],
1473  'unknown_action'
1474  );
1475  // @codeCoverageIgnoreEnd
1476  }
1477  $moduleParams = $module->extractRequestParams();
1478 
1479  // Check token, if necessary
1480  if ( $module->needsToken() === true ) {
1481  throw new MWException(
1482  "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
1483  'See documentation for ApiBase::needsToken for details.'
1484  );
1485  }
1486  if ( $module->needsToken() ) {
1487  if ( !$module->mustBePosted() ) {
1488  throw new MWException(
1489  "Module '{$module->getModuleName()}' must require POST to use tokens."
1490  );
1491  }
1492 
1493  if ( !isset( $moduleParams['token'] ) ) {
1494  // Probably can't happen
1495  // @codeCoverageIgnoreStart
1496  $module->dieWithError( [ 'apierror-missingparam', 'token' ] );
1497  // @codeCoverageIgnoreEnd
1498  }
1499 
1500  $module->requirePostedParameters( [ 'token' ] );
1501 
1502  if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) {
1503  $module->dieWithError( 'apierror-badtoken' );
1504  }
1505  }
1506 
1507  return $module;
1508  }
1509 
1513  private function getMaxLag() {
1514  $dbLag = MediaWikiServices::getInstance()->getDBLoadBalancer()->getMaxLag();
1515  $lagInfo = [
1516  'host' => $dbLag[0],
1517  'lag' => $dbLag[1],
1518  'type' => 'db'
1519  ];
1520 
1521  $jobQueueLagFactor = $this->getConfig()->get( 'JobQueueIncludeInMaxLagFactor' );
1522  if ( $jobQueueLagFactor ) {
1523  // Turn total number of jobs into seconds by using the configured value
1524  $totalJobs = array_sum( JobQueueGroup::singleton()->getQueueSizes() );
1525  $jobQueueLag = $totalJobs / (float)$jobQueueLagFactor;
1526  if ( $jobQueueLag > $lagInfo['lag'] ) {
1527  $lagInfo = [
1528  'host' => wfHostname(), // XXX: Is there a better value that could be used?
1529  'lag' => $jobQueueLag,
1530  'type' => 'jobqueue',
1531  'jobs' => $totalJobs,
1532  ];
1533  }
1534  }
1535 
1536  $this->getHookRunner()->onApiMaxLagInfo( $lagInfo );
1537 
1538  return $lagInfo;
1539  }
1540 
1547  protected function checkMaxLag( $module, $params ) {
1548  if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
1549  $maxLag = $params['maxlag'];
1550  $lagInfo = $this->getMaxLag();
1551  if ( $lagInfo['lag'] > $maxLag ) {
1552  $response = $this->getRequest()->response();
1553 
1554  $response->header( 'Retry-After: ' . max( (int)$maxLag, 5 ) );
1555  $response->header( 'X-Database-Lag: ' . (int)$lagInfo['lag'] );
1556 
1557  if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
1558  $this->dieWithError(
1559  [ 'apierror-maxlag', $lagInfo['lag'], $lagInfo['host'] ],
1560  'maxlag',
1561  $lagInfo
1562  );
1563  }
1564 
1565  $this->dieWithError( [ 'apierror-maxlag-generic', $lagInfo['lag'] ], 'maxlag', $lagInfo );
1566  }
1567  }
1568 
1569  return true;
1570  }
1571 
1593  protected function checkConditionalRequestHeaders( $module ) {
1594  if ( $this->mInternalMode ) {
1595  // No headers to check in internal mode
1596  return true;
1597  }
1598 
1599  if ( $this->getRequest()->getMethod() !== 'GET' && $this->getRequest()->getMethod() !== 'HEAD' ) {
1600  // Don't check POSTs
1601  return true;
1602  }
1603 
1604  $return304 = false;
1605 
1606  $ifNoneMatch = array_diff(
1607  $this->getRequest()->getHeader( 'If-None-Match', WebRequest::GETHEADER_LIST ) ?: [],
1608  [ '' ]
1609  );
1610  if ( $ifNoneMatch ) {
1611  // @phan-suppress-next-line PhanImpossibleTypeComparison
1612  if ( $ifNoneMatch === [ '*' ] ) {
1613  // API responses always "exist"
1614  $etag = '*';
1615  } else {
1616  $etag = $module->getConditionalRequestData( 'etag' );
1617  }
1618  }
1619  if ( $ifNoneMatch && $etag !== null ) {
1620  $test = substr( $etag, 0, 2 ) === 'W/' ? substr( $etag, 2 ) : $etag;
1621  $match = array_map( static function ( $s ) {
1622  return substr( $s, 0, 2 ) === 'W/' ? substr( $s, 2 ) : $s;
1623  }, $ifNoneMatch );
1624  $return304 = in_array( $test, $match, true );
1625  } else {
1626  $value = trim( $this->getRequest()->getHeader( 'If-Modified-Since' ) );
1627 
1628  // Some old browsers sends sizes after the date, like this:
1629  // Wed, 20 Aug 2003 06:51:19 GMT; length=5202
1630  // Ignore that.
1631  $i = strpos( $value, ';' );
1632  if ( $i !== false ) {
1633  $value = trim( substr( $value, 0, $i ) );
1634  }
1635 
1636  if ( $value !== '' ) {
1637  try {
1638  $ts = new MWTimestamp( $value );
1639  if (
1640  // RFC 7231 IMF-fixdate
1641  $ts->getTimestamp( TS_RFC2822 ) === $value ||
1642  // RFC 850
1643  $ts->format( 'l, d-M-y H:i:s' ) . ' GMT' === $value ||
1644  // asctime (with and without space-padded day)
1645  $ts->format( 'D M j H:i:s Y' ) === $value ||
1646  $ts->format( 'D M j H:i:s Y' ) === $value
1647  ) {
1648  $config = $this->getConfig();
1649  $lastMod = $module->getConditionalRequestData( 'last-modified' );
1650  if ( $lastMod !== null ) {
1651  // Mix in some MediaWiki modification times
1652  $modifiedTimes = [
1653  'page' => $lastMod,
1654  'user' => $this->getUser()->getTouched(),
1655  'epoch' => $config->get( 'CacheEpoch' ),
1656  ];
1657 
1658  if ( $config->get( 'UseCdn' ) ) {
1659  // T46570: the core page itself may not change, but resources might
1660  $modifiedTimes['sepoch'] = wfTimestamp(
1661  TS_MW, time() - $config->get( 'CdnMaxAge' )
1662  );
1663  }
1664  $this->getHookRunner()->onOutputPageCheckLastModified( $modifiedTimes, $this->getOutput() );
1665  $lastMod = max( $modifiedTimes );
1666  $return304 = wfTimestamp( TS_MW, $lastMod ) <= $ts->getTimestamp( TS_MW );
1667  }
1668  }
1669  } catch ( TimestampException $e ) {
1670  // Invalid timestamp, ignore it
1671  }
1672  }
1673  }
1674 
1675  if ( $return304 ) {
1676  $this->getRequest()->response()->statusHeader( 304 );
1677 
1678  // Avoid outputting the compressed representation of a zero-length body
1679  Wikimedia\suppressWarnings();
1680  ini_set( 'zlib.output_compression', 0 );
1681  Wikimedia\restoreWarnings();
1682  wfResetOutputBuffers( false );
1683 
1684  return false;
1685  }
1686 
1687  return true;
1688  }
1689 
1694  protected function checkExecutePermissions( $module ) {
1695  $user = $this->getUser();
1696  if ( $module->isReadMode() && !$this->getPermissionManager()->isEveryoneAllowed( 'read' ) &&
1697  !$this->getAuthority()->isAllowed( 'read' )
1698  ) {
1699  $this->dieWithError( 'apierror-readapidenied' );
1700  }
1701 
1702  if ( $module->isWriteMode() ) {
1703  if ( !$this->mEnableWrite ) {
1704  $this->dieWithError( 'apierror-noapiwrite' );
1705  } elseif ( !$this->getAuthority()->isAllowed( 'writeapi' ) ) {
1706  $this->dieWithError( 'apierror-writeapidenied' );
1707  } elseif ( $this->getRequest()->getHeader( 'Promise-Non-Write-API-Action' ) ) {
1708  $this->dieWithError( 'apierror-promised-nonwrite-api' );
1709  }
1710 
1711  $this->checkReadOnly( $module );
1712  }
1713 
1714  // Allow extensions to stop execution for arbitrary reasons.
1715  // TODO: change hook to accept Authority
1716  $message = 'hookaborted';
1717  if ( !$this->getHookRunner()->onApiCheckCanExecute( $module, $user, $message ) ) {
1718  $this->dieWithError( $message );
1719  }
1720  }
1721 
1726  protected function checkReadOnly( $module ) {
1727  if ( MediaWikiServices::getInstance()->getReadOnlyMode()->isReadOnly() ) {
1728  $this->dieReadOnly();
1729  }
1730 
1731  if ( $module->isWriteMode()
1732  && $this->getUser()->isBot()
1733  && MediaWikiServices::getInstance()->getDBLoadBalancer()->getServerCount() > 1
1734  ) {
1735  $this->checkBotReadOnly();
1736  }
1737  }
1738 
1742  private function checkBotReadOnly() {
1743  // Figure out how many servers have passed the lag threshold
1744  $numLagged = 0;
1745  $lagLimit = $this->getConfig()->get( 'APIMaxLagThreshold' );
1746  $laggedServers = [];
1747  $loadBalancer = MediaWikiServices::getInstance()->getDBLoadBalancer();
1748  foreach ( $loadBalancer->getLagTimes() as $serverIndex => $lag ) {
1749  if ( $lag > $lagLimit ) {
1750  ++$numLagged;
1751  $laggedServers[] = $loadBalancer->getServerName( $serverIndex ) . " ({$lag}s)";
1752  }
1753  }
1754 
1755  // If a majority of replica DBs are too lagged then disallow writes
1756  $replicaCount = $loadBalancer->getServerCount() - 1;
1757  if ( $numLagged >= ceil( $replicaCount / 2 ) ) {
1758  $laggedServers = implode( ', ', $laggedServers );
1759  wfDebugLog(
1760  'api-readonly', // Deprecate this channel in favor of api-warning?
1761  "Api request failed as read only because the following DBs are lagged: $laggedServers"
1762  );
1763  LoggerFactory::getInstance( 'api-warning' )->warning(
1764  "Api request failed as read only because the following DBs are lagged: {laggeddbs}", [
1765  'laggeddbs' => $laggedServers,
1766  ]
1767  );
1768 
1769  $this->dieWithError(
1770  'readonly_lag',
1771  'readonly',
1772  [ 'readonlyreason' => "Waiting for $numLagged lagged database(s)" ]
1773  );
1774  }
1775  }
1776 
1781  protected function checkAsserts( $params ) {
1782  if ( isset( $params['assert'] ) ) {
1783  $user = $this->getUser();
1784  switch ( $params['assert'] ) {
1785  case 'anon':
1786  if ( $user->isRegistered() ) {
1787  $this->dieWithError( 'apierror-assertanonfailed' );
1788  }
1789  break;
1790  case 'user':
1791  if ( !$user->isRegistered() ) {
1792  $this->dieWithError( 'apierror-assertuserfailed' );
1793  }
1794  break;
1795  case 'bot':
1796  if ( !$this->getAuthority()->isAllowed( 'bot' ) ) {
1797  $this->dieWithError( 'apierror-assertbotfailed' );
1798  }
1799  break;
1800  }
1801  }
1802  if ( isset( $params['assertuser'] ) ) {
1803  // TODO inject stuff, see T265644
1804  $assertUser = MediaWikiServices::getInstance()->getUserFactory()
1805  ->newFromName( $params['assertuser'], UserFactory::RIGOR_NONE );
1806  if ( !$assertUser || !$this->getUser()->equals( $assertUser ) ) {
1807  $this->dieWithError(
1808  [ 'apierror-assertnameduserfailed', wfEscapeWikiText( $params['assertuser'] ) ]
1809  );
1810  }
1811  }
1812  }
1813 
1819  protected function setupExternalResponse( $module, $params ) {
1820  $validMethods = [ 'GET', 'HEAD', 'POST', 'OPTIONS' ];
1821  $request = $this->getRequest();
1822 
1823  if ( !in_array( $request->getMethod(), $validMethods ) ) {
1824  $this->dieWithError( 'apierror-invalidmethod', null, null, 405 );
1825  }
1826 
1827  if ( !$request->wasPosted() && $module->mustBePosted() ) {
1828  // Module requires POST. GET request might still be allowed
1829  // if $wgDebugApi is true, otherwise fail.
1830  $this->dieWithErrorOrDebug( [ 'apierror-mustbeposted', $this->mAction ] );
1831  }
1832 
1833  if ( $request->wasPosted() && !$request->getHeader( 'Content-Type' ) ) {
1834  $this->addDeprecation(
1835  'apiwarn-deprecation-post-without-content-type', 'post-without-content-type'
1836  );
1837  }
1838 
1839  // See if custom printer is used
1840  $this->mPrinter = $module->getCustomPrinter();
1841  if ( $this->mPrinter === null ) {
1842  // Create an appropriate printer
1843  $this->mPrinter = $this->createPrinterByName( $params['format'] );
1844  }
1845 
1846  if ( $request->getProtocol() === 'http' &&
1847  (
1848  $this->getConfig()->get( 'ForceHTTPS' ) ||
1849  $request->getSession()->shouldForceHTTPS() ||
1850  ( $this->getUser()->isRegistered() &&
1851  $this->getUser()->requiresHTTPS() )
1852  )
1853  ) {
1854  $this->addDeprecation( 'apiwarn-deprecation-httpsexpected', 'https-expected' );
1855  }
1856  }
1857 
1861  protected function executeAction() {
1862  $params = $this->setupExecuteAction();
1863 
1864  // Check asserts early so e.g. errors in parsing a module's parameters due to being
1865  // logged out don't override the client's intended "am I logged in?" check.
1866  $this->checkAsserts( $params );
1867 
1868  $module = $this->setupModule();
1869  $this->mModule = $module;
1870 
1871  if ( !$this->mInternalMode ) {
1872  $this->setRequestExpectations( $module );
1873  }
1874 
1875  $this->checkExecutePermissions( $module );
1876 
1877  if ( !$this->checkMaxLag( $module, $params ) ) {
1878  return;
1879  }
1880 
1881  if ( !$this->checkConditionalRequestHeaders( $module ) ) {
1882  return;
1883  }
1884 
1885  if ( !$this->mInternalMode ) {
1886  $this->setupExternalResponse( $module, $params );
1887  }
1888 
1889  $module->execute();
1890  $this->getHookRunner()->onAPIAfterExecute( $module );
1891 
1892  $this->reportUnusedParams();
1893 
1894  if ( !$this->mInternalMode ) {
1896 
1897  $this->printResult();
1898  }
1899  }
1900 
1905  protected function setRequestExpectations( ApiBase $module ) {
1906  $limits = $this->getConfig()->get( 'TrxProfilerLimits' );
1907  $trxProfiler = Profiler::instance()->getTransactionProfiler();
1908  $trxProfiler->setLogger( LoggerFactory::getInstance( 'DBPerformance' ) );
1909  if ( $this->getRequest()->hasSafeMethod() ) {
1910  $trxProfiler->setExpectations( $limits['GET'], __METHOD__ );
1911  } elseif ( $this->getRequest()->wasPosted() && !$module->isWriteMode() ) {
1912  $trxProfiler->setExpectations( $limits['POST-nonwrite'], __METHOD__ );
1913  $this->getRequest()->markAsSafeRequest();
1914  } else {
1915  $trxProfiler->setExpectations( $limits['POST'], __METHOD__ );
1916  }
1917  }
1918 
1924  protected function logRequest( $time, Throwable $e = null ) {
1925  $request = $this->getRequest();
1926 
1927  $user = $this->getUser();
1928  $performer = [
1929  'user_text' => $user->getName(),
1930  ];
1931  if ( $user->isRegistered() ) {
1932  $performer['user_id'] = $user->getId();
1933  }
1934  $logCtx = [
1935  // https://gerrit.wikimedia.org/g/mediawiki/event-schemas/+/master/jsonschema/mediawiki/api/request
1936  '$schema' => '/mediawiki/api/request/1.0.0',
1937  'meta' => [
1938  'request_id' => WebRequest::getRequestId(),
1939  'id' => MediaWikiServices::getInstance()
1940  ->getGlobalIdGenerator()->newUUIDv4(),
1941  'dt' => wfTimestamp( TS_ISO_8601 ),
1942  'domain' => $this->getConfig()->get( 'ServerName' ),
1943  // If using the EventBus extension (as intended) with this log channel,
1944  // this stream name will map to a Kafka topic.
1945  'stream' => 'mediawiki.api-request'
1946  ],
1947  'http' => [
1948  'method' => $request->getMethod(),
1949  'client_ip' => $request->getIP()
1950  ],
1951  'performer' => $performer,
1952  'database' => WikiMap::getCurrentWikiDbDomain()->getId(),
1953  'backend_time_ms' => (int)round( $time * 1000 ),
1954  ];
1955 
1956  // If set, these headers will be logged in http.request_headers.
1957  $httpRequestHeadersToLog = [ 'accept-language', 'referer', 'user-agent' ];
1958  foreach ( $httpRequestHeadersToLog as $header ) {
1959  if ( $request->getHeader( $header ) ) {
1960  // Set the header in http.request_headers
1961  $logCtx['http']['request_headers'][$header] = $request->getHeader( $header );
1962  }
1963  }
1964 
1965  if ( $e ) {
1966  $logCtx['api_error_codes'] = [];
1967  foreach ( $this->errorMessagesFromException( $e ) as $msg ) {
1968  $logCtx['api_error_codes'][] = $msg->getApiCode();
1969  }
1970  }
1971 
1972  // Construct space separated message for 'api' log channel
1973  $msg = "API {$request->getMethod()} " .
1974  wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
1975  " {$logCtx['http']['client_ip']} " .
1976  "T={$logCtx['backend_time_ms']}ms";
1977 
1978  $sensitive = array_fill_keys( $this->getSensitiveParams(), true );
1979  foreach ( $this->getParamsUsed() as $name ) {
1980  $value = $request->getVal( $name );
1981  if ( $value === null ) {
1982  continue;
1983  }
1984 
1985  if ( isset( $sensitive[$name] ) ) {
1986  $value = '[redacted]';
1987  $encValue = '[redacted]';
1988  } elseif ( strlen( $value ) > 256 ) {
1989  $value = substr( $value, 0, 256 );
1990  $encValue = $this->encodeRequestLogValue( $value ) . '[...]';
1991  } else {
1992  $encValue = $this->encodeRequestLogValue( $value );
1993  }
1994 
1995  $logCtx['params'][$name] = $value;
1996  $msg .= " {$name}={$encValue}";
1997  }
1998 
1999  // Log an unstructured message to the api channel.
2000  wfDebugLog( 'api', $msg, 'private' );
2001 
2002  // The api-request channel a structured data log channel.
2003  wfDebugLog( 'api-request', '', 'private', $logCtx );
2004  }
2005 
2011  protected function encodeRequestLogValue( $s ) {
2012  static $table = [];
2013  if ( !$table ) {
2014  $chars = ';@$!*(),/:';
2015  $numChars = strlen( $chars );
2016  for ( $i = 0; $i < $numChars; $i++ ) {
2017  $table[rawurlencode( $chars[$i] )] = $chars[$i];
2018  }
2019  }
2020 
2021  return strtr( rawurlencode( $s ), $table );
2022  }
2023 
2028  protected function getParamsUsed() {
2029  return array_keys( $this->mParamsUsed );
2030  }
2031 
2036  public function markParamsUsed( $params ) {
2037  $this->mParamsUsed += array_fill_keys( (array)$params, true );
2038  }
2039 
2045  protected function getSensitiveParams() {
2046  return array_keys( $this->mParamsSensitive );
2047  }
2048 
2058  public function markParamsSensitive( $params ) {
2059  $this->mParamsSensitive += array_fill_keys( (array)$params, true );
2060  }
2061 
2068  public function getVal( $name, $default = null ) {
2069  $this->mParamsUsed[$name] = true;
2070 
2071  $ret = $this->getRequest()->getVal( $name );
2072  if ( $ret === null ) {
2073  if ( $this->getRequest()->getArray( $name ) !== null ) {
2074  // See T12262 for why we don't just implode( '|', ... ) the
2075  // array.
2076  $this->addWarning( [ 'apiwarn-unsupportedarray', $name ] );
2077  }
2078  $ret = $default;
2079  }
2080  return $ret;
2081  }
2082 
2089  public function getCheck( $name ) {
2090  $this->mParamsUsed[$name] = true;
2091  return $this->getRequest()->getCheck( $name );
2092  }
2093 
2101  public function getUpload( $name ) {
2102  $this->mParamsUsed[$name] = true;
2103 
2104  return $this->getRequest()->getUpload( $name );
2105  }
2106 
2111  protected function reportUnusedParams() {
2112  $paramsUsed = $this->getParamsUsed();
2113  $allParams = $this->getRequest()->getValueNames();
2114 
2115  if ( !$this->mInternalMode ) {
2116  // Printer has not yet executed; don't warn that its parameters are unused
2117  $printerParams = $this->mPrinter->encodeParamName(
2118  array_keys( $this->mPrinter->getFinalParams() ?: [] )
2119  );
2120  $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
2121  } else {
2122  $unusedParams = array_diff( $allParams, $paramsUsed );
2123  }
2124 
2125  if ( count( $unusedParams ) ) {
2126  $this->addWarning( [
2127  'apierror-unrecognizedparams',
2128  Message::listParam( array_map( 'wfEscapeWikiText', $unusedParams ), 'comma' ),
2129  count( $unusedParams )
2130  ] );
2131  }
2132  }
2133 
2139  protected function printResult( $httpCode = 0 ) {
2140  if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
2141  $this->addWarning( 'apiwarn-wgdebugapi' );
2142  }
2143 
2144  $printer = $this->mPrinter;
2145  $printer->initPrinter( false );
2146  if ( $httpCode ) {
2147  $printer->setHttpStatus( $httpCode );
2148  }
2149  $printer->execute();
2150  $printer->closePrinter();
2151  }
2152 
2156  public function isReadMode() {
2157  return false;
2158  }
2159 
2165  public function getAllowedParams() {
2166  return [
2167  'action' => [
2168  ApiBase::PARAM_DFLT => 'help',
2169  ApiBase::PARAM_TYPE => 'submodule',
2170  ],
2171  'format' => [
2173  ApiBase::PARAM_TYPE => 'submodule',
2174  ],
2175  'maxlag' => [
2176  ApiBase::PARAM_TYPE => 'integer'
2177  ],
2178  'smaxage' => [
2179  ApiBase::PARAM_TYPE => 'integer',
2180  ApiBase::PARAM_DFLT => 0
2181  ],
2182  'maxage' => [
2183  ApiBase::PARAM_TYPE => 'integer',
2184  ApiBase::PARAM_DFLT => 0
2185  ],
2186  'assert' => [
2187  ApiBase::PARAM_TYPE => [ 'anon', 'user', 'bot' ]
2188  ],
2189  'assertuser' => [
2190  ApiBase::PARAM_TYPE => 'user',
2191  UserDef::PARAM_ALLOWED_USER_TYPES => [ 'name' ],
2192  ],
2193  'requestid' => null,
2194  'servedby' => false,
2195  'curtimestamp' => false,
2196  'responselanginfo' => false,
2197  'origin' => null,
2198  'uselang' => [
2200  ],
2201  'variant' => null,
2202  'errorformat' => [
2203  ApiBase::PARAM_TYPE => [ 'plaintext', 'wikitext', 'html', 'raw', 'none', 'bc' ],
2204  ApiBase::PARAM_DFLT => 'bc',
2206  ],
2207  'errorlang' => [
2208  ApiBase::PARAM_DFLT => 'uselang',
2209  ],
2210  'errorsuselocal' => [
2211  ApiBase::PARAM_DFLT => false,
2212  ],
2213  ];
2214  }
2215 
2217  protected function getExamplesMessages() {
2218  return [
2219  'action=help'
2220  => 'apihelp-help-example-main',
2221  'action=help&recursivesubmodules=1'
2222  => 'apihelp-help-example-recursive',
2223  ];
2224  }
2225 
2230  public function modifyHelp( array &$help, array $options, array &$tocData ) {
2231  // Wish PHP had an "array_insert_before". Instead, we have to manually
2232  // reindex the array to get 'permissions' in the right place.
2233  $oldHelp = $help;
2234  $help = [];
2235  foreach ( $oldHelp as $k => $v ) {
2236  if ( $k === 'submodules' ) {
2237  $help['permissions'] = '';
2238  }
2239  $help[$k] = $v;
2240  }
2241  $help['datatypes'] = '';
2242  $help['templatedparams'] = '';
2243  $help['credits'] = '';
2244 
2245  // Fill 'permissions'
2246  $help['permissions'] .= Html::openElement( 'div',
2247  [ 'class' => 'apihelp-block apihelp-permissions' ] );
2248  $m = $this->msg( 'api-help-permissions' );
2249  if ( !$m->isDisabled() ) {
2250  $help['permissions'] .= Html::rawElement( 'div', [ 'class' => 'apihelp-block-head' ],
2251  $m->numParams( count( self::RIGHTS_MAP ) )->parse()
2252  );
2253  }
2254  $help['permissions'] .= Html::openElement( 'dl' );
2255  // TODO inject stuff, see T265644
2256  $groupPermissionsLookup = MediaWikiServices::getInstance()->getGroupPermissionsLookup();
2257  foreach ( self::RIGHTS_MAP as $right => $rightMsg ) {
2258  $help['permissions'] .= Html::element( 'dt', [], $right );
2259 
2260  $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse();
2261  $help['permissions'] .= Html::rawElement( 'dd', [], $rightMsg );
2262 
2263  $groups = array_map( static function ( $group ) {
2264  return $group == '*' ? 'all' : $group;
2265  }, $groupPermissionsLookup->getGroupsWithPermission( $right ) );
2266 
2267  $help['permissions'] .= Html::rawElement( 'dd', [],
2268  $this->msg( 'api-help-permissions-granted-to' )
2269  ->numParams( count( $groups ) )
2270  ->params( Message::listParam( $groups ) )
2271  ->parse()
2272  );
2273  }
2274  $help['permissions'] .= Html::closeElement( 'dl' );
2275  $help['permissions'] .= Html::closeElement( 'div' );
2276 
2277  // Fill 'datatypes', 'templatedparams', and 'credits', if applicable
2278  if ( empty( $options['nolead'] ) ) {
2279  $level = $options['headerlevel'];
2280  $tocnumber = &$options['tocnumber'];
2281 
2282  $header = $this->msg( 'api-help-datatypes-header' )->parse();
2283 
2284  $id = Sanitizer::escapeIdForAttribute( 'main/datatypes', Sanitizer::ID_PRIMARY );
2285  $idFallback = Sanitizer::escapeIdForAttribute( 'main/datatypes', Sanitizer::ID_FALLBACK );
2286  $headline = Linker::makeHeadline( min( 6, $level ),
2287  ' class="apihelp-header">',
2288  $id,
2289  $header,
2290  '',
2291  $idFallback
2292  );
2293  // Ensure we have a sensible anchor
2294  if ( $id !== 'main/datatypes' && $idFallback !== 'main/datatypes' ) {
2295  $headline = '<div id="main/datatypes"></div>' . $headline;
2296  }
2297  $help['datatypes'] .= $headline;
2298  $help['datatypes'] .= $this->msg( 'api-help-datatypes-top' )->parseAsBlock();
2299  $help['datatypes'] .= '<dl>';
2300  foreach ( $this->getParamValidator()->knownTypes() as $type ) {
2301  $m = $this->msg( "api-help-datatype-$type" );
2302  if ( !$m->isDisabled() ) {
2303  $id = "main/datatype/$type";
2304  $help['datatypes'] .= '<dt id="' . htmlspecialchars( $id ) . '">';
2306  if ( $encId !== $id ) {
2307  $help['datatypes'] .= '<span id="' . htmlspecialchars( $encId ) . '"></span>';
2308  }
2310  if ( $encId2 !== $id && $encId2 !== $encId ) {
2311  $help['datatypes'] .= '<span id="' . htmlspecialchars( $encId2 ) . '"></span>';
2312  }
2313  $help['datatypes'] .= htmlspecialchars( $type ) . '</dt><dd>' . $m->parseAsBlock() . "</dd>";
2314  }
2315  }
2316  $help['datatypes'] .= '</dl>';
2317  if ( !isset( $tocData['main/datatypes'] ) ) {
2318  $tocnumber[$level]++;
2319  $tocData['main/datatypes'] = [
2320  'toclevel' => count( $tocnumber ),
2321  'level' => $level,
2322  'anchor' => 'main/datatypes',
2323  'line' => $header,
2324  'number' => implode( '.', $tocnumber ),
2325  'index' => false,
2326  ];
2327  }
2328 
2329  $header = $this->msg( 'api-help-templatedparams-header' )->parse();
2330 
2331  $id = Sanitizer::escapeIdForAttribute( 'main/templatedparams', Sanitizer::ID_PRIMARY );
2332  $idFallback = Sanitizer::escapeIdForAttribute( 'main/templatedparams', Sanitizer::ID_FALLBACK );
2333  $headline = Linker::makeHeadline( min( 6, $level ),
2334  ' class="apihelp-header">',
2335  $id,
2336  $header,
2337  '',
2338  $idFallback
2339  );
2340  // Ensure we have a sensible anchor
2341  if ( $id !== 'main/templatedparams' && $idFallback !== 'main/templatedparams' ) {
2342  $headline = '<div id="main/templatedparams"></div>' . $headline;
2343  }
2344  $help['templatedparams'] .= $headline;
2345  $help['templatedparams'] .= $this->msg( 'api-help-templatedparams' )->parseAsBlock();
2346  if ( !isset( $tocData['main/templatedparams'] ) ) {
2347  $tocnumber[$level]++;
2348  $tocData['main/templatedparams'] = [
2349  'toclevel' => count( $tocnumber ),
2350  'level' => $level,
2351  'anchor' => 'main/templatedparams',
2352  'line' => $header,
2353  'number' => implode( '.', $tocnumber ),
2354  'index' => false,
2355  ];
2356  }
2357 
2358  $header = $this->msg( 'api-credits-header' )->parse();
2359  $id = Sanitizer::escapeIdForAttribute( 'main/credits', Sanitizer::ID_PRIMARY );
2360  $idFallback = Sanitizer::escapeIdForAttribute( 'main/credits', Sanitizer::ID_FALLBACK );
2361  $headline = Linker::makeHeadline( min( 6, $level ),
2362  ' class="apihelp-header">',
2363  $id,
2364  $header,
2365  '',
2366  $idFallback
2367  );
2368  // Ensure we have a sensible anchor
2369  if ( $id !== 'main/credits' && $idFallback !== 'main/credits' ) {
2370  $headline = '<div id="main/credits"></div>' . $headline;
2371  }
2372  $help['credits'] .= $headline;
2373  $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
2374  if ( !isset( $tocData['main/credits'] ) ) {
2375  $tocnumber[$level]++;
2376  $tocData['main/credits'] = [
2377  'toclevel' => count( $tocnumber ),
2378  'level' => $level,
2379  'anchor' => 'main/credits',
2380  'line' => $header,
2381  'number' => implode( '.', $tocnumber ),
2382  'index' => false,
2383  ];
2384  }
2385  }
2386  }
2387 
2388  private $mCanApiHighLimits = null;
2389 
2394  public function canApiHighLimits() {
2395  if ( !isset( $this->mCanApiHighLimits ) ) {
2396  $this->mCanApiHighLimits = $this->getAuthority()->isAllowed( 'apihighlimits' );
2397  }
2398 
2399  return $this->mCanApiHighLimits;
2400  }
2401 
2406  public function getModuleManager() {
2407  return $this->mModuleMgr;
2408  }
2409 
2418  public function getUserAgent() {
2419  return trim(
2420  $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
2421  $this->getRequest()->getHeader( 'User-agent' )
2422  );
2423  }
2424 }
2425 
ApiUsageException\getStatusValue
getStatusValue()
Fetch the error status.
Definition: ApiUsageException.php:107
ApiMain\$mModuleMgr
ApiModuleManager $mModuleMgr
Definition: ApiMain.php:468
ApiMain\executeActionWithErrorHandling
executeActionWithErrorHandling()
Execute an action, and in case of an error, erase whatever partial results have been accumulated,...
Definition: ApiMain.php:847
MWTimestamp
Library for creating and parsing MW-style timestamps.
Definition: MWTimestamp.php:38
ApiMain
This is the main API class, used for both external and internal processing.
Definition: ApiMain.php:49
ContextSource\$context
IContextSource $context
Definition: ContextSource.php:39
ContextSource\getConfig
getConfig()
Definition: ContextSource.php:72
Sanitizer\ID_FALLBACK
const ID_FALLBACK
Tells escapeUrlForHtml() to encode the ID using the fallback encoding, or return false if no fallback...
Definition: Sanitizer.php:79
Message\newFromSpecifier
static newFromSpecifier( $value)
Transform a MessageSpecifier or a primitive value used interchangeably with specifiers (a message key...
Definition: Message.php:399
FauxRequest
WebRequest clone which takes values from a provided array.
Definition: FauxRequest.php:36
ApiUsageException
Exception used to abort API execution with an error.
Definition: ApiUsageException.php:29
ContextSource\getContext
getContext()
Get the base IContextSource object.
Definition: ContextSource.php:47
wfResetOutputBuffers
wfResetOutputBuffers( $resetGzipEncoding=true)
Clear away any user-level output buffers, discarding contents.
Definition: GlobalFunctions.php:1588
ApiMain\substituteResultWithError
substituteResultWithError(Throwable $e)
Replace the result data with the information about a throwable.
Definition: ApiMain.php:1328
ApiMain\checkReadOnly
checkReadOnly( $module)
Check if the DB is read-only for this user.
Definition: ApiMain.php:1726
ApiBase\addWarning
addWarning( $msg, $code=null, $data=null)
Add a warning for this module.
Definition: ApiBase.php:1354
RequestContext\sanitizeLangCode
static sanitizeLangCode( $code)
Accepts a language code and ensures it's sensible.
Definition: RequestContext.php:327
WikiMap\getCurrentWikiDbDomain
static getCurrentWikiDbDomain()
Definition: WikiMap.php:293
ApiErrorFormatter_BackCompat
Format errors and warnings in the old style, for backwards compatibility.
Definition: ApiErrorFormatter_BackCompat.php:30
ApiErrorFormatter\isValidApiCode
static isValidApiCode( $code)
Test whether a code is a valid API error code.
Definition: ApiErrorFormatter.php:79
ApiMain\getParamsUsed
getParamsUsed()
Get the request parameters used in the course of the preceding execute() request.
Definition: ApiMain.php:2028
Profiler\instance
static instance()
Singleton.
Definition: Profiler.php:69
ApiMain\MODULES
const MODULES
List of available modules: action name => module class.
Definition: ApiMain.php:63
ApiMain\createErrorPrinter
createErrorPrinter()
Create the printer for error output.
Definition: ApiMain.php:1259
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:203
ApiMain\getErrorFormatter
getErrorFormatter()
Get the ApiErrorFormatter object associated with current request.
Definition: ApiMain.php:681
ApiMain\getVal
getVal( $name, $default=null)
Get a request value, and register the fact that it was used, for logging.
Definition: ApiMain.php:2068
ApiMain\errorMessagesFromException
errorMessagesFromException(Throwable $e, $type='error')
Create an error message for the given throwable.
Definition: ApiMain.php:1290
ApiUsageException\getModulePath
getModulePath()
Fetch the responsible module name.
Definition: ApiUsageException.php:99
ApiContinuationManager
This manages continuation state.
Definition: ApiContinuationManager.php:26
Sanitizer\escapeIdForAttribute
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:811
ApiBase\dieWithError
dieWithError( $msg, $code=null, $data=null, $httpCode=null)
Abort execution with an error.
Definition: ApiBase.php:1436
ApiMain\$mEnableWrite
bool $mEnableWrite
Definition: ApiMain.php:486
ApiMain\sendCacheHeaders
sendCacheHeaders( $isError)
Send caching headers.
Definition: ApiMain.php:1153
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1649
ApiBase\PARAM_TYPE
const PARAM_TYPE
Definition: ApiBase.php:81
ApiFormatBase
This is the abstract base class for API formatters.
Definition: ApiFormatBase.php:30
ApiMain\handleException
handleException(Throwable $e)
Handle a throwable as an API response.
Definition: ApiMain.php:913
MessageSpecifier
Definition: MessageSpecifier.php:24
wfUrlencode
wfUrlencode( $s)
We want some things to be included as literal characters in our title URLs for prettiness,...
Definition: GlobalFunctions.php:292
ApiMain\isReadMode
isReadMode()
Definition: ApiMain.php:2156
ApiMain\handleCORS
handleCORS()
Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
Definition: ApiMain.php:1019
MediaWiki\Api\Validator\ApiParamValidator
This wraps a bunch of the API-specific parameter validation logic.
Definition: ApiParamValidator.php:38
ApiMain\checkConditionalRequestHeaders
checkConditionalRequestHeaders( $module)
Check selected RFC 7232 precondition headers.
Definition: ApiMain.php:1593
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:1608
ApiMain\lacksSameOriginSecurity
lacksSameOriginSecurity()
Get the security flag for the current request.
Definition: ApiMain.php:645
wfHostname
wfHostname()
Get host name of the current machine, for use in error reporting.
Definition: GlobalFunctions.php:1230
ApiMain\getParamValidator
getParamValidator()
Get the parameter validator.
Definition: ApiMain.php:709
StubGlobalUser\setUser
static setUser( $user)
Reset the stub global user to a different "real" user object, while ensuring that any method calls on...
Definition: StubGlobalUser.php:79
ApiResult\NO_SIZE_CHECK
const NO_SIZE_CHECK
For addValue() and similar functions, do not check size while adding a value Don't use this unless yo...
Definition: ApiResult.php:58
ContextSource\getRequest
getRequest()
Definition: ContextSource.php:81
ApiMain\$mCacheControl
array $mCacheControl
Definition: ApiMain.php:498
ApiMain\encodeRequestLogValue
encodeRequestLogValue( $s)
Encode a value in a format suitable for a space-separated log line.
Definition: ApiMain.php:2011
ApiMain\$mResult
ApiResult $mResult
Definition: ApiMain.php:471
ContextSource\getUser
getUser()
Definition: ContextSource.php:136
ApiMain\getMaxLag
getMaxLag()
Definition: ApiMain.php:1513
ApiMain\$mContinuationManager
ApiContinuationManager null $mContinuationManager
Definition: ApiMain.php:480
$wgLang
$wgLang
Definition: Setup.php:861
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:958
Message\listParam
static listParam(array $list, $type='text')
Definition: Message.php:1259
ApiMain\FORMATS
const FORMATS
List of available formats: format name => format class.
Definition: ApiMain.php:420
ApiBase
This abstract class implements many basic API functions, and is the base of all API classes.
Definition: ApiBase.php:55
ApiMain\$mErrorFormatter
ApiErrorFormatter $mErrorFormatter
Definition: ApiMain.php:474
Wikimedia\ParamValidator\ParamValidator::TypeDef\UserDef
Type definition for user types.
Definition: UserDef.php:26
ContextSource\getLanguage
getLanguage()
Definition: ContextSource.php:153
ApiMain\matchRequestedHeaders
static matchRequestedHeaders( $requestedHeaders, $allowedHeaders)
Attempt to validate the value of Access-Control-Request-Headers against a list of headers that we all...
Definition: ApiMain.php:1127
Html\closeElement
static closeElement( $element)
Returns "</$element>".
Definition: Html.php:319
ApiMain\getModule
getModule()
Get the API module object.
Definition: ApiMain.php:718
MWExceptionHandler\getRedactedTraceAsString
static getRedactedTraceAsString(Throwable $e)
Generate a string representation of a throwable's stack trace.
Definition: MWExceptionHandler.php:375
DerivativeContext
An IContextSource implementation which will inherit context from another source but allow individual ...
Definition: DerivativeContext.php:32
ApiMain\markParamsUsed
markParamsUsed( $params)
Mark parameters as used.
Definition: ApiMain.php:2036
MWException
MediaWiki exception.
Definition: MWException.php:29
MediaWiki\Logger\LoggerFactory
PSR-3 logger instance factory.
Definition: LoggerFactory.php:45
ApiMain\setupExecuteAction
setupExecuteAction()
Set up for the execution.
Definition: ApiMain.php:1450
wfScript
wfScript( $script='index')
Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScri...
Definition: GlobalFunctions.php:2268
ApiResult
This class represents the result of the API operations.
Definition: ApiResult.php:35
ApiMain\$lacksSameOriginSecurity
bool null $lacksSameOriginSecurity
Cached return value from self::lacksSameOriginSecurity()
Definition: ApiMain.php:507
ApiMain\$mParamsSensitive
array $mParamsSensitive
Definition: ApiMain.php:504
ContextSource\getOutput
getOutput()
Definition: ContextSource.php:126
Linker\makeHeadline
static makeHeadline( $level, $attribs, $anchor, $html, $link, $fallbackAnchor=false)
Create a headline for content.
Definition: Linker.php:1737
ApiMain\getResult
getResult()
Get the ApiResult object associated with current request.
Definition: ApiMain.php:637
ApiMain\getSensitiveParams
getSensitiveParams()
Get the request parameters that should be considered sensitive.
Definition: ApiMain.php:2045
ApiMain\$mPrinter
ApiFormatBase null $mPrinter
Definition: ApiMain.php:465
ApiMain\checkMaxLag
checkMaxLag( $module, $params)
Check the max lag if necessary.
Definition: ApiMain.php:1547
ApiMain\API_DEFAULT_USELANG
const API_DEFAULT_USELANG
When no uselang parameter is given, this language will be used.
Definition: ApiMain.php:58
ApiBase\extractRequestParams
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition: ApiBase.php:764
ApiMain\getExamplesMessages
getExamplesMessages()
Returns usage examples for this module.Return value has query strings as keys, with values being eith...
Definition: ApiMain.php:2217
ApiMain\setCacheControl
setCacheControl( $directives)
Set directives (key/value pairs) for the Cache-Control header.
Definition: ApiMain.php:809
ApiMain\getAllowedParams
getAllowedParams()
See ApiBase for description.
Definition: ApiMain.php:2165
ApiMain\setupExternalResponse
setupExternalResponse( $module, $params)
Check POST for external response and setup result printer.
Definition: ApiMain.php:1819
ApiMain\createPrinterByName
createPrinterByName( $format)
Create an instance of an output formatter by its name.
Definition: ApiMain.php:820
ApiMain\getModuleManager
getModuleManager()
Overrides to return this instance's module manager.
Definition: ApiMain.php:2406
ApiMain\$mCanApiHighLimits
$mCanApiHighLimits
Definition: ApiMain.php:2388
ApiMessage\create
static create( $msg, $code=null, array $data=null)
Create an IApiMessage for the message.
Definition: ApiMessage.php:43
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:894
ApiMain\addRequestedFields
addRequestedFields( $force=[])
Add requested fields to the result.
Definition: ApiMain.php:1412
ContextSource\setContext
setContext(IContextSource $context)
Definition: ContextSource.php:63
ILocalizedException
Interface for MediaWiki-localized exceptions.
Definition: ILocalizedException.php:29
ApiMain\canApiHighLimits
canApiHighLimits()
Check whether the current user is allowed to use high limits.
Definition: ApiMain.php:2394
ApiMain\checkBotReadOnly
checkBotReadOnly()
Check whether we are readonly for bots.
Definition: ApiMain.php:1742
ApiMain\getContinuationManager
getContinuationManager()
Definition: ApiMain.php:688
ApiModuleManager
This class holds a list of modules and handles instantiation.
Definition: ApiModuleManager.php:33
ContextSource\msg
msg( $key,... $params)
Get a Message object with context set Parameters are the same as wfMessage()
Definition: ContextSource.php:197
ApiMain\RIGHTS_MAP
const RIGHTS_MAP
List of user roles that are specifically relevant to the API.
Definition: ApiMain.php:453
ApiMain\checkAsserts
checkAsserts( $params)
Check asserts of the user's rights.
Definition: ApiMain.php:1781
MWDebug\appendDebugInfoToApiResult
static appendDebugInfoToApiResult(IContextSource $context, ApiResult $result)
Append the debug info to given ApiResult.
Definition: MWDebug.php:673
$s
foreach( $mmfl['setupFiles'] as $fileName) if( $queue) if(empty( $mmfl['quiet'])) $s
Definition: mergeMessageFileList.php:206
ApiMain\setContinuationManager
setContinuationManager(ApiContinuationManager $manager=null)
Definition: ApiMain.php:695
MediaWiki\preOutputCommit
static preOutputCommit(IContextSource $context, callable $postCommitWork=null)
This function commits all DB and session changes as needed before the client can receive a response (...
Definition: MediaWiki.php:661
ApiMain\checkExecutePermissions
checkExecutePermissions( $module)
Check for sufficient permissions to execute.
Definition: ApiMain.php:1694
ApiBase\addDeprecation
addDeprecation( $msg, $feature, $data=[])
Add a deprecation warning for this module.
Definition: ApiBase.php:1368
ContextSource\getAuthority
getAuthority()
Definition: ContextSource.php:144
$header
$header
Definition: updateCredits.php:37
ApiBase\LIMIT_SML2
const LIMIT_SML2
Slow query, apihighlimits limit.
Definition: ApiBase.php:226
ApiBase\dieReadOnly
dieReadOnly()
Helper function for readonly errors.
Definition: ApiBase.php:1528
MediaWiki\Session\SessionManager
This serves as the entry point to the MediaWiki session handling system.
Definition: SessionManager.php:83
ApiMain\__construct
__construct( $context=null, $enableWrite=false)
Constructs an instance of ApiMain that utilizes the module and format specified by $request.
Definition: ApiMain.php:517
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:2111
ApiBase\getPermissionManager
getPermissionManager()
Obtain a PermissionManager instance that subclasses may use in their authorization checks.
Definition: ApiBase.php:685
ApiMain\execute
execute()
Execute api request.
Definition: ApiMain.php:835
ApiBase\isWriteMode
isWriteMode()
Indicates whether this module requires write mode.
Definition: ApiBase.php:399
wfEscapeWikiText
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
Definition: GlobalFunctions.php:1440
ApiMain\$mInternalMode
bool $mInternalMode
Definition: ApiMain.php:489
ApiMain\markParamsSensitive
markParamsSensitive( $params)
Mark parameters as sensitive.
Definition: ApiMain.php:2058
ApiMain\setRequestExpectations
setRequestExpectations(ApiBase $module)
Set database connection, query, and write expectations given this module request.
Definition: ApiMain.php:1905
ApiMain\$mParamValidator
ApiParamValidator $mParamValidator
Definition: ApiMain.php:477
RequestContext\getMain
static getMain()
Get the RequestContext object associated with the main request.
Definition: RequestContext.php:484
ApiMain\logRequest
logRequest( $time, Throwable $e=null)
Log the preceding request.
Definition: ApiMain.php:1924
ApiMain\getCheck
getCheck( $name)
Get a boolean request value, and register the fact that the parameter was used, for logging.
Definition: ApiMain.php:2089
ApiMain\printResult
printResult( $httpCode=0)
Print results using the current printer.
Definition: ApiMain.php:2139
WebRequest
The WebRequest class encapsulates getting at data passed in the URL or via a POSTed form stripping il...
Definition: WebRequest.php:43
ApiErrorFormatter
Formats errors and warnings for the API, and add them to the associated ApiResult.
Definition: ApiErrorFormatter.php:34
MWExceptionHandler\rollbackPrimaryChangesAndLog
static rollbackPrimaryChangesAndLog(Throwable $e, $catcher=self::CAUGHT_BY_OTHER)
Roll back any open database transactions and log the stack trace of the throwable.
Definition: MWExceptionHandler.php:126
ApiMain\handleApiBeforeMainException
static handleApiBeforeMainException(Throwable $e)
Handle a throwable from the ApiBeforeMain hook.
Definition: ApiMain.php:987
JobQueueGroup\singleton
static singleton( $domain=false)
Definition: JobQueueGroup.php:114
ApiBase\LIMIT_BIG2
const LIMIT_BIG2
Fast query, apihighlimits limit.
Definition: ApiBase.php:222
ApiMain\API_DEFAULT_FORMAT
const API_DEFAULT_FORMAT
When no format parameter is given, this format will be used.
Definition: ApiMain.php:53
WebRequest\GETHEADER_LIST
const GETHEADER_LIST
Flag to make WebRequest::getHeader return an array of values.
Definition: WebRequest.php:73
ApiMain\getUpload
getUpload( $name)
Get a request upload, and register the fact that it was used, for logging.
Definition: ApiMain.php:2101
ApiMain\$mAction
string null $mAction
Definition: ApiMain.php:483
ApiMain\modifyHelp
modifyHelp(array &$help, array $options, array &$tocData)
Called from ApiHelp before the pieces are joined together and returned.This exists mainly for ApiMain...
Definition: ApiMain.php:2230
Sanitizer\ID_PRIMARY
const ID_PRIMARY
Tells escapeUrlForHtml() to encode the ID using the wiki's primary encoding.
Definition: Sanitizer.php:71
WebRequest\getRequestId
static getRequestId()
Get the current request ID.
Definition: WebRequest.php:333
$path
$path
Definition: NoLocalSettings.php:25
ApiBase\PARAM_DFLT
const PARAM_DFLT
Definition: ApiBase.php:73
ApiBase\getParameter
getParameter( $paramName, $parseLimit=true)
Get a value for the given parameter.
Definition: ApiBase.php:884
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:255
Html\rawElement
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
Definition: Html.php:213
ApiMain\executeAction
executeAction()
Execute the actual module, without any error handling.
Definition: ApiMain.php:1861
ApiMain\setupModule
setupModule()
Set up the module for response.
Definition: ApiMain.php:1465
$help
$help
Definition: mcc.php:32
ApiMain\$mCacheMode
string $mCacheMode
Definition: ApiMain.php:495
$t
$t
Definition: testCompression.php:74
Html\element
static element( $element, $attribs=[], $contents='')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
Definition: Html.php:235
ApiMain\isInternalMode
isInternalMode()
Return true if the API was started by other PHP code using FauxRequest.
Definition: ApiMain.php:628
ApiMain\getUserAgent
getUserAgent()
Fetches the user agent used for this request.
Definition: ApiMain.php:2418
ApiBase\PARAM_HELP_MSG_PER_VALUE
const PARAM_HELP_MSG_PER_VALUE
((string|array|Message)[]) When PARAM_TYPE is an array, this is an array mapping those values to $msg...
Definition: ApiBase.php:195
ApiMain\setCacheMaxAge
setCacheMaxAge( $maxage)
Set how long the response should be cached.
Definition: ApiMain.php:736
ApiBase\getHookRunner
getHookRunner()
Get an ApiHookRunner for running core API hooks.
Definition: ApiBase.php:710
User
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:67
MediaWiki\Rest\HeaderParser\Origin
A class to assist with the parsing of Origin header according to the RFC 6454 https://tools....
Definition: Origin.php:12
ApiFormatBase\initPrinter
initPrinter( $unused=false)
Initialize the printer function and prepare the output headers.
Definition: ApiFormatBase.php:189
ApiMain\setCacheMode
setCacheMode( $mode)
Set the type of caching headers which will be sent.
Definition: ApiMain.php:768
MediaWiki\User\UserFactory
Creates User objects.
Definition: UserFactory.php:41
ApiMain\getPrinter
getPrinter()
Get the result formatter object.
Definition: ApiMain.php:727
wfExpandUrl
wfExpandUrl( $url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.
Definition: GlobalFunctions.php:474
ApiMain\$mParamsUsed
array $mParamsUsed
Definition: ApiMain.php:501
$type
$type
Definition: testCompression.php:52
ApiMain\$mModule
ApiBase $mModule
Definition: ApiMain.php:492