MediaWiki  1.27.1
ApiBase.php
Go to the documentation of this file.
1 <?php
39 abstract class ApiBase extends ContextSource {
40 
50  const PARAM_DFLT = 0;
51 
53  const PARAM_ISMULTI = 1;
54 
88  const PARAM_TYPE = 2;
89 
91  const PARAM_MAX = 3;
92 
97  const PARAM_MAX2 = 4;
98 
100  const PARAM_MIN = 5;
101 
104 
106  const PARAM_DEPRECATED = 7;
107 
112  const PARAM_REQUIRED = 8;
113 
119 
125  const PARAM_HELP_MSG = 10;
126 
133 
143 
149  const PARAM_VALUE_LINKS = 13;
150 
158 
166 
173 
177  const LIMIT_BIG1 = 500;
179  const LIMIT_BIG2 = 5000;
181  const LIMIT_SML1 = 50;
183  const LIMIT_SML2 = 500;
184 
191 
193  private static $extensionInfo = null;
194 
196  private $mMainModule;
199  private $mSlaveDB = null;
200  private $mParamCache = [];
202  private $mModuleSource = false;
203 
209  public function __construct( ApiMain $mainModule, $moduleName, $modulePrefix = '' ) {
210  $this->mMainModule = $mainModule;
211  $this->mModuleName = $moduleName;
212  $this->mModulePrefix = $modulePrefix;
213 
214  if ( !$this->isMain() ) {
215  $this->setContext( $mainModule->getContext() );
216  }
217  }
218 
219  /************************************************************************/
240  abstract public function execute();
241 
247  public function getModuleManager() {
248  return null;
249  }
250 
260  public function getCustomPrinter() {
261  return null;
262  }
263 
275  protected function getExamplesMessages() {
276  // Fall back to old non-localised method
277  $ret = [];
278 
279  $examples = $this->getExamples();
280  if ( $examples ) {
281  if ( !is_array( $examples ) ) {
282  $examples = [ $examples ];
283  } elseif ( $examples && ( count( $examples ) & 1 ) == 0 &&
284  array_keys( $examples ) === range( 0, count( $examples ) - 1 ) &&
285  !preg_match( '/^\s*api\.php\?/', $examples[0] )
286  ) {
287  // Fix up the ugly "even numbered elements are description, odd
288  // numbered elemts are the link" format (see doc for self::getExamples)
289  $tmp = [];
290  $examplesCount = count( $examples );
291  for ( $i = 0; $i < $examplesCount; $i += 2 ) {
292  $tmp[$examples[$i + 1]] = $examples[$i];
293  }
294  $examples = $tmp;
295  }
296 
297  foreach ( $examples as $k => $v ) {
298  if ( is_numeric( $k ) ) {
299  $qs = $v;
300  $msg = '';
301  } else {
302  $qs = $k;
303  $msg = self::escapeWikiText( $v );
304  if ( is_array( $msg ) ) {
305  $msg = implode( ' ', $msg );
306  }
307  }
308 
309  $qs = preg_replace( '/^\s*api\.php\?/', '', $qs );
310  $ret[$qs] = $this->msg( 'api-help-fallback-example', [ $msg ] );
311  }
312  }
313 
314  return $ret;
315  }
316 
322  public function getHelpUrls() {
323  return [];
324  }
325 
338  protected function getAllowedParams( /* $flags = 0 */ ) {
339  // int $flags is not declared because it causes "Strict standards"
340  // warning. Most derived classes do not implement it.
341  return [];
342  }
343 
348  public function shouldCheckMaxlag() {
349  return true;
350  }
351 
356  public function isReadMode() {
357  return true;
358  }
359 
364  public function isWriteMode() {
365  return false;
366  }
367 
372  public function mustBePosted() {
373  return $this->needsToken() !== false;
374  }
375 
381  public function isDeprecated() {
382  return false;
383  }
384 
391  public function isInternal() {
392  return false;
393  }
394 
413  public function needsToken() {
414  return false;
415  }
416 
426  protected function getWebUITokenSalt( array $params ) {
427  return null;
428  }
429 
442  public function getConditionalRequestData( $condition ) {
443  return null;
444  }
445 
448  /************************************************************************/
457  public function getModuleName() {
458  return $this->mModuleName;
459  }
460 
465  public function getModulePrefix() {
466  return $this->mModulePrefix;
467  }
468 
473  public function getMain() {
474  return $this->mMainModule;
475  }
476 
482  public function isMain() {
483  return $this === $this->mMainModule;
484  }
485 
491  public function getParent() {
492  return $this->isMain() ? null : $this->getMain();
493  }
494 
505  public function lacksSameOriginSecurity() {
506  // Main module has this method overridden
507  // Safety - avoid infinite loop:
508  if ( $this->isMain() ) {
509  ApiBase::dieDebug( __METHOD__, 'base method was called on main module.' );
510  }
511 
512  return $this->getMain()->lacksSameOriginSecurity();
513  }
514 
521  public function getModulePath() {
522  if ( $this->isMain() ) {
523  return 'main';
524  } elseif ( $this->getParent()->isMain() ) {
525  return $this->getModuleName();
526  } else {
527  return $this->getParent()->getModulePath() . '+' . $this->getModuleName();
528  }
529  }
530 
539  public function getModuleFromPath( $path ) {
540  $module = $this->getMain();
541  if ( $path === 'main' ) {
542  return $module;
543  }
544 
545  $parts = explode( '+', $path );
546  if ( count( $parts ) === 1 ) {
547  // In case the '+' was typed into URL, it resolves as a space
548  $parts = explode( ' ', $path );
549  }
550 
551  $count = count( $parts );
552  for ( $i = 0; $i < $count; $i++ ) {
553  $parent = $module;
554  $manager = $parent->getModuleManager();
555  if ( $manager === null ) {
556  $errorPath = implode( '+', array_slice( $parts, 0, $i ) );
557  $this->dieUsage( "The module \"$errorPath\" has no submodules", 'badmodule' );
558  }
559  $module = $manager->getModule( $parts[$i] );
560 
561  if ( $module === null ) {
562  $errorPath = $i ? implode( '+', array_slice( $parts, 0, $i ) ) : $parent->getModuleName();
563  $this->dieUsage(
564  "The module \"$errorPath\" does not have a submodule \"{$parts[$i]}\"",
565  'badmodule'
566  );
567  }
568  }
569 
570  return $module;
571  }
572 
577  public function getResult() {
578  // Main module has getResult() method overridden
579  // Safety - avoid infinite loop:
580  if ( $this->isMain() ) {
581  ApiBase::dieDebug( __METHOD__, 'base method was called on main module. ' );
582  }
583 
584  return $this->getMain()->getResult();
585  }
586 
591  public function getErrorFormatter() {
592  // Main module has getErrorFormatter() method overridden
593  // Safety - avoid infinite loop:
594  if ( $this->isMain() ) {
595  ApiBase::dieDebug( __METHOD__, 'base method was called on main module. ' );
596  }
597 
598  return $this->getMain()->getErrorFormatter();
599  }
600 
605  protected function getDB() {
606  if ( !isset( $this->mSlaveDB ) ) {
607  $this->mSlaveDB = wfGetDB( DB_SLAVE, 'api' );
608  }
609 
610  return $this->mSlaveDB;
611  }
612 
617  public function getContinuationManager() {
618  // Main module has getContinuationManager() method overridden
619  // Safety - avoid infinite loop:
620  if ( $this->isMain() ) {
621  ApiBase::dieDebug( __METHOD__, 'base method was called on main module. ' );
622  }
623 
624  return $this->getMain()->getContinuationManager();
625  }
626 
631  public function setContinuationManager( $manager ) {
632  // Main module has setContinuationManager() method overridden
633  // Safety - avoid infinite loop:
634  if ( $this->isMain() ) {
635  ApiBase::dieDebug( __METHOD__, 'base method was called on main module. ' );
636  }
637 
638  $this->getMain()->setContinuationManager( $manager );
639  }
640 
643  /************************************************************************/
655  public function dynamicParameterDocumentation() {
656  return null;
657  }
658 
665  public function encodeParamName( $paramName ) {
666  return $this->mModulePrefix . $paramName;
667  }
668 
678  public function extractRequestParams( $parseLimit = true ) {
679  // Cache parameters, for performance and to avoid bug 24564.
680  if ( !isset( $this->mParamCache[$parseLimit] ) ) {
681  $params = $this->getFinalParams();
682  $results = [];
683 
684  if ( $params ) { // getFinalParams() can return false
685  foreach ( $params as $paramName => $paramSettings ) {
686  $results[$paramName] = $this->getParameterFromSettings(
687  $paramName, $paramSettings, $parseLimit );
688  }
689  }
690  $this->mParamCache[$parseLimit] = $results;
691  }
692 
693  return $this->mParamCache[$parseLimit];
694  }
695 
702  protected function getParameter( $paramName, $parseLimit = true ) {
703  $paramSettings = $this->getFinalParams()[$paramName];
704 
705  return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
706  }
707 
714  public function requireOnlyOneParameter( $params, $required /*...*/ ) {
715  $required = func_get_args();
716  array_shift( $required );
717  $p = $this->getModulePrefix();
718 
719  $intersection = array_intersect( array_keys( array_filter( $params,
720  [ $this, 'parameterNotEmpty' ] ) ), $required );
721 
722  if ( count( $intersection ) > 1 ) {
723  $this->dieUsage(
724  "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
725  'invalidparammix' );
726  } elseif ( count( $intersection ) == 0 ) {
727  $this->dieUsage(
728  "One of the parameters {$p}" . implode( ", {$p}", $required ) . ' is required',
729  'missingparam'
730  );
731  }
732  }
733 
740  public function requireMaxOneParameter( $params, $required /*...*/ ) {
741  $required = func_get_args();
742  array_shift( $required );
743  $p = $this->getModulePrefix();
744 
745  $intersection = array_intersect( array_keys( array_filter( $params,
746  [ $this, 'parameterNotEmpty' ] ) ), $required );
747 
748  if ( count( $intersection ) > 1 ) {
749  $this->dieUsage(
750  "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
751  'invalidparammix'
752  );
753  }
754  }
755 
763  public function requireAtLeastOneParameter( $params, $required /*...*/ ) {
764  $required = func_get_args();
765  array_shift( $required );
766  $p = $this->getModulePrefix();
767 
768  $intersection = array_intersect(
769  array_keys( array_filter( $params, [ $this, 'parameterNotEmpty' ] ) ),
770  $required
771  );
772 
773  if ( count( $intersection ) == 0 ) {
774  $this->dieUsage( "At least one of the parameters {$p}" .
775  implode( ", {$p}", $required ) . ' is required', "{$p}missingparam" );
776  }
777  }
778 
785  private function parameterNotEmpty( $x ) {
786  return !is_null( $x ) && $x !== false;
787  }
788 
800  public function getTitleOrPageId( $params, $load = false ) {
801  $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
802 
803  $pageObj = null;
804  if ( isset( $params['title'] ) ) {
805  $titleObj = Title::newFromText( $params['title'] );
806  if ( !$titleObj || $titleObj->isExternal() ) {
807  $this->dieUsageMsg( [ 'invalidtitle', $params['title'] ] );
808  }
809  if ( !$titleObj->canExist() ) {
810  $this->dieUsage( "Namespace doesn't allow actual pages", 'pagecannotexist' );
811  }
812  $pageObj = WikiPage::factory( $titleObj );
813  if ( $load !== false ) {
814  $pageObj->loadPageData( $load );
815  }
816  } elseif ( isset( $params['pageid'] ) ) {
817  if ( $load === false ) {
818  $load = 'fromdb';
819  }
820  $pageObj = WikiPage::newFromID( $params['pageid'], $load );
821  if ( !$pageObj ) {
822  $this->dieUsageMsg( [ 'nosuchpageid', $params['pageid'] ] );
823  }
824  }
825 
826  return $pageObj;
827  }
828 
837  protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
838 
839  $userWatching = $this->getUser()->isWatched( $titleObj, User::IGNORE_USER_RIGHTS );
840 
841  switch ( $watchlist ) {
842  case 'watch':
843  return true;
844 
845  case 'unwatch':
846  return false;
847 
848  case 'preferences':
849  # If the user is already watching, don't bother checking
850  if ( $userWatching ) {
851  return true;
852  }
853  # If no user option was passed, use watchdefault and watchcreations
854  if ( is_null( $userOption ) ) {
855  return $this->getUser()->getBoolOption( 'watchdefault' ) ||
856  $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
857  }
858 
859  # Watch the article based on the user preference
860  return $this->getUser()->getBoolOption( $userOption );
861 
862  case 'nochange':
863  return $userWatching;
864 
865  default:
866  return $userWatching;
867  }
868  }
869 
879  protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
880  // Some classes may decide to change parameter names
881  $encParamName = $this->encodeParamName( $paramName );
882 
883  if ( !is_array( $paramSettings ) ) {
884  $default = $paramSettings;
885  $multi = false;
886  $type = gettype( $paramSettings );
887  $dupes = false;
888  $deprecated = false;
889  $required = false;
890  } else {
891  $default = isset( $paramSettings[self::PARAM_DFLT] )
892  ? $paramSettings[self::PARAM_DFLT]
893  : null;
894  $multi = isset( $paramSettings[self::PARAM_ISMULTI] )
895  ? $paramSettings[self::PARAM_ISMULTI]
896  : false;
897  $type = isset( $paramSettings[self::PARAM_TYPE] )
898  ? $paramSettings[self::PARAM_TYPE]
899  : null;
900  $dupes = isset( $paramSettings[self::PARAM_ALLOW_DUPLICATES] )
901  ? $paramSettings[self::PARAM_ALLOW_DUPLICATES]
902  : false;
903  $deprecated = isset( $paramSettings[self::PARAM_DEPRECATED] )
904  ? $paramSettings[self::PARAM_DEPRECATED]
905  : false;
906  $required = isset( $paramSettings[self::PARAM_REQUIRED] )
907  ? $paramSettings[self::PARAM_REQUIRED]
908  : false;
909 
910  // When type is not given, and no choices, the type is the same as $default
911  if ( !isset( $type ) ) {
912  if ( isset( $default ) ) {
913  $type = gettype( $default );
914  } else {
915  $type = 'NULL'; // allow everything
916  }
917  }
918  }
919 
920  if ( $type == 'boolean' ) {
921  if ( isset( $default ) && $default !== false ) {
922  // Having a default value of anything other than 'false' is not allowed
924  __METHOD__,
925  "Boolean param $encParamName's default is set to '$default'. " .
926  'Boolean parameters must default to false.'
927  );
928  }
929 
930  $value = $this->getMain()->getCheck( $encParamName );
931  } elseif ( $type == 'upload' ) {
932  if ( isset( $default ) ) {
933  // Having a default value is not allowed
935  __METHOD__,
936  "File upload param $encParamName's default is set to " .
937  "'$default'. File upload parameters may not have a default." );
938  }
939  if ( $multi ) {
940  ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
941  }
942  $value = $this->getMain()->getUpload( $encParamName );
943  if ( !$value->exists() ) {
944  // This will get the value without trying to normalize it
945  // (because trying to normalize a large binary file
946  // accidentally uploaded as a field fails spectacularly)
947  $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
948  if ( $value !== null ) {
949  $this->dieUsage(
950  "File upload param $encParamName is not a file upload; " .
951  'be sure to use multipart/form-data for your POST and include ' .
952  'a filename in the Content-Disposition header.',
953  "badupload_{$encParamName}"
954  );
955  }
956  }
957  } else {
958  $value = $this->getMain()->getVal( $encParamName, $default );
959 
960  if ( isset( $value ) && $type == 'namespace' ) {
962  }
963  if ( isset( $value ) && $type == 'submodule' ) {
964  if ( isset( $paramSettings[self::PARAM_SUBMODULE_MAP] ) ) {
965  $type = array_keys( $paramSettings[self::PARAM_SUBMODULE_MAP] );
966  } else {
967  $type = $this->getModuleManager()->getNames( $paramName );
968  }
969  }
970  }
971 
972  if ( isset( $value ) && ( $multi || is_array( $type ) ) ) {
973  $value = $this->parseMultiValue(
974  $encParamName,
975  $value,
976  $multi,
977  is_array( $type ) ? $type : null
978  );
979  }
980 
981  // More validation only when choices were not given
982  // choices were validated in parseMultiValue()
983  if ( isset( $value ) ) {
984  if ( !is_array( $type ) ) {
985  switch ( $type ) {
986  case 'NULL': // nothing to do
987  break;
988  case 'string':
989  case 'text':
990  case 'password':
991  if ( $required && $value === '' ) {
992  $this->dieUsageMsg( [ 'missingparam', $paramName ] );
993  }
994  break;
995  case 'integer': // Force everything using intval() and optionally validate limits
996  $min = isset( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[self::PARAM_MIN] : null;
997  $max = isset( $paramSettings[self::PARAM_MAX] ) ? $paramSettings[self::PARAM_MAX] : null;
998  $enforceLimits = isset( $paramSettings[self::PARAM_RANGE_ENFORCE] )
999  ? $paramSettings[self::PARAM_RANGE_ENFORCE] : false;
1000 
1001  if ( is_array( $value ) ) {
1002  $value = array_map( 'intval', $value );
1003  if ( !is_null( $min ) || !is_null( $max ) ) {
1004  foreach ( $value as &$v ) {
1005  $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
1006  }
1007  }
1008  } else {
1009  $value = intval( $value );
1010  if ( !is_null( $min ) || !is_null( $max ) ) {
1011  $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
1012  }
1013  }
1014  break;
1015  case 'limit':
1016  if ( !$parseLimit ) {
1017  // Don't do any validation whatsoever
1018  break;
1019  }
1020  if ( !isset( $paramSettings[self::PARAM_MAX] )
1021  || !isset( $paramSettings[self::PARAM_MAX2] )
1022  ) {
1024  __METHOD__,
1025  "MAX1 or MAX2 are not defined for the limit $encParamName"
1026  );
1027  }
1028  if ( $multi ) {
1029  ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
1030  }
1031  $min = isset( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[self::PARAM_MIN] : 0;
1032  if ( $value == 'max' ) {
1033  $value = $this->getMain()->canApiHighLimits()
1034  ? $paramSettings[self::PARAM_MAX2]
1035  : $paramSettings[self::PARAM_MAX];
1036  $this->getResult()->addParsedLimit( $this->getModuleName(), $value );
1037  } else {
1038  $value = intval( $value );
1039  $this->validateLimit(
1040  $paramName,
1041  $value,
1042  $min,
1043  $paramSettings[self::PARAM_MAX],
1044  $paramSettings[self::PARAM_MAX2]
1045  );
1046  }
1047  break;
1048  case 'boolean':
1049  if ( $multi ) {
1050  ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
1051  }
1052  break;
1053  case 'timestamp':
1054  if ( is_array( $value ) ) {
1055  foreach ( $value as $key => $val ) {
1056  $value[$key] = $this->validateTimestamp( $val, $encParamName );
1057  }
1058  } else {
1059  $value = $this->validateTimestamp( $value, $encParamName );
1060  }
1061  break;
1062  case 'user':
1063  if ( is_array( $value ) ) {
1064  foreach ( $value as $key => $val ) {
1065  $value[$key] = $this->validateUser( $val, $encParamName );
1066  }
1067  } else {
1068  $value = $this->validateUser( $value, $encParamName );
1069  }
1070  break;
1071  case 'upload': // nothing to do
1072  break;
1073  case 'tags':
1074  // If change tagging was requested, check that the tags are valid.
1075  if ( !is_array( $value ) && !$multi ) {
1076  $value = [ $value ];
1077  }
1079  if ( !$tagsStatus->isGood() ) {
1080  $this->dieStatus( $tagsStatus );
1081  }
1082  break;
1083  default:
1084  ApiBase::dieDebug( __METHOD__, "Param $encParamName's type is unknown - $type" );
1085  }
1086  }
1087 
1088  // Throw out duplicates if requested
1089  if ( !$dupes && is_array( $value ) ) {
1090  $value = array_unique( $value );
1091  }
1092 
1093  // Set a warning if a deprecated parameter has been passed
1094  if ( $deprecated && $value !== false ) {
1095  $this->setWarning( "The $encParamName parameter has been deprecated." );
1096 
1097  $feature = $encParamName;
1098  $m = $this;
1099  while ( !$m->isMain() ) {
1100  $p = $m->getParent();
1101  $name = $m->getModuleName();
1102  $param = $p->encodeParamName( $p->getModuleManager()->getModuleGroup( $name ) );
1103  $feature = "{$param}={$name}&{$feature}";
1104  $m = $p;
1105  }
1106  $this->logFeatureUsage( $feature );
1107  }
1108  } elseif ( $required ) {
1109  $this->dieUsageMsg( [ 'missingparam', $paramName ] );
1110  }
1111 
1112  return $value;
1113  }
1114 
1128  protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues ) {
1129  if ( trim( $value ) === '' && $allowMultiple ) {
1130  return [];
1131  }
1132 
1133  // This is a bit awkward, but we want to avoid calling canApiHighLimits()
1134  // because it unstubs $wgUser
1135  $valuesList = explode( '|', $value, self::LIMIT_SML2 + 1 );
1136  $sizeLimit = count( $valuesList ) > self::LIMIT_SML1 && $this->mMainModule->canApiHighLimits()
1137  ? self::LIMIT_SML2
1138  : self::LIMIT_SML1;
1139 
1140  if ( self::truncateArray( $valuesList, $sizeLimit ) ) {
1141  $this->setWarning( "Too many values supplied for parameter '$valueName': " .
1142  "the limit is $sizeLimit" );
1143  }
1144 
1145  if ( !$allowMultiple && count( $valuesList ) != 1 ) {
1146  // Bug 33482 - Allow entries with | in them for non-multiple values
1147  if ( in_array( $value, $allowedValues, true ) ) {
1148  return $value;
1149  }
1150 
1151  $possibleValues = is_array( $allowedValues )
1152  ? "of '" . implode( "', '", $allowedValues ) . "'"
1153  : '';
1154  $this->dieUsage(
1155  "Only one $possibleValues is allowed for parameter '$valueName'",
1156  "multival_$valueName"
1157  );
1158  }
1159 
1160  if ( is_array( $allowedValues ) ) {
1161  // Check for unknown values
1162  $unknown = array_diff( $valuesList, $allowedValues );
1163  if ( count( $unknown ) ) {
1164  if ( $allowMultiple ) {
1165  $s = count( $unknown ) > 1 ? 's' : '';
1166  $vals = implode( ', ', $unknown );
1167  $this->setWarning( "Unrecognized value$s for parameter '$valueName': $vals" );
1168  } else {
1169  $this->dieUsage(
1170  "Unrecognized value for parameter '$valueName': {$valuesList[0]}",
1171  "unknown_$valueName"
1172  );
1173  }
1174  }
1175  // Now throw them out
1176  $valuesList = array_intersect( $valuesList, $allowedValues );
1177  }
1178 
1179  return $allowMultiple ? $valuesList : $valuesList[0];
1180  }
1181 
1192  protected function validateLimit( $paramName, &$value, $min, $max, $botMax = null,
1193  $enforceLimits = false
1194  ) {
1195  if ( !is_null( $min ) && $value < $min ) {
1196  $msg = $this->encodeParamName( $paramName ) . " may not be less than $min (set to $value)";
1197  $this->warnOrDie( $msg, $enforceLimits );
1198  $value = $min;
1199  }
1200 
1201  // Minimum is always validated, whereas maximum is checked only if not
1202  // running in internal call mode
1203  if ( $this->getMain()->isInternalMode() ) {
1204  return;
1205  }
1206 
1207  // Optimization: do not check user's bot status unless really needed -- skips db query
1208  // assumes $botMax >= $max
1209  if ( !is_null( $max ) && $value > $max ) {
1210  if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1211  if ( $value > $botMax ) {
1212  $msg = $this->encodeParamName( $paramName ) .
1213  " may not be over $botMax (set to $value) for bots or sysops";
1214  $this->warnOrDie( $msg, $enforceLimits );
1215  $value = $botMax;
1216  }
1217  } else {
1218  $msg = $this->encodeParamName( $paramName ) . " may not be over $max (set to $value) for users";
1219  $this->warnOrDie( $msg, $enforceLimits );
1220  $value = $max;
1221  }
1222  }
1223  }
1224 
1231  protected function validateTimestamp( $value, $encParamName ) {
1232  // Confusing synonyms for the current time accepted by wfTimestamp()
1233  // (wfTimestamp() also accepts various non-strings and the string of 14
1234  // ASCII NUL bytes, but those can't get here)
1235  if ( !$value ) {
1236  $this->logFeatureUsage( 'unclear-"now"-timestamp' );
1237  $this->setWarning(
1238  "Passing '$value' for timestamp parameter $encParamName has been deprecated." .
1239  ' If for some reason you need to explicitly specify the current time without' .
1240  ' calculating it client-side, use "now".'
1241  );
1242  return wfTimestamp( TS_MW );
1243  }
1244 
1245  // Explicit synonym for the current time
1246  if ( $value === 'now' ) {
1247  return wfTimestamp( TS_MW );
1248  }
1249 
1250  $unixTimestamp = wfTimestamp( TS_UNIX, $value );
1251  if ( $unixTimestamp === false ) {
1252  $this->dieUsage(
1253  "Invalid value '$value' for timestamp parameter $encParamName",
1254  "badtimestamp_{$encParamName}"
1255  );
1256  }
1257 
1258  return wfTimestamp( TS_MW, $unixTimestamp );
1259  }
1260 
1270  final public function validateToken( $token, array $params ) {
1271  $tokenType = $this->needsToken();
1273  if ( !isset( $salts[$tokenType] ) ) {
1274  throw new MWException(
1275  "Module '{$this->getModuleName()}' tried to use token type '$tokenType' " .
1276  'without registering it'
1277  );
1278  }
1279 
1280  $tokenObj = ApiQueryTokens::getToken(
1281  $this->getUser(), $this->getRequest()->getSession(), $salts[$tokenType]
1282  );
1283  if ( $tokenObj->match( $token ) ) {
1284  return true;
1285  }
1286 
1287  $webUiSalt = $this->getWebUITokenSalt( $params );
1288  if ( $webUiSalt !== null && $this->getUser()->matchEditToken(
1289  $token,
1290  $webUiSalt,
1291  $this->getRequest()
1292  ) ) {
1293  return true;
1294  }
1295 
1296  return false;
1297  }
1298 
1305  private function validateUser( $value, $encParamName ) {
1307  if ( $title === null || $title->hasFragment() ) {
1308  $this->dieUsage(
1309  "Invalid value '$value' for user parameter $encParamName",
1310  "baduser_{$encParamName}"
1311  );
1312  }
1313 
1314  return $title->getText();
1315  }
1316 
1319  /************************************************************************/
1330  protected function setWatch( $watch, $titleObj, $userOption = null ) {
1331  $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
1332  if ( $value === null ) {
1333  return;
1334  }
1335 
1336  WatchAction::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
1337  }
1338 
1345  public static function truncateArray( &$arr, $limit ) {
1346  $modified = false;
1347  while ( count( $arr ) > $limit ) {
1348  array_pop( $arr );
1349  $modified = true;
1350  }
1351 
1352  return $modified;
1353  }
1354 
1361  public function getWatchlistUser( $params ) {
1362  if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1363  $user = User::newFromName( $params['owner'], false );
1364  if ( !( $user && $user->getId() ) ) {
1365  $this->dieUsage( 'Specified user does not exist', 'bad_wlowner' );
1366  }
1367  $token = $user->getOption( 'watchlisttoken' );
1368  if ( $token == '' || !hash_equals( $token, $params['token'] ) ) {
1369  $this->dieUsage(
1370  'Incorrect watchlist token provided -- please set a correct token in Special:Preferences',
1371  'bad_wltoken'
1372  );
1373  }
1374  } else {
1375  if ( !$this->getUser()->isLoggedIn() ) {
1376  $this->dieUsage( 'You must be logged-in to have a watchlist', 'notloggedin' );
1377  }
1378  if ( !$this->getUser()->isAllowed( 'viewmywatchlist' ) ) {
1379  $this->dieUsage( 'You don\'t have permission to view your watchlist', 'permissiondenied' );
1380  }
1381  $user = $this->getUser();
1382  }
1383 
1384  return $user;
1385  }
1386 
1394  private static function escapeWikiText( $v ) {
1395  if ( is_array( $v ) ) {
1396  return array_map( 'self::escapeWikiText', $v );
1397  } else {
1398  return strtr( $v, [
1399  '__' => '_&#95;', '{' => '&#123;', '}' => '&#125;',
1400  '[[Category:' => '[[:Category:',
1401  '[[File:' => '[[:File:', '[[Image:' => '[[:Image:',
1402  ] );
1403  }
1404  }
1405 
1418  public static function makeMessage( $msg, IContextSource $context, array $params = null ) {
1419  if ( is_string( $msg ) ) {
1420  $msg = wfMessage( $msg );
1421  } elseif ( is_array( $msg ) ) {
1422  $msg = call_user_func_array( 'wfMessage', $msg );
1423  }
1424  if ( !$msg instanceof Message ) {
1425  return null;
1426  }
1427 
1428  $msg->setContext( $context );
1429  if ( $params ) {
1430  $msg->params( $params );
1431  }
1432 
1433  return $msg;
1434  }
1435 
1438  /************************************************************************/
1450  public function setWarning( $warning ) {
1451  $msg = new ApiRawMessage( $warning, 'warning' );
1452  $this->getErrorFormatter()->addWarning( $this->getModuleName(), $msg );
1453  }
1454 
1461  private function warnOrDie( $msg, $enforceLimits = false ) {
1462  if ( $enforceLimits ) {
1463  $this->dieUsage( $msg, 'integeroutofrange' );
1464  }
1465 
1466  $this->setWarning( $msg );
1467  }
1468 
1481  public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
1482  throw new UsageException(
1483  $description,
1484  $this->encodeParamName( $errorCode ),
1485  $httpRespCode,
1486  $extradata
1487  );
1488  }
1489 
1498  public function dieBlocked( Block $block ) {
1499  // Die using the appropriate message depending on block type
1500  if ( $block->getType() == Block::TYPE_AUTO ) {
1501  $this->dieUsage(
1502  'Your IP address has been blocked automatically, because it was used by a blocked user',
1503  'autoblocked',
1504  0,
1505  [ 'blockinfo' => ApiQueryUserInfo::getBlockInfo( $block ) ]
1506  );
1507  } else {
1508  $this->dieUsage(
1509  'You have been blocked from editing',
1510  'blocked',
1511  0,
1512  [ 'blockinfo' => ApiQueryUserInfo::getBlockInfo( $block ) ]
1513  );
1514  }
1515  }
1516 
1526  public function getErrorFromStatus( $status, &$extraData = null ) {
1527  if ( $status->isGood() ) {
1528  throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
1529  }
1530 
1531  $errors = $status->getErrorsByType( 'error' );
1532  if ( !$errors ) {
1533  // No errors? Assume the warnings should be treated as errors
1534  $errors = $status->getErrorsByType( 'warning' );
1535  }
1536  if ( !$errors ) {
1537  // Still no errors? Punt
1538  $errors = [ [ 'message' => 'unknownerror-nocode', 'params' => [] ] ];
1539  }
1540 
1541  // Cannot use dieUsageMsg() because extensions might return custom
1542  // error messages.
1543  if ( $errors[0]['message'] instanceof Message ) {
1544  $msg = $errors[0]['message'];
1545  if ( $msg instanceof IApiMessage ) {
1546  $extraData = $msg->getApiData();
1547  $code = $msg->getApiCode();
1548  } else {
1549  $code = $msg->getKey();
1550  }
1551  } else {
1552  $code = $errors[0]['message'];
1553  $msg = wfMessage( $code, $errors[0]['params'] );
1554  }
1555  if ( isset( ApiBase::$messageMap[$code] ) ) {
1556  // Translate message to code, for backwards compatibility
1557  $code = ApiBase::$messageMap[$code]['code'];
1558  }
1559 
1560  return [ $code, $msg->inLanguage( 'en' )->useDatabase( false )->plain() ];
1561  }
1562 
1570  public function dieStatus( $status ) {
1571  $extraData = null;
1572  list( $code, $msg ) = $this->getErrorFromStatus( $status, $extraData );
1573  $this->dieUsage( $msg, $code, 0, $extraData );
1574  }
1575 
1576  // @codingStandardsIgnoreStart Allow long lines. Cannot split these.
1580  public static $messageMap = [
1581  // This one MUST be present, or dieUsageMsg() will recurse infinitely
1582  'unknownerror' => [ 'code' => 'unknownerror', 'info' => "Unknown error: \"\$1\"" ],
1583  'unknownerror-nocode' => [ 'code' => 'unknownerror', 'info' => 'Unknown error' ],
1584 
1585  // Messages from Title::getUserPermissionsErrors()
1586  'ns-specialprotected' => [
1587  'code' => 'unsupportednamespace',
1588  'info' => "Pages in the Special namespace can't be edited"
1589  ],
1590  'protectedinterface' => [
1591  'code' => 'protectednamespace-interface',
1592  'info' => "You're not allowed to edit interface messages"
1593  ],
1594  'namespaceprotected' => [
1595  'code' => 'protectednamespace',
1596  'info' => "You're not allowed to edit pages in the \"\$1\" namespace"
1597  ],
1598  'customcssprotected' => [
1599  'code' => 'customcssprotected',
1600  'info' => "You're not allowed to edit custom CSS pages"
1601  ],
1602  'customjsprotected' => [
1603  'code' => 'customjsprotected',
1604  'info' => "You're not allowed to edit custom JavaScript pages"
1605  ],
1606  'cascadeprotected' => [
1607  'code' => 'cascadeprotected',
1608  'info' => "The page you're trying to edit is protected because it's included in a cascade-protected page"
1609  ],
1610  'protectedpagetext' => [
1611  'code' => 'protectedpage',
1612  'info' => "The \"\$1\" right is required to edit this page"
1613  ],
1614  'protect-cantedit' => [
1615  'code' => 'cantedit',
1616  'info' => "You can't protect this page because you can't edit it"
1617  ],
1618  'deleteprotected' => [
1619  'code' => 'cantedit',
1620  'info' => "You can't delete this page because it has been protected"
1621  ],
1622  'badaccess-group0' => [
1623  'code' => 'permissiondenied',
1624  'info' => 'Permission denied'
1625  ], // Generic permission denied message
1626  'badaccess-groups' => [
1627  'code' => 'permissiondenied',
1628  'info' => 'Permission denied'
1629  ],
1630  'titleprotected' => [
1631  'code' => 'protectedtitle',
1632  'info' => 'This title has been protected from creation'
1633  ],
1634  'nocreate-loggedin' => [
1635  'code' => 'cantcreate',
1636  'info' => "You don't have permission to create new pages"
1637  ],
1638  'nocreatetext' => [
1639  'code' => 'cantcreate-anon',
1640  'info' => "Anonymous users can't create new pages"
1641  ],
1642  'movenologintext' => [
1643  'code' => 'cantmove-anon',
1644  'info' => "Anonymous users can't move pages"
1645  ],
1646  'movenotallowed' => [
1647  'code' => 'cantmove',
1648  'info' => "You don't have permission to move pages"
1649  ],
1650  'confirmedittext' => [
1651  'code' => 'confirmemail',
1652  'info' => 'You must confirm your email address before you can edit'
1653  ],
1654  'blockedtext' => [
1655  'code' => 'blocked',
1656  'info' => 'You have been blocked from editing'
1657  ],
1658  'autoblockedtext' => [
1659  'code' => 'autoblocked',
1660  'info' => 'Your IP address has been blocked automatically, because it was used by a blocked user'
1661  ],
1662 
1663  // Miscellaneous interface messages
1664  'actionthrottledtext' => [
1665  'code' => 'ratelimited',
1666  'info' => "You've exceeded your rate limit. Please wait some time and try again"
1667  ],
1668  'alreadyrolled' => [
1669  'code' => 'alreadyrolled',
1670  'info' => 'The page you tried to rollback was already rolled back'
1671  ],
1672  'cantrollback' => [
1673  'code' => 'onlyauthor',
1674  'info' => 'The page you tried to rollback only has one author'
1675  ],
1676  'readonlytext' => [
1677  'code' => 'readonly',
1678  'info' => 'The wiki is currently in read-only mode'
1679  ],
1680  'sessionfailure' => [
1681  'code' => 'badtoken',
1682  'info' => 'Invalid token' ],
1683  'cannotdelete' => [
1684  'code' => 'cantdelete',
1685  'info' => "Couldn't delete \"\$1\". Maybe it was deleted already by someone else"
1686  ],
1687  'notanarticle' => [
1688  'code' => 'missingtitle',
1689  'info' => "The page you requested doesn't exist"
1690  ],
1691  'selfmove' => [ 'code' => 'selfmove', 'info' => "Can't move a page to itself"
1692  ],
1693  'immobile_namespace' => [
1694  'code' => 'immobilenamespace',
1695  'info' => 'You tried to move pages from or to a namespace that is protected from moving'
1696  ],
1697  'articleexists' => [
1698  'code' => 'articleexists',
1699  'info' => 'The destination article already exists and is not a redirect to the source article'
1700  ],
1701  'protectedpage' => [
1702  'code' => 'protectedpage',
1703  'info' => "You don't have permission to perform this move"
1704  ],
1705  'hookaborted' => [
1706  'code' => 'hookaborted',
1707  'info' => 'The modification you tried to make was aborted by an extension hook'
1708  ],
1709  'cantmove-titleprotected' => [
1710  'code' => 'protectedtitle',
1711  'info' => 'The destination article has been protected from creation'
1712  ],
1713  'imagenocrossnamespace' => [
1714  'code' => 'nonfilenamespace',
1715  'info' => "Can't move a file to a non-file namespace"
1716  ],
1717  'imagetypemismatch' => [
1718  'code' => 'filetypemismatch',
1719  'info' => "The new file extension doesn't match its type"
1720  ],
1721  // 'badarticleerror' => shouldn't happen
1722  // 'badtitletext' => shouldn't happen
1723  'ip_range_invalid' => [ 'code' => 'invalidrange', 'info' => 'Invalid IP range' ],
1724  'range_block_disabled' => [
1725  'code' => 'rangedisabled',
1726  'info' => 'Blocking IP ranges has been disabled'
1727  ],
1728  'nosuchusershort' => [
1729  'code' => 'nosuchuser',
1730  'info' => "The user you specified doesn't exist"
1731  ],
1732  'badipaddress' => [ 'code' => 'invalidip', 'info' => 'Invalid IP address specified' ],
1733  'ipb_expiry_invalid' => [ 'code' => 'invalidexpiry', 'info' => 'Invalid expiry time' ],
1734  'ipb_already_blocked' => [
1735  'code' => 'alreadyblocked',
1736  'info' => 'The user you tried to block was already blocked'
1737  ],
1738  'ipb_blocked_as_range' => [
1739  'code' => 'blockedasrange',
1740  'info' => "IP address \"\$1\" was blocked as part of range \"\$2\". You can't unblock the IP individually, but you can unblock the range as a whole."
1741  ],
1742  'ipb_cant_unblock' => [
1743  'code' => 'cantunblock',
1744  'info' => 'The block you specified was not found. It may have been unblocked already'
1745  ],
1746  'mailnologin' => [
1747  'code' => 'cantsend',
1748  'info' => 'You are not logged in, you do not have a confirmed email address, or you are not allowed to send email to other users, so you cannot send email'
1749  ],
1750  'ipbblocked' => [
1751  'code' => 'ipbblocked',
1752  'info' => 'You cannot block or unblock users while you are yourself blocked'
1753  ],
1754  'ipbnounblockself' => [
1755  'code' => 'ipbnounblockself',
1756  'info' => 'You are not allowed to unblock yourself'
1757  ],
1758  'usermaildisabled' => [
1759  'code' => 'usermaildisabled',
1760  'info' => 'User email has been disabled'
1761  ],
1762  'blockedemailuser' => [
1763  'code' => 'blockedfrommail',
1764  'info' => 'You have been blocked from sending email'
1765  ],
1766  'notarget' => [
1767  'code' => 'notarget',
1768  'info' => 'You have not specified a valid target for this action'
1769  ],
1770  'noemail' => [
1771  'code' => 'noemail',
1772  'info' => 'The user has not specified a valid email address, or has chosen not to receive email from other users'
1773  ],
1774  'rcpatroldisabled' => [
1775  'code' => 'patroldisabled',
1776  'info' => 'Patrolling is disabled on this wiki'
1777  ],
1778  'markedaspatrollederror-noautopatrol' => [
1779  'code' => 'noautopatrol',
1780  'info' => "You don't have permission to patrol your own changes"
1781  ],
1782  'delete-toobig' => [
1783  'code' => 'bigdelete',
1784  'info' => "You can't delete this page because it has more than \$1 revisions"
1785  ],
1786  'movenotallowedfile' => [
1787  'code' => 'cantmovefile',
1788  'info' => "You don't have permission to move files"
1789  ],
1790  'userrights-no-interwiki' => [
1791  'code' => 'nointerwikiuserrights',
1792  'info' => "You don't have permission to change user rights on other wikis"
1793  ],
1794  'userrights-nodatabase' => [
1795  'code' => 'nosuchdatabase',
1796  'info' => "Database \"\$1\" does not exist or is not local"
1797  ],
1798  'nouserspecified' => [ 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ],
1799  'noname' => [ 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ],
1800  'summaryrequired' => [ 'code' => 'summaryrequired', 'info' => 'Summary required' ],
1801  'import-rootpage-invalid' => [
1802  'code' => 'import-rootpage-invalid',
1803  'info' => 'Root page is an invalid title'
1804  ],
1805  'import-rootpage-nosubpage' => [
1806  'code' => 'import-rootpage-nosubpage',
1807  'info' => 'Namespace "$1" of the root page does not allow subpages'
1808  ],
1809 
1810  // API-specific messages
1811  'readrequired' => [
1812  'code' => 'readapidenied',
1813  'info' => 'You need read permission to use this module'
1814  ],
1815  'writedisabled' => [
1816  'code' => 'noapiwrite',
1817  'info' => "Editing of this wiki through the API is disabled. Make sure the \$wgEnableWriteAPI=true; statement is included in the wiki's LocalSettings.php file"
1818  ],
1819  'writerequired' => [
1820  'code' => 'writeapidenied',
1821  'info' => "You're not allowed to edit this wiki through the API"
1822  ],
1823  'missingparam' => [ 'code' => 'no$1', 'info' => "The \$1 parameter must be set" ],
1824  'invalidtitle' => [ 'code' => 'invalidtitle', 'info' => "Bad title \"\$1\"" ],
1825  'nosuchpageid' => [ 'code' => 'nosuchpageid', 'info' => "There is no page with ID \$1" ],
1826  'nosuchrevid' => [ 'code' => 'nosuchrevid', 'info' => "There is no revision with ID \$1" ],
1827  'nosuchuser' => [ 'code' => 'nosuchuser', 'info' => "User \"\$1\" doesn't exist" ],
1828  'invaliduser' => [ 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ],
1829  'invalidexpiry' => [ 'code' => 'invalidexpiry', 'info' => "Invalid expiry time \"\$1\"" ],
1830  'pastexpiry' => [ 'code' => 'pastexpiry', 'info' => "Expiry time \"\$1\" is in the past" ],
1831  'create-titleexists' => [
1832  'code' => 'create-titleexists',
1833  'info' => "Existing titles can't be protected with 'create'"
1834  ],
1835  'missingtitle-createonly' => [
1836  'code' => 'missingtitle-createonly',
1837  'info' => "Missing titles can only be protected with 'create'"
1838  ],
1839  'cantblock' => [ 'code' => 'cantblock',
1840  'info' => "You don't have permission to block users"
1841  ],
1842  'canthide' => [
1843  'code' => 'canthide',
1844  'info' => "You don't have permission to hide user names from the block log"
1845  ],
1846  'cantblock-email' => [
1847  'code' => 'cantblock-email',
1848  'info' => "You don't have permission to block users from sending email through the wiki"
1849  ],
1850  'unblock-notarget' => [
1851  'code' => 'notarget',
1852  'info' => 'Either the id or the user parameter must be set'
1853  ],
1854  'unblock-idanduser' => [
1855  'code' => 'idanduser',
1856  'info' => "The id and user parameters can't be used together"
1857  ],
1858  'cantunblock' => [
1859  'code' => 'permissiondenied',
1860  'info' => "You don't have permission to unblock users"
1861  ],
1862  'cannotundelete' => [
1863  'code' => 'cantundelete',
1864  'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already"
1865  ],
1866  'permdenied-undelete' => [
1867  'code' => 'permissiondenied',
1868  'info' => "You don't have permission to restore deleted revisions"
1869  ],
1870  'createonly-exists' => [
1871  'code' => 'articleexists',
1872  'info' => 'The article you tried to create has been created already'
1873  ],
1874  'nocreate-missing' => [
1875  'code' => 'missingtitle',
1876  'info' => "The article you tried to edit doesn't exist"
1877  ],
1878  'cantchangecontentmodel' => [
1879  'code' => 'cantchangecontentmodel',
1880  'info' => "You don't have permission to change the content model of a page"
1881  ],
1882  'nosuchrcid' => [
1883  'code' => 'nosuchrcid',
1884  'info' => "There is no change with rcid \"\$1\""
1885  ],
1886  'nosuchlogid' => [
1887  'code' => 'nosuchlogid',
1888  'info' => "There is no log entry with ID \"\$1\""
1889  ],
1890  'protect-invalidaction' => [
1891  'code' => 'protect-invalidaction',
1892  'info' => "Invalid protection type \"\$1\""
1893  ],
1894  'protect-invalidlevel' => [
1895  'code' => 'protect-invalidlevel',
1896  'info' => "Invalid protection level \"\$1\""
1897  ],
1898  'toofewexpiries' => [
1899  'code' => 'toofewexpiries',
1900  'info' => "\$1 expiry timestamps were provided where \$2 were needed"
1901  ],
1902  'cantimport' => [
1903  'code' => 'cantimport',
1904  'info' => "You don't have permission to import pages"
1905  ],
1906  'cantimport-upload' => [
1907  'code' => 'cantimport-upload',
1908  'info' => "You don't have permission to import uploaded pages"
1909  ],
1910  'importnofile' => [ 'code' => 'nofile', 'info' => "You didn't upload a file" ],
1911  'importuploaderrorsize' => [
1912  'code' => 'filetoobig',
1913  'info' => 'The file you uploaded is bigger than the maximum upload size'
1914  ],
1915  'importuploaderrorpartial' => [
1916  'code' => 'partialupload',
1917  'info' => 'The file was only partially uploaded'
1918  ],
1919  'importuploaderrortemp' => [
1920  'code' => 'notempdir',
1921  'info' => 'The temporary upload directory is missing'
1922  ],
1923  'importcantopen' => [
1924  'code' => 'cantopenfile',
1925  'info' => "Couldn't open the uploaded file"
1926  ],
1927  'import-noarticle' => [
1928  'code' => 'badinterwiki',
1929  'info' => 'Invalid interwiki title specified'
1930  ],
1931  'importbadinterwiki' => [
1932  'code' => 'badinterwiki',
1933  'info' => 'Invalid interwiki title specified'
1934  ],
1935  'import-unknownerror' => [
1936  'code' => 'import-unknownerror',
1937  'info' => "Unknown error on import: \"\$1\""
1938  ],
1939  'cantoverwrite-sharedfile' => [
1940  'code' => 'cantoverwrite-sharedfile',
1941  'info' => 'The target file exists on a shared repository and you do not have permission to override it'
1942  ],
1943  'sharedfile-exists' => [
1944  'code' => 'fileexists-sharedrepo-perm',
1945  'info' => 'The target file exists on a shared repository. Use the ignorewarnings parameter to override it.'
1946  ],
1947  'mustbeposted' => [
1948  'code' => 'mustbeposted',
1949  'info' => "The \$1 module requires a POST request"
1950  ],
1951  'show' => [
1952  'code' => 'show',
1953  'info' => 'Incorrect parameter - mutually exclusive values may not be supplied'
1954  ],
1955  'specialpage-cantexecute' => [
1956  'code' => 'specialpage-cantexecute',
1957  'info' => "You don't have permission to view the results of this special page"
1958  ],
1959  'invalidoldimage' => [
1960  'code' => 'invalidoldimage',
1961  'info' => 'The oldimage parameter has invalid format'
1962  ],
1963  'nodeleteablefile' => [
1964  'code' => 'nodeleteablefile',
1965  'info' => 'No such old version of the file'
1966  ],
1967  'fileexists-forbidden' => [
1968  'code' => 'fileexists-forbidden',
1969  'info' => 'A file with name "$1" already exists, and cannot be overwritten.'
1970  ],
1971  'fileexists-shared-forbidden' => [
1972  'code' => 'fileexists-shared-forbidden',
1973  'info' => 'A file with name "$1" already exists in the shared file repository, and cannot be overwritten.'
1974  ],
1975  'filerevert-badversion' => [
1976  'code' => 'filerevert-badversion',
1977  'info' => 'There is no previous local version of this file with the provided timestamp.'
1978  ],
1979 
1980  // ApiEditPage messages
1981  'noimageredirect-anon' => [
1982  'code' => 'noimageredirect-anon',
1983  'info' => "Anonymous users can't create image redirects"
1984  ],
1985  'noimageredirect-logged' => [
1986  'code' => 'noimageredirect',
1987  'info' => "You don't have permission to create image redirects"
1988  ],
1989  'spamdetected' => [
1990  'code' => 'spamdetected',
1991  'info' => "Your edit was refused because it contained a spam fragment: \"\$1\""
1992  ],
1993  'contenttoobig' => [
1994  'code' => 'contenttoobig',
1995  'info' => "The content you supplied exceeds the article size limit of \$1 kilobytes"
1996  ],
1997  'noedit-anon' => [ 'code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages" ],
1998  'noedit' => [ 'code' => 'noedit', 'info' => "You don't have permission to edit pages" ],
1999  'wasdeleted' => [
2000  'code' => 'pagedeleted',
2001  'info' => 'The page has been deleted since you fetched its timestamp'
2002  ],
2003  'blankpage' => [
2004  'code' => 'emptypage',
2005  'info' => 'Creating new, empty pages is not allowed'
2006  ],
2007  'editconflict' => [ 'code' => 'editconflict', 'info' => 'Edit conflict detected' ],
2008  'hashcheckfailed' => [ 'code' => 'badmd5', 'info' => 'The supplied MD5 hash was incorrect' ],
2009  'missingtext' => [
2010  'code' => 'notext',
2011  'info' => 'One of the text, appendtext, prependtext and undo parameters must be set'
2012  ],
2013  'emptynewsection' => [
2014  'code' => 'emptynewsection',
2015  'info' => 'Creating empty new sections is not possible.'
2016  ],
2017  'revwrongpage' => [
2018  'code' => 'revwrongpage',
2019  'info' => "r\$1 is not a revision of \"\$2\""
2020  ],
2021  'undo-failure' => [
2022  'code' => 'undofailure',
2023  'info' => 'Undo failed due to conflicting intermediate edits'
2024  ],
2025  'content-not-allowed-here' => [
2026  'code' => 'contentnotallowedhere',
2027  'info' => 'Content model "$1" is not allowed at title "$2"'
2028  ],
2029 
2030  // Messages from WikiPage::doEit(]
2031  'edit-hook-aborted' => [
2032  'code' => 'edit-hook-aborted',
2033  'info' => 'Your edit was aborted by an ArticleSave hook'
2034  ],
2035  'edit-gone-missing' => [
2036  'code' => 'edit-gone-missing',
2037  'info' => "The page you tried to edit doesn't seem to exist anymore"
2038  ],
2039  'edit-conflict' => [ 'code' => 'editconflict', 'info' => 'Edit conflict detected' ],
2040  'edit-already-exists' => [
2041  'code' => 'edit-already-exists',
2042  'info' => 'It seems the page you tried to create already exist'
2043  ],
2044 
2045  // uploadMsgs
2046  'invalid-file-key' => [ 'code' => 'invalid-file-key', 'info' => 'Not a valid file key' ],
2047  'nouploadmodule' => [ 'code' => 'nouploadmodule', 'info' => 'No upload module set' ],
2048  'uploaddisabled' => [
2049  'code' => 'uploaddisabled',
2050  'info' => 'Uploads are not enabled. Make sure $wgEnableUploads is set to true in LocalSettings.php and the PHP ini setting file_uploads is true'
2051  ],
2052  'copyuploaddisabled' => [
2053  'code' => 'copyuploaddisabled',
2054  'info' => 'Uploads by URL is not enabled. Make sure $wgAllowCopyUploads is set to true in LocalSettings.php.'
2055  ],
2056  'copyuploadbaddomain' => [
2057  'code' => 'copyuploadbaddomain',
2058  'info' => 'Uploads by URL are not allowed from this domain.'
2059  ],
2060  'copyuploadbadurl' => [
2061  'code' => 'copyuploadbadurl',
2062  'info' => 'Upload not allowed from this URL.'
2063  ],
2064 
2065  'filename-tooshort' => [
2066  'code' => 'filename-tooshort',
2067  'info' => 'The filename is too short'
2068  ],
2069  'filename-toolong' => [ 'code' => 'filename-toolong', 'info' => 'The filename is too long' ],
2070  'illegal-filename' => [
2071  'code' => 'illegal-filename',
2072  'info' => 'The filename is not allowed'
2073  ],
2074  'filetype-missing' => [
2075  'code' => 'filetype-missing',
2076  'info' => 'The file is missing an extension'
2077  ],
2078 
2079  'mustbeloggedin' => [ 'code' => 'mustbeloggedin', 'info' => 'You must be logged in to $1.' ]
2080  ];
2081  // @codingStandardsIgnoreEnd
2082 
2088  public function dieReadOnly() {
2089  $parsed = $this->parseMsg( [ 'readonlytext' ] );
2090  $this->dieUsage( $parsed['info'], $parsed['code'], /* http error */ 0,
2091  [ 'readonlyreason' => wfReadOnlyReason() ] );
2092  }
2093 
2099  public function dieUsageMsg( $error ) {
2100  # most of the time we send a 1 element, so we might as well send it as
2101  # a string and make this an array here.
2102  if ( is_string( $error ) ) {
2103  $error = [ $error ];
2104  }
2105  $parsed = $this->parseMsg( $error );
2106  $extraData = isset( $parsed['data'] ) ? $parsed['data'] : null;
2107  $this->dieUsage( $parsed['info'], $parsed['code'], 0, $extraData );
2108  }
2109 
2117  public function dieUsageMsgOrDebug( $error ) {
2118  if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
2119  $this->dieUsageMsg( $error );
2120  }
2121 
2122  if ( is_string( $error ) ) {
2123  $error = [ $error ];
2124  }
2125  $parsed = $this->parseMsg( $error );
2126  $this->setWarning( '$wgDebugAPI: ' . $parsed['code'] . ' - ' . $parsed['info'] );
2127  }
2128 
2136  protected function dieContinueUsageIf( $condition ) {
2137  if ( $condition ) {
2138  $this->dieUsage(
2139  'Invalid continue param. You should pass the original value returned by the previous query',
2140  'badcontinue' );
2141  }
2142  }
2143 
2149  public function parseMsg( $error ) {
2150  $error = (array)$error; // It seems strings sometimes make their way in here
2151  $key = array_shift( $error );
2152 
2153  // Check whether the error array was nested
2154  // array( array( <code>, <params> ), array( <another_code>, <params> ) )
2155  if ( is_array( $key ) ) {
2156  $error = $key;
2157  $key = array_shift( $error );
2158  }
2159 
2160  if ( $key instanceof IApiMessage ) {
2161  return [
2162  'code' => $key->getApiCode(),
2163  'info' => $key->inLanguage( 'en' )->useDatabase( false )->text(),
2164  'data' => $key->getApiData()
2165  ];
2166  }
2167 
2168  if ( isset( self::$messageMap[$key] ) ) {
2169  return [
2170  'code' => wfMsgReplaceArgs( self::$messageMap[$key]['code'], $error ),
2171  'info' => wfMsgReplaceArgs( self::$messageMap[$key]['info'], $error )
2172  ];
2173  }
2174 
2175  // If the key isn't present, throw an "unknown error"
2176  return $this->parseMsg( [ 'unknownerror', $key ] );
2177  }
2178 
2185  protected static function dieDebug( $method, $message ) {
2186  throw new MWException( "Internal error in $method: $message" );
2187  }
2188 
2194  protected function logFeatureUsage( $feature ) {
2195  $request = $this->getRequest();
2196  $s = '"' . addslashes( $feature ) . '"' .
2197  ' "' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) . '"' .
2198  ' "' . $request->getIP() . '"' .
2199  ' "' . addslashes( $request->getHeader( 'Referer' ) ) . '"' .
2200  ' "' . addslashes( $this->getMain()->getUserAgent() ) . '"';
2201  wfDebugLog( 'api-feature-usage', $s, 'private' );
2202  }
2203 
2206  /************************************************************************/
2216  protected function getDescriptionMessage() {
2217  return "apihelp-{$this->getModulePath()}-description";
2218  }
2219 
2227  public function getFinalDescription() {
2228  $desc = $this->getDescription();
2229  Hooks::run( 'APIGetDescription', [ &$this, &$desc ] );
2230  $desc = self::escapeWikiText( $desc );
2231  if ( is_array( $desc ) ) {
2232  $desc = implode( "\n", $desc );
2233  } else {
2234  $desc = (string)$desc;
2235  }
2236 
2237  $msg = ApiBase::makeMessage( $this->getDescriptionMessage(), $this->getContext(), [
2238  $this->getModulePrefix(),
2239  $this->getModuleName(),
2240  $this->getModulePath(),
2241  ] );
2242  if ( !$msg->exists() ) {
2243  $msg = $this->msg( 'api-help-fallback-description', $desc );
2244  }
2245  $msgs = [ $msg ];
2246 
2247  Hooks::run( 'APIGetDescriptionMessages', [ $this, &$msgs ] );
2248 
2249  return $msgs;
2250  }
2251 
2260  public function getFinalParams( $flags = 0 ) {
2261  $params = $this->getAllowedParams( $flags );
2262  if ( !$params ) {
2263  $params = [];
2264  }
2265 
2266  if ( $this->needsToken() ) {
2267  $params['token'] = [
2268  ApiBase::PARAM_TYPE => 'string',
2269  ApiBase::PARAM_REQUIRED => true,
2271  'api-help-param-token',
2272  $this->needsToken(),
2273  ],
2274  ] + ( isset( $params['token'] ) ? $params['token'] : [] );
2275  }
2276 
2277  Hooks::run( 'APIGetAllowedParams', [ &$this, &$params, $flags ] );
2278 
2279  return $params;
2280  }
2281 
2289  public function getFinalParamDescription() {
2290  $prefix = $this->getModulePrefix();
2291  $name = $this->getModuleName();
2292  $path = $this->getModulePath();
2293 
2294  $desc = $this->getParamDescription();
2295  Hooks::run( 'APIGetParamDescription', [ &$this, &$desc ] );
2296 
2297  if ( !$desc ) {
2298  $desc = [];
2299  }
2300  $desc = self::escapeWikiText( $desc );
2301 
2303  $msgs = [];
2304  foreach ( $params as $param => $settings ) {
2305  if ( !is_array( $settings ) ) {
2306  $settings = [];
2307  }
2308 
2309  $d = isset( $desc[$param] ) ? $desc[$param] : '';
2310  if ( is_array( $d ) ) {
2311  // Special handling for prop parameters
2312  $d = array_map( function ( $line ) {
2313  if ( preg_match( '/^\s+(\S+)\s+-\s+(.+)$/', $line, $m ) ) {
2314  $line = "\n;{$m[1]}:{$m[2]}";
2315  }
2316  return $line;
2317  }, $d );
2318  $d = implode( ' ', $d );
2319  }
2320 
2321  if ( isset( $settings[ApiBase::PARAM_HELP_MSG] ) ) {
2322  $msg = $settings[ApiBase::PARAM_HELP_MSG];
2323  } else {
2324  $msg = $this->msg( "apihelp-{$path}-param-{$param}" );
2325  if ( !$msg->exists() ) {
2326  $msg = $this->msg( 'api-help-fallback-parameter', $d );
2327  }
2328  }
2329  $msg = ApiBase::makeMessage( $msg, $this->getContext(),
2330  [ $prefix, $param, $name, $path ] );
2331  if ( !$msg ) {
2332  self::dieDebug( __METHOD__,
2333  'Value in ApiBase::PARAM_HELP_MSG is not valid' );
2334  }
2335  $msgs[$param] = [ $msg ];
2336 
2337  if ( isset( $settings[ApiBase::PARAM_HELP_MSG_PER_VALUE] ) ) {
2338  if ( !is_array( $settings[ApiBase::PARAM_HELP_MSG_PER_VALUE] ) ) {
2339  self::dieDebug( __METHOD__,
2340  'ApiBase::PARAM_HELP_MSG_PER_VALUE is not valid' );
2341  }
2342  if ( !is_array( $settings[ApiBase::PARAM_TYPE] ) ) {
2343  self::dieDebug( __METHOD__,
2344  'ApiBase::PARAM_HELP_MSG_PER_VALUE may only be used when ' .
2345  'ApiBase::PARAM_TYPE is an array' );
2346  }
2347 
2348  $valueMsgs = $settings[ApiBase::PARAM_HELP_MSG_PER_VALUE];
2349  foreach ( $settings[ApiBase::PARAM_TYPE] as $value ) {
2350  if ( isset( $valueMsgs[$value] ) ) {
2351  $msg = $valueMsgs[$value];
2352  } else {
2353  $msg = "apihelp-{$path}-paramvalue-{$param}-{$value}";
2354  }
2355  $m = ApiBase::makeMessage( $msg, $this->getContext(),
2356  [ $prefix, $param, $name, $path, $value ] );
2357  if ( $m ) {
2358  $m = new ApiHelpParamValueMessage(
2359  $value,
2360  [ $m->getKey(), 'api-help-param-no-description' ],
2361  $m->getParams()
2362  );
2363  $msgs[$param][] = $m->setContext( $this->getContext() );
2364  } else {
2365  self::dieDebug( __METHOD__,
2366  "Value in ApiBase::PARAM_HELP_MSG_PER_VALUE for $value is not valid" );
2367  }
2368  }
2369  }
2370 
2371  if ( isset( $settings[ApiBase::PARAM_HELP_MSG_APPEND] ) ) {
2372  if ( !is_array( $settings[ApiBase::PARAM_HELP_MSG_APPEND] ) ) {
2373  self::dieDebug( __METHOD__,
2374  'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
2375  }
2376  foreach ( $settings[ApiBase::PARAM_HELP_MSG_APPEND] as $m ) {
2377  $m = ApiBase::makeMessage( $m, $this->getContext(),
2378  [ $prefix, $param, $name, $path ] );
2379  if ( $m ) {
2380  $msgs[$param][] = $m;
2381  } else {
2382  self::dieDebug( __METHOD__,
2383  'Value in ApiBase::PARAM_HELP_MSG_APPEND is not valid' );
2384  }
2385  }
2386  }
2387  }
2388 
2389  Hooks::run( 'APIGetParamDescriptionMessages', [ $this, &$msgs ] );
2390 
2391  return $msgs;
2392  }
2393 
2403  protected function getHelpFlags() {
2404  $flags = [];
2405 
2406  if ( $this->isDeprecated() ) {
2407  $flags[] = 'deprecated';
2408  }
2409  if ( $this->isInternal() ) {
2410  $flags[] = 'internal';
2411  }
2412  if ( $this->isReadMode() ) {
2413  $flags[] = 'readrights';
2414  }
2415  if ( $this->isWriteMode() ) {
2416  $flags[] = 'writerights';
2417  }
2418  if ( $this->mustBePosted() ) {
2419  $flags[] = 'mustbeposted';
2420  }
2421 
2422  return $flags;
2423  }
2424 
2436  protected function getModuleSourceInfo() {
2437  global $IP;
2438 
2439  if ( $this->mModuleSource !== false ) {
2440  return $this->mModuleSource;
2441  }
2442 
2443  // First, try to find where the module comes from...
2444  $rClass = new ReflectionClass( $this );
2445  $path = $rClass->getFileName();
2446  if ( !$path ) {
2447  // No path known?
2448  $this->mModuleSource = null;
2449  return null;
2450  }
2451  $path = realpath( $path ) ?: $path;
2452 
2453  // Build map of extension directories to extension info
2454  if ( self::$extensionInfo === null ) {
2455  self::$extensionInfo = [
2456  realpath( __DIR__ ) ?: __DIR__ => [
2457  'path' => $IP,
2458  'name' => 'MediaWiki',
2459  'license-name' => 'GPL-2.0+',
2460  ],
2461  realpath( "$IP/extensions" ) ?: "$IP/extensions" => null,
2462  ];
2463  $keep = [
2464  'path' => null,
2465  'name' => null,
2466  'namemsg' => null,
2467  'license-name' => null,
2468  ];
2469  foreach ( $this->getConfig()->get( 'ExtensionCredits' ) as $group ) {
2470  foreach ( $group as $ext ) {
2471  if ( !isset( $ext['path'] ) || !isset( $ext['name'] ) ) {
2472  // This shouldn't happen, but does anyway.
2473  continue;
2474  }
2475 
2476  $extpath = $ext['path'];
2477  if ( !is_dir( $extpath ) ) {
2478  $extpath = dirname( $extpath );
2479  }
2480  self::$extensionInfo[realpath( $extpath ) ?: $extpath] =
2481  array_intersect_key( $ext, $keep );
2482  }
2483  }
2484  foreach ( ExtensionRegistry::getInstance()->getAllThings() as $ext ) {
2485  $extpath = $ext['path'];
2486  if ( !is_dir( $extpath ) ) {
2487  $extpath = dirname( $extpath );
2488  }
2489  self::$extensionInfo[realpath( $extpath ) ?: $extpath] =
2490  array_intersect_key( $ext, $keep );
2491  }
2492  }
2493 
2494  // Now traverse parent directories until we find a match or run out of
2495  // parents.
2496  do {
2497  if ( array_key_exists( $path, self::$extensionInfo ) ) {
2498  // Found it!
2499  $this->mModuleSource = self::$extensionInfo[$path];
2500  return $this->mModuleSource;
2501  }
2502 
2503  $oldpath = $path;
2504  $path = dirname( $path );
2505  } while ( $path !== $oldpath );
2506 
2507  // No idea what extension this might be.
2508  $this->mModuleSource = null;
2509  return null;
2510  }
2511 
2523  public function modifyHelp( array &$help, array $options, array &$tocData ) {
2524  }
2525 
2528  /************************************************************************/
2542  protected function getDescription() {
2543  return false;
2544  }
2545 
2558  protected function getParamDescription() {
2559  return [];
2560  }
2561 
2578  protected function getExamples() {
2579  return false;
2580  }
2581 
2587  public function makeHelpMsg() {
2588  wfDeprecated( __METHOD__, '1.25' );
2589  static $lnPrfx = "\n ";
2590 
2591  $msg = $this->getFinalDescription();
2592 
2593  if ( $msg !== false ) {
2594 
2595  if ( !is_array( $msg ) ) {
2596  $msg = [
2597  $msg
2598  ];
2599  }
2600  $msg = $lnPrfx . implode( $lnPrfx, $msg ) . "\n";
2601 
2602  $msg .= $this->makeHelpArrayToString( $lnPrfx, false, $this->getHelpUrls() );
2603 
2604  if ( $this->isReadMode() ) {
2605  $msg .= "\nThis module requires read rights";
2606  }
2607  if ( $this->isWriteMode() ) {
2608  $msg .= "\nThis module requires write rights";
2609  }
2610  if ( $this->mustBePosted() ) {
2611  $msg .= "\nThis module only accepts POST requests";
2612  }
2613  if ( $this->isReadMode() || $this->isWriteMode() ||
2614  $this->mustBePosted()
2615  ) {
2616  $msg .= "\n";
2617  }
2618 
2619  // Parameters
2620  $paramsMsg = $this->makeHelpMsgParameters();
2621  if ( $paramsMsg !== false ) {
2622  $msg .= "Parameters:\n$paramsMsg";
2623  }
2624 
2625  $examples = $this->getExamples();
2626  if ( $examples ) {
2627  if ( !is_array( $examples ) ) {
2628  $examples = [
2629  $examples
2630  ];
2631  }
2632  $msg .= 'Example' . ( count( $examples ) > 1 ? 's' : '' ) . ":\n";
2633  foreach ( $examples as $k => $v ) {
2634  if ( is_numeric( $k ) ) {
2635  $msg .= " $v\n";
2636  } else {
2637  if ( is_array( $v ) ) {
2638  $msgExample = implode( "\n", array_map( [ $this, 'indentExampleText' ], $v ) );
2639  } else {
2640  $msgExample = " $v";
2641  }
2642  $msgExample .= ':';
2643  $msg .= wordwrap( $msgExample, 100, "\n" ) . "\n $k\n";
2644  }
2645  }
2646  }
2647  }
2648 
2649  return $msg;
2650  }
2651 
2657  private function indentExampleText( $item ) {
2658  return ' ' . $item;
2659  }
2660 
2668  protected function makeHelpArrayToString( $prefix, $title, $input ) {
2669  wfDeprecated( __METHOD__, '1.25' );
2670  if ( $input === false ) {
2671  return '';
2672  }
2673  if ( !is_array( $input ) ) {
2674  $input = [ $input ];
2675  }
2676 
2677  if ( count( $input ) > 0 ) {
2678  if ( $title ) {
2679  $msg = $title . ( count( $input ) > 1 ? 's' : '' ) . ":\n ";
2680  } else {
2681  $msg = ' ';
2682  }
2683  $msg .= implode( $prefix, $input ) . "\n";
2684 
2685  return $msg;
2686  }
2687 
2688  return '';
2689  }
2690 
2697  public function makeHelpMsgParameters() {
2698  wfDeprecated( __METHOD__, '1.25' );
2700  if ( $params ) {
2701  $paramsDescription = $this->getFinalParamDescription();
2702  $msg = '';
2703  $paramPrefix = "\n" . str_repeat( ' ', 24 );
2704  $descWordwrap = "\n" . str_repeat( ' ', 28 );
2705  foreach ( $params as $paramName => $paramSettings ) {
2706  $desc = isset( $paramsDescription[$paramName] ) ? $paramsDescription[$paramName] : '';
2707  if ( is_array( $desc ) ) {
2708  $desc = implode( $paramPrefix, $desc );
2709  }
2710 
2711  // handle shorthand
2712  if ( !is_array( $paramSettings ) ) {
2713  $paramSettings = [
2714  self::PARAM_DFLT => $paramSettings,
2715  ];
2716  }
2717 
2718  // handle missing type
2719  if ( !isset( $paramSettings[ApiBase::PARAM_TYPE] ) ) {
2720  $dflt = isset( $paramSettings[ApiBase::PARAM_DFLT] )
2721  ? $paramSettings[ApiBase::PARAM_DFLT]
2722  : null;
2723  if ( is_bool( $dflt ) ) {
2724  $paramSettings[ApiBase::PARAM_TYPE] = 'boolean';
2725  } elseif ( is_string( $dflt ) || is_null( $dflt ) ) {
2726  $paramSettings[ApiBase::PARAM_TYPE] = 'string';
2727  } elseif ( is_int( $dflt ) ) {
2728  $paramSettings[ApiBase::PARAM_TYPE] = 'integer';
2729  }
2730  }
2731 
2732  if ( isset( $paramSettings[self::PARAM_DEPRECATED] )
2733  && $paramSettings[self::PARAM_DEPRECATED]
2734  ) {
2735  $desc = "DEPRECATED! $desc";
2736  }
2737 
2738  if ( isset( $paramSettings[self::PARAM_REQUIRED] )
2739  && $paramSettings[self::PARAM_REQUIRED]
2740  ) {
2741  $desc .= $paramPrefix . 'This parameter is required';
2742  }
2743 
2744  $type = isset( $paramSettings[self::PARAM_TYPE] )
2745  ? $paramSettings[self::PARAM_TYPE]
2746  : null;
2747  if ( isset( $type ) ) {
2748  $hintPipeSeparated = true;
2749  $multi = isset( $paramSettings[self::PARAM_ISMULTI] )
2750  ? $paramSettings[self::PARAM_ISMULTI]
2751  : false;
2752  if ( $multi ) {
2753  $prompt = 'Values (separate with \'|\'): ';
2754  } else {
2755  $prompt = 'One value: ';
2756  }
2757 
2758  if ( $type === 'submodule' ) {
2759  if ( isset( $paramSettings[self::PARAM_SUBMODULE_MAP] ) ) {
2760  $type = array_keys( $paramSettings[self::PARAM_SUBMODULE_MAP] );
2761  } else {
2762  $type = $this->getModuleManager()->getNames( $paramName );
2763  }
2764  sort( $type );
2765  }
2766  if ( is_array( $type ) ) {
2767  $choices = [];
2768  $nothingPrompt = '';
2769  foreach ( $type as $t ) {
2770  if ( $t === '' ) {
2771  $nothingPrompt = 'Can be empty, or ';
2772  } else {
2773  $choices[] = $t;
2774  }
2775  }
2776  $desc .= $paramPrefix . $nothingPrompt . $prompt;
2777  $choicesstring = implode( ', ', $choices );
2778  $desc .= wordwrap( $choicesstring, 100, $descWordwrap );
2779  $hintPipeSeparated = false;
2780  } else {
2781  switch ( $type ) {
2782  case 'namespace':
2783  // Special handling because namespaces are
2784  // type-limited, yet they are not given
2785  $desc .= $paramPrefix . $prompt;
2786  $desc .= wordwrap( implode( ', ', MWNamespace::getValidNamespaces() ),
2787  100, $descWordwrap );
2788  $hintPipeSeparated = false;
2789  break;
2790  case 'limit':
2791  $desc .= $paramPrefix . "No more than {$paramSettings[self::PARAM_MAX]}";
2792  if ( isset( $paramSettings[self::PARAM_MAX2] ) ) {
2793  $desc .= " ({$paramSettings[self::PARAM_MAX2]} for bots)";
2794  }
2795  $desc .= ' allowed';
2796  break;
2797  case 'integer':
2798  $s = $multi ? 's' : '';
2799  $hasMin = isset( $paramSettings[self::PARAM_MIN] );
2800  $hasMax = isset( $paramSettings[self::PARAM_MAX] );
2801  if ( $hasMin || $hasMax ) {
2802  if ( !$hasMax ) {
2803  $intRangeStr = "The value$s must be no less than " .
2804  "{$paramSettings[self::PARAM_MIN]}";
2805  } elseif ( !$hasMin ) {
2806  $intRangeStr = "The value$s must be no more than " .
2807  "{$paramSettings[self::PARAM_MAX]}";
2808  } else {
2809  $intRangeStr = "The value$s must be between " .
2810  "{$paramSettings[self::PARAM_MIN]} and {$paramSettings[self::PARAM_MAX]}";
2811  }
2812 
2813  $desc .= $paramPrefix . $intRangeStr;
2814  }
2815  break;
2816  case 'upload':
2817  $desc .= $paramPrefix . 'Must be posted as a file upload using multipart/form-data';
2818  break;
2819  }
2820  }
2821 
2822  if ( $multi ) {
2823  if ( $hintPipeSeparated ) {
2824  $desc .= $paramPrefix . "Separate values with '|'";
2825  }
2826 
2827  $isArray = is_array( $type );
2828  if ( !$isArray
2829  || $isArray && count( $type ) > self::LIMIT_SML1
2830  ) {
2831  $desc .= $paramPrefix . 'Maximum number of values ' .
2832  self::LIMIT_SML1 . ' (' . self::LIMIT_SML2 . ' for bots)';
2833  }
2834  }
2835  }
2836 
2837  $default = isset( $paramSettings[self::PARAM_DFLT] ) ? $paramSettings[self::PARAM_DFLT] : null;
2838  if ( !is_null( $default ) && $default !== false ) {
2839  $desc .= $paramPrefix . "Default: $default";
2840  }
2841 
2842  $msg .= sprintf( " %-19s - %s\n", $this->encodeParamName( $paramName ), $desc );
2843  }
2844 
2845  return $msg;
2846  }
2847 
2848  return false;
2849  }
2850 
2856  public function getModuleProfileName( $db = false ) {
2857  wfDeprecated( __METHOD__, '1.25' );
2858  return '';
2859  }
2860 
2864  public function profileIn() {
2865  // No wfDeprecated() yet because extensions call this and might need to
2866  // keep doing so for BC.
2867  }
2868 
2872  public function profileOut() {
2873  // No wfDeprecated() yet because extensions call this and might need to
2874  // keep doing so for BC.
2875  }
2876 
2880  public function safeProfileOut() {
2881  wfDeprecated( __METHOD__, '1.25' );
2882  }
2883 
2888  public function getProfileTime() {
2889  wfDeprecated( __METHOD__, '1.25' );
2890  return 0;
2891  }
2892 
2896  public function profileDBIn() {
2897  wfDeprecated( __METHOD__, '1.25' );
2898  }
2899 
2903  public function profileDBOut() {
2904  wfDeprecated( __METHOD__, '1.25' );
2905  }
2906 
2911  public function getProfileDBTime() {
2912  wfDeprecated( __METHOD__, '1.25' );
2913  return 0;
2914  }
2915 
2921  public function getResultData() {
2922  wfDeprecated( __METHOD__, '1.25' );
2923  return $this->getResult()->getData();
2924  }
2925 
2930  protected function useTransactionalTimeLimit() {
2931  if ( $this->getRequest()->wasPosted() ) {
2933  }
2934  }
2935 
2937 }
2938 
static newFromName($name, $validate= 'valid')
Static factory method for creation from username.
Definition: User.php:568
dieUsageMsgOrDebug($error)
Will only set a warning instead of failing if the global $wgDebugAPI is set to true.
Definition: ApiBase.php:2117
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
Definition: WikiPage.php:99
setContext(IContextSource $context)
Set the IContextSource object.
const PARAM_VALUE_LINKS
(string[]) When PARAM_TYPE is an array, this may be an array mapping those values to page titles whic...
Definition: ApiBase.php:149
getFinalParamDescription()
Get final parameter descriptions, after hooks have had a chance to tweak it as needed.
Definition: ApiBase.php:2289
const PARAM_TYPE
(string|string[]) Either an array of allowed value strings, or a string type as described below...
Definition: ApiBase.php:88
getErrorFormatter()
Get the error formatter.
Definition: ApiBase.php:591
const LIMIT_BIG2
Fast query, apihighlimits limit.
Definition: ApiBase.php:179
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
Interface for objects which can provide a MediaWiki context on request.
wfGetDB($db, $groups=[], $wiki=false)
Get a Database object.
profileDBOut()
Definition: ApiBase.php:2903
isReadMode()
Indicates whether this module requires read rights.
Definition: ApiBase.php:356
the array() calling protocol came about after MediaWiki 1.4rc1.
validateTimestamp($value, $encParamName)
Validate and normalize of parameters of type 'timestamp'.
Definition: ApiBase.php:1231
getResult()
Get the result object.
Definition: ApiBase.php:577
static $messageMap
Array that maps message keys to error messages.
Definition: ApiBase.php:1580
getWatchlistUser($params)
Gets the user for whom to get the watchlist.
Definition: ApiBase.php:1361
magic word the default is to use $key to get the and $key value or $key value text $key value html to format the value $key
Definition: hooks.txt:2321
Message subclass that prepends wikitext for API help.
getParameter($paramName, $parseLimit=true)
Get a value for the given parameter.
Definition: ApiBase.php:702
getDescriptionMessage()
Return the description message.
Definition: ApiBase.php:2216
getModuleProfileName($db=false)
Definition: ApiBase.php:2856
getModuleSourceInfo()
Returns information about the source of this module, if known.
Definition: ApiBase.php:2436
$IP
Definition: WebStart.php:58
getCustomPrinter()
If the module may only be used with a certain format module, it should override this method to return...
Definition: ApiBase.php:260
static array $extensionInfo
Maps extension paths to info arrays.
Definition: ApiBase.php:193
requireMaxOneParameter($params, $required)
Die if more than one of a certain set of parameters is set and not false.
Definition: ApiBase.php:740
useTransactionalTimeLimit()
Call wfTransactionalTimeLimit() if this request was POSTed.
Definition: ApiBase.php:2930
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses & $ret
Definition: hooks.txt:1798
getMain()
Get the main module.
Definition: ApiBase.php:473
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
Definition: ApiBase.php:50
The simplest way of implementing IContextSource is to hold a RequestContext as a member variable and ...
static escapeWikiText($v)
A subset of wfEscapeWikiText for BC texts.
Definition: ApiBase.php:1394
getType()
Get the type of target for this particular block.
Definition: Block.php:1354
const GET_VALUES_FOR_HELP
getAllowedParams() flag: When set, the result could take longer to generate, but should be more thoro...
Definition: ApiBase.php:190
const LIMIT_BIG1
Fast query, standard limit.
Definition: ApiBase.php:177
safeProfileOut()
Definition: ApiBase.php:2880
getDB()
Gets a default slave database connection object.
Definition: ApiBase.php:605
getResultData()
Get the result data array (read-only)
Definition: ApiBase.php:2921
const PARAM_MAX
(integer) Max value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'.
Definition: ApiBase.php:91
setWatch($watch, $titleObj, $userOption=null)
Set a watch (or unwatch) based the based on a watchlist parameter.
Definition: ApiBase.php:1330
const PARAM_REQUIRED
(boolean) Is the parameter required?
Definition: ApiBase.php:112
ApiMain $mMainModule
Definition: ApiBase.php:196
getWatchlistValue($watchlist, $titleObj, $userOption=null)
Return true if we're to watch the page, false if not, null if no change.
Definition: ApiBase.php:837
const PARAM_HELP_MSG_INFO
(array) Specify additional information tags for the parameter.
Definition: ApiBase.php:142
lacksSameOriginSecurity()
Returns true if the current request breaks the same-origin policy.
Definition: ApiBase.php:505
extractRequestParams($parseLimit=true)
Using getAllowedParams(), this function makes an array of the values provided by the user...
Definition: ApiBase.php:678
This code would result in ircNotify being run twice when an article is and once for brion Hooks can return three possible true was required This is the default since MediaWiki *some string
Definition: hooks.txt:177
$value
getParent()
Get the parent of this module.
Definition: ApiBase.php:491
requireOnlyOneParameter($params, $required)
Die if none or more than one of a certain set of parameters is set and not false. ...
Definition: ApiBase.php:714
static makeMessage($msg, IContextSource $context, array $params=null)
Create a Message from a string or array.
Definition: ApiBase.php:1418
it s the revision text itself In either if gzip is the revision text is gzipped $flags
Definition: hooks.txt:2548
const PARAM_HELP_MSG_PER_VALUE
((string|array|Message)[]) When PARAM_TYPE is an array, this is an array mapping those values to $msg...
Definition: ApiBase.php:157
Interface for messages with machine-readable data for use by the API.
Definition: ApiMessage.php:35
wfUrlencode($s)
We want some things to be included as literal characters in our title URLs for prettiness, which urlencode encodes by default.
static newFromText($text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:277
isDeprecated()
Indicates whether this module is deprecated.
Definition: ApiBase.php:381
when a variable name is used in a it is silently declared as a new local masking the global
Definition: design.txt:93
getHelpUrls()
Return links to more detailed help pages about the module.
Definition: ApiBase.php:322
string $mModuleName
Definition: ApiBase.php:198
needsToken()
Returns the token type this module requires in order to execute.
Definition: ApiBase.php:413
IContextSource $context
indentExampleText($item)
Definition: ApiBase.php:2657
getConditionalRequestData($condition)
Returns data for HTTP conditional request mechanisms.
Definition: ApiBase.php:442
getParameterFromSettings($paramName, $paramSettings, $parseLimit)
Using the settings determine the value for the given parameter.
Definition: ApiBase.php:879
static getBlockInfo(Block $block)
Get basic info about a given block.
wfTimestamp($outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
getRequest()
Get the WebRequest object.
wfMsgReplaceArgs($message, $args)
Replace message parameter keys on the given formatted output.
const PARAM_HELP_MSG_APPEND
((string|array|Message)[]) Specify additional i18n messages to append to the normal message for this ...
Definition: ApiBase.php:132
wfDebugLog($logGroup, $text, $dest= 'all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not...
getTitleOrPageId($params, $load=false)
Get a WikiPage object from a title or pageid param, if possible.
Definition: ApiBase.php:800
msg()
Get a Message object with context set Parameters are the same as wfMessage()
const PARAM_SUBMODULE_PARAM_PREFIX
(string) When PARAM_TYPE is 'submodule', used to indicate the 'g' prefix added by ApiQueryGeneratorBa...
Definition: ApiBase.php:172
static truncateArray(&$arr, $limit)
Truncate an array to a certain length.
Definition: ApiBase.php:1345
profileOut()
Definition: ApiBase.php:2872
validateToken($token, array $params)
Validate the supplied token.
Definition: ApiBase.php:1270
parameterNotEmpty($x)
Callback function used in requireOnlyOneParameter to check whether required parameters are set...
Definition: ApiBase.php:785
getProfileTime()
Definition: ApiBase.php:2888
getErrorFromStatus($status, &$extraData=null)
Get error (as code, string) from a Status object.
Definition: ApiBase.php:1526
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context $options
Definition: hooks.txt:1004
getHelpFlags()
Generates the list of flags for the help screen and for action=paraminfo.
Definition: ApiBase.php:2403
const PARAM_RANGE_ENFORCE
(boolean) For PARAM_TYPE 'integer', enforce PARAM_MIN and PARAM_MAX?
Definition: ApiBase.php:118
getProfileDBTime()
Definition: ApiBase.php:2911
getModulePath()
Get the path to this module.
Definition: ApiBase.php:521
getContinuationManager()
Get the continuation manager.
Definition: ApiBase.php:617
getConfig()
Get the Config object.
const LIMIT_SML2
Slow query, apihighlimits limit.
Definition: ApiBase.php:183
const PARAM_SUBMODULE_MAP
(string[]) When PARAM_TYPE is 'submodule', map parameter values to submodule paths.
Definition: ApiBase.php:165
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 an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses after processing after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock()-offset Set to overwrite offset parameter in $wgRequest set to ''to unsetoffset-wrap String Wrap the message in html(usually something like"&lt
getContext()
Get the base IContextSource object.
const IGNORE_USER_RIGHTS
Definition: User.php:84
$params
This is the main API class, used for both external and internal processing.
Definition: ApiMain.php:41
validateUser($value, $encParamName)
Validate and normalize of parameters of type 'user'.
Definition: ApiBase.php:1305
wfDeprecated($function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
isInternal()
Indicates whether this module is "internal" Internal API modules are not (yet) intended for 3rd party...
Definition: ApiBase.php:391
static makeTitleSafe($ns, $title, $fragment= '', $interwiki= '')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:548
const DB_SLAVE
Definition: Defines.php:46
setContext(IContextSource $context)
Set the language and the title from a context object.
Definition: Message.php:678
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:912
dynamicParameterDocumentation()
Indicate if the module supports dynamically-determined parameters that cannot be included in self::ge...
Definition: ApiBase.php:655
getModuleName()
Get the name of the module being executed by this instance.
Definition: ApiBase.php:457
static dieReadOnly()
Helper function for readonly errors.
Definition: ApiBase.php:2088
static run($event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:131
$help
Definition: mcc.php:32
const PARAM_MAX2
(integer) Max value allowed for the parameter for users with the apihighlimits right, for PARAM_TYPE 'limit'.
Definition: ApiBase.php:97
string $mModulePrefix
Definition: ApiBase.php:198
const TYPE_AUTO
Definition: Block.php:78
setWarning($warning)
Set warning section for this module.
Definition: ApiBase.php:1450
modifyHelp(array &$help, array $options, array &$tocData)
Called from ApiHelp before the pieces are joined together and returned.
Definition: ApiBase.php:2523
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable & $code
Definition: hooks.txt:762
dieContinueUsageIf($condition)
Die with the $prefix.
Definition: ApiBase.php:2136
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter...
Definition: ApiBase.php:125
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
const TS_MW
MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
const LIMIT_SML1
Slow query, standard limit.
Definition: ApiBase.php:181
getModuleManager()
Get the module manager, or null if this module has no sub-modules.
Definition: ApiBase.php:247
static getTokenTypeSalts()
Get the salts for known token types.
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
mustBePosted()
Indicates whether this module must be called with a POST request.
Definition: ApiBase.php:372
error also a ContextSource you ll probably need to make sure the header is varied on $request
Definition: hooks.txt:2418
wfReadOnlyReason()
Check if the site is in read-only mode and return the message if so.
getModulePrefix()
Get parameter prefix (usually two letters or an empty string).
Definition: ApiBase.php:465
validateLimit($paramName, &$value, $min, $max, $botMax=null, $enforceLimits=false)
Validate the value against the minimum and user/bot maximum limits.
Definition: ApiBase.php:1192
getDescription()
Returns the description string for this module.
Definition: ApiBase.php:2542
parseMultiValue($valueName, $value, $allowMultiple, $allowedValues)
Return an array of values that were given in a 'a|b|c' notation, after it optionally validates them a...
Definition: ApiBase.php:1128
static getToken(User $user, MediaWiki\Session\Session $session, $salt)
Get a token from a salt.
getFinalDescription()
Get final module description, after hooks have had a chance to tweak it as needed.
Definition: ApiBase.php:2227
$line
Definition: cdb.php:59
requireAtLeastOneParameter($params, $required)
Die if none of a certain set of parameters is set and not false.
Definition: ApiBase.php:763
makeHelpMsg()
Generates help message for this module, or false if there is no description.
Definition: ApiBase.php:2587
const PARAM_ISMULTI
(boolean) Accept multiple pipe-separated values for this parameter (e.g.
Definition: ApiBase.php:53
__construct(ApiMain $mainModule, $moduleName, $modulePrefix= '')
Definition: ApiBase.php:209
wfTransactionalTimeLimit()
Set PHP's time limit to the larger of php.ini or $wgTransactionalTimeLimit.
dieUsage($description, $errorCode, $httpRespCode=0, $extradata=null)
Throw a UsageException, which will (if uncaught) call the main module's error handler and die with an...
Definition: ApiBase.php:1481
this 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 the output can only depend on parameters provided to this hook not on global state indicating whether full HTML should be generated If generation of HTML may be but other information should still be present in the ParserOutput object to manipulate or replace but no entry for that model exists in $wgContentHandlers if desired whether it is OK to use $contentModel on $title Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok inclusive $limit
Definition: hooks.txt:1004
getExamples()
Returns usage examples for this module.
Definition: ApiBase.php:2578
profileIn()
Definition: ApiBase.php:2864
dieBlocked(Block $block)
Throw a UsageException, which will (if uncaught) call the main module's error handler and die with an...
Definition: ApiBase.php:1498
$mParamCache
Definition: ApiBase.php:200
static newFromID($id, $from= 'fromdb')
Constructor from a page id.
Definition: WikiPage.php:132
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 $status
Definition: hooks.txt:1004
Extension of RawMessage implementing IApiMessage.
Definition: ApiMessage.php:171
This abstract class implements many basic API functions, and is the base of all API classes...
Definition: ApiBase.php:39
$count
execute()
Evaluates the parameters, performs the requested query, and sets up the result.
getWebUITokenSalt(array $params)
Fetch the salt used in the Web UI corresponding to this module.
Definition: ApiBase.php:426
const PARAM_DEPRECATED
(boolean) Is the parameter deprecated (will show a warning)?
Definition: ApiBase.php:106
array null bool $mModuleSource
Definition: ApiBase.php:202
getParamDescription()
Returns an array of parameter descriptions.
Definition: ApiBase.php:2558
static canAddTagsAccompanyingChange(array $tags, User $user=null)
Is it OK to allow the user to apply all the specified tags at the same time as they edit/make the cha...
Definition: ChangeTags.php:378
const TS_UNIX
Unix time - the number of seconds since 1970-01-01 00:00:00 UTC.
getExamplesMessages()
Returns usage examples for this module.
Definition: ApiBase.php:275
parseMsg($error)
Return the error message related to a certain array.
Definition: ApiBase.php:2149
profileDBIn()
Definition: ApiBase.php:2896
makeHelpMsgParameters()
Generates the parameter descriptions for this module, to be displayed in the module's help...
Definition: ApiBase.php:2697
const PARAM_MIN
(integer) Lowest value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'.
Definition: ApiBase.php:100
static dieDebug($method, $message)
Internal code errors should be reported with this method.
Definition: ApiBase.php:2185
logFeatureUsage($feature)
Write logging information for API features to a debug log, for usage analysis.
Definition: ApiBase.php:2194
static doWatchOrUnwatch($watch, Title $title, User $user)
Watch or unwatch a page.
Definition: WatchAction.php:83
dieStatus($status)
Throw a UsageException based on the errors in the Status object.
Definition: ApiBase.php:1570
shouldCheckMaxlag()
Indicates if this module needs maxlag to be checked.
Definition: ApiBase.php:348
static getValidNamespaces()
Returns an array of the namespaces (by integer id) that exist on the wiki.
encodeParamName($paramName)
This method mangles parameter name based on the prefix supplied to the constructor.
Definition: ApiBase.php:665
setContinuationManager($manager)
Set the continuation manager.
Definition: ApiBase.php:631
warnOrDie($msg, $enforceLimits=false)
Adds a warning to the output, else dies.
Definition: ApiBase.php:1461
Definition: Block.php:22
getUser()
Get the User object.
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached one of or reset my talk my contributions etc etc otherwise the built in rate limiting checks are if enabled allows for interception of redirect as a string mapping parameter names to values & $type
Definition: hooks.txt:2338
dieUsageMsg($error)
Output the error message related to a certain array.
Definition: ApiBase.php:2099
const PARAM_ALLOW_DUPLICATES
(boolean) Allow the same value to be set more than once when PARAM_ISMULTI is true?
Definition: ApiBase.php:103
getModuleFromPath($path)
Get a module from its module path.
Definition: ApiBase.php:539
This exception will be thrown when dieUsage is called to stop module execution.
Definition: ApiMain.php:1876
getFinalParams($flags=0)
Get final list of parameters, after hooks have had a chance to tweak it as needed.
Definition: ApiBase.php:2260
isMain()
Returns true if this module is the main module ($this === $this->mMainModule), false otherwise...
Definition: ApiBase.php:482
isWriteMode()
Indicates whether this module requires write mode.
Definition: ApiBase.php:364
makeHelpArrayToString($prefix, $title, $input)
Definition: ApiBase.php:2668
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:310
getAllowedParams()
Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (ar...
Definition: ApiBase.php:338