MediaWiki  1.29.2
ApiMain.php
Go to the documentation of this file.
1 <?php
28 use Wikimedia\Timestamp\TimestampException;
31 
45 class ApiMain extends ApiBase {
49  const API_DEFAULT_FORMAT = 'jsonfm';
50 
54  const API_DEFAULT_USELANG = 'user';
55 
59  private static $Modules = [
60  'login' => 'ApiLogin',
61  'clientlogin' => 'ApiClientLogin',
62  'logout' => 'ApiLogout',
63  'createaccount' => 'ApiAMCreateAccount',
64  'linkaccount' => 'ApiLinkAccount',
65  'unlinkaccount' => 'ApiRemoveAuthenticationData',
66  'changeauthenticationdata' => 'ApiChangeAuthenticationData',
67  'removeauthenticationdata' => 'ApiRemoveAuthenticationData',
68  'resetpassword' => 'ApiResetPassword',
69  'query' => 'ApiQuery',
70  'expandtemplates' => 'ApiExpandTemplates',
71  'parse' => 'ApiParse',
72  'stashedit' => 'ApiStashEdit',
73  'opensearch' => 'ApiOpenSearch',
74  'feedcontributions' => 'ApiFeedContributions',
75  'feedrecentchanges' => 'ApiFeedRecentChanges',
76  'feedwatchlist' => 'ApiFeedWatchlist',
77  'help' => 'ApiHelp',
78  'paraminfo' => 'ApiParamInfo',
79  'rsd' => 'ApiRsd',
80  'compare' => 'ApiComparePages',
81  'tokens' => 'ApiTokens',
82  'checktoken' => 'ApiCheckToken',
83  'cspreport' => 'ApiCSPReport',
84  'validatepassword' => 'ApiValidatePassword',
85 
86  // Write modules
87  'purge' => 'ApiPurge',
88  'setnotificationtimestamp' => 'ApiSetNotificationTimestamp',
89  'rollback' => 'ApiRollback',
90  'delete' => 'ApiDelete',
91  'undelete' => 'ApiUndelete',
92  'protect' => 'ApiProtect',
93  'block' => 'ApiBlock',
94  'unblock' => 'ApiUnblock',
95  'move' => 'ApiMove',
96  'edit' => 'ApiEditPage',
97  'upload' => 'ApiUpload',
98  'filerevert' => 'ApiFileRevert',
99  'emailuser' => 'ApiEmailUser',
100  'watch' => 'ApiWatch',
101  'patrol' => 'ApiPatrol',
102  'import' => 'ApiImport',
103  'clearhasmsg' => 'ApiClearHasMsg',
104  'userrights' => 'ApiUserrights',
105  'options' => 'ApiOptions',
106  'imagerotate' => 'ApiImageRotate',
107  'revisiondelete' => 'ApiRevisionDelete',
108  'managetags' => 'ApiManageTags',
109  'tag' => 'ApiTag',
110  'mergehistory' => 'ApiMergeHistory',
111  'setpagelanguage' => 'ApiSetPageLanguage',
112  ];
113 
117  private static $Formats = [
118  'json' => 'ApiFormatJson',
119  'jsonfm' => 'ApiFormatJson',
120  'php' => 'ApiFormatPhp',
121  'phpfm' => 'ApiFormatPhp',
122  'xml' => 'ApiFormatXml',
123  'xmlfm' => 'ApiFormatXml',
124  'rawfm' => 'ApiFormatJson',
125  'none' => 'ApiFormatNone',
126  ];
127 
128  // @codingStandardsIgnoreStart String contenation on "msg" not allowed to break long line
135  private static $mRights = [
136  'writeapi' => [
137  'msg' => 'right-writeapi',
138  'params' => []
139  ],
140  'apihighlimits' => [
141  'msg' => 'api-help-right-apihighlimits',
143  ]
144  ];
145  // @codingStandardsIgnoreEnd
146 
150  private $mPrinter;
151 
155  private $mAction;
156  private $mEnableWrite;
159  private $mModule;
160 
161  private $mCacheMode = 'private';
162  private $mCacheControl = [];
163  private $mParamsUsed = [];
164  private $mParamsSensitive = [];
165 
167  private $lacksSameOriginSecurity = null;
168 
176  public function __construct( $context = null, $enableWrite = false ) {
177  if ( $context === null ) {
179  } elseif ( $context instanceof WebRequest ) {
180  // BC for pre-1.19
181  $request = $context;
183  }
184  // We set a derivative context so we can change stuff later
185  $this->setContext( new DerivativeContext( $context ) );
186 
187  if ( isset( $request ) ) {
188  $this->getContext()->setRequest( $request );
189  } else {
190  $request = $this->getRequest();
191  }
192 
193  $this->mInternalMode = ( $request instanceof FauxRequest );
194 
195  // Special handling for the main module: $parent === $this
196  parent::__construct( $this, $this->mInternalMode ? 'main_int' : 'main' );
197 
198  $config = $this->getConfig();
199 
200  if ( !$this->mInternalMode ) {
201  // Log if a request with a non-whitelisted Origin header is seen
202  // with session cookies.
203  $originHeader = $request->getHeader( 'Origin' );
204  if ( $originHeader === false ) {
205  $origins = [];
206  } else {
207  $originHeader = trim( $originHeader );
208  $origins = preg_split( '/\s+/', $originHeader );
209  }
210  $sessionCookies = array_intersect(
211  array_keys( $_COOKIE ),
212  MediaWiki\Session\SessionManager::singleton()->getVaryCookies()
213  );
214  if ( $origins && $sessionCookies && (
215  count( $origins ) !== 1 || !self::matchOrigin(
216  $origins[0],
217  $config->get( 'CrossSiteAJAXdomains' ),
218  $config->get( 'CrossSiteAJAXdomainExceptions' )
219  )
220  ) ) {
221  LoggerFactory::getInstance( 'cors' )->warning(
222  'Non-whitelisted CORS request with session cookies', [
223  'origin' => $originHeader,
224  'cookies' => $sessionCookies,
225  'ip' => $request->getIP(),
226  'userAgent' => $this->getUserAgent(),
227  'wiki' => wfWikiID(),
228  ]
229  );
230  }
231 
232  // If we're in a mode that breaks the same-origin policy, strip
233  // user credentials for security.
234  if ( $this->lacksSameOriginSecurity() ) {
235  global $wgUser;
236  wfDebug( "API: stripping user credentials when the same-origin policy is not applied\n" );
237  $wgUser = new User();
238  $this->getContext()->setUser( $wgUser );
239  }
240  }
241 
242  $this->mResult = new ApiResult( $this->getConfig()->get( 'APIMaxResultSize' ) );
243 
244  // Setup uselang. This doesn't use $this->getParameter()
245  // because we're not ready to handle errors yet.
246  $uselang = $request->getVal( 'uselang', self::API_DEFAULT_USELANG );
247  if ( $uselang === 'user' ) {
248  // Assume the parent context is going to return the user language
249  // for uselang=user (see T85635).
250  } else {
251  if ( $uselang === 'content' ) {
253  $uselang = $wgContLang->getCode();
254  }
256  $this->getContext()->setLanguage( $code );
257  if ( !$this->mInternalMode ) {
258  global $wgLang;
259  $wgLang = $this->getContext()->getLanguage();
260  RequestContext::getMain()->setLanguage( $wgLang );
261  }
262  }
263 
264  // Set up the error formatter. This doesn't use $this->getParameter()
265  // because we're not ready to handle errors yet.
266  $errorFormat = $request->getVal( 'errorformat', 'bc' );
267  $errorLangCode = $request->getVal( 'errorlang', 'uselang' );
268  $errorsUseDB = $request->getCheck( 'errorsuselocal' );
269  if ( in_array( $errorFormat, [ 'plaintext', 'wikitext', 'html', 'raw', 'none' ], true ) ) {
270  if ( $errorLangCode === 'uselang' ) {
271  $errorLang = $this->getLanguage();
272  } elseif ( $errorLangCode === 'content' ) {
274  $errorLang = $wgContLang;
275  } else {
276  $errorLangCode = RequestContext::sanitizeLangCode( $errorLangCode );
277  $errorLang = Language::factory( $errorLangCode );
278  }
279  $this->mErrorFormatter = new ApiErrorFormatter(
280  $this->mResult, $errorLang, $errorFormat, $errorsUseDB
281  );
282  } else {
283  $this->mErrorFormatter = new ApiErrorFormatter_BackCompat( $this->mResult );
284  }
285  $this->mResult->setErrorFormatter( $this->getErrorFormatter() );
286 
287  $this->mModuleMgr = new ApiModuleManager( $this );
288  $this->mModuleMgr->addModules( self::$Modules, 'action' );
289  $this->mModuleMgr->addModules( $config->get( 'APIModules' ), 'action' );
290  $this->mModuleMgr->addModules( self::$Formats, 'format' );
291  $this->mModuleMgr->addModules( $config->get( 'APIFormatModules' ), 'format' );
292 
293  Hooks::run( 'ApiMain::moduleManager', [ $this->mModuleMgr ] );
294 
295  $this->mContinuationManager = null;
296  $this->mEnableWrite = $enableWrite;
297 
298  $this->mSquidMaxage = -1; // flag for executeActionWithErrorHandling()
299  $this->mCommit = false;
300  }
301 
306  public function isInternalMode() {
307  return $this->mInternalMode;
308  }
309 
315  public function getResult() {
316  return $this->mResult;
317  }
318 
323  public function lacksSameOriginSecurity() {
324  if ( $this->lacksSameOriginSecurity !== null ) {
326  }
327 
328  $request = $this->getRequest();
329 
330  // JSONP mode
331  if ( $request->getVal( 'callback' ) !== null ) {
332  $this->lacksSameOriginSecurity = true;
333  return true;
334  }
335 
336  // Anonymous CORS
337  if ( $request->getVal( 'origin' ) === '*' ) {
338  $this->lacksSameOriginSecurity = true;
339  return true;
340  }
341 
342  // Header to be used from XMLHTTPRequest when the request might
343  // otherwise be used for XSS.
344  if ( $request->getHeader( 'Treat-as-Untrusted' ) !== false ) {
345  $this->lacksSameOriginSecurity = true;
346  return true;
347  }
348 
349  // Allow extensions to override.
350  $this->lacksSameOriginSecurity = !Hooks::run( 'RequestHasSameOriginSecurity', [ $request ] );
352  }
353 
358  public function getErrorFormatter() {
359  return $this->mErrorFormatter;
360  }
361 
366  public function getContinuationManager() {
368  }
369 
374  public function setContinuationManager( $manager ) {
375  if ( $manager !== null ) {
376  if ( !$manager instanceof ApiContinuationManager ) {
377  throw new InvalidArgumentException( __METHOD__ . ': Was passed ' .
378  is_object( $manager ) ? get_class( $manager ) : gettype( $manager )
379  );
380  }
381  if ( $this->mContinuationManager !== null ) {
382  throw new UnexpectedValueException(
383  __METHOD__ . ': tried to set manager from ' . $manager->getSource() .
384  ' when a manager is already set from ' . $this->mContinuationManager->getSource()
385  );
386  }
387  }
388  $this->mContinuationManager = $manager;
389  }
390 
396  public function getModule() {
397  return $this->mModule;
398  }
399 
405  public function getPrinter() {
406  return $this->mPrinter;
407  }
408 
414  public function setCacheMaxAge( $maxage ) {
415  $this->setCacheControl( [
416  'max-age' => $maxage,
417  's-maxage' => $maxage
418  ] );
419  }
420 
446  public function setCacheMode( $mode ) {
447  if ( !in_array( $mode, [ 'private', 'public', 'anon-public-user-private' ] ) ) {
448  wfDebug( __METHOD__ . ": unrecognised cache mode \"$mode\"\n" );
449 
450  // Ignore for forwards-compatibility
451  return;
452  }
453 
454  if ( !User::isEveryoneAllowed( 'read' ) ) {
455  // Private wiki, only private headers
456  if ( $mode !== 'private' ) {
457  wfDebug( __METHOD__ . ": ignoring request for $mode cache mode, private wiki\n" );
458 
459  return;
460  }
461  }
462 
463  if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) {
464  // User language is used for i18n, so we don't want to publicly
465  // cache. Anons are ok, because if they have non-default language
466  // then there's an appropriate Vary header set by whatever set
467  // their non-default language.
468  wfDebug( __METHOD__ . ": downgrading cache mode 'public' to " .
469  "'anon-public-user-private' due to uselang=user\n" );
470  $mode = 'anon-public-user-private';
471  }
472 
473  wfDebug( __METHOD__ . ": setting cache mode $mode\n" );
474  $this->mCacheMode = $mode;
475  }
476 
487  public function setCacheControl( $directives ) {
488  $this->mCacheControl = $directives + $this->mCacheControl;
489  }
490 
498  public function createPrinterByName( $format ) {
499  $printer = $this->mModuleMgr->getModule( $format, 'format' );
500  if ( $printer === null ) {
501  $this->dieWithError(
502  [ 'apierror-unknownformat', wfEscapeWikiText( $format ) ], 'unknown_format'
503  );
504  }
505 
506  return $printer;
507  }
508 
512  public function execute() {
513  if ( $this->mInternalMode ) {
514  $this->executeAction();
515  } else {
517  }
518  }
519 
524  protected function executeActionWithErrorHandling() {
525  // Verify the CORS header before executing the action
526  if ( !$this->handleCORS() ) {
527  // handleCORS() has sent a 403, abort
528  return;
529  }
530 
531  // Exit here if the request method was OPTIONS
532  // (assume there will be a followup GET or POST)
533  if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
534  return;
535  }
536 
537  // In case an error occurs during data output,
538  // clear the output buffer and print just the error information
539  $obLevel = ob_get_level();
540  ob_start();
541 
542  $t = microtime( true );
543  $isError = false;
544  try {
545  $this->executeAction();
546  $runTime = microtime( true ) - $t;
547  $this->logRequest( $runTime );
548  if ( $this->mModule->isWriteMode() && $this->getRequest()->wasPosted() ) {
549  MediaWikiServices::getInstance()->getStatsdDataFactory()->timing(
550  'api.' . $this->mModule->getModuleName() . '.executeTiming', 1000 * $runTime
551  );
552  }
553  } catch ( Exception $e ) {
554  $this->handleException( $e );
555  $this->logRequest( microtime( true ) - $t, $e );
556  $isError = true;
557  }
558 
559  // Commit DBs and send any related cookies and headers
561 
562  // Send cache headers after any code which might generate an error, to
563  // avoid sending public cache headers for errors.
564  $this->sendCacheHeaders( $isError );
565 
566  // Executing the action might have already messed with the output
567  // buffers.
568  while ( ob_get_level() > $obLevel ) {
569  ob_end_flush();
570  }
571  }
572 
579  protected function handleException( Exception $e ) {
580  // T65145: Rollback any open database transactions
581  if ( !( $e instanceof ApiUsageException || $e instanceof UsageException ) ) {
582  // UsageExceptions are intentional, so don't rollback if that's the case
584  }
585 
586  // Allow extra cleanup and logging
587  Hooks::run( 'ApiMain::onException', [ $this, $e ] );
588 
589  // Handle any kind of exception by outputting properly formatted error message.
590  // If this fails, an unhandled exception should be thrown so that global error
591  // handler will process and log it.
592 
593  $errCodes = $this->substituteResultWithError( $e );
594 
595  // Error results should not be cached
596  $this->setCacheMode( 'private' );
597 
598  $response = $this->getRequest()->response();
599  $headerStr = 'MediaWiki-API-Error: ' . join( ', ', $errCodes );
600  $response->header( $headerStr );
601 
602  // Reset and print just the error message
603  ob_clean();
604 
605  // Printer may not be initialized if the extractRequestParams() fails for the main module
606  $this->createErrorPrinter();
607 
608  $failed = false;
609  try {
610  $this->printResult( $e->getCode() );
611  } catch ( ApiUsageException $ex ) {
612  // The error printer itself is failing. Try suppressing its request
613  // parameters and redo.
614  $failed = true;
615  $this->addWarning( 'apiwarn-errorprinterfailed' );
616  foreach ( $ex->getStatusValue()->getErrors() as $error ) {
617  try {
618  $this->mPrinter->addWarning( $error );
619  } catch ( Exception $ex2 ) {
620  // WTF?
621  $this->addWarning( $error );
622  }
623  }
624  } catch ( UsageException $ex ) {
625  // The error printer itself is failing. Try suppressing its request
626  // parameters and redo.
627  $failed = true;
628  $this->addWarning(
629  [ 'apiwarn-errorprinterfailed-ex', $ex->getMessage() ], 'errorprinterfailed'
630  );
631  }
632  if ( $failed ) {
633  $this->mPrinter = null;
634  $this->createErrorPrinter();
635  $this->mPrinter->forceDefaultParams();
636  if ( $e->getCode() ) {
637  $response->statusHeader( 200 ); // Reset in case the fallback doesn't want a non-200
638  }
639  $this->printResult( $e->getCode() );
640  }
641  }
642 
653  public static function handleApiBeforeMainException( Exception $e ) {
654  ob_start();
655 
656  try {
657  $main = new self( RequestContext::getMain(), false );
658  $main->handleException( $e );
659  $main->logRequest( 0, $e );
660  } catch ( Exception $e2 ) {
661  // Nope, even that didn't work. Punt.
662  throw $e;
663  }
664 
665  // Reset cache headers
666  $main->sendCacheHeaders( true );
667 
668  ob_end_flush();
669  }
670 
685  protected function handleCORS() {
686  $originParam = $this->getParameter( 'origin' ); // defaults to null
687  if ( $originParam === null ) {
688  // No origin parameter, nothing to do
689  return true;
690  }
691 
692  $request = $this->getRequest();
693  $response = $request->response();
694 
695  $matchOrigin = false;
696  $allowTiming = false;
697  $varyOrigin = true;
698 
699  if ( $originParam === '*' ) {
700  // Request for anonymous CORS
701  $matchOrigin = true;
702  $allowOrigin = '*';
703  $allowCredentials = 'false';
704  $varyOrigin = false; // No need to vary
705  } else {
706  // Non-anonymous CORS, check we allow the domain
707 
708  // Origin: header is a space-separated list of origins, check all of them
709  $originHeader = $request->getHeader( 'Origin' );
710  if ( $originHeader === false ) {
711  $origins = [];
712  } else {
713  $originHeader = trim( $originHeader );
714  $origins = preg_split( '/\s+/', $originHeader );
715  }
716 
717  if ( !in_array( $originParam, $origins ) ) {
718  // origin parameter set but incorrect
719  // Send a 403 response
720  $response->statusHeader( 403 );
721  $response->header( 'Cache-Control: no-cache' );
722  echo "'origin' parameter does not match Origin header\n";
723 
724  return false;
725  }
726 
727  $config = $this->getConfig();
728  $matchOrigin = count( $origins ) === 1 && self::matchOrigin(
729  $originParam,
730  $config->get( 'CrossSiteAJAXdomains' ),
731  $config->get( 'CrossSiteAJAXdomainExceptions' )
732  );
733 
734  $allowOrigin = $originHeader;
735  $allowCredentials = 'true';
736  $allowTiming = $originHeader;
737  }
738 
739  if ( $matchOrigin ) {
740  $requestedMethod = $request->getHeader( 'Access-Control-Request-Method' );
741  $preflight = $request->getMethod() === 'OPTIONS' && $requestedMethod !== false;
742  if ( $preflight ) {
743  // This is a CORS preflight request
744  if ( $requestedMethod !== 'POST' && $requestedMethod !== 'GET' ) {
745  // If method is not a case-sensitive match, do not set any additional headers and terminate.
746  return true;
747  }
748  // We allow the actual request to send the following headers
749  $requestedHeaders = $request->getHeader( 'Access-Control-Request-Headers' );
750  if ( $requestedHeaders !== false ) {
751  if ( !self::matchRequestedHeaders( $requestedHeaders ) ) {
752  return true;
753  }
754  $response->header( 'Access-Control-Allow-Headers: ' . $requestedHeaders );
755  }
756 
757  // We only allow the actual request to be GET or POST
758  $response->header( 'Access-Control-Allow-Methods: POST, GET' );
759  }
760 
761  $response->header( "Access-Control-Allow-Origin: $allowOrigin" );
762  $response->header( "Access-Control-Allow-Credentials: $allowCredentials" );
763  // https://www.w3.org/TR/resource-timing/#timing-allow-origin
764  if ( $allowTiming !== false ) {
765  $response->header( "Timing-Allow-Origin: $allowTiming" );
766  }
767 
768  if ( !$preflight ) {
769  $response->header(
770  'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag'
771  );
772  }
773  }
774 
775  if ( $varyOrigin ) {
776  $this->getOutput()->addVaryHeader( 'Origin' );
777  }
778 
779  return true;
780  }
781 
790  protected static function matchOrigin( $value, $rules, $exceptions ) {
791  foreach ( $rules as $rule ) {
792  if ( preg_match( self::wildcardToRegex( $rule ), $value ) ) {
793  // Rule matches, check exceptions
794  foreach ( $exceptions as $exc ) {
795  if ( preg_match( self::wildcardToRegex( $exc ), $value ) ) {
796  return false;
797  }
798  }
799 
800  return true;
801  }
802  }
803 
804  return false;
805  }
806 
814  protected static function matchRequestedHeaders( $requestedHeaders ) {
815  if ( trim( $requestedHeaders ) === '' ) {
816  return true;
817  }
818  $requestedHeaders = explode( ',', $requestedHeaders );
819  $allowedAuthorHeaders = array_flip( [
820  /* simple headers (see spec) */
821  'accept',
822  'accept-language',
823  'content-language',
824  'content-type',
825  /* non-authorable headers in XHR, which are however requested by some UAs */
826  'accept-encoding',
827  'dnt',
828  'origin',
829  /* MediaWiki whitelist */
830  'api-user-agent',
831  ] );
832  foreach ( $requestedHeaders as $rHeader ) {
833  $rHeader = strtolower( trim( $rHeader ) );
834  if ( !isset( $allowedAuthorHeaders[$rHeader] ) ) {
835  wfDebugLog( 'api', 'CORS preflight failed on requested header: ' . $rHeader );
836  return false;
837  }
838  }
839  return true;
840  }
841 
850  protected static function wildcardToRegex( $wildcard ) {
851  $wildcard = preg_quote( $wildcard, '/' );
852  $wildcard = str_replace(
853  [ '\*', '\?' ],
854  [ '.*?', '.' ],
855  $wildcard
856  );
857 
858  return "/^https?:\/\/$wildcard$/";
859  }
860 
866  protected function sendCacheHeaders( $isError ) {
867  $response = $this->getRequest()->response();
868  $out = $this->getOutput();
869 
870  $out->addVaryHeader( 'Treat-as-Untrusted' );
871 
872  $config = $this->getConfig();
873 
874  if ( $config->get( 'VaryOnXFP' ) ) {
875  $out->addVaryHeader( 'X-Forwarded-Proto' );
876  }
877 
878  if ( !$isError && $this->mModule &&
879  ( $this->getRequest()->getMethod() === 'GET' || $this->getRequest()->getMethod() === 'HEAD' )
880  ) {
881  $etag = $this->mModule->getConditionalRequestData( 'etag' );
882  if ( $etag !== null ) {
883  $response->header( "ETag: $etag" );
884  }
885  $lastMod = $this->mModule->getConditionalRequestData( 'last-modified' );
886  if ( $lastMod !== null ) {
887  $response->header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822, $lastMod ) );
888  }
889  }
890 
891  // The logic should be:
892  // $this->mCacheControl['max-age'] is set?
893  // Use it, the module knows better than our guess.
894  // !$this->mModule || $this->mModule->isWriteMode(), and mCacheMode is private?
895  // Use 0 because we can guess caching is probably the wrong thing to do.
896  // Use $this->getParameter( 'maxage' ), which already defaults to 0.
897  $maxage = 0;
898  if ( isset( $this->mCacheControl['max-age'] ) ) {
899  $maxage = $this->mCacheControl['max-age'];
900  } elseif ( ( $this->mModule && !$this->mModule->isWriteMode() ) ||
901  $this->mCacheMode !== 'private'
902  ) {
903  $maxage = $this->getParameter( 'maxage' );
904  }
905  $privateCache = 'private, must-revalidate, max-age=' . $maxage;
906 
907  if ( $this->mCacheMode == 'private' ) {
908  $response->header( "Cache-Control: $privateCache" );
909  return;
910  }
911 
912  $useKeyHeader = $config->get( 'UseKeyHeader' );
913  if ( $this->mCacheMode == 'anon-public-user-private' ) {
914  $out->addVaryHeader( 'Cookie' );
915  $response->header( $out->getVaryHeader() );
916  if ( $useKeyHeader ) {
917  $response->header( $out->getKeyHeader() );
918  if ( $out->haveCacheVaryCookies() ) {
919  // Logged in, mark this request private
920  $response->header( "Cache-Control: $privateCache" );
921  return;
922  }
923  // Logged out, send normal public headers below
924  } elseif ( MediaWiki\Session\SessionManager::getGlobalSession()->isPersistent() ) {
925  // Logged in or otherwise has session (e.g. anonymous users who have edited)
926  // Mark request private
927  $response->header( "Cache-Control: $privateCache" );
928 
929  return;
930  } // else no Key and anonymous, send public headers below
931  }
932 
933  // Send public headers
934  $response->header( $out->getVaryHeader() );
935  if ( $useKeyHeader ) {
936  $response->header( $out->getKeyHeader() );
937  }
938 
939  // If nobody called setCacheMaxAge(), use the (s)maxage parameters
940  if ( !isset( $this->mCacheControl['s-maxage'] ) ) {
941  $this->mCacheControl['s-maxage'] = $this->getParameter( 'smaxage' );
942  }
943  if ( !isset( $this->mCacheControl['max-age'] ) ) {
944  $this->mCacheControl['max-age'] = $this->getParameter( 'maxage' );
945  }
946 
947  if ( !$this->mCacheControl['s-maxage'] && !$this->mCacheControl['max-age'] ) {
948  // Public cache not requested
949  // Sending a Vary header in this case is harmless, and protects us
950  // against conditional calls of setCacheMaxAge().
951  $response->header( "Cache-Control: $privateCache" );
952 
953  return;
954  }
955 
956  $this->mCacheControl['public'] = true;
957 
958  // Send an Expires header
959  $maxAge = min( $this->mCacheControl['s-maxage'], $this->mCacheControl['max-age'] );
960  $expiryUnixTime = ( $maxAge == 0 ? 1 : time() + $maxAge );
961  $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822, $expiryUnixTime ) );
962 
963  // Construct the Cache-Control header
964  $ccHeader = '';
965  $separator = '';
966  foreach ( $this->mCacheControl as $name => $value ) {
967  if ( is_bool( $value ) ) {
968  if ( $value ) {
969  $ccHeader .= $separator . $name;
970  $separator = ', ';
971  }
972  } else {
973  $ccHeader .= $separator . "$name=$value";
974  $separator = ', ';
975  }
976  }
977 
978  $response->header( "Cache-Control: $ccHeader" );
979  }
980 
984  private function createErrorPrinter() {
985  if ( !isset( $this->mPrinter ) ) {
986  $value = $this->getRequest()->getVal( 'format', self::API_DEFAULT_FORMAT );
987  if ( !$this->mModuleMgr->isDefined( $value, 'format' ) ) {
989  }
990  $this->mPrinter = $this->createPrinterByName( $value );
991  }
992 
993  // Printer may not be able to handle errors. This is particularly
994  // likely if the module returns something for getCustomPrinter().
995  if ( !$this->mPrinter->canPrintErrors() ) {
996  $this->mPrinter = $this->createPrinterByName( self::API_DEFAULT_FORMAT );
997  }
998  }
999 
1018  protected function errorMessagesFromException( $e, $type = 'error' ) {
1019  $messages = [];
1020  if ( $e instanceof ApiUsageException ) {
1021  foreach ( $e->getStatusValue()->getErrorsByType( $type ) as $error ) {
1022  $messages[] = ApiMessage::create( $error );
1023  }
1024  } elseif ( $type !== 'error' ) {
1025  // None of the rest have any messages for non-error types
1026  } elseif ( $e instanceof UsageException ) {
1027  // User entered incorrect parameters - generate error response
1028  $data = $e->getMessageArray();
1029  $code = $data['code'];
1030  $info = $data['info'];
1031  unset( $data['code'], $data['info'] );
1032  $messages[] = new ApiRawMessage( [ '$1', $info ], $code, $data );
1033  } else {
1034  // Something is seriously wrong
1035  $config = $this->getConfig();
1036  $class = preg_replace( '#^Wikimedia\\\Rdbms\\\#', '', get_class( $e ) );
1037  $code = 'internal_api_error_' . $class;
1038  if ( ( $e instanceof DBQueryError ) && !$config->get( 'ShowSQLErrors' ) ) {
1039  $params = [ 'apierror-databaseerror', WebRequest::getRequestId() ];
1040  } else {
1041  $params = [
1042  'apierror-exceptioncaught',
1044  $e instanceof ILocalizedException
1045  ? $e->getMessageObject()
1046  : wfEscapeWikiText( $e->getMessage() )
1047  ];
1048  }
1050  }
1051  return $messages;
1052  }
1053 
1059  protected function substituteResultWithError( $e ) {
1060  $result = $this->getResult();
1061  $formatter = $this->getErrorFormatter();
1062  $config = $this->getConfig();
1063  $errorCodes = [];
1064 
1065  // Remember existing warnings and errors across the reset
1066  $errors = $result->getResultData( [ 'errors' ] );
1067  $warnings = $result->getResultData( [ 'warnings' ] );
1068  $result->reset();
1069  if ( $warnings !== null ) {
1070  $result->addValue( null, 'warnings', $warnings, ApiResult::NO_SIZE_CHECK );
1071  }
1072  if ( $errors !== null ) {
1073  $result->addValue( null, 'errors', $errors, ApiResult::NO_SIZE_CHECK );
1074 
1075  // Collect the copied error codes for the return value
1076  foreach ( $errors as $error ) {
1077  if ( isset( $error['code'] ) ) {
1078  $errorCodes[$error['code']] = true;
1079  }
1080  }
1081  }
1082 
1083  // Add errors from the exception
1084  $modulePath = $e instanceof ApiUsageException ? $e->getModulePath() : null;
1085  foreach ( $this->errorMessagesFromException( $e, 'error' ) as $msg ) {
1086  $errorCodes[$msg->getApiCode()] = true;
1087  $formatter->addError( $modulePath, $msg );
1088  }
1089  foreach ( $this->errorMessagesFromException( $e, 'warning' ) as $msg ) {
1090  $formatter->addWarning( $modulePath, $msg );
1091  }
1092 
1093  // Add additional data. Path depends on whether we're in BC mode or not.
1094  // Data depends on the type of exception.
1095  if ( $formatter instanceof ApiErrorFormatter_BackCompat ) {
1096  $path = [ 'error' ];
1097  } else {
1098  $path = null;
1099  }
1100  if ( $e instanceof ApiUsageException || $e instanceof UsageException ) {
1101  $link = wfExpandUrl( wfScript( 'api' ) );
1102  $result->addContentValue(
1103  $path,
1104  'docref',
1105  trim(
1106  $this->msg( 'api-usage-docref', $link )->inLanguage( $formatter->getLanguage() )->text()
1107  . ' '
1108  . $this->msg( 'api-usage-mailinglist-ref' )->inLanguage( $formatter->getLanguage() )->text()
1109  )
1110  );
1111  } else {
1112  if ( $config->get( 'ShowExceptionDetails' ) &&
1113  ( !$e instanceof DBError || $config->get( 'ShowDBErrorBacktrace' ) )
1114  ) {
1115  $result->addContentValue(
1116  $path,
1117  'trace',
1118  $this->msg( 'api-exception-trace',
1119  get_class( $e ),
1120  $e->getFile(),
1121  $e->getLine(),
1123  )->inLanguage( $formatter->getLanguage() )->text()
1124  );
1125  }
1126  }
1127 
1128  // Add the id and such
1129  $this->addRequestedFields( [ 'servedby' ] );
1130 
1131  return array_keys( $errorCodes );
1132  }
1133 
1139  protected function addRequestedFields( $force = [] ) {
1140  $result = $this->getResult();
1141 
1142  $requestid = $this->getParameter( 'requestid' );
1143  if ( $requestid !== null ) {
1144  $result->addValue( null, 'requestid', $requestid, ApiResult::NO_SIZE_CHECK );
1145  }
1146 
1147  if ( $this->getConfig()->get( 'ShowHostnames' ) && (
1148  in_array( 'servedby', $force, true ) || $this->getParameter( 'servedby' )
1149  ) ) {
1150  $result->addValue( null, 'servedby', wfHostname(), ApiResult::NO_SIZE_CHECK );
1151  }
1152 
1153  if ( $this->getParameter( 'curtimestamp' ) ) {
1154  $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601, time() ),
1156  }
1157 
1158  if ( $this->getParameter( 'responselanginfo' ) ) {
1159  $result->addValue( null, 'uselang', $this->getLanguage()->getCode(),
1161  $result->addValue( null, 'errorlang', $this->getErrorFormatter()->getLanguage()->getCode(),
1163  }
1164  }
1165 
1170  protected function setupExecuteAction() {
1171  $this->addRequestedFields();
1172 
1173  $params = $this->extractRequestParams();
1174  $this->mAction = $params['action'];
1175 
1176  return $params;
1177  }
1178 
1185  protected function setupModule() {
1186  // Instantiate the module requested by the user
1187  $module = $this->mModuleMgr->getModule( $this->mAction, 'action' );
1188  if ( $module === null ) {
1189  $this->dieWithError(
1190  [ 'apierror-unknownaction', wfEscapeWikiText( $this->mAction ) ], 'unknown_action'
1191  );
1192  }
1193  $moduleParams = $module->extractRequestParams();
1194 
1195  // Check token, if necessary
1196  if ( $module->needsToken() === true ) {
1197  throw new MWException(
1198  "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
1199  'See documentation for ApiBase::needsToken for details.'
1200  );
1201  }
1202  if ( $module->needsToken() ) {
1203  if ( !$module->mustBePosted() ) {
1204  throw new MWException(
1205  "Module '{$module->getModuleName()}' must require POST to use tokens."
1206  );
1207  }
1208 
1209  if ( !isset( $moduleParams['token'] ) ) {
1210  $module->dieWithError( [ 'apierror-missingparam', 'token' ] );
1211  }
1212 
1213  $module->requirePostedParameters( [ 'token' ] );
1214 
1215  if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) {
1216  $module->dieWithError( 'apierror-badtoken' );
1217  }
1218  }
1219 
1220  return $module;
1221  }
1222 
1226  private function getMaxLag() {
1227  $dbLag = MediaWikiServices::getInstance()->getDBLoadBalancer()->getMaxLag();
1228  $lagInfo = [
1229  'host' => $dbLag[0],
1230  'lag' => $dbLag[1],
1231  'type' => 'db'
1232  ];
1233 
1234  $jobQueueLagFactor = $this->getConfig()->get( 'JobQueueIncludeInMaxLagFactor' );
1235  if ( $jobQueueLagFactor ) {
1236  // Turn total number of jobs into seconds by using the configured value
1237  $totalJobs = array_sum( JobQueueGroup::singleton()->getQueueSizes() );
1238  $jobQueueLag = $totalJobs / (float)$jobQueueLagFactor;
1239  if ( $jobQueueLag > $lagInfo['lag'] ) {
1240  $lagInfo = [
1241  'host' => wfHostname(), // XXX: Is there a better value that could be used?
1242  'lag' => $jobQueueLag,
1243  'type' => 'jobqueue',
1244  'jobs' => $totalJobs,
1245  ];
1246  }
1247  }
1248 
1249  return $lagInfo;
1250  }
1251 
1258  protected function checkMaxLag( $module, $params ) {
1259  if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
1260  $maxLag = $params['maxlag'];
1261  $lagInfo = $this->getMaxLag();
1262  if ( $lagInfo['lag'] > $maxLag ) {
1263  $response = $this->getRequest()->response();
1264 
1265  $response->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
1266  $response->header( 'X-Database-Lag: ' . intval( $lagInfo['lag'] ) );
1267 
1268  if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
1269  $this->dieWithError(
1270  [ 'apierror-maxlag', $lagInfo['lag'], $lagInfo['host'] ],
1271  'maxlag',
1272  $lagInfo
1273  );
1274  }
1275 
1276  $this->dieWithError( [ 'apierror-maxlag-generic', $lagInfo['lag'] ], 'maxlag', $lagInfo );
1277  }
1278  }
1279 
1280  return true;
1281  }
1282 
1304  protected function checkConditionalRequestHeaders( $module ) {
1305  if ( $this->mInternalMode ) {
1306  // No headers to check in internal mode
1307  return true;
1308  }
1309 
1310  if ( $this->getRequest()->getMethod() !== 'GET' && $this->getRequest()->getMethod() !== 'HEAD' ) {
1311  // Don't check POSTs
1312  return true;
1313  }
1314 
1315  $return304 = false;
1316 
1317  $ifNoneMatch = array_diff(
1318  $this->getRequest()->getHeader( 'If-None-Match', WebRequest::GETHEADER_LIST ) ?: [],
1319  [ '' ]
1320  );
1321  if ( $ifNoneMatch ) {
1322  if ( $ifNoneMatch === [ '*' ] ) {
1323  // API responses always "exist"
1324  $etag = '*';
1325  } else {
1326  $etag = $module->getConditionalRequestData( 'etag' );
1327  }
1328  }
1329  if ( $ifNoneMatch && $etag !== null ) {
1330  $test = substr( $etag, 0, 2 ) === 'W/' ? substr( $etag, 2 ) : $etag;
1331  $match = array_map( function ( $s ) {
1332  return substr( $s, 0, 2 ) === 'W/' ? substr( $s, 2 ) : $s;
1333  }, $ifNoneMatch );
1334  $return304 = in_array( $test, $match, true );
1335  } else {
1336  $value = trim( $this->getRequest()->getHeader( 'If-Modified-Since' ) );
1337 
1338  // Some old browsers sends sizes after the date, like this:
1339  // Wed, 20 Aug 2003 06:51:19 GMT; length=5202
1340  // Ignore that.
1341  $i = strpos( $value, ';' );
1342  if ( $i !== false ) {
1343  $value = trim( substr( $value, 0, $i ) );
1344  }
1345 
1346  if ( $value !== '' ) {
1347  try {
1348  $ts = new MWTimestamp( $value );
1349  if (
1350  // RFC 7231 IMF-fixdate
1351  $ts->getTimestamp( TS_RFC2822 ) === $value ||
1352  // RFC 850
1353  $ts->format( 'l, d-M-y H:i:s' ) . ' GMT' === $value ||
1354  // asctime (with and without space-padded day)
1355  $ts->format( 'D M j H:i:s Y' ) === $value ||
1356  $ts->format( 'D M j H:i:s Y' ) === $value
1357  ) {
1358  $lastMod = $module->getConditionalRequestData( 'last-modified' );
1359  if ( $lastMod !== null ) {
1360  // Mix in some MediaWiki modification times
1361  $modifiedTimes = [
1362  'page' => $lastMod,
1363  'user' => $this->getUser()->getTouched(),
1364  'epoch' => $this->getConfig()->get( 'CacheEpoch' ),
1365  ];
1366  if ( $this->getConfig()->get( 'UseSquid' ) ) {
1367  // T46570: the core page itself may not change, but resources might
1368  $modifiedTimes['sepoch'] = wfTimestamp(
1369  TS_MW, time() - $this->getConfig()->get( 'SquidMaxage' )
1370  );
1371  }
1372  Hooks::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this->getOutput() ] );
1373  $lastMod = max( $modifiedTimes );
1374  $return304 = wfTimestamp( TS_MW, $lastMod ) <= $ts->getTimestamp( TS_MW );
1375  }
1376  }
1377  } catch ( TimestampException $e ) {
1378  // Invalid timestamp, ignore it
1379  }
1380  }
1381  }
1382 
1383  if ( $return304 ) {
1384  $this->getRequest()->response()->statusHeader( 304 );
1385 
1386  // Avoid outputting the compressed representation of a zero-length body
1387  MediaWiki\suppressWarnings();
1388  ini_set( 'zlib.output_compression', 0 );
1389  MediaWiki\restoreWarnings();
1391 
1392  return false;
1393  }
1394 
1395  return true;
1396  }
1397 
1402  protected function checkExecutePermissions( $module ) {
1403  $user = $this->getUser();
1404  if ( $module->isReadMode() && !User::isEveryoneAllowed( 'read' ) &&
1405  !$user->isAllowed( 'read' )
1406  ) {
1407  $this->dieWithError( 'apierror-readapidenied' );
1408  }
1409 
1410  if ( $module->isWriteMode() ) {
1411  if ( !$this->mEnableWrite ) {
1412  $this->dieWithError( 'apierror-noapiwrite' );
1413  } elseif ( !$user->isAllowed( 'writeapi' ) ) {
1414  $this->dieWithError( 'apierror-writeapidenied' );
1415  } elseif ( $this->getRequest()->getHeader( 'Promise-Non-Write-API-Action' ) ) {
1416  $this->dieWithError( 'apierror-promised-nonwrite-api' );
1417  }
1418 
1419  $this->checkReadOnly( $module );
1420  }
1421 
1422  // Allow extensions to stop execution for arbitrary reasons.
1423  $message = false;
1424  if ( !Hooks::run( 'ApiCheckCanExecute', [ $module, $user, &$message ] ) ) {
1425  $this->dieWithError( $message );
1426  }
1427  }
1428 
1433  protected function checkReadOnly( $module ) {
1434  if ( wfReadOnly() ) {
1435  $this->dieReadOnly();
1436  }
1437 
1438  if ( $module->isWriteMode()
1439  && $this->getUser()->isBot()
1440  && wfGetLB()->getServerCount() > 1
1441  ) {
1442  $this->checkBotReadOnly();
1443  }
1444  }
1445 
1449  private function checkBotReadOnly() {
1450  // Figure out how many servers have passed the lag threshold
1451  $numLagged = 0;
1452  $lagLimit = $this->getConfig()->get( 'APIMaxLagThreshold' );
1453  $laggedServers = [];
1454  $loadBalancer = wfGetLB();
1455  foreach ( $loadBalancer->getLagTimes() as $serverIndex => $lag ) {
1456  if ( $lag > $lagLimit ) {
1457  ++$numLagged;
1458  $laggedServers[] = $loadBalancer->getServerName( $serverIndex ) . " ({$lag}s)";
1459  }
1460  }
1461 
1462  // If a majority of replica DBs are too lagged then disallow writes
1463  $replicaCount = wfGetLB()->getServerCount() - 1;
1464  if ( $numLagged >= ceil( $replicaCount / 2 ) ) {
1465  $laggedServers = implode( ', ', $laggedServers );
1466  wfDebugLog(
1467  'api-readonly',
1468  "Api request failed as read only because the following DBs are lagged: $laggedServers"
1469  );
1470 
1471  $this->dieWithError(
1472  'readonly_lag',
1473  'readonly',
1474  [ 'readonlyreason' => "Waiting for $numLagged lagged database(s)" ]
1475  );
1476  }
1477  }
1478 
1483  protected function checkAsserts( $params ) {
1484  if ( isset( $params['assert'] ) ) {
1485  $user = $this->getUser();
1486  switch ( $params['assert'] ) {
1487  case 'user':
1488  if ( $user->isAnon() ) {
1489  $this->dieWithError( 'apierror-assertuserfailed' );
1490  }
1491  break;
1492  case 'bot':
1493  if ( !$user->isAllowed( 'bot' ) ) {
1494  $this->dieWithError( 'apierror-assertbotfailed' );
1495  }
1496  break;
1497  }
1498  }
1499  if ( isset( $params['assertuser'] ) ) {
1500  $assertUser = User::newFromName( $params['assertuser'], false );
1501  if ( !$assertUser || !$this->getUser()->equals( $assertUser ) ) {
1502  $this->dieWithError(
1503  [ 'apierror-assertnameduserfailed', wfEscapeWikiText( $params['assertuser'] ) ]
1504  );
1505  }
1506  }
1507  }
1508 
1514  protected function setupExternalResponse( $module, $params ) {
1515  $request = $this->getRequest();
1516  if ( !$request->wasPosted() && $module->mustBePosted() ) {
1517  // Module requires POST. GET request might still be allowed
1518  // if $wgDebugApi is true, otherwise fail.
1519  $this->dieWithErrorOrDebug( [ 'apierror-mustbeposted', $this->mAction ] );
1520  }
1521 
1522  // See if custom printer is used
1523  $this->mPrinter = $module->getCustomPrinter();
1524  if ( is_null( $this->mPrinter ) ) {
1525  // Create an appropriate printer
1526  $this->mPrinter = $this->createPrinterByName( $params['format'] );
1527  }
1528 
1529  if ( $request->getProtocol() === 'http' && (
1530  $request->getSession()->shouldForceHTTPS() ||
1531  ( $this->getUser()->isLoggedIn() &&
1532  $this->getUser()->requiresHTTPS() )
1533  ) ) {
1534  $this->addDeprecation( 'apiwarn-deprecation-httpsexpected', 'https-expected' );
1535  }
1536  }
1537 
1541  protected function executeAction() {
1542  $params = $this->setupExecuteAction();
1543  $module = $this->setupModule();
1544  $this->mModule = $module;
1545 
1546  if ( !$this->mInternalMode ) {
1547  $this->setRequestExpectations( $module );
1548  }
1549 
1550  $this->checkExecutePermissions( $module );
1551 
1552  if ( !$this->checkMaxLag( $module, $params ) ) {
1553  return;
1554  }
1555 
1556  if ( !$this->checkConditionalRequestHeaders( $module ) ) {
1557  return;
1558  }
1559 
1560  if ( !$this->mInternalMode ) {
1561  $this->setupExternalResponse( $module, $params );
1562  }
1563 
1564  $this->checkAsserts( $params );
1565 
1566  // Execute
1567  $module->execute();
1568  Hooks::run( 'APIAfterExecute', [ &$module ] );
1569 
1570  $this->reportUnusedParams();
1571 
1572  if ( !$this->mInternalMode ) {
1573  // append Debug information
1575 
1576  // Print result data
1577  $this->printResult();
1578  }
1579  }
1580 
1585  protected function setRequestExpectations( ApiBase $module ) {
1586  $limits = $this->getConfig()->get( 'TrxProfilerLimits' );
1587  $trxProfiler = Profiler::instance()->getTransactionProfiler();
1588  $trxProfiler->setLogger( LoggerFactory::getInstance( 'DBPerformance' ) );
1589  if ( $this->getRequest()->hasSafeMethod() ) {
1590  $trxProfiler->setExpectations( $limits['GET'], __METHOD__ );
1591  } elseif ( $this->getRequest()->wasPosted() && !$module->isWriteMode() ) {
1592  $trxProfiler->setExpectations( $limits['POST-nonwrite'], __METHOD__ );
1593  $this->getRequest()->markAsSafeRequest();
1594  } else {
1595  $trxProfiler->setExpectations( $limits['POST'], __METHOD__ );
1596  }
1597  }
1598 
1604  protected function logRequest( $time, $e = null ) {
1605  $request = $this->getRequest();
1606  $logCtx = [
1607  'ts' => time(),
1608  'ip' => $request->getIP(),
1609  'userAgent' => $this->getUserAgent(),
1610  'wiki' => wfWikiID(),
1611  'timeSpentBackend' => (int)round( $time * 1000 ),
1612  'hadError' => $e !== null,
1613  'errorCodes' => [],
1614  'params' => [],
1615  ];
1616 
1617  if ( $e ) {
1618  foreach ( $this->errorMessagesFromException( $e ) as $msg ) {
1619  $logCtx['errorCodes'][] = $msg->getApiCode();
1620  }
1621  }
1622 
1623  // Construct space separated message for 'api' log channel
1624  $msg = "API {$request->getMethod()} " .
1625  wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
1626  " {$logCtx['ip']} " .
1627  "T={$logCtx['timeSpentBackend']}ms";
1628 
1629  $sensitive = array_flip( $this->getSensitiveParams() );
1630  foreach ( $this->getParamsUsed() as $name ) {
1631  $value = $request->getVal( $name );
1632  if ( $value === null ) {
1633  continue;
1634  }
1635 
1636  if ( isset( $sensitive[$name] ) ) {
1637  $value = '[redacted]';
1638  $encValue = '[redacted]';
1639  } elseif ( strlen( $value ) > 256 ) {
1640  $value = substr( $value, 0, 256 );
1641  $encValue = $this->encodeRequestLogValue( $value ) . '[...]';
1642  } else {
1643  $encValue = $this->encodeRequestLogValue( $value );
1644  }
1645 
1646  $logCtx['params'][$name] = $value;
1647  $msg .= " {$name}={$encValue}";
1648  }
1649 
1650  wfDebugLog( 'api', $msg, 'private' );
1651  // ApiAction channel is for structured data consumers
1652  wfDebugLog( 'ApiAction', '', 'private', $logCtx );
1653  }
1654 
1660  protected function encodeRequestLogValue( $s ) {
1661  static $table;
1662  if ( !$table ) {
1663  $chars = ';@$!*(),/:';
1664  $numChars = strlen( $chars );
1665  for ( $i = 0; $i < $numChars; $i++ ) {
1666  $table[rawurlencode( $chars[$i] )] = $chars[$i];
1667  }
1668  }
1669 
1670  return strtr( rawurlencode( $s ), $table );
1671  }
1672 
1677  protected function getParamsUsed() {
1678  return array_keys( $this->mParamsUsed );
1679  }
1680 
1685  public function markParamsUsed( $params ) {
1686  $this->mParamsUsed += array_fill_keys( (array)$params, true );
1687  }
1688 
1694  protected function getSensitiveParams() {
1695  return array_keys( $this->mParamsSensitive );
1696  }
1697 
1703  public function markParamsSensitive( $params ) {
1704  $this->mParamsSensitive += array_fill_keys( (array)$params, true );
1705  }
1706 
1713  public function getVal( $name, $default = null ) {
1714  $this->mParamsUsed[$name] = true;
1715 
1716  $ret = $this->getRequest()->getVal( $name );
1717  if ( $ret === null ) {
1718  if ( $this->getRequest()->getArray( $name ) !== null ) {
1719  // See T12262 for why we don't just implode( '|', ... ) the
1720  // array.
1721  $this->addWarning( [ 'apiwarn-unsupportedarray', $name ] );
1722  }
1723  $ret = $default;
1724  }
1725  return $ret;
1726  }
1727 
1734  public function getCheck( $name ) {
1735  return $this->getVal( $name, null ) !== null;
1736  }
1737 
1745  public function getUpload( $name ) {
1746  $this->mParamsUsed[$name] = true;
1747 
1748  return $this->getRequest()->getUpload( $name );
1749  }
1750 
1755  protected function reportUnusedParams() {
1756  $paramsUsed = $this->getParamsUsed();
1757  $allParams = $this->getRequest()->getValueNames();
1758 
1759  if ( !$this->mInternalMode ) {
1760  // Printer has not yet executed; don't warn that its parameters are unused
1761  $printerParams = $this->mPrinter->encodeParamName(
1762  array_keys( $this->mPrinter->getFinalParams() ?: [] )
1763  );
1764  $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1765  } else {
1766  $unusedParams = array_diff( $allParams, $paramsUsed );
1767  }
1768 
1769  if ( count( $unusedParams ) ) {
1770  $this->addWarning( [
1771  'apierror-unrecognizedparams',
1772  Message::listParam( array_map( 'wfEscapeWikiText', $unusedParams ), 'comma' ),
1773  count( $unusedParams )
1774  ] );
1775  }
1776  }
1777 
1783  protected function printResult( $httpCode = 0 ) {
1784  if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
1785  $this->addWarning( 'apiwarn-wgDebugAPI' );
1786  }
1787 
1788  $printer = $this->mPrinter;
1789  $printer->initPrinter( false );
1790  if ( $httpCode ) {
1791  $printer->setHttpStatus( $httpCode );
1792  }
1793  $printer->execute();
1794  $printer->closePrinter();
1795  }
1796 
1800  public function isReadMode() {
1801  return false;
1802  }
1803 
1809  public function getAllowedParams() {
1810  return [
1811  'action' => [
1812  ApiBase::PARAM_DFLT => 'help',
1813  ApiBase::PARAM_TYPE => 'submodule',
1814  ],
1815  'format' => [
1817  ApiBase::PARAM_TYPE => 'submodule',
1818  ],
1819  'maxlag' => [
1820  ApiBase::PARAM_TYPE => 'integer'
1821  ],
1822  'smaxage' => [
1823  ApiBase::PARAM_TYPE => 'integer',
1824  ApiBase::PARAM_DFLT => 0
1825  ],
1826  'maxage' => [
1827  ApiBase::PARAM_TYPE => 'integer',
1828  ApiBase::PARAM_DFLT => 0
1829  ],
1830  'assert' => [
1831  ApiBase::PARAM_TYPE => [ 'user', 'bot' ]
1832  ],
1833  'assertuser' => [
1834  ApiBase::PARAM_TYPE => 'user',
1835  ],
1836  'requestid' => null,
1837  'servedby' => false,
1838  'curtimestamp' => false,
1839  'responselanginfo' => false,
1840  'origin' => null,
1841  'uselang' => [
1843  ],
1844  'errorformat' => [
1845  ApiBase::PARAM_TYPE => [ 'plaintext', 'wikitext', 'html', 'raw', 'none', 'bc' ],
1846  ApiBase::PARAM_DFLT => 'bc',
1847  ],
1848  'errorlang' => [
1849  ApiBase::PARAM_DFLT => 'uselang',
1850  ],
1851  'errorsuselocal' => [
1852  ApiBase::PARAM_DFLT => false,
1853  ],
1854  ];
1855  }
1856 
1858  protected function getExamplesMessages() {
1859  return [
1860  'action=help'
1861  => 'apihelp-help-example-main',
1862  'action=help&recursivesubmodules=1'
1863  => 'apihelp-help-example-recursive',
1864  ];
1865  }
1866 
1867  public function modifyHelp( array &$help, array $options, array &$tocData ) {
1868  // Wish PHP had an "array_insert_before". Instead, we have to manually
1869  // reindex the array to get 'permissions' in the right place.
1870  $oldHelp = $help;
1871  $help = [];
1872  foreach ( $oldHelp as $k => $v ) {
1873  if ( $k === 'submodules' ) {
1874  $help['permissions'] = '';
1875  }
1876  $help[$k] = $v;
1877  }
1878  $help['datatypes'] = '';
1879  $help['credits'] = '';
1880 
1881  // Fill 'permissions'
1882  $help['permissions'] .= Html::openElement( 'div',
1883  [ 'class' => 'apihelp-block apihelp-permissions' ] );
1884  $m = $this->msg( 'api-help-permissions' );
1885  if ( !$m->isDisabled() ) {
1886  $help['permissions'] .= Html::rawElement( 'div', [ 'class' => 'apihelp-block-head' ],
1887  $m->numParams( count( self::$mRights ) )->parse()
1888  );
1889  }
1890  $help['permissions'] .= Html::openElement( 'dl' );
1891  foreach ( self::$mRights as $right => $rightMsg ) {
1892  $help['permissions'] .= Html::element( 'dt', null, $right );
1893 
1894  $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse();
1895  $help['permissions'] .= Html::rawElement( 'dd', null, $rightMsg );
1896 
1897  $groups = array_map( function ( $group ) {
1898  return $group == '*' ? 'all' : $group;
1899  }, User::getGroupsWithPermission( $right ) );
1900 
1901  $help['permissions'] .= Html::rawElement( 'dd', null,
1902  $this->msg( 'api-help-permissions-granted-to' )
1903  ->numParams( count( $groups ) )
1904  ->params( Message::listParam( $groups ) )
1905  ->parse()
1906  );
1907  }
1908  $help['permissions'] .= Html::closeElement( 'dl' );
1909  $help['permissions'] .= Html::closeElement( 'div' );
1910 
1911  // Fill 'datatypes' and 'credits', if applicable
1912  if ( empty( $options['nolead'] ) ) {
1913  $level = $options['headerlevel'];
1914  $tocnumber = &$options['tocnumber'];
1915 
1916  $header = $this->msg( 'api-help-datatypes-header' )->parse();
1917 
1918  // Add an additional span with sanitized ID
1919  if ( !$this->getConfig()->get( 'ExperimentalHtmlIds' ) ) {
1920  $header = Html::element( 'span', [ 'id' => Sanitizer::escapeId( 'main/datatypes' ) ] ) .
1921  $header;
1922  }
1923  $help['datatypes'] .= Html::rawElement( 'h' . min( 6, $level ),
1924  [ 'id' => 'main/datatypes', 'class' => 'apihelp-header' ],
1925  $header
1926  );
1927  $help['datatypes'] .= $this->msg( 'api-help-datatypes' )->parseAsBlock();
1928  if ( !isset( $tocData['main/datatypes'] ) ) {
1929  $tocnumber[$level]++;
1930  $tocData['main/datatypes'] = [
1931  'toclevel' => count( $tocnumber ),
1932  'level' => $level,
1933  'anchor' => 'main/datatypes',
1934  'line' => $header,
1935  'number' => implode( '.', $tocnumber ),
1936  'index' => false,
1937  ];
1938  }
1939 
1940  // Add an additional span with sanitized ID
1941  if ( !$this->getConfig()->get( 'ExperimentalHtmlIds' ) ) {
1942  $header = Html::element( 'span', [ 'id' => Sanitizer::escapeId( 'main/credits' ) ] ) .
1943  $header;
1944  }
1945  $header = $this->msg( 'api-credits-header' )->parse();
1946  $help['credits'] .= Html::rawElement( 'h' . min( 6, $level ),
1947  [ 'id' => 'main/credits', 'class' => 'apihelp-header' ],
1948  $header
1949  );
1950  $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
1951  if ( !isset( $tocData['main/credits'] ) ) {
1952  $tocnumber[$level]++;
1953  $tocData['main/credits'] = [
1954  'toclevel' => count( $tocnumber ),
1955  'level' => $level,
1956  'anchor' => 'main/credits',
1957  'line' => $header,
1958  'number' => implode( '.', $tocnumber ),
1959  'index' => false,
1960  ];
1961  }
1962  }
1963  }
1964 
1965  private $mCanApiHighLimits = null;
1966 
1971  public function canApiHighLimits() {
1972  if ( !isset( $this->mCanApiHighLimits ) ) {
1973  $this->mCanApiHighLimits = $this->getUser()->isAllowed( 'apihighlimits' );
1974  }
1975 
1976  return $this->mCanApiHighLimits;
1977  }
1978 
1983  public function getModuleManager() {
1984  return $this->mModuleMgr;
1985  }
1986 
1995  public function getUserAgent() {
1996  return trim(
1997  $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
1998  $this->getRequest()->getHeader( 'User-agent' )
1999  );
2000  }
2001 }
2002 
ApiUsageException\getStatusValue
getStatusValue()
Fetch the error status.
Definition: ApiUsageException.php:176
ApiMain\executeActionWithErrorHandling
executeActionWithErrorHandling()
Execute an action, and in case of an error, erase whatever partial results have been accumulated,...
Definition: ApiMain.php:524
MWTimestamp
Library for creating and parsing MW-style timestamps.
Definition: MWTimestamp.php:32
ApiMain
This is the main API class, used for both external and internal processing.
Definition: ApiMain.php:45
ContextSource\$context
IContextSource $context
Definition: ContextSource.php:34
ContextSource\getConfig
getConfig()
Get the Config object.
Definition: ContextSource.php:68
$wgUser
$wgUser
Definition: Setup.php:781
FauxRequest
WebRequest clone which takes values from a provided array.
Definition: FauxRequest.php:33
ApiUsageException
Exception used to abort API execution with an error.
Definition: ApiUsageException.php:98
ContextSource\getContext
getContext()
Get the base IContextSource object.
Definition: ContextSource.php:41
$request
error also a ContextSource you ll probably need to make sure the header is varied on $request
Definition: hooks.txt:2612
ApiMain\checkReadOnly
checkReadOnly( $module)
Check if the DB is read-only for this user.
Definition: ApiMain.php:1433
ApiBase\addWarning
addWarning( $msg, $code=null, $data=null)
Add a warning for this module.
Definition: ApiBase.php:1720
RequestContext\sanitizeLangCode
static sanitizeLangCode( $code)
Accepts a language code and ensures it's sane.
Definition: RequestContext.php:304
ApiMain\$mParamsSensitive
$mParamsSensitive
Definition: ApiMain.php:164
false
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:189
ApiMain\$mAction
$mAction
Definition: ApiMain.php:155
ApiErrorFormatter_BackCompat
Format errors and warnings in the old style, for backwards compatibility.
Definition: ApiErrorFormatter.php:362
ApiMain\$mSquidMaxage
$mSquidMaxage
Definition: ApiMain.php:157
ContextSource\msg
msg()
Get a Message object with context set Parameters are the same as wfMessage()
Definition: ContextSource.php:187
ApiMain\getParamsUsed
getParamsUsed()
Get the request parameters used in the course of the preceding execute() request.
Definition: ApiMain.php:1677
Profiler\instance
static instance()
Singleton.
Definition: Profiler.php:62
ApiMain\createErrorPrinter
createErrorPrinter()
Create the printer for error output.
Definition: ApiMain.php:984
ApiMain\getErrorFormatter
getErrorFormatter()
Get the ApiErrorFormatter object associated with current request.
Definition: ApiMain.php:358
ApiMain\getVal
getVal( $name, $default=null)
Get a request value, and register the fact that it was used, for logging.
Definition: ApiMain.php:1713
captcha-old.count
count
Definition: captcha-old.py:225
wfGetLB
wfGetLB( $wiki=false)
Get a load balancer object.
Definition: GlobalFunctions.php:3073
text
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add text
Definition: design.txt:12
ApiContinuationManager
This manages continuation state.
Definition: ApiContinuationManager.php:26
ApiBase\dieWithError
dieWithError( $msg, $code=null, $data=null, $httpCode=null)
Abort execution with an error.
Definition: ApiBase.php:1796
ApiMain\sendCacheHeaders
sendCacheHeaders( $isError)
Send caching headers.
Definition: ApiMain.php:866
$result
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetMagic':DEPRECATED! Use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language & $magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetSpecialPageAliases':DEPRECATED! Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language & $specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:1954
ApiMain\$Modules
static $Modules
List of available modules: action name => module class.
Definition: ApiMain.php:59
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1994
ApiBase\PARAM_TYPE
const PARAM_TYPE
(string|string[]) Either an array of allowed value strings, or a string type as described below.
Definition: ApiBase.php:91
ApiFormatBase
This is the abstract base class for API formatters.
Definition: ApiFormatBase.php:32
ApiMain\logRequest
logRequest( $time, $e=null)
Log the preceding request.
Definition: ApiMain.php:1604
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
wfUrlencode
wfUrlencode( $s)
We want some things to be included as literal characters in our title URLs for prettiness,...
Definition: GlobalFunctions.php:371
ApiMain\isReadMode
isReadMode()
Definition: ApiMain.php:1800
$user
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a account $user
Definition: hooks.txt:246
ApiMain\handleCORS
handleCORS()
Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
Definition: ApiMain.php:685
ApiMain\handleApiBeforeMainException
static handleApiBeforeMainException(Exception $e)
Handle an exception from the ApiBeforeMain hook.
Definition: ApiMain.php:653
ApiMain\checkConditionalRequestHeaders
checkConditionalRequestHeaders( $module)
Check selected RFC 7232 precondition headers.
Definition: ApiMain.php:1304
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:1933
$params
$params
Definition: styleTest.css.php:40
ApiMain\lacksSameOriginSecurity
lacksSameOriginSecurity()
Get the security flag for the current request.
Definition: ApiMain.php:323
wfHostname
wfHostname()
Fetch server name for use in error reporting etc.
Definition: GlobalFunctions.php:1435
wfReadOnly
wfReadOnly()
Check whether the wiki is in read-only mode.
Definition: GlobalFunctions.php:1277
User\newFromName
static newFromName( $name, $validate='valid')
Static factory method for creation from username.
Definition: User.php:556
$s
$s
Definition: mergeMessageFileList.php:188
ApiResult\NO_SIZE_CHECK
const NO_SIZE_CHECK
For addValue() and similar functions, do not check size while adding a value Don't use this unless yo...
Definition: ApiResult.php:56
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:304
ContextSource\getRequest
getRequest()
Get the WebRequest object.
Definition: ContextSource.php:78
User
User
Definition: All_system_messages.txt:425
$type
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached my talk my contributions etc etc otherwise the built in rate limiting checks are if enabled allows for interception of redirect as a string mapping parameter names to values & $type
Definition: hooks.txt:2536
ApiMain\encodeRequestLogValue
encodeRequestLogValue( $s)
Encode a value in a format suitable for a space-separated log line.
Definition: ApiMain.php:1660
ContextSource\getUser
getUser()
Get the User object.
Definition: ContextSource.php:133
ApiMain\getMaxLag
getMaxLag()
Definition: ApiMain.php:1226
$messages
$messages
Definition: LogTests.i18n.php:8
Wikimedia\Rdbms\DBError
Database error base class.
Definition: DBError.php:30
ApiMain\$mContinuationManager
ApiContinuationManager null $mContinuationManager
Definition: ApiMain.php:154
ApiMain\matchOrigin
static matchOrigin( $value, $rules, $exceptions)
Attempt to match an Origin header against a set of rules and a set of exceptions.
Definition: ApiMain.php:790
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:1092
ApiMain\$mRights
static $mRights
List of user roles that are specifically relevant to the API.
Definition: ApiMain.php:135
php
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
ApiBase
This abstract class implements many basic API functions, and is the base of all API classes.
Definition: ApiBase.php:41
ApiRawMessage
Extension of RawMessage implementing IApiMessage.
Definition: ApiMessage.php:268
ContextSource\getLanguage
getLanguage()
Get the Language object.
Definition: ContextSource.php:143
Html\closeElement
static closeElement( $element)
Returns "</$element>".
Definition: Html.php:309
ApiMain\getModule
getModule()
Get the API module object.
Definition: ApiMain.php:396
DerivativeContext
An IContextSource implementation which will inherit context from another source but allow individual ...
Definition: DerivativeContext.php:31
ApiMain\markParamsUsed
markParamsUsed( $params)
Mark parameters as used.
Definition: ApiMain.php:1685
MWException
MediaWiki exception.
Definition: MWException.php:26
ApiMain\setupExecuteAction
setupExecuteAction()
Set up for the execution.
Definition: ApiMain.php:1170
wfScript
wfScript( $script='index')
Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScri...
Definition: GlobalFunctions.php:3138
ApiResult
This class represents the result of the API operations.
Definition: ApiResult.php:33
ApiMain\setContinuationManager
setContinuationManager( $manager)
Set the continuation manager.
Definition: ApiMain.php:374
ApiMain\$mResult
$mResult
Definition: ApiMain.php:152
UsageException
This exception will be thrown when dieUsage is called to stop module execution.
Definition: ApiUsageException.php:28
ApiMain\$lacksSameOriginSecurity
bool null $lacksSameOriginSecurity
Cached return value from self::lacksSameOriginSecurity()
Definition: ApiMain.php:167
ContextSource\getOutput
getOutput()
Get the OutputPage object.
Definition: ContextSource.php:123
MWExceptionHandler\rollbackMasterChangesAndLog
static rollbackMasterChangesAndLog( $e)
Roll back any open database transactions and log the stack trace of the exception.
Definition: MWExceptionHandler.php:93
ApiMain\getResult
getResult()
Get the ApiResult object associated with current request.
Definition: ApiMain.php:315
ApiMain\getSensitiveParams
getSensitiveParams()
Get the request parameters that should be considered sensitive.
Definition: ApiMain.php:1694
MediaWiki
A helper class for throttling authentication attempts.
ApiMain\checkMaxLag
checkMaxLag( $module, $params)
Check the max lag if necessary.
Definition: ApiMain.php:1258
ApiMain\API_DEFAULT_USELANG
const API_DEFAULT_USELANG
When no uselang parameter is given, this language will be used.
Definition: ApiMain.php:54
ApiMain\getExamplesMessages
getExamplesMessages()
Definition: ApiMain.php:1858
ApiMain\setCacheControl
setCacheControl( $directives)
Set directives (key/value pairs) for the Cache-Control header.
Definition: ApiMain.php:487
$wgLang
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as $wgLang
Definition: design.txt:56
ApiMain\getAllowedParams
getAllowedParams()
See ApiBase for description.
Definition: ApiMain.php:1809
ApiMain\setupExternalResponse
setupExternalResponse( $module, $params)
Check POST for external response and setup result printer.
Definition: ApiMain.php:1514
$time
see documentation in includes Linker php for Linker::makeImageLink & $time
Definition: hooks.txt:1769
ApiMain\createPrinterByName
createPrinterByName( $format)
Create an instance of an output formatter by its name.
Definition: ApiMain.php:498
ApiMain\getModuleManager
getModuleManager()
Overrides to return this instance's module manager.
Definition: ApiMain.php:1983
global
when a variable name is used in a it is silently declared as a new masking the global
Definition: design.txt:93
ApiMain\$mCanApiHighLimits
$mCanApiHighLimits
Definition: ApiMain.php:1965
ApiMessage\create
static create( $msg, $code=null, array $data=null)
Create an IApiMessage for the message.
Definition: ApiMessage.php:212
ApiMain\matchRequestedHeaders
static matchRequestedHeaders( $requestedHeaders)
Attempt to validate the value of Access-Control-Request-Headers against a list of headers that we all...
Definition: ApiMain.php:814
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:999
ApiMain\addRequestedFields
addRequestedFields( $force=[])
Add requested fields to the result.
Definition: ApiMain.php:1139
ContextSource\setContext
setContext(IContextSource $context)
Set the IContextSource object.
Definition: ContextSource.php:58
ILocalizedException
Interface for MediaWiki-localized exceptions.
Definition: LocalizedException.php:27
ApiMain\canApiHighLimits
canApiHighLimits()
Check whether the current user is allowed to use high limits.
Definition: ApiMain.php:1971
ApiMain\$mPrinter
ApiFormatBase $mPrinter
Definition: ApiMain.php:150
Wikimedia\Rdbms\DBQueryError
Definition: DBQueryError.php:27
ApiMain\checkBotReadOnly
checkBotReadOnly()
Check whether we are readonly for bots.
Definition: ApiMain.php:1449
ApiMain\getContinuationManager
getContinuationManager()
Get the continuation manager.
Definition: ApiMain.php:366
ApiModuleManager
This class holds a list of modules and handles instantiation.
Definition: ApiModuleManager.php:34
ApiMain\checkAsserts
checkAsserts( $params)
Check asserts of the user's rights.
Definition: ApiMain.php:1483
wfWikiID
wfWikiID()
Get an ASCII string identifying this wiki This is used as a prefix in memcached keys.
Definition: GlobalFunctions.php:3011
ApiBase\extractRequestParams
extractRequestParams( $parseLimit=true)
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition: ApiBase.php:718
ApiMain\$mCacheMode
$mCacheMode
Definition: ApiMain.php:161
$e
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2122
MWDebug\appendDebugInfoToApiResult
static appendDebugInfoToApiResult(IContextSource $context, ApiResult $result)
Append the debug info to given ApiResult.
Definition: MWDebug.php:481
wfClearOutputBuffers
wfClearOutputBuffers()
More legible than passing a 'false' parameter to wfResetOutputBuffers():
Definition: GlobalFunctions.php:1856
ApiMain\$mErrorFormatter
$mErrorFormatter
Definition: ApiMain.php:152
ApiMain\$mInternalMode
$mInternalMode
Definition: ApiMain.php:157
$value
$value
Definition: styleTest.css.php:45
MediaWiki\preOutputCommit
static preOutputCommit(IContextSource $context, callable $postCommitWork=null)
This function commits all DB changes as needed before the user can receive a response (in case commit...
Definition: MediaWiki.php:583
ApiMain\wildcardToRegex
static wildcardToRegex( $wildcard)
Helper function to convert wildcard string into a regex '*' => '.
Definition: ApiMain.php:850
ApiMain\checkExecutePermissions
checkExecutePermissions( $module)
Check for sufficient permissions to execute.
Definition: ApiMain.php:1402
ApiBase\addDeprecation
addDeprecation( $msg, $feature, $data=[])
Add a deprecation warning for this module.
Definition: ApiBase.php:1734
$header
$header
Definition: updateCredits.php:35
ApiBase\LIMIT_SML2
const LIMIT_SML2
Slow query, apihighlimits limit.
Definition: ApiBase.php:209
ApiBase\dieReadOnly
dieReadOnly()
Helper function for readonly errors.
Definition: ApiBase.php:1874
ApiMain\__construct
__construct( $context=null, $enableWrite=false)
Constructs an instance of ApiMain that utilizes the module and format specified by $request.
Definition: ApiMain.php:176
ApiMain\reportUnusedParams
reportUnusedParams()
Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,...
Definition: ApiMain.php:1755
ApiMain\execute
execute()
Execute api request.
Definition: ApiMain.php:512
ApiBase\isWriteMode
isWriteMode()
Indicates whether this module requires write mode.
Definition: ApiBase.php:397
wfEscapeWikiText
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
Definition: GlobalFunctions.php:1657
$ret
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses & $ret
Definition: hooks.txt:1956
ApiMain\$Formats
static $Formats
List of available formats: format name => format class.
Definition: ApiMain.php:117
ApiMain\markParamsSensitive
markParamsSensitive( $params)
Mark parameters as sensitive.
Definition: ApiMain.php:1703
ApiMain\setRequestExpectations
setRequestExpectations(ApiBase $module)
Set database connection, query, and write expectations given this module request.
Definition: ApiMain.php:1585
ApiMain\substituteResultWithError
substituteResultWithError( $e)
Replace the result data with the information about an exception.
Definition: ApiMain.php:1059
RequestContext\getMain
static getMain()
Static methods.
Definition: RequestContext.php:468
ApiMain\getCheck
getCheck( $name)
Get a boolean request value, and register the fact that the parameter was used, for logging.
Definition: ApiMain.php:1734
ApiMain\printResult
printResult( $httpCode=0)
Print results using the current printer.
Definition: ApiMain.php:1783
$response
this hook is for auditing only $response
Definition: hooks.txt:783
WebRequest
The WebRequest class encapsulates getting at data passed in the URL or via a POSTed form stripping il...
Definition: WebRequest.php:38
ApiErrorFormatter
Formats errors and warnings for the API, and add them to the associated ApiResult.
Definition: ApiErrorFormatter.php:30
ApiMain\$mEnableWrite
$mEnableWrite
Definition: ApiMain.php:156
User\isEveryoneAllowed
static isEveryoneAllowed( $right)
Check if all users may be assumed to have the given permission.
Definition: User.php:4786
ApiBase\LIMIT_BIG2
const LIMIT_BIG2
Fast query, apihighlimits limit.
Definition: ApiBase.php:205
ApiMain\API_DEFAULT_FORMAT
const API_DEFAULT_FORMAT
When no format parameter is given, this format will be used.
Definition: ApiMain.php:49
WebRequest\GETHEADER_LIST
const GETHEADER_LIST
Flag to make WebRequest::getHeader return an array of values.
Definition: WebRequest.php:45
ApiMain\getUpload
getUpload( $name)
Get a request upload, and register the fact that it was used, for logging.
Definition: ApiMain.php:1745
$code
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable & $code
Definition: hooks.txt:783
ApiMain\modifyHelp
modifyHelp(array &$help, array $options, array &$tocData)
Called from ApiHelp before the pieces are joined together and returned.
Definition: ApiMain.php:1867
WebRequest\getRequestId
static getRequestId()
Get the unique request ID.
Definition: WebRequest.php:272
JobQueueGroup\singleton
static singleton( $wiki=false)
Definition: JobQueueGroup.php:71
$path
$path
Definition: NoLocalSettings.php:26
ApiBase\PARAM_DFLT
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
Definition: ApiBase.php:52
ApiBase\getParameter
getParameter( $paramName, $parseLimit=true)
Get a value for the given parameter.
Definition: ApiBase.php:742
as
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
Html\openElement
static openElement( $element, $attribs=[])
Identical to rawElement(), but has no third parameter and omits the end tag (and the self-closing '/'...
Definition: Html.php:251
Html\rawElement
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
Definition: Html.php:209
ApiMain\executeAction
executeAction()
Execute the actual module, without any error handling.
Definition: ApiMain.php:1541
$link
usually copyright or history_copyright This message must be in HTML not wikitext & $link
Definition: hooks.txt:2929
LoggerFactory
MediaWiki Logger LoggerFactory implements a PSR[0] compatible message logging system Named Psr Log LoggerInterface instances can be obtained from the MediaWiki Logger LoggerFactory::getInstance() static method. MediaWiki\Logger\LoggerFactory expects a class implementing the MediaWiki\Logger\Spi interface to act as a factory for new Psr\Log\LoggerInterface instances. The "Spi" in MediaWiki\Logger\Spi stands for "service provider interface". An SPI is an API intended to be implemented or extended by a third party. This software design pattern is intended to enable framework extension and replaceable components. It is specifically used in the MediaWiki\Logger\LoggerFactory service to allow alternate PSR-3 logging implementations to be easily integrated with MediaWiki. The service provider interface allows the backend logging library to be implemented in multiple ways. The $wgMWLoggerDefaultSpi global provides the classname of the default MediaWiki\Logger\Spi implementation to be loaded at runtime. This can either be the name of a class implementing the MediaWiki\Logger\Spi with a zero argument const ructor or a callable that will return an MediaWiki\Logger\Spi instance. Alternately the MediaWiki\Logger\LoggerFactory MediaWiki Logger LoggerFactory
Definition: logger.txt:5
ApiMain\setupModule
setupModule()
Set up the module for response.
Definition: ApiMain.php:1185
true
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return true
Definition: hooks.txt:1956
$help
$help
Definition: mcc.php:32
Language\factory
static factory( $code)
Get a cached or new language object for a given language code.
Definition: Language.php:183
ApiMain\$mCacheControl
$mCacheControl
Definition: ApiMain.php:162
$t
$t
Definition: testCompression.php:67
ApiMain\handleException
handleException(Exception $e)
Handle an exception as an API response.
Definition: ApiMain.php:579
Html\element
static element( $element, $attribs=[], $contents='')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
Definition: Html.php:231
ApiMain\isInternalMode
isInternalMode()
Return true if the API was started by other PHP code using FauxRequest.
Definition: ApiMain.php:306
ApiMain\$mParamsUsed
$mParamsUsed
Definition: ApiMain.php:163
MediaWikiServices
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency MediaWikiServices
Definition: injection.txt:23
ApiMain\$mModuleMgr
$mModuleMgr
Definition: ApiMain.php:152
ApiMain\getUserAgent
getUserAgent()
Fetches the user agent used for this request.
Definition: ApiMain.php:1995
ApiMain\setCacheMaxAge
setCacheMaxAge( $maxage)
Set how long the response should be cached.
Definition: ApiMain.php:414
Hooks\run
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:131
ApiMain\errorMessagesFromException
errorMessagesFromException( $e, $type='error')
Create an error message for the given exception.
Definition: ApiMain.php:1018
ApiFormatBase\initPrinter
initPrinter( $unused=false)
Initialize the printer function and prepare the output headers.
Definition: ApiFormatBase.php:192
MWExceptionHandler\getRedactedTraceAsString
static getRedactedTraceAsString( $e)
Generate a string representation of an exception's stack trace.
Definition: MWExceptionHandler.php:313
ApiMain\setCacheMode
setCacheMode( $mode)
Set the type of caching headers which will be sent.
Definition: ApiMain.php:446
$options
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing you specify which group they belong to You can reuse existing or create your you must register them with $special registerFilterGroup removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context $options
Definition: hooks.txt:1049
ApiMain\getPrinter
getPrinter()
Get the result formatter object.
Definition: ApiMain.php:405
wfExpandUrl
wfExpandUrl( $url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.
Definition: GlobalFunctions.php:552
array
the array() calling protocol came about after MediaWiki 1.4rc1.
User\getGroupsWithPermission
static getGroupsWithPermission( $role)
Get all the groups who have a given permission.
Definition: User.php:4743
$wgContLang
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as and the content language as $wgContLang
Definition: design.txt:56
$out
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output $out
Definition: hooks.txt:783
ApiMain\$mModule
ApiBase $mModule
Definition: ApiMain.php:159