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  ]
268  ],
269  'protect' => [
270  'class' => ApiProtect::class,
271  'services' => [
272  'WatchlistManager',
273  'UserOptionsLookup',
274  ]
275  ],
276  'block' => [
277  'class' => ApiBlock::class,
278  'services' => [
279  'BlockPermissionCheckerFactory',
280  'BlockUserFactory',
281  'TitleFactory',
282  'UserIdentityLookup',
283  'WatchedItemStore',
284  'BlockUtils',
285  'BlockActionInfo',
286  'WatchlistManager',
287  'UserOptionsLookup',
288  ]
289  ],
290  'unblock' => [
291  'class' => ApiUnblock::class,
292  'services' => [
293  'BlockPermissionCheckerFactory',
294  'UnblockUserFactory',
295  'UserIdentityLookup',
296  ]
297  ],
298  'move' => [
299  'class' => ApiMove::class,
300  'services' => [
301  'MovePageFactory',
302  'RepoGroup',
303  'WatchlistManager',
304  'UserOptionsLookup',
305  ]
306  ],
307  'edit' => [
308  'class' => ApiEditPage::class,
309  'services' => [
310  'ContentHandlerFactory',
311  'RevisionLookup',
312  'WatchedItemStore',
313  'WikiPageFactory',
314  'WatchlistManager',
315  'UserOptionsLookup',
316  ]
317  ],
318  'upload' => [
319  'class' => ApiUpload::class,
320  'services' => [
321  'JobQueueGroup',
322  'WatchlistManager',
323  'UserOptionsLookup',
324  ]
325  ],
326  'filerevert' => [
327  'class' => ApiFileRevert::class,
328  'services' => [
329  'RepoGroup',
330  ]
331  ],
332  'emailuser' => [
333  'class' => ApiEmailUser::class,
334  ],
335  'watch' => [
336  'class' => ApiWatch::class,
337  'services' => [
338  'WatchlistManager',
339  ]
340  ],
341  'patrol' => [
342  'class' => ApiPatrol::class,
343  'services' => [
344  'RevisionStore',
345  ]
346  ],
347  'import' => [
348  'class' => ApiImport::class,
349  'services' => [
350  'WikiImporterFactory',
351  ]
352  ],
353  'clearhasmsg' => [
354  'class' => ApiClearHasMsg::class,
355  'services' => [
356  'TalkPageNotificationManager',
357  ]
358  ],
359  'userrights' => [
360  'class' => ApiUserrights::class,
361  'services' => [
362  'UserGroupManager',
363  ]
364  ],
365  'options' => [
366  'class' => ApiOptions::class,
367  'services' => [
368  'UserOptionsManager',
369  'PreferencesFactory',
370  ],
371  ],
372  'imagerotate' => [
373  'class' => ApiImageRotate::class,
374  'services' => [
375  'RepoGroup',
376  'TempFSFileFactory',
377  ]
378  ],
379  'revisiondelete' => [
380  'class' => ApiRevisionDelete::class,
381  ],
382  'managetags' => [
383  'class' => ApiManageTags::class,
384  ],
385  'tag' => [
386  'class' => ApiTag::class,
387  'services' => [
388  'DBLoadBalancer',
389  'RevisionStore',
390  ]
391  ],
392  'mergehistory' => [
393  'class' => ApiMergeHistory::class,
394  'services' => [
395  'MergeHistoryFactory',
396  ],
397  ],
398  'setpagelanguage' => [
399  'class' => ApiSetPageLanguage::class,
400  'services' => [
401  'DBLoadBalancer',
402  'LanguageNameUtils',
403  ]
404  ],
405  'changecontentmodel' => [
406  'class' => ApiChangeContentModel::class,
407  'services' => [
408  'ContentHandlerFactory',
409  'ContentModelChangeFactory',
410  ]
411  ],
412  ];
413 
417  private const FORMATS = [
418  'json' => [
419  'class' => ApiFormatJson::class,
420  ],
421  'jsonfm' => [
422  'class' => ApiFormatJson::class,
423  ],
424  'php' => [
425  'class' => ApiFormatPhp::class,
426  ],
427  'phpfm' => [
428  'class' => ApiFormatPhp::class,
429  ],
430  'xml' => [
431  'class' => ApiFormatXml::class,
432  ],
433  'xmlfm' => [
434  'class' => ApiFormatXml::class,
435  ],
436  'rawfm' => [
437  'class' => ApiFormatJson::class,
438  ],
439  'none' => [
440  'class' => ApiFormatNone::class,
441  ],
442  ];
443 
450  private const RIGHTS_MAP = [
451  'writeapi' => [
452  'msg' => 'right-writeapi',
453  'params' => []
454  ],
455  'apihighlimits' => [
456  'msg' => 'api-help-right-apihighlimits',
458  ]
459  ];
460 
462  private $mPrinter;
463 
465  private $mModuleMgr;
466 
468  private $mResult;
469 
472 
475 
478 
480  private $mAction;
481 
483  private $mEnableWrite;
484 
486  private $mInternalMode;
487 
489  private $mModule;
490 
492  private $mCacheMode = 'private';
493 
495  private $mCacheControl = [];
496 
498  private $mParamsUsed = [];
499 
501  private $mParamsSensitive = [];
502 
504  private $lacksSameOriginSecurity = null;
505 
514  public function __construct( $context = null, $enableWrite = false ) {
515  if ( $context === null ) {
517  } elseif ( $context instanceof WebRequest ) {
518  // BC for pre-1.19
519  $request = $context;
521  }
522  // We set a derivative context so we can change stuff later
523  $derivativeContext = new DerivativeContext( $context );
524  $this->setContext( $derivativeContext );
525 
526  if ( isset( $request ) ) {
527  $derivativeContext->setRequest( $request );
528  } else {
529  $request = $this->getRequest();
530  }
531 
532  $this->mInternalMode = ( $request instanceof FauxRequest );
533 
534  // Special handling for the main module: $parent === $this
535  parent::__construct( $this, $this->mInternalMode ? 'main_int' : 'main' );
536 
537  $config = $this->getConfig();
538 
539  if ( !$this->mInternalMode ) {
540  // If we're in a mode that breaks the same-origin policy, strip
541  // user credentials for security.
542  if ( $this->lacksSameOriginSecurity() ) {
543  wfDebug( "API: stripping user credentials when the same-origin policy is not applied" );
544  $user = new User();
545  StubGlobalUser::setUser( $user );
546  $derivativeContext->setUser( $user );
547  $request->response()->header( 'MediaWiki-Login-Suppressed: true' );
548  }
549  }
550 
551  // TODO inject stuff, see T265644
552  $services = MediaWikiServices::getInstance();
553  $this->mParamValidator = new ApiParamValidator(
554  $this,
555  $services->getObjectFactory()
556  );
557 
558  $this->mResult = new ApiResult( $this->getConfig()->get( 'APIMaxResultSize' ) );
559 
560  // Setup uselang. This doesn't use $this->getParameter()
561  // because we're not ready to handle errors yet.
562  // Optimisation: Avoid slow getVal(), this isn't user-generated content.
563  $uselang = $request->getRawVal( 'uselang', self::API_DEFAULT_USELANG );
564  if ( $uselang === 'user' ) {
565  // Assume the parent context is going to return the user language
566  // for uselang=user (see T85635).
567  } else {
568  if ( $uselang === 'content' ) {
569  $uselang = $services->getContentLanguage()->getCode();
570  }
571  $code = RequestContext::sanitizeLangCode( $uselang );
572  $derivativeContext->setLanguage( $code );
573  if ( !$this->mInternalMode ) {
574  global $wgLang;
575  $wgLang = $derivativeContext->getLanguage();
576  RequestContext::getMain()->setLanguage( $wgLang );
577  }
578  }
579 
580  // Set up the error formatter. This doesn't use $this->getParameter()
581  // because we're not ready to handle errors yet.
582  // Optimisation: Avoid slow getVal(), this isn't user-generated content.
583  $errorFormat = $request->getRawVal( 'errorformat', 'bc' );
584  $errorLangCode = $request->getRawVal( 'errorlang', 'uselang' );
585  $errorsUseDB = $request->getCheck( 'errorsuselocal' );
586  if ( in_array( $errorFormat, [ 'plaintext', 'wikitext', 'html', 'raw', 'none' ], true ) ) {
587  if ( $errorLangCode === 'uselang' ) {
588  $errorLang = $this->getLanguage();
589  } elseif ( $errorLangCode === 'content' ) {
590  $errorLang = $services->getContentLanguage();
591  } else {
592  $errorLangCode = RequestContext::sanitizeLangCode( $errorLangCode );
593  $errorLang = $services->getLanguageFactory()->getLanguage( $errorLangCode );
594  }
595  $this->mErrorFormatter = new ApiErrorFormatter(
596  $this->mResult,
597  $errorLang,
598  $errorFormat,
599  $errorsUseDB
600  );
601  } else {
602  $this->mErrorFormatter = new ApiErrorFormatter_BackCompat( $this->mResult );
603  }
604  $this->mResult->setErrorFormatter( $this->getErrorFormatter() );
605 
606  $this->mModuleMgr = new ApiModuleManager(
607  $this,
608  $services->getObjectFactory()
609  );
610  $this->mModuleMgr->addModules( self::MODULES, 'action' );
611  $this->mModuleMgr->addModules( $config->get( 'APIModules' ), 'action' );
612  $this->mModuleMgr->addModules( self::FORMATS, 'format' );
613  $this->mModuleMgr->addModules( $config->get( 'APIFormatModules' ), 'format' );
614 
615  $this->getHookRunner()->onApiMain__moduleManager( $this->mModuleMgr );
616 
617  $this->mContinuationManager = null;
618  $this->mEnableWrite = $enableWrite;
619  }
620 
625  public function isInternalMode() {
626  return $this->mInternalMode;
627  }
628 
634  public function getResult() {
635  return $this->mResult;
636  }
637 
642  public function lacksSameOriginSecurity() {
643  if ( $this->lacksSameOriginSecurity !== null ) {
645  }
646 
647  $request = $this->getRequest();
648 
649  // JSONP mode
650  if ( $request->getCheck( 'callback' ) ) {
651  $this->lacksSameOriginSecurity = true;
652  return true;
653  }
654 
655  // Anonymous CORS
656  if ( $request->getVal( 'origin' ) === '*' ) {
657  $this->lacksSameOriginSecurity = true;
658  return true;
659  }
660 
661  // Header to be used from XMLHTTPRequest when the request might
662  // otherwise be used for XSS.
663  if ( $request->getHeader( 'Treat-as-Untrusted' ) !== false ) {
664  $this->lacksSameOriginSecurity = true;
665  return true;
666  }
667 
668  // Allow extensions to override.
669  $this->lacksSameOriginSecurity = !$this->getHookRunner()
670  ->onRequestHasSameOriginSecurity( $request );
672  }
673 
678  public function getErrorFormatter() {
679  return $this->mErrorFormatter;
680  }
681 
685  public function getContinuationManager() {
687  }
688 
692  public function setContinuationManager( ApiContinuationManager $manager = null ) {
693  if ( $manager !== null && $this->mContinuationManager !== null ) {
694  throw new UnexpectedValueException(
695  __METHOD__ . ': tried to set manager from ' . $manager->getSource() .
696  ' when a manager is already set from ' . $this->mContinuationManager->getSource()
697  );
698  }
699  $this->mContinuationManager = $manager;
700  }
701 
707  return $this->mParamValidator;
708  }
709 
715  public function getModule() {
716  return $this->mModule;
717  }
718 
724  public function getPrinter() {
725  return $this->mPrinter;
726  }
727 
733  public function setCacheMaxAge( $maxage ) {
734  $this->setCacheControl( [
735  'max-age' => $maxage,
736  's-maxage' => $maxage
737  ] );
738  }
739 
765  public function setCacheMode( $mode ) {
766  if ( !in_array( $mode, [ 'private', 'public', 'anon-public-user-private' ] ) ) {
767  wfDebug( __METHOD__ . ": unrecognised cache mode \"$mode\"" );
768 
769  // Ignore for forwards-compatibility
770  return;
771  }
772 
773  if ( !$this->getPermissionManager()->isEveryoneAllowed( 'read' ) ) {
774  // Private wiki, only private headers
775  if ( $mode !== 'private' ) {
776  wfDebug( __METHOD__ . ": ignoring request for $mode cache mode, private wiki" );
777 
778  return;
779  }
780  }
781 
782  if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) {
783  // User language is used for i18n, so we don't want to publicly
784  // cache. Anons are ok, because if they have non-default language
785  // then there's an appropriate Vary header set by whatever set
786  // their non-default language.
787  wfDebug( __METHOD__ . ": downgrading cache mode 'public' to " .
788  "'anon-public-user-private' due to uselang=user" );
789  $mode = 'anon-public-user-private';
790  }
791 
792  wfDebug( __METHOD__ . ": setting cache mode $mode" );
793  $this->mCacheMode = $mode;
794  }
795 
806  public function setCacheControl( $directives ) {
807  $this->mCacheControl = $directives + $this->mCacheControl;
808  }
809 
817  public function createPrinterByName( $format ) {
818  $printer = $this->mModuleMgr->getModule( $format, 'format', /* $ignoreCache */ true );
819  if ( $printer === null ) {
820  $this->dieWithError(
821  [ 'apierror-unknownformat', wfEscapeWikiText( $format ) ], 'unknown_format'
822  );
823  }
824 
825  // @phan-suppress-next-line PhanTypeMismatchReturnSuperType
826  return $printer;
827  }
828 
832  public function execute() {
833  if ( $this->mInternalMode ) {
834  $this->executeAction();
835  } else {
837  }
838  }
839 
844  protected function executeActionWithErrorHandling() {
845  // Verify the CORS header before executing the action
846  if ( !$this->handleCORS() ) {
847  // handleCORS() has sent a 403, abort
848  return;
849  }
850 
851  // Exit here if the request method was OPTIONS
852  // (assume there will be a followup GET or POST)
853  if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
854  return;
855  }
856 
857  // In case an error occurs during data output,
858  // clear the output buffer and print just the error information
859  $obLevel = ob_get_level();
860  ob_start();
861 
862  $t = microtime( true );
863  $isError = false;
864  try {
865  $this->executeAction();
866  $runTime = microtime( true ) - $t;
867  $this->logRequest( $runTime );
868  MediaWikiServices::getInstance()->getStatsdDataFactory()->timing(
869  'api.' . $this->mModule->getModuleName() . '.executeTiming', 1000 * $runTime
870  );
871  } catch ( Throwable $e ) {
872  $this->handleException( $e );
873  $this->logRequest( microtime( true ) - $t, $e );
874  $isError = true;
875  }
876 
877  // Disable the client cache on the output so that BlockManager::trackBlockWithCookie is executed
878  // as part of MediaWiki::preOutputCommit().
879  if (
880  $this->mCacheMode === 'private'
881  || (
882  $this->mCacheMode === 'anon-public-user-private'
883  && SessionManager::getGlobalSession()->isPersistent()
884  )
885  ) {
886  $this->getContext()->getOutput()->enableClientCache( false );
887  $this->getContext()->getOutput()->considerCacheSettingsFinal();
888  }
889 
890  // Commit DBs and send any related cookies and headers
892 
893  // Send cache headers after any code which might generate an error, to
894  // avoid sending public cache headers for errors.
895  $this->sendCacheHeaders( $isError );
896 
897  // Executing the action might have already messed with the output
898  // buffers.
899  while ( ob_get_level() > $obLevel ) {
900  ob_end_flush();
901  }
902  }
903 
910  protected function handleException( Throwable $e ) {
911  // T65145: Rollback any open database transactions
912  if ( !$e instanceof ApiUsageException ) {
913  // ApiUsageExceptions are intentional, so don't rollback if that's the case
915  $e,
916  MWExceptionHandler::CAUGHT_BY_ENTRYPOINT
917  );
918  }
919 
920  // Allow extra cleanup and logging
921  $this->getHookRunner()->onApiMain__onException( $this, $e );
922 
923  // Handle any kind of exception by outputting properly formatted error message.
924  // If this fails, an unhandled exception should be thrown so that global error
925  // handler will process and log it.
926 
927  $errCodes = $this->substituteResultWithError( $e );
928 
929  // Error results should not be cached
930  $this->setCacheMode( 'private' );
931 
932  $response = $this->getRequest()->response();
933  $headerStr = 'MediaWiki-API-Error: ' . implode( ', ', $errCodes );
934  $response->header( $headerStr );
935 
936  // Reset and print just the error message
937  ob_clean();
938 
939  // Printer may not be initialized if the extractRequestParams() fails for the main module
940  $this->createErrorPrinter();
941 
942  // Get desired HTTP code from an ApiUsageException. Don't use codes from other
943  // exception types, as they are unlikely to be intended as an HTTP code.
944  $httpCode = $e instanceof ApiUsageException ? $e->getCode() : 0;
945 
946  $failed = false;
947  try {
948  $this->printResult( $httpCode );
949  } catch ( ApiUsageException $ex ) {
950  // The error printer itself is failing. Try suppressing its request
951  // parameters and redo.
952  $failed = true;
953  $this->addWarning( 'apiwarn-errorprinterfailed' );
954  foreach ( $ex->getStatusValue()->getErrors() as $error ) {
955  try {
956  $this->mPrinter->addWarning( $error );
957  } catch ( Throwable $ex2 ) {
958  // WTF?
959  $this->addWarning( $error );
960  }
961  }
962  }
963  if ( $failed ) {
964  $this->mPrinter = null;
965  $this->createErrorPrinter();
966  $this->mPrinter->forceDefaultParams();
967  if ( $httpCode ) {
968  $response->statusHeader( 200 ); // Reset in case the fallback doesn't want a non-200
969  }
970  $this->printResult( $httpCode );
971  }
972  }
973 
984  public static function handleApiBeforeMainException( Throwable $e ) {
985  ob_start();
986 
987  try {
988  $main = new self( RequestContext::getMain(), false );
989  $main->handleException( $e );
990  $main->logRequest( 0, $e );
991  } catch ( Throwable $e2 ) {
992  // Nope, even that didn't work. Punt.
993  throw $e;
994  }
995 
996  // Reset cache headers
997  $main->sendCacheHeaders( true );
998 
999  ob_end_flush();
1000  }
1001 
1016  protected function handleCORS() {
1017  $originParam = $this->getParameter( 'origin' ); // defaults to null
1018  if ( $originParam === null ) {
1019  // No origin parameter, nothing to do
1020  return true;
1021  }
1022 
1023  $request = $this->getRequest();
1024  $response = $request->response();
1025 
1026  $allowTiming = false;
1027  $varyOrigin = true;
1028 
1029  if ( $originParam === '*' ) {
1030  // Request for anonymous CORS
1031  // Technically we should check for the presence of an Origin header
1032  // and not process it as CORS if it's not set, but that would
1033  // require us to vary on Origin for all 'origin=*' requests which
1034  // we don't want to do.
1035  $matchedOrigin = true;
1036  $allowOrigin = '*';
1037  $allowCredentials = 'false';
1038  $varyOrigin = false; // No need to vary
1039  } else {
1040  // Non-anonymous CORS, check we allow the domain
1041 
1042  // Origin: header is a space-separated list of origins, check all of them
1043  $originHeader = $request->getHeader( 'Origin' );
1044  if ( $originHeader === false ) {
1045  $origins = [];
1046  } else {
1047  $originHeader = trim( $originHeader );
1048  $origins = preg_split( '/\s+/', $originHeader );
1049  }
1050 
1051  if ( !in_array( $originParam, $origins ) ) {
1052  // origin parameter set but incorrect
1053  // Send a 403 response
1054  $response->statusHeader( 403 );
1055  $response->header( 'Cache-Control: no-cache' );
1056  echo "'origin' parameter does not match Origin header\n";
1057 
1058  return false;
1059  }
1060 
1061  $config = $this->getConfig();
1062  $origin = Origin::parseHeaderList( $origins );
1063  $matchedOrigin = $origin->match(
1064  $config->get( 'CrossSiteAJAXdomains' ),
1065  $config->get( 'CrossSiteAJAXdomainExceptions' )
1066  );
1067 
1068  $allowOrigin = $originHeader;
1069  $allowCredentials = 'true';
1070  $allowTiming = $originHeader;
1071  }
1072 
1073  if ( $matchedOrigin ) {
1074  $requestedMethod = $request->getHeader( 'Access-Control-Request-Method' );
1075  $preflight = $request->getMethod() === 'OPTIONS' && $requestedMethod !== false;
1076  if ( $preflight ) {
1077  // We allow the actual request to send the following headers
1078  $requestedHeaders = $request->getHeader( 'Access-Control-Request-Headers' );
1079  $allowedHeaders = $this->getConfig()->get( 'AllowedCorsHeaders' );
1080  if ( $requestedHeaders !== false ) {
1081  if ( !self::matchRequestedHeaders( $requestedHeaders, $allowedHeaders ) ) {
1082  $response->header( 'MediaWiki-CORS-Rejection: Unsupported header requested in preflight' );
1083  return true;
1084  }
1085  $response->header( 'Access-Control-Allow-Headers: ' . $requestedHeaders );
1086  }
1087 
1088  // We only allow the actual request to be GET, POST, or HEAD
1089  $response->header( 'Access-Control-Allow-Methods: POST, GET, HEAD' );
1090  }
1091 
1092  $response->header( "Access-Control-Allow-Origin: $allowOrigin" );
1093  $response->header( "Access-Control-Allow-Credentials: $allowCredentials" );
1094  // https://www.w3.org/TR/resource-timing/#timing-allow-origin
1095  if ( $allowTiming !== false ) {
1096  $response->header( "Timing-Allow-Origin: $allowTiming" );
1097  }
1098 
1099  if ( !$preflight ) {
1100  $response->header(
1101  'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag, '
1102  . 'MediaWiki-Login-Suppressed'
1103  );
1104  }
1105  } else {
1106  $response->header( 'MediaWiki-CORS-Rejection: Origin mismatch' );
1107  }
1108 
1109  if ( $varyOrigin ) {
1110  $this->getOutput()->addVaryHeader( 'Origin' );
1111  }
1112 
1113  return true;
1114  }
1115 
1124  protected static function matchRequestedHeaders( $requestedHeaders, $allowedHeaders ) {
1125  if ( trim( $requestedHeaders ) === '' ) {
1126  return true;
1127  }
1128  $requestedHeaders = explode( ',', $requestedHeaders );
1129  $allowedHeaders = array_change_key_case(
1130  array_fill_keys( $allowedHeaders, true ), CASE_LOWER );
1131  foreach ( $requestedHeaders as $rHeader ) {
1132  $rHeader = strtolower( trim( $rHeader ) );
1133  if ( !isset( $allowedHeaders[$rHeader] ) ) {
1134  LoggerFactory::getInstance( 'api-warning' )->warning(
1135  'CORS preflight failed on requested header: {header}', [
1136  'header' => $rHeader
1137  ]
1138  );
1139  return false;
1140  }
1141  }
1142  return true;
1143  }
1144 
1150  protected function sendCacheHeaders( $isError ) {
1151  $response = $this->getRequest()->response();
1152  $out = $this->getOutput();
1153 
1154  $out->addVaryHeader( 'Treat-as-Untrusted' );
1155 
1156  $config = $this->getConfig();
1157 
1158  if ( $config->get( 'VaryOnXFP' ) ) {
1159  $out->addVaryHeader( 'X-Forwarded-Proto' );
1160  }
1161 
1162  if ( !$isError && $this->mModule &&
1163  ( $this->getRequest()->getMethod() === 'GET' || $this->getRequest()->getMethod() === 'HEAD' )
1164  ) {
1165  $etag = $this->mModule->getConditionalRequestData( 'etag' );
1166  if ( $etag !== null ) {
1167  $response->header( "ETag: $etag" );
1168  }
1169  $lastMod = $this->mModule->getConditionalRequestData( 'last-modified' );
1170  if ( $lastMod !== null ) {
1171  $response->header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822, $lastMod ) );
1172  }
1173  }
1174 
1175  // The logic should be:
1176  // $this->mCacheControl['max-age'] is set?
1177  // Use it, the module knows better than our guess.
1178  // !$this->mModule || $this->mModule->isWriteMode(), and mCacheMode is private?
1179  // Use 0 because we can guess caching is probably the wrong thing to do.
1180  // Use $this->getParameter( 'maxage' ), which already defaults to 0.
1181  $maxage = 0;
1182  if ( isset( $this->mCacheControl['max-age'] ) ) {
1183  $maxage = $this->mCacheControl['max-age'];
1184  } elseif ( ( $this->mModule && !$this->mModule->isWriteMode() ) ||
1185  $this->mCacheMode !== 'private'
1186  ) {
1187  $maxage = $this->getParameter( 'maxage' );
1188  }
1189  $privateCache = 'private, must-revalidate, max-age=' . $maxage;
1190 
1191  if ( $this->mCacheMode == 'private' ) {
1192  $response->header( "Cache-Control: $privateCache" );
1193  return;
1194  }
1195 
1196  if ( $this->mCacheMode == 'anon-public-user-private' ) {
1197  $out->addVaryHeader( 'Cookie' );
1198  $response->header( $out->getVaryHeader() );
1199  if ( SessionManager::getGlobalSession()->isPersistent() ) {
1200  // Logged in or otherwise has session (e.g. anonymous users who have edited)
1201  // Mark request private
1202  $response->header( "Cache-Control: $privateCache" );
1203 
1204  return;
1205  } // else anonymous, send public headers below
1206  }
1207 
1208  // Send public headers
1209  $response->header( $out->getVaryHeader() );
1210 
1211  // If nobody called setCacheMaxAge(), use the (s)maxage parameters
1212  if ( !isset( $this->mCacheControl['s-maxage'] ) ) {
1213  $this->mCacheControl['s-maxage'] = $this->getParameter( 'smaxage' );
1214  }
1215  if ( !isset( $this->mCacheControl['max-age'] ) ) {
1216  $this->mCacheControl['max-age'] = $this->getParameter( 'maxage' );
1217  }
1218 
1219  if ( !$this->mCacheControl['s-maxage'] && !$this->mCacheControl['max-age'] ) {
1220  // Public cache not requested
1221  // Sending a Vary header in this case is harmless, and protects us
1222  // against conditional calls of setCacheMaxAge().
1223  $response->header( "Cache-Control: $privateCache" );
1224 
1225  return;
1226  }
1227 
1228  $this->mCacheControl['public'] = true;
1229 
1230  // Send an Expires header
1231  $maxAge = min( $this->mCacheControl['s-maxage'], $this->mCacheControl['max-age'] );
1232  $expiryUnixTime = ( $maxAge == 0 ? 1 : time() + $maxAge );
1233  $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822, $expiryUnixTime ) );
1234 
1235  // Construct the Cache-Control header
1236  $ccHeader = '';
1237  $separator = '';
1238  foreach ( $this->mCacheControl as $name => $value ) {
1239  if ( is_bool( $value ) ) {
1240  if ( $value ) {
1241  $ccHeader .= $separator . $name;
1242  $separator = ', ';
1243  }
1244  } else {
1245  $ccHeader .= $separator . "$name=$value";
1246  $separator = ', ';
1247  }
1248  }
1249 
1250  $response->header( "Cache-Control: $ccHeader" );
1251  }
1252 
1256  private function createErrorPrinter() {
1257  if ( !isset( $this->mPrinter ) ) {
1258  $value = $this->getRequest()->getVal( 'format', self::API_DEFAULT_FORMAT );
1259  if ( !$this->mModuleMgr->isDefined( $value, 'format' ) ) {
1260  $value = self::API_DEFAULT_FORMAT;
1261  }
1262  $this->mPrinter = $this->createPrinterByName( $value );
1263  }
1264 
1265  // Printer may not be able to handle errors. This is particularly
1266  // likely if the module returns something for getCustomPrinter().
1267  if ( !$this->mPrinter->canPrintErrors() ) {
1268  $this->mPrinter = $this->createPrinterByName( self::API_DEFAULT_FORMAT );
1269  }
1270  }
1271 
1287  protected function errorMessagesFromException( Throwable $e, $type = 'error' ) {
1288  $messages = [];
1289  if ( $e instanceof ApiUsageException ) {
1290  foreach ( $e->getStatusValue()->getErrorsByType( $type ) as $error ) {
1291  $messages[] = ApiMessage::create( $error );
1292  }
1293  } elseif ( $type !== 'error' ) {
1294  // None of the rest have any messages for non-error types
1295  } else {
1296  // Something is seriously wrong
1297  $config = $this->getConfig();
1298  // TODO: Avoid embedding arbitrary class names in the error code.
1299  $class = preg_replace( '#^Wikimedia\\\Rdbms\\\#', '', get_class( $e ) );
1300  $code = 'internal_api_error_' . $class;
1301  $data = [ 'errorclass' => get_class( $e ) ];
1302  if ( $config->get( 'ShowExceptionDetails' ) ) {
1303  if ( $e instanceof ILocalizedException ) {
1304  $msg = $e->getMessageObject();
1305  } elseif ( $e instanceof MessageSpecifier ) {
1306  $msg = Message::newFromSpecifier( $e );
1307  } else {
1308  $msg = wfEscapeWikiText( $e->getMessage() );
1309  }
1310  $params = [ 'apierror-exceptioncaught', WebRequest::getRequestId(), $msg ];
1311  } else {
1312  $params = [ 'apierror-exceptioncaughttype', WebRequest::getRequestId(), get_class( $e ) ];
1313  }
1314 
1315  $messages[] = ApiMessage::create( $params, $code, $data );
1316  }
1317  return $messages;
1318  }
1319 
1325  protected function substituteResultWithError( Throwable $e ) {
1326  $result = $this->getResult();
1327  $formatter = $this->getErrorFormatter();
1328  $config = $this->getConfig();
1329  $errorCodes = [];
1330 
1331  // Remember existing warnings and errors across the reset
1332  $errors = $result->getResultData( [ 'errors' ] );
1333  $warnings = $result->getResultData( [ 'warnings' ] );
1334  $result->reset();
1335  if ( $warnings !== null ) {
1336  $result->addValue( null, 'warnings', $warnings, ApiResult::NO_SIZE_CHECK );
1337  }
1338  if ( $errors !== null ) {
1339  $result->addValue( null, 'errors', $errors, ApiResult::NO_SIZE_CHECK );
1340 
1341  // Collect the copied error codes for the return value
1342  foreach ( $errors as $error ) {
1343  if ( isset( $error['code'] ) ) {
1344  $errorCodes[$error['code']] = true;
1345  }
1346  }
1347  }
1348 
1349  // Add errors from the exception
1350  $modulePath = $e instanceof ApiUsageException ? $e->getModulePath() : null;
1351  foreach ( $this->errorMessagesFromException( $e, 'error' ) as $msg ) {
1352  if ( ApiErrorFormatter::isValidApiCode( $msg->getApiCode() ) ) {
1353  $errorCodes[$msg->getApiCode()] = true;
1354  } else {
1355  LoggerFactory::getInstance( 'api-warning' )->error( 'Invalid API error code "{code}"', [
1356  'code' => $msg->getApiCode(),
1357  'exception' => $e,
1358  ] );
1359  $errorCodes['<invalid-code>'] = true;
1360  }
1361  $formatter->addError( $modulePath, $msg );
1362  }
1363  foreach ( $this->errorMessagesFromException( $e, 'warning' ) as $msg ) {
1364  $formatter->addWarning( $modulePath, $msg );
1365  }
1366 
1367  // Add additional data. Path depends on whether we're in BC mode or not.
1368  // Data depends on the type of exception.
1369  if ( $formatter instanceof ApiErrorFormatter_BackCompat ) {
1370  $path = [ 'error' ];
1371  } else {
1372  $path = null;
1373  }
1374  if ( $e instanceof ApiUsageException ) {
1375  $link = wfExpandUrl( wfScript( 'api' ) );
1376  $result->addContentValue(
1377  $path,
1378  'docref',
1379  trim(
1380  $this->msg( 'api-usage-docref', $link )->inLanguage( $formatter->getLanguage() )->text()
1381  . ' '
1382  . $this->msg( 'api-usage-mailinglist-ref' )->inLanguage( $formatter->getLanguage() )->text()
1383  )
1384  );
1385  } elseif ( $config->get( 'ShowExceptionDetails' ) ) {
1386  $result->addContentValue(
1387  $path,
1388  'trace',
1389  $this->msg( 'api-exception-trace',
1390  get_class( $e ),
1391  $e->getFile(),
1392  $e->getLine(),
1394  )->inLanguage( $formatter->getLanguage() )->text()
1395  );
1396  }
1397 
1398  // Add the id and such
1399  $this->addRequestedFields( [ 'servedby' ] );
1400 
1401  return array_keys( $errorCodes );
1402  }
1403 
1409  protected function addRequestedFields( $force = [] ) {
1410  $result = $this->getResult();
1411 
1412  $requestid = $this->getParameter( 'requestid' );
1413  if ( $requestid !== null ) {
1414  $result->addValue( null, 'requestid', $requestid, ApiResult::NO_SIZE_CHECK );
1415  }
1416 
1417  if ( $this->getConfig()->get( 'ShowHostnames' ) && (
1418  in_array( 'servedby', $force, true ) || $this->getParameter( 'servedby' )
1419  ) ) {
1420  $result->addValue( null, 'servedby', wfHostname(), ApiResult::NO_SIZE_CHECK );
1421  }
1422 
1423  if ( $this->getParameter( 'curtimestamp' ) ) {
1424  $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601 ), ApiResult::NO_SIZE_CHECK );
1425  }
1426 
1427  if ( $this->getParameter( 'responselanginfo' ) ) {
1428  $result->addValue(
1429  null,
1430  'uselang',
1431  $this->getLanguage()->getCode(),
1433  );
1434  $result->addValue(
1435  null,
1436  'errorlang',
1437  $this->getErrorFormatter()->getLanguage()->getCode(),
1439  );
1440  }
1441  }
1442 
1447  protected function setupExecuteAction() {
1448  $this->addRequestedFields();
1449 
1450  $params = $this->extractRequestParams();
1451  $this->mAction = $params['action'];
1452 
1453  return $params;
1454  }
1455 
1462  protected function setupModule() {
1463  // Instantiate the module requested by the user
1464  $module = $this->mModuleMgr->getModule( $this->mAction, 'action' );
1465  if ( $module === null ) {
1466  // Probably can't happen
1467  // @codeCoverageIgnoreStart
1468  $this->dieWithError(
1469  [ 'apierror-unknownaction', wfEscapeWikiText( $this->mAction ) ],
1470  'unknown_action'
1471  );
1472  // @codeCoverageIgnoreEnd
1473  }
1474  $moduleParams = $module->extractRequestParams();
1475 
1476  // Check token, if necessary
1477  if ( $module->needsToken() === true ) {
1478  throw new MWException(
1479  "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
1480  'See documentation for ApiBase::needsToken for details.'
1481  );
1482  }
1483  if ( $module->needsToken() ) {
1484  if ( !$module->mustBePosted() ) {
1485  throw new MWException(
1486  "Module '{$module->getModuleName()}' must require POST to use tokens."
1487  );
1488  }
1489 
1490  if ( !isset( $moduleParams['token'] ) ) {
1491  // Probably can't happen
1492  // @codeCoverageIgnoreStart
1493  $module->dieWithError( [ 'apierror-missingparam', 'token' ] );
1494  // @codeCoverageIgnoreEnd
1495  }
1496 
1497  $module->requirePostedParameters( [ 'token' ] );
1498 
1499  if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) {
1500  $module->dieWithError( 'apierror-badtoken' );
1501  }
1502  }
1503 
1504  return $module;
1505  }
1506 
1510  private function getMaxLag() {
1511  $dbLag = MediaWikiServices::getInstance()->getDBLoadBalancer()->getMaxLag();
1512  $lagInfo = [
1513  'host' => $dbLag[0],
1514  'lag' => $dbLag[1],
1515  'type' => 'db'
1516  ];
1517 
1518  $jobQueueLagFactor = $this->getConfig()->get( 'JobQueueIncludeInMaxLagFactor' );
1519  if ( $jobQueueLagFactor ) {
1520  // Turn total number of jobs into seconds by using the configured value
1521  $totalJobs = array_sum( JobQueueGroup::singleton()->getQueueSizes() );
1522  $jobQueueLag = $totalJobs / (float)$jobQueueLagFactor;
1523  if ( $jobQueueLag > $lagInfo['lag'] ) {
1524  $lagInfo = [
1525  'host' => wfHostname(), // XXX: Is there a better value that could be used?
1526  'lag' => $jobQueueLag,
1527  'type' => 'jobqueue',
1528  'jobs' => $totalJobs,
1529  ];
1530  }
1531  }
1532 
1533  $this->getHookRunner()->onApiMaxLagInfo( $lagInfo );
1534 
1535  return $lagInfo;
1536  }
1537 
1544  protected function checkMaxLag( $module, $params ) {
1545  if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
1546  $maxLag = $params['maxlag'];
1547  $lagInfo = $this->getMaxLag();
1548  if ( $lagInfo['lag'] > $maxLag ) {
1549  $response = $this->getRequest()->response();
1550 
1551  $response->header( 'Retry-After: ' . max( (int)$maxLag, 5 ) );
1552  $response->header( 'X-Database-Lag: ' . (int)$lagInfo['lag'] );
1553 
1554  if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
1555  $this->dieWithError(
1556  [ 'apierror-maxlag', $lagInfo['lag'], $lagInfo['host'] ],
1557  'maxlag',
1558  $lagInfo
1559  );
1560  }
1561 
1562  $this->dieWithError( [ 'apierror-maxlag-generic', $lagInfo['lag'] ], 'maxlag', $lagInfo );
1563  }
1564  }
1565 
1566  return true;
1567  }
1568 
1590  protected function checkConditionalRequestHeaders( $module ) {
1591  if ( $this->mInternalMode ) {
1592  // No headers to check in internal mode
1593  return true;
1594  }
1595 
1596  if ( $this->getRequest()->getMethod() !== 'GET' && $this->getRequest()->getMethod() !== 'HEAD' ) {
1597  // Don't check POSTs
1598  return true;
1599  }
1600 
1601  $return304 = false;
1602 
1603  $ifNoneMatch = array_diff(
1604  $this->getRequest()->getHeader( 'If-None-Match', WebRequest::GETHEADER_LIST ) ?: [],
1605  [ '' ]
1606  );
1607  if ( $ifNoneMatch ) {
1608  // @phan-suppress-next-line PhanImpossibleTypeComparison
1609  if ( $ifNoneMatch === [ '*' ] ) {
1610  // API responses always "exist"
1611  $etag = '*';
1612  } else {
1613  $etag = $module->getConditionalRequestData( 'etag' );
1614  }
1615  }
1616  if ( $ifNoneMatch && $etag !== null ) {
1617  $test = substr( $etag, 0, 2 ) === 'W/' ? substr( $etag, 2 ) : $etag;
1618  $match = array_map( static function ( $s ) {
1619  return substr( $s, 0, 2 ) === 'W/' ? substr( $s, 2 ) : $s;
1620  }, $ifNoneMatch );
1621  $return304 = in_array( $test, $match, true );
1622  } else {
1623  $value = trim( $this->getRequest()->getHeader( 'If-Modified-Since' ) );
1624 
1625  // Some old browsers sends sizes after the date, like this:
1626  // Wed, 20 Aug 2003 06:51:19 GMT; length=5202
1627  // Ignore that.
1628  $i = strpos( $value, ';' );
1629  if ( $i !== false ) {
1630  $value = trim( substr( $value, 0, $i ) );
1631  }
1632 
1633  if ( $value !== '' ) {
1634  try {
1635  $ts = new MWTimestamp( $value );
1636  if (
1637  // RFC 7231 IMF-fixdate
1638  $ts->getTimestamp( TS_RFC2822 ) === $value ||
1639  // RFC 850
1640  $ts->format( 'l, d-M-y H:i:s' ) . ' GMT' === $value ||
1641  // asctime (with and without space-padded day)
1642  $ts->format( 'D M j H:i:s Y' ) === $value ||
1643  $ts->format( 'D M j H:i:s Y' ) === $value
1644  ) {
1645  $config = $this->getConfig();
1646  $lastMod = $module->getConditionalRequestData( 'last-modified' );
1647  if ( $lastMod !== null ) {
1648  // Mix in some MediaWiki modification times
1649  $modifiedTimes = [
1650  'page' => $lastMod,
1651  'user' => $this->getUser()->getTouched(),
1652  'epoch' => $config->get( 'CacheEpoch' ),
1653  ];
1654 
1655  if ( $config->get( 'UseCdn' ) ) {
1656  // T46570: the core page itself may not change, but resources might
1657  $modifiedTimes['sepoch'] = wfTimestamp(
1658  TS_MW, time() - $config->get( 'CdnMaxAge' )
1659  );
1660  }
1661  $this->getHookRunner()->onOutputPageCheckLastModified( $modifiedTimes, $this->getOutput() );
1662  $lastMod = max( $modifiedTimes );
1663  $return304 = wfTimestamp( TS_MW, $lastMod ) <= $ts->getTimestamp( TS_MW );
1664  }
1665  }
1666  } catch ( TimestampException $e ) {
1667  // Invalid timestamp, ignore it
1668  }
1669  }
1670  }
1671 
1672  if ( $return304 ) {
1673  $this->getRequest()->response()->statusHeader( 304 );
1674 
1675  // Avoid outputting the compressed representation of a zero-length body
1676  Wikimedia\suppressWarnings();
1677  ini_set( 'zlib.output_compression', 0 );
1678  Wikimedia\restoreWarnings();
1679  wfResetOutputBuffers( false );
1680 
1681  return false;
1682  }
1683 
1684  return true;
1685  }
1686 
1691  protected function checkExecutePermissions( $module ) {
1692  $user = $this->getUser();
1693  if ( $module->isReadMode() && !$this->getPermissionManager()->isEveryoneAllowed( 'read' ) &&
1694  !$this->getAuthority()->isAllowed( 'read' )
1695  ) {
1696  $this->dieWithError( 'apierror-readapidenied' );
1697  }
1698 
1699  if ( $module->isWriteMode() ) {
1700  if ( !$this->mEnableWrite ) {
1701  $this->dieWithError( 'apierror-noapiwrite' );
1702  } elseif ( !$this->getAuthority()->isAllowed( 'writeapi' ) ) {
1703  $this->dieWithError( 'apierror-writeapidenied' );
1704  } elseif ( $this->getRequest()->getHeader( 'Promise-Non-Write-API-Action' ) ) {
1705  $this->dieWithError( 'apierror-promised-nonwrite-api' );
1706  }
1707 
1708  $this->checkReadOnly( $module );
1709  }
1710 
1711  // Allow extensions to stop execution for arbitrary reasons.
1712  // TODO: change hook to accept Authority
1713  $message = 'hookaborted';
1714  if ( !$this->getHookRunner()->onApiCheckCanExecute( $module, $user, $message ) ) {
1715  $this->dieWithError( $message );
1716  }
1717  }
1718 
1723  protected function checkReadOnly( $module ) {
1724  if ( MediaWikiServices::getInstance()->getReadOnlyMode()->isReadOnly() ) {
1725  $this->dieReadOnly();
1726  }
1727 
1728  if ( $module->isWriteMode()
1729  && $this->getUser()->isBot()
1730  && MediaWikiServices::getInstance()->getDBLoadBalancer()->getServerCount() > 1
1731  ) {
1732  $this->checkBotReadOnly();
1733  }
1734  }
1735 
1739  private function checkBotReadOnly() {
1740  // Figure out how many servers have passed the lag threshold
1741  $numLagged = 0;
1742  $lagLimit = $this->getConfig()->get( 'APIMaxLagThreshold' );
1743  $laggedServers = [];
1744  $loadBalancer = MediaWikiServices::getInstance()->getDBLoadBalancer();
1745  foreach ( $loadBalancer->getLagTimes() as $serverIndex => $lag ) {
1746  if ( $lag > $lagLimit ) {
1747  ++$numLagged;
1748  $laggedServers[] = $loadBalancer->getServerName( $serverIndex ) . " ({$lag}s)";
1749  }
1750  }
1751 
1752  // If a majority of replica DBs are too lagged then disallow writes
1753  $replicaCount = $loadBalancer->getServerCount() - 1;
1754  if ( $numLagged >= ceil( $replicaCount / 2 ) ) {
1755  $laggedServers = implode( ', ', $laggedServers );
1756  wfDebugLog(
1757  'api-readonly', // Deprecate this channel in favor of api-warning?
1758  "Api request failed as read only because the following DBs are lagged: $laggedServers"
1759  );
1760  LoggerFactory::getInstance( 'api-warning' )->warning(
1761  "Api request failed as read only because the following DBs are lagged: {laggeddbs}", [
1762  'laggeddbs' => $laggedServers,
1763  ]
1764  );
1765 
1766  $this->dieWithError(
1767  'readonly_lag',
1768  'readonly',
1769  [ 'readonlyreason' => "Waiting for $numLagged lagged database(s)" ]
1770  );
1771  }
1772  }
1773 
1778  protected function checkAsserts( $params ) {
1779  if ( isset( $params['assert'] ) ) {
1780  $user = $this->getUser();
1781  switch ( $params['assert'] ) {
1782  case 'anon':
1783  if ( $user->isRegistered() ) {
1784  $this->dieWithError( 'apierror-assertanonfailed' );
1785  }
1786  break;
1787  case 'user':
1788  if ( !$user->isRegistered() ) {
1789  $this->dieWithError( 'apierror-assertuserfailed' );
1790  }
1791  break;
1792  case 'bot':
1793  if ( !$this->getAuthority()->isAllowed( 'bot' ) ) {
1794  $this->dieWithError( 'apierror-assertbotfailed' );
1795  }
1796  break;
1797  }
1798  }
1799  if ( isset( $params['assertuser'] ) ) {
1800  // TODO inject stuff, see T265644
1801  $assertUser = MediaWikiServices::getInstance()->getUserFactory()
1802  ->newFromName( $params['assertuser'], UserFactory::RIGOR_NONE );
1803  if ( !$assertUser || !$this->getUser()->equals( $assertUser ) ) {
1804  $this->dieWithError(
1805  [ 'apierror-assertnameduserfailed', wfEscapeWikiText( $params['assertuser'] ) ]
1806  );
1807  }
1808  }
1809  }
1810 
1816  protected function setupExternalResponse( $module, $params ) {
1817  $validMethods = [ 'GET', 'HEAD', 'POST', 'OPTIONS' ];
1818  $request = $this->getRequest();
1819 
1820  if ( !in_array( $request->getMethod(), $validMethods ) ) {
1821  $this->dieWithError( 'apierror-invalidmethod', null, null, 405 );
1822  }
1823 
1824  if ( !$request->wasPosted() && $module->mustBePosted() ) {
1825  // Module requires POST. GET request might still be allowed
1826  // if $wgDebugApi is true, otherwise fail.
1827  $this->dieWithErrorOrDebug( [ 'apierror-mustbeposted', $this->mAction ] );
1828  }
1829 
1830  if ( $request->wasPosted() && !$request->getHeader( 'Content-Type' ) ) {
1831  $this->addDeprecation(
1832  'apiwarn-deprecation-post-without-content-type', 'post-without-content-type'
1833  );
1834  }
1835 
1836  // See if custom printer is used
1837  $this->mPrinter = $module->getCustomPrinter();
1838  if ( $this->mPrinter === null ) {
1839  // Create an appropriate printer
1840  $this->mPrinter = $this->createPrinterByName( $params['format'] );
1841  }
1842 
1843  if ( $request->getProtocol() === 'http' &&
1844  (
1845  $this->getConfig()->get( 'ForceHTTPS' ) ||
1846  $request->getSession()->shouldForceHTTPS() ||
1847  ( $this->getUser()->isRegistered() &&
1848  $this->getUser()->requiresHTTPS() )
1849  )
1850  ) {
1851  $this->addDeprecation( 'apiwarn-deprecation-httpsexpected', 'https-expected' );
1852  }
1853  }
1854 
1858  protected function executeAction() {
1859  $params = $this->setupExecuteAction();
1860 
1861  // Check asserts early so e.g. errors in parsing a module's parameters due to being
1862  // logged out don't override the client's intended "am I logged in?" check.
1863  $this->checkAsserts( $params );
1864 
1865  $module = $this->setupModule();
1866  $this->mModule = $module;
1867 
1868  if ( !$this->mInternalMode ) {
1869  $this->setRequestExpectations( $module );
1870  }
1871 
1872  $this->checkExecutePermissions( $module );
1873 
1874  if ( !$this->checkMaxLag( $module, $params ) ) {
1875  return;
1876  }
1877 
1878  if ( !$this->checkConditionalRequestHeaders( $module ) ) {
1879  return;
1880  }
1881 
1882  if ( !$this->mInternalMode ) {
1883  $this->setupExternalResponse( $module, $params );
1884  }
1885 
1886  $module->execute();
1887  $this->getHookRunner()->onAPIAfterExecute( $module );
1888 
1889  $this->reportUnusedParams();
1890 
1891  if ( !$this->mInternalMode ) {
1893 
1894  $this->printResult();
1895  }
1896  }
1897 
1902  protected function setRequestExpectations( ApiBase $module ) {
1903  $limits = $this->getConfig()->get( 'TrxProfilerLimits' );
1904  $trxProfiler = Profiler::instance()->getTransactionProfiler();
1905  $trxProfiler->setLogger( LoggerFactory::getInstance( 'DBPerformance' ) );
1906  if ( $this->getRequest()->hasSafeMethod() ) {
1907  $trxProfiler->setExpectations( $limits['GET'], __METHOD__ );
1908  } elseif ( $this->getRequest()->wasPosted() && !$module->isWriteMode() ) {
1909  $trxProfiler->setExpectations( $limits['POST-nonwrite'], __METHOD__ );
1910  $this->getRequest()->markAsSafeRequest();
1911  } else {
1912  $trxProfiler->setExpectations( $limits['POST'], __METHOD__ );
1913  }
1914  }
1915 
1921  protected function logRequest( $time, Throwable $e = null ) {
1922  $request = $this->getRequest();
1923 
1924  $user = $this->getUser();
1925  $performer = [
1926  'user_text' => $user->getName(),
1927  ];
1928  if ( $user->isRegistered() ) {
1929  $performer['user_id'] = $user->getId();
1930  }
1931  $logCtx = [
1932  // https://gerrit.wikimedia.org/g/mediawiki/event-schemas/+/master/jsonschema/mediawiki/api/request
1933  '$schema' => '/mediawiki/api/request/1.0.0',
1934  'meta' => [
1935  'request_id' => WebRequest::getRequestId(),
1936  'id' => MediaWikiServices::getInstance()
1937  ->getGlobalIdGenerator()->newUUIDv4(),
1938  'dt' => wfTimestamp( TS_ISO_8601 ),
1939  'domain' => $this->getConfig()->get( 'ServerName' ),
1940  // If using the EventBus extension (as intended) with this log channel,
1941  // this stream name will map to a Kafka topic.
1942  'stream' => 'mediawiki.api-request'
1943  ],
1944  'http' => [
1945  'method' => $request->getMethod(),
1946  'client_ip' => $request->getIP()
1947  ],
1948  'performer' => $performer,
1949  'database' => WikiMap::getCurrentWikiDbDomain()->getId(),
1950  'backend_time_ms' => (int)round( $time * 1000 ),
1951  ];
1952 
1953  // If set, these headers will be logged in http.request_headers.
1954  $httpRequestHeadersToLog = [ 'accept-language', 'referer', 'user-agent' ];
1955  foreach ( $httpRequestHeadersToLog as $header ) {
1956  if ( $request->getHeader( $header ) ) {
1957  // Set the header in http.request_headers
1958  $logCtx['http']['request_headers'][$header] = $request->getHeader( $header );
1959  }
1960  }
1961 
1962  if ( $e ) {
1963  $logCtx['api_error_codes'] = [];
1964  foreach ( $this->errorMessagesFromException( $e ) as $msg ) {
1965  $logCtx['api_error_codes'][] = $msg->getApiCode();
1966  }
1967  }
1968 
1969  // Construct space separated message for 'api' log channel
1970  $msg = "API {$request->getMethod()} " .
1971  wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
1972  " {$logCtx['http']['client_ip']} " .
1973  "T={$logCtx['backend_time_ms']}ms";
1974 
1975  $sensitive = array_fill_keys( $this->getSensitiveParams(), true );
1976  foreach ( $this->getParamsUsed() as $name ) {
1977  $value = $request->getVal( $name );
1978  if ( $value === null ) {
1979  continue;
1980  }
1981 
1982  if ( isset( $sensitive[$name] ) ) {
1983  $value = '[redacted]';
1984  $encValue = '[redacted]';
1985  } elseif ( strlen( $value ) > 256 ) {
1986  $value = substr( $value, 0, 256 );
1987  $encValue = $this->encodeRequestLogValue( $value ) . '[...]';
1988  } else {
1989  $encValue = $this->encodeRequestLogValue( $value );
1990  }
1991 
1992  $logCtx['params'][$name] = $value;
1993  $msg .= " {$name}={$encValue}";
1994  }
1995 
1996  // Log an unstructured message to the api channel.
1997  wfDebugLog( 'api', $msg, 'private' );
1998 
1999  // The api-request channel a structured data log channel.
2000  wfDebugLog( 'api-request', '', 'private', $logCtx );
2001  }
2002 
2008  protected function encodeRequestLogValue( $s ) {
2009  static $table = [];
2010  if ( !$table ) {
2011  $chars = ';@$!*(),/:';
2012  $numChars = strlen( $chars );
2013  for ( $i = 0; $i < $numChars; $i++ ) {
2014  $table[rawurlencode( $chars[$i] )] = $chars[$i];
2015  }
2016  }
2017 
2018  return strtr( rawurlencode( $s ), $table );
2019  }
2020 
2025  protected function getParamsUsed() {
2026  return array_keys( $this->mParamsUsed );
2027  }
2028 
2033  public function markParamsUsed( $params ) {
2034  $this->mParamsUsed += array_fill_keys( (array)$params, true );
2035  }
2036 
2042  protected function getSensitiveParams() {
2043  return array_keys( $this->mParamsSensitive );
2044  }
2045 
2055  public function markParamsSensitive( $params ) {
2056  $this->mParamsSensitive += array_fill_keys( (array)$params, true );
2057  }
2058 
2065  public function getVal( $name, $default = null ) {
2066  $this->mParamsUsed[$name] = true;
2067 
2068  $ret = $this->getRequest()->getVal( $name );
2069  if ( $ret === null ) {
2070  if ( $this->getRequest()->getArray( $name ) !== null ) {
2071  // See T12262 for why we don't just implode( '|', ... ) the
2072  // array.
2073  $this->addWarning( [ 'apiwarn-unsupportedarray', $name ] );
2074  }
2075  $ret = $default;
2076  }
2077  return $ret;
2078  }
2079 
2086  public function getCheck( $name ) {
2087  $this->mParamsUsed[$name] = true;
2088  return $this->getRequest()->getCheck( $name );
2089  }
2090 
2098  public function getUpload( $name ) {
2099  $this->mParamsUsed[$name] = true;
2100 
2101  return $this->getRequest()->getUpload( $name );
2102  }
2103 
2108  protected function reportUnusedParams() {
2109  $paramsUsed = $this->getParamsUsed();
2110  $allParams = $this->getRequest()->getValueNames();
2111 
2112  if ( !$this->mInternalMode ) {
2113  // Printer has not yet executed; don't warn that its parameters are unused
2114  $printerParams = $this->mPrinter->encodeParamName(
2115  array_keys( $this->mPrinter->getFinalParams() ?: [] )
2116  );
2117  $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
2118  } else {
2119  $unusedParams = array_diff( $allParams, $paramsUsed );
2120  }
2121 
2122  if ( count( $unusedParams ) ) {
2123  $this->addWarning( [
2124  'apierror-unrecognizedparams',
2125  Message::listParam( array_map( 'wfEscapeWikiText', $unusedParams ), 'comma' ),
2126  count( $unusedParams )
2127  ] );
2128  }
2129  }
2130 
2136  protected function printResult( $httpCode = 0 ) {
2137  if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
2138  $this->addWarning( 'apiwarn-wgdebugapi' );
2139  }
2140 
2141  $printer = $this->mPrinter;
2142  $printer->initPrinter( false );
2143  if ( $httpCode ) {
2144  $printer->setHttpStatus( $httpCode );
2145  }
2146  $printer->execute();
2147  $printer->closePrinter();
2148  }
2149 
2153  public function isReadMode() {
2154  return false;
2155  }
2156 
2162  public function getAllowedParams() {
2163  return [
2164  'action' => [
2165  ApiBase::PARAM_DFLT => 'help',
2166  ApiBase::PARAM_TYPE => 'submodule',
2167  ],
2168  'format' => [
2170  ApiBase::PARAM_TYPE => 'submodule',
2171  ],
2172  'maxlag' => [
2173  ApiBase::PARAM_TYPE => 'integer'
2174  ],
2175  'smaxage' => [
2176  ApiBase::PARAM_TYPE => 'integer',
2177  ApiBase::PARAM_DFLT => 0
2178  ],
2179  'maxage' => [
2180  ApiBase::PARAM_TYPE => 'integer',
2181  ApiBase::PARAM_DFLT => 0
2182  ],
2183  'assert' => [
2184  ApiBase::PARAM_TYPE => [ 'anon', 'user', 'bot' ]
2185  ],
2186  'assertuser' => [
2187  ApiBase::PARAM_TYPE => 'user',
2188  UserDef::PARAM_ALLOWED_USER_TYPES => [ 'name' ],
2189  ],
2190  'requestid' => null,
2191  'servedby' => false,
2192  'curtimestamp' => false,
2193  'responselanginfo' => false,
2194  'origin' => null,
2195  'uselang' => [
2197  ],
2198  'errorformat' => [
2199  ApiBase::PARAM_TYPE => [ 'plaintext', 'wikitext', 'html', 'raw', 'none', 'bc' ],
2200  ApiBase::PARAM_DFLT => 'bc',
2202  ],
2203  'errorlang' => [
2204  ApiBase::PARAM_DFLT => 'uselang',
2205  ],
2206  'errorsuselocal' => [
2207  ApiBase::PARAM_DFLT => false,
2208  ],
2209  ];
2210  }
2211 
2213  protected function getExamplesMessages() {
2214  return [
2215  'action=help'
2216  => 'apihelp-help-example-main',
2217  'action=help&recursivesubmodules=1'
2218  => 'apihelp-help-example-recursive',
2219  ];
2220  }
2221 
2226  public function modifyHelp( array &$help, array $options, array &$tocData ) {
2227  // Wish PHP had an "array_insert_before". Instead, we have to manually
2228  // reindex the array to get 'permissions' in the right place.
2229  $oldHelp = $help;
2230  $help = [];
2231  foreach ( $oldHelp as $k => $v ) {
2232  if ( $k === 'submodules' ) {
2233  $help['permissions'] = '';
2234  }
2235  $help[$k] = $v;
2236  }
2237  $help['datatypes'] = '';
2238  $help['templatedparams'] = '';
2239  $help['credits'] = '';
2240 
2241  // Fill 'permissions'
2242  $help['permissions'] .= Html::openElement( 'div',
2243  [ 'class' => 'apihelp-block apihelp-permissions' ] );
2244  $m = $this->msg( 'api-help-permissions' );
2245  if ( !$m->isDisabled() ) {
2246  $help['permissions'] .= Html::rawElement( 'div', [ 'class' => 'apihelp-block-head' ],
2247  $m->numParams( count( self::RIGHTS_MAP ) )->parse()
2248  );
2249  }
2250  $help['permissions'] .= Html::openElement( 'dl' );
2251  // TODO inject stuff, see T265644
2252  $groupPermissionsLookup = MediaWikiServices::getInstance()->getGroupPermissionsLookup();
2253  foreach ( self::RIGHTS_MAP as $right => $rightMsg ) {
2254  $help['permissions'] .= Html::element( 'dt', [], $right );
2255 
2256  $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse();
2257  $help['permissions'] .= Html::rawElement( 'dd', [], $rightMsg );
2258 
2259  $groups = array_map( static function ( $group ) {
2260  return $group == '*' ? 'all' : $group;
2261  }, $groupPermissionsLookup->getGroupsWithPermission( $right ) );
2262 
2263  $help['permissions'] .= Html::rawElement( 'dd', [],
2264  $this->msg( 'api-help-permissions-granted-to' )
2265  ->numParams( count( $groups ) )
2266  ->params( Message::listParam( $groups ) )
2267  ->parse()
2268  );
2269  }
2270  $help['permissions'] .= Html::closeElement( 'dl' );
2271  $help['permissions'] .= Html::closeElement( 'div' );
2272 
2273  // Fill 'datatypes', 'templatedparams', and 'credits', if applicable
2274  if ( empty( $options['nolead'] ) ) {
2275  $level = $options['headerlevel'];
2276  $tocnumber = &$options['tocnumber'];
2277 
2278  $header = $this->msg( 'api-help-datatypes-header' )->parse();
2279 
2280  $id = Sanitizer::escapeIdForAttribute( 'main/datatypes', Sanitizer::ID_PRIMARY );
2281  $idFallback = Sanitizer::escapeIdForAttribute( 'main/datatypes', Sanitizer::ID_FALLBACK );
2282  $headline = Linker::makeHeadline( min( 6, $level ),
2283  ' class="apihelp-header">',
2284  $id,
2285  $header,
2286  '',
2287  $idFallback
2288  );
2289  // Ensure we have a sane anchor
2290  if ( $id !== 'main/datatypes' && $idFallback !== 'main/datatypes' ) {
2291  $headline = '<div id="main/datatypes"></div>' . $headline;
2292  }
2293  $help['datatypes'] .= $headline;
2294  $help['datatypes'] .= $this->msg( 'api-help-datatypes-top' )->parseAsBlock();
2295  $help['datatypes'] .= '<dl>';
2296  foreach ( $this->getParamValidator()->knownTypes() as $type ) {
2297  $m = $this->msg( "api-help-datatype-$type" );
2298  if ( !$m->isDisabled() ) {
2299  $id = "main/datatype/$type";
2300  $help['datatypes'] .= '<dt id="' . htmlspecialchars( $id ) . '">';
2302  if ( $encId !== $id ) {
2303  $help['datatypes'] .= '<span id="' . htmlspecialchars( $encId ) . '"></span>';
2304  }
2306  if ( $encId2 !== $id && $encId2 !== $encId ) {
2307  $help['datatypes'] .= '<span id="' . htmlspecialchars( $encId2 ) . '"></span>';
2308  }
2309  $help['datatypes'] .= htmlspecialchars( $type ) . '</dt><dd>' . $m->parseAsBlock() . "</dd>";
2310  }
2311  }
2312  $help['datatypes'] .= '</dl>';
2313  if ( !isset( $tocData['main/datatypes'] ) ) {
2314  $tocnumber[$level]++;
2315  $tocData['main/datatypes'] = [
2316  'toclevel' => count( $tocnumber ),
2317  'level' => $level,
2318  'anchor' => 'main/datatypes',
2319  'line' => $header,
2320  'number' => implode( '.', $tocnumber ),
2321  'index' => false,
2322  ];
2323  }
2324 
2325  $header = $this->msg( 'api-help-templatedparams-header' )->parse();
2326 
2327  $id = Sanitizer::escapeIdForAttribute( 'main/templatedparams', Sanitizer::ID_PRIMARY );
2328  $idFallback = Sanitizer::escapeIdForAttribute( 'main/templatedparams', Sanitizer::ID_FALLBACK );
2329  $headline = Linker::makeHeadline( min( 6, $level ),
2330  ' class="apihelp-header">',
2331  $id,
2332  $header,
2333  '',
2334  $idFallback
2335  );
2336  // Ensure we have a sane anchor
2337  if ( $id !== 'main/templatedparams' && $idFallback !== 'main/templatedparams' ) {
2338  $headline = '<div id="main/templatedparams"></div>' . $headline;
2339  }
2340  $help['templatedparams'] .= $headline;
2341  $help['templatedparams'] .= $this->msg( 'api-help-templatedparams' )->parseAsBlock();
2342  if ( !isset( $tocData['main/templatedparams'] ) ) {
2343  $tocnumber[$level]++;
2344  $tocData['main/templatedparams'] = [
2345  'toclevel' => count( $tocnumber ),
2346  'level' => $level,
2347  'anchor' => 'main/templatedparams',
2348  'line' => $header,
2349  'number' => implode( '.', $tocnumber ),
2350  'index' => false,
2351  ];
2352  }
2353 
2354  $header = $this->msg( 'api-credits-header' )->parse();
2355  $id = Sanitizer::escapeIdForAttribute( 'main/credits', Sanitizer::ID_PRIMARY );
2356  $idFallback = Sanitizer::escapeIdForAttribute( 'main/credits', Sanitizer::ID_FALLBACK );
2357  $headline = Linker::makeHeadline( min( 6, $level ),
2358  ' class="apihelp-header">',
2359  $id,
2360  $header,
2361  '',
2362  $idFallback
2363  );
2364  // Ensure we have a sane anchor
2365  if ( $id !== 'main/credits' && $idFallback !== 'main/credits' ) {
2366  $headline = '<div id="main/credits"></div>' . $headline;
2367  }
2368  $help['credits'] .= $headline;
2369  $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
2370  if ( !isset( $tocData['main/credits'] ) ) {
2371  $tocnumber[$level]++;
2372  $tocData['main/credits'] = [
2373  'toclevel' => count( $tocnumber ),
2374  'level' => $level,
2375  'anchor' => 'main/credits',
2376  'line' => $header,
2377  'number' => implode( '.', $tocnumber ),
2378  'index' => false,
2379  ];
2380  }
2381  }
2382  }
2383 
2384  private $mCanApiHighLimits = null;
2385 
2390  public function canApiHighLimits() {
2391  if ( !isset( $this->mCanApiHighLimits ) ) {
2392  $this->mCanApiHighLimits = $this->getAuthority()->isAllowed( 'apihighlimits' );
2393  }
2394 
2395  return $this->mCanApiHighLimits;
2396  }
2397 
2402  public function getModuleManager() {
2403  return $this->mModuleMgr;
2404  }
2405 
2414  public function getUserAgent() {
2415  return trim(
2416  $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
2417  $this->getRequest()->getHeader( 'User-agent' )
2418  );
2419  }
2420 }
2421 
ApiUsageException\getStatusValue
getStatusValue()
Fetch the error status.
Definition: ApiUsageException.php:107
ApiMain\$mModuleMgr
ApiModuleManager $mModuleMgr
Definition: ApiMain.php:465
ApiMain\executeActionWithErrorHandling
executeActionWithErrorHandling()
Execute an action, and in case of an error, erase whatever partial results have been accumulated,...
Definition: ApiMain.php:844
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:398
FauxRequest
WebRequest clone which takes values from a provided array.
Definition: FauxRequest.php:35
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:1596
ApiMain\substituteResultWithError
substituteResultWithError(Throwable $e)
Replace the result data with the information about a throwable.
Definition: ApiMain.php:1325
ApiMain\checkReadOnly
checkReadOnly( $module)
Check if the DB is read-only for this user.
Definition: ApiMain.php:1723
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 sane.
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:2025
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:1256
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:200
ApiMain\getErrorFormatter
getErrorFormatter()
Get the ApiErrorFormatter object associated with current request.
Definition: ApiMain.php:678
ApiMain\getVal
getVal( $name, $default=null)
Get a request value, and register the fact that it was used, for logging.
Definition: ApiMain.php:2065
ApiMain\errorMessagesFromException
errorMessagesFromException(Throwable $e, $type='error')
Create an error message for the given throwable.
Definition: ApiMain.php:1287
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:812
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:483
ApiMain\sendCacheHeaders
sendCacheHeaders( $isError)
Send caching headers.
Definition: ApiMain.php:1150
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1657
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:910
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:2153
ApiMain\handleCORS
handleCORS()
Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
Definition: ApiMain.php:1016
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:1590
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:642
wfHostname
wfHostname()
Get host name of the current machine, for use in error reporting.
Definition: GlobalFunctions.php:1238
ApiMain\getParamValidator
getParamValidator()
Get the parameter validator.
Definition: ApiMain.php:706
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:495
ApiMain\encodeRequestLogValue
encodeRequestLogValue( $s)
Encode a value in a format suitable for a space-separated log line.
Definition: ApiMain.php:2008
ApiMain\$mResult
ApiResult $mResult
Definition: ApiMain.php:468
ContextSource\getUser
getUser()
Definition: ContextSource.php:136
ApiMain\getMaxLag
getMaxLag()
Definition: ApiMain.php:1510
ApiMain\$mContinuationManager
ApiContinuationManager null $mContinuationManager
Definition: ApiMain.php:477
$wgLang
$wgLang
Definition: Setup.php:834
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:950
Message\listParam
static listParam(array $list, $type='text')
Definition: Message.php:1227
ApiMain\FORMATS
const FORMATS
List of available formats: format name => format class.
Definition: ApiMain.php:417
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:471
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:1124
Html\closeElement
static closeElement( $element)
Returns "</$element>".
Definition: Html.php:316
ApiMain\getModule
getModule()
Get the API module object.
Definition: ApiMain.php:715
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:2033
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:1447
wfScript
wfScript( $script='index')
Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScri...
Definition: GlobalFunctions.php:2274
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:504
ApiMain\$mParamsSensitive
array $mParamsSensitive
Definition: ApiMain.php:501
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:1698
ApiMain\getResult
getResult()
Get the ApiResult object associated with current request.
Definition: ApiMain.php:634
ApiMain\getSensitiveParams
getSensitiveParams()
Get the request parameters that should be considered sensitive.
Definition: ApiMain.php:2042
ApiMain\$mPrinter
ApiFormatBase null $mPrinter
Definition: ApiMain.php:462
ApiMain\checkMaxLag
checkMaxLag( $module, $params)
Check the max lag if necessary.
Definition: ApiMain.php:1544
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:2213
ApiMain\setCacheControl
setCacheControl( $directives)
Set directives (key/value pairs) for the Cache-Control header.
Definition: ApiMain.php:806
ApiMain\getAllowedParams
getAllowedParams()
See ApiBase for description.
Definition: ApiMain.php:2162
ApiMain\setupExternalResponse
setupExternalResponse( $module, $params)
Check POST for external response and setup result printer.
Definition: ApiMain.php:1816
ApiMain\createPrinterByName
createPrinterByName( $format)
Create an instance of an output formatter by its name.
Definition: ApiMain.php:817
ApiMain\getModuleManager
getModuleManager()
Overrides to return this instance's module manager.
Definition: ApiMain.php:2402
ApiMain\$mCanApiHighLimits
$mCanApiHighLimits
Definition: ApiMain.php:2384
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:886
ApiMain\addRequestedFields
addRequestedFields( $force=[])
Add requested fields to the result.
Definition: ApiMain.php:1409
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:2390
ApiMain\checkBotReadOnly
checkBotReadOnly()
Check whether we are readonly for bots.
Definition: ApiMain.php:1739
ApiMain\getContinuationManager
getContinuationManager()
Definition: ApiMain.php:685
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:450
ApiMain\checkAsserts
checkAsserts( $params)
Check asserts of the user's rights.
Definition: ApiMain.php:1778
MWDebug\appendDebugInfoToApiResult
static appendDebugInfoToApiResult(IContextSource $context, ApiResult $result)
Append the debug info to given ApiResult.
Definition: MWDebug.php:669
$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:692
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:668
ApiMain\checkExecutePermissions
checkExecutePermissions( $module)
Check for sufficient permissions to execute.
Definition: ApiMain.php:1691
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:514
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:2108
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:832
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:1448
ApiMain\$mInternalMode
bool $mInternalMode
Definition: ApiMain.php:486
ApiMain\markParamsSensitive
markParamsSensitive( $params)
Mark parameters as sensitive.
Definition: ApiMain.php:2055
ApiMain\setRequestExpectations
setRequestExpectations(ApiBase $module)
Set database connection, query, and write expectations given this module request.
Definition: ApiMain.php:1902
ApiMain\$mParamValidator
ApiParamValidator $mParamValidator
Definition: ApiMain.php:474
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:1921
ApiMain\getCheck
getCheck( $name)
Get a boolean request value, and register the fact that the parameter was used, for logging.
Definition: ApiMain.php:2086
ApiMain\printResult
printResult( $httpCode=0)
Print results using the current printer.
Definition: ApiMain.php:2136
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:984
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:2098
ApiMain\$mAction
string null $mAction
Definition: ApiMain.php:480
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:2226
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:252
Html\rawElement
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
Definition: Html.php:210
ApiMain\executeAction
executeAction()
Execute the actual module, without any error handling.
Definition: ApiMain.php:1858
ApiMain\setupModule
setupModule()
Set up the module for response.
Definition: ApiMain.php:1462
$help
$help
Definition: mcc.php:32
ApiMain\$mCacheMode
string $mCacheMode
Definition: ApiMain.php:492
$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:232
ApiMain\isInternalMode
isInternalMode()
Return true if the API was started by other PHP code using FauxRequest.
Definition: ApiMain.php:625
ApiMain\getUserAgent
getUserAgent()
Fetches the user agent used for this request.
Definition: ApiMain.php:2414
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:733
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:68
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:765
MediaWiki\User\UserFactory
Creates User objects.
Definition: UserFactory.php:41
ApiMain\getPrinter
getPrinter()
Get the result formatter object.
Definition: ApiMain.php:724
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:498
$type
$type
Definition: testCompression.php:52
ApiMain\$mModule
ApiBase $mModule
Definition: ApiMain.php:489