MediaWiki  1.27.2
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  private $mParamsSensitive = [];
149 
151  private $lacksSameOriginSecurity = null;
152 
160  public function __construct( $context = null, $enableWrite = false ) {
161  if ( $context === null ) {
163  } elseif ( $context instanceof WebRequest ) {
164  // BC for pre-1.19
165  $request = $context;
167  }
168  // We set a derivative context so we can change stuff later
169  $this->setContext( new DerivativeContext( $context ) );
170 
171  if ( isset( $request ) ) {
172  $this->getContext()->setRequest( $request );
173  }
174 
175  $this->mInternalMode = ( $this->getRequest() instanceof FauxRequest );
176 
177  // Special handling for the main module: $parent === $this
178  parent::__construct( $this, $this->mInternalMode ? 'main_int' : 'main' );
179 
180  if ( !$this->mInternalMode ) {
181  // Impose module restrictions.
182  // If the current user cannot read,
183  // Remove all modules other than login
184  global $wgUser;
185 
186  if ( $this->lacksSameOriginSecurity() ) {
187  // If we're in a mode that breaks the same-origin policy, strip
188  // user credentials for security.
189  wfDebug( "API: stripping user credentials when the same-origin policy is not applied\n" );
190  $wgUser = new User();
191  $this->getContext()->setUser( $wgUser );
192  }
193  }
194 
195  $uselang = $this->getParameter( 'uselang' );
196  if ( $uselang === 'user' ) {
197  // Assume the parent context is going to return the user language
198  // for uselang=user (see T85635).
199  } else {
200  if ( $uselang === 'content' ) {
202  $uselang = $wgContLang->getCode();
203  }
205  $this->getContext()->setLanguage( $code );
206  if ( !$this->mInternalMode ) {
207  global $wgLang;
208  $wgLang = $this->getContext()->getLanguage();
209  RequestContext::getMain()->setLanguage( $wgLang );
210  }
211  }
212 
213  $config = $this->getConfig();
214  $this->mModuleMgr = new ApiModuleManager( $this );
215  $this->mModuleMgr->addModules( self::$Modules, 'action' );
216  $this->mModuleMgr->addModules( $config->get( 'APIModules' ), 'action' );
217  $this->mModuleMgr->addModules( self::$Formats, 'format' );
218  $this->mModuleMgr->addModules( $config->get( 'APIFormatModules' ), 'format' );
219 
220  Hooks::run( 'ApiMain::moduleManager', [ $this->mModuleMgr ] );
221 
222  $this->mResult = new ApiResult( $this->getConfig()->get( 'APIMaxResultSize' ) );
223  $this->mErrorFormatter = new ApiErrorFormatter_BackCompat( $this->mResult );
224  $this->mResult->setErrorFormatter( $this->mErrorFormatter );
225  $this->mResult->setMainForContinuation( $this );
226  $this->mContinuationManager = null;
227  $this->mEnableWrite = $enableWrite;
228 
229  $this->mSquidMaxage = -1; // flag for executeActionWithErrorHandling()
230  $this->mCommit = false;
231  }
232 
237  public function isInternalMode() {
238  return $this->mInternalMode;
239  }
240 
246  public function getResult() {
247  return $this->mResult;
248  }
249 
254  public function lacksSameOriginSecurity() {
255  if ( $this->lacksSameOriginSecurity !== null ) {
257  }
258 
259  $request = $this->getRequest();
260 
261  // JSONP mode
262  if ( $request->getVal( 'callback' ) !== null ) {
263  $this->lacksSameOriginSecurity = true;
264  return true;
265  }
266 
267  // Header to be used from XMLHTTPRequest when the request might
268  // otherwise be used for XSS.
269  if ( $request->getHeader( 'Treat-as-Untrusted' ) !== false ) {
270  $this->lacksSameOriginSecurity = true;
271  return true;
272  }
273 
274  // Allow extensions to override.
275  $this->lacksSameOriginSecurity = !Hooks::run( 'RequestHasSameOriginSecurity', [ $request ] );
277  }
278 
283  public function getErrorFormatter() {
284  return $this->mErrorFormatter;
285  }
286 
291  public function getContinuationManager() {
293  }
294 
299  public function setContinuationManager( $manager ) {
300  if ( $manager !== null ) {
301  if ( !$manager instanceof ApiContinuationManager ) {
302  throw new InvalidArgumentException( __METHOD__ . ': Was passed ' .
303  is_object( $manager ) ? get_class( $manager ) : gettype( $manager )
304  );
305  }
306  if ( $this->mContinuationManager !== null ) {
307  throw new UnexpectedValueException(
308  __METHOD__ . ': tried to set manager from ' . $manager->getSource() .
309  ' when a manager is already set from ' . $this->mContinuationManager->getSource()
310  );
311  }
312  }
313  $this->mContinuationManager = $manager;
314  }
315 
321  public function getModule() {
322  return $this->mModule;
323  }
324 
330  public function getPrinter() {
331  return $this->mPrinter;
332  }
333 
339  public function setCacheMaxAge( $maxage ) {
340  $this->setCacheControl( [
341  'max-age' => $maxage,
342  's-maxage' => $maxage
343  ] );
344  }
345 
371  public function setCacheMode( $mode ) {
372  if ( !in_array( $mode, [ 'private', 'public', 'anon-public-user-private' ] ) ) {
373  wfDebug( __METHOD__ . ": unrecognised cache mode \"$mode\"\n" );
374 
375  // Ignore for forwards-compatibility
376  return;
377  }
378 
379  if ( !User::isEveryoneAllowed( 'read' ) ) {
380  // Private wiki, only private headers
381  if ( $mode !== 'private' ) {
382  wfDebug( __METHOD__ . ": ignoring request for $mode cache mode, private wiki\n" );
383 
384  return;
385  }
386  }
387 
388  if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) {
389  // User language is used for i18n, so we don't want to publicly
390  // cache. Anons are ok, because if they have non-default language
391  // then there's an appropriate Vary header set by whatever set
392  // their non-default language.
393  wfDebug( __METHOD__ . ": downgrading cache mode 'public' to " .
394  "'anon-public-user-private' due to uselang=user\n" );
395  $mode = 'anon-public-user-private';
396  }
397 
398  wfDebug( __METHOD__ . ": setting cache mode $mode\n" );
399  $this->mCacheMode = $mode;
400  }
401 
412  public function setCacheControl( $directives ) {
413  $this->mCacheControl = $directives + $this->mCacheControl;
414  }
415 
423  public function createPrinterByName( $format ) {
424  $printer = $this->mModuleMgr->getModule( $format, 'format' );
425  if ( $printer === null ) {
426  $this->dieUsage( "Unrecognized format: {$format}", 'unknown_format' );
427  }
428 
429  return $printer;
430  }
431 
435  public function execute() {
436  if ( $this->mInternalMode ) {
437  $this->executeAction();
438  } else {
439  $start = microtime( true );
441  if ( $this->isWriteMode() && $this->getRequest()->wasPosted() ) {
442  $timeMs = 1000 * max( 0, microtime( true ) - $start );
443  $this->getStats()->timing(
444  'api.' . $this->getModuleName() . '.executeTiming', $timeMs );
445  }
446  }
447  }
448 
453  protected function executeActionWithErrorHandling() {
454  // Verify the CORS header before executing the action
455  if ( !$this->handleCORS() ) {
456  // handleCORS() has sent a 403, abort
457  return;
458  }
459 
460  // Exit here if the request method was OPTIONS
461  // (assume there will be a followup GET or POST)
462  if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
463  return;
464  }
465 
466  // In case an error occurs during data output,
467  // clear the output buffer and print just the error information
468  $obLevel = ob_get_level();
469  ob_start();
470 
471  $t = microtime( true );
472  $isError = false;
473  try {
474  $this->executeAction();
475  $this->logRequest( microtime( true ) - $t );
476 
477  } catch ( Exception $e ) {
478  $this->handleException( $e );
479  $this->logRequest( microtime( true ) - $t, $e );
480  $isError = true;
481  }
482 
483  // Commit DBs and send any related cookies and headers
485 
486  // Send cache headers after any code which might generate an error, to
487  // avoid sending public cache headers for errors.
488  $this->sendCacheHeaders( $isError );
489 
490  // Executing the action might have already messed with the output
491  // buffers.
492  while ( ob_get_level() > $obLevel ) {
493  ob_end_flush();
494  }
495  }
496 
503  protected function handleException( Exception $e ) {
504  // Bug 63145: Rollback any open database transactions
505  if ( !( $e instanceof UsageException ) ) {
506  // UsageExceptions are intentional, so don't rollback if that's the case
507  try {
509  } catch ( DBError $e2 ) {
510  // Rollback threw an exception too. Log it, but don't interrupt
511  // our regularly scheduled exception handling.
513  }
514  }
515 
516  // Allow extra cleanup and logging
517  Hooks::run( 'ApiMain::onException', [ $this, $e ] );
518 
519  // Log it
520  if ( !( $e instanceof UsageException ) ) {
522  }
523 
524  // Handle any kind of exception by outputting properly formatted error message.
525  // If this fails, an unhandled exception should be thrown so that global error
526  // handler will process and log it.
527 
528  $errCode = $this->substituteResultWithError( $e );
529 
530  // Error results should not be cached
531  $this->setCacheMode( 'private' );
532 
533  $response = $this->getRequest()->response();
534  $headerStr = 'MediaWiki-API-Error: ' . $errCode;
535  if ( $e->getCode() === 0 ) {
536  $response->header( $headerStr );
537  } else {
538  $response->header( $headerStr, true, $e->getCode() );
539  }
540 
541  // Reset and print just the error message
542  ob_clean();
543 
544  // Printer may not be initialized if the extractRequestParams() fails for the main module
545  $this->createErrorPrinter();
546 
547  try {
548  $this->printResult( true );
549  } catch ( UsageException $ex ) {
550  // The error printer itself is failing. Try suppressing its request
551  // parameters and redo.
552  $this->setWarning(
553  'Error printer failed (will retry without params): ' . $ex->getMessage()
554  );
555  $this->mPrinter = null;
556  $this->createErrorPrinter();
557  $this->mPrinter->forceDefaultParams();
558  $this->printResult( true );
559  }
560  }
561 
572  public static function handleApiBeforeMainException( Exception $e ) {
573  ob_start();
574 
575  try {
576  $main = new self( RequestContext::getMain(), false );
577  $main->handleException( $e );
578  $main->logRequest( 0, $e );
579  } catch ( Exception $e2 ) {
580  // Nope, even that didn't work. Punt.
581  throw $e;
582  }
583 
584  // Reset cache headers
585  $main->sendCacheHeaders( true );
586 
587  ob_end_flush();
588  }
589 
604  protected function handleCORS() {
605  $originParam = $this->getParameter( 'origin' ); // defaults to null
606  if ( $originParam === null ) {
607  // No origin parameter, nothing to do
608  return true;
609  }
610 
611  $request = $this->getRequest();
612  $response = $request->response();
613 
614  // Origin: header is a space-separated list of origins, check all of them
615  $originHeader = $request->getHeader( 'Origin' );
616  if ( $originHeader === false ) {
617  $origins = [];
618  } else {
619  $originHeader = trim( $originHeader );
620  $origins = preg_split( '/\s+/', $originHeader );
621  }
622 
623  if ( !in_array( $originParam, $origins ) ) {
624  // origin parameter set but incorrect
625  // Send a 403 response
626  $response->statusHeader( 403 );
627  $response->header( 'Cache-Control: no-cache' );
628  echo "'origin' parameter does not match Origin header\n";
629 
630  return false;
631  }
632 
633  $config = $this->getConfig();
634  $matchOrigin = count( $origins ) === 1 && self::matchOrigin(
635  $originParam,
636  $config->get( 'CrossSiteAJAXdomains' ),
637  $config->get( 'CrossSiteAJAXdomainExceptions' )
638  );
639 
640  if ( $matchOrigin ) {
641  $requestedMethod = $request->getHeader( 'Access-Control-Request-Method' );
642  $preflight = $request->getMethod() === 'OPTIONS' && $requestedMethod !== false;
643  if ( $preflight ) {
644  // This is a CORS preflight request
645  if ( $requestedMethod !== 'POST' && $requestedMethod !== 'GET' ) {
646  // If method is not a case-sensitive match, do not set any additional headers and terminate.
647  return true;
648  }
649  // We allow the actual request to send the following headers
650  $requestedHeaders = $request->getHeader( 'Access-Control-Request-Headers' );
651  if ( $requestedHeaders !== false ) {
652  if ( !self::matchRequestedHeaders( $requestedHeaders ) ) {
653  return true;
654  }
655  $response->header( 'Access-Control-Allow-Headers: ' . $requestedHeaders );
656  }
657 
658  // We only allow the actual request to be GET or POST
659  $response->header( 'Access-Control-Allow-Methods: POST, GET' );
660  }
661 
662  $response->header( "Access-Control-Allow-Origin: $originHeader" );
663  $response->header( 'Access-Control-Allow-Credentials: true' );
664  // http://www.w3.org/TR/resource-timing/#timing-allow-origin
665  $response->header( "Timing-Allow-Origin: $originHeader" );
666 
667  if ( !$preflight ) {
668  $response->header(
669  'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag'
670  );
671  }
672  }
673 
674  $this->getOutput()->addVaryHeader( 'Origin' );
675  return true;
676  }
677 
686  protected static function matchOrigin( $value, $rules, $exceptions ) {
687  foreach ( $rules as $rule ) {
688  if ( preg_match( self::wildcardToRegex( $rule ), $value ) ) {
689  // Rule matches, check exceptions
690  foreach ( $exceptions as $exc ) {
691  if ( preg_match( self::wildcardToRegex( $exc ), $value ) ) {
692  return false;
693  }
694  }
695 
696  return true;
697  }
698  }
699 
700  return false;
701  }
702 
710  protected static function matchRequestedHeaders( $requestedHeaders ) {
711  if ( trim( $requestedHeaders ) === '' ) {
712  return true;
713  }
714  $requestedHeaders = explode( ',', $requestedHeaders );
715  $allowedAuthorHeaders = array_flip( [
716  /* simple headers (see spec) */
717  'accept',
718  'accept-language',
719  'content-language',
720  'content-type',
721  /* non-authorable headers in XHR, which are however requested by some UAs */
722  'accept-encoding',
723  'dnt',
724  'origin',
725  /* MediaWiki whitelist */
726  'api-user-agent',
727  ] );
728  foreach ( $requestedHeaders as $rHeader ) {
729  $rHeader = strtolower( trim( $rHeader ) );
730  if ( !isset( $allowedAuthorHeaders[$rHeader] ) ) {
731  wfDebugLog( 'api', 'CORS preflight failed on requested header: ' . $rHeader );
732  return false;
733  }
734  }
735  return true;
736  }
737 
746  protected static function wildcardToRegex( $wildcard ) {
747  $wildcard = preg_quote( $wildcard, '/' );
748  $wildcard = str_replace(
749  [ '\*', '\?' ],
750  [ '.*?', '.' ],
751  $wildcard
752  );
753 
754  return "/^https?:\/\/$wildcard$/";
755  }
756 
762  protected function sendCacheHeaders( $isError ) {
763  $response = $this->getRequest()->response();
764  $out = $this->getOutput();
765 
766  $out->addVaryHeader( 'Treat-as-Untrusted' );
767 
768  $config = $this->getConfig();
769 
770  if ( $config->get( 'VaryOnXFP' ) ) {
771  $out->addVaryHeader( 'X-Forwarded-Proto' );
772  }
773 
774  if ( !$isError && $this->mModule &&
775  ( $this->getRequest()->getMethod() === 'GET' || $this->getRequest()->getMethod() === 'HEAD' )
776  ) {
777  $etag = $this->mModule->getConditionalRequestData( 'etag' );
778  if ( $etag !== null ) {
779  $response->header( "ETag: $etag" );
780  }
781  $lastMod = $this->mModule->getConditionalRequestData( 'last-modified' );
782  if ( $lastMod !== null ) {
783  $response->header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822, $lastMod ) );
784  }
785  }
786 
787  // The logic should be:
788  // $this->mCacheControl['max-age'] is set?
789  // Use it, the module knows better than our guess.
790  // !$this->mModule || $this->mModule->isWriteMode(), and mCacheMode is private?
791  // Use 0 because we can guess caching is probably the wrong thing to do.
792  // Use $this->getParameter( 'maxage' ), which already defaults to 0.
793  $maxage = 0;
794  if ( isset( $this->mCacheControl['max-age'] ) ) {
795  $maxage = $this->mCacheControl['max-age'];
796  } elseif ( ( $this->mModule && !$this->mModule->isWriteMode() ) ||
797  $this->mCacheMode !== 'private'
798  ) {
799  $maxage = $this->getParameter( 'maxage' );
800  }
801  $privateCache = 'private, must-revalidate, max-age=' . $maxage;
802 
803  if ( $this->mCacheMode == 'private' ) {
804  $response->header( "Cache-Control: $privateCache" );
805  return;
806  }
807 
808  $useKeyHeader = $config->get( 'UseKeyHeader' );
809  if ( $this->mCacheMode == 'anon-public-user-private' ) {
810  $out->addVaryHeader( 'Cookie' );
811  $response->header( $out->getVaryHeader() );
812  if ( $useKeyHeader ) {
813  $response->header( $out->getKeyHeader() );
814  if ( $out->haveCacheVaryCookies() ) {
815  // Logged in, mark this request private
816  $response->header( "Cache-Control: $privateCache" );
817  return;
818  }
819  // Logged out, send normal public headers below
820  } elseif ( MediaWiki\Session\SessionManager::getGlobalSession()->isPersistent() ) {
821  // Logged in or otherwise has session (e.g. anonymous users who have edited)
822  // Mark request private
823  $response->header( "Cache-Control: $privateCache" );
824 
825  return;
826  } // else no Key and anonymous, send public headers below
827  }
828 
829  // Send public headers
830  $response->header( $out->getVaryHeader() );
831  if ( $useKeyHeader ) {
832  $response->header( $out->getKeyHeader() );
833  }
834 
835  // If nobody called setCacheMaxAge(), use the (s)maxage parameters
836  if ( !isset( $this->mCacheControl['s-maxage'] ) ) {
837  $this->mCacheControl['s-maxage'] = $this->getParameter( 'smaxage' );
838  }
839  if ( !isset( $this->mCacheControl['max-age'] ) ) {
840  $this->mCacheControl['max-age'] = $this->getParameter( 'maxage' );
841  }
842 
843  if ( !$this->mCacheControl['s-maxage'] && !$this->mCacheControl['max-age'] ) {
844  // Public cache not requested
845  // Sending a Vary header in this case is harmless, and protects us
846  // against conditional calls of setCacheMaxAge().
847  $response->header( "Cache-Control: $privateCache" );
848 
849  return;
850  }
851 
852  $this->mCacheControl['public'] = true;
853 
854  // Send an Expires header
855  $maxAge = min( $this->mCacheControl['s-maxage'], $this->mCacheControl['max-age'] );
856  $expiryUnixTime = ( $maxAge == 0 ? 1 : time() + $maxAge );
857  $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822, $expiryUnixTime ) );
858 
859  // Construct the Cache-Control header
860  $ccHeader = '';
861  $separator = '';
862  foreach ( $this->mCacheControl as $name => $value ) {
863  if ( is_bool( $value ) ) {
864  if ( $value ) {
865  $ccHeader .= $separator . $name;
866  $separator = ', ';
867  }
868  } else {
869  $ccHeader .= $separator . "$name=$value";
870  $separator = ', ';
871  }
872  }
873 
874  $response->header( "Cache-Control: $ccHeader" );
875  }
876 
880  private function createErrorPrinter() {
881  if ( !isset( $this->mPrinter ) ) {
882  $value = $this->getRequest()->getVal( 'format', self::API_DEFAULT_FORMAT );
883  if ( !$this->mModuleMgr->isDefined( $value, 'format' ) ) {
884  $value = self::API_DEFAULT_FORMAT;
885  }
886  $this->mPrinter = $this->createPrinterByName( $value );
887  }
888 
889  // Printer may not be able to handle errors. This is particularly
890  // likely if the module returns something for getCustomPrinter().
891  if ( !$this->mPrinter->canPrintErrors() ) {
892  $this->mPrinter = $this->createPrinterByName( self::API_DEFAULT_FORMAT );
893  }
894  }
895 
906  protected function errorMessageFromException( $e ) {
907  if ( $e instanceof UsageException ) {
908  // User entered incorrect parameters - generate error response
909  $errMessage = $e->getMessageArray();
910  } else {
911  $config = $this->getConfig();
912  // Something is seriously wrong
913  if ( ( $e instanceof DBQueryError ) && !$config->get( 'ShowSQLErrors' ) ) {
914  $info = 'Database query error';
915  } else {
916  $info = "Exception Caught: {$e->getMessage()}";
917  }
918 
919  $errMessage = [
920  'code' => 'internal_api_error_' . get_class( $e ),
921  'info' => '[' . WebRequest::getRequestId() . '] ' . $info,
922  ];
923  }
924  return $errMessage;
925  }
926 
933  protected function substituteResultWithError( $e ) {
934  $result = $this->getResult();
935  $config = $this->getConfig();
936 
937  $errMessage = $this->errorMessageFromException( $e );
938  if ( $e instanceof UsageException ) {
939  // User entered incorrect parameters - generate error response
940  $link = wfExpandUrl( wfScript( 'api' ) );
941  ApiResult::setContentValue( $errMessage, 'docref', "See $link for API usage" );
942  } else {
943  // Something is seriously wrong
944  if ( $config->get( 'ShowExceptionDetails' ) ) {
946  $errMessage,
947  'trace',
949  );
950  }
951  }
952 
953  // Remember all the warnings to re-add them later
954  $warnings = $result->getResultData( [ 'warnings' ] );
955 
956  $result->reset();
957  // Re-add the id
958  $requestid = $this->getParameter( 'requestid' );
959  if ( !is_null( $requestid ) ) {
960  $result->addValue( null, 'requestid', $requestid, ApiResult::NO_SIZE_CHECK );
961  }
962  if ( $config->get( 'ShowHostnames' ) ) {
963  // servedby is especially useful when debugging errors
964  $result->addValue( null, 'servedby', wfHostname(), ApiResult::NO_SIZE_CHECK );
965  }
966  if ( $warnings !== null ) {
967  $result->addValue( null, 'warnings', $warnings, ApiResult::NO_SIZE_CHECK );
968  }
969 
970  $result->addValue( null, 'error', $errMessage, ApiResult::NO_SIZE_CHECK );
971 
972  return $errMessage['code'];
973  }
974 
979  protected function setupExecuteAction() {
980  // First add the id to the top element
981  $result = $this->getResult();
982  $requestid = $this->getParameter( 'requestid' );
983  if ( !is_null( $requestid ) ) {
984  $result->addValue( null, 'requestid', $requestid );
985  }
986 
987  if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
988  $servedby = $this->getParameter( 'servedby' );
989  if ( $servedby ) {
990  $result->addValue( null, 'servedby', wfHostname() );
991  }
992  }
993 
994  if ( $this->getParameter( 'curtimestamp' ) ) {
995  $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601, time() ),
997  }
998 
999  $params = $this->extractRequestParams();
1000 
1001  $this->mAction = $params['action'];
1002 
1003  if ( !is_string( $this->mAction ) ) {
1004  $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
1005  }
1006 
1007  return $params;
1008  }
1009 
1016  protected function setupModule() {
1017  // Instantiate the module requested by the user
1018  $module = $this->mModuleMgr->getModule( $this->mAction, 'action' );
1019  if ( $module === null ) {
1020  $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
1021  }
1022  $moduleParams = $module->extractRequestParams();
1023 
1024  // Check token, if necessary
1025  if ( $module->needsToken() === true ) {
1026  throw new MWException(
1027  "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
1028  'See documentation for ApiBase::needsToken for details.'
1029  );
1030  }
1031  if ( $module->needsToken() ) {
1032  if ( !$module->mustBePosted() ) {
1033  throw new MWException(
1034  "Module '{$module->getModuleName()}' must require POST to use tokens."
1035  );
1036  }
1037 
1038  if ( !isset( $moduleParams['token'] ) ) {
1039  $this->dieUsageMsg( [ 'missingparam', 'token' ] );
1040  }
1041 
1042  $module->requirePostedParameters( [ 'token' ] );
1043 
1044  if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) {
1045  $this->dieUsageMsg( 'sessionfailure' );
1046  }
1047  }
1048 
1049  return $module;
1050  }
1051 
1058  protected function checkMaxLag( $module, $params ) {
1059  if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
1060  $maxLag = $params['maxlag'];
1061  list( $host, $lag ) = wfGetLB()->getMaxLag();
1062  if ( $lag > $maxLag ) {
1063  $response = $this->getRequest()->response();
1064 
1065  $response->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
1066  $response->header( 'X-Database-Lag: ' . intval( $lag ) );
1067 
1068  if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
1069  $this->dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
1070  }
1071 
1072  $this->dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
1073  }
1074  }
1075 
1076  return true;
1077  }
1078 
1100  protected function checkConditionalRequestHeaders( $module ) {
1101  if ( $this->mInternalMode ) {
1102  // No headers to check in internal mode
1103  return true;
1104  }
1105 
1106  if ( $this->getRequest()->getMethod() !== 'GET' && $this->getRequest()->getMethod() !== 'HEAD' ) {
1107  // Don't check POSTs
1108  return true;
1109  }
1110 
1111  $return304 = false;
1112 
1113  $ifNoneMatch = array_diff(
1114  $this->getRequest()->getHeader( 'If-None-Match', WebRequest::GETHEADER_LIST ) ?: [],
1115  [ '' ]
1116  );
1117  if ( $ifNoneMatch ) {
1118  if ( $ifNoneMatch === [ '*' ] ) {
1119  // API responses always "exist"
1120  $etag = '*';
1121  } else {
1122  $etag = $module->getConditionalRequestData( 'etag' );
1123  }
1124  }
1125  if ( $ifNoneMatch && $etag !== null ) {
1126  $test = substr( $etag, 0, 2 ) === 'W/' ? substr( $etag, 2 ) : $etag;
1127  $match = array_map( function ( $s ) {
1128  return substr( $s, 0, 2 ) === 'W/' ? substr( $s, 2 ) : $s;
1129  }, $ifNoneMatch );
1130  $return304 = in_array( $test, $match, true );
1131  } else {
1132  $value = trim( $this->getRequest()->getHeader( 'If-Modified-Since' ) );
1133 
1134  // Some old browsers sends sizes after the date, like this:
1135  // Wed, 20 Aug 2003 06:51:19 GMT; length=5202
1136  // Ignore that.
1137  $i = strpos( $value, ';' );
1138  if ( $i !== false ) {
1139  $value = trim( substr( $value, 0, $i ) );
1140  }
1141 
1142  if ( $value !== '' ) {
1143  try {
1144  $ts = new MWTimestamp( $value );
1145  if (
1146  // RFC 7231 IMF-fixdate
1147  $ts->getTimestamp( TS_RFC2822 ) === $value ||
1148  // RFC 850
1149  $ts->format( 'l, d-M-y H:i:s' ) . ' GMT' === $value ||
1150  // asctime (with and without space-padded day)
1151  $ts->format( 'D M j H:i:s Y' ) === $value ||
1152  $ts->format( 'D M j H:i:s Y' ) === $value
1153  ) {
1154  $lastMod = $module->getConditionalRequestData( 'last-modified' );
1155  if ( $lastMod !== null ) {
1156  // Mix in some MediaWiki modification times
1157  $modifiedTimes = [
1158  'page' => $lastMod,
1159  'user' => $this->getUser()->getTouched(),
1160  'epoch' => $this->getConfig()->get( 'CacheEpoch' ),
1161  ];
1162  if ( $this->getConfig()->get( 'UseSquid' ) ) {
1163  // T46570: the core page itself may not change, but resources might
1164  $modifiedTimes['sepoch'] = wfTimestamp(
1165  TS_MW, time() - $this->getConfig()->get( 'SquidMaxage' )
1166  );
1167  }
1168  Hooks::run( 'OutputPageCheckLastModified', [ &$modifiedTimes ] );
1169  $lastMod = max( $modifiedTimes );
1170  $return304 = wfTimestamp( TS_MW, $lastMod ) <= $ts->getTimestamp( TS_MW );
1171  }
1172  }
1173  } catch ( TimestampException $e ) {
1174  // Invalid timestamp, ignore it
1175  }
1176  }
1177  }
1178 
1179  if ( $return304 ) {
1180  $this->getRequest()->response()->statusHeader( 304 );
1181 
1182  // Avoid outputting the compressed representation of a zero-length body
1183  MediaWiki\suppressWarnings();
1184  ini_set( 'zlib.output_compression', 0 );
1185  MediaWiki\restoreWarnings();
1187 
1188  return false;
1189  }
1190 
1191  return true;
1192  }
1193 
1198  protected function checkExecutePermissions( $module ) {
1199  $user = $this->getUser();
1200  if ( $module->isReadMode() && !User::isEveryoneAllowed( 'read' ) &&
1201  !$user->isAllowed( 'read' )
1202  ) {
1203  $this->dieUsageMsg( 'readrequired' );
1204  }
1205 
1206  if ( $module->isWriteMode() ) {
1207  if ( !$this->mEnableWrite ) {
1208  $this->dieUsageMsg( 'writedisabled' );
1209  } elseif ( !$user->isAllowed( 'writeapi' ) ) {
1210  $this->dieUsageMsg( 'writerequired' );
1211  } elseif ( $this->getRequest()->getHeader( 'Promise-Non-Write-API-Action' ) ) {
1212  $this->dieUsage(
1213  'Promise-Non-Write-API-Action HTTP header cannot be sent to write API modules',
1214  'promised-nonwrite-api'
1215  );
1216  }
1217 
1218  $this->checkReadOnly( $module );
1219  }
1220 
1221  // Allow extensions to stop execution for arbitrary reasons.
1222  $message = false;
1223  if ( !Hooks::run( 'ApiCheckCanExecute', [ $module, $user, &$message ] ) ) {
1224  $this->dieUsageMsg( $message );
1225  }
1226  }
1227 
1232  protected function checkReadOnly( $module ) {
1233  if ( wfReadOnly() ) {
1234  $this->dieReadOnly();
1235  }
1236 
1237  if ( $module->isWriteMode()
1238  && in_array( 'bot', $this->getUser()->getGroups() )
1239  && wfGetLB()->getServerCount() > 1
1240  ) {
1241  $this->checkBotReadOnly();
1242  }
1243  }
1244 
1248  private function checkBotReadOnly() {
1249  // Figure out how many servers have passed the lag threshold
1250  $numLagged = 0;
1251  $lagLimit = $this->getConfig()->get( 'APIMaxLagThreshold' );
1252  $laggedServers = [];
1253  $loadBalancer = wfGetLB();
1254  foreach ( $loadBalancer->getLagTimes() as $serverIndex => $lag ) {
1255  if ( $lag > $lagLimit ) {
1256  ++$numLagged;
1257  $laggedServers[] = $loadBalancer->getServerName( $serverIndex ) . " ({$lag}s)";
1258  }
1259  }
1260 
1261  // If a majority of slaves are too lagged then disallow writes
1262  $slaveCount = wfGetLB()->getServerCount() - 1;
1263  if ( $numLagged >= ceil( $slaveCount / 2 ) ) {
1264  $laggedServers = implode( ', ', $laggedServers );
1265  wfDebugLog(
1266  'api-readonly',
1267  "Api request failed as read only because the following DBs are lagged: $laggedServers"
1268  );
1269 
1270  $parsed = $this->parseMsg( [ 'readonlytext' ] );
1271  $this->dieUsage(
1272  $parsed['info'],
1273  $parsed['code'],
1274  /* http error */
1275  0,
1276  [ 'readonlyreason' => "Waiting for $numLagged lagged database(s)" ]
1277  );
1278  }
1279  }
1280 
1285  protected function checkAsserts( $params ) {
1286  if ( isset( $params['assert'] ) ) {
1287  $user = $this->getUser();
1288  switch ( $params['assert'] ) {
1289  case 'user':
1290  if ( $user->isAnon() ) {
1291  $this->dieUsage( 'Assertion that the user is logged in failed', 'assertuserfailed' );
1292  }
1293  break;
1294  case 'bot':
1295  if ( !$user->isAllowed( 'bot' ) ) {
1296  $this->dieUsage( 'Assertion that the user has the bot right failed', 'assertbotfailed' );
1297  }
1298  break;
1299  }
1300  }
1301  }
1302 
1308  protected function setupExternalResponse( $module, $params ) {
1309  $request = $this->getRequest();
1310  if ( !$request->wasPosted() && $module->mustBePosted() ) {
1311  // Module requires POST. GET request might still be allowed
1312  // if $wgDebugApi is true, otherwise fail.
1313  $this->dieUsageMsgOrDebug( [ 'mustbeposted', $this->mAction ] );
1314  }
1315 
1316  // See if custom printer is used
1317  $this->mPrinter = $module->getCustomPrinter();
1318  if ( is_null( $this->mPrinter ) ) {
1319  // Create an appropriate printer
1320  $this->mPrinter = $this->createPrinterByName( $params['format'] );
1321  }
1322 
1323  if ( $request->getProtocol() === 'http' && (
1324  $request->getSession()->shouldForceHTTPS() ||
1325  ( $this->getUser()->isLoggedIn() &&
1326  $this->getUser()->requiresHTTPS() )
1327  ) ) {
1328  $this->logFeatureUsage( 'https-expected' );
1329  $this->setWarning( 'HTTP used when HTTPS was expected' );
1330  }
1331  }
1332 
1336  protected function executeAction() {
1337  $params = $this->setupExecuteAction();
1338  $module = $this->setupModule();
1339  $this->mModule = $module;
1340 
1341  if ( !$this->mInternalMode ) {
1342  $this->setRequestExpectations( $module );
1343  }
1344 
1345  $this->checkExecutePermissions( $module );
1346 
1347  if ( !$this->checkMaxLag( $module, $params ) ) {
1348  return;
1349  }
1350 
1351  if ( !$this->checkConditionalRequestHeaders( $module ) ) {
1352  return;
1353  }
1354 
1355  if ( !$this->mInternalMode ) {
1356  $this->setupExternalResponse( $module, $params );
1357  }
1358 
1359  $this->checkAsserts( $params );
1360 
1361  // Execute
1362  $module->execute();
1363  Hooks::run( 'APIAfterExecute', [ &$module ] );
1364 
1365  $this->reportUnusedParams();
1366 
1367  if ( !$this->mInternalMode ) {
1368  // append Debug information
1370 
1371  // Print result data
1372  $this->printResult( false );
1373  }
1374  }
1375 
1380  protected function setRequestExpectations( ApiBase $module ) {
1381  $limits = $this->getConfig()->get( 'TrxProfilerLimits' );
1382  $trxProfiler = Profiler::instance()->getTransactionProfiler();
1383  if ( $this->getRequest()->wasPosted() ) {
1384  if ( $module->isWriteMode() ) {
1385  $trxProfiler->setExpectations( $limits['POST'], __METHOD__ );
1386  } else {
1387  $trxProfiler->setExpectations( $limits['POST-nonwrite'], __METHOD__ );
1388  }
1389  } else {
1390  $trxProfiler->setExpectations( $limits['GET'], __METHOD__ );
1391  }
1392  }
1393 
1399  protected function logRequest( $time, $e = null ) {
1400  $request = $this->getRequest();
1401  $logCtx = [
1402  'ts' => time(),
1403  'ip' => $request->getIP(),
1404  'userAgent' => $this->getUserAgent(),
1405  'wiki' => wfWikiID(),
1406  'timeSpentBackend' => (int) round( $time * 1000 ),
1407  'hadError' => $e !== null,
1408  'errorCodes' => [],
1409  'params' => [],
1410  ];
1411 
1412  if ( $e ) {
1413  $logCtx['errorCodes'][] = $this->errorMessageFromException( $e )['code'];
1414  }
1415 
1416  // Construct space separated message for 'api' log channel
1417  $msg = "API {$request->getMethod()} " .
1418  wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
1419  " {$logCtx['ip']} " .
1420  "T={$logCtx['timeSpentBackend']}ms";
1421 
1422  $sensitive = array_flip( $this->getSensitiveParams() );
1423  foreach ( $this->getParamsUsed() as $name ) {
1424  $value = $request->getVal( $name );
1425  if ( $value === null ) {
1426  continue;
1427  }
1428 
1429  if ( isset( $sensitive[$name] ) ) {
1430  $value = '[redacted]';
1431  $encValue = '[redacted]';
1432  } elseif ( strlen( $value ) > 256 ) {
1433  $value = substr( $value, 0, 256 );
1434  $encValue = $this->encodeRequestLogValue( $value ) . '[...]';
1435  } else {
1436  $encValue = $this->encodeRequestLogValue( $value );
1437  }
1438 
1439  $logCtx['params'][$name] = $value;
1440  $msg .= " {$name}={$encValue}";
1441  }
1442 
1443  wfDebugLog( 'api', $msg, 'private' );
1444  // ApiAction channel is for structured data consumers
1445  wfDebugLog( 'ApiAction', '', 'private', $logCtx );
1446  }
1447 
1453  protected function encodeRequestLogValue( $s ) {
1454  static $table;
1455  if ( !$table ) {
1456  $chars = ';@$!*(),/:';
1457  $numChars = strlen( $chars );
1458  for ( $i = 0; $i < $numChars; $i++ ) {
1459  $table[rawurlencode( $chars[$i] )] = $chars[$i];
1460  }
1461  }
1462 
1463  return strtr( rawurlencode( $s ), $table );
1464  }
1465 
1470  protected function getParamsUsed() {
1471  return array_keys( $this->mParamsUsed );
1472  }
1473 
1478  public function markParamsUsed( $params ) {
1479  $this->mParamsUsed += array_fill_keys( (array)$params, true );
1480  }
1481 
1487  protected function getSensitiveParams() {
1488  return array_keys( $this->mParamsSensitive );
1489  }
1490 
1496  public function markParamsSensitive( $params ) {
1497  $this->mParamsSensitive += array_fill_keys( (array)$params, true );
1498  }
1499 
1506  public function getVal( $name, $default = null ) {
1507  $this->mParamsUsed[$name] = true;
1508 
1509  $ret = $this->getRequest()->getVal( $name );
1510  if ( $ret === null ) {
1511  if ( $this->getRequest()->getArray( $name ) !== null ) {
1512  // See bug 10262 for why we don't just implode( '|', ... ) the
1513  // array.
1514  $this->setWarning(
1515  "Parameter '$name' uses unsupported PHP array syntax"
1516  );
1517  }
1518  $ret = $default;
1519  }
1520  return $ret;
1521  }
1522 
1529  public function getCheck( $name ) {
1530  return $this->getVal( $name, null ) !== null;
1531  }
1532 
1540  public function getUpload( $name ) {
1541  $this->mParamsUsed[$name] = true;
1542 
1543  return $this->getRequest()->getUpload( $name );
1544  }
1545 
1550  protected function reportUnusedParams() {
1551  $paramsUsed = $this->getParamsUsed();
1552  $allParams = $this->getRequest()->getValueNames();
1553 
1554  if ( !$this->mInternalMode ) {
1555  // Printer has not yet executed; don't warn that its parameters are unused
1556  $printerParams = array_map(
1557  [ $this->mPrinter, 'encodeParamName' ],
1558  array_keys( $this->mPrinter->getFinalParams() ?: [] )
1559  );
1560  $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1561  } else {
1562  $unusedParams = array_diff( $allParams, $paramsUsed );
1563  }
1564 
1565  if ( count( $unusedParams ) ) {
1566  $s = count( $unusedParams ) > 1 ? 's' : '';
1567  $this->setWarning( "Unrecognized parameter$s: '" . implode( $unusedParams, "', '" ) . "'" );
1568  }
1569  }
1570 
1576  protected function printResult( $isError ) {
1577  if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
1578  $this->setWarning( 'SECURITY WARNING: $wgDebugAPI is enabled' );
1579  }
1580 
1581  $printer = $this->mPrinter;
1582  $printer->initPrinter( false );
1583  $printer->execute();
1584  $printer->closePrinter();
1585  }
1586 
1590  public function isReadMode() {
1591  return false;
1592  }
1593 
1599  public function getAllowedParams() {
1600  return [
1601  'action' => [
1602  ApiBase::PARAM_DFLT => 'help',
1603  ApiBase::PARAM_TYPE => 'submodule',
1604  ],
1605  'format' => [
1607  ApiBase::PARAM_TYPE => 'submodule',
1608  ],
1609  'maxlag' => [
1610  ApiBase::PARAM_TYPE => 'integer'
1611  ],
1612  'smaxage' => [
1613  ApiBase::PARAM_TYPE => 'integer',
1614  ApiBase::PARAM_DFLT => 0
1615  ],
1616  'maxage' => [
1617  ApiBase::PARAM_TYPE => 'integer',
1618  ApiBase::PARAM_DFLT => 0
1619  ],
1620  'assert' => [
1621  ApiBase::PARAM_TYPE => [ 'user', 'bot' ]
1622  ],
1623  'requestid' => null,
1624  'servedby' => false,
1625  'curtimestamp' => false,
1626  'origin' => null,
1627  'uselang' => [
1628  ApiBase::PARAM_DFLT => 'user',
1629  ],
1630  ];
1631  }
1632 
1634  protected function getExamplesMessages() {
1635  return [
1636  'action=help'
1637  => 'apihelp-help-example-main',
1638  'action=help&recursivesubmodules=1'
1639  => 'apihelp-help-example-recursive',
1640  ];
1641  }
1642 
1643  public function modifyHelp( array &$help, array $options, array &$tocData ) {
1644  // Wish PHP had an "array_insert_before". Instead, we have to manually
1645  // reindex the array to get 'permissions' in the right place.
1646  $oldHelp = $help;
1647  $help = [];
1648  foreach ( $oldHelp as $k => $v ) {
1649  if ( $k === 'submodules' ) {
1650  $help['permissions'] = '';
1651  }
1652  $help[$k] = $v;
1653  }
1654  $help['datatypes'] = '';
1655  $help['credits'] = '';
1656 
1657  // Fill 'permissions'
1658  $help['permissions'] .= Html::openElement( 'div',
1659  [ 'class' => 'apihelp-block apihelp-permissions' ] );
1660  $m = $this->msg( 'api-help-permissions' );
1661  if ( !$m->isDisabled() ) {
1662  $help['permissions'] .= Html::rawElement( 'div', [ 'class' => 'apihelp-block-head' ],
1663  $m->numParams( count( self::$mRights ) )->parse()
1664  );
1665  }
1666  $help['permissions'] .= Html::openElement( 'dl' );
1667  foreach ( self::$mRights as $right => $rightMsg ) {
1668  $help['permissions'] .= Html::element( 'dt', null, $right );
1669 
1670  $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse();
1671  $help['permissions'] .= Html::rawElement( 'dd', null, $rightMsg );
1672 
1673  $groups = array_map( function ( $group ) {
1674  return $group == '*' ? 'all' : $group;
1675  }, User::getGroupsWithPermission( $right ) );
1676 
1677  $help['permissions'] .= Html::rawElement( 'dd', null,
1678  $this->msg( 'api-help-permissions-granted-to' )
1679  ->numParams( count( $groups ) )
1680  ->params( $this->getLanguage()->commaList( $groups ) )
1681  ->parse()
1682  );
1683  }
1684  $help['permissions'] .= Html::closeElement( 'dl' );
1685  $help['permissions'] .= Html::closeElement( 'div' );
1686 
1687  // Fill 'datatypes' and 'credits', if applicable
1688  if ( empty( $options['nolead'] ) ) {
1689  $level = $options['headerlevel'];
1690  $tocnumber = &$options['tocnumber'];
1691 
1692  $header = $this->msg( 'api-help-datatypes-header' )->parse();
1693  $help['datatypes'] .= Html::rawElement( 'h' . min( 6, $level ),
1694  [ 'id' => 'main/datatypes', 'class' => 'apihelp-header' ],
1695  Html::element( 'span', [ 'id' => Sanitizer::escapeId( 'main/datatypes' ) ] ) .
1696  $header
1697  );
1698  $help['datatypes'] .= $this->msg( 'api-help-datatypes' )->parseAsBlock();
1699  if ( !isset( $tocData['main/datatypes'] ) ) {
1700  $tocnumber[$level]++;
1701  $tocData['main/datatypes'] = [
1702  'toclevel' => count( $tocnumber ),
1703  'level' => $level,
1704  'anchor' => 'main/datatypes',
1705  'line' => $header,
1706  'number' => implode( '.', $tocnumber ),
1707  'index' => false,
1708  ];
1709  }
1710 
1711  $header = $this->msg( 'api-credits-header' )->parse();
1712  $help['credits'] .= Html::rawElement( 'h' . min( 6, $level ),
1713  [ 'id' => 'main/credits', 'class' => 'apihelp-header' ],
1714  Html::element( 'span', [ 'id' => Sanitizer::escapeId( 'main/credits' ) ] ) .
1715  $header
1716  );
1717  $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
1718  if ( !isset( $tocData['main/credits'] ) ) {
1719  $tocnumber[$level]++;
1720  $tocData['main/credits'] = [
1721  'toclevel' => count( $tocnumber ),
1722  'level' => $level,
1723  'anchor' => 'main/credits',
1724  'line' => $header,
1725  'number' => implode( '.', $tocnumber ),
1726  'index' => false,
1727  ];
1728  }
1729  }
1730  }
1731 
1732  private $mCanApiHighLimits = null;
1733 
1738  public function canApiHighLimits() {
1739  if ( !isset( $this->mCanApiHighLimits ) ) {
1740  $this->mCanApiHighLimits = $this->getUser()->isAllowed( 'apihighlimits' );
1741  }
1742 
1743  return $this->mCanApiHighLimits;
1744  }
1745 
1750  public function getModuleManager() {
1751  return $this->mModuleMgr;
1752  }
1753 
1762  public function getUserAgent() {
1763  return trim(
1764  $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
1765  $this->getRequest()->getHeader( 'User-agent' )
1766  );
1767  }
1768 
1769  /************************************************************************/
1780  public function setHelp( $help = true ) {
1781  wfDeprecated( __METHOD__, '1.25' );
1782  $this->mPrinter->setHelp( $help );
1783  }
1784 
1791  public function makeHelpMsg() {
1792  wfDeprecated( __METHOD__, '1.25' );
1793 
1794  $this->setHelp();
1795  $cacheHelpTimeout = $this->getConfig()->get( 'APICacheHelpTimeout' );
1796 
1797  return ObjectCache::getMainWANInstance()->getWithSetCallback(
1798  wfMemcKey(
1799  'apihelp',
1800  $this->getModuleName(),
1801  str_replace( ' ', '_', SpecialVersion::getVersion( 'nodb' ) )
1802  ),
1803  $cacheHelpTimeout > 0 ? $cacheHelpTimeout : WANObjectCache::TTL_UNCACHEABLE,
1804  [ $this, 'reallyMakeHelpMsg' ]
1805  );
1806  }
1807 
1812  public function reallyMakeHelpMsg() {
1813  wfDeprecated( __METHOD__, '1.25' );
1814  $this->setHelp();
1815 
1816  // Use parent to make default message for the main module
1817  $msg = parent::makeHelpMsg();
1818 
1819  $asterisks = str_repeat( '*** ', 14 );
1820  $msg .= "\n\n$asterisks Modules $asterisks\n\n";
1821 
1822  foreach ( $this->mModuleMgr->getNames( 'action' ) as $name ) {
1823  $module = $this->mModuleMgr->getModule( $name );
1824  $msg .= self::makeHelpMsgHeader( $module, 'action' );
1825 
1826  $msg2 = $module->makeHelpMsg();
1827  if ( $msg2 !== false ) {
1828  $msg .= $msg2;
1829  }
1830  $msg .= "\n";
1831  }
1832 
1833  $msg .= "\n$asterisks Permissions $asterisks\n\n";
1834  foreach ( self::$mRights as $right => $rightMsg ) {
1835  $rightsMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )
1836  ->useDatabase( false )
1837  ->inLanguage( 'en' )
1838  ->text();
1839  $groups = User::getGroupsWithPermission( $right );
1840  $msg .= '* ' . $right . " *\n $rightsMsg" .
1841  "\nGranted to:\n " . str_replace( '*', 'all', implode( ', ', $groups ) ) . "\n\n";
1842  }
1843 
1844  $msg .= "\n$asterisks Formats $asterisks\n\n";
1845  foreach ( $this->mModuleMgr->getNames( 'format' ) as $name ) {
1846  $module = $this->mModuleMgr->getModule( $name );
1847  $msg .= self::makeHelpMsgHeader( $module, 'format' );
1848  $msg2 = $module->makeHelpMsg();
1849  if ( $msg2 !== false ) {
1850  $msg .= $msg2;
1851  }
1852  $msg .= "\n";
1853  }
1854 
1855  $credits = $this->msg( 'api-credits' )->useDatabase( 'false' )->inLanguage( 'en' )->text();
1856  $credits = str_replace( "\n", "\n ", $credits );
1857  $msg .= "\n*** Credits: ***\n $credits\n";
1858 
1859  return $msg;
1860  }
1861 
1869  public static function makeHelpMsgHeader( $module, $paramName ) {
1870  wfDeprecated( __METHOD__, '1.25' );
1871  $modulePrefix = $module->getModulePrefix();
1872  if ( strval( $modulePrefix ) !== '' ) {
1873  $modulePrefix = "($modulePrefix) ";
1874  }
1875 
1876  return "* $paramName={$module->getModuleName()} $modulePrefix*";
1877  }
1878 
1881 }
1882 
1889 
1890  private $mCodestr;
1891 
1895  private $mExtraData;
1896 
1903  public function __construct( $message, $codestr, $code = 0, $extradata = null ) {
1904  parent::__construct( $message, $code );
1905  $this->mCodestr = $codestr;
1906  $this->mExtraData = $extradata;
1907  }
1908 
1912  public function getCodeString() {
1913  return $this->mCodestr;
1914  }
1915 
1919  public function getMessageArray() {
1920  $result = [
1921  'code' => $this->mCodestr,
1922  'info' => $this->getMessage()
1923  ];
1924  if ( is_array( $this->mExtraData ) ) {
1925  $result = array_merge( $result, $this->mExtraData );
1926  }
1927 
1928  return $result;
1929  }
1930 
1934  public function __toString() {
1935  return "{$this->getCodeString()}: {$this->getMessage()}";
1936  }
1937 }
1938 
dieUsageMsgOrDebug($error)
Will only set a warning instead of failing if the global $wgDebugAPI is set to true.
Definition: ApiBase.php:2162
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:1599
static closeElement($element)
Returns "".
Definition: Html.php:306
getModuleManager()
Overrides to return this instance's module manager.
Definition: ApiMain.php:1750
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:1762
const LIMIT_BIG2
Fast query, apihighlimits limit.
Definition: ApiBase.php:186
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:291
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:1576
checkConditionalRequestHeaders($module)
Check selected RFC 7232 precondition headers.
Definition: ApiMain.php:1100
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:453
getParameter($paramName, $parseLimit=true)
Get a value for the given parameter.
Definition: ApiBase.php:709
modifyHelp(array &$help, array $options, array &$tocData)
Definition: ApiMain.php:1643
__construct($context=null, $enableWrite=false)
Constructs an instance of ApiMain that utilizes the module and format specified by $request...
Definition: ApiMain.php:160
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:1232
bool null $lacksSameOriginSecurity
Cached return value from self::lacksSameOriginSecurity()
Definition: ApiMain.php:151
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:710
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:339
This manages continuation state.
extractRequestParams($parseLimit=true)
Using getAllowedParams(), this function makes an array of the values provided by the user...
Definition: ApiBase.php:685
isInternalMode()
Return true if the API was started by other PHP code using FauxRequest.
Definition: ApiMain.php:237
$value
markParamsSensitive($params)
Mark parameters as sensitive.
Definition: ApiMain.php:1496
$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:1738
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:539
static handleApiBeforeMainException(Exception $e)
Handle an exception from the ApiBeforeMain hook.
Definition: ApiMain.php:572
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:371
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:1812
setupExternalResponse($module, $params)
Check POST for external response and setup result printer.
Definition: ApiMain.php:1308
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:412
errorMessageFromException($e)
Create an error message for the given exception.
Definition: ApiMain.php:906
static isEveryoneAllowed($right)
Check if all users may be assumed to have the given permission.
Definition: User.php:4572
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:1016
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:1791
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:746
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:1380
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:190
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:1336
isReadMode()
Definition: ApiMain.php:1590
handleCORS()
Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
Definition: ApiMain.php:604
setupExecuteAction()
Set up for the execution.
Definition: ApiMain.php:979
wfDeprecated($function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
getSensitiveParams()
Get the request parameters that should be considered sensitive.
Definition: ApiMain.php:1487
$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:254
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:423
getModuleName()
Get the name of the module being executed by this instance.
Definition: ApiBase.php:464
static dieReadOnly()
Helper function for readonly errors.
Definition: ApiBase.php:2133
static matchOrigin($value, $rules, $exceptions)
Attempt to match an Origin header against a set of rules and a set of exceptions. ...
Definition: ApiMain.php:686
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:1869
$help
Definition: mcc.php:32
wfWikiID()
Get an ASCII string identifying this wiki This is used as a prefix in memcached keys.
$mParamsSensitive
Definition: ApiMain.php:148
encodeRequestLogValue($s)
Encode a value in a format suitable for a space-separated log line.
Definition: ApiMain.php:1453
checkMaxLag($module, $params)
Check the max lag if necessary.
Definition: ApiMain.php:1058
setWarning($warning)
Set warning section for this module.
Definition: ApiBase.php:1495
$mCanApiHighLimits
Definition: ApiMain.php:1732
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:1470
getExamplesMessages()
Definition: ApiMain.php:1634
logRequest($time, $e=null)
Log the preceding request.
Definition: ApiMain.php:1399
getErrorFormatter()
Get the ApiErrorFormatter object associated with current request.
Definition: ApiMain.php:283
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:1132
getUpload($name)
Get a request upload, and register the fact that it was used, for logging.
Definition: ApiMain.php:1540
const TS_MW
MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
markParamsUsed($params)
Mark parameters as used.
Definition: ApiMain.php:1478
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:1248
getModule()
Get the API module object.
Definition: ApiMain.php:321
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:1780
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:1550
wfClearOutputBuffers()
More legible than passing a 'false' parameter to wfResetOutputBuffers():
null array $mExtraData
Definition: ApiMain.php:1895
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:1526
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:330
wfMemcKey()
Make a cache key for the local wiki.
checkAsserts($params)
Check asserts of the user's rights.
Definition: ApiMain.php:1285
parseMsg($error)
Return the error message related to a certain array.
Definition: ApiBase.php:2194
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:1529
logFeatureUsage($feature)
Write logging information for API features to a debug log, for usage analysis.
Definition: ApiBase.php:2239
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:762
getVal($name, $default=null)
Get a request value, and register the fact that it was used, for logging.
Definition: ApiMain.php:1506
__construct($message, $codestr, $code=0, $extradata=null)
Definition: ApiMain.php:1903
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:933
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:2144
$mModuleMgr
Definition: ApiMain.php:140
static getGroupsWithPermission($role)
Get all the groups who have a given permission.
Definition: User.php:4529
execute()
Execute api request.
Definition: ApiMain.php:435
This exception will be thrown when dieUsage is called to stop module execution.
Definition: ApiMain.php:1888
getResult()
Get the ApiResult object associated with current request.
Definition: ApiMain.php:246
checkExecutePermissions($module)
Check for sufficient permissions to execute.
Definition: ApiMain.php:1198
createErrorPrinter()
Create the printer for error output.
Definition: ApiMain.php:880
$wgUser
Definition: Setup.php:794
isWriteMode()
Indicates whether this module requires write mode.
Definition: ApiBase.php:371
setContinuationManager($manager)
Set the continuation manager.
Definition: ApiMain.php:299
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:503