MediaWiki  1.23.12
ApiMain.php
Go to the documentation of this file.
1 <?php
41 class ApiMain extends ApiBase {
45  const API_DEFAULT_FORMAT = 'xmlfm';
46 
50  private static $Modules = array(
51  'login' => 'ApiLogin',
52  'logout' => 'ApiLogout',
53  'createaccount' => 'ApiCreateAccount',
54  'query' => 'ApiQuery',
55  'expandtemplates' => 'ApiExpandTemplates',
56  'parse' => 'ApiParse',
57  'opensearch' => 'ApiOpenSearch',
58  'feedcontributions' => 'ApiFeedContributions',
59  'feedrecentchanges' => 'ApiFeedRecentChanges',
60  'feedwatchlist' => 'ApiFeedWatchlist',
61  'help' => 'ApiHelp',
62  'paraminfo' => 'ApiParamInfo',
63  'rsd' => 'ApiRsd',
64  'compare' => 'ApiComparePages',
65  'tokens' => 'ApiTokens',
66 
67  // Write modules
68  'purge' => 'ApiPurge',
69  'setnotificationtimestamp' => 'ApiSetNotificationTimestamp',
70  'rollback' => 'ApiRollback',
71  'delete' => 'ApiDelete',
72  'undelete' => 'ApiUndelete',
73  'protect' => 'ApiProtect',
74  'block' => 'ApiBlock',
75  'unblock' => 'ApiUnblock',
76  'move' => 'ApiMove',
77  'edit' => 'ApiEditPage',
78  'upload' => 'ApiUpload',
79  'filerevert' => 'ApiFileRevert',
80  'emailuser' => 'ApiEmailUser',
81  'watch' => 'ApiWatch',
82  'patrol' => 'ApiPatrol',
83  'import' => 'ApiImport',
84  'userrights' => 'ApiUserrights',
85  'options' => 'ApiOptions',
86  'imagerotate' => 'ApiImageRotate',
87  'revisiondelete' => 'ApiRevisionDelete',
88  );
89 
93  private static $Formats = array(
94  'json' => 'ApiFormatJson',
95  'jsonfm' => 'ApiFormatJson',
96  'php' => 'ApiFormatPhp',
97  'phpfm' => 'ApiFormatPhp',
98  'wddx' => 'ApiFormatWddx',
99  'wddxfm' => 'ApiFormatWddx',
100  'xml' => 'ApiFormatXml',
101  'xmlfm' => 'ApiFormatXml',
102  'yaml' => 'ApiFormatYaml',
103  'yamlfm' => 'ApiFormatYaml',
104  'rawfm' => 'ApiFormatJson',
105  'txt' => 'ApiFormatTxt',
106  'txtfm' => 'ApiFormatTxt',
107  'dbg' => 'ApiFormatDbg',
108  'dbgfm' => 'ApiFormatDbg',
109  'dump' => 'ApiFormatDump',
110  'dumpfm' => 'ApiFormatDump',
111  'none' => 'ApiFormatNone',
112  );
113 
114  // @codingStandardsIgnoreStart String contenation on "msg" not allowed to break long line
121  private static $mRights = array(
122  'writeapi' => array(
123  'msg' => 'Use of the write API',
124  'params' => array()
125  ),
126  'apihighlimits' => array(
127  'msg' => 'Use higher limits in API queries (Slow queries: $1 results; Fast queries: $2 results). The limits for slow queries also apply to multivalue parameters.',
129  )
130  );
131  // @codingStandardsIgnoreEnd
132 
136  private $mPrinter;
137 
139  private $mAction;
140  private $mEnableWrite;
142 
143  private $mCacheMode = 'private';
144  private $mCacheControl = array();
145  private $mParamsUsed = array();
146 
154  public function __construct( $context = null, $enableWrite = false ) {
155  if ( $context === null ) {
157  } elseif ( $context instanceof WebRequest ) {
158  // BC for pre-1.19
159  $request = $context;
161  }
162  // We set a derivative context so we can change stuff later
163  $this->setContext( new DerivativeContext( $context ) );
164 
165  if ( isset( $request ) ) {
166  $this->getContext()->setRequest( $request );
167  }
168 
169  $this->mInternalMode = ( $this->getRequest() instanceof FauxRequest );
170 
171  // Special handling for the main module: $parent === $this
172  parent::__construct( $this, $this->mInternalMode ? 'main_int' : 'main' );
173 
174  if ( !$this->mInternalMode ) {
175  // Impose module restrictions.
176  // If the current user cannot read,
177  // Remove all modules other than login
178  global $wgUser;
179 
180  if ( $this->getVal( 'callback' ) !== null ) {
181  // JSON callback allows cross-site reads.
182  // For safety, strip user credentials.
183  wfDebug( "API: stripping user credentials for JSON callback\n" );
184  $wgUser = new User();
185  $this->getContext()->setUser( $wgUser );
186  }
187  }
188 
189  global $wgAPIModules, $wgAPIFormatModules;
190  $this->mModuleMgr = new ApiModuleManager( $this );
191  $this->mModuleMgr->addModules( self::$Modules, 'action' );
192  $this->mModuleMgr->addModules( $wgAPIModules, 'action' );
193  $this->mModuleMgr->addModules( self::$Formats, 'format' );
194  $this->mModuleMgr->addModules( $wgAPIFormatModules, 'format' );
195 
196  $this->mResult = new ApiResult( $this );
197  $this->mEnableWrite = $enableWrite;
198 
199  $this->mSquidMaxage = -1; // flag for executeActionWithErrorHandling()
200  $this->mCommit = false;
201  }
202 
207  public function isInternalMode() {
208  return $this->mInternalMode;
209  }
210 
216  public function getResult() {
217  return $this->mResult;
218  }
219 
225  public function getModule() {
226  return $this->mModule;
227  }
228 
234  public function getPrinter() {
235  return $this->mPrinter;
236  }
237 
243  public function setCacheMaxAge( $maxage ) {
244  $this->setCacheControl( array(
245  'max-age' => $maxage,
246  's-maxage' => $maxage
247  ) );
248  }
249 
275  public function setCacheMode( $mode ) {
276  if ( !in_array( $mode, array( 'private', 'public', 'anon-public-user-private' ) ) ) {
277  wfDebug( __METHOD__ . ": unrecognised cache mode \"$mode\"\n" );
278 
279  // Ignore for forwards-compatibility
280  return;
281  }
282 
283  if ( !User::isEveryoneAllowed( 'read' ) ) {
284  // Private wiki, only private headers
285  if ( $mode !== 'private' ) {
286  wfDebug( __METHOD__ . ": ignoring request for $mode cache mode, private wiki\n" );
287 
288  return;
289  }
290  }
291 
292  wfDebug( __METHOD__ . ": setting cache mode $mode\n" );
293  $this->mCacheMode = $mode;
294  }
295 
306  public function setCacheControl( $directives ) {
307  $this->mCacheControl = $directives + $this->mCacheControl;
308  }
309 
317  public function createPrinterByName( $format ) {
318  $printer = $this->mModuleMgr->getModule( $format, 'format' );
319  if ( $printer === null ) {
320  $this->dieUsage( "Unrecognized format: {$format}", 'unknown_format' );
321  }
322 
323  return $printer;
324  }
325 
329  public function execute() {
330  $this->profileIn();
331  if ( $this->mInternalMode ) {
332  $this->executeAction();
333  } else {
335  }
336 
337  $this->profileOut();
338  }
339 
344  protected function executeActionWithErrorHandling() {
345  // Verify the CORS header before executing the action
346  if ( !$this->handleCORS() ) {
347  // handleCORS() has sent a 403, abort
348  return;
349  }
350 
351  // Exit here if the request method was OPTIONS
352  // (assume there will be a followup GET or POST)
353  if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
354  return;
355  }
356 
357  // In case an error occurs during data output,
358  // clear the output buffer and print just the error information
359  ob_start();
360 
361  $t = microtime( true );
362  try {
363  $this->executeAction();
364  } catch ( Exception $e ) {
365  $this->handleException( $e );
366  }
367 
368  // Log the request whether or not there was an error
369  $this->logRequest( microtime( true ) - $t );
370 
371  // Send cache headers after any code which might generate an error, to
372  // avoid sending public cache headers for errors.
373  $this->sendCacheHeaders();
374 
375  if ( $this->mPrinter->getIsHtml() && !$this->mPrinter->isDisabled() ) {
376  echo wfReportTime();
377  }
378 
379  ob_end_flush();
380  }
381 
388  protected function handleException( Exception $e ) {
389  // Bug 63145: Rollback any open database transactions
390  if ( !( $e instanceof UsageException ) ) {
391  // UsageExceptions are intentional, so don't rollback if that's the case
393  }
394 
395  // Allow extra cleanup and logging
396  wfRunHooks( 'ApiMain::onException', array( $this, $e ) );
397 
398  // Log it
399  if ( !( $e instanceof UsageException ) ) {
401  }
402 
403  // Handle any kind of exception by outputting properly formatted error message.
404  // If this fails, an unhandled exception should be thrown so that global error
405  // handler will process and log it.
406 
407  $errCode = $this->substituteResultWithError( $e );
408 
409  // Error results should not be cached
410  $this->setCacheMode( 'private' );
411 
412  $response = $this->getRequest()->response();
413  $headerStr = 'MediaWiki-API-Error: ' . $errCode;
414  if ( $e->getCode() === 0 ) {
415  $response->header( $headerStr );
416  } else {
417  $response->header( $headerStr, true, $e->getCode() );
418  }
419 
420  // Reset and print just the error message
421  ob_clean();
422 
423  // If the error occurred during printing, do a printer->profileOut()
424  $this->mPrinter->safeProfileOut();
425  $this->printResult( true );
426  }
427 
437  public static function handleApiBeforeMainException( Exception $e ) {
438  ob_start();
439 
440  try {
441  $main = new self( RequestContext::getMain(), false );
442  $main->handleException( $e );
443  } catch ( Exception $e2 ) {
444  // Nope, even that didn't work. Punt.
445  throw $e;
446  }
447 
448  // Log the request and reset cache headers
449  $main->logRequest( 0 );
450  $main->sendCacheHeaders();
451 
452  ob_end_flush();
453  }
454 
467  protected function handleCORS() {
468  global $wgCrossSiteAJAXdomains, $wgCrossSiteAJAXdomainExceptions;
469 
470  $originParam = $this->getParameter( 'origin' ); // defaults to null
471  if ( $originParam === null ) {
472  // No origin parameter, nothing to do
473  return true;
474  }
475 
476  $request = $this->getRequest();
477  $response = $request->response();
478  // Origin: header is a space-separated list of origins, check all of them
479  $originHeader = $request->getHeader( 'Origin' );
480  if ( $originHeader === false ) {
481  $origins = array();
482  } else {
483  $origins = explode( ' ', $originHeader );
484  }
485 
486  if ( !in_array( $originParam, $origins ) ) {
487  // origin parameter set but incorrect
488  // Send a 403 response
489  $message = HttpStatus::getMessage( 403 );
490  $response->header( "HTTP/1.1 403 $message", true, 403 );
491  $response->header( 'Cache-Control: no-cache' );
492  echo "'origin' parameter does not match Origin header\n";
493 
494  return false;
495  }
496 
497  $matchOrigin = self::matchOrigin(
498  $originParam,
499  $wgCrossSiteAJAXdomains,
500  $wgCrossSiteAJAXdomainExceptions
501  );
502 
503  if ( $matchOrigin ) {
504  $response->header( "Access-Control-Allow-Origin: $originParam" );
505  $response->header( 'Access-Control-Allow-Credentials: true' );
506  $this->getOutput()->addVaryHeader( 'Origin' );
507  }
508 
509  return true;
510  }
511 
520  protected static function matchOrigin( $value, $rules, $exceptions ) {
521  foreach ( $rules as $rule ) {
522  if ( preg_match( self::wildcardToRegex( $rule ), $value ) ) {
523  // Rule matches, check exceptions
524  foreach ( $exceptions as $exc ) {
525  if ( preg_match( self::wildcardToRegex( $exc ), $value ) ) {
526  return false;
527  }
528  }
529 
530  return true;
531  }
532  }
533 
534  return false;
535  }
536 
545  protected static function wildcardToRegex( $wildcard ) {
546  $wildcard = preg_quote( $wildcard, '/' );
547  $wildcard = str_replace(
548  array( '\*', '\?' ),
549  array( '.*?', '.' ),
550  $wildcard
551  );
552 
553  return "/^https?:\/\/$wildcard$/";
554  }
555 
556  protected function sendCacheHeaders() {
557  global $wgUseXVO, $wgVaryOnXFP;
558  $response = $this->getRequest()->response();
559  $out = $this->getOutput();
560 
561  if ( $wgVaryOnXFP ) {
562  $out->addVaryHeader( 'X-Forwarded-Proto' );
563  }
564 
565  if ( $this->mCacheMode == 'private' ) {
566  $response->header( 'Cache-Control: private' );
567 
568  return;
569  }
570 
571  if ( $this->mCacheMode == 'anon-public-user-private' ) {
572  $out->addVaryHeader( 'Cookie' );
573  $response->header( $out->getVaryHeader() );
574  if ( $wgUseXVO ) {
575  $response->header( $out->getXVO() );
576  if ( $out->haveCacheVaryCookies() ) {
577  // Logged in, mark this request private
578  $response->header( 'Cache-Control: private' );
579 
580  return;
581  }
582  // Logged out, send normal public headers below
583  } elseif ( session_id() != '' ) {
584  // Logged in or otherwise has session (e.g. anonymous users who have edited)
585  // Mark request private
586  $response->header( 'Cache-Control: private' );
587 
588  return;
589  } // else no XVO and anonymous, send public headers below
590  }
591 
592  // Send public headers
593  $response->header( $out->getVaryHeader() );
594  if ( $wgUseXVO ) {
595  $response->header( $out->getXVO() );
596  }
597 
598  // If nobody called setCacheMaxAge(), use the (s)maxage parameters
599  if ( !isset( $this->mCacheControl['s-maxage'] ) ) {
600  $this->mCacheControl['s-maxage'] = $this->getParameter( 'smaxage' );
601  }
602  if ( !isset( $this->mCacheControl['max-age'] ) ) {
603  $this->mCacheControl['max-age'] = $this->getParameter( 'maxage' );
604  }
605 
606  if ( !$this->mCacheControl['s-maxage'] && !$this->mCacheControl['max-age'] ) {
607  // Public cache not requested
608  // Sending a Vary header in this case is harmless, and protects us
609  // against conditional calls of setCacheMaxAge().
610  $response->header( 'Cache-Control: private' );
611 
612  return;
613  }
614 
615  $this->mCacheControl['public'] = true;
616 
617  // Send an Expires header
618  $maxAge = min( $this->mCacheControl['s-maxage'], $this->mCacheControl['max-age'] );
619  $expiryUnixTime = ( $maxAge == 0 ? 1 : time() + $maxAge );
620  $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822, $expiryUnixTime ) );
621 
622  // Construct the Cache-Control header
623  $ccHeader = '';
624  $separator = '';
625  foreach ( $this->mCacheControl as $name => $value ) {
626  if ( is_bool( $value ) ) {
627  if ( $value ) {
628  $ccHeader .= $separator . $name;
629  $separator = ', ';
630  }
631  } else {
632  $ccHeader .= $separator . "$name=$value";
633  $separator = ', ';
634  }
635  }
636 
637  $response->header( "Cache-Control: $ccHeader" );
638  }
639 
646  protected function substituteResultWithError( $e ) {
647  global $wgShowHostnames;
648 
649  $result = $this->getResult();
650 
651  // Printer may not be initialized if the extractRequestParams() fails for the main module
652  if ( !isset( $this->mPrinter ) ) {
653  // The printer has not been created yet. Try to manually get formatter value.
654  $value = $this->getRequest()->getVal( 'format', self::API_DEFAULT_FORMAT );
655  if ( !$this->mModuleMgr->isDefined( $value, 'format' ) ) {
657  }
658 
659  $this->mPrinter = $this->createPrinterByName( $value );
660  }
661 
662  // Printer may not be able to handle errors. This is particularly
663  // likely if the module returns something for getCustomPrinter().
664  if ( !$this->mPrinter->canPrintErrors() ) {
665  $this->mPrinter->safeProfileOut();
666  $this->mPrinter = $this->createPrinterByName( self::API_DEFAULT_FORMAT );
667  }
668 
669  // Update raw mode flag for the selected printer.
670  $result->setRawMode( $this->mPrinter->getNeedsRawData() );
671 
672  if ( $e instanceof UsageException ) {
673  // User entered incorrect parameters - print usage screen
674  $errMessage = $e->getMessageArray();
675 
676  // Only print the help message when this is for the developer, not runtime
677  if ( $this->mPrinter->getWantsHelp() || $this->mAction == 'help' ) {
678  ApiResult::setContent( $errMessage, $this->makeHelpMsg() );
679  }
680  } else {
681  global $wgShowSQLErrors, $wgShowExceptionDetails;
682  // Something is seriously wrong
683  if ( ( $e instanceof DBQueryError ) && !$wgShowSQLErrors ) {
684  $info = 'Database query error';
685  } else {
686  $info = "Exception Caught: {$e->getMessage()}";
687  }
688 
689  $errMessage = array(
690  'code' => 'internal_api_error_' . get_class( $e ),
691  'info' => $info,
692  );
694  $errMessage,
695  $wgShowExceptionDetails ? "\n\n{$e->getTraceAsString()}\n\n" : ''
696  );
697  }
698 
699  // Remember all the warnings to re-add them later
700  $oldResult = $result->getData();
701  $warnings = isset( $oldResult['warnings'] ) ? $oldResult['warnings'] : null;
702 
703  $result->reset();
704  $result->disableSizeCheck();
705  // Re-add the id
706  $requestid = $this->getParameter( 'requestid' );
707  if ( !is_null( $requestid ) ) {
708  $result->addValue( null, 'requestid', $requestid );
709  }
710  if ( $wgShowHostnames ) {
711  // servedby is especially useful when debugging errors
712  $result->addValue( null, 'servedby', wfHostName() );
713  }
714  if ( $warnings !== null ) {
715  $result->addValue( null, 'warnings', $warnings );
716  }
717 
718  $result->addValue( null, 'error', $errMessage );
719 
720  return $errMessage['code'];
721  }
722 
727  protected function setupExecuteAction() {
728  global $wgShowHostnames;
729 
730  // First add the id to the top element
731  $result = $this->getResult();
732  $requestid = $this->getParameter( 'requestid' );
733  if ( !is_null( $requestid ) ) {
734  $result->addValue( null, 'requestid', $requestid );
735  }
736 
737  if ( $wgShowHostnames ) {
738  $servedby = $this->getParameter( 'servedby' );
739  if ( $servedby ) {
740  $result->addValue( null, 'servedby', wfHostName() );
741  }
742  }
743 
744  $params = $this->extractRequestParams();
745 
746  $this->mAction = $params['action'];
747 
748  if ( !is_string( $this->mAction ) ) {
749  $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
750  }
751 
752  return $params;
753  }
754 
759  protected function setupModule() {
760  // Instantiate the module requested by the user
761  $module = $this->mModuleMgr->getModule( $this->mAction, 'action' );
762  if ( $module === null ) {
763  $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
764  }
765  $moduleParams = $module->extractRequestParams();
766 
767  // Die if token required, but not provided
768  $salt = $module->getTokenSalt();
769  if ( $salt !== false ) {
770  if ( !isset( $moduleParams['token'] ) ) {
771  $this->dieUsageMsg( array( 'missingparam', 'token' ) );
772  }
773 
774  if ( !$this->getUser()->matchEditToken(
775  $moduleParams['token'],
776  $salt,
777  $this->getContext()->getRequest() )
778  ) {
779  $this->dieUsageMsg( 'sessionfailure' );
780  }
781  }
782 
783  return $module;
784  }
785 
792  protected function checkMaxLag( $module, $params ) {
793  if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
794  // Check for maxlag
795  global $wgShowHostnames;
796  $maxLag = $params['maxlag'];
797  list( $host, $lag ) = wfGetLB()->getMaxLag();
798  if ( $lag > $maxLag ) {
799  $response = $this->getRequest()->response();
800 
801  $response->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
802  $response->header( 'X-Database-Lag: ' . intval( $lag ) );
803 
804  if ( $wgShowHostnames ) {
805  $this->dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
806  }
807 
808  $this->dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
809  }
810  }
811 
812  return true;
813  }
814 
819  protected function checkExecutePermissions( $module ) {
820  $user = $this->getUser();
821  if ( $module->isReadMode() && !User::isEveryoneAllowed( 'read' ) &&
822  !$user->isAllowed( 'read' )
823  ) {
824  $this->dieUsageMsg( 'readrequired' );
825  }
826  if ( $module->isWriteMode() ) {
827  if ( !$this->mEnableWrite ) {
828  $this->dieUsageMsg( 'writedisabled' );
829  }
830  if ( !$user->isAllowed( 'writeapi' ) ) {
831  $this->dieUsageMsg( 'writerequired' );
832  }
833  if ( wfReadOnly() ) {
834  $this->dieReadOnly();
835  }
836  }
837 
838  // Allow extensions to stop execution for arbitrary reasons.
839  $message = false;
840  if ( !wfRunHooks( 'ApiCheckCanExecute', array( $module, $user, &$message ) ) ) {
841  $this->dieUsageMsg( $message );
842  }
843  }
844 
849  protected function checkAsserts( $params ) {
850  if ( isset( $params['assert'] ) ) {
851  $user = $this->getUser();
852  switch ( $params['assert'] ) {
853  case 'user':
854  if ( $user->isAnon() ) {
855  $this->dieUsage( 'Assertion that the user is logged in failed', 'assertuserfailed' );
856  }
857  break;
858  case 'bot':
859  if ( !$user->isAllowed( 'bot' ) ) {
860  $this->dieUsage( 'Assertion that the user has the bot right failed', 'assertbotfailed' );
861  }
862  break;
863  }
864  }
865  }
866 
872  protected function setupExternalResponse( $module, $params ) {
873  if ( !$this->getRequest()->wasPosted() && $module->mustBePosted() ) {
874  // Module requires POST. GET request might still be allowed
875  // if $wgDebugApi is true, otherwise fail.
876  $this->dieUsageMsgOrDebug( array( 'mustbeposted', $this->mAction ) );
877  }
878 
879  // See if custom printer is used
880  $this->mPrinter = $module->getCustomPrinter();
881  if ( is_null( $this->mPrinter ) ) {
882  // Create an appropriate printer
883  $this->mPrinter = $this->createPrinterByName( $params['format'] );
884  }
885 
886  if ( $this->mPrinter->getNeedsRawData() ) {
887  $this->getResult()->setRawMode();
888  }
889  }
890 
894  protected function executeAction() {
895  $params = $this->setupExecuteAction();
896  $module = $this->setupModule();
897  $this->mModule = $module;
898 
899  $this->checkExecutePermissions( $module );
900 
901  if ( !$this->checkMaxLag( $module, $params ) ) {
902  return;
903  }
904 
905  if ( !$this->mInternalMode ) {
906  $this->setupExternalResponse( $module, $params );
907  }
908 
909  $this->checkAsserts( $params );
910 
911  // Execute
912  $module->profileIn();
913  $module->execute();
914  wfRunHooks( 'APIAfterExecute', array( &$module ) );
915  $module->profileOut();
916 
917  $this->reportUnusedParams();
918 
919  if ( !$this->mInternalMode ) {
920  //append Debug information
922 
923  // Print result data
924  $this->printResult( false );
925  }
926  }
927 
932  protected function logRequest( $time ) {
933  $request = $this->getRequest();
934  $milliseconds = $time === null ? '?' : round( $time * 1000 );
935  $s = 'API' .
936  ' ' . $request->getMethod() .
937  ' ' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
938  ' ' . $request->getIP() .
939  ' T=' . $milliseconds . 'ms';
940  foreach ( $this->getParamsUsed() as $name ) {
941  $value = $request->getVal( $name );
942  if ( $value === null ) {
943  continue;
944  }
945  $s .= ' ' . $name . '=';
946  if ( strlen( $value ) > 256 ) {
947  $encValue = $this->encodeRequestLogValue( substr( $value, 0, 256 ) );
948  $s .= $encValue . '[...]';
949  } else {
950  $s .= $this->encodeRequestLogValue( $value );
951  }
952  }
953  $s .= "\n";
954  wfDebugLog( 'api', $s, 'private' );
955  }
956 
960  protected function encodeRequestLogValue( $s ) {
961  static $table;
962  if ( !$table ) {
963  $chars = ';@$!*(),/:';
964  $numChars = strlen( $chars );
965  for ( $i = 0; $i < $numChars; $i++ ) {
966  $table[rawurlencode( $chars[$i] )] = $chars[$i];
967  }
968  }
969 
970  return strtr( rawurlencode( $s ), $table );
971  }
972 
976  protected function getParamsUsed() {
977  return array_keys( $this->mParamsUsed );
978  }
979 
983  public function getVal( $name, $default = null ) {
984  $this->mParamsUsed[$name] = true;
985 
986  return $this->getRequest()->getVal( $name, $default );
987  }
988 
993  public function getCheck( $name ) {
994  $this->mParamsUsed[$name] = true;
995 
996  return $this->getRequest()->getCheck( $name );
997  }
998 
1006  public function getUpload( $name ) {
1007  $this->mParamsUsed[$name] = true;
1008 
1009  return $this->getRequest()->getUpload( $name );
1010  }
1011 
1016  protected function reportUnusedParams() {
1017  $paramsUsed = $this->getParamsUsed();
1018  $allParams = $this->getRequest()->getValueNames();
1019 
1020  if ( !$this->mInternalMode ) {
1021  // Printer has not yet executed; don't warn that its parameters are unused
1022  $printerParams = array_map(
1023  array( $this->mPrinter, 'encodeParamName' ),
1024  array_keys( $this->mPrinter->getFinalParams() ?: array() )
1025  );
1026  $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1027  } else {
1028  $unusedParams = array_diff( $allParams, $paramsUsed );
1029  }
1030 
1031  if ( count( $unusedParams ) ) {
1032  $s = count( $unusedParams ) > 1 ? 's' : '';
1033  $this->setWarning( "Unrecognized parameter$s: '" . implode( $unusedParams, "', '" ) . "'" );
1034  }
1035  }
1036 
1042  protected function printResult( $isError ) {
1043  global $wgDebugAPI;
1044  if ( $wgDebugAPI !== false ) {
1045  $this->setWarning( 'SECURITY WARNING: $wgDebugAPI is enabled' );
1046  }
1047 
1048  $this->getResult()->cleanUpUTF8();
1049  $printer = $this->mPrinter;
1050  $printer->profileIn();
1051 
1057  $isHelp = $isError || $this->mAction == 'help';
1058  $printer->setUnescapeAmps( $isHelp && $printer->getFormat() == 'XML' && $printer->getIsHtml() );
1059 
1060  $printer->initPrinter( $isHelp );
1061 
1062  $printer->execute();
1063  $printer->closePrinter();
1064  $printer->profileOut();
1065  }
1066 
1070  public function isReadMode() {
1071  return false;
1072  }
1073 
1079  public function getAllowedParams() {
1080  return array(
1081  'format' => array(
1083  ApiBase::PARAM_TYPE => $this->mModuleMgr->getNames( 'format' )
1084  ),
1085  'action' => array(
1086  ApiBase::PARAM_DFLT => 'help',
1087  ApiBase::PARAM_TYPE => $this->mModuleMgr->getNames( 'action' )
1088  ),
1089  'maxlag' => array(
1090  ApiBase::PARAM_TYPE => 'integer'
1091  ),
1092  'smaxage' => array(
1093  ApiBase::PARAM_TYPE => 'integer',
1094  ApiBase::PARAM_DFLT => 0
1095  ),
1096  'maxage' => array(
1097  ApiBase::PARAM_TYPE => 'integer',
1098  ApiBase::PARAM_DFLT => 0
1099  ),
1100  'assert' => array(
1101  ApiBase::PARAM_TYPE => array( 'user', 'bot' )
1102  ),
1103  'requestid' => null,
1104  'servedby' => false,
1105  'origin' => null,
1106  );
1107  }
1108 
1114  public function getParamDescription() {
1115  return array(
1116  'format' => 'The format of the output',
1117  'action' => 'What action you would like to perform. See below for module help',
1118  'maxlag' => array(
1119  'Maximum lag can be used when MediaWiki is installed on a database replicated cluster.',
1120  'To save actions causing any more site replication lag, this parameter can make the client',
1121  'wait until the replication lag is less than the specified value.',
1122  'In case of a replag error, error code "maxlag" is returned, with the message like',
1123  '"Waiting for $host: $lag seconds lagged\n".',
1124  'See https://www.mediawiki.org/wiki/Manual:Maxlag_parameter for more information',
1125  ),
1126  'smaxage' => 'Set the s-maxage header to this many seconds. Errors are never cached',
1127  'maxage' => 'Set the max-age header to this many seconds. Errors are never cached',
1128  'assert' => 'Verify the user is logged in if set to "user", or has the bot userright if "bot"',
1129  'requestid' => 'Request ID to distinguish requests. This will just be output back to you',
1130  'servedby' => 'Include the hostname that served the request in the ' .
1131  'results. Unconditionally shown on error',
1132  'origin' => array(
1133  'When accessing the API using a cross-domain AJAX request (CORS), set this to the',
1134  'originating domain. This must be included in any pre-flight request, and',
1135  'therefore must be part of the request URI (not the POST body). This must match',
1136  'one of the origins in the Origin: header exactly, so it has to be set to ',
1137  'something like http://en.wikipedia.org or https://meta.wikimedia.org . If this',
1138  'parameter does not match the Origin: header, a 403 response will be returned. If',
1139  'this parameter matches the Origin: header and the origin is whitelisted, an',
1140  'Access-Control-Allow-Origin header will be set.',
1141  ),
1142  );
1143  }
1144 
1150  public function getDescription() {
1151  return array(
1152  '',
1153  '',
1154  '**********************************************************************************************',
1155  '** **',
1156  '** This is an auto-generated MediaWiki API documentation page **',
1157  '** **',
1158  '** Documentation and Examples: **',
1159  '** https://www.mediawiki.org/wiki/API **',
1160  '** **',
1161  '**********************************************************************************************',
1162  '',
1163  'Status: All features shown on this page should be working, but the API',
1164  ' is still in active development, and may change at any time.',
1165  ' Make sure to monitor our mailing list for any updates.',
1166  '',
1167  'Erroneous requests: When erroneous requests are sent to the API, a HTTP header will be sent',
1168  ' with the key "MediaWiki-API-Error" and then both the value of the',
1169  ' header and the error code sent back will be set to the same value.',
1170  '',
1171  ' In the case of an invalid action being passed, these will have a value',
1172  ' of "unknown_action".',
1173  '',
1174  ' For more information see https://www.mediawiki.org' .
1175  '/wiki/API:Errors_and_warnings',
1176  '',
1177  'Documentation: https://www.mediawiki.org/wiki/API:Main_page',
1178  'FAQ https://www.mediawiki.org/wiki/API:FAQ',
1179  'Mailing list: https://lists.wikimedia.org/mailman/listinfo/mediawiki-api',
1180  'Api Announcements: https://lists.wikimedia.org/mailman/listinfo/mediawiki-api-announce',
1181  'Bugs & Requests: https://bugzilla.wikimedia.org/buglist.cgi?component=API&' .
1182  'bug_status=NEW&bug_status=ASSIGNED&bug_status=REOPENED&order=bugs.delta_ts',
1183  '',
1184  '',
1185  '',
1186  '',
1187  '',
1188  );
1189  }
1190 
1194  public function getPossibleErrors() {
1195  return array_merge( parent::getPossibleErrors(), array(
1196  array( 'readonlytext' ),
1197  array( 'code' => 'unknown_format', 'info' => 'Unrecognized format: format' ),
1198  array( 'code' => 'unknown_action', 'info' => 'The API requires a valid action parameter' ),
1199  array( 'code' => 'maxlag', 'info' => 'Waiting for host: x seconds lagged' ),
1200  array( 'code' => 'maxlag', 'info' => 'Waiting for a database server: x seconds lagged' ),
1201  array( 'code' => 'assertuserfailed', 'info' => 'Assertion that the user is logged in failed' ),
1202  array(
1203  'code' => 'assertbotfailed',
1204  'info' => 'Assertion that the user has the bot right failed'
1205  ),
1206  ) );
1207  }
1208 
1213  protected function getCredits() {
1214  return array(
1215  'API developers:',
1216  ' Roan Kattouw (lead developer Sep 2007-2009)',
1217  ' Victor Vasiliev',
1218  ' Bryan Tong Minh',
1219  ' Sam Reed',
1220  ' Yuri Astrakhan (creator, lead developer Sep 2006-Sep 2007, 2012-present)',
1221  '',
1222  'Please send your comments, suggestions and questions to mediawiki-api@lists.wikimedia.org',
1223  'or file a bug report at https://bugzilla.wikimedia.org/'
1224  );
1225  }
1226 
1232  public function setHelp( $help = true ) {
1233  $this->mPrinter->setHelp( $help );
1234  }
1235 
1241  public function makeHelpMsg() {
1242  global $wgMemc, $wgAPICacheHelpTimeout;
1243  $this->setHelp();
1244  // Get help text from cache if present
1245  $key = wfMemcKey( 'apihelp', $this->getModuleName(),
1246  str_replace( ' ', '_', SpecialVersion::getVersion( 'nodb' ) ) );
1247  if ( $wgAPICacheHelpTimeout > 0 ) {
1248  $cached = $wgMemc->get( $key );
1249  if ( $cached ) {
1250  return $cached;
1251  }
1252  }
1253  $retval = $this->reallyMakeHelpMsg();
1254  if ( $wgAPICacheHelpTimeout > 0 ) {
1255  $wgMemc->set( $key, $retval, $wgAPICacheHelpTimeout );
1256  }
1257 
1258  return $retval;
1259  }
1260 
1264  public function reallyMakeHelpMsg() {
1265  $this->setHelp();
1266 
1267  // Use parent to make default message for the main module
1268  $msg = parent::makeHelpMsg();
1269 
1270  $astriks = str_repeat( '*** ', 14 );
1271  $msg .= "\n\n$astriks Modules $astriks\n\n";
1272 
1273  foreach ( $this->mModuleMgr->getNames( 'action' ) as $name ) {
1274  $module = $this->mModuleMgr->getModule( $name );
1275  $msg .= self::makeHelpMsgHeader( $module, 'action' );
1276 
1277  $msg2 = $module->makeHelpMsg();
1278  if ( $msg2 !== false ) {
1279  $msg .= $msg2;
1280  }
1281  $msg .= "\n";
1282  }
1283 
1284  $msg .= "\n$astriks Permissions $astriks\n\n";
1285  foreach ( self::$mRights as $right => $rightMsg ) {
1287  $msg .= "* " . $right . " *\n " . wfMsgReplaceArgs( $rightMsg['msg'], $rightMsg['params'] ) .
1288  "\nGranted to:\n " . str_replace( '*', 'all', implode( ', ', $groups ) ) . "\n\n";
1289  }
1290 
1291  $msg .= "\n$astriks Formats $astriks\n\n";
1292  foreach ( $this->mModuleMgr->getNames( 'format' ) as $name ) {
1293  $module = $this->mModuleMgr->getModule( $name );
1294  $msg .= self::makeHelpMsgHeader( $module, 'format' );
1295  $msg2 = $module->makeHelpMsg();
1296  if ( $msg2 !== false ) {
1297  $msg .= $msg2;
1298  }
1299  $msg .= "\n";
1300  }
1301 
1302  $msg .= "\n*** Credits: ***\n " . implode( "\n ", $this->getCredits() ) . "\n";
1303 
1304  return $msg;
1305  }
1306 
1313  public static function makeHelpMsgHeader( $module, $paramName ) {
1314  $modulePrefix = $module->getModulePrefix();
1315  if ( strval( $modulePrefix ) !== '' ) {
1316  $modulePrefix = "($modulePrefix) ";
1317  }
1318 
1319  return "* $paramName={$module->getModuleName()} $modulePrefix*";
1320  }
1322  private $mCanApiHighLimits = null;
1323 
1328  public function canApiHighLimits() {
1329  if ( !isset( $this->mCanApiHighLimits ) ) {
1330  $this->mCanApiHighLimits = $this->getUser()->isAllowed( 'apihighlimits' );
1331  }
1332 
1333  return $this->mCanApiHighLimits;
1334  }
1335 
1341  public function getShowVersions() {
1342  wfDeprecated( __METHOD__, '1.21' );
1343 
1344  return false;
1345  }
1346 
1351  public function getModuleManager() {
1352  return $this->mModuleMgr;
1353  }
1354 
1364  protected function addModule( $name, $class ) {
1365  $this->getModuleManager()->addModule( $name, 'action', $class );
1366  }
1367 
1376  protected function addFormat( $name, $class ) {
1377  $this->getModuleManager()->addModule( $name, 'format', $class );
1378  }
1379 
1385  function getModules() {
1386  return $this->getModuleManager()->getNamesWithClasses( 'action' );
1387  }
1388 
1396  public function getFormats() {
1397  return $this->getModuleManager()->getNamesWithClasses( 'format' );
1398  }
1399 }
1400 
1407 class UsageException extends MWException {
1409  private $mCodestr;
1410 
1414  private $mExtraData;
1415 
1422  public function __construct( $message, $codestr, $code = 0, $extradata = null ) {
1423  parent::__construct( $message, $code );
1424  $this->mCodestr = $codestr;
1425  $this->mExtraData = $extradata;
1426  }
1427 
1431  public function getCodeString() {
1432  return $this->mCodestr;
1433  }
1434 
1438  public function getMessageArray() {
1439  $result = array(
1440  'code' => $this->mCodestr,
1441  'info' => $this->getMessage()
1442  );
1443  if ( is_array( $this->mExtraData ) ) {
1444  $result = array_merge( $result, $this->mExtraData );
1445  }
1446 
1447  return $result;
1448  }
1449 
1453  public function __toString() {
1454  return "{$this->getCodeString()}: {$this->getMessage()}";
1455  }
1456 }
ApiMain\getDescription
getDescription()
See ApiBase for description.
Definition: ApiMain.php:1149
ApiBase\dieUsageMsgOrDebug
dieUsageMsgOrDebug( $error)
Will only set a warning instead of failing if the global $wgDebugAPI is set to true.
Definition: ApiBase.php:1949
ApiMain\executeActionWithErrorHandling
executeActionWithErrorHandling()
Execute an action, and in case of an error, erase whatever partial results have been accumulated,...
Definition: ApiMain.php:343
ApiMain
This is the main API class, used for both external and internal processing.
Definition: ApiMain.php:41
ContextSource\$context
IContextSource $context
Definition: ContextSource.php:33
$wgUser
$wgUser
Definition: Setup.php:572
$result
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. $reader:XMLReader object $logInfo:Array of information Return false to stop further processing of the tag 'ImportHandlePageXMLTag':When parsing a XML tag in a page. $reader:XMLReader object $pageInfo:Array of information Return false to stop further processing of the tag 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information Return false to stop further processing of the tag 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. $reader:XMLReader object Return false to stop further processing of the tag 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. $reader:XMLReader object $revisionInfo:Array of information Return false to stop further processing of the tag '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 '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. '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 '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 '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 wfIsTrustedProxy() $ip:IP being check $result:Change this value to override the result of wfIsTrustedProxy() '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 User::isValidEmailAddr(), 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. '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 '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) '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. '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:1528
FauxRequest
WebRequest clone which takes values from a provided array.
Definition: WebRequest.php:1275
ContextSource\getContext
getContext()
Get the RequestContext object.
Definition: ContextSource.php:40
ApiMain\getCredits
getCredits()
Returns an array of strings with credits for the API.
Definition: ApiMain.php:1212
ApiMain\sendCacheHeaders
sendCacheHeaders()
Definition: ApiMain.php:555
ApiMain\$mAction
$mAction
Definition: ApiMain.php:138
php
skin txt MediaWiki includes four core it has been set as the default in MediaWiki since the replacing Monobook it had been been the default skin since before being replaced by Vector largely rewritten in while keeping its appearance Several legacy skins were removed in the as the burden of supporting them became too heavy to bear Those in etc for skin dependent CSS etc for skin dependent JavaScript These can also be customised on a per user by etc This feature has led to a wide variety of user styles becoming that gallery is a good place to ending in php
Definition: skin.txt:62
ApiMain\getModules
getModules()
Get the array mapping module names to class names.
Definition: ApiMain.php:1384
ApiMain\$mSquidMaxage
$mSquidMaxage
Definition: ApiMain.php:140
$response
$response
Definition: opensearch_desc.php:32
ApiMain\getParamsUsed
getParamsUsed()
Get the request parameters used in the course of the preceding execute() request.
Definition: ApiMain.php:975
ApiResult\setContent
static setContent(&$arr, $value, $subElemName=null)
Adds a content element to an array.
Definition: ApiResult.php:201
ApiMain\getVal
getVal( $name, $default=null)
Get a request value, and register the fact that it was used, for logging.
Definition: ApiMain.php:982
$wgMemc
globals will be eliminated from MediaWiki replaced by an application object which would be passed to constructors Whether that would be an convenient solution remains to be but certainly PHP makes such object oriented programming models easier than they were in previous versions For the time being MediaWiki programmers will have to work in an environment with some global context At the time of globals were initialised on startup by MediaWiki of these were configuration which are documented in DefaultSettings php There is no comprehensive documentation for the remaining however some of the most important ones are listed below They are typically initialised either in index php or in Setup php For a description of the see design txt $wgTitle Title object created from the request URL $wgOut OutputPage object for HTTP response $wgUser User object for the user associated with the current request $wgLang Language object selected by user preferences $wgContLang Language object associated with the wiki being viewed $wgParser Parser object Parser extensions register their hooks here $wgRequest WebRequest to get request data $wgMemc
Definition: globals.txt:25
wfGetLB
wfGetLB( $wiki=false)
Get a load balancer object.
Definition: GlobalFunctions.php:3716
ApiBase\dieUsageMsg
dieUsageMsg( $error)
Output the error message related to a certain array.
Definition: ApiBase.php:1933
ApiMain\$Modules
static $Modules
List of available modules: action name => module class.
Definition: ApiMain.php:50
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:2530
ApiBase\PARAM_TYPE
const PARAM_TYPE
Definition: ApiBase.php:50
ApiFormatBase
This is the abstract base class for API formatters.
Definition: ApiFormatBase.php:32
wfDebugLog
wfDebugLog( $logGroup, $text, $dest='all')
Send a line to a supplementary debug log file, if configured, or main debug log if not.
Definition: GlobalFunctions.php:1087
wfUrlencode
wfUrlencode( $s)
We want some things to be included as literal characters in our title URLs for prettiness,...
Definition: GlobalFunctions.php:377
ApiMain\isReadMode
isReadMode()
Definition: ApiMain.php:1069
ApiMain\handleCORS
handleCORS()
Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
Definition: ApiMain.php:466
$time
see documentation in includes Linker php for Linker::makeImageLink & $time
Definition: hooks.txt:1358
ApiMain\handleApiBeforeMainException
static handleApiBeforeMainException(Exception $e)
Handle an exception from the ApiBeforeMain hook.
Definition: ApiMain.php:436
$right
return false if a UserGetRights hook might remove the named right $right
Definition: hooks.txt:2803
ApiMain\getShowVersions
getShowVersions()
Check whether the user wants us to show version information in the API help.
Definition: ApiMain.php:1340
$params
$params
Definition: styleTest.css.php:40
UsageException\getMessageArray
getMessageArray()
Definition: ApiMain.php:1436
wfReadOnly
wfReadOnly()
Check whether the wiki is in read-only mode.
Definition: GlobalFunctions.php:1360
wfMsgReplaceArgs
wfMsgReplaceArgs( $message, $args)
Replace message parameter keys on the given formatted output.
Definition: GlobalFunctions.php:1637
$s
$s
Definition: mergeMessageFileList.php:156
ContextSource\getRequest
getRequest()
Get the WebRequest object.
Definition: ContextSource.php:77
ApiMain\encodeRequestLogValue
encodeRequestLogValue( $s)
Encode a value in a format suitable for a space-separated log line.
Definition: ApiMain.php:959
ContextSource\getUser
getUser()
Get the User object.
Definition: ContextSource.php:132
UsageException\$mExtraData
null array $mExtraData
Definition: ApiMain.php:1412
ApiMain\makeHelpMsg
makeHelpMsg()
Override the parent to generate help messages for all available modules.
Definition: ApiMain.php:1240
ApiMain\matchOrigin
static matchOrigin( $value, $rules, $exceptions)
Attempt to match an Origin header against a set of rules and a set of exceptions.
Definition: ApiMain.php:519
ApiMain\$mRights
static $mRights
List of user roles that are specifically relevant to the API.
Definition: ApiMain.php:121
ApiBase
This abstract class implements many basic API functions, and is the base of all API classes.
Definition: ApiBase.php:42
ApiMain\getModule
getModule()
Get the API module object.
Definition: ApiMain.php:224
ApiBase\profileOut
profileOut()
End module profiling.
Definition: ApiBase.php:2217
DerivativeContext
An IContextSource implementation which will inherit context from another source but allow individual ...
Definition: DerivativeContext.php:32
MWException
MediaWiki exception.
Definition: MWException.php:26
wfMemcKey
wfMemcKey()
Get a cache key.
Definition: GlobalFunctions.php:3627
$out
$out
Definition: UtfNormalGenerate.php:167
ApiMain\getParamDescription
getParamDescription()
See ApiBase for description.
Definition: ApiMain.php:1113
wfDeprecated
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
Definition: GlobalFunctions.php:1174
DBQueryError
Definition: DatabaseError.php:306
ApiMain\setupExecuteAction
setupExecuteAction()
Set up for the execution.
Definition: ApiMain.php:726
ApiResult
This class represents the result of the API operations.
Definition: ApiResult.php:44
ApiMain\$mResult
$mResult
Definition: ApiMain.php:137
UsageException
This exception will be thrown when dieUsage is called to stop module execution.
Definition: ApiMain.php:1406
ApiMain\addFormat
addFormat( $name, $class)
Add or overwrite an output format for this ApiMain.
Definition: ApiMain.php:1375
ContextSource\getOutput
getOutput()
Get the OutputPage object.
Definition: ContextSource.php:122
ApiMain\getResult
getResult()
Get the ApiResult object associated with current request.
Definition: ApiMain.php:215
UsageException\__toString
__toString()
Definition: ApiMain.php:1451
wfRunHooks
wfRunHooks( $event, array $args=array(), $deprecatedVersion=null)
Call hook functions defined in $wgHooks.
Definition: GlobalFunctions.php:4058
ApiMain\checkMaxLag
checkMaxLag( $module, $params)
Check the max lag if necessary.
Definition: ApiMain.php:791
ApiMain\setCacheControl
setCacheControl( $directives)
Set directives (key/value pairs) for the Cache-Control header.
Definition: ApiMain.php:305
array
the array() calling protocol came about after MediaWiki 1.4rc1.
List of Api Query prop modules.
ApiMain\getAllowedParams
getAllowedParams()
See ApiBase for description.
Definition: ApiMain.php:1078
ApiMain\setupExternalResponse
setupExternalResponse( $module, $params)
Check POST for external response and setup result printer.
Definition: ApiMain.php:871
ApiMain\createPrinterByName
createPrinterByName( $format)
Create an instance of an output formatter by its name.
Definition: ApiMain.php:316
ApiMain\getModuleManager
getModuleManager()
Overrides to return this instance's module manager.
Definition: ApiMain.php:1350
global
when a variable name is used in a it is silently declared as a new masking the global
Definition: design.txt:93
ApiMain\$mCanApiHighLimits
$mCanApiHighLimits
Definition: ApiMain.php:1321
ContextSource\setContext
setContext(IContextSource $context)
Set the IContextSource object.
Definition: ContextSource.php:57
ApiMain\canApiHighLimits
canApiHighLimits()
Check whether the current user is allowed to use high limits.
Definition: ApiMain.php:1327
list
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
false
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:188
ApiMain\$mPrinter
ApiFormatBase $mPrinter
Definition: ApiMain.php:135
ApiMain\$mModule
$mModule
Definition: ApiMain.php:140
ApiModuleManager
This class holds a list of modules and handles instantiation.
Definition: ApiModuleManager.php:34
wfDebug
wfDebug( $text, $dest='all')
Sends a line to the debug log if enabled or, optionally, to a comment in output.
Definition: GlobalFunctions.php:980
ApiMain\checkAsserts
checkAsserts( $params)
Check asserts of the user's rights.
Definition: ApiMain.php:848
ApiBase\extractRequestParams
extractRequestParams( $parseLimit=true)
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition: ApiBase.php:687
ApiMain\$mCacheMode
$mCacheMode
Definition: ApiMain.php:142
MWDebug\appendDebugInfoToApiResult
static appendDebugInfoToApiResult(IContextSource $context, ApiResult $result)
Append the debug info to given ApiResult.
Definition: Debug.php:491
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:336
UsageException\$mCodestr
$mCodestr
Definition: ApiMain.php:1408
ApiMain\$mInternalMode
$mInternalMode
Definition: ApiMain.php:140
$value
$value
Definition: styleTest.css.php:45
ApiMain\wildcardToRegex
static wildcardToRegex( $wildcard)
Helper function to convert wildcard string into a regex '*' => '.
Definition: ApiMain.php:544
ApiMain\checkExecutePermissions
checkExecutePermissions( $module)
Check for sufficient permissions to execute.
Definition: ApiMain.php:818
ApiMain\reallyMakeHelpMsg
reallyMakeHelpMsg()
Definition: ApiMain.php:1263
ApiBase\LIMIT_SML2
const LIMIT_SML2
Definition: ApiBase.php:81
ApiBase\dieUsage
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:1363
ApiBase\dieReadOnly
dieReadOnly()
Helper function for readonly errors.
Definition: ApiBase.php:1923
ApiMain\__construct
__construct( $context=null, $enableWrite=false)
Constructs an instance of ApiMain that utilizes the module and format specified by $request.
Definition: ApiMain.php:153
ApiMain\reportUnusedParams
reportUnusedParams()
Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,...
Definition: ApiMain.php:1015
cssjanus.main
def main(argv)
Definition: cssjanus.py:554
ApiMain\execute
execute()
Execute api request.
Definition: ApiMain.php:328
ApiMain\logRequest
logRequest( $time)
Log the preceding request.
Definition: ApiMain.php:931
ApiMain\$Formats
static $Formats
List of available formats: format name => format class.
Definition: ApiMain.php:93
ApiMain\substituteResultWithError
substituteResultWithError( $e)
Replace the result data with the information about an exception.
Definition: ApiMain.php:645
RequestContext\getMain
static getMain()
Static methods.
Definition: RequestContext.php:420
HttpStatus\getMessage
static getMessage( $code)
Get the message associated with HTTP response code $code.
Definition: HttpStatus.php:37
$exceptions
$exceptions
Definition: Utf8Test.php:72
$user
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a account $user
Definition: hooks.txt:237
ApiMain\getCheck
getCheck( $name)
Get a boolean request value, and register the fact that the parameter was used, for logging.
Definition: ApiMain.php:992
UsageException\getCodeString
getCodeString()
Definition: ApiMain.php:1429
wfReportTime
wfReportTime()
Returns a script tag that stores the amount of time it took MediaWiki to handle the request in millis...
Definition: GlobalFunctions.php:1873
ApiBase\profileIn
profileIn()
Start module profiling.
Definition: ApiBase.php:2206
WebRequest
The WebRequest class encapsulates getting at data passed in the URL or via a POSTed form,...
Definition: WebRequest.php:38
ApiMain\makeHelpMsgHeader
static makeHelpMsgHeader( $module, $paramName)
Definition: ApiMain.php:1312
ApiMain\$mEnableWrite
$mEnableWrite
Definition: ApiMain.php:139
ApiBase\setWarning
setWarning( $warning)
Set warning section for this module.
Definition: ApiBase.php:245
User\isEveryoneAllowed
static isEveryoneAllowed( $right)
Check if all users have the given permission.
Definition: User.php:4160
UsageException\__construct
__construct( $message, $codestr, $code=0, $extradata=null)
Definition: ApiMain.php:1420
ApiBase\LIMIT_BIG2
const LIMIT_BIG2
Definition: ApiBase.php:79
ApiMain\API_DEFAULT_FORMAT
const API_DEFAULT_FORMAT
When no format parameter is given, this format will be used.
Definition: ApiMain.php:45
ApiMain\addModule
addModule( $name, $class)
Add or overwrite a module in this ApiMain instance.
Definition: ApiMain.php:1363
ApiMain\setHelp
setHelp( $help=true)
Sets whether the pretty-printer should format bold and $italics$.
Definition: ApiMain.php:1231
ApiMain\printResult
printResult( $isError)
Print results using the current printer.
Definition: ApiMain.php:1041
ApiMain\getUpload
getUpload( $name)
Get a request upload, and register the fact that it was used, for logging.
Definition: ApiMain.php:1005
MWExceptionHandler\rollbackMasterChangesAndLog
static rollbackMasterChangesAndLog(Exception $e)
If there are any open database transactions, roll them back and log the stack trace of the exception ...
Definition: MWExceptionHandler.php:111
ApiBase\PARAM_DFLT
const PARAM_DFLT
Definition: ApiBase.php:46
ApiBase\getParameter
getParameter( $paramName, $parseLimit=true)
Get a value for the given parameter.
Definition: ApiBase.php:711
as
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
ApiMain\getPossibleErrors
getPossibleErrors()
Definition: ApiMain.php:1193
ApiBase\getModuleName
getModuleName()
Get the name of the module being executed by this instance.
Definition: ApiBase.php:148
User
User
Definition: All_system_messages.txt:425
ApiMain\executeAction
executeAction()
Execute the actual module, without any error handling.
Definition: ApiMain.php:893
ApiMain\setupModule
setupModule()
Set up the module for response.
Definition: ApiMain.php:758
$help
$help
Definition: mcc.php:31
MWExceptionHandler\logException
static logException(Exception $e)
Log an exception to the exception log (if enabled).
Definition: MWExceptionHandler.php:351
ApiMain\$mCacheControl
$mCacheControl
Definition: ApiMain.php:143
$t
$t
Definition: testCompression.php:65
ApiMain\handleException
handleException(Exception $e)
Handle an exception as an API response.
Definition: ApiMain.php:387
ApiMain\isInternalMode
isInternalMode()
Return true if the API was started by other PHP code using FauxRequest.
Definition: ApiMain.php:206
ApiMain\$mParamsUsed
$mParamsUsed
Definition: ApiMain.php:144
ApiMain\$mModuleMgr
$mModuleMgr
Definition: ApiMain.php:137
ApiMain\setCacheMaxAge
setCacheMaxAge( $maxage)
Set how long the response should be cached.
Definition: ApiMain.php:242
$retval
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a account incomplete not yet checked for validity & $retval
Definition: hooks.txt:237
ApiMain\setCacheMode
setCacheMode( $mode)
Set the type of caching headers which will be sent.
Definition: ApiMain.php:274
TS_RFC2822
const TS_RFC2822
RFC 2822 format, for E-mail and HTTP headers.
Definition: GlobalFunctions.php:2488
ApiMain\getPrinter
getPrinter()
Get the result formatter object.
Definition: ApiMain.php:233
if
if(!function_exists('version_compare')||version_compare(phpversion(), '5.3.2')< 0)
Definition: api.php:37
User\getGroupsWithPermission
static getGroupsWithPermission( $role)
Get all the groups who have a given permission.
Definition: User.php:4124
$e
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:1632
SpecialVersion\getVersion
static getVersion( $flags='')
Return a string of the MediaWiki version with SVN revision if available.
Definition: SpecialVersion.php:246
ApiMain\getFormats
getFormats()
Returns the list of supported formats in form ( 'format' => 'ClassName' )
Definition: ApiMain.php:1395