MediaWiki  1.27.1
ApiMain.php
Go to the documentation of this file.
1 <?php
41 class ApiMain extends ApiBase {
45  const API_DEFAULT_FORMAT = 'jsonfm';
46 
50  private static $Modules = [
51  'login' => 'ApiLogin',
52  'clientlogin' => 'ApiClientLogin',
53  'logout' => 'ApiLogout',
54  'createaccount' => 'ApiAMCreateAccount',
55  'linkaccount' => 'ApiLinkAccount',
56  'unlinkaccount' => 'ApiRemoveAuthenticationData',
57  'changeauthenticationdata' => 'ApiChangeAuthenticationData',
58  'removeauthenticationdata' => 'ApiRemoveAuthenticationData',
59  'resetpassword' => 'ApiResetPassword',
60  'query' => 'ApiQuery',
61  'expandtemplates' => 'ApiExpandTemplates',
62  'parse' => 'ApiParse',
63  'stashedit' => 'ApiStashEdit',
64  'opensearch' => 'ApiOpenSearch',
65  'feedcontributions' => 'ApiFeedContributions',
66  'feedrecentchanges' => 'ApiFeedRecentChanges',
67  'feedwatchlist' => 'ApiFeedWatchlist',
68  'help' => 'ApiHelp',
69  'paraminfo' => 'ApiParamInfo',
70  'rsd' => 'ApiRsd',
71  'compare' => 'ApiComparePages',
72  'tokens' => 'ApiTokens',
73  'checktoken' => 'ApiCheckToken',
74 
75  // Write modules
76  'purge' => 'ApiPurge',
77  'setnotificationtimestamp' => 'ApiSetNotificationTimestamp',
78  'rollback' => 'ApiRollback',
79  'delete' => 'ApiDelete',
80  'undelete' => 'ApiUndelete',
81  'protect' => 'ApiProtect',
82  'block' => 'ApiBlock',
83  'unblock' => 'ApiUnblock',
84  'move' => 'ApiMove',
85  'edit' => 'ApiEditPage',
86  'upload' => 'ApiUpload',
87  'filerevert' => 'ApiFileRevert',
88  'emailuser' => 'ApiEmailUser',
89  'watch' => 'ApiWatch',
90  'patrol' => 'ApiPatrol',
91  'import' => 'ApiImport',
92  'clearhasmsg' => 'ApiClearHasMsg',
93  'userrights' => 'ApiUserrights',
94  'options' => 'ApiOptions',
95  'imagerotate' => 'ApiImageRotate',
96  'revisiondelete' => 'ApiRevisionDelete',
97  'managetags' => 'ApiManageTags',
98  'tag' => 'ApiTag',
99  'mergehistory' => 'ApiMergeHistory',
100  ];
101 
105  private static $Formats = [
106  'json' => 'ApiFormatJson',
107  'jsonfm' => 'ApiFormatJson',
108  'php' => 'ApiFormatPhp',
109  'phpfm' => 'ApiFormatPhp',
110  'xml' => 'ApiFormatXml',
111  'xmlfm' => 'ApiFormatXml',
112  'rawfm' => 'ApiFormatJson',
113  'none' => 'ApiFormatNone',
114  ];
115 
116  // @codingStandardsIgnoreStart String contenation on "msg" not allowed to break long line
123  private static $mRights = [
124  'writeapi' => [
125  'msg' => 'right-writeapi',
126  'params' => []
127  ],
128  'apihighlimits' => [
129  'msg' => 'api-help-right-apihighlimits',
131  ]
132  ];
133  // @codingStandardsIgnoreEnd
134 
138  private $mPrinter;
139 
141  private $mAction;
142  private $mEnableWrite;
144 
145  private $mCacheMode = 'private';
146  private $mCacheControl = [];
147  private $mParamsUsed = [];
148 
150  private $lacksSameOriginSecurity = null;
151 
159  public function __construct( $context = null, $enableWrite = false ) {
160  if ( $context === null ) {
162  } elseif ( $context instanceof WebRequest ) {
163  // BC for pre-1.19
164  $request = $context;
166  }
167  // We set a derivative context so we can change stuff later
168  $this->setContext( new DerivativeContext( $context ) );
169 
170  if ( isset( $request ) ) {
171  $this->getContext()->setRequest( $request );
172  }
173 
174  $this->mInternalMode = ( $this->getRequest() instanceof FauxRequest );
175 
176  // Special handling for the main module: $parent === $this
177  parent::__construct( $this, $this->mInternalMode ? 'main_int' : 'main' );
178 
179  if ( !$this->mInternalMode ) {
180  // Impose module restrictions.
181  // If the current user cannot read,
182  // Remove all modules other than login
183  global $wgUser;
184 
185  if ( $this->lacksSameOriginSecurity() ) {
186  // If we're in a mode that breaks the same-origin policy, strip
187  // user credentials for security.
188  wfDebug( "API: stripping user credentials when the same-origin policy is not applied\n" );
189  $wgUser = new User();
190  $this->getContext()->setUser( $wgUser );
191  }
192  }
193 
194  $uselang = $this->getParameter( 'uselang' );
195  if ( $uselang === 'user' ) {
196  // Assume the parent context is going to return the user language
197  // for uselang=user (see T85635).
198  } else {
199  if ( $uselang === 'content' ) {
201  $uselang = $wgContLang->getCode();
202  }
204  $this->getContext()->setLanguage( $code );
205  if ( !$this->mInternalMode ) {
206  global $wgLang;
207  $wgLang = $this->getContext()->getLanguage();
208  RequestContext::getMain()->setLanguage( $wgLang );
209  }
210  }
211 
212  $config = $this->getConfig();
213  $this->mModuleMgr = new ApiModuleManager( $this );
214  $this->mModuleMgr->addModules( self::$Modules, 'action' );
215  $this->mModuleMgr->addModules( $config->get( 'APIModules' ), 'action' );
216  $this->mModuleMgr->addModules( self::$Formats, 'format' );
217  $this->mModuleMgr->addModules( $config->get( 'APIFormatModules' ), 'format' );
218 
219  Hooks::run( 'ApiMain::moduleManager', [ $this->mModuleMgr ] );
220 
221  $this->mResult = new ApiResult( $this->getConfig()->get( 'APIMaxResultSize' ) );
222  $this->mErrorFormatter = new ApiErrorFormatter_BackCompat( $this->mResult );
223  $this->mResult->setErrorFormatter( $this->mErrorFormatter );
224  $this->mResult->setMainForContinuation( $this );
225  $this->mContinuationManager = null;
226  $this->mEnableWrite = $enableWrite;
227 
228  $this->mSquidMaxage = -1; // flag for executeActionWithErrorHandling()
229  $this->mCommit = false;
230  }
231 
236  public function isInternalMode() {
237  return $this->mInternalMode;
238  }
239 
245  public function getResult() {
246  return $this->mResult;
247  }
248 
253  public function lacksSameOriginSecurity() {
254  if ( $this->lacksSameOriginSecurity !== null ) {
256  }
257 
258  $request = $this->getRequest();
259 
260  // JSONP mode
261  if ( $request->getVal( 'callback' ) !== null ) {
262  $this->lacksSameOriginSecurity = true;
263  return true;
264  }
265 
266  // Header to be used from XMLHTTPRequest when the request might
267  // otherwise be used for XSS.
268  if ( $request->getHeader( 'Treat-as-Untrusted' ) !== false ) {
269  $this->lacksSameOriginSecurity = true;
270  return true;
271  }
272 
273  // Allow extensions to override.
274  $this->lacksSameOriginSecurity = !Hooks::run( 'RequestHasSameOriginSecurity', [ $request ] );
276  }
277 
282  public function getErrorFormatter() {
283  return $this->mErrorFormatter;
284  }
285 
290  public function getContinuationManager() {
292  }
293 
298  public function setContinuationManager( $manager ) {
299  if ( $manager !== null ) {
300  if ( !$manager instanceof ApiContinuationManager ) {
301  throw new InvalidArgumentException( __METHOD__ . ': Was passed ' .
302  is_object( $manager ) ? get_class( $manager ) : gettype( $manager )
303  );
304  }
305  if ( $this->mContinuationManager !== null ) {
306  throw new UnexpectedValueException(
307  __METHOD__ . ': tried to set manager from ' . $manager->getSource() .
308  ' when a manager is already set from ' . $this->mContinuationManager->getSource()
309  );
310  }
311  }
312  $this->mContinuationManager = $manager;
313  }
314 
320  public function getModule() {
321  return $this->mModule;
322  }
323 
329  public function getPrinter() {
330  return $this->mPrinter;
331  }
332 
338  public function setCacheMaxAge( $maxage ) {
339  $this->setCacheControl( [
340  'max-age' => $maxage,
341  's-maxage' => $maxage
342  ] );
343  }
344 
370  public function setCacheMode( $mode ) {
371  if ( !in_array( $mode, [ 'private', 'public', 'anon-public-user-private' ] ) ) {
372  wfDebug( __METHOD__ . ": unrecognised cache mode \"$mode\"\n" );
373 
374  // Ignore for forwards-compatibility
375  return;
376  }
377 
378  if ( !User::isEveryoneAllowed( 'read' ) ) {
379  // Private wiki, only private headers
380  if ( $mode !== 'private' ) {
381  wfDebug( __METHOD__ . ": ignoring request for $mode cache mode, private wiki\n" );
382 
383  return;
384  }
385  }
386 
387  if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) {
388  // User language is used for i18n, so we don't want to publicly
389  // cache. Anons are ok, because if they have non-default language
390  // then there's an appropriate Vary header set by whatever set
391  // their non-default language.
392  wfDebug( __METHOD__ . ": downgrading cache mode 'public' to " .
393  "'anon-public-user-private' due to uselang=user\n" );
394  $mode = 'anon-public-user-private';
395  }
396 
397  wfDebug( __METHOD__ . ": setting cache mode $mode\n" );
398  $this->mCacheMode = $mode;
399  }
400 
411  public function setCacheControl( $directives ) {
412  $this->mCacheControl = $directives + $this->mCacheControl;
413  }
414 
422  public function createPrinterByName( $format ) {
423  $printer = $this->mModuleMgr->getModule( $format, 'format' );
424  if ( $printer === null ) {
425  $this->dieUsage( "Unrecognized format: {$format}", 'unknown_format' );
426  }
427 
428  return $printer;
429  }
430 
434  public function execute() {
435  if ( $this->mInternalMode ) {
436  $this->executeAction();
437  } else {
438  $start = microtime( true );
440  if ( $this->isWriteMode() && $this->getRequest()->wasPosted() ) {
441  $timeMs = 1000 * max( 0, microtime( true ) - $start );
442  $this->getStats()->timing(
443  'api.' . $this->getModuleName() . '.executeTiming', $timeMs );
444  }
445  }
446  }
447 
452  protected function executeActionWithErrorHandling() {
453  // Verify the CORS header before executing the action
454  if ( !$this->handleCORS() ) {
455  // handleCORS() has sent a 403, abort
456  return;
457  }
458 
459  // Exit here if the request method was OPTIONS
460  // (assume there will be a followup GET or POST)
461  if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
462  return;
463  }
464 
465  // In case an error occurs during data output,
466  // clear the output buffer and print just the error information
467  $obLevel = ob_get_level();
468  ob_start();
469 
470  $t = microtime( true );
471  $isError = false;
472  try {
473  $this->executeAction();
474  $this->logRequest( microtime( true ) - $t );
475 
476  } catch ( Exception $e ) {
477  $this->handleException( $e );
478  $this->logRequest( microtime( true ) - $t, $e );
479  $isError = true;
480  }
481 
482  // Commit DBs and send any related cookies and headers
484 
485  // Send cache headers after any code which might generate an error, to
486  // avoid sending public cache headers for errors.
487  $this->sendCacheHeaders( $isError );
488 
489  // Executing the action might have already messed with the output
490  // buffers.
491  while ( ob_get_level() > $obLevel ) {
492  ob_end_flush();
493  }
494  }
495 
502  protected function handleException( Exception $e ) {
503  // Bug 63145: Rollback any open database transactions
504  if ( !( $e instanceof UsageException ) ) {
505  // UsageExceptions are intentional, so don't rollback if that's the case
506  try {
508  } catch ( DBError $e2 ) {
509  // Rollback threw an exception too. Log it, but don't interrupt
510  // our regularly scheduled exception handling.
512  }
513  }
514 
515  // Allow extra cleanup and logging
516  Hooks::run( 'ApiMain::onException', [ $this, $e ] );
517 
518  // Log it
519  if ( !( $e instanceof UsageException ) ) {
521  }
522 
523  // Handle any kind of exception by outputting properly formatted error message.
524  // If this fails, an unhandled exception should be thrown so that global error
525  // handler will process and log it.
526 
527  $errCode = $this->substituteResultWithError( $e );
528 
529  // Error results should not be cached
530  $this->setCacheMode( 'private' );
531 
532  $response = $this->getRequest()->response();
533  $headerStr = 'MediaWiki-API-Error: ' . $errCode;
534  if ( $e->getCode() === 0 ) {
535  $response->header( $headerStr );
536  } else {
537  $response->header( $headerStr, true, $e->getCode() );
538  }
539 
540  // Reset and print just the error message
541  ob_clean();
542 
543  // Printer may not be initialized if the extractRequestParams() fails for the main module
544  $this->createErrorPrinter();
545 
546  try {
547  $this->printResult( true );
548  } catch ( UsageException $ex ) {
549  // The error printer itself is failing. Try suppressing its request
550  // parameters and redo.
551  $this->setWarning(
552  'Error printer failed (will retry without params): ' . $ex->getMessage()
553  );
554  $this->mPrinter = null;
555  $this->createErrorPrinter();
556  $this->mPrinter->forceDefaultParams();
557  $this->printResult( true );
558  }
559  }
560 
571  public static function handleApiBeforeMainException( Exception $e ) {
572  ob_start();
573 
574  try {
575  $main = new self( RequestContext::getMain(), false );
576  $main->handleException( $e );
577  $main->logRequest( 0, $e );
578  } catch ( Exception $e2 ) {
579  // Nope, even that didn't work. Punt.
580  throw $e;
581  }
582 
583  // Reset cache headers
584  $main->sendCacheHeaders( true );
585 
586  ob_end_flush();
587  }
588 
603  protected function handleCORS() {
604  $originParam = $this->getParameter( 'origin' ); // defaults to null
605  if ( $originParam === null ) {
606  // No origin parameter, nothing to do
607  return true;
608  }
609 
610  $request = $this->getRequest();
611  $response = $request->response();
612 
613  // Origin: header is a space-separated list of origins, check all of them
614  $originHeader = $request->getHeader( 'Origin' );
615  if ( $originHeader === false ) {
616  $origins = [];
617  } else {
618  $originHeader = trim( $originHeader );
619  $origins = preg_split( '/\s+/', $originHeader );
620  }
621 
622  if ( !in_array( $originParam, $origins ) ) {
623  // origin parameter set but incorrect
624  // Send a 403 response
625  $response->statusHeader( 403 );
626  $response->header( 'Cache-Control: no-cache' );
627  echo "'origin' parameter does not match Origin header\n";
628 
629  return false;
630  }
631 
632  $config = $this->getConfig();
633  $matchOrigin = count( $origins ) === 1 && self::matchOrigin(
634  $originParam,
635  $config->get( 'CrossSiteAJAXdomains' ),
636  $config->get( 'CrossSiteAJAXdomainExceptions' )
637  );
638 
639  if ( $matchOrigin ) {
640  $requestedMethod = $request->getHeader( 'Access-Control-Request-Method' );
641  $preflight = $request->getMethod() === 'OPTIONS' && $requestedMethod !== false;
642  if ( $preflight ) {
643  // This is a CORS preflight request
644  if ( $requestedMethod !== 'POST' && $requestedMethod !== 'GET' ) {
645  // If method is not a case-sensitive match, do not set any additional headers and terminate.
646  return true;
647  }
648  // We allow the actual request to send the following headers
649  $requestedHeaders = $request->getHeader( 'Access-Control-Request-Headers' );
650  if ( $requestedHeaders !== false ) {
651  if ( !self::matchRequestedHeaders( $requestedHeaders ) ) {
652  return true;
653  }
654  $response->header( 'Access-Control-Allow-Headers: ' . $requestedHeaders );
655  }
656 
657  // We only allow the actual request to be GET or POST
658  $response->header( 'Access-Control-Allow-Methods: POST, GET' );
659  }
660 
661  $response->header( "Access-Control-Allow-Origin: $originHeader" );
662  $response->header( 'Access-Control-Allow-Credentials: true' );
663  // http://www.w3.org/TR/resource-timing/#timing-allow-origin
664  $response->header( "Timing-Allow-Origin: $originHeader" );
665 
666  if ( !$preflight ) {
667  $response->header(
668  'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag'
669  );
670  }
671  }
672 
673  $this->getOutput()->addVaryHeader( 'Origin' );
674  return true;
675  }
676 
685  protected static function matchOrigin( $value, $rules, $exceptions ) {
686  foreach ( $rules as $rule ) {
687  if ( preg_match( self::wildcardToRegex( $rule ), $value ) ) {
688  // Rule matches, check exceptions
689  foreach ( $exceptions as $exc ) {
690  if ( preg_match( self::wildcardToRegex( $exc ), $value ) ) {
691  return false;
692  }
693  }
694 
695  return true;
696  }
697  }
698 
699  return false;
700  }
701 
709  protected static function matchRequestedHeaders( $requestedHeaders ) {
710  if ( trim( $requestedHeaders ) === '' ) {
711  return true;
712  }
713  $requestedHeaders = explode( ',', $requestedHeaders );
714  $allowedAuthorHeaders = array_flip( [
715  /* simple headers (see spec) */
716  'accept',
717  'accept-language',
718  'content-language',
719  'content-type',
720  /* non-authorable headers in XHR, which are however requested by some UAs */
721  'accept-encoding',
722  'dnt',
723  'origin',
724  /* MediaWiki whitelist */
725  'api-user-agent',
726  ] );
727  foreach ( $requestedHeaders as $rHeader ) {
728  $rHeader = strtolower( trim( $rHeader ) );
729  if ( !isset( $allowedAuthorHeaders[$rHeader] ) ) {
730  wfDebugLog( 'api', 'CORS preflight failed on requested header: ' . $rHeader );
731  return false;
732  }
733  }
734  return true;
735  }
736 
745  protected static function wildcardToRegex( $wildcard ) {
746  $wildcard = preg_quote( $wildcard, '/' );
747  $wildcard = str_replace(
748  [ '\*', '\?' ],
749  [ '.*?', '.' ],
750  $wildcard
751  );
752 
753  return "/^https?:\/\/$wildcard$/";
754  }
755 
761  protected function sendCacheHeaders( $isError ) {
762  $response = $this->getRequest()->response();
763  $out = $this->getOutput();
764 
765  $out->addVaryHeader( 'Treat-as-Untrusted' );
766 
767  $config = $this->getConfig();
768 
769  if ( $config->get( 'VaryOnXFP' ) ) {
770  $out->addVaryHeader( 'X-Forwarded-Proto' );
771  }
772 
773  if ( !$isError && $this->mModule &&
774  ( $this->getRequest()->getMethod() === 'GET' || $this->getRequest()->getMethod() === 'HEAD' )
775  ) {
776  $etag = $this->mModule->getConditionalRequestData( 'etag' );
777  if ( $etag !== null ) {
778  $response->header( "ETag: $etag" );
779  }
780  $lastMod = $this->mModule->getConditionalRequestData( 'last-modified' );
781  if ( $lastMod !== null ) {
782  $response->header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822, $lastMod ) );
783  }
784  }
785 
786  // The logic should be:
787  // $this->mCacheControl['max-age'] is set?
788  // Use it, the module knows better than our guess.
789  // !$this->mModule || $this->mModule->isWriteMode(), and mCacheMode is private?
790  // Use 0 because we can guess caching is probably the wrong thing to do.
791  // Use $this->getParameter( 'maxage' ), which already defaults to 0.
792  $maxage = 0;
793  if ( isset( $this->mCacheControl['max-age'] ) ) {
794  $maxage = $this->mCacheControl['max-age'];
795  } elseif ( ( $this->mModule && !$this->mModule->isWriteMode() ) ||
796  $this->mCacheMode !== 'private'
797  ) {
798  $maxage = $this->getParameter( 'maxage' );
799  }
800  $privateCache = 'private, must-revalidate, max-age=' . $maxage;
801 
802  if ( $this->mCacheMode == 'private' ) {
803  $response->header( "Cache-Control: $privateCache" );
804  return;
805  }
806 
807  $useKeyHeader = $config->get( 'UseKeyHeader' );
808  if ( $this->mCacheMode == 'anon-public-user-private' ) {
809  $out->addVaryHeader( 'Cookie' );
810  $response->header( $out->getVaryHeader() );
811  if ( $useKeyHeader ) {
812  $response->header( $out->getKeyHeader() );
813  if ( $out->haveCacheVaryCookies() ) {
814  // Logged in, mark this request private
815  $response->header( "Cache-Control: $privateCache" );
816  return;
817  }
818  // Logged out, send normal public headers below
819  } elseif ( MediaWiki\Session\SessionManager::getGlobalSession()->isPersistent() ) {
820  // Logged in or otherwise has session (e.g. anonymous users who have edited)
821  // Mark request private
822  $response->header( "Cache-Control: $privateCache" );
823 
824  return;
825  } // else no Key and anonymous, send public headers below
826  }
827 
828  // Send public headers
829  $response->header( $out->getVaryHeader() );
830  if ( $useKeyHeader ) {
831  $response->header( $out->getKeyHeader() );
832  }
833 
834  // If nobody called setCacheMaxAge(), use the (s)maxage parameters
835  if ( !isset( $this->mCacheControl['s-maxage'] ) ) {
836  $this->mCacheControl['s-maxage'] = $this->getParameter( 'smaxage' );
837  }
838  if ( !isset( $this->mCacheControl['max-age'] ) ) {
839  $this->mCacheControl['max-age'] = $this->getParameter( 'maxage' );
840  }
841 
842  if ( !$this->mCacheControl['s-maxage'] && !$this->mCacheControl['max-age'] ) {
843  // Public cache not requested
844  // Sending a Vary header in this case is harmless, and protects us
845  // against conditional calls of setCacheMaxAge().
846  $response->header( "Cache-Control: $privateCache" );
847 
848  return;
849  }
850 
851  $this->mCacheControl['public'] = true;
852 
853  // Send an Expires header
854  $maxAge = min( $this->mCacheControl['s-maxage'], $this->mCacheControl['max-age'] );
855  $expiryUnixTime = ( $maxAge == 0 ? 1 : time() + $maxAge );
856  $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822, $expiryUnixTime ) );
857 
858  // Construct the Cache-Control header
859  $ccHeader = '';
860  $separator = '';
861  foreach ( $this->mCacheControl as $name => $value ) {
862  if ( is_bool( $value ) ) {
863  if ( $value ) {
864  $ccHeader .= $separator . $name;
865  $separator = ', ';
866  }
867  } else {
868  $ccHeader .= $separator . "$name=$value";
869  $separator = ', ';
870  }
871  }
872 
873  $response->header( "Cache-Control: $ccHeader" );
874  }
875 
879  private function createErrorPrinter() {
880  if ( !isset( $this->mPrinter ) ) {
881  $value = $this->getRequest()->getVal( 'format', self::API_DEFAULT_FORMAT );
882  if ( !$this->mModuleMgr->isDefined( $value, 'format' ) ) {
883  $value = self::API_DEFAULT_FORMAT;
884  }
885  $this->mPrinter = $this->createPrinterByName( $value );
886  }
887 
888  // Printer may not be able to handle errors. This is particularly
889  // likely if the module returns something for getCustomPrinter().
890  if ( !$this->mPrinter->canPrintErrors() ) {
891  $this->mPrinter = $this->createPrinterByName( self::API_DEFAULT_FORMAT );
892  }
893  }
894 
905  protected function errorMessageFromException( $e ) {
906  if ( $e instanceof UsageException ) {
907  // User entered incorrect parameters - generate error response
908  $errMessage = $e->getMessageArray();
909  } else {
910  $config = $this->getConfig();
911  // Something is seriously wrong
912  if ( ( $e instanceof DBQueryError ) && !$config->get( 'ShowSQLErrors' ) ) {
913  $info = 'Database query error';
914  } else {
915  $info = "Exception Caught: {$e->getMessage()}";
916  }
917 
918  $errMessage = [
919  'code' => 'internal_api_error_' . get_class( $e ),
920  'info' => '[' . WebRequest::getRequestId() . '] ' . $info,
921  ];
922  }
923  return $errMessage;
924  }
925 
932  protected function substituteResultWithError( $e ) {
933  $result = $this->getResult();
934  $config = $this->getConfig();
935 
936  $errMessage = $this->errorMessageFromException( $e );
937  if ( $e instanceof UsageException ) {
938  // User entered incorrect parameters - generate error response
939  $link = wfExpandUrl( wfScript( 'api' ) );
940  ApiResult::setContentValue( $errMessage, 'docref', "See $link for API usage" );
941  } else {
942  // Something is seriously wrong
943  if ( $config->get( 'ShowExceptionDetails' ) ) {
945  $errMessage,
946  'trace',
948  );
949  }
950  }
951 
952  // Remember all the warnings to re-add them later
953  $warnings = $result->getResultData( [ 'warnings' ] );
954 
955  $result->reset();
956  // Re-add the id
957  $requestid = $this->getParameter( 'requestid' );
958  if ( !is_null( $requestid ) ) {
959  $result->addValue( null, 'requestid', $requestid, ApiResult::NO_SIZE_CHECK );
960  }
961  if ( $config->get( 'ShowHostnames' ) ) {
962  // servedby is especially useful when debugging errors
963  $result->addValue( null, 'servedby', wfHostname(), ApiResult::NO_SIZE_CHECK );
964  }
965  if ( $warnings !== null ) {
966  $result->addValue( null, 'warnings', $warnings, ApiResult::NO_SIZE_CHECK );
967  }
968 
969  $result->addValue( null, 'error', $errMessage, ApiResult::NO_SIZE_CHECK );
970 
971  return $errMessage['code'];
972  }
973 
978  protected function setupExecuteAction() {
979  // First add the id to the top element
980  $result = $this->getResult();
981  $requestid = $this->getParameter( 'requestid' );
982  if ( !is_null( $requestid ) ) {
983  $result->addValue( null, 'requestid', $requestid );
984  }
985 
986  if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
987  $servedby = $this->getParameter( 'servedby' );
988  if ( $servedby ) {
989  $result->addValue( null, 'servedby', wfHostname() );
990  }
991  }
992 
993  if ( $this->getParameter( 'curtimestamp' ) ) {
994  $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601, time() ),
996  }
997 
998  $params = $this->extractRequestParams();
999 
1000  $this->mAction = $params['action'];
1001 
1002  if ( !is_string( $this->mAction ) ) {
1003  $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
1004  }
1005 
1006  return $params;
1007  }
1008 
1015  protected function setupModule() {
1016  // Instantiate the module requested by the user
1017  $module = $this->mModuleMgr->getModule( $this->mAction, 'action' );
1018  if ( $module === null ) {
1019  $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
1020  }
1021  $moduleParams = $module->extractRequestParams();
1022 
1023  // Check token, if necessary
1024  if ( $module->needsToken() === true ) {
1025  throw new MWException(
1026  "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
1027  'See documentation for ApiBase::needsToken for details.'
1028  );
1029  }
1030  if ( $module->needsToken() ) {
1031  if ( !$module->mustBePosted() ) {
1032  throw new MWException(
1033  "Module '{$module->getModuleName()}' must require POST to use tokens."
1034  );
1035  }
1036 
1037  if ( !isset( $moduleParams['token'] ) ) {
1038  $this->dieUsageMsg( [ 'missingparam', 'token' ] );
1039  }
1040 
1041  if ( !$this->getConfig()->get( 'DebugAPI' ) &&
1042  array_key_exists(
1043  $module->encodeParamName( 'token' ),
1044  $this->getRequest()->getQueryValues()
1045  )
1046  ) {
1047  $this->dieUsage(
1048  "The '{$module->encodeParamName( 'token' )}' parameter was " .
1049  'found in the query string, but must be in the POST body',
1050  'mustposttoken'
1051  );
1052  }
1053 
1054  if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) {
1055  $this->dieUsageMsg( 'sessionfailure' );
1056  }
1057  }
1058 
1059  return $module;
1060  }
1061 
1068  protected function checkMaxLag( $module, $params ) {
1069  if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
1070  $maxLag = $params['maxlag'];
1071  list( $host, $lag ) = wfGetLB()->getMaxLag();
1072  if ( $lag > $maxLag ) {
1073  $response = $this->getRequest()->response();
1074 
1075  $response->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
1076  $response->header( 'X-Database-Lag: ' . intval( $lag ) );
1077 
1078  if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
1079  $this->dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
1080  }
1081 
1082  $this->dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
1083  }
1084  }
1085 
1086  return true;
1087  }
1088 
1110  protected function checkConditionalRequestHeaders( $module ) {
1111  if ( $this->mInternalMode ) {
1112  // No headers to check in internal mode
1113  return true;
1114  }
1115 
1116  if ( $this->getRequest()->getMethod() !== 'GET' && $this->getRequest()->getMethod() !== 'HEAD' ) {
1117  // Don't check POSTs
1118  return true;
1119  }
1120 
1121  $return304 = false;
1122 
1123  $ifNoneMatch = array_diff(
1124  $this->getRequest()->getHeader( 'If-None-Match', WebRequest::GETHEADER_LIST ) ?: [],
1125  [ '' ]
1126  );
1127  if ( $ifNoneMatch ) {
1128  if ( $ifNoneMatch === [ '*' ] ) {
1129  // API responses always "exist"
1130  $etag = '*';
1131  } else {
1132  $etag = $module->getConditionalRequestData( 'etag' );
1133  }
1134  }
1135  if ( $ifNoneMatch && $etag !== null ) {
1136  $test = substr( $etag, 0, 2 ) === 'W/' ? substr( $etag, 2 ) : $etag;
1137  $match = array_map( function ( $s ) {
1138  return substr( $s, 0, 2 ) === 'W/' ? substr( $s, 2 ) : $s;
1139  }, $ifNoneMatch );
1140  $return304 = in_array( $test, $match, true );
1141  } else {
1142  $value = trim( $this->getRequest()->getHeader( 'If-Modified-Since' ) );
1143 
1144  // Some old browsers sends sizes after the date, like this:
1145  // Wed, 20 Aug 2003 06:51:19 GMT; length=5202
1146  // Ignore that.
1147  $i = strpos( $value, ';' );
1148  if ( $i !== false ) {
1149  $value = trim( substr( $value, 0, $i ) );
1150  }
1151 
1152  if ( $value !== '' ) {
1153  try {
1154  $ts = new MWTimestamp( $value );
1155  if (
1156  // RFC 7231 IMF-fixdate
1157  $ts->getTimestamp( TS_RFC2822 ) === $value ||
1158  // RFC 850
1159  $ts->format( 'l, d-M-y H:i:s' ) . ' GMT' === $value ||
1160  // asctime (with and without space-padded day)
1161  $ts->format( 'D M j H:i:s Y' ) === $value ||
1162  $ts->format( 'D M j H:i:s Y' ) === $value
1163  ) {
1164  $lastMod = $module->getConditionalRequestData( 'last-modified' );
1165  if ( $lastMod !== null ) {
1166  // Mix in some MediaWiki modification times
1167  $modifiedTimes = [
1168  'page' => $lastMod,
1169  'user' => $this->getUser()->getTouched(),
1170  'epoch' => $this->getConfig()->get( 'CacheEpoch' ),
1171  ];
1172  if ( $this->getConfig()->get( 'UseSquid' ) ) {
1173  // T46570: the core page itself may not change, but resources might
1174  $modifiedTimes['sepoch'] = wfTimestamp(
1175  TS_MW, time() - $this->getConfig()->get( 'SquidMaxage' )
1176  );
1177  }
1178  Hooks::run( 'OutputPageCheckLastModified', [ &$modifiedTimes ] );
1179  $lastMod = max( $modifiedTimes );
1180  $return304 = wfTimestamp( TS_MW, $lastMod ) <= $ts->getTimestamp( TS_MW );
1181  }
1182  }
1183  } catch ( TimestampException $e ) {
1184  // Invalid timestamp, ignore it
1185  }
1186  }
1187  }
1188 
1189  if ( $return304 ) {
1190  $this->getRequest()->response()->statusHeader( 304 );
1191 
1192  // Avoid outputting the compressed representation of a zero-length body
1193  MediaWiki\suppressWarnings();
1194  ini_set( 'zlib.output_compression', 0 );
1195  MediaWiki\restoreWarnings();
1197 
1198  return false;
1199  }
1200 
1201  return true;
1202  }
1203 
1208  protected function checkExecutePermissions( $module ) {
1209  $user = $this->getUser();
1210  if ( $module->isReadMode() && !User::isEveryoneAllowed( 'read' ) &&
1211  !$user->isAllowed( 'read' )
1212  ) {
1213  $this->dieUsageMsg( 'readrequired' );
1214  }
1215 
1216  if ( $module->isWriteMode() ) {
1217  if ( !$this->mEnableWrite ) {
1218  $this->dieUsageMsg( 'writedisabled' );
1219  } elseif ( !$user->isAllowed( 'writeapi' ) ) {
1220  $this->dieUsageMsg( 'writerequired' );
1221  } elseif ( $this->getRequest()->getHeader( 'Promise-Non-Write-API-Action' ) ) {
1222  $this->dieUsage(
1223  'Promise-Non-Write-API-Action HTTP header cannot be sent to write API modules',
1224  'promised-nonwrite-api'
1225  );
1226  }
1227 
1228  $this->checkReadOnly( $module );
1229  }
1230 
1231  // Allow extensions to stop execution for arbitrary reasons.
1232  $message = false;
1233  if ( !Hooks::run( 'ApiCheckCanExecute', [ $module, $user, &$message ] ) ) {
1234  $this->dieUsageMsg( $message );
1235  }
1236  }
1237 
1242  protected function checkReadOnly( $module ) {
1243  if ( wfReadOnly() ) {
1244  $this->dieReadOnly();
1245  }
1246 
1247  if ( $module->isWriteMode()
1248  && in_array( 'bot', $this->getUser()->getGroups() )
1249  && wfGetLB()->getServerCount() > 1
1250  ) {
1251  $this->checkBotReadOnly();
1252  }
1253  }
1254 
1258  private function checkBotReadOnly() {
1259  // Figure out how many servers have passed the lag threshold
1260  $numLagged = 0;
1261  $lagLimit = $this->getConfig()->get( 'APIMaxLagThreshold' );
1262  $laggedServers = [];
1263  $loadBalancer = wfGetLB();
1264  foreach ( $loadBalancer->getLagTimes() as $serverIndex => $lag ) {
1265  if ( $lag > $lagLimit ) {
1266  ++$numLagged;
1267  $laggedServers[] = $loadBalancer->getServerName( $serverIndex ) . " ({$lag}s)";
1268  }
1269  }
1270 
1271  // If a majority of slaves are too lagged then disallow writes
1272  $slaveCount = wfGetLB()->getServerCount() - 1;
1273  if ( $numLagged >= ceil( $slaveCount / 2 ) ) {
1274  $laggedServers = implode( ', ', $laggedServers );
1275  wfDebugLog(
1276  'api-readonly',
1277  "Api request failed as read only because the following DBs are lagged: $laggedServers"
1278  );
1279 
1280  $parsed = $this->parseMsg( [ 'readonlytext' ] );
1281  $this->dieUsage(
1282  $parsed['info'],
1283  $parsed['code'],
1284  /* http error */
1285  0,
1286  [ 'readonlyreason' => "Waiting for $numLagged lagged database(s)" ]
1287  );
1288  }
1289  }
1290 
1295  protected function checkAsserts( $params ) {
1296  if ( isset( $params['assert'] ) ) {
1297  $user = $this->getUser();
1298  switch ( $params['assert'] ) {
1299  case 'user':
1300  if ( $user->isAnon() ) {
1301  $this->dieUsage( 'Assertion that the user is logged in failed', 'assertuserfailed' );
1302  }
1303  break;
1304  case 'bot':
1305  if ( !$user->isAllowed( 'bot' ) ) {
1306  $this->dieUsage( 'Assertion that the user has the bot right failed', 'assertbotfailed' );
1307  }
1308  break;
1309  }
1310  }
1311  }
1312 
1318  protected function setupExternalResponse( $module, $params ) {
1319  $request = $this->getRequest();
1320  if ( !$request->wasPosted() && $module->mustBePosted() ) {
1321  // Module requires POST. GET request might still be allowed
1322  // if $wgDebugApi is true, otherwise fail.
1323  $this->dieUsageMsgOrDebug( [ 'mustbeposted', $this->mAction ] );
1324  }
1325 
1326  // See if custom printer is used
1327  $this->mPrinter = $module->getCustomPrinter();
1328  if ( is_null( $this->mPrinter ) ) {
1329  // Create an appropriate printer
1330  $this->mPrinter = $this->createPrinterByName( $params['format'] );
1331  }
1332 
1333  if ( $request->getProtocol() === 'http' && (
1334  $request->getSession()->shouldForceHTTPS() ||
1335  ( $this->getUser()->isLoggedIn() &&
1336  $this->getUser()->requiresHTTPS() )
1337  ) ) {
1338  $this->logFeatureUsage( 'https-expected' );
1339  $this->setWarning( 'HTTP used when HTTPS was expected' );
1340  }
1341  }
1342 
1346  protected function executeAction() {
1347  $params = $this->setupExecuteAction();
1348  $module = $this->setupModule();
1349  $this->mModule = $module;
1350 
1351  if ( !$this->mInternalMode ) {
1352  $this->setRequestExpectations( $module );
1353  }
1354 
1355  $this->checkExecutePermissions( $module );
1356 
1357  if ( !$this->checkMaxLag( $module, $params ) ) {
1358  return;
1359  }
1360 
1361  if ( !$this->checkConditionalRequestHeaders( $module ) ) {
1362  return;
1363  }
1364 
1365  if ( !$this->mInternalMode ) {
1366  $this->setupExternalResponse( $module, $params );
1367  }
1368 
1369  $this->checkAsserts( $params );
1370 
1371  // Execute
1372  $module->execute();
1373  Hooks::run( 'APIAfterExecute', [ &$module ] );
1374 
1375  $this->reportUnusedParams();
1376 
1377  if ( !$this->mInternalMode ) {
1378  // append Debug information
1380 
1381  // Print result data
1382  $this->printResult( false );
1383  }
1384  }
1385 
1390  protected function setRequestExpectations( ApiBase $module ) {
1391  $limits = $this->getConfig()->get( 'TrxProfilerLimits' );
1392  $trxProfiler = Profiler::instance()->getTransactionProfiler();
1393  if ( $this->getRequest()->wasPosted() ) {
1394  if ( $module->isWriteMode() ) {
1395  $trxProfiler->setExpectations( $limits['POST'], __METHOD__ );
1396  } else {
1397  $trxProfiler->setExpectations( $limits['POST-nonwrite'], __METHOD__ );
1398  }
1399  } else {
1400  $trxProfiler->setExpectations( $limits['GET'], __METHOD__ );
1401  }
1402  }
1403 
1409  protected function logRequest( $time, $e = null ) {
1410  $request = $this->getRequest();
1411  $logCtx = [
1412  'ts' => time(),
1413  'ip' => $request->getIP(),
1414  'userAgent' => $this->getUserAgent(),
1415  'wiki' => wfWikiID(),
1416  'timeSpentBackend' => (int) round( $time * 1000 ),
1417  'hadError' => $e !== null,
1418  'errorCodes' => [],
1419  'params' => [],
1420  ];
1421 
1422  if ( $e ) {
1423  $logCtx['errorCodes'][] = $this->errorMessageFromException( $e )['code'];
1424  }
1425 
1426  // Construct space separated message for 'api' log channel
1427  $msg = "API {$request->getMethod()} " .
1428  wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
1429  " {$logCtx['ip']} " .
1430  "T={$logCtx['timeSpentBackend']}ms";
1431 
1432  foreach ( $this->getParamsUsed() as $name ) {
1433  $value = $request->getVal( $name );
1434  if ( $value === null ) {
1435  continue;
1436  }
1437 
1438  if ( strlen( $value ) > 256 ) {
1439  $value = substr( $value, 0, 256 );
1440  $encValue = $this->encodeRequestLogValue( $value ) . '[...]';
1441  } else {
1442  $encValue = $this->encodeRequestLogValue( $value );
1443  }
1444 
1445  $logCtx['params'][$name] = $value;
1446  $msg .= " {$name}={$encValue}";
1447  }
1448 
1449  wfDebugLog( 'api', $msg, 'private' );
1450  // ApiAction channel is for structured data consumers
1451  wfDebugLog( 'ApiAction', '', 'private', $logCtx );
1452  }
1453 
1459  protected function encodeRequestLogValue( $s ) {
1460  static $table;
1461  if ( !$table ) {
1462  $chars = ';@$!*(),/:';
1463  $numChars = strlen( $chars );
1464  for ( $i = 0; $i < $numChars; $i++ ) {
1465  $table[rawurlencode( $chars[$i] )] = $chars[$i];
1466  }
1467  }
1468 
1469  return strtr( rawurlencode( $s ), $table );
1470  }
1471 
1476  protected function getParamsUsed() {
1477  return array_keys( $this->mParamsUsed );
1478  }
1479 
1484  public function markParamsUsed( $params ) {
1485  $this->mParamsUsed += array_fill_keys( (array)$params, true );
1486  }
1487 
1494  public function getVal( $name, $default = null ) {
1495  $this->mParamsUsed[$name] = true;
1496 
1497  $ret = $this->getRequest()->getVal( $name );
1498  if ( $ret === null ) {
1499  if ( $this->getRequest()->getArray( $name ) !== null ) {
1500  // See bug 10262 for why we don't just implode( '|', ... ) the
1501  // array.
1502  $this->setWarning(
1503  "Parameter '$name' uses unsupported PHP array syntax"
1504  );
1505  }
1506  $ret = $default;
1507  }
1508  return $ret;
1509  }
1510 
1517  public function getCheck( $name ) {
1518  return $this->getVal( $name, null ) !== null;
1519  }
1520 
1528  public function getUpload( $name ) {
1529  $this->mParamsUsed[$name] = true;
1530 
1531  return $this->getRequest()->getUpload( $name );
1532  }
1533 
1538  protected function reportUnusedParams() {
1539  $paramsUsed = $this->getParamsUsed();
1540  $allParams = $this->getRequest()->getValueNames();
1541 
1542  if ( !$this->mInternalMode ) {
1543  // Printer has not yet executed; don't warn that its parameters are unused
1544  $printerParams = array_map(
1545  [ $this->mPrinter, 'encodeParamName' ],
1546  array_keys( $this->mPrinter->getFinalParams() ?: [] )
1547  );
1548  $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1549  } else {
1550  $unusedParams = array_diff( $allParams, $paramsUsed );
1551  }
1552 
1553  if ( count( $unusedParams ) ) {
1554  $s = count( $unusedParams ) > 1 ? 's' : '';
1555  $this->setWarning( "Unrecognized parameter$s: '" . implode( $unusedParams, "', '" ) . "'" );
1556  }
1557  }
1558 
1564  protected function printResult( $isError ) {
1565  if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
1566  $this->setWarning( 'SECURITY WARNING: $wgDebugAPI is enabled' );
1567  }
1568 
1569  $printer = $this->mPrinter;
1570  $printer->initPrinter( false );
1571  $printer->execute();
1572  $printer->closePrinter();
1573  }
1574 
1578  public function isReadMode() {
1579  return false;
1580  }
1581 
1587  public function getAllowedParams() {
1588  return [
1589  'action' => [
1590  ApiBase::PARAM_DFLT => 'help',
1591  ApiBase::PARAM_TYPE => 'submodule',
1592  ],
1593  'format' => [
1595  ApiBase::PARAM_TYPE => 'submodule',
1596  ],
1597  'maxlag' => [
1598  ApiBase::PARAM_TYPE => 'integer'
1599  ],
1600  'smaxage' => [
1601  ApiBase::PARAM_TYPE => 'integer',
1602  ApiBase::PARAM_DFLT => 0
1603  ],
1604  'maxage' => [
1605  ApiBase::PARAM_TYPE => 'integer',
1606  ApiBase::PARAM_DFLT => 0
1607  ],
1608  'assert' => [
1609  ApiBase::PARAM_TYPE => [ 'user', 'bot' ]
1610  ],
1611  'requestid' => null,
1612  'servedby' => false,
1613  'curtimestamp' => false,
1614  'origin' => null,
1615  'uselang' => [
1616  ApiBase::PARAM_DFLT => 'user',
1617  ],
1618  ];
1619  }
1620 
1622  protected function getExamplesMessages() {
1623  return [
1624  'action=help'
1625  => 'apihelp-help-example-main',
1626  'action=help&recursivesubmodules=1'
1627  => 'apihelp-help-example-recursive',
1628  ];
1629  }
1630 
1631  public function modifyHelp( array &$help, array $options, array &$tocData ) {
1632  // Wish PHP had an "array_insert_before". Instead, we have to manually
1633  // reindex the array to get 'permissions' in the right place.
1634  $oldHelp = $help;
1635  $help = [];
1636  foreach ( $oldHelp as $k => $v ) {
1637  if ( $k === 'submodules' ) {
1638  $help['permissions'] = '';
1639  }
1640  $help[$k] = $v;
1641  }
1642  $help['datatypes'] = '';
1643  $help['credits'] = '';
1644 
1645  // Fill 'permissions'
1646  $help['permissions'] .= Html::openElement( 'div',
1647  [ 'class' => 'apihelp-block apihelp-permissions' ] );
1648  $m = $this->msg( 'api-help-permissions' );
1649  if ( !$m->isDisabled() ) {
1650  $help['permissions'] .= Html::rawElement( 'div', [ 'class' => 'apihelp-block-head' ],
1651  $m->numParams( count( self::$mRights ) )->parse()
1652  );
1653  }
1654  $help['permissions'] .= Html::openElement( 'dl' );
1655  foreach ( self::$mRights as $right => $rightMsg ) {
1656  $help['permissions'] .= Html::element( 'dt', null, $right );
1657 
1658  $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse();
1659  $help['permissions'] .= Html::rawElement( 'dd', null, $rightMsg );
1660 
1661  $groups = array_map( function ( $group ) {
1662  return $group == '*' ? 'all' : $group;
1663  }, User::getGroupsWithPermission( $right ) );
1664 
1665  $help['permissions'] .= Html::rawElement( 'dd', null,
1666  $this->msg( 'api-help-permissions-granted-to' )
1667  ->numParams( count( $groups ) )
1668  ->params( $this->getLanguage()->commaList( $groups ) )
1669  ->parse()
1670  );
1671  }
1672  $help['permissions'] .= Html::closeElement( 'dl' );
1673  $help['permissions'] .= Html::closeElement( 'div' );
1674 
1675  // Fill 'datatypes' and 'credits', if applicable
1676  if ( empty( $options['nolead'] ) ) {
1677  $level = $options['headerlevel'];
1678  $tocnumber = &$options['tocnumber'];
1679 
1680  $header = $this->msg( 'api-help-datatypes-header' )->parse();
1681  $help['datatypes'] .= Html::rawElement( 'h' . min( 6, $level ),
1682  [ 'id' => 'main/datatypes', 'class' => 'apihelp-header' ],
1683  Html::element( 'span', [ 'id' => Sanitizer::escapeId( 'main/datatypes' ) ] ) .
1684  $header
1685  );
1686  $help['datatypes'] .= $this->msg( 'api-help-datatypes' )->parseAsBlock();
1687  if ( !isset( $tocData['main/datatypes'] ) ) {
1688  $tocnumber[$level]++;
1689  $tocData['main/datatypes'] = [
1690  'toclevel' => count( $tocnumber ),
1691  'level' => $level,
1692  'anchor' => 'main/datatypes',
1693  'line' => $header,
1694  'number' => implode( '.', $tocnumber ),
1695  'index' => false,
1696  ];
1697  }
1698 
1699  $header = $this->msg( 'api-credits-header' )->parse();
1700  $help['credits'] .= Html::rawElement( 'h' . min( 6, $level ),
1701  [ 'id' => 'main/credits', 'class' => 'apihelp-header' ],
1702  Html::element( 'span', [ 'id' => Sanitizer::escapeId( 'main/credits' ) ] ) .
1703  $header
1704  );
1705  $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
1706  if ( !isset( $tocData['main/credits'] ) ) {
1707  $tocnumber[$level]++;
1708  $tocData['main/credits'] = [
1709  'toclevel' => count( $tocnumber ),
1710  'level' => $level,
1711  'anchor' => 'main/credits',
1712  'line' => $header,
1713  'number' => implode( '.', $tocnumber ),
1714  'index' => false,
1715  ];
1716  }
1717  }
1718  }
1719 
1720  private $mCanApiHighLimits = null;
1721 
1726  public function canApiHighLimits() {
1727  if ( !isset( $this->mCanApiHighLimits ) ) {
1728  $this->mCanApiHighLimits = $this->getUser()->isAllowed( 'apihighlimits' );
1729  }
1730 
1731  return $this->mCanApiHighLimits;
1732  }
1733 
1738  public function getModuleManager() {
1739  return $this->mModuleMgr;
1740  }
1741 
1750  public function getUserAgent() {
1751  return trim(
1752  $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
1753  $this->getRequest()->getHeader( 'User-agent' )
1754  );
1755  }
1756 
1757  /************************************************************************/
1768  public function setHelp( $help = true ) {
1769  wfDeprecated( __METHOD__, '1.25' );
1770  $this->mPrinter->setHelp( $help );
1771  }
1772 
1779  public function makeHelpMsg() {
1780  wfDeprecated( __METHOD__, '1.25' );
1781 
1782  $this->setHelp();
1783  $cacheHelpTimeout = $this->getConfig()->get( 'APICacheHelpTimeout' );
1784 
1785  return ObjectCache::getMainWANInstance()->getWithSetCallback(
1786  wfMemcKey(
1787  'apihelp',
1788  $this->getModuleName(),
1789  str_replace( ' ', '_', SpecialVersion::getVersion( 'nodb' ) )
1790  ),
1791  $cacheHelpTimeout > 0 ? $cacheHelpTimeout : WANObjectCache::TTL_UNCACHEABLE,
1792  [ $this, 'reallyMakeHelpMsg' ]
1793  );
1794  }
1795 
1800  public function reallyMakeHelpMsg() {
1801  wfDeprecated( __METHOD__, '1.25' );
1802  $this->setHelp();
1803 
1804  // Use parent to make default message for the main module
1805  $msg = parent::makeHelpMsg();
1806 
1807  $asterisks = str_repeat( '*** ', 14 );
1808  $msg .= "\n\n$asterisks Modules $asterisks\n\n";
1809 
1810  foreach ( $this->mModuleMgr->getNames( 'action' ) as $name ) {
1811  $module = $this->mModuleMgr->getModule( $name );
1812  $msg .= self::makeHelpMsgHeader( $module, 'action' );
1813 
1814  $msg2 = $module->makeHelpMsg();
1815  if ( $msg2 !== false ) {
1816  $msg .= $msg2;
1817  }
1818  $msg .= "\n";
1819  }
1820 
1821  $msg .= "\n$asterisks Permissions $asterisks\n\n";
1822  foreach ( self::$mRights as $right => $rightMsg ) {
1823  $rightsMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )
1824  ->useDatabase( false )
1825  ->inLanguage( 'en' )
1826  ->text();
1827  $groups = User::getGroupsWithPermission( $right );
1828  $msg .= '* ' . $right . " *\n $rightsMsg" .
1829  "\nGranted to:\n " . str_replace( '*', 'all', implode( ', ', $groups ) ) . "\n\n";
1830  }
1831 
1832  $msg .= "\n$asterisks Formats $asterisks\n\n";
1833  foreach ( $this->mModuleMgr->getNames( 'format' ) as $name ) {
1834  $module = $this->mModuleMgr->getModule( $name );
1835  $msg .= self::makeHelpMsgHeader( $module, 'format' );
1836  $msg2 = $module->makeHelpMsg();
1837  if ( $msg2 !== false ) {
1838  $msg .= $msg2;
1839  }
1840  $msg .= "\n";
1841  }
1842 
1843  $credits = $this->msg( 'api-credits' )->useDatabase( 'false' )->inLanguage( 'en' )->text();
1844  $credits = str_replace( "\n", "\n ", $credits );
1845  $msg .= "\n*** Credits: ***\n $credits\n";
1846 
1847  return $msg;
1848  }
1849 
1857  public static function makeHelpMsgHeader( $module, $paramName ) {
1858  wfDeprecated( __METHOD__, '1.25' );
1859  $modulePrefix = $module->getModulePrefix();
1860  if ( strval( $modulePrefix ) !== '' ) {
1861  $modulePrefix = "($modulePrefix) ";
1862  }
1863 
1864  return "* $paramName={$module->getModuleName()} $modulePrefix*";
1865  }
1866 
1869 }
1870 
1877 
1878  private $mCodestr;
1879 
1883  private $mExtraData;
1884 
1891  public function __construct( $message, $codestr, $code = 0, $extradata = null ) {
1892  parent::__construct( $message, $code );
1893  $this->mCodestr = $codestr;
1894  $this->mExtraData = $extradata;
1895  }
1896 
1900  public function getCodeString() {
1901  return $this->mCodestr;
1902  }
1903 
1907  public function getMessageArray() {
1908  $result = [
1909  'code' => $this->mCodestr,
1910  'info' => $this->getMessage()
1911  ];
1912  if ( is_array( $this->mExtraData ) ) {
1913  $result = array_merge( $result, $this->mExtraData );
1914  }
1915 
1916  return $result;
1917  }
1918 
1922  public function __toString() {
1923  return "{$this->getCodeString()}: {$this->getMessage()}";
1924  }
1925 }
1926 
dieUsageMsgOrDebug($error)
Will only set a warning instead of failing if the global $wgDebugAPI is set to true.
Definition: ApiBase.php:2117
setContext(IContextSource $context)
Set the IContextSource object.
const TS_RFC2822
RFC 2822 format, for E-mail and HTTP headers.
getAllowedParams()
See ApiBase for description.
Definition: ApiMain.php:1587
static closeElement($element)
Returns "".
Definition: Html.php:306
getModuleManager()
Overrides to return this instance's module manager.
Definition: ApiMain.php:1738
const PARAM_TYPE
(string|string[]) Either an array of allowed value strings, or a string type as described below...
Definition: ApiBase.php:88
getStats()
Get the Stats object.
getUserAgent()
Fetches the user agent used for this request.
Definition: ApiMain.php:1750
const LIMIT_BIG2
Fast query, apihighlimits limit.
Definition: ApiBase.php:179
static getMainWANInstance()
Get the main WAN cache object.
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
getContinuationManager()
Get the continuation manager.
Definition: ApiMain.php:290
static $Modules
List of available modules: action name => module class.
Definition: ApiMain.php:50
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:762
Database error base class.
printResult($isError)
Print results using the current printer.
Definition: ApiMain.php:1564
checkConditionalRequestHeaders($module)
Check selected RFC 7232 precondition headers.
Definition: ApiMain.php:1110
the array() calling protocol came about after MediaWiki 1.4rc1.
$mEnableWrite
Definition: ApiMain.php:142
getLanguage()
Get the Language object.
static getRequestId()
Get the unique request ID.
Definition: WebRequest.php:265
wfScript($script= 'index')
Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScri...
initPrinter($unused=false)
Initialize the printer function and prepare the output headers.
executeActionWithErrorHandling()
Execute an action, and in case of an error, erase whatever partial results have been accumulated...
Definition: ApiMain.php:452
getParameter($paramName, $parseLimit=true)
Get a value for the given parameter.
Definition: ApiBase.php:702
modifyHelp(array &$help, array $options, array &$tocData)
Definition: ApiMain.php:1631
__construct($context=null, $enableWrite=false)
Constructs an instance of ApiMain that utilizes the module and format specified by $request...
Definition: ApiMain.php:159
This class holds a list of modules and handles instantiation.
checkReadOnly($module)
Check if the DB is read-only for this user.
Definition: ApiMain.php:1242
bool null $lacksSameOriginSecurity
Cached return value from self::lacksSameOriginSecurity()
Definition: ApiMain.php:150
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException'returning false will NOT prevent logging $e
Definition: hooks.txt:1932
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:1798
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
Definition: ApiBase.php:50
static instance()
Singleton.
Definition: Profiler.php:60
static rawElement($element, $attribs=[], $contents= '')
Returns an HTML element in a string.
Definition: Html.php:210
wfHostname()
Fetch server name for use in error reporting etc.
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:189
$mCacheControl
Definition: ApiMain.php:146
An IContextSource implementation which will inherit context from another source but allow individual ...
static matchRequestedHeaders($requestedHeaders)
Attempt to validate the value of Access-Control-Request-Headers against a list of headers that we all...
Definition: ApiMain.php:709
static static static ApiFormatBase $mPrinter
Definition: ApiMain.php:126
const TTL_UNCACHEABLE
Idiom for getWithSetCallback() callbacks to avoid calling set()
setCacheMaxAge($maxage)
Set how long the response should be cached.
Definition: ApiMain.php:338
This manages continuation state.
extractRequestParams($parseLimit=true)
Using getAllowedParams(), this function makes an array of the values provided by the user...
Definition: ApiBase.php:678
isInternalMode()
Return true if the API was started by other PHP code using FauxRequest.
Definition: ApiMain.php:236
$value
$mContinuationManager
Definition: ApiMain.php:140
const GETHEADER_LIST
Flag to make WebRequest::getHeader return an array of values.
Definition: WebRequest.php:44
canApiHighLimits()
Check whether the current user is allowed to use high limits.
Definition: ApiMain.php:1726
wfUrlencode($s)
We want some things to be included as literal characters in our title URLs for prettiness, which urlencode encodes by default.
A helper class for throttling authentication attempts.
this hook is for auditing only $response
Definition: hooks.txt:762
when a variable name is used in a it is silently declared as a new local masking the global
Definition: design.txt:93
wfExpandUrl($url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.
static preOutputCommit(IContextSource $context)
This function commits all DB changes as needed before the user can receive a response (in case commit...
Definition: MediaWiki.php:549
static handleApiBeforeMainException(Exception $e)
Handle an exception from the ApiBeforeMain hook.
Definition: ApiMain.php:571
static setContentValue(array &$arr, $name, $value, $flags=0)
Add an output value to the array by name and mark as META_CONTENT.
Definition: ApiResult.php:480
const API_DEFAULT_FORMAT
When no format parameter is given, this format will be used.
Definition: ApiMain.php:45
IContextSource $context
setCacheMode($mode)
Set the type of caching headers which will be sent.
Definition: ApiMain.php:370
see documentation in includes Linker php for Linker::makeImageLink & $time
Definition: hooks.txt:1612
static static static $mRights
List of user roles that are specifically relevant to the API.
Definition: ApiMain.php:123
reallyMakeHelpMsg()
Definition: ApiMain.php:1800
setupExternalResponse($module, $params)
Check POST for external response and setup result printer.
Definition: ApiMain.php:1318
wfDebug($text, $dest= 'all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
setCacheControl($directives)
Set directives (key/value pairs) for the Cache-Control header.
Definition: ApiMain.php:411
errorMessageFromException($e)
Create an error message for the given exception.
Definition: ApiMain.php:905
static isEveryoneAllowed($right)
Check if all users may be assumed to have the given permission.
Definition: User.php:4574
static sanitizeLangCode($code)
Accepts a language code and ensures it's sane.
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
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:Associative array mapping language codes to prefixed links of the form"language:title".&$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':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:1796
setupModule()
Set up the module for response.
Definition: ApiMain.php:1015
the value to return A Title object or null for latest to be modified or replaced by the hook handler or if authentication is not possible after cache objects are set for highlighting & $link
Definition: hooks.txt:2581
makeHelpMsg()
Override the parent to generate help messages for all available modules.
Definition: ApiMain.php:1779
wfTimestamp($outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
getRequest()
Get the WebRequest object.
static wildcardToRegex($wildcard)
Helper function to convert wildcard string into a regex '*' => '.
Definition: ApiMain.php:745
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:1798
wfDebugLog($logGroup, $text, $dest= 'all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not...
msg()
Get a Message object with context set Parameters are the same as wfMessage()
setRequestExpectations(ApiBase $module)
Set database connection, query, and write expectations given this module request. ...
Definition: ApiMain.php:1390
static openElement($element, $attribs=[])
Identical to rawElement(), but has no third parameter and omits the end tag (and the self-closing '/'...
Definition: Html.php:248
wfGetLB($wiki=false)
Get a load balancer object.
wfReadOnly()
Check whether the wiki is in read-only mode.
static getMain()
Static methods.
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist 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:1004
const TS_ISO_8601
ISO 8601 format with no timezone: 1986-02-09T20:00:00Z.
getConfig()
Get the Config object.
const LIMIT_SML2
Slow query, apihighlimits limit.
Definition: ApiBase.php:183
getContext()
Get the base IContextSource object.
$params
This is the main API class, used for both external and internal processing.
Definition: ApiMain.php:41
executeAction()
Execute the actual module, without any error handling.
Definition: ApiMain.php:1346
isReadMode()
Definition: ApiMain.php:1578
handleCORS()
Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
Definition: ApiMain.php:603
setupExecuteAction()
Set up for the execution.
Definition: ApiMain.php:978
wfDeprecated($function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
$mCacheMode
Definition: ApiMain.php:145
Format errors and warnings in the old style, for backwards compatibility.
$mErrorFormatter
Definition: ApiMain.php:140
lacksSameOriginSecurity()
Get the security flag for the current request.
Definition: ApiMain.php:253
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
createPrinterByName($format)
Create an instance of an output formatter by its name.
Definition: ApiMain.php:422
getModuleName()
Get the name of the module being executed by this instance.
Definition: ApiBase.php:457
static dieReadOnly()
Helper function for readonly errors.
Definition: ApiBase.php:2088
static matchOrigin($value, $rules, $exceptions)
Attempt to match an Origin header against a set of rules and a set of exceptions. ...
Definition: ApiMain.php:685
This class represents the result of the API operations.
Definition: ApiResult.php:33
static run($event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:131
static makeHelpMsgHeader($module, $paramName)
Definition: ApiMain.php:1857
$help
Definition: mcc.php:32
wfWikiID()
Get an ASCII string identifying this wiki This is used as a prefix in memcached keys.
encodeRequestLogValue($s)
Encode a value in a format suitable for a space-separated log line.
Definition: ApiMain.php:1459
checkMaxLag($module, $params)
Check the max lag if necessary.
Definition: ApiMain.php:1068
setWarning($warning)
Set warning section for this module.
Definition: ApiBase.php:1450
$mCanApiHighLimits
Definition: ApiMain.php:1720
static getRedactedTraceAsString($e)
Generate a string representation of an exception's stack trace.
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
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:762
static static $Formats
List of available formats: format name => format class.
Definition: ApiMain.php:105
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 local account $user
Definition: hooks.txt:242
getParamsUsed()
Get the request parameters used in the course of the preceding execute() request. ...
Definition: ApiMain.php:1476
getExamplesMessages()
Definition: ApiMain.php:1622
logRequest($time, $e=null)
Log the preceding request.
Definition: ApiMain.php:1409
getErrorFormatter()
Get the ApiErrorFormatter object associated with current request.
Definition: ApiMain.php:282
static rollbackMasterChangesAndLog($e)
If there are any open database transactions, roll them back and log the stack trace of the exception ...
static escapeId($id, $options=[])
Given a value, escape it so that it can be used in an id attribute and return it. ...
Definition: Sanitizer.php:1131
getUpload($name)
Get a request upload, and register the fact that it was used, for logging.
Definition: ApiMain.php:1528
const TS_MW
MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
markParamsUsed($params)
Mark parameters as used.
Definition: ApiMain.php:1484
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
checkBotReadOnly()
Check whether we are readonly for bots.
Definition: ApiMain.php:1258
getModule()
Get the API module object.
Definition: ApiMain.php:320
error also a ContextSource you ll probably need to make sure the header is varied on $request
Definition: hooks.txt:2418
setHelp($help=true)
Sets whether the pretty-printer should format bold and $italics$.
Definition: ApiMain.php:1768
static appendDebugInfoToApiResult(IContextSource $context, ApiResult $result)
Append the debug info to given ApiResult.
Definition: MWDebug.php:486
$mSquidMaxage
Definition: ApiMain.php:143
$mParamsUsed
Definition: ApiMain.php:147
reportUnusedParams()
Report unused parameters, so the client gets a hint in case it gave us parameters we don't know...
Definition: ApiMain.php:1538
wfClearOutputBuffers()
More legible than passing a 'false' parameter to wfResetOutputBuffers():
null array $mExtraData
Definition: ApiMain.php:1883
dieUsage($description, $errorCode, $httpRespCode=0, $extradata=null)
Throw a UsageException, which will (if uncaught) call the main module's error handler and die with an...
Definition: ApiBase.php:1481
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 local content language as $wgContLang
Definition: design.txt:56
This abstract class implements many basic API functions, and is the base of all API classes...
Definition: ApiBase.php:39
getPrinter()
Get the result formatter object.
Definition: ApiMain.php:329
wfMemcKey()
Make a cache key for the local wiki.
checkAsserts($params)
Check asserts of the user's rights.
Definition: ApiMain.php:1295
parseMsg($error)
Return the error message related to a certain array.
Definition: ApiBase.php:2149
static logException($e)
Log an exception to the exception log (if enabled).
getCheck($name)
Get a boolean request value, and register the fact that the parameter was used, for logging...
Definition: ApiMain.php:1517
logFeatureUsage($feature)
Write logging information for API features to a debug log, for usage analysis.
Definition: ApiBase.php:2194
static getVersion($flags= '', $lang=null)
Return a string of the MediaWiki version with Git revision if available.
sendCacheHeaders($isError)
Send caching headers.
Definition: ApiMain.php:761
getVal($name, $default=null)
Get a request value, and register the fact that it was used, for logging.
Definition: ApiMain.php:1494
__construct($message, $codestr, $code=0, $extradata=null)
Definition: ApiMain.php:1891
static element($element, $attribs=[], $contents= '')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
Definition: Html.php:230
getUser()
Get the User object.
$mInternalMode
Definition: ApiMain.php:143
substituteResultWithError($e)
Replace the result data with the information about an exception.
Definition: ApiMain.php:932
Library for creating and parsing MW-style timestamps.
Definition: MWTimestamp.php:31
dieUsageMsg($error)
Output the error message related to a certain array.
Definition: ApiBase.php:2099
$mModuleMgr
Definition: ApiMain.php:140
static getGroupsWithPermission($role)
Get all the groups who have a given permission.
Definition: User.php:4531
execute()
Execute api request.
Definition: ApiMain.php:434
This exception will be thrown when dieUsage is called to stop module execution.
Definition: ApiMain.php:1876
getResult()
Get the ApiResult object associated with current request.
Definition: ApiMain.php:245
checkExecutePermissions($module)
Check for sufficient permissions to execute.
Definition: ApiMain.php:1208
createErrorPrinter()
Create the printer for error output.
Definition: ApiMain.php:879
$wgUser
Definition: Setup.php:794
isWriteMode()
Indicates whether this module requires write mode.
Definition: ApiBase.php:364
setContinuationManager($manager)
Set the continuation manager.
Definition: ApiMain.php:298
getOutput()
Get the OutputPage object.
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:310
handleException(Exception $e)
Handle an exception as an API response.
Definition: ApiMain.php:502