MediaWiki  1.28.1
ApiMain.php
Go to the documentation of this file.
1 <?php
29 
43 class ApiMain extends ApiBase {
47  const API_DEFAULT_FORMAT = 'jsonfm';
48 
52  private static $Modules = [
53  'login' => 'ApiLogin',
54  'clientlogin' => 'ApiClientLogin',
55  'logout' => 'ApiLogout',
56  'createaccount' => 'ApiAMCreateAccount',
57  'linkaccount' => 'ApiLinkAccount',
58  'unlinkaccount' => 'ApiRemoveAuthenticationData',
59  'changeauthenticationdata' => 'ApiChangeAuthenticationData',
60  'removeauthenticationdata' => 'ApiRemoveAuthenticationData',
61  'resetpassword' => 'ApiResetPassword',
62  'query' => 'ApiQuery',
63  'expandtemplates' => 'ApiExpandTemplates',
64  'parse' => 'ApiParse',
65  'stashedit' => 'ApiStashEdit',
66  'opensearch' => 'ApiOpenSearch',
67  'feedcontributions' => 'ApiFeedContributions',
68  'feedrecentchanges' => 'ApiFeedRecentChanges',
69  'feedwatchlist' => 'ApiFeedWatchlist',
70  'help' => 'ApiHelp',
71  'paraminfo' => 'ApiParamInfo',
72  'rsd' => 'ApiRsd',
73  'compare' => 'ApiComparePages',
74  'tokens' => 'ApiTokens',
75  'checktoken' => 'ApiCheckToken',
76  'cspreport' => 'ApiCSPReport',
77 
78  // Write modules
79  'purge' => 'ApiPurge',
80  'setnotificationtimestamp' => 'ApiSetNotificationTimestamp',
81  'rollback' => 'ApiRollback',
82  'delete' => 'ApiDelete',
83  'undelete' => 'ApiUndelete',
84  'protect' => 'ApiProtect',
85  'block' => 'ApiBlock',
86  'unblock' => 'ApiUnblock',
87  'move' => 'ApiMove',
88  'edit' => 'ApiEditPage',
89  'upload' => 'ApiUpload',
90  'filerevert' => 'ApiFileRevert',
91  'emailuser' => 'ApiEmailUser',
92  'watch' => 'ApiWatch',
93  'patrol' => 'ApiPatrol',
94  'import' => 'ApiImport',
95  'clearhasmsg' => 'ApiClearHasMsg',
96  'userrights' => 'ApiUserrights',
97  'options' => 'ApiOptions',
98  'imagerotate' => 'ApiImageRotate',
99  'revisiondelete' => 'ApiRevisionDelete',
100  'managetags' => 'ApiManageTags',
101  'tag' => 'ApiTag',
102  'mergehistory' => 'ApiMergeHistory',
103  ];
104 
108  private static $Formats = [
109  'json' => 'ApiFormatJson',
110  'jsonfm' => 'ApiFormatJson',
111  'php' => 'ApiFormatPhp',
112  'phpfm' => 'ApiFormatPhp',
113  'xml' => 'ApiFormatXml',
114  'xmlfm' => 'ApiFormatXml',
115  'rawfm' => 'ApiFormatJson',
116  'none' => 'ApiFormatNone',
117  ];
118 
119  // @codingStandardsIgnoreStart String contenation on "msg" not allowed to break long line
126  private static $mRights = [
127  'writeapi' => [
128  'msg' => 'right-writeapi',
129  'params' => []
130  ],
131  'apihighlimits' => [
132  'msg' => 'api-help-right-apihighlimits',
134  ]
135  ];
136  // @codingStandardsIgnoreEnd
137 
141  private $mPrinter;
142 
146  private $mAction;
147  private $mEnableWrite;
150  private $mModule;
151 
152  private $mCacheMode = 'private';
153  private $mCacheControl = [];
154  private $mParamsUsed = [];
155  private $mParamsSensitive = [];
156 
158  private $lacksSameOriginSecurity = null;
159 
167  public function __construct( $context = null, $enableWrite = false ) {
168  if ( $context === null ) {
170  } elseif ( $context instanceof WebRequest ) {
171  // BC for pre-1.19
172  $request = $context;
174  }
175  // We set a derivative context so we can change stuff later
176  $this->setContext( new DerivativeContext( $context ) );
177 
178  if ( isset( $request ) ) {
179  $this->getContext()->setRequest( $request );
180  } else {
181  $request = $this->getRequest();
182  }
183 
184  $this->mInternalMode = ( $request instanceof FauxRequest );
185 
186  // Special handling for the main module: $parent === $this
187  parent::__construct( $this, $this->mInternalMode ? 'main_int' : 'main' );
188 
189  $config = $this->getConfig();
190 
191  if ( !$this->mInternalMode ) {
192  // Log if a request with a non-whitelisted Origin header is seen
193  // with session cookies.
194  $originHeader = $request->getHeader( 'Origin' );
195  if ( $originHeader === false ) {
196  $origins = [];
197  } else {
198  $originHeader = trim( $originHeader );
199  $origins = preg_split( '/\s+/', $originHeader );
200  }
201  $sessionCookies = array_intersect(
202  array_keys( $_COOKIE ),
203  MediaWiki\Session\SessionManager::singleton()->getVaryCookies()
204  );
205  if ( $origins && $sessionCookies && (
206  count( $origins ) !== 1 || !self::matchOrigin(
207  $origins[0],
208  $config->get( 'CrossSiteAJAXdomains' ),
209  $config->get( 'CrossSiteAJAXdomainExceptions' )
210  )
211  ) ) {
212  LoggerFactory::getInstance( 'cors' )->warning(
213  'Non-whitelisted CORS request with session cookies', [
214  'origin' => $originHeader,
215  'cookies' => $sessionCookies,
216  'ip' => $request->getIP(),
217  'userAgent' => $this->getUserAgent(),
218  'wiki' => wfWikiID(),
219  ]
220  );
221  }
222 
223  // If we're in a mode that breaks the same-origin policy, strip
224  // user credentials for security.
225  if ( $this->lacksSameOriginSecurity() ) {
226  global $wgUser;
227  wfDebug( "API: stripping user credentials when the same-origin policy is not applied\n" );
228  $wgUser = new User();
229  $this->getContext()->setUser( $wgUser );
230  }
231  }
232 
233  $uselang = $this->getParameter( 'uselang' );
234  if ( $uselang === 'user' ) {
235  // Assume the parent context is going to return the user language
236  // for uselang=user (see T85635).
237  } else {
238  if ( $uselang === 'content' ) {
240  $uselang = $wgContLang->getCode();
241  }
243  $this->getContext()->setLanguage( $code );
244  if ( !$this->mInternalMode ) {
245  global $wgLang;
246  $wgLang = $this->getContext()->getLanguage();
247  RequestContext::getMain()->setLanguage( $wgLang );
248  }
249  }
250 
251  $this->mModuleMgr = new ApiModuleManager( $this );
252  $this->mModuleMgr->addModules( self::$Modules, 'action' );
253  $this->mModuleMgr->addModules( $config->get( 'APIModules' ), 'action' );
254  $this->mModuleMgr->addModules( self::$Formats, 'format' );
255  $this->mModuleMgr->addModules( $config->get( 'APIFormatModules' ), 'format' );
256 
257  Hooks::run( 'ApiMain::moduleManager', [ $this->mModuleMgr ] );
258 
259  $this->mResult = new ApiResult( $this->getConfig()->get( 'APIMaxResultSize' ) );
260  $this->mErrorFormatter = new ApiErrorFormatter_BackCompat( $this->mResult );
261  $this->mResult->setErrorFormatter( $this->mErrorFormatter );
262  $this->mContinuationManager = null;
263  $this->mEnableWrite = $enableWrite;
264 
265  $this->mSquidMaxage = -1; // flag for executeActionWithErrorHandling()
266  $this->mCommit = false;
267  }
268 
273  public function isInternalMode() {
274  return $this->mInternalMode;
275  }
276 
282  public function getResult() {
283  return $this->mResult;
284  }
285 
290  public function lacksSameOriginSecurity() {
291  if ( $this->lacksSameOriginSecurity !== null ) {
293  }
294 
295  $request = $this->getRequest();
296 
297  // JSONP mode
298  if ( $request->getVal( 'callback' ) !== null ) {
299  $this->lacksSameOriginSecurity = true;
300  return true;
301  }
302 
303  // Anonymous CORS
304  if ( $request->getVal( 'origin' ) === '*' ) {
305  $this->lacksSameOriginSecurity = true;
306  return true;
307  }
308 
309  // Header to be used from XMLHTTPRequest when the request might
310  // otherwise be used for XSS.
311  if ( $request->getHeader( 'Treat-as-Untrusted' ) !== false ) {
312  $this->lacksSameOriginSecurity = true;
313  return true;
314  }
315 
316  // Allow extensions to override.
317  $this->lacksSameOriginSecurity = !Hooks::run( 'RequestHasSameOriginSecurity', [ $request ] );
319  }
320 
325  public function getErrorFormatter() {
326  return $this->mErrorFormatter;
327  }
328 
333  public function getContinuationManager() {
335  }
336 
341  public function setContinuationManager( $manager ) {
342  if ( $manager !== null ) {
343  if ( !$manager instanceof ApiContinuationManager ) {
344  throw new InvalidArgumentException( __METHOD__ . ': Was passed ' .
345  is_object( $manager ) ? get_class( $manager ) : gettype( $manager )
346  );
347  }
348  if ( $this->mContinuationManager !== null ) {
349  throw new UnexpectedValueException(
350  __METHOD__ . ': tried to set manager from ' . $manager->getSource() .
351  ' when a manager is already set from ' . $this->mContinuationManager->getSource()
352  );
353  }
354  }
355  $this->mContinuationManager = $manager;
356  }
357 
363  public function getModule() {
364  return $this->mModule;
365  }
366 
372  public function getPrinter() {
373  return $this->mPrinter;
374  }
375 
381  public function setCacheMaxAge( $maxage ) {
382  $this->setCacheControl( [
383  'max-age' => $maxage,
384  's-maxage' => $maxage
385  ] );
386  }
387 
413  public function setCacheMode( $mode ) {
414  if ( !in_array( $mode, [ 'private', 'public', 'anon-public-user-private' ] ) ) {
415  wfDebug( __METHOD__ . ": unrecognised cache mode \"$mode\"\n" );
416 
417  // Ignore for forwards-compatibility
418  return;
419  }
420 
421  if ( !User::isEveryoneAllowed( 'read' ) ) {
422  // Private wiki, only private headers
423  if ( $mode !== 'private' ) {
424  wfDebug( __METHOD__ . ": ignoring request for $mode cache mode, private wiki\n" );
425 
426  return;
427  }
428  }
429 
430  if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) {
431  // User language is used for i18n, so we don't want to publicly
432  // cache. Anons are ok, because if they have non-default language
433  // then there's an appropriate Vary header set by whatever set
434  // their non-default language.
435  wfDebug( __METHOD__ . ": downgrading cache mode 'public' to " .
436  "'anon-public-user-private' due to uselang=user\n" );
437  $mode = 'anon-public-user-private';
438  }
439 
440  wfDebug( __METHOD__ . ": setting cache mode $mode\n" );
441  $this->mCacheMode = $mode;
442  }
443 
454  public function setCacheControl( $directives ) {
455  $this->mCacheControl = $directives + $this->mCacheControl;
456  }
457 
465  public function createPrinterByName( $format ) {
466  $printer = $this->mModuleMgr->getModule( $format, 'format' );
467  if ( $printer === null ) {
468  $this->dieUsage( "Unrecognized format: {$format}", 'unknown_format' );
469  }
470 
471  return $printer;
472  }
473 
477  public function execute() {
478  if ( $this->mInternalMode ) {
479  $this->executeAction();
480  } else {
482  }
483  }
484 
489  protected function executeActionWithErrorHandling() {
490  // Verify the CORS header before executing the action
491  if ( !$this->handleCORS() ) {
492  // handleCORS() has sent a 403, abort
493  return;
494  }
495 
496  // Exit here if the request method was OPTIONS
497  // (assume there will be a followup GET or POST)
498  if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
499  return;
500  }
501 
502  // In case an error occurs during data output,
503  // clear the output buffer and print just the error information
504  $obLevel = ob_get_level();
505  ob_start();
506 
507  $t = microtime( true );
508  $isError = false;
509  try {
510  $this->executeAction();
511  $runTime = microtime( true ) - $t;
512  $this->logRequest( $runTime );
513  if ( $this->mModule->isWriteMode() && $this->getRequest()->wasPosted() ) {
514  $this->getStats()->timing(
515  'api.' . $this->mModule->getModuleName() . '.executeTiming', 1000 * $runTime
516  );
517  }
518  } catch ( Exception $e ) {
519  $this->handleException( $e );
520  $this->logRequest( microtime( true ) - $t, $e );
521  $isError = true;
522  }
523 
524  // Commit DBs and send any related cookies and headers
526 
527  // Send cache headers after any code which might generate an error, to
528  // avoid sending public cache headers for errors.
529  $this->sendCacheHeaders( $isError );
530 
531  // Executing the action might have already messed with the output
532  // buffers.
533  while ( ob_get_level() > $obLevel ) {
534  ob_end_flush();
535  }
536  }
537 
544  protected function handleException( Exception $e ) {
545  // Bug 63145: Rollback any open database transactions
546  if ( !( $e instanceof UsageException ) ) {
547  // UsageExceptions are intentional, so don't rollback if that's the case
548  try {
550  } catch ( DBError $e2 ) {
551  // Rollback threw an exception too. Log it, but don't interrupt
552  // our regularly scheduled exception handling.
554  }
555  }
556 
557  // Allow extra cleanup and logging
558  Hooks::run( 'ApiMain::onException', [ $this, $e ] );
559 
560  // Log it
561  if ( !( $e instanceof UsageException ) ) {
563  }
564 
565  // Handle any kind of exception by outputting properly formatted error message.
566  // If this fails, an unhandled exception should be thrown so that global error
567  // handler will process and log it.
568 
569  $errCode = $this->substituteResultWithError( $e );
570 
571  // Error results should not be cached
572  $this->setCacheMode( 'private' );
573 
574  $response = $this->getRequest()->response();
575  $headerStr = 'MediaWiki-API-Error: ' . $errCode;
576  if ( $e->getCode() === 0 ) {
577  $response->header( $headerStr );
578  } else {
579  $response->header( $headerStr, true, $e->getCode() );
580  }
581 
582  // Reset and print just the error message
583  ob_clean();
584 
585  // Printer may not be initialized if the extractRequestParams() fails for the main module
586  $this->createErrorPrinter();
587 
588  try {
589  $this->printResult( true );
590  } catch ( UsageException $ex ) {
591  // The error printer itself is failing. Try suppressing its request
592  // parameters and redo.
593  $this->setWarning(
594  'Error printer failed (will retry without params): ' . $ex->getMessage()
595  );
596  $this->mPrinter = null;
597  $this->createErrorPrinter();
598  $this->mPrinter->forceDefaultParams();
599  $this->printResult( true );
600  }
601  }
602 
613  public static function handleApiBeforeMainException( Exception $e ) {
614  ob_start();
615 
616  try {
617  $main = new self( RequestContext::getMain(), false );
618  $main->handleException( $e );
619  $main->logRequest( 0, $e );
620  } catch ( Exception $e2 ) {
621  // Nope, even that didn't work. Punt.
622  throw $e;
623  }
624 
625  // Reset cache headers
626  $main->sendCacheHeaders( true );
627 
628  ob_end_flush();
629  }
630 
645  protected function handleCORS() {
646  $originParam = $this->getParameter( 'origin' ); // defaults to null
647  if ( $originParam === null ) {
648  // No origin parameter, nothing to do
649  return true;
650  }
651 
652  $request = $this->getRequest();
653  $response = $request->response();
654 
655  $matchOrigin = false;
656  $allowTiming = false;
657  $varyOrigin = true;
658 
659  if ( $originParam === '*' ) {
660  // Request for anonymous CORS
661  $matchOrigin = true;
662  $allowOrigin = '*';
663  $allowCredentials = 'false';
664  $varyOrigin = false; // No need to vary
665  } else {
666  // Non-anonymous CORS, check we allow the domain
667 
668  // Origin: header is a space-separated list of origins, check all of them
669  $originHeader = $request->getHeader( 'Origin' );
670  if ( $originHeader === false ) {
671  $origins = [];
672  } else {
673  $originHeader = trim( $originHeader );
674  $origins = preg_split( '/\s+/', $originHeader );
675  }
676 
677  if ( !in_array( $originParam, $origins ) ) {
678  // origin parameter set but incorrect
679  // Send a 403 response
680  $response->statusHeader( 403 );
681  $response->header( 'Cache-Control: no-cache' );
682  echo "'origin' parameter does not match Origin header\n";
683 
684  return false;
685  }
686 
687  $config = $this->getConfig();
688  $matchOrigin = count( $origins ) === 1 && self::matchOrigin(
689  $originParam,
690  $config->get( 'CrossSiteAJAXdomains' ),
691  $config->get( 'CrossSiteAJAXdomainExceptions' )
692  );
693 
694  $allowOrigin = $originHeader;
695  $allowCredentials = 'true';
696  $allowTiming = $originHeader;
697  }
698 
699  if ( $matchOrigin ) {
700  $requestedMethod = $request->getHeader( 'Access-Control-Request-Method' );
701  $preflight = $request->getMethod() === 'OPTIONS' && $requestedMethod !== false;
702  if ( $preflight ) {
703  // This is a CORS preflight request
704  if ( $requestedMethod !== 'POST' && $requestedMethod !== 'GET' ) {
705  // If method is not a case-sensitive match, do not set any additional headers and terminate.
706  return true;
707  }
708  // We allow the actual request to send the following headers
709  $requestedHeaders = $request->getHeader( 'Access-Control-Request-Headers' );
710  if ( $requestedHeaders !== false ) {
711  if ( !self::matchRequestedHeaders( $requestedHeaders ) ) {
712  return true;
713  }
714  $response->header( 'Access-Control-Allow-Headers: ' . $requestedHeaders );
715  }
716 
717  // We only allow the actual request to be GET or POST
718  $response->header( 'Access-Control-Allow-Methods: POST, GET' );
719  }
720 
721  $response->header( "Access-Control-Allow-Origin: $allowOrigin" );
722  $response->header( "Access-Control-Allow-Credentials: $allowCredentials" );
723  // http://www.w3.org/TR/resource-timing/#timing-allow-origin
724  if ( $allowTiming !== false ) {
725  $response->header( "Timing-Allow-Origin: $allowTiming" );
726  }
727 
728  if ( !$preflight ) {
729  $response->header(
730  'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag'
731  );
732  }
733  }
734 
735  if ( $varyOrigin ) {
736  $this->getOutput()->addVaryHeader( 'Origin' );
737  }
738 
739  return true;
740  }
741 
750  protected static function matchOrigin( $value, $rules, $exceptions ) {
751  foreach ( $rules as $rule ) {
752  if ( preg_match( self::wildcardToRegex( $rule ), $value ) ) {
753  // Rule matches, check exceptions
754  foreach ( $exceptions as $exc ) {
755  if ( preg_match( self::wildcardToRegex( $exc ), $value ) ) {
756  return false;
757  }
758  }
759 
760  return true;
761  }
762  }
763 
764  return false;
765  }
766 
774  protected static function matchRequestedHeaders( $requestedHeaders ) {
775  if ( trim( $requestedHeaders ) === '' ) {
776  return true;
777  }
778  $requestedHeaders = explode( ',', $requestedHeaders );
779  $allowedAuthorHeaders = array_flip( [
780  /* simple headers (see spec) */
781  'accept',
782  'accept-language',
783  'content-language',
784  'content-type',
785  /* non-authorable headers in XHR, which are however requested by some UAs */
786  'accept-encoding',
787  'dnt',
788  'origin',
789  /* MediaWiki whitelist */
790  'api-user-agent',
791  ] );
792  foreach ( $requestedHeaders as $rHeader ) {
793  $rHeader = strtolower( trim( $rHeader ) );
794  if ( !isset( $allowedAuthorHeaders[$rHeader] ) ) {
795  wfDebugLog( 'api', 'CORS preflight failed on requested header: ' . $rHeader );
796  return false;
797  }
798  }
799  return true;
800  }
801 
810  protected static function wildcardToRegex( $wildcard ) {
811  $wildcard = preg_quote( $wildcard, '/' );
812  $wildcard = str_replace(
813  [ '\*', '\?' ],
814  [ '.*?', '.' ],
815  $wildcard
816  );
817 
818  return "/^https?:\/\/$wildcard$/";
819  }
820 
826  protected function sendCacheHeaders( $isError ) {
827  $response = $this->getRequest()->response();
828  $out = $this->getOutput();
829 
830  $out->addVaryHeader( 'Treat-as-Untrusted' );
831 
832  $config = $this->getConfig();
833 
834  if ( $config->get( 'VaryOnXFP' ) ) {
835  $out->addVaryHeader( 'X-Forwarded-Proto' );
836  }
837 
838  if ( !$isError && $this->mModule &&
839  ( $this->getRequest()->getMethod() === 'GET' || $this->getRequest()->getMethod() === 'HEAD' )
840  ) {
841  $etag = $this->mModule->getConditionalRequestData( 'etag' );
842  if ( $etag !== null ) {
843  $response->header( "ETag: $etag" );
844  }
845  $lastMod = $this->mModule->getConditionalRequestData( 'last-modified' );
846  if ( $lastMod !== null ) {
847  $response->header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822, $lastMod ) );
848  }
849  }
850 
851  // The logic should be:
852  // $this->mCacheControl['max-age'] is set?
853  // Use it, the module knows better than our guess.
854  // !$this->mModule || $this->mModule->isWriteMode(), and mCacheMode is private?
855  // Use 0 because we can guess caching is probably the wrong thing to do.
856  // Use $this->getParameter( 'maxage' ), which already defaults to 0.
857  $maxage = 0;
858  if ( isset( $this->mCacheControl['max-age'] ) ) {
859  $maxage = $this->mCacheControl['max-age'];
860  } elseif ( ( $this->mModule && !$this->mModule->isWriteMode() ) ||
861  $this->mCacheMode !== 'private'
862  ) {
863  $maxage = $this->getParameter( 'maxage' );
864  }
865  $privateCache = 'private, must-revalidate, max-age=' . $maxage;
866 
867  if ( $this->mCacheMode == 'private' ) {
868  $response->header( "Cache-Control: $privateCache" );
869  return;
870  }
871 
872  $useKeyHeader = $config->get( 'UseKeyHeader' );
873  if ( $this->mCacheMode == 'anon-public-user-private' ) {
874  $out->addVaryHeader( 'Cookie' );
875  $response->header( $out->getVaryHeader() );
876  if ( $useKeyHeader ) {
877  $response->header( $out->getKeyHeader() );
878  if ( $out->haveCacheVaryCookies() ) {
879  // Logged in, mark this request private
880  $response->header( "Cache-Control: $privateCache" );
881  return;
882  }
883  // Logged out, send normal public headers below
884  } elseif ( MediaWiki\Session\SessionManager::getGlobalSession()->isPersistent() ) {
885  // Logged in or otherwise has session (e.g. anonymous users who have edited)
886  // Mark request private
887  $response->header( "Cache-Control: $privateCache" );
888 
889  return;
890  } // else no Key and anonymous, send public headers below
891  }
892 
893  // Send public headers
894  $response->header( $out->getVaryHeader() );
895  if ( $useKeyHeader ) {
896  $response->header( $out->getKeyHeader() );
897  }
898 
899  // If nobody called setCacheMaxAge(), use the (s)maxage parameters
900  if ( !isset( $this->mCacheControl['s-maxage'] ) ) {
901  $this->mCacheControl['s-maxage'] = $this->getParameter( 'smaxage' );
902  }
903  if ( !isset( $this->mCacheControl['max-age'] ) ) {
904  $this->mCacheControl['max-age'] = $this->getParameter( 'maxage' );
905  }
906 
907  if ( !$this->mCacheControl['s-maxage'] && !$this->mCacheControl['max-age'] ) {
908  // Public cache not requested
909  // Sending a Vary header in this case is harmless, and protects us
910  // against conditional calls of setCacheMaxAge().
911  $response->header( "Cache-Control: $privateCache" );
912 
913  return;
914  }
915 
916  $this->mCacheControl['public'] = true;
917 
918  // Send an Expires header
919  $maxAge = min( $this->mCacheControl['s-maxage'], $this->mCacheControl['max-age'] );
920  $expiryUnixTime = ( $maxAge == 0 ? 1 : time() + $maxAge );
921  $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822, $expiryUnixTime ) );
922 
923  // Construct the Cache-Control header
924  $ccHeader = '';
925  $separator = '';
926  foreach ( $this->mCacheControl as $name => $value ) {
927  if ( is_bool( $value ) ) {
928  if ( $value ) {
929  $ccHeader .= $separator . $name;
930  $separator = ', ';
931  }
932  } else {
933  $ccHeader .= $separator . "$name=$value";
934  $separator = ', ';
935  }
936  }
937 
938  $response->header( "Cache-Control: $ccHeader" );
939  }
940 
944  private function createErrorPrinter() {
945  if ( !isset( $this->mPrinter ) ) {
946  $value = $this->getRequest()->getVal( 'format', self::API_DEFAULT_FORMAT );
947  if ( !$this->mModuleMgr->isDefined( $value, 'format' ) ) {
948  $value = self::API_DEFAULT_FORMAT;
949  }
950  $this->mPrinter = $this->createPrinterByName( $value );
951  }
952 
953  // Printer may not be able to handle errors. This is particularly
954  // likely if the module returns something for getCustomPrinter().
955  if ( !$this->mPrinter->canPrintErrors() ) {
956  $this->mPrinter = $this->createPrinterByName( self::API_DEFAULT_FORMAT );
957  }
958  }
959 
970  protected function errorMessageFromException( $e ) {
971  if ( $e instanceof UsageException ) {
972  // User entered incorrect parameters - generate error response
973  $errMessage = $e->getMessageArray();
974  } else {
975  $config = $this->getConfig();
976  // Something is seriously wrong
977  if ( ( $e instanceof DBQueryError ) && !$config->get( 'ShowSQLErrors' ) ) {
978  $info = 'Database query error';
979  } else {
980  $info = "Exception Caught: {$e->getMessage()}";
981  }
982 
983  $errMessage = [
984  'code' => 'internal_api_error_' . get_class( $e ),
985  'info' => '[' . WebRequest::getRequestId() . '] ' . $info,
986  ];
987  }
988  return $errMessage;
989  }
990 
997  protected function substituteResultWithError( $e ) {
998  $result = $this->getResult();
999  $config = $this->getConfig();
1000 
1001  $errMessage = $this->errorMessageFromException( $e );
1002  if ( $e instanceof UsageException ) {
1003  // User entered incorrect parameters - generate error response
1004  $link = wfExpandUrl( wfScript( 'api' ) );
1005  ApiResult::setContentValue( $errMessage, 'docref', "See $link for API usage" );
1006  } else {
1007  // Something is seriously wrong
1008  if ( $config->get( 'ShowExceptionDetails' ) ) {
1010  $errMessage,
1011  'trace',
1013  );
1014  }
1015  }
1016 
1017  // Remember all the warnings to re-add them later
1018  $warnings = $result->getResultData( [ 'warnings' ] );
1019 
1020  $result->reset();
1021  // Re-add the id
1022  $requestid = $this->getParameter( 'requestid' );
1023  if ( !is_null( $requestid ) ) {
1024  $result->addValue( null, 'requestid', $requestid, ApiResult::NO_SIZE_CHECK );
1025  }
1026  if ( $config->get( 'ShowHostnames' ) ) {
1027  // servedby is especially useful when debugging errors
1028  $result->addValue( null, 'servedby', wfHostname(), ApiResult::NO_SIZE_CHECK );
1029  }
1030  if ( $warnings !== null ) {
1031  $result->addValue( null, 'warnings', $warnings, ApiResult::NO_SIZE_CHECK );
1032  }
1033 
1034  $result->addValue( null, 'error', $errMessage, ApiResult::NO_SIZE_CHECK );
1035 
1036  return $errMessage['code'];
1037  }
1038 
1043  protected function setupExecuteAction() {
1044  // First add the id to the top element
1045  $result = $this->getResult();
1046  $requestid = $this->getParameter( 'requestid' );
1047  if ( !is_null( $requestid ) ) {
1048  $result->addValue( null, 'requestid', $requestid );
1049  }
1050 
1051  if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
1052  $servedby = $this->getParameter( 'servedby' );
1053  if ( $servedby ) {
1054  $result->addValue( null, 'servedby', wfHostname() );
1055  }
1056  }
1057 
1058  if ( $this->getParameter( 'curtimestamp' ) ) {
1059  $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601, time() ),
1061  }
1062 
1063  $params = $this->extractRequestParams();
1064 
1065  $this->mAction = $params['action'];
1066 
1067  if ( !is_string( $this->mAction ) ) {
1068  $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
1069  }
1070 
1071  return $params;
1072  }
1073 
1080  protected function setupModule() {
1081  // Instantiate the module requested by the user
1082  $module = $this->mModuleMgr->getModule( $this->mAction, 'action' );
1083  if ( $module === null ) {
1084  $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
1085  }
1086  $moduleParams = $module->extractRequestParams();
1087 
1088  // Check token, if necessary
1089  if ( $module->needsToken() === true ) {
1090  throw new MWException(
1091  "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
1092  'See documentation for ApiBase::needsToken for details.'
1093  );
1094  }
1095  if ( $module->needsToken() ) {
1096  if ( !$module->mustBePosted() ) {
1097  throw new MWException(
1098  "Module '{$module->getModuleName()}' must require POST to use tokens."
1099  );
1100  }
1101 
1102  if ( !isset( $moduleParams['token'] ) ) {
1103  $this->dieUsageMsg( [ 'missingparam', 'token' ] );
1104  }
1105 
1106  $module->requirePostedParameters( [ 'token' ] );
1107 
1108  if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) {
1109  $this->dieUsageMsg( 'sessionfailure' );
1110  }
1111  }
1112 
1113  return $module;
1114  }
1115 
1122  protected function checkMaxLag( $module, $params ) {
1123  if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
1124  $maxLag = $params['maxlag'];
1125  list( $host, $lag ) = wfGetLB()->getMaxLag();
1126  if ( $lag > $maxLag ) {
1127  $response = $this->getRequest()->response();
1128 
1129  $response->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
1130  $response->header( 'X-Database-Lag: ' . intval( $lag ) );
1131 
1132  if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
1133  $this->dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
1134  }
1135 
1136  $this->dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
1137  }
1138  }
1139 
1140  return true;
1141  }
1142 
1164  protected function checkConditionalRequestHeaders( $module ) {
1165  if ( $this->mInternalMode ) {
1166  // No headers to check in internal mode
1167  return true;
1168  }
1169 
1170  if ( $this->getRequest()->getMethod() !== 'GET' && $this->getRequest()->getMethod() !== 'HEAD' ) {
1171  // Don't check POSTs
1172  return true;
1173  }
1174 
1175  $return304 = false;
1176 
1177  $ifNoneMatch = array_diff(
1178  $this->getRequest()->getHeader( 'If-None-Match', WebRequest::GETHEADER_LIST ) ?: [],
1179  [ '' ]
1180  );
1181  if ( $ifNoneMatch ) {
1182  if ( $ifNoneMatch === [ '*' ] ) {
1183  // API responses always "exist"
1184  $etag = '*';
1185  } else {
1186  $etag = $module->getConditionalRequestData( 'etag' );
1187  }
1188  }
1189  if ( $ifNoneMatch && $etag !== null ) {
1190  $test = substr( $etag, 0, 2 ) === 'W/' ? substr( $etag, 2 ) : $etag;
1191  $match = array_map( function ( $s ) {
1192  return substr( $s, 0, 2 ) === 'W/' ? substr( $s, 2 ) : $s;
1193  }, $ifNoneMatch );
1194  $return304 = in_array( $test, $match, true );
1195  } else {
1196  $value = trim( $this->getRequest()->getHeader( 'If-Modified-Since' ) );
1197 
1198  // Some old browsers sends sizes after the date, like this:
1199  // Wed, 20 Aug 2003 06:51:19 GMT; length=5202
1200  // Ignore that.
1201  $i = strpos( $value, ';' );
1202  if ( $i !== false ) {
1203  $value = trim( substr( $value, 0, $i ) );
1204  }
1205 
1206  if ( $value !== '' ) {
1207  try {
1208  $ts = new MWTimestamp( $value );
1209  if (
1210  // RFC 7231 IMF-fixdate
1211  $ts->getTimestamp( TS_RFC2822 ) === $value ||
1212  // RFC 850
1213  $ts->format( 'l, d-M-y H:i:s' ) . ' GMT' === $value ||
1214  // asctime (with and without space-padded day)
1215  $ts->format( 'D M j H:i:s Y' ) === $value ||
1216  $ts->format( 'D M j H:i:s Y' ) === $value
1217  ) {
1218  $lastMod = $module->getConditionalRequestData( 'last-modified' );
1219  if ( $lastMod !== null ) {
1220  // Mix in some MediaWiki modification times
1221  $modifiedTimes = [
1222  'page' => $lastMod,
1223  'user' => $this->getUser()->getTouched(),
1224  'epoch' => $this->getConfig()->get( 'CacheEpoch' ),
1225  ];
1226  if ( $this->getConfig()->get( 'UseSquid' ) ) {
1227  // T46570: the core page itself may not change, but resources might
1228  $modifiedTimes['sepoch'] = wfTimestamp(
1229  TS_MW, time() - $this->getConfig()->get( 'SquidMaxage' )
1230  );
1231  }
1232  Hooks::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this->getOutput() ] );
1233  $lastMod = max( $modifiedTimes );
1234  $return304 = wfTimestamp( TS_MW, $lastMod ) <= $ts->getTimestamp( TS_MW );
1235  }
1236  }
1237  } catch ( TimestampException $e ) {
1238  // Invalid timestamp, ignore it
1239  }
1240  }
1241  }
1242 
1243  if ( $return304 ) {
1244  $this->getRequest()->response()->statusHeader( 304 );
1245 
1246  // Avoid outputting the compressed representation of a zero-length body
1247  MediaWiki\suppressWarnings();
1248  ini_set( 'zlib.output_compression', 0 );
1249  MediaWiki\restoreWarnings();
1251 
1252  return false;
1253  }
1254 
1255  return true;
1256  }
1257 
1262  protected function checkExecutePermissions( $module ) {
1263  $user = $this->getUser();
1264  if ( $module->isReadMode() && !User::isEveryoneAllowed( 'read' ) &&
1265  !$user->isAllowed( 'read' )
1266  ) {
1267  $this->dieUsageMsg( 'readrequired' );
1268  }
1269 
1270  if ( $module->isWriteMode() ) {
1271  if ( !$this->mEnableWrite ) {
1272  $this->dieUsageMsg( 'writedisabled' );
1273  } elseif ( !$user->isAllowed( 'writeapi' ) ) {
1274  $this->dieUsageMsg( 'writerequired' );
1275  } elseif ( $this->getRequest()->getHeader( 'Promise-Non-Write-API-Action' ) ) {
1276  $this->dieUsage(
1277  'Promise-Non-Write-API-Action HTTP header cannot be sent to write API modules',
1278  'promised-nonwrite-api'
1279  );
1280  }
1281 
1282  $this->checkReadOnly( $module );
1283  }
1284 
1285  // Allow extensions to stop execution for arbitrary reasons.
1286  $message = false;
1287  if ( !Hooks::run( 'ApiCheckCanExecute', [ $module, $user, &$message ] ) ) {
1288  $this->dieUsageMsg( $message );
1289  }
1290  }
1291 
1296  protected function checkReadOnly( $module ) {
1297  if ( wfReadOnly() ) {
1298  $this->dieReadOnly();
1299  }
1300 
1301  if ( $module->isWriteMode()
1302  && $this->getUser()->isBot()
1303  && wfGetLB()->getServerCount() > 1
1304  ) {
1305  $this->checkBotReadOnly();
1306  }
1307  }
1308 
1312  private function checkBotReadOnly() {
1313  // Figure out how many servers have passed the lag threshold
1314  $numLagged = 0;
1315  $lagLimit = $this->getConfig()->get( 'APIMaxLagThreshold' );
1316  $laggedServers = [];
1317  $loadBalancer = wfGetLB();
1318  foreach ( $loadBalancer->getLagTimes() as $serverIndex => $lag ) {
1319  if ( $lag > $lagLimit ) {
1320  ++$numLagged;
1321  $laggedServers[] = $loadBalancer->getServerName( $serverIndex ) . " ({$lag}s)";
1322  }
1323  }
1324 
1325  // If a majority of replica DBs are too lagged then disallow writes
1326  $replicaCount = wfGetLB()->getServerCount() - 1;
1327  if ( $numLagged >= ceil( $replicaCount / 2 ) ) {
1328  $laggedServers = implode( ', ', $laggedServers );
1329  wfDebugLog(
1330  'api-readonly',
1331  "Api request failed as read only because the following DBs are lagged: $laggedServers"
1332  );
1333 
1334  $parsed = $this->parseMsg( [ 'readonlytext' ] );
1335  $this->dieUsage(
1336  $parsed['info'],
1337  $parsed['code'],
1338  /* http error */
1339  0,
1340  [ 'readonlyreason' => "Waiting for $numLagged lagged database(s)" ]
1341  );
1342  }
1343  }
1344 
1349  protected function checkAsserts( $params ) {
1350  if ( isset( $params['assert'] ) ) {
1351  $user = $this->getUser();
1352  switch ( $params['assert'] ) {
1353  case 'user':
1354  if ( $user->isAnon() ) {
1355  $this->dieUsage( 'Assertion that the user is logged in failed', 'assertuserfailed' );
1356  }
1357  break;
1358  case 'bot':
1359  if ( !$user->isAllowed( 'bot' ) ) {
1360  $this->dieUsage( 'Assertion that the user has the bot right failed', 'assertbotfailed' );
1361  }
1362  break;
1363  }
1364  }
1365  if ( isset( $params['assertuser'] ) ) {
1366  $assertUser = User::newFromName( $params['assertuser'], false );
1367  if ( !$assertUser || !$this->getUser()->equals( $assertUser ) ) {
1368  $this->dieUsage(
1369  'Assertion that the user is "' . $params['assertuser'] . '" failed',
1370  'assertnameduserfailed'
1371  );
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  $trxProfiler->setLogger( LoggerFactory::getInstance( 'DBPerformance' ) );
1457  if ( $this->getRequest()->hasSafeMethod() ) {
1458  $trxProfiler->setExpectations( $limits['GET'], __METHOD__ );
1459  } elseif ( $this->getRequest()->wasPosted() && !$module->isWriteMode() ) {
1460  $trxProfiler->setExpectations( $limits['POST-nonwrite'], __METHOD__ );
1461  $this->getRequest()->markAsSafeRequest();
1462  } else {
1463  $trxProfiler->setExpectations( $limits['POST'], __METHOD__ );
1464  }
1465  }
1466 
1472  protected function logRequest( $time, $e = null ) {
1473  $request = $this->getRequest();
1474  $logCtx = [
1475  'ts' => time(),
1476  'ip' => $request->getIP(),
1477  'userAgent' => $this->getUserAgent(),
1478  'wiki' => wfWikiID(),
1479  'timeSpentBackend' => (int) round( $time * 1000 ),
1480  'hadError' => $e !== null,
1481  'errorCodes' => [],
1482  'params' => [],
1483  ];
1484 
1485  if ( $e ) {
1486  $logCtx['errorCodes'][] = $this->errorMessageFromException( $e )['code'];
1487  }
1488 
1489  // Construct space separated message for 'api' log channel
1490  $msg = "API {$request->getMethod()} " .
1491  wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
1492  " {$logCtx['ip']} " .
1493  "T={$logCtx['timeSpentBackend']}ms";
1494 
1495  $sensitive = array_flip( $this->getSensitiveParams() );
1496  foreach ( $this->getParamsUsed() as $name ) {
1497  $value = $request->getVal( $name );
1498  if ( $value === null ) {
1499  continue;
1500  }
1501 
1502  if ( isset( $sensitive[$name] ) ) {
1503  $value = '[redacted]';
1504  $encValue = '[redacted]';
1505  } elseif ( strlen( $value ) > 256 ) {
1506  $value = substr( $value, 0, 256 );
1507  $encValue = $this->encodeRequestLogValue( $value ) . '[...]';
1508  } else {
1509  $encValue = $this->encodeRequestLogValue( $value );
1510  }
1511 
1512  $logCtx['params'][$name] = $value;
1513  $msg .= " {$name}={$encValue}";
1514  }
1515 
1516  wfDebugLog( 'api', $msg, 'private' );
1517  // ApiAction channel is for structured data consumers
1518  wfDebugLog( 'ApiAction', '', 'private', $logCtx );
1519  }
1520 
1526  protected function encodeRequestLogValue( $s ) {
1527  static $table;
1528  if ( !$table ) {
1529  $chars = ';@$!*(),/:';
1530  $numChars = strlen( $chars );
1531  for ( $i = 0; $i < $numChars; $i++ ) {
1532  $table[rawurlencode( $chars[$i] )] = $chars[$i];
1533  }
1534  }
1535 
1536  return strtr( rawurlencode( $s ), $table );
1537  }
1538 
1543  protected function getParamsUsed() {
1544  return array_keys( $this->mParamsUsed );
1545  }
1546 
1551  public function markParamsUsed( $params ) {
1552  $this->mParamsUsed += array_fill_keys( (array)$params, true );
1553  }
1554 
1560  protected function getSensitiveParams() {
1561  return array_keys( $this->mParamsSensitive );
1562  }
1563 
1569  public function markParamsSensitive( $params ) {
1570  $this->mParamsSensitive += array_fill_keys( (array)$params, true );
1571  }
1572 
1579  public function getVal( $name, $default = null ) {
1580  $this->mParamsUsed[$name] = true;
1581 
1582  $ret = $this->getRequest()->getVal( $name );
1583  if ( $ret === null ) {
1584  if ( $this->getRequest()->getArray( $name ) !== null ) {
1585  // See bug 10262 for why we don't just implode( '|', ... ) the
1586  // array.
1587  $this->setWarning(
1588  "Parameter '$name' uses unsupported PHP array syntax"
1589  );
1590  }
1591  $ret = $default;
1592  }
1593  return $ret;
1594  }
1595 
1602  public function getCheck( $name ) {
1603  return $this->getVal( $name, null ) !== null;
1604  }
1605 
1613  public function getUpload( $name ) {
1614  $this->mParamsUsed[$name] = true;
1615 
1616  return $this->getRequest()->getUpload( $name );
1617  }
1618 
1623  protected function reportUnusedParams() {
1624  $paramsUsed = $this->getParamsUsed();
1625  $allParams = $this->getRequest()->getValueNames();
1626 
1627  if ( !$this->mInternalMode ) {
1628  // Printer has not yet executed; don't warn that its parameters are unused
1629  $printerParams = array_map(
1630  [ $this->mPrinter, 'encodeParamName' ],
1631  array_keys( $this->mPrinter->getFinalParams() ?: [] )
1632  );
1633  $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1634  } else {
1635  $unusedParams = array_diff( $allParams, $paramsUsed );
1636  }
1637 
1638  if ( count( $unusedParams ) ) {
1639  $s = count( $unusedParams ) > 1 ? 's' : '';
1640  $this->setWarning( "Unrecognized parameter$s: '" . implode( $unusedParams, "', '" ) . "'" );
1641  }
1642  }
1643 
1649  protected function printResult( $isError ) {
1650  if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
1651  $this->setWarning( 'SECURITY WARNING: $wgDebugAPI is enabled' );
1652  }
1653 
1654  $printer = $this->mPrinter;
1655  $printer->initPrinter( false );
1656  $printer->execute();
1657  $printer->closePrinter();
1658  }
1659 
1663  public function isReadMode() {
1664  return false;
1665  }
1666 
1672  public function getAllowedParams() {
1673  return [
1674  'action' => [
1675  ApiBase::PARAM_DFLT => 'help',
1676  ApiBase::PARAM_TYPE => 'submodule',
1677  ],
1678  'format' => [
1680  ApiBase::PARAM_TYPE => 'submodule',
1681  ],
1682  'maxlag' => [
1683  ApiBase::PARAM_TYPE => 'integer'
1684  ],
1685  'smaxage' => [
1686  ApiBase::PARAM_TYPE => 'integer',
1687  ApiBase::PARAM_DFLT => 0
1688  ],
1689  'maxage' => [
1690  ApiBase::PARAM_TYPE => 'integer',
1691  ApiBase::PARAM_DFLT => 0
1692  ],
1693  'assert' => [
1694  ApiBase::PARAM_TYPE => [ 'user', 'bot' ]
1695  ],
1696  'assertuser' => [
1697  ApiBase::PARAM_TYPE => 'user',
1698  ],
1699  'requestid' => null,
1700  'servedby' => false,
1701  'curtimestamp' => false,
1702  'origin' => null,
1703  'uselang' => [
1704  ApiBase::PARAM_DFLT => 'user',
1705  ],
1706  ];
1707  }
1708 
1710  protected function getExamplesMessages() {
1711  return [
1712  'action=help'
1713  => 'apihelp-help-example-main',
1714  'action=help&recursivesubmodules=1'
1715  => 'apihelp-help-example-recursive',
1716  ];
1717  }
1718 
1719  public function modifyHelp( array &$help, array $options, array &$tocData ) {
1720  // Wish PHP had an "array_insert_before". Instead, we have to manually
1721  // reindex the array to get 'permissions' in the right place.
1722  $oldHelp = $help;
1723  $help = [];
1724  foreach ( $oldHelp as $k => $v ) {
1725  if ( $k === 'submodules' ) {
1726  $help['permissions'] = '';
1727  }
1728  $help[$k] = $v;
1729  }
1730  $help['datatypes'] = '';
1731  $help['credits'] = '';
1732 
1733  // Fill 'permissions'
1734  $help['permissions'] .= Html::openElement( 'div',
1735  [ 'class' => 'apihelp-block apihelp-permissions' ] );
1736  $m = $this->msg( 'api-help-permissions' );
1737  if ( !$m->isDisabled() ) {
1738  $help['permissions'] .= Html::rawElement( 'div', [ 'class' => 'apihelp-block-head' ],
1739  $m->numParams( count( self::$mRights ) )->parse()
1740  );
1741  }
1742  $help['permissions'] .= Html::openElement( 'dl' );
1743  foreach ( self::$mRights as $right => $rightMsg ) {
1744  $help['permissions'] .= Html::element( 'dt', null, $right );
1745 
1746  $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse();
1747  $help['permissions'] .= Html::rawElement( 'dd', null, $rightMsg );
1748 
1749  $groups = array_map( function ( $group ) {
1750  return $group == '*' ? 'all' : $group;
1751  }, User::getGroupsWithPermission( $right ) );
1752 
1753  $help['permissions'] .= Html::rawElement( 'dd', null,
1754  $this->msg( 'api-help-permissions-granted-to' )
1755  ->numParams( count( $groups ) )
1756  ->params( $this->getLanguage()->commaList( $groups ) )
1757  ->parse()
1758  );
1759  }
1760  $help['permissions'] .= Html::closeElement( 'dl' );
1761  $help['permissions'] .= Html::closeElement( 'div' );
1762 
1763  // Fill 'datatypes' and 'credits', if applicable
1764  if ( empty( $options['nolead'] ) ) {
1765  $level = $options['headerlevel'];
1766  $tocnumber = &$options['tocnumber'];
1767 
1768  $header = $this->msg( 'api-help-datatypes-header' )->parse();
1769 
1770  // Add an additional span with sanitized ID
1771  if ( !$this->getConfig()->get( 'ExperimentalHtmlIds' ) ) {
1772  $header = Html::element( 'span', [ 'id' => Sanitizer::escapeId( 'main/datatypes' ) ] ) .
1773  $header;
1774  }
1775  $help['datatypes'] .= Html::rawElement( 'h' . min( 6, $level ),
1776  [ 'id' => 'main/datatypes', 'class' => 'apihelp-header' ],
1777  $header
1778  );
1779  $help['datatypes'] .= $this->msg( 'api-help-datatypes' )->parseAsBlock();
1780  if ( !isset( $tocData['main/datatypes'] ) ) {
1781  $tocnumber[$level]++;
1782  $tocData['main/datatypes'] = [
1783  'toclevel' => count( $tocnumber ),
1784  'level' => $level,
1785  'anchor' => 'main/datatypes',
1786  'line' => $header,
1787  'number' => implode( '.', $tocnumber ),
1788  'index' => false,
1789  ];
1790  }
1791 
1792  // Add an additional span with sanitized ID
1793  if ( !$this->getConfig()->get( 'ExperimentalHtmlIds' ) ) {
1794  $header = Html::element( 'span', [ 'id' => Sanitizer::escapeId( 'main/credits' ) ] ) .
1795  $header;
1796  }
1797  $header = $this->msg( 'api-credits-header' )->parse();
1798  $help['credits'] .= Html::rawElement( 'h' . min( 6, $level ),
1799  [ 'id' => 'main/credits', 'class' => 'apihelp-header' ],
1800  $header
1801  );
1802  $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
1803  if ( !isset( $tocData['main/credits'] ) ) {
1804  $tocnumber[$level]++;
1805  $tocData['main/credits'] = [
1806  'toclevel' => count( $tocnumber ),
1807  'level' => $level,
1808  'anchor' => 'main/credits',
1809  'line' => $header,
1810  'number' => implode( '.', $tocnumber ),
1811  'index' => false,
1812  ];
1813  }
1814  }
1815  }
1816 
1817  private $mCanApiHighLimits = null;
1818 
1823  public function canApiHighLimits() {
1824  if ( !isset( $this->mCanApiHighLimits ) ) {
1825  $this->mCanApiHighLimits = $this->getUser()->isAllowed( 'apihighlimits' );
1826  }
1827 
1828  return $this->mCanApiHighLimits;
1829  }
1830 
1835  public function getModuleManager() {
1836  return $this->mModuleMgr;
1837  }
1838 
1847  public function getUserAgent() {
1848  return trim(
1849  $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
1850  $this->getRequest()->getHeader( 'User-agent' )
1851  );
1852  }
1853 }
1854 
1861 
1862  private $mCodestr;
1863 
1867  private $mExtraData;
1868 
1875  public function __construct( $message, $codestr, $code = 0, $extradata = null ) {
1876  parent::__construct( $message, $code );
1877  $this->mCodestr = $codestr;
1878  $this->mExtraData = $extradata;
1879 
1880  // This should never happen, so throw an exception about it that will
1881  // hopefully get logged with a backtrace (T138585)
1882  if ( !is_string( $codestr ) || $codestr === '' ) {
1883  throw new InvalidArgumentException( 'Invalid $codestr, was ' .
1884  ( $codestr === '' ? 'empty string' : gettype( $codestr ) )
1885  );
1886  }
1887  }
1888 
1892  public function getCodeString() {
1893  return $this->mCodestr;
1894  }
1895 
1899  public function getMessageArray() {
1900  $result = [
1901  'code' => $this->mCodestr,
1902  'info' => $this->getMessage()
1903  ];
1904  if ( is_array( $this->mExtraData ) ) {
1905  $result = array_merge( $result, $this->mExtraData );
1906  }
1907 
1908  return $result;
1909  }
1910 
1914  public function __toString() {
1915  return "{$this->getCodeString()}: {$this->getMessage()}";
1916  }
1917 }
1918 
static newFromName($name, $validate= 'valid')
Static factory method for creation from username.
Definition: User.php:525
dieUsageMsgOrDebug($error)
Will only set a warning instead of failing if the global $wgDebugAPI is set to true.
Definition: ApiBase.php:2221
setContext(IContextSource $context)
Set the IContextSource object.
getAllowedParams()
See ApiBase for description.
Definition: ApiMain.php:1672
static closeElement($element)
Returns "".
Definition: Html.php:305
getModuleManager()
Overrides to return this instance's module manager.
Definition: ApiMain.php:1835
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:1847
const LIMIT_BIG2
Fast query, apihighlimits limit.
Definition: ApiBase.php:186
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:333
static $Modules
List of available modules: action name => module class.
Definition: ApiMain.php:52
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:802
Database error base class.
Definition: DBError.php:26
printResult($isError)
Print results using the current printer.
Definition: ApiMain.php:1649
checkConditionalRequestHeaders($module)
Check selected RFC 7232 precondition headers.
Definition: ApiMain.php:1164
the array() calling protocol came about after MediaWiki 1.4rc1.
$mEnableWrite
Definition: ApiMain.php:147
getLanguage()
Get the Language object.
static getRequestId()
Get the unique request ID.
Definition: WebRequest.php:272
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:489
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:1719
__construct($context=null, $enableWrite=false)
Constructs an instance of ApiMain that utilizes the module and format specified by $request...
Definition: ApiMain.php:167
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:1296
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:1936
bool null $lacksSameOriginSecurity
Cached return value from self::lacksSameOriginSecurity()
Definition: ApiMain.php:158
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException'returning false will NOT prevent logging $e
Definition: hooks.txt:2102
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
Definition: ApiBase.php:50
static instance()
Singleton.
Definition: Profiler.php:61
static rawElement($element, $attribs=[], $contents= '')
Returns an HTML element in a string.
Definition: Html.php:209
wfHostname()
Fetch server name for use in error reporting etc.
$mCacheControl
Definition: ApiMain.php:153
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:774
static static static ApiFormatBase $mPrinter
Definition: ApiMain.php:129
setCacheMaxAge($maxage)
Set how long the response should be cached.
Definition: ApiMain.php:381
const TS_RFC2822
RFC 2822 format, for E-mail and HTTP headers.
Definition: defines.php:21
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:273
$value
markParamsSensitive($params)
Mark parameters as sensitive.
Definition: ApiMain.php:1569
static preOutputCommit(IContextSource $context, callable $postCommitWork=null)
This function commits all DB changes as needed before the user can receive a response (in case commit...
Definition: MediaWiki.php:572
const GETHEADER_LIST
Flag to make WebRequest::getHeader return an array of values.
Definition: WebRequest.php:45
canApiHighLimits()
Check whether the current user is allowed to use high limits.
Definition: ApiMain.php:1823
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:802
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 handleApiBeforeMainException(Exception $e)
Handle an exception from the ApiBeforeMain hook.
Definition: ApiMain.php:613
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:47
const TS_ISO_8601
ISO 8601 format with no timezone: 1986-02-09T20:00:00Z.
Definition: defines.php:28
IContextSource $context
setCacheMode($mode)
Set the type of caching headers which will be sent.
Definition: ApiMain.php:413
ApiBase $mModule
Definition: ApiMain.php:150
static static static $mRights
List of user roles that are specifically relevant to the API.
Definition: ApiMain.php:126
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:454
errorMessageFromException($e)
Create an error message for the given exception.
Definition: ApiMain.php:970
static isEveryoneAllowed($right)
Check if all users may be assumed to have the given permission.
Definition: User.php:4645
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:1934
setupModule()
Set up the module for response.
Definition: ApiMain.php:1080
usually copyright or history_copyright This message must be in HTML not wikitext & $link
Definition: hooks.txt:2889
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:810
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:1936
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:247
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:1046
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:43
executeAction()
Execute the actual module, without any error handling.
Definition: ApiMain.php:1409
isReadMode()
Definition: ApiMain.php:1663
handleCORS()
Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
Definition: ApiMain.php:645
setupExecuteAction()
Set up for the execution.
Definition: ApiMain.php:1043
getSensitiveParams()
Get the request parameters that should be considered sensitive.
Definition: ApiMain.php:1560
const TS_MW
MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
Definition: defines.php:11
$mCacheMode
Definition: ApiMain.php:152
Format errors and warnings in the old style, for backwards compatibility.
$mErrorFormatter
Definition: ApiMain.php:143
lacksSameOriginSecurity()
Get the security flag for the current request.
Definition: ApiMain.php:290
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:465
static dieReadOnly()
Helper function for readonly errors.
Definition: ApiBase.php:2192
static matchOrigin($value, $rules, $exceptions)
Attempt to match an Origin header against a set of rules and a set of exceptions. ...
Definition: ApiMain.php:750
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
$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:155
encodeRequestLogValue($s)
Encode a value in a format suitable for a space-separated log line.
Definition: ApiMain.php:1526
$header
checkMaxLag($module, $params)
Check the max lag if necessary.
Definition: ApiMain.php:1122
setWarning($warning)
Set warning section for this module.
Definition: ApiBase.php:1554
$mCanApiHighLimits
Definition: ApiMain.php:1817
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:802
static static $Formats
List of available formats: format name => format class.
Definition: ApiMain.php:108
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:1543
getExamplesMessages()
Definition: ApiMain.php:1710
logRequest($time, $e=null)
Log the preceding request.
Definition: ApiMain.php:1472
getErrorFormatter()
Get the ApiErrorFormatter object associated with current request.
Definition: ApiMain.php:325
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:1170
getUpload($name)
Get a request upload, and register the fact that it was used, for logging.
Definition: ApiMain.php:1613
markParamsUsed($params)
Mark parameters as used.
Definition: ApiMain.php:1551
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:1312
getModule()
Get the API module object.
Definition: ApiMain.php:363
error also a ContextSource you ll probably need to make sure the header is varied on $request
Definition: hooks.txt:2573
static appendDebugInfoToApiResult(IContextSource $context, ApiResult $result)
Append the debug info to given ApiResult.
Definition: MWDebug.php:483
$mSquidMaxage
Definition: ApiMain.php:148
$mParamsUsed
Definition: ApiMain.php:154
reportUnusedParams()
Report unused parameters, so the client gets a hint in case it gave us parameters we don't know...
Definition: ApiMain.php:1623
wfClearOutputBuffers()
More legible than passing a 'false' parameter to wfResetOutputBuffers():
null array $mExtraData
Definition: ApiMain.php:1867
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:1585
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
MediaWiki Logger LoggerFactory implements a PSR[0] compatible message logging system Named Psr Log LoggerInterface instances can be obtained from the MediaWiki Logger LoggerFactory::getInstance() static method.MediaWiki\Logger\LoggerFactory expects a class implementing the MediaWiki\Logger\Spi interface to act as a factory for new Psr\Log\LoggerInterface instances.The"Spi"in MediaWiki\Logger\Spi stands for"service provider interface".An SPI is an API intended to be implemented or extended by a third party.This software design pattern is intended to enable framework extension and replaceable components.It is specifically used in the MediaWiki\Logger\LoggerFactory service to allow alternate PSR-3 logging implementations to be easily integrated with MediaWiki.The service provider interface allows the backend logging library to be implemented in multiple ways.The $wgMWLoggerDefaultSpi global provides the classname of the default MediaWiki\Logger\Spi implementation to be loaded at runtime.This can either be the name of a class implementing the MediaWiki\Logger\Spi with a zero argument const ructor or a callable that will return an MediaWiki\Logger\Spi instance.Alternately the MediaWiki\Logger\LoggerFactory MediaWiki Logger LoggerFactory
Definition: logger.txt:5
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:372
checkAsserts($params)
Check asserts of the user's rights.
Definition: ApiMain.php:1349
parseMsg($error)
Return the error message related to a certain array.
Definition: ApiBase.php:2253
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:1602
logFeatureUsage($feature)
Write logging information for API features to a debug log, for usage analysis.
Definition: ApiBase.php:2304
sendCacheHeaders($isError)
Send caching headers.
Definition: ApiMain.php:826
getVal($name, $default=null)
Get a request value, and register the fact that it was used, for logging.
Definition: ApiMain.php:1579
__construct($message, $codestr, $code=0, $extradata=null)
Definition: ApiMain.php:1875
static element($element, $attribs=[], $contents= '')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
Definition: Html.php:229
getUser()
Get the User object.
$mInternalMode
Definition: ApiMain.php:148
substituteResultWithError($e)
Replace the result data with the information about an exception.
Definition: ApiMain.php:997
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:2203
see documentation in includes Linker php for Linker::makeImageLink & $time
Definition: hooks.txt:1749
$mModuleMgr
Definition: ApiMain.php:143
static getGroupsWithPermission($role)
Get all the groups who have a given permission.
Definition: User.php:4602
execute()
Execute api request.
Definition: ApiMain.php:477
This exception will be thrown when dieUsage is called to stop module execution.
Definition: ApiMain.php:1860
getResult()
Get the ApiResult object associated with current request.
Definition: ApiMain.php:282
checkExecutePermissions($module)
Check for sufficient permissions to execute.
Definition: ApiMain.php:1262
createErrorPrinter()
Create the printer for error output.
Definition: ApiMain.php:944
$wgUser
Definition: Setup.php:806
isWriteMode()
Indicates whether this module requires write mode.
Definition: ApiBase.php:371
ApiContinuationManager null $mContinuationManager
Definition: ApiMain.php:145
setContinuationManager($manager)
Set the continuation manager.
Definition: ApiMain.php:341
getOutput()
Get the OutputPage object.
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:300
handleException(Exception $e)
Handle an exception as an API response.
Definition: ApiMain.php:544