MediaWiki  master
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  'cspreport' => 'ApiCSPReport',
75 
76  // Write modules
77  'purge' => 'ApiPurge',
78  'setnotificationtimestamp' => 'ApiSetNotificationTimestamp',
79  'rollback' => 'ApiRollback',
80  'delete' => 'ApiDelete',
81  'undelete' => 'ApiUndelete',
82  'protect' => 'ApiProtect',
83  'block' => 'ApiBlock',
84  'unblock' => 'ApiUnblock',
85  'move' => 'ApiMove',
86  'edit' => 'ApiEditPage',
87  'upload' => 'ApiUpload',
88  'filerevert' => 'ApiFileRevert',
89  'emailuser' => 'ApiEmailUser',
90  'watch' => 'ApiWatch',
91  'patrol' => 'ApiPatrol',
92  'import' => 'ApiImport',
93  'clearhasmsg' => 'ApiClearHasMsg',
94  'userrights' => 'ApiUserrights',
95  'options' => 'ApiOptions',
96  'imagerotate' => 'ApiImageRotate',
97  'revisiondelete' => 'ApiRevisionDelete',
98  'managetags' => 'ApiManageTags',
99  'tag' => 'ApiTag',
100  'mergehistory' => 'ApiMergeHistory',
101  ];
102 
106  private static $Formats = [
107  'json' => 'ApiFormatJson',
108  'jsonfm' => 'ApiFormatJson',
109  'php' => 'ApiFormatPhp',
110  'phpfm' => 'ApiFormatPhp',
111  'xml' => 'ApiFormatXml',
112  'xmlfm' => 'ApiFormatXml',
113  'rawfm' => 'ApiFormatJson',
114  'none' => 'ApiFormatNone',
115  ];
116 
117  // @codingStandardsIgnoreStart String contenation on "msg" not allowed to break long line
124  private static $mRights = [
125  'writeapi' => [
126  'msg' => 'right-writeapi',
127  'params' => []
128  ],
129  'apihighlimits' => [
130  'msg' => 'api-help-right-apihighlimits',
132  ]
133  ];
134  // @codingStandardsIgnoreEnd
135 
139  private $mPrinter;
140 
144  private $mAction;
145  private $mEnableWrite;
148  private $mModule;
149 
150  private $mCacheMode = 'private';
151  private $mCacheControl = [];
152  private $mParamsUsed = [];
153 
155  private $lacksSameOriginSecurity = null;
156 
164  public function __construct( $context = null, $enableWrite = false ) {
165  if ( $context === null ) {
167  } elseif ( $context instanceof WebRequest ) {
168  // BC for pre-1.19
169  $request = $context;
171  }
172  // We set a derivative context so we can change stuff later
173  $this->setContext( new DerivativeContext( $context ) );
174 
175  if ( isset( $request ) ) {
176  $this->getContext()->setRequest( $request );
177  } else {
178  $request = $this->getRequest();
179  }
180 
181  $this->mInternalMode = ( $request instanceof FauxRequest );
182 
183  // Special handling for the main module: $parent === $this
184  parent::__construct( $this, $this->mInternalMode ? 'main_int' : 'main' );
185 
186  $config = $this->getConfig();
187 
188  if ( !$this->mInternalMode ) {
189  // Log if a request with a non-whitelisted Origin header is seen
190  // with session cookies.
191  $originHeader = $request->getHeader( 'Origin' );
192  if ( $originHeader === false ) {
193  $origins = [];
194  } else {
195  $originHeader = trim( $originHeader );
196  $origins = preg_split( '/\s+/', $originHeader );
197  }
198  $sessionCookies = array_intersect(
199  array_keys( $_COOKIE ),
200  MediaWiki\Session\SessionManager::singleton()->getVaryCookies()
201  );
202  if ( $origins && $sessionCookies && (
203  count( $origins ) !== 1 || !self::matchOrigin(
204  $origins[0],
205  $config->get( 'CrossSiteAJAXdomains' ),
206  $config->get( 'CrossSiteAJAXdomainExceptions' )
207  )
208  ) ) {
210  'Non-whitelisted CORS request with session cookies', [
211  'origin' => $originHeader,
212  'cookies' => $sessionCookies,
213  'ip' => $request->getIP(),
214  'userAgent' => $this->getUserAgent(),
215  'wiki' => wfWikiID(),
216  ]
217  );
218  }
219 
220  // If we're in a mode that breaks the same-origin policy, strip
221  // user credentials for security.
222  if ( $this->lacksSameOriginSecurity() ) {
223  global $wgUser;
224  wfDebug( "API: stripping user credentials when the same-origin policy is not applied\n" );
225  $wgUser = new User();
226  $this->getContext()->setUser( $wgUser );
227  }
228  }
229 
230  $uselang = $this->getParameter( 'uselang' );
231  if ( $uselang === 'user' ) {
232  // Assume the parent context is going to return the user language
233  // for uselang=user (see T85635).
234  } else {
235  if ( $uselang === 'content' ) {
237  $uselang = $wgContLang->getCode();
238  }
240  $this->getContext()->setLanguage( $code );
241  if ( !$this->mInternalMode ) {
242  global $wgLang;
243  $wgLang = $this->getContext()->getLanguage();
244  RequestContext::getMain()->setLanguage( $wgLang );
245  }
246  }
247 
248  $this->mModuleMgr = new ApiModuleManager( $this );
249  $this->mModuleMgr->addModules( self::$Modules, 'action' );
250  $this->mModuleMgr->addModules( $config->get( 'APIModules' ), 'action' );
251  $this->mModuleMgr->addModules( self::$Formats, 'format' );
252  $this->mModuleMgr->addModules( $config->get( 'APIFormatModules' ), 'format' );
253 
254  Hooks::run( 'ApiMain::moduleManager', [ $this->mModuleMgr ] );
255 
256  $this->mResult = new ApiResult( $this->getConfig()->get( 'APIMaxResultSize' ) );
257  $this->mErrorFormatter = new ApiErrorFormatter_BackCompat( $this->mResult );
258  $this->mResult->setErrorFormatter( $this->mErrorFormatter );
259  $this->mResult->setMainForContinuation( $this );
260  $this->mContinuationManager = null;
261  $this->mEnableWrite = $enableWrite;
262 
263  $this->mSquidMaxage = -1; // flag for executeActionWithErrorHandling()
264  $this->mCommit = false;
265  }
266 
271  public function isInternalMode() {
272  return $this->mInternalMode;
273  }
274 
280  public function getResult() {
281  return $this->mResult;
282  }
283 
288  public function lacksSameOriginSecurity() {
289  if ( $this->lacksSameOriginSecurity !== null ) {
291  }
292 
293  $request = $this->getRequest();
294 
295  // JSONP mode
296  if ( $request->getVal( 'callback' ) !== null ) {
297  $this->lacksSameOriginSecurity = true;
298  return true;
299  }
300 
301  // Anonymous CORS
302  if ( $request->getVal( 'origin' ) === '*' ) {
303  $this->lacksSameOriginSecurity = true;
304  return true;
305  }
306 
307  // Header to be used from XMLHTTPRequest when the request might
308  // otherwise be used for XSS.
309  if ( $request->getHeader( 'Treat-as-Untrusted' ) !== false ) {
310  $this->lacksSameOriginSecurity = true;
311  return true;
312  }
313 
314  // Allow extensions to override.
315  $this->lacksSameOriginSecurity = !Hooks::run( 'RequestHasSameOriginSecurity', [ $request ] );
317  }
318 
323  public function getErrorFormatter() {
324  return $this->mErrorFormatter;
325  }
326 
331  public function getContinuationManager() {
333  }
334 
339  public function setContinuationManager( $manager ) {
340  if ( $manager !== null ) {
341  if ( !$manager instanceof ApiContinuationManager ) {
342  throw new InvalidArgumentException( __METHOD__ . ': Was passed ' .
343  is_object( $manager ) ? get_class( $manager ) : gettype( $manager )
344  );
345  }
346  if ( $this->mContinuationManager !== null ) {
347  throw new UnexpectedValueException(
348  __METHOD__ . ': tried to set manager from ' . $manager->getSource() .
349  ' when a manager is already set from ' . $this->mContinuationManager->getSource()
350  );
351  }
352  }
353  $this->mContinuationManager = $manager;
354  }
355 
361  public function getModule() {
362  return $this->mModule;
363  }
364 
370  public function getPrinter() {
371  return $this->mPrinter;
372  }
373 
379  public function setCacheMaxAge( $maxage ) {
380  $this->setCacheControl( [
381  'max-age' => $maxage,
382  's-maxage' => $maxage
383  ] );
384  }
385 
411  public function setCacheMode( $mode ) {
412  if ( !in_array( $mode, [ 'private', 'public', 'anon-public-user-private' ] ) ) {
413  wfDebug( __METHOD__ . ": unrecognised cache mode \"$mode\"\n" );
414 
415  // Ignore for forwards-compatibility
416  return;
417  }
418 
419  if ( !User::isEveryoneAllowed( 'read' ) ) {
420  // Private wiki, only private headers
421  if ( $mode !== 'private' ) {
422  wfDebug( __METHOD__ . ": ignoring request for $mode cache mode, private wiki\n" );
423 
424  return;
425  }
426  }
427 
428  if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) {
429  // User language is used for i18n, so we don't want to publicly
430  // cache. Anons are ok, because if they have non-default language
431  // then there's an appropriate Vary header set by whatever set
432  // their non-default language.
433  wfDebug( __METHOD__ . ": downgrading cache mode 'public' to " .
434  "'anon-public-user-private' due to uselang=user\n" );
435  $mode = 'anon-public-user-private';
436  }
437 
438  wfDebug( __METHOD__ . ": setting cache mode $mode\n" );
439  $this->mCacheMode = $mode;
440  }
441 
452  public function setCacheControl( $directives ) {
453  $this->mCacheControl = $directives + $this->mCacheControl;
454  }
455 
463  public function createPrinterByName( $format ) {
464  $printer = $this->mModuleMgr->getModule( $format, 'format' );
465  if ( $printer === null ) {
466  $this->dieUsage( "Unrecognized format: {$format}", 'unknown_format' );
467  }
468 
469  return $printer;
470  }
471 
475  public function execute() {
476  if ( $this->mInternalMode ) {
477  $this->executeAction();
478  } else {
480  }
481  }
482 
487  protected function executeActionWithErrorHandling() {
488  // Verify the CORS header before executing the action
489  if ( !$this->handleCORS() ) {
490  // handleCORS() has sent a 403, abort
491  return;
492  }
493 
494  // Exit here if the request method was OPTIONS
495  // (assume there will be a followup GET or POST)
496  if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
497  return;
498  }
499 
500  // In case an error occurs during data output,
501  // clear the output buffer and print just the error information
502  $obLevel = ob_get_level();
503  ob_start();
504 
505  $t = microtime( true );
506  $isError = false;
507  try {
508  $this->executeAction();
509  $runTime = microtime( true ) - $t;
510  $this->logRequest( $runTime );
511  if ( $this->mModule->isWriteMode() && $this->getRequest()->wasPosted() ) {
512  $this->getStats()->timing(
513  'api.' . $this->mModule->getModuleName() . '.executeTiming', 1000 * $runTime
514  );
515  }
516  } catch ( Exception $e ) {
517  $this->handleException( $e );
518  $this->logRequest( microtime( true ) - $t, $e );
519  $isError = true;
520  }
521 
522  // Commit DBs and send any related cookies and headers
524 
525  // Send cache headers after any code which might generate an error, to
526  // avoid sending public cache headers for errors.
527  $this->sendCacheHeaders( $isError );
528 
529  // Executing the action might have already messed with the output
530  // buffers.
531  while ( ob_get_level() > $obLevel ) {
532  ob_end_flush();
533  }
534  }
535 
542  protected function handleException( Exception $e ) {
543  // Bug 63145: Rollback any open database transactions
544  if ( !( $e instanceof UsageException ) ) {
545  // UsageExceptions are intentional, so don't rollback if that's the case
546  try {
548  } catch ( DBError $e2 ) {
549  // Rollback threw an exception too. Log it, but don't interrupt
550  // our regularly scheduled exception handling.
552  }
553  }
554 
555  // Allow extra cleanup and logging
556  Hooks::run( 'ApiMain::onException', [ $this, $e ] );
557 
558  // Log it
559  if ( !( $e instanceof UsageException ) ) {
561  }
562 
563  // Handle any kind of exception by outputting properly formatted error message.
564  // If this fails, an unhandled exception should be thrown so that global error
565  // handler will process and log it.
566 
567  $errCode = $this->substituteResultWithError( $e );
568 
569  // Error results should not be cached
570  $this->setCacheMode( 'private' );
571 
572  $response = $this->getRequest()->response();
573  $headerStr = 'MediaWiki-API-Error: ' . $errCode;
574  if ( $e->getCode() === 0 ) {
575  $response->header( $headerStr );
576  } else {
577  $response->header( $headerStr, true, $e->getCode() );
578  }
579 
580  // Reset and print just the error message
581  ob_clean();
582 
583  // Printer may not be initialized if the extractRequestParams() fails for the main module
584  $this->createErrorPrinter();
585 
586  try {
587  $this->printResult( true );
588  } catch ( UsageException $ex ) {
589  // The error printer itself is failing. Try suppressing its request
590  // parameters and redo.
591  $this->setWarning(
592  'Error printer failed (will retry without params): ' . $ex->getMessage()
593  );
594  $this->mPrinter = null;
595  $this->createErrorPrinter();
596  $this->mPrinter->forceDefaultParams();
597  $this->printResult( true );
598  }
599  }
600 
611  public static function handleApiBeforeMainException( Exception $e ) {
612  ob_start();
613 
614  try {
615  $main = new self( RequestContext::getMain(), false );
616  $main->handleException( $e );
617  $main->logRequest( 0, $e );
618  } catch ( Exception $e2 ) {
619  // Nope, even that didn't work. Punt.
620  throw $e;
621  }
622 
623  // Reset cache headers
624  $main->sendCacheHeaders( true );
625 
626  ob_end_flush();
627  }
628 
643  protected function handleCORS() {
644  $originParam = $this->getParameter( 'origin' ); // defaults to null
645  if ( $originParam === null ) {
646  // No origin parameter, nothing to do
647  return true;
648  }
649 
650  $request = $this->getRequest();
651  $response = $request->response();
652 
653  $matchOrigin = false;
654  $allowTiming = false;
655  $varyOrigin = true;
656 
657  if ( $originParam === '*' ) {
658  // Request for anonymous CORS
659  $matchOrigin = true;
660  $allowOrigin = '*';
661  $allowCredentials = 'false';
662  $varyOrigin = false; // No need to vary
663  } else {
664  // Non-anonymous CORS, check we allow the domain
665 
666  // Origin: header is a space-separated list of origins, check all of them
667  $originHeader = $request->getHeader( 'Origin' );
668  if ( $originHeader === false ) {
669  $origins = [];
670  } else {
671  $originHeader = trim( $originHeader );
672  $origins = preg_split( '/\s+/', $originHeader );
673  }
674 
675  if ( !in_array( $originParam, $origins ) ) {
676  // origin parameter set but incorrect
677  // Send a 403 response
678  $response->statusHeader( 403 );
679  $response->header( 'Cache-Control: no-cache' );
680  echo "'origin' parameter does not match Origin header\n";
681 
682  return false;
683  }
684 
685  $config = $this->getConfig();
686  $matchOrigin = count( $origins ) === 1 && self::matchOrigin(
687  $originParam,
688  $config->get( 'CrossSiteAJAXdomains' ),
689  $config->get( 'CrossSiteAJAXdomainExceptions' )
690  );
691 
692  $allowOrigin = $originHeader;
693  $allowCredentials = 'true';
694  $allowTiming = $originHeader;
695  }
696 
697  if ( $matchOrigin ) {
698  $requestedMethod = $request->getHeader( 'Access-Control-Request-Method' );
699  $preflight = $request->getMethod() === 'OPTIONS' && $requestedMethod !== false;
700  if ( $preflight ) {
701  // This is a CORS preflight request
702  if ( $requestedMethod !== 'POST' && $requestedMethod !== 'GET' ) {
703  // If method is not a case-sensitive match, do not set any additional headers and terminate.
704  return true;
705  }
706  // We allow the actual request to send the following headers
707  $requestedHeaders = $request->getHeader( 'Access-Control-Request-Headers' );
708  if ( $requestedHeaders !== false ) {
709  if ( !self::matchRequestedHeaders( $requestedHeaders ) ) {
710  return true;
711  }
712  $response->header( 'Access-Control-Allow-Headers: ' . $requestedHeaders );
713  }
714 
715  // We only allow the actual request to be GET or POST
716  $response->header( 'Access-Control-Allow-Methods: POST, GET' );
717  }
718 
719  $response->header( "Access-Control-Allow-Origin: $allowOrigin" );
720  $response->header( "Access-Control-Allow-Credentials: $allowCredentials" );
721  // http://www.w3.org/TR/resource-timing/#timing-allow-origin
722  if ( $allowTiming !== false ) {
723  $response->header( "Timing-Allow-Origin: $allowTiming" );
724  }
725 
726  if ( !$preflight ) {
727  $response->header(
728  'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag'
729  );
730  }
731  }
732 
733  if ( $varyOrigin ) {
734  $this->getOutput()->addVaryHeader( 'Origin' );
735  }
736 
737  return true;
738  }
739 
748  protected static function matchOrigin( $value, $rules, $exceptions ) {
749  foreach ( $rules as $rule ) {
750  if ( preg_match( self::wildcardToRegex( $rule ), $value ) ) {
751  // Rule matches, check exceptions
752  foreach ( $exceptions as $exc ) {
753  if ( preg_match( self::wildcardToRegex( $exc ), $value ) ) {
754  return false;
755  }
756  }
757 
758  return true;
759  }
760  }
761 
762  return false;
763  }
764 
772  protected static function matchRequestedHeaders( $requestedHeaders ) {
773  if ( trim( $requestedHeaders ) === '' ) {
774  return true;
775  }
776  $requestedHeaders = explode( ',', $requestedHeaders );
777  $allowedAuthorHeaders = array_flip( [
778  /* simple headers (see spec) */
779  'accept',
780  'accept-language',
781  'content-language',
782  'content-type',
783  /* non-authorable headers in XHR, which are however requested by some UAs */
784  'accept-encoding',
785  'dnt',
786  'origin',
787  /* MediaWiki whitelist */
788  'api-user-agent',
789  ] );
790  foreach ( $requestedHeaders as $rHeader ) {
791  $rHeader = strtolower( trim( $rHeader ) );
792  if ( !isset( $allowedAuthorHeaders[$rHeader] ) ) {
793  wfDebugLog( 'api', 'CORS preflight failed on requested header: ' . $rHeader );
794  return false;
795  }
796  }
797  return true;
798  }
799 
808  protected static function wildcardToRegex( $wildcard ) {
809  $wildcard = preg_quote( $wildcard, '/' );
810  $wildcard = str_replace(
811  [ '\*', '\?' ],
812  [ '.*?', '.' ],
813  $wildcard
814  );
815 
816  return "/^https?:\/\/$wildcard$/";
817  }
818 
824  protected function sendCacheHeaders( $isError ) {
825  $response = $this->getRequest()->response();
826  $out = $this->getOutput();
827 
828  $out->addVaryHeader( 'Treat-as-Untrusted' );
829 
830  $config = $this->getConfig();
831 
832  if ( $config->get( 'VaryOnXFP' ) ) {
833  $out->addVaryHeader( 'X-Forwarded-Proto' );
834  }
835 
836  if ( !$isError && $this->mModule &&
837  ( $this->getRequest()->getMethod() === 'GET' || $this->getRequest()->getMethod() === 'HEAD' )
838  ) {
839  $etag = $this->mModule->getConditionalRequestData( 'etag' );
840  if ( $etag !== null ) {
841  $response->header( "ETag: $etag" );
842  }
843  $lastMod = $this->mModule->getConditionalRequestData( 'last-modified' );
844  if ( $lastMod !== null ) {
845  $response->header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822, $lastMod ) );
846  }
847  }
848 
849  // The logic should be:
850  // $this->mCacheControl['max-age'] is set?
851  // Use it, the module knows better than our guess.
852  // !$this->mModule || $this->mModule->isWriteMode(), and mCacheMode is private?
853  // Use 0 because we can guess caching is probably the wrong thing to do.
854  // Use $this->getParameter( 'maxage' ), which already defaults to 0.
855  $maxage = 0;
856  if ( isset( $this->mCacheControl['max-age'] ) ) {
857  $maxage = $this->mCacheControl['max-age'];
858  } elseif ( ( $this->mModule && !$this->mModule->isWriteMode() ) ||
859  $this->mCacheMode !== 'private'
860  ) {
861  $maxage = $this->getParameter( 'maxage' );
862  }
863  $privateCache = 'private, must-revalidate, max-age=' . $maxage;
864 
865  if ( $this->mCacheMode == 'private' ) {
866  $response->header( "Cache-Control: $privateCache" );
867  return;
868  }
869 
870  $useKeyHeader = $config->get( 'UseKeyHeader' );
871  if ( $this->mCacheMode == 'anon-public-user-private' ) {
872  $out->addVaryHeader( 'Cookie' );
873  $response->header( $out->getVaryHeader() );
874  if ( $useKeyHeader ) {
875  $response->header( $out->getKeyHeader() );
876  if ( $out->haveCacheVaryCookies() ) {
877  // Logged in, mark this request private
878  $response->header( "Cache-Control: $privateCache" );
879  return;
880  }
881  // Logged out, send normal public headers below
882  } elseif ( MediaWiki\Session\SessionManager::getGlobalSession()->isPersistent() ) {
883  // Logged in or otherwise has session (e.g. anonymous users who have edited)
884  // Mark request private
885  $response->header( "Cache-Control: $privateCache" );
886 
887  return;
888  } // else no Key and anonymous, send public headers below
889  }
890 
891  // Send public headers
892  $response->header( $out->getVaryHeader() );
893  if ( $useKeyHeader ) {
894  $response->header( $out->getKeyHeader() );
895  }
896 
897  // If nobody called setCacheMaxAge(), use the (s)maxage parameters
898  if ( !isset( $this->mCacheControl['s-maxage'] ) ) {
899  $this->mCacheControl['s-maxage'] = $this->getParameter( 'smaxage' );
900  }
901  if ( !isset( $this->mCacheControl['max-age'] ) ) {
902  $this->mCacheControl['max-age'] = $this->getParameter( 'maxage' );
903  }
904 
905  if ( !$this->mCacheControl['s-maxage'] && !$this->mCacheControl['max-age'] ) {
906  // Public cache not requested
907  // Sending a Vary header in this case is harmless, and protects us
908  // against conditional calls of setCacheMaxAge().
909  $response->header( "Cache-Control: $privateCache" );
910 
911  return;
912  }
913 
914  $this->mCacheControl['public'] = true;
915 
916  // Send an Expires header
917  $maxAge = min( $this->mCacheControl['s-maxage'], $this->mCacheControl['max-age'] );
918  $expiryUnixTime = ( $maxAge == 0 ? 1 : time() + $maxAge );
919  $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822, $expiryUnixTime ) );
920 
921  // Construct the Cache-Control header
922  $ccHeader = '';
923  $separator = '';
924  foreach ( $this->mCacheControl as $name => $value ) {
925  if ( is_bool( $value ) ) {
926  if ( $value ) {
927  $ccHeader .= $separator . $name;
928  $separator = ', ';
929  }
930  } else {
931  $ccHeader .= $separator . "$name=$value";
932  $separator = ', ';
933  }
934  }
935 
936  $response->header( "Cache-Control: $ccHeader" );
937  }
938 
942  private function createErrorPrinter() {
943  if ( !isset( $this->mPrinter ) ) {
944  $value = $this->getRequest()->getVal( 'format', self::API_DEFAULT_FORMAT );
945  if ( !$this->mModuleMgr->isDefined( $value, 'format' ) ) {
946  $value = self::API_DEFAULT_FORMAT;
947  }
948  $this->mPrinter = $this->createPrinterByName( $value );
949  }
950 
951  // Printer may not be able to handle errors. This is particularly
952  // likely if the module returns something for getCustomPrinter().
953  if ( !$this->mPrinter->canPrintErrors() ) {
954  $this->mPrinter = $this->createPrinterByName( self::API_DEFAULT_FORMAT );
955  }
956  }
957 
968  protected function errorMessageFromException( $e ) {
969  if ( $e instanceof UsageException ) {
970  // User entered incorrect parameters - generate error response
971  $errMessage = $e->getMessageArray();
972  } else {
973  $config = $this->getConfig();
974  // Something is seriously wrong
975  if ( ( $e instanceof DBQueryError ) && !$config->get( 'ShowSQLErrors' ) ) {
976  $info = 'Database query error';
977  } else {
978  $info = "Exception Caught: {$e->getMessage()}";
979  }
980 
981  $errMessage = [
982  'code' => 'internal_api_error_' . get_class( $e ),
983  'info' => '[' . WebRequest::getRequestId() . '] ' . $info,
984  ];
985  }
986  return $errMessage;
987  }
988 
995  protected function substituteResultWithError( $e ) {
996  $result = $this->getResult();
997  $config = $this->getConfig();
998 
999  $errMessage = $this->errorMessageFromException( $e );
1000  if ( $e instanceof UsageException ) {
1001  // User entered incorrect parameters - generate error response
1002  $link = wfExpandUrl( wfScript( 'api' ) );
1003  ApiResult::setContentValue( $errMessage, 'docref', "See $link for API usage" );
1004  } else {
1005  // Something is seriously wrong
1006  if ( $config->get( 'ShowExceptionDetails' ) ) {
1008  $errMessage,
1009  'trace',
1011  );
1012  }
1013  }
1014 
1015  // Remember all the warnings to re-add them later
1016  $warnings = $result->getResultData( [ 'warnings' ] );
1017 
1018  $result->reset();
1019  // Re-add the id
1020  $requestid = $this->getParameter( 'requestid' );
1021  if ( !is_null( $requestid ) ) {
1022  $result->addValue( null, 'requestid', $requestid, ApiResult::NO_SIZE_CHECK );
1023  }
1024  if ( $config->get( 'ShowHostnames' ) ) {
1025  // servedby is especially useful when debugging errors
1026  $result->addValue( null, 'servedby', wfHostname(), ApiResult::NO_SIZE_CHECK );
1027  }
1028  if ( $warnings !== null ) {
1029  $result->addValue( null, 'warnings', $warnings, ApiResult::NO_SIZE_CHECK );
1030  }
1031 
1032  $result->addValue( null, 'error', $errMessage, ApiResult::NO_SIZE_CHECK );
1033 
1034  return $errMessage['code'];
1035  }
1036 
1041  protected function setupExecuteAction() {
1042  // First add the id to the top element
1043  $result = $this->getResult();
1044  $requestid = $this->getParameter( 'requestid' );
1045  if ( !is_null( $requestid ) ) {
1046  $result->addValue( null, 'requestid', $requestid );
1047  }
1048 
1049  if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
1050  $servedby = $this->getParameter( 'servedby' );
1051  if ( $servedby ) {
1052  $result->addValue( null, 'servedby', wfHostname() );
1053  }
1054  }
1055 
1056  if ( $this->getParameter( 'curtimestamp' ) ) {
1057  $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601, time() ),
1059  }
1060 
1061  $params = $this->extractRequestParams();
1062 
1063  $this->mAction = $params['action'];
1064 
1065  if ( !is_string( $this->mAction ) ) {
1066  $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
1067  }
1068 
1069  return $params;
1070  }
1071 
1078  protected function setupModule() {
1079  // Instantiate the module requested by the user
1080  $module = $this->mModuleMgr->getModule( $this->mAction, 'action' );
1081  if ( $module === null ) {
1082  $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
1083  }
1084  $moduleParams = $module->extractRequestParams();
1085 
1086  // Check token, if necessary
1087  if ( $module->needsToken() === true ) {
1088  throw new MWException(
1089  "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
1090  'See documentation for ApiBase::needsToken for details.'
1091  );
1092  }
1093  if ( $module->needsToken() ) {
1094  if ( !$module->mustBePosted() ) {
1095  throw new MWException(
1096  "Module '{$module->getModuleName()}' must require POST to use tokens."
1097  );
1098  }
1099 
1100  if ( !isset( $moduleParams['token'] ) ) {
1101  $this->dieUsageMsg( [ 'missingparam', 'token' ] );
1102  }
1103 
1104  if ( !$this->getConfig()->get( 'DebugAPI' ) &&
1105  array_key_exists(
1106  $module->encodeParamName( 'token' ),
1107  $this->getRequest()->getQueryValues()
1108  )
1109  ) {
1110  $this->dieUsage(
1111  "The '{$module->encodeParamName( 'token' )}' parameter was " .
1112  'found in the query string, but must be in the POST body',
1113  'mustposttoken'
1114  );
1115  }
1116 
1117  if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) {
1118  $this->dieUsageMsg( 'sessionfailure' );
1119  }
1120  }
1121 
1122  return $module;
1123  }
1124 
1131  protected function checkMaxLag( $module, $params ) {
1132  if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
1133  $maxLag = $params['maxlag'];
1134  list( $host, $lag ) = wfGetLB()->getMaxLag();
1135  if ( $lag > $maxLag ) {
1136  $response = $this->getRequest()->response();
1137 
1138  $response->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
1139  $response->header( 'X-Database-Lag: ' . intval( $lag ) );
1140 
1141  if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
1142  $this->dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
1143  }
1144 
1145  $this->dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
1146  }
1147  }
1148 
1149  return true;
1150  }
1151 
1173  protected function checkConditionalRequestHeaders( $module ) {
1174  if ( $this->mInternalMode ) {
1175  // No headers to check in internal mode
1176  return true;
1177  }
1178 
1179  if ( $this->getRequest()->getMethod() !== 'GET' && $this->getRequest()->getMethod() !== 'HEAD' ) {
1180  // Don't check POSTs
1181  return true;
1182  }
1183 
1184  $return304 = false;
1185 
1186  $ifNoneMatch = array_diff(
1187  $this->getRequest()->getHeader( 'If-None-Match', WebRequest::GETHEADER_LIST ) ?: [],
1188  [ '' ]
1189  );
1190  if ( $ifNoneMatch ) {
1191  if ( $ifNoneMatch === [ '*' ] ) {
1192  // API responses always "exist"
1193  $etag = '*';
1194  } else {
1195  $etag = $module->getConditionalRequestData( 'etag' );
1196  }
1197  }
1198  if ( $ifNoneMatch && $etag !== null ) {
1199  $test = substr( $etag, 0, 2 ) === 'W/' ? substr( $etag, 2 ) : $etag;
1200  $match = array_map( function ( $s ) {
1201  return substr( $s, 0, 2 ) === 'W/' ? substr( $s, 2 ) : $s;
1202  }, $ifNoneMatch );
1203  $return304 = in_array( $test, $match, true );
1204  } else {
1205  $value = trim( $this->getRequest()->getHeader( 'If-Modified-Since' ) );
1206 
1207  // Some old browsers sends sizes after the date, like this:
1208  // Wed, 20 Aug 2003 06:51:19 GMT; length=5202
1209  // Ignore that.
1210  $i = strpos( $value, ';' );
1211  if ( $i !== false ) {
1212  $value = trim( substr( $value, 0, $i ) );
1213  }
1214 
1215  if ( $value !== '' ) {
1216  try {
1217  $ts = new MWTimestamp( $value );
1218  if (
1219  // RFC 7231 IMF-fixdate
1220  $ts->getTimestamp( TS_RFC2822 ) === $value ||
1221  // RFC 850
1222  $ts->format( 'l, d-M-y H:i:s' ) . ' GMT' === $value ||
1223  // asctime (with and without space-padded day)
1224  $ts->format( 'D M j H:i:s Y' ) === $value ||
1225  $ts->format( 'D M j H:i:s Y' ) === $value
1226  ) {
1227  $lastMod = $module->getConditionalRequestData( 'last-modified' );
1228  if ( $lastMod !== null ) {
1229  // Mix in some MediaWiki modification times
1230  $modifiedTimes = [
1231  'page' => $lastMod,
1232  'user' => $this->getUser()->getTouched(),
1233  'epoch' => $this->getConfig()->get( 'CacheEpoch' ),
1234  ];
1235  if ( $this->getConfig()->get( 'UseSquid' ) ) {
1236  // T46570: the core page itself may not change, but resources might
1237  $modifiedTimes['sepoch'] = wfTimestamp(
1238  TS_MW, time() - $this->getConfig()->get( 'SquidMaxage' )
1239  );
1240  }
1241  Hooks::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this->getOutput() ] );
1242  $lastMod = max( $modifiedTimes );
1243  $return304 = wfTimestamp( TS_MW, $lastMod ) <= $ts->getTimestamp( TS_MW );
1244  }
1245  }
1246  } catch ( TimestampException $e ) {
1247  // Invalid timestamp, ignore it
1248  }
1249  }
1250  }
1251 
1252  if ( $return304 ) {
1253  $this->getRequest()->response()->statusHeader( 304 );
1254 
1255  // Avoid outputting the compressed representation of a zero-length body
1256  MediaWiki\suppressWarnings();
1257  ini_set( 'zlib.output_compression', 0 );
1258  MediaWiki\restoreWarnings();
1260 
1261  return false;
1262  }
1263 
1264  return true;
1265  }
1266 
1271  protected function checkExecutePermissions( $module ) {
1272  $user = $this->getUser();
1273  if ( $module->isReadMode() && !User::isEveryoneAllowed( 'read' ) &&
1274  !$user->isAllowed( 'read' )
1275  ) {
1276  $this->dieUsageMsg( 'readrequired' );
1277  }
1278 
1279  if ( $module->isWriteMode() ) {
1280  if ( !$this->mEnableWrite ) {
1281  $this->dieUsageMsg( 'writedisabled' );
1282  } elseif ( !$user->isAllowed( 'writeapi' ) ) {
1283  $this->dieUsageMsg( 'writerequired' );
1284  } elseif ( $this->getRequest()->getHeader( 'Promise-Non-Write-API-Action' ) ) {
1285  $this->dieUsage(
1286  'Promise-Non-Write-API-Action HTTP header cannot be sent to write API modules',
1287  'promised-nonwrite-api'
1288  );
1289  }
1290 
1291  $this->checkReadOnly( $module );
1292  }
1293 
1294  // Allow extensions to stop execution for arbitrary reasons.
1295  $message = false;
1296  if ( !Hooks::run( 'ApiCheckCanExecute', [ $module, $user, &$message ] ) ) {
1297  $this->dieUsageMsg( $message );
1298  }
1299  }
1300 
1305  protected function checkReadOnly( $module ) {
1306  if ( wfReadOnly() ) {
1307  $this->dieReadOnly();
1308  }
1309 
1310  if ( $module->isWriteMode()
1311  && in_array( 'bot', $this->getUser()->getGroups() )
1312  && wfGetLB()->getServerCount() > 1
1313  ) {
1314  $this->checkBotReadOnly();
1315  }
1316  }
1317 
1321  private function checkBotReadOnly() {
1322  // Figure out how many servers have passed the lag threshold
1323  $numLagged = 0;
1324  $lagLimit = $this->getConfig()->get( 'APIMaxLagThreshold' );
1325  $laggedServers = [];
1326  $loadBalancer = wfGetLB();
1327  foreach ( $loadBalancer->getLagTimes() as $serverIndex => $lag ) {
1328  if ( $lag > $lagLimit ) {
1329  ++$numLagged;
1330  $laggedServers[] = $loadBalancer->getServerName( $serverIndex ) . " ({$lag}s)";
1331  }
1332  }
1333 
1334  // If a majority of slaves are too lagged then disallow writes
1335  $slaveCount = wfGetLB()->getServerCount() - 1;
1336  if ( $numLagged >= ceil( $slaveCount / 2 ) ) {
1337  $laggedServers = implode( ', ', $laggedServers );
1338  wfDebugLog(
1339  'api-readonly',
1340  "Api request failed as read only because the following DBs are lagged: $laggedServers"
1341  );
1342 
1343  $parsed = $this->parseMsg( [ 'readonlytext' ] );
1344  $this->dieUsage(
1345  $parsed['info'],
1346  $parsed['code'],
1347  /* http error */
1348  0,
1349  [ 'readonlyreason' => "Waiting for $numLagged lagged database(s)" ]
1350  );
1351  }
1352  }
1353 
1358  protected function checkAsserts( $params ) {
1359  if ( isset( $params['assert'] ) ) {
1360  $user = $this->getUser();
1361  switch ( $params['assert'] ) {
1362  case 'user':
1363  if ( $user->isAnon() ) {
1364  $this->dieUsage( 'Assertion that the user is logged in failed', 'assertuserfailed' );
1365  }
1366  break;
1367  case 'bot':
1368  if ( !$user->isAllowed( 'bot' ) ) {
1369  $this->dieUsage( 'Assertion that the user has the bot right failed', 'assertbotfailed' );
1370  }
1371  break;
1372  }
1373  }
1374  }
1375 
1381  protected function setupExternalResponse( $module, $params ) {
1382  $request = $this->getRequest();
1383  if ( !$request->wasPosted() && $module->mustBePosted() ) {
1384  // Module requires POST. GET request might still be allowed
1385  // if $wgDebugApi is true, otherwise fail.
1386  $this->dieUsageMsgOrDebug( [ 'mustbeposted', $this->mAction ] );
1387  }
1388 
1389  // See if custom printer is used
1390  $this->mPrinter = $module->getCustomPrinter();
1391  if ( is_null( $this->mPrinter ) ) {
1392  // Create an appropriate printer
1393  $this->mPrinter = $this->createPrinterByName( $params['format'] );
1394  }
1395 
1396  if ( $request->getProtocol() === 'http' && (
1397  $request->getSession()->shouldForceHTTPS() ||
1398  ( $this->getUser()->isLoggedIn() &&
1399  $this->getUser()->requiresHTTPS() )
1400  ) ) {
1401  $this->logFeatureUsage( 'https-expected' );
1402  $this->setWarning( 'HTTP used when HTTPS was expected' );
1403  }
1404  }
1405 
1409  protected function executeAction() {
1410  $params = $this->setupExecuteAction();
1411  $module = $this->setupModule();
1412  $this->mModule = $module;
1413 
1414  if ( !$this->mInternalMode ) {
1415  $this->setRequestExpectations( $module );
1416  }
1417 
1418  $this->checkExecutePermissions( $module );
1419 
1420  if ( !$this->checkMaxLag( $module, $params ) ) {
1421  return;
1422  }
1423 
1424  if ( !$this->checkConditionalRequestHeaders( $module ) ) {
1425  return;
1426  }
1427 
1428  if ( !$this->mInternalMode ) {
1429  $this->setupExternalResponse( $module, $params );
1430  }
1431 
1432  $this->checkAsserts( $params );
1433 
1434  // Execute
1435  $module->execute();
1436  Hooks::run( 'APIAfterExecute', [ &$module ] );
1437 
1438  $this->reportUnusedParams();
1439 
1440  if ( !$this->mInternalMode ) {
1441  // append Debug information
1443 
1444  // Print result data
1445  $this->printResult( false );
1446  }
1447  }
1448 
1453  protected function setRequestExpectations( ApiBase $module ) {
1454  $limits = $this->getConfig()->get( 'TrxProfilerLimits' );
1455  $trxProfiler = Profiler::instance()->getTransactionProfiler();
1456  if ( $this->getRequest()->hasSafeMethod() ) {
1457  $trxProfiler->setExpectations( $limits['GET'], __METHOD__ );
1458  } elseif ( $this->getRequest()->wasPosted() && !$module->isWriteMode() ) {
1459  $trxProfiler->setExpectations( $limits['POST-nonwrite'], __METHOD__ );
1460  $this->getRequest()->markAsSafeRequest();
1461  } else {
1462  $trxProfiler->setExpectations( $limits['POST'], __METHOD__ );
1463  }
1464  }
1465 
1471  protected function logRequest( $time, $e = null ) {
1472  $request = $this->getRequest();
1473  $logCtx = [
1474  'ts' => time(),
1475  'ip' => $request->getIP(),
1476  'userAgent' => $this->getUserAgent(),
1477  'wiki' => wfWikiID(),
1478  'timeSpentBackend' => (int) round( $time * 1000 ),
1479  'hadError' => $e !== null,
1480  'errorCodes' => [],
1481  'params' => [],
1482  ];
1483 
1484  if ( $e ) {
1485  $logCtx['errorCodes'][] = $this->errorMessageFromException( $e )['code'];
1486  }
1487 
1488  // Construct space separated message for 'api' log channel
1489  $msg = "API {$request->getMethod()} " .
1490  wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
1491  " {$logCtx['ip']} " .
1492  "T={$logCtx['timeSpentBackend']}ms";
1493 
1494  foreach ( $this->getParamsUsed() as $name ) {
1495  $value = $request->getVal( $name );
1496  if ( $value === null ) {
1497  continue;
1498  }
1499 
1500  if ( strlen( $value ) > 256 ) {
1501  $value = substr( $value, 0, 256 );
1502  $encValue = $this->encodeRequestLogValue( $value ) . '[...]';
1503  } else {
1504  $encValue = $this->encodeRequestLogValue( $value );
1505  }
1506 
1507  $logCtx['params'][$name] = $value;
1508  $msg .= " {$name}={$encValue}";
1509  }
1510 
1511  wfDebugLog( 'api', $msg, 'private' );
1512  // ApiAction channel is for structured data consumers
1513  wfDebugLog( 'ApiAction', '', 'private', $logCtx );
1514  }
1515 
1521  protected function encodeRequestLogValue( $s ) {
1522  static $table;
1523  if ( !$table ) {
1524  $chars = ';@$!*(),/:';
1525  $numChars = strlen( $chars );
1526  for ( $i = 0; $i < $numChars; $i++ ) {
1527  $table[rawurlencode( $chars[$i] )] = $chars[$i];
1528  }
1529  }
1530 
1531  return strtr( rawurlencode( $s ), $table );
1532  }
1533 
1538  protected function getParamsUsed() {
1539  return array_keys( $this->mParamsUsed );
1540  }
1541 
1546  public function markParamsUsed( $params ) {
1547  $this->mParamsUsed += array_fill_keys( (array)$params, true );
1548  }
1549 
1556  public function getVal( $name, $default = null ) {
1557  $this->mParamsUsed[$name] = true;
1558 
1559  $ret = $this->getRequest()->getVal( $name );
1560  if ( $ret === null ) {
1561  if ( $this->getRequest()->getArray( $name ) !== null ) {
1562  // See bug 10262 for why we don't just implode( '|', ... ) the
1563  // array.
1564  $this->setWarning(
1565  "Parameter '$name' uses unsupported PHP array syntax"
1566  );
1567  }
1568  $ret = $default;
1569  }
1570  return $ret;
1571  }
1572 
1579  public function getCheck( $name ) {
1580  return $this->getVal( $name, null ) !== null;
1581  }
1582 
1590  public function getUpload( $name ) {
1591  $this->mParamsUsed[$name] = true;
1592 
1593  return $this->getRequest()->getUpload( $name );
1594  }
1595 
1600  protected function reportUnusedParams() {
1601  $paramsUsed = $this->getParamsUsed();
1602  $allParams = $this->getRequest()->getValueNames();
1603 
1604  if ( !$this->mInternalMode ) {
1605  // Printer has not yet executed; don't warn that its parameters are unused
1606  $printerParams = array_map(
1607  [ $this->mPrinter, 'encodeParamName' ],
1608  array_keys( $this->mPrinter->getFinalParams() ?: [] )
1609  );
1610  $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1611  } else {
1612  $unusedParams = array_diff( $allParams, $paramsUsed );
1613  }
1614 
1615  if ( count( $unusedParams ) ) {
1616  $s = count( $unusedParams ) > 1 ? 's' : '';
1617  $this->setWarning( "Unrecognized parameter$s: '" . implode( $unusedParams, "', '" ) . "'" );
1618  }
1619  }
1620 
1626  protected function printResult( $isError ) {
1627  if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
1628  $this->setWarning( 'SECURITY WARNING: $wgDebugAPI is enabled' );
1629  }
1630 
1631  $printer = $this->mPrinter;
1632  $printer->initPrinter( false );
1633  $printer->execute();
1634  $printer->closePrinter();
1635  }
1636 
1640  public function isReadMode() {
1641  return false;
1642  }
1643 
1649  public function getAllowedParams() {
1650  return [
1651  'action' => [
1652  ApiBase::PARAM_DFLT => 'help',
1653  ApiBase::PARAM_TYPE => 'submodule',
1654  ],
1655  'format' => [
1657  ApiBase::PARAM_TYPE => 'submodule',
1658  ],
1659  'maxlag' => [
1660  ApiBase::PARAM_TYPE => 'integer'
1661  ],
1662  'smaxage' => [
1663  ApiBase::PARAM_TYPE => 'integer',
1664  ApiBase::PARAM_DFLT => 0
1665  ],
1666  'maxage' => [
1667  ApiBase::PARAM_TYPE => 'integer',
1668  ApiBase::PARAM_DFLT => 0
1669  ],
1670  'assert' => [
1671  ApiBase::PARAM_TYPE => [ 'user', 'bot' ]
1672  ],
1673  'requestid' => null,
1674  'servedby' => false,
1675  'curtimestamp' => false,
1676  'origin' => null,
1677  'uselang' => [
1678  ApiBase::PARAM_DFLT => 'user',
1679  ],
1680  ];
1681  }
1682 
1684  protected function getExamplesMessages() {
1685  return [
1686  'action=help'
1687  => 'apihelp-help-example-main',
1688  'action=help&recursivesubmodules=1'
1689  => 'apihelp-help-example-recursive',
1690  ];
1691  }
1692 
1693  public function modifyHelp( array &$help, array $options, array &$tocData ) {
1694  // Wish PHP had an "array_insert_before". Instead, we have to manually
1695  // reindex the array to get 'permissions' in the right place.
1696  $oldHelp = $help;
1697  $help = [];
1698  foreach ( $oldHelp as $k => $v ) {
1699  if ( $k === 'submodules' ) {
1700  $help['permissions'] = '';
1701  }
1702  $help[$k] = $v;
1703  }
1704  $help['datatypes'] = '';
1705  $help['credits'] = '';
1706 
1707  // Fill 'permissions'
1708  $help['permissions'] .= Html::openElement( 'div',
1709  [ 'class' => 'apihelp-block apihelp-permissions' ] );
1710  $m = $this->msg( 'api-help-permissions' );
1711  if ( !$m->isDisabled() ) {
1712  $help['permissions'] .= Html::rawElement( 'div', [ 'class' => 'apihelp-block-head' ],
1713  $m->numParams( count( self::$mRights ) )->parse()
1714  );
1715  }
1716  $help['permissions'] .= Html::openElement( 'dl' );
1717  foreach ( self::$mRights as $right => $rightMsg ) {
1718  $help['permissions'] .= Html::element( 'dt', null, $right );
1719 
1720  $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse();
1721  $help['permissions'] .= Html::rawElement( 'dd', null, $rightMsg );
1722 
1723  $groups = array_map( function ( $group ) {
1724  return $group == '*' ? 'all' : $group;
1725  }, User::getGroupsWithPermission( $right ) );
1726 
1727  $help['permissions'] .= Html::rawElement( 'dd', null,
1728  $this->msg( 'api-help-permissions-granted-to' )
1729  ->numParams( count( $groups ) )
1730  ->params( $this->getLanguage()->commaList( $groups ) )
1731  ->parse()
1732  );
1733  }
1734  $help['permissions'] .= Html::closeElement( 'dl' );
1735  $help['permissions'] .= Html::closeElement( 'div' );
1736 
1737  // Fill 'datatypes' and 'credits', if applicable
1738  if ( empty( $options['nolead'] ) ) {
1739  $level = $options['headerlevel'];
1740  $tocnumber = &$options['tocnumber'];
1741 
1742  $header = $this->msg( 'api-help-datatypes-header' )->parse();
1743 
1744  // Add an additional span with sanitized ID
1745  if ( !$this->getConfig()->get( 'ExperimentalHtmlIds' ) ) {
1746  $header = Html::element( 'span', [ 'id' => Sanitizer::escapeId( 'main/datatypes' ) ] ) .
1747  $header;
1748  }
1749  $help['datatypes'] .= Html::rawElement( 'h' . min( 6, $level ),
1750  [ 'id' => 'main/datatypes', 'class' => 'apihelp-header' ],
1751  $header
1752  );
1753  $help['datatypes'] .= $this->msg( 'api-help-datatypes' )->parseAsBlock();
1754  if ( !isset( $tocData['main/datatypes'] ) ) {
1755  $tocnumber[$level]++;
1756  $tocData['main/datatypes'] = [
1757  'toclevel' => count( $tocnumber ),
1758  'level' => $level,
1759  'anchor' => 'main/datatypes',
1760  'line' => $header,
1761  'number' => implode( '.', $tocnumber ),
1762  'index' => false,
1763  ];
1764  }
1765 
1766  // Add an additional span with sanitized ID
1767  if ( !$this->getConfig()->get( 'ExperimentalHtmlIds' ) ) {
1768  $header = Html::element( 'span', [ 'id' => Sanitizer::escapeId( 'main/credits' ) ] ) .
1769  $header;
1770  }
1771  $header = $this->msg( 'api-credits-header' )->parse();
1772  $help['credits'] .= Html::rawElement( 'h' . min( 6, $level ),
1773  [ 'id' => 'main/credits', 'class' => 'apihelp-header' ],
1774  $header
1775  );
1776  $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
1777  if ( !isset( $tocData['main/credits'] ) ) {
1778  $tocnumber[$level]++;
1779  $tocData['main/credits'] = [
1780  'toclevel' => count( $tocnumber ),
1781  'level' => $level,
1782  'anchor' => 'main/credits',
1783  'line' => $header,
1784  'number' => implode( '.', $tocnumber ),
1785  'index' => false,
1786  ];
1787  }
1788  }
1789  }
1790 
1791  private $mCanApiHighLimits = null;
1792 
1797  public function canApiHighLimits() {
1798  if ( !isset( $this->mCanApiHighLimits ) ) {
1799  $this->mCanApiHighLimits = $this->getUser()->isAllowed( 'apihighlimits' );
1800  }
1801 
1802  return $this->mCanApiHighLimits;
1803  }
1804 
1809  public function getModuleManager() {
1810  return $this->mModuleMgr;
1811  }
1812 
1821  public function getUserAgent() {
1822  return trim(
1823  $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
1824  $this->getRequest()->getHeader( 'User-agent' )
1825  );
1826  }
1827 
1828  /************************************************************************/
1839  public function setHelp( $help = true ) {
1840  wfDeprecated( __METHOD__, '1.25' );
1841  $this->mPrinter->setHelp( $help );
1842  }
1843 
1850  public function makeHelpMsg() {
1851  wfDeprecated( __METHOD__, '1.25' );
1852 
1853  $this->setHelp();
1854  $cacheHelpTimeout = $this->getConfig()->get( 'APICacheHelpTimeout' );
1855 
1856  return ObjectCache::getMainWANInstance()->getWithSetCallback(
1857  wfMemcKey(
1858  'apihelp',
1859  $this->getModuleName(),
1860  str_replace( ' ', '_', SpecialVersion::getVersion( 'nodb' ) )
1861  ),
1862  $cacheHelpTimeout > 0 ? $cacheHelpTimeout : WANObjectCache::TTL_UNCACHEABLE,
1863  [ $this, 'reallyMakeHelpMsg' ]
1864  );
1865  }
1866 
1871  public function reallyMakeHelpMsg() {
1872  wfDeprecated( __METHOD__, '1.25' );
1873  $this->setHelp();
1874 
1875  // Use parent to make default message for the main module
1876  $msg = parent::makeHelpMsg();
1877 
1878  $asterisks = str_repeat( '*** ', 14 );
1879  $msg .= "\n\n$asterisks Modules $asterisks\n\n";
1880 
1881  foreach ( $this->mModuleMgr->getNames( 'action' ) as $name ) {
1882  $module = $this->mModuleMgr->getModule( $name );
1883  $msg .= self::makeHelpMsgHeader( $module, 'action' );
1884 
1885  $msg2 = $module->makeHelpMsg();
1886  if ( $msg2 !== false ) {
1887  $msg .= $msg2;
1888  }
1889  $msg .= "\n";
1890  }
1891 
1892  $msg .= "\n$asterisks Permissions $asterisks\n\n";
1893  foreach ( self::$mRights as $right => $rightMsg ) {
1894  $rightsMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )
1895  ->useDatabase( false )
1896  ->inLanguage( 'en' )
1897  ->text();
1898  $groups = User::getGroupsWithPermission( $right );
1899  $msg .= '* ' . $right . " *\n $rightsMsg" .
1900  "\nGranted to:\n " . str_replace( '*', 'all', implode( ', ', $groups ) ) . "\n\n";
1901  }
1902 
1903  $msg .= "\n$asterisks Formats $asterisks\n\n";
1904  foreach ( $this->mModuleMgr->getNames( 'format' ) as $name ) {
1905  $module = $this->mModuleMgr->getModule( $name );
1906  $msg .= self::makeHelpMsgHeader( $module, 'format' );
1907  $msg2 = $module->makeHelpMsg();
1908  if ( $msg2 !== false ) {
1909  $msg .= $msg2;
1910  }
1911  $msg .= "\n";
1912  }
1913 
1914  $credits = $this->msg( 'api-credits' )->useDatabase( 'false' )->inLanguage( 'en' )->text();
1915  $credits = str_replace( "\n", "\n ", $credits );
1916  $msg .= "\n*** Credits: ***\n $credits\n";
1917 
1918  return $msg;
1919  }
1920 
1928  public static function makeHelpMsgHeader( $module, $paramName ) {
1929  wfDeprecated( __METHOD__, '1.25' );
1930  $modulePrefix = $module->getModulePrefix();
1931  if ( strval( $modulePrefix ) !== '' ) {
1932  $modulePrefix = "($modulePrefix) ";
1933  }
1934 
1935  return "* $paramName={$module->getModuleName()} $modulePrefix*";
1936  }
1937 
1940 }
1941 
1948 
1949  private $mCodestr;
1950 
1954  private $mExtraData;
1955 
1962  public function __construct( $message, $codestr, $code = 0, $extradata = null ) {
1963  parent::__construct( $message, $code );
1964  $this->mCodestr = $codestr;
1965  $this->mExtraData = $extradata;
1966 
1967  // This should never happen, so throw an exception about it that will
1968  // hopefully get logged with a backtrace (T138585)
1969  if ( !is_string( $codestr ) || $codestr === '' ) {
1970  throw new InvalidArgumentException( 'Invalid $codestr, was ' .
1971  ( $codestr === '' ? 'empty string' : gettype( $codestr ) )
1972  );
1973  }
1974  }
1975 
1979  public function getCodeString() {
1980  return $this->mCodestr;
1981  }
1982 
1986  public function getMessageArray() {
1987  $result = [
1988  'code' => $this->mCodestr,
1989  'info' => $this->getMessage()
1990  ];
1991  if ( is_array( $this->mExtraData ) ) {
1992  $result = array_merge( $result, $this->mExtraData );
1993  }
1994 
1995  return $result;
1996  }
1997 
2001  public function __toString() {
2002  return "{$this->getCodeString()}: {$this->getMessage()}";
2003  }
2004 }
2005 
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:1649
static closeElement($element)
Returns "</$element>".
Definition: Html.php:306
getModuleManager()
Overrides to return this instance's module manager.
Definition: ApiMain.php:1809
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:1821
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:331
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:776
Database error base class.
printResult($isError)
Print results using the current printer.
Definition: ApiMain.php:1626
checkConditionalRequestHeaders($module)
Check selected RFC 7232 precondition headers.
Definition: ApiMain.php:1173
the array() calling protocol came about after MediaWiki 1.4rc1.
$mEnableWrite
Definition: ApiMain.php:145
getLanguage()
Get the Language object.
static getRequestId()
Get the unique request ID.
Definition: WebRequest.php:268
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:487
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:1693
__construct($context=null, $enableWrite=false)
Constructs an instance of ApiMain that utilizes the module and format specified by $request...
Definition: ApiMain.php:164
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:189
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:1305
bool null $lacksSameOriginSecurity
Cached return value from self::lacksSameOriginSecurity()
Definition: ApiMain.php:155
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException'returning false will NOT prevent logging $e
Definition: hooks.txt:1980
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
The WebRequest class encapsulates getting at data passed in the URL or via a POSTed form stripping il...
Definition: WebRequest.php:37
wfHostname()
Fetch server name for use in error reporting etc.
$mCacheControl
Definition: ApiMain.php:151
static getInstance($channel)
Get a named logger instance from the currently configured logger factory.
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:772
static static static ApiFormatBase $mPrinter
Definition: ApiMain.php:127
const TTL_UNCACHEABLE
Idiom for getWithSetCallback() callbacks to avoid calling set()
setCacheMaxAge($maxage)
Set how long the response should be cached.
Definition: ApiMain.php:379
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:271
$value
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:1797
The MediaWiki class is the helper class for the index.php entry point.
Definition: MediaWiki.php:28
wfUrlencode($s)
We want some things to be included as literal characters in our title URLs for prettiness, which urlencode encodes by default.
this hook is for auditing only $response
Definition: hooks.txt:776
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:550
static handleApiBeforeMainException(Exception $e)
Handle an exception from the ApiBeforeMain hook.
Definition: ApiMain.php:611
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:411
ApiBase $mModule
Definition: ApiMain.php:148
see documentation in includes Linker php for Linker::makeImageLink & $time
Definition: hooks.txt:1629
static static static $mRights
List of user roles that are specifically relevant to the API.
Definition: ApiMain.php:124
reallyMakeHelpMsg()
Definition: ApiMain.php:1871
setupExternalResponse($module, $params)
Check POST for external response and setup result printer.
Definition: ApiMain.php:1381
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:452
errorMessageFromException($e)
Create an error message for the given exception.
Definition: ApiMain.php:968
static isEveryoneAllowed($right)
Check if all users may be assumed to have the given permission.
Definition: User.php:4842
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':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:1814
setupModule()
Set up the module for response.
Definition: ApiMain.php:1078
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:2621
makeHelpMsg()
Override the parent to generate help messages for all available modules.
Definition: ApiMain.php:1850
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:808
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:1816
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:1453
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:1020
const TS_ISO_8601
ISO 8601 format with no timezone: 1986-02-09T20:00:00Z.
getConfig()
Get the Config object.
MediaWiki exception.
Definition: MWException.php:26
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:1409
isReadMode()
Definition: ApiMain.php:1640
handleCORS()
Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
Definition: ApiMain.php:643
setupExecuteAction()
Set up for the execution.
Definition: ApiMain.php:1041
wfDeprecated($function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
$mCacheMode
Definition: ApiMain.php:150
Format errors and warnings in the old style, for backwards compatibility.
$mErrorFormatter
Definition: ApiMain.php:141
lacksSameOriginSecurity()
Get the security flag for the current request.
Definition: ApiMain.php:288
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:463
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:748
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:1928
$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:1521
checkMaxLag($module, $params)
Check the max lag if necessary.
Definition: ApiMain.php:1131
setWarning($warning)
Set warning section for this module.
Definition: ApiBase.php:1450
$mCanApiHighLimits
Definition: ApiMain.php:1791
static getRedactedTraceAsString($e)
Generate a string representation of an exception's stack trace.
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:1816
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:776
static static $Formats
List of available formats: format name => format class.
Definition: ApiMain.php:106
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:1538
getExamplesMessages()
Definition: ApiMain.php:1684
logRequest($time, $e=null)
Log the preceding request.
Definition: ApiMain.php:1471
getErrorFormatter()
Get the ApiErrorFormatter object associated with current request.
Definition: ApiMain.php:323
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:1169
getUpload($name)
Get a request upload, and register the fact that it was used, for logging.
Definition: ApiMain.php:1590
const TS_MW
MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
markParamsUsed($params)
Mark parameters as used.
Definition: ApiMain.php:1546
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:1321
getModule()
Get the API module object.
Definition: ApiMain.php:361
error also a ContextSource you ll probably need to make sure the header is varied on $request
Definition: hooks.txt:2458
setHelp($help=true)
Sets whether the pretty-printer should format bold and $italics$.
Definition: ApiMain.php:1839
static appendDebugInfoToApiResult(IContextSource $context, ApiResult $result)
Append the debug info to given ApiResult.
Definition: MWDebug.php:495
WebRequest clone which takes values from a provided array.
Definition: FauxRequest.php:33
$mSquidMaxage
Definition: ApiMain.php:146
$mParamsUsed
Definition: ApiMain.php:152
reportUnusedParams()
Report unused parameters, so the client gets a hint in case it gave us parameters we don't know...
Definition: ApiMain.php:1600
wfClearOutputBuffers()
More legible than passing a 'false' parameter to wfResetOutputBuffers():
null array $mExtraData
Definition: ApiMain.php:1954
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:370
wfMemcKey()
Make a cache key for the local wiki.
checkAsserts($params)
Check asserts of the user's rights.
Definition: ApiMain.php:1358
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:1579
logFeatureUsage($feature)
Write logging information for API features to a debug log, for usage analysis.
Definition: ApiBase.php:2200
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:824
getVal($name, $default=null)
Get a request value, and register the fact that it was used, for logging.
Definition: ApiMain.php:1556
__construct($message, $codestr, $code=0, $extradata=null)
Definition: ApiMain.php:1962
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:146
substituteResultWithError($e)
Replace the result data with the information about an exception.
Definition: ApiMain.php:995
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:141
static getGroupsWithPermission($role)
Get all the groups who have a given permission.
Definition: User.php:4799
execute()
Execute api request.
Definition: ApiMain.php:475
This exception will be thrown when dieUsage is called to stop module execution.
Definition: ApiMain.php:1947
getResult()
Get the ApiResult object associated with current request.
Definition: ApiMain.php:280
checkExecutePermissions($module)
Check for sufficient permissions to execute.
Definition: ApiMain.php:1271
createErrorPrinter()
Create the printer for error output.
Definition: ApiMain.php:942
$wgUser
Definition: Setup.php:801
isWriteMode()
Indicates whether this module requires write mode.
Definition: ApiBase.php:364
ApiContinuationManager null $mContinuationManager
Definition: ApiMain.php:143
setContinuationManager($manager)
Set the continuation manager.
Definition: ApiMain.php:339
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:542