MediaWiki  1.27.2
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 
179  const PARAM_SENSITIVE = 17;
180 
184  const LIMIT_BIG1 = 500;
186  const LIMIT_BIG2 = 5000;
188  const LIMIT_SML1 = 50;
190  const LIMIT_SML2 = 500;
191 
198 
200  private static $extensionInfo = null;
201 
203  private $mMainModule;
206  private $mSlaveDB = null;
207  private $mParamCache = [];
209  private $mModuleSource = false;
210 
216  public function __construct( ApiMain $mainModule, $moduleName, $modulePrefix = '' ) {
217  $this->mMainModule = $mainModule;
218  $this->mModuleName = $moduleName;
219  $this->mModulePrefix = $modulePrefix;
220 
221  if ( !$this->isMain() ) {
222  $this->setContext( $mainModule->getContext() );
223  }
224  }
225 
226  /************************************************************************/
247  abstract public function execute();
248 
254  public function getModuleManager() {
255  return null;
256  }
257 
267  public function getCustomPrinter() {
268  return null;
269  }
270 
282  protected function getExamplesMessages() {
283  // Fall back to old non-localised method
284  $ret = [];
285 
286  $examples = $this->getExamples();
287  if ( $examples ) {
288  if ( !is_array( $examples ) ) {
289  $examples = [ $examples ];
290  } elseif ( $examples && ( count( $examples ) & 1 ) == 0 &&
291  array_keys( $examples ) === range( 0, count( $examples ) - 1 ) &&
292  !preg_match( '/^\s*api\.php\?/', $examples[0] )
293  ) {
294  // Fix up the ugly "even numbered elements are description, odd
295  // numbered elemts are the link" format (see doc for self::getExamples)
296  $tmp = [];
297  $examplesCount = count( $examples );
298  for ( $i = 0; $i < $examplesCount; $i += 2 ) {
299  $tmp[$examples[$i + 1]] = $examples[$i];
300  }
301  $examples = $tmp;
302  }
303 
304  foreach ( $examples as $k => $v ) {
305  if ( is_numeric( $k ) ) {
306  $qs = $v;
307  $msg = '';
308  } else {
309  $qs = $k;
310  $msg = self::escapeWikiText( $v );
311  if ( is_array( $msg ) ) {
312  $msg = implode( ' ', $msg );
313  }
314  }
315 
316  $qs = preg_replace( '/^\s*api\.php\?/', '', $qs );
317  $ret[$qs] = $this->msg( 'api-help-fallback-example', [ $msg ] );
318  }
319  }
320 
321  return $ret;
322  }
323 
329  public function getHelpUrls() {
330  return [];
331  }
332 
345  protected function getAllowedParams( /* $flags = 0 */ ) {
346  // int $flags is not declared because it causes "Strict standards"
347  // warning. Most derived classes do not implement it.
348  return [];
349  }
350 
355  public function shouldCheckMaxlag() {
356  return true;
357  }
358 
363  public function isReadMode() {
364  return true;
365  }
366 
371  public function isWriteMode() {
372  return false;
373  }
374 
379  public function mustBePosted() {
380  return $this->needsToken() !== false;
381  }
382 
388  public function isDeprecated() {
389  return false;
390  }
391 
398  public function isInternal() {
399  return false;
400  }
401 
420  public function needsToken() {
421  return false;
422  }
423 
433  protected function getWebUITokenSalt( array $params ) {
434  return null;
435  }
436 
449  public function getConditionalRequestData( $condition ) {
450  return null;
451  }
452 
455  /************************************************************************/
464  public function getModuleName() {
465  return $this->mModuleName;
466  }
467 
472  public function getModulePrefix() {
473  return $this->mModulePrefix;
474  }
475 
480  public function getMain() {
481  return $this->mMainModule;
482  }
483 
489  public function isMain() {
490  return $this === $this->mMainModule;
491  }
492 
498  public function getParent() {
499  return $this->isMain() ? null : $this->getMain();
500  }
501 
512  public function lacksSameOriginSecurity() {
513  // Main module has this method overridden
514  // Safety - avoid infinite loop:
515  if ( $this->isMain() ) {
516  ApiBase::dieDebug( __METHOD__, 'base method was called on main module.' );
517  }
518 
519  return $this->getMain()->lacksSameOriginSecurity();
520  }
521 
528  public function getModulePath() {
529  if ( $this->isMain() ) {
530  return 'main';
531  } elseif ( $this->getParent()->isMain() ) {
532  return $this->getModuleName();
533  } else {
534  return $this->getParent()->getModulePath() . '+' . $this->getModuleName();
535  }
536  }
537 
546  public function getModuleFromPath( $path ) {
547  $module = $this->getMain();
548  if ( $path === 'main' ) {
549  return $module;
550  }
551 
552  $parts = explode( '+', $path );
553  if ( count( $parts ) === 1 ) {
554  // In case the '+' was typed into URL, it resolves as a space
555  $parts = explode( ' ', $path );
556  }
557 
558  $count = count( $parts );
559  for ( $i = 0; $i < $count; $i++ ) {
560  $parent = $module;
561  $manager = $parent->getModuleManager();
562  if ( $manager === null ) {
563  $errorPath = implode( '+', array_slice( $parts, 0, $i ) );
564  $this->dieUsage( "The module \"$errorPath\" has no submodules", 'badmodule' );
565  }
566  $module = $manager->getModule( $parts[$i] );
567 
568  if ( $module === null ) {
569  $errorPath = $i ? implode( '+', array_slice( $parts, 0, $i ) ) : $parent->getModuleName();
570  $this->dieUsage(
571  "The module \"$errorPath\" does not have a submodule \"{$parts[$i]}\"",
572  'badmodule'
573  );
574  }
575  }
576 
577  return $module;
578  }
579 
584  public function getResult() {
585  // Main module has getResult() method overridden
586  // Safety - avoid infinite loop:
587  if ( $this->isMain() ) {
588  ApiBase::dieDebug( __METHOD__, 'base method was called on main module. ' );
589  }
590 
591  return $this->getMain()->getResult();
592  }
593 
598  public function getErrorFormatter() {
599  // Main module has getErrorFormatter() method overridden
600  // Safety - avoid infinite loop:
601  if ( $this->isMain() ) {
602  ApiBase::dieDebug( __METHOD__, 'base method was called on main module. ' );
603  }
604 
605  return $this->getMain()->getErrorFormatter();
606  }
607 
612  protected function getDB() {
613  if ( !isset( $this->mSlaveDB ) ) {
614  $this->mSlaveDB = wfGetDB( DB_SLAVE, 'api' );
615  }
616 
617  return $this->mSlaveDB;
618  }
619 
624  public function getContinuationManager() {
625  // Main module has getContinuationManager() method overridden
626  // Safety - avoid infinite loop:
627  if ( $this->isMain() ) {
628  ApiBase::dieDebug( __METHOD__, 'base method was called on main module. ' );
629  }
630 
631  return $this->getMain()->getContinuationManager();
632  }
633 
638  public function setContinuationManager( $manager ) {
639  // Main module has setContinuationManager() method overridden
640  // Safety - avoid infinite loop:
641  if ( $this->isMain() ) {
642  ApiBase::dieDebug( __METHOD__, 'base method was called on main module. ' );
643  }
644 
645  $this->getMain()->setContinuationManager( $manager );
646  }
647 
650  /************************************************************************/
662  public function dynamicParameterDocumentation() {
663  return null;
664  }
665 
672  public function encodeParamName( $paramName ) {
673  return $this->mModulePrefix . $paramName;
674  }
675 
685  public function extractRequestParams( $parseLimit = true ) {
686  // Cache parameters, for performance and to avoid bug 24564.
687  if ( !isset( $this->mParamCache[$parseLimit] ) ) {
688  $params = $this->getFinalParams();
689  $results = [];
690 
691  if ( $params ) { // getFinalParams() can return false
692  foreach ( $params as $paramName => $paramSettings ) {
693  $results[$paramName] = $this->getParameterFromSettings(
694  $paramName, $paramSettings, $parseLimit );
695  }
696  }
697  $this->mParamCache[$parseLimit] = $results;
698  }
699 
700  return $this->mParamCache[$parseLimit];
701  }
702 
709  protected function getParameter( $paramName, $parseLimit = true ) {
710  $paramSettings = $this->getFinalParams()[$paramName];
711 
712  return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
713  }
714 
721  public function requireOnlyOneParameter( $params, $required /*...*/ ) {
722  $required = func_get_args();
723  array_shift( $required );
724  $p = $this->getModulePrefix();
725 
726  $intersection = array_intersect( array_keys( array_filter( $params,
727  [ $this, 'parameterNotEmpty' ] ) ), $required );
728 
729  if ( count( $intersection ) > 1 ) {
730  $this->dieUsage(
731  "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
732  'invalidparammix' );
733  } elseif ( count( $intersection ) == 0 ) {
734  $this->dieUsage(
735  "One of the parameters {$p}" . implode( ", {$p}", $required ) . ' is required',
736  'missingparam'
737  );
738  }
739  }
740 
747  public function requireMaxOneParameter( $params, $required /*...*/ ) {
748  $required = func_get_args();
749  array_shift( $required );
750  $p = $this->getModulePrefix();
751 
752  $intersection = array_intersect( array_keys( array_filter( $params,
753  [ $this, 'parameterNotEmpty' ] ) ), $required );
754 
755  if ( count( $intersection ) > 1 ) {
756  $this->dieUsage(
757  "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
758  'invalidparammix'
759  );
760  }
761  }
762 
770  public function requireAtLeastOneParameter( $params, $required /*...*/ ) {
771  $required = func_get_args();
772  array_shift( $required );
773  $p = $this->getModulePrefix();
774 
775  $intersection = array_intersect(
776  array_keys( array_filter( $params, [ $this, 'parameterNotEmpty' ] ) ),
777  $required
778  );
779 
780  if ( count( $intersection ) == 0 ) {
781  $this->dieUsage( "At least one of the parameters {$p}" .
782  implode( ", {$p}", $required ) . ' is required', "{$p}missingparam" );
783  }
784  }
785 
793  public function requirePostedParameters( $params, $prefix = 'prefix' ) {
794  // Skip if $wgDebugAPI is set or we're in internal mode
795  if ( $this->getConfig()->get( 'DebugAPI' ) || $this->getMain()->isInternalMode() ) {
796  return;
797  }
798 
799  $queryValues = $this->getRequest()->getQueryValues();
800  $badParams = [];
801  foreach ( $params as $param ) {
802  if ( $prefix !== 'noprefix' ) {
803  $param = $this->encodeParamName( $param );
804  }
805  if ( array_key_exists( $param, $queryValues ) ) {
806  $badParams[] = $param;
807  }
808  }
809 
810  if ( $badParams ) {
811  $this->dieUsage(
812  'The following parameters were found in the query string, but must be in the POST body: '
813  . join( ', ', $badParams ),
814  'mustpostparams'
815  );
816  }
817  }
818 
825  private function parameterNotEmpty( $x ) {
826  return !is_null( $x ) && $x !== false;
827  }
828 
840  public function getTitleOrPageId( $params, $load = false ) {
841  $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
842 
843  $pageObj = null;
844  if ( isset( $params['title'] ) ) {
845  $titleObj = Title::newFromText( $params['title'] );
846  if ( !$titleObj || $titleObj->isExternal() ) {
847  $this->dieUsageMsg( [ 'invalidtitle', $params['title'] ] );
848  }
849  if ( !$titleObj->canExist() ) {
850  $this->dieUsage( "Namespace doesn't allow actual pages", 'pagecannotexist' );
851  }
852  $pageObj = WikiPage::factory( $titleObj );
853  if ( $load !== false ) {
854  $pageObj->loadPageData( $load );
855  }
856  } elseif ( isset( $params['pageid'] ) ) {
857  if ( $load === false ) {
858  $load = 'fromdb';
859  }
860  $pageObj = WikiPage::newFromID( $params['pageid'], $load );
861  if ( !$pageObj ) {
862  $this->dieUsageMsg( [ 'nosuchpageid', $params['pageid'] ] );
863  }
864  }
865 
866  return $pageObj;
867  }
868 
877  protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
878 
879  $userWatching = $this->getUser()->isWatched( $titleObj, User::IGNORE_USER_RIGHTS );
880 
881  switch ( $watchlist ) {
882  case 'watch':
883  return true;
884 
885  case 'unwatch':
886  return false;
887 
888  case 'preferences':
889  # If the user is already watching, don't bother checking
890  if ( $userWatching ) {
891  return true;
892  }
893  # If no user option was passed, use watchdefault and watchcreations
894  if ( is_null( $userOption ) ) {
895  return $this->getUser()->getBoolOption( 'watchdefault' ) ||
896  $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
897  }
898 
899  # Watch the article based on the user preference
900  return $this->getUser()->getBoolOption( $userOption );
901 
902  case 'nochange':
903  return $userWatching;
904 
905  default:
906  return $userWatching;
907  }
908  }
909 
919  protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
920  // Some classes may decide to change parameter names
921  $encParamName = $this->encodeParamName( $paramName );
922 
923  if ( !is_array( $paramSettings ) ) {
924  $default = $paramSettings;
925  $multi = false;
926  $type = gettype( $paramSettings );
927  $dupes = false;
928  $deprecated = false;
929  $required = false;
930  } else {
931  $default = isset( $paramSettings[self::PARAM_DFLT] )
932  ? $paramSettings[self::PARAM_DFLT]
933  : null;
934  $multi = isset( $paramSettings[self::PARAM_ISMULTI] )
935  ? $paramSettings[self::PARAM_ISMULTI]
936  : false;
937  $type = isset( $paramSettings[self::PARAM_TYPE] )
938  ? $paramSettings[self::PARAM_TYPE]
939  : null;
940  $dupes = isset( $paramSettings[self::PARAM_ALLOW_DUPLICATES] )
941  ? $paramSettings[self::PARAM_ALLOW_DUPLICATES]
942  : false;
943  $deprecated = isset( $paramSettings[self::PARAM_DEPRECATED] )
944  ? $paramSettings[self::PARAM_DEPRECATED]
945  : false;
946  $required = isset( $paramSettings[self::PARAM_REQUIRED] )
947  ? $paramSettings[self::PARAM_REQUIRED]
948  : false;
949 
950  // When type is not given, and no choices, the type is the same as $default
951  if ( !isset( $type ) ) {
952  if ( isset( $default ) ) {
953  $type = gettype( $default );
954  } else {
955  $type = 'NULL'; // allow everything
956  }
957  }
958 
959  if ( $type == 'password' || !empty( $paramSettings[self::PARAM_SENSITIVE] ) ) {
960  $this->getMain()->markParamsSensitive( $encParamName );
961  }
962 
963  }
964 
965  if ( $type == 'boolean' ) {
966  if ( isset( $default ) && $default !== false ) {
967  // Having a default value of anything other than 'false' is not allowed
969  __METHOD__,
970  "Boolean param $encParamName's default is set to '$default'. " .
971  'Boolean parameters must default to false.'
972  );
973  }
974 
975  $value = $this->getMain()->getCheck( $encParamName );
976  } elseif ( $type == 'upload' ) {
977  if ( isset( $default ) ) {
978  // Having a default value is not allowed
980  __METHOD__,
981  "File upload param $encParamName's default is set to " .
982  "'$default'. File upload parameters may not have a default." );
983  }
984  if ( $multi ) {
985  ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
986  }
987  $value = $this->getMain()->getUpload( $encParamName );
988  if ( !$value->exists() ) {
989  // This will get the value without trying to normalize it
990  // (because trying to normalize a large binary file
991  // accidentally uploaded as a field fails spectacularly)
992  $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
993  if ( $value !== null ) {
994  $this->dieUsage(
995  "File upload param $encParamName is not a file upload; " .
996  'be sure to use multipart/form-data for your POST and include ' .
997  'a filename in the Content-Disposition header.',
998  "badupload_{$encParamName}"
999  );
1000  }
1001  }
1002  } else {
1003  $value = $this->getMain()->getVal( $encParamName, $default );
1004 
1005  if ( isset( $value ) && $type == 'namespace' ) {
1007  }
1008  if ( isset( $value ) && $type == 'submodule' ) {
1009  if ( isset( $paramSettings[self::PARAM_SUBMODULE_MAP] ) ) {
1010  $type = array_keys( $paramSettings[self::PARAM_SUBMODULE_MAP] );
1011  } else {
1012  $type = $this->getModuleManager()->getNames( $paramName );
1013  }
1014  }
1015  }
1016 
1017  if ( isset( $value ) && ( $multi || is_array( $type ) ) ) {
1018  $value = $this->parseMultiValue(
1019  $encParamName,
1020  $value,
1021  $multi,
1022  is_array( $type ) ? $type : null
1023  );
1024  }
1025 
1026  // More validation only when choices were not given
1027  // choices were validated in parseMultiValue()
1028  if ( isset( $value ) ) {
1029  if ( !is_array( $type ) ) {
1030  switch ( $type ) {
1031  case 'NULL': // nothing to do
1032  break;
1033  case 'string':
1034  case 'text':
1035  case 'password':
1036  if ( $required && $value === '' ) {
1037  $this->dieUsageMsg( [ 'missingparam', $paramName ] );
1038  }
1039  break;
1040  case 'integer': // Force everything using intval() and optionally validate limits
1041  $min = isset( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[self::PARAM_MIN] : null;
1042  $max = isset( $paramSettings[self::PARAM_MAX] ) ? $paramSettings[self::PARAM_MAX] : null;
1043  $enforceLimits = isset( $paramSettings[self::PARAM_RANGE_ENFORCE] )
1044  ? $paramSettings[self::PARAM_RANGE_ENFORCE] : false;
1045 
1046  if ( is_array( $value ) ) {
1047  $value = array_map( 'intval', $value );
1048  if ( !is_null( $min ) || !is_null( $max ) ) {
1049  foreach ( $value as &$v ) {
1050  $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
1051  }
1052  }
1053  } else {
1054  $value = intval( $value );
1055  if ( !is_null( $min ) || !is_null( $max ) ) {
1056  $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
1057  }
1058  }
1059  break;
1060  case 'limit':
1061  if ( !$parseLimit ) {
1062  // Don't do any validation whatsoever
1063  break;
1064  }
1065  if ( !isset( $paramSettings[self::PARAM_MAX] )
1066  || !isset( $paramSettings[self::PARAM_MAX2] )
1067  ) {
1069  __METHOD__,
1070  "MAX1 or MAX2 are not defined for the limit $encParamName"
1071  );
1072  }
1073  if ( $multi ) {
1074  ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
1075  }
1076  $min = isset( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[self::PARAM_MIN] : 0;
1077  if ( $value == 'max' ) {
1078  $value = $this->getMain()->canApiHighLimits()
1079  ? $paramSettings[self::PARAM_MAX2]
1080  : $paramSettings[self::PARAM_MAX];
1081  $this->getResult()->addParsedLimit( $this->getModuleName(), $value );
1082  } else {
1083  $value = intval( $value );
1084  $this->validateLimit(
1085  $paramName,
1086  $value,
1087  $min,
1088  $paramSettings[self::PARAM_MAX],
1089  $paramSettings[self::PARAM_MAX2]
1090  );
1091  }
1092  break;
1093  case 'boolean':
1094  if ( $multi ) {
1095  ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
1096  }
1097  break;
1098  case 'timestamp':
1099  if ( is_array( $value ) ) {
1100  foreach ( $value as $key => $val ) {
1101  $value[$key] = $this->validateTimestamp( $val, $encParamName );
1102  }
1103  } else {
1104  $value = $this->validateTimestamp( $value, $encParamName );
1105  }
1106  break;
1107  case 'user':
1108  if ( is_array( $value ) ) {
1109  foreach ( $value as $key => $val ) {
1110  $value[$key] = $this->validateUser( $val, $encParamName );
1111  }
1112  } else {
1113  $value = $this->validateUser( $value, $encParamName );
1114  }
1115  break;
1116  case 'upload': // nothing to do
1117  break;
1118  case 'tags':
1119  // If change tagging was requested, check that the tags are valid.
1120  if ( !is_array( $value ) && !$multi ) {
1121  $value = [ $value ];
1122  }
1124  if ( !$tagsStatus->isGood() ) {
1125  $this->dieStatus( $tagsStatus );
1126  }
1127  break;
1128  default:
1129  ApiBase::dieDebug( __METHOD__, "Param $encParamName's type is unknown - $type" );
1130  }
1131  }
1132 
1133  // Throw out duplicates if requested
1134  if ( !$dupes && is_array( $value ) ) {
1135  $value = array_unique( $value );
1136  }
1137 
1138  // Set a warning if a deprecated parameter has been passed
1139  if ( $deprecated && $value !== false ) {
1140  $this->setWarning( "The $encParamName parameter has been deprecated." );
1141 
1142  $feature = $encParamName;
1143  $m = $this;
1144  while ( !$m->isMain() ) {
1145  $p = $m->getParent();
1146  $name = $m->getModuleName();
1147  $param = $p->encodeParamName( $p->getModuleManager()->getModuleGroup( $name ) );
1148  $feature = "{$param}={$name}&{$feature}";
1149  $m = $p;
1150  }
1151  $this->logFeatureUsage( $feature );
1152  }
1153  } elseif ( $required ) {
1154  $this->dieUsageMsg( [ 'missingparam', $paramName ] );
1155  }
1156 
1157  return $value;
1158  }
1159 
1173  protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues ) {
1174  if ( trim( $value ) === '' && $allowMultiple ) {
1175  return [];
1176  }
1177 
1178  // This is a bit awkward, but we want to avoid calling canApiHighLimits()
1179  // because it unstubs $wgUser
1180  $valuesList = explode( '|', $value, self::LIMIT_SML2 + 1 );
1181  $sizeLimit = count( $valuesList ) > self::LIMIT_SML1 && $this->mMainModule->canApiHighLimits()
1182  ? self::LIMIT_SML2
1183  : self::LIMIT_SML1;
1184 
1185  if ( self::truncateArray( $valuesList, $sizeLimit ) ) {
1186  $this->setWarning( "Too many values supplied for parameter '$valueName': " .
1187  "the limit is $sizeLimit" );
1188  }
1189 
1190  if ( !$allowMultiple && count( $valuesList ) != 1 ) {
1191  // Bug 33482 - Allow entries with | in them for non-multiple values
1192  if ( in_array( $value, $allowedValues, true ) ) {
1193  return $value;
1194  }
1195 
1196  $possibleValues = is_array( $allowedValues )
1197  ? "of '" . implode( "', '", $allowedValues ) . "'"
1198  : '';
1199  $this->dieUsage(
1200  "Only one $possibleValues is allowed for parameter '$valueName'",
1201  "multival_$valueName"
1202  );
1203  }
1204 
1205  if ( is_array( $allowedValues ) ) {
1206  // Check for unknown values
1207  $unknown = array_diff( $valuesList, $allowedValues );
1208  if ( count( $unknown ) ) {
1209  if ( $allowMultiple ) {
1210  $s = count( $unknown ) > 1 ? 's' : '';
1211  $vals = implode( ', ', $unknown );
1212  $this->setWarning( "Unrecognized value$s for parameter '$valueName': $vals" );
1213  } else {
1214  $this->dieUsage(
1215  "Unrecognized value for parameter '$valueName': {$valuesList[0]}",
1216  "unknown_$valueName"
1217  );
1218  }
1219  }
1220  // Now throw them out
1221  $valuesList = array_intersect( $valuesList, $allowedValues );
1222  }
1223 
1224  return $allowMultiple ? $valuesList : $valuesList[0];
1225  }
1226 
1237  protected function validateLimit( $paramName, &$value, $min, $max, $botMax = null,
1238  $enforceLimits = false
1239  ) {
1240  if ( !is_null( $min ) && $value < $min ) {
1241  $msg = $this->encodeParamName( $paramName ) . " may not be less than $min (set to $value)";
1242  $this->warnOrDie( $msg, $enforceLimits );
1243  $value = $min;
1244  }
1245 
1246  // Minimum is always validated, whereas maximum is checked only if not
1247  // running in internal call mode
1248  if ( $this->getMain()->isInternalMode() ) {
1249  return;
1250  }
1251 
1252  // Optimization: do not check user's bot status unless really needed -- skips db query
1253  // assumes $botMax >= $max
1254  if ( !is_null( $max ) && $value > $max ) {
1255  if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1256  if ( $value > $botMax ) {
1257  $msg = $this->encodeParamName( $paramName ) .
1258  " may not be over $botMax (set to $value) for bots or sysops";
1259  $this->warnOrDie( $msg, $enforceLimits );
1260  $value = $botMax;
1261  }
1262  } else {
1263  $msg = $this->encodeParamName( $paramName ) . " may not be over $max (set to $value) for users";
1264  $this->warnOrDie( $msg, $enforceLimits );
1265  $value = $max;
1266  }
1267  }
1268  }
1269 
1276  protected function validateTimestamp( $value, $encParamName ) {
1277  // Confusing synonyms for the current time accepted by wfTimestamp()
1278  // (wfTimestamp() also accepts various non-strings and the string of 14
1279  // ASCII NUL bytes, but those can't get here)
1280  if ( !$value ) {
1281  $this->logFeatureUsage( 'unclear-"now"-timestamp' );
1282  $this->setWarning(
1283  "Passing '$value' for timestamp parameter $encParamName has been deprecated." .
1284  ' If for some reason you need to explicitly specify the current time without' .
1285  ' calculating it client-side, use "now".'
1286  );
1287  return wfTimestamp( TS_MW );
1288  }
1289 
1290  // Explicit synonym for the current time
1291  if ( $value === 'now' ) {
1292  return wfTimestamp( TS_MW );
1293  }
1294 
1295  $unixTimestamp = wfTimestamp( TS_UNIX, $value );
1296  if ( $unixTimestamp === false ) {
1297  $this->dieUsage(
1298  "Invalid value '$value' for timestamp parameter $encParamName",
1299  "badtimestamp_{$encParamName}"
1300  );
1301  }
1302 
1303  return wfTimestamp( TS_MW, $unixTimestamp );
1304  }
1305 
1315  final public function validateToken( $token, array $params ) {
1316  $tokenType = $this->needsToken();
1318  if ( !isset( $salts[$tokenType] ) ) {
1319  throw new MWException(
1320  "Module '{$this->getModuleName()}' tried to use token type '$tokenType' " .
1321  'without registering it'
1322  );
1323  }
1324 
1325  $tokenObj = ApiQueryTokens::getToken(
1326  $this->getUser(), $this->getRequest()->getSession(), $salts[$tokenType]
1327  );
1328  if ( $tokenObj->match( $token ) ) {
1329  return true;
1330  }
1331 
1332  $webUiSalt = $this->getWebUITokenSalt( $params );
1333  if ( $webUiSalt !== null && $this->getUser()->matchEditToken(
1334  $token,
1335  $webUiSalt,
1336  $this->getRequest()
1337  ) ) {
1338  return true;
1339  }
1340 
1341  return false;
1342  }
1343 
1350  private function validateUser( $value, $encParamName ) {
1352  if ( $title === null || $title->hasFragment() ) {
1353  $this->dieUsage(
1354  "Invalid value '$value' for user parameter $encParamName",
1355  "baduser_{$encParamName}"
1356  );
1357  }
1358 
1359  return $title->getText();
1360  }
1361 
1364  /************************************************************************/
1375  protected function setWatch( $watch, $titleObj, $userOption = null ) {
1376  $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
1377  if ( $value === null ) {
1378  return;
1379  }
1380 
1381  WatchAction::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
1382  }
1383 
1390  public static function truncateArray( &$arr, $limit ) {
1391  $modified = false;
1392  while ( count( $arr ) > $limit ) {
1393  array_pop( $arr );
1394  $modified = true;
1395  }
1396 
1397  return $modified;
1398  }
1399 
1406  public function getWatchlistUser( $params ) {
1407  if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1408  $user = User::newFromName( $params['owner'], false );
1409  if ( !( $user && $user->getId() ) ) {
1410  $this->dieUsage( 'Specified user does not exist', 'bad_wlowner' );
1411  }
1412  $token = $user->getOption( 'watchlisttoken' );
1413  if ( $token == '' || !hash_equals( $token, $params['token'] ) ) {
1414  $this->dieUsage(
1415  'Incorrect watchlist token provided -- please set a correct token in Special:Preferences',
1416  'bad_wltoken'
1417  );
1418  }
1419  } else {
1420  if ( !$this->getUser()->isLoggedIn() ) {
1421  $this->dieUsage( 'You must be logged-in to have a watchlist', 'notloggedin' );
1422  }
1423  if ( !$this->getUser()->isAllowed( 'viewmywatchlist' ) ) {
1424  $this->dieUsage( 'You don\'t have permission to view your watchlist', 'permissiondenied' );
1425  }
1426  $user = $this->getUser();
1427  }
1428 
1429  return $user;
1430  }
1431 
1439  private static function escapeWikiText( $v ) {
1440  if ( is_array( $v ) ) {
1441  return array_map( 'self::escapeWikiText', $v );
1442  } else {
1443  return strtr( $v, [
1444  '__' => '_&#95;', '{' => '&#123;', '}' => '&#125;',
1445  '[[Category:' => '[[:Category:',
1446  '[[File:' => '[[:File:', '[[Image:' => '[[:Image:',
1447  ] );
1448  }
1449  }
1450 
1463  public static function makeMessage( $msg, IContextSource $context, array $params = null ) {
1464  if ( is_string( $msg ) ) {
1465  $msg = wfMessage( $msg );
1466  } elseif ( is_array( $msg ) ) {
1467  $msg = call_user_func_array( 'wfMessage', $msg );
1468  }
1469  if ( !$msg instanceof Message ) {
1470  return null;
1471  }
1472 
1473  $msg->setContext( $context );
1474  if ( $params ) {
1475  $msg->params( $params );
1476  }
1477 
1478  return $msg;
1479  }
1480 
1483  /************************************************************************/
1495  public function setWarning( $warning ) {
1496  $msg = new ApiRawMessage( $warning, 'warning' );
1497  $this->getErrorFormatter()->addWarning( $this->getModuleName(), $msg );
1498  }
1499 
1506  private function warnOrDie( $msg, $enforceLimits = false ) {
1507  if ( $enforceLimits ) {
1508  $this->dieUsage( $msg, 'integeroutofrange' );
1509  }
1510 
1511  $this->setWarning( $msg );
1512  }
1513 
1526  public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
1527  throw new UsageException(
1528  $description,
1529  $this->encodeParamName( $errorCode ),
1530  $httpRespCode,
1531  $extradata
1532  );
1533  }
1534 
1543  public function dieBlocked( Block $block ) {
1544  // Die using the appropriate message depending on block type
1545  if ( $block->getType() == Block::TYPE_AUTO ) {
1546  $this->dieUsage(
1547  'Your IP address has been blocked automatically, because it was used by a blocked user',
1548  'autoblocked',
1549  0,
1550  [ 'blockinfo' => ApiQueryUserInfo::getBlockInfo( $block ) ]
1551  );
1552  } else {
1553  $this->dieUsage(
1554  'You have been blocked from editing',
1555  'blocked',
1556  0,
1557  [ 'blockinfo' => ApiQueryUserInfo::getBlockInfo( $block ) ]
1558  );
1559  }
1560  }
1561 
1571  public function getErrorFromStatus( $status, &$extraData = null ) {
1572  if ( $status->isGood() ) {
1573  throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
1574  }
1575 
1576  $errors = $status->getErrorsByType( 'error' );
1577  if ( !$errors ) {
1578  // No errors? Assume the warnings should be treated as errors
1579  $errors = $status->getErrorsByType( 'warning' );
1580  }
1581  if ( !$errors ) {
1582  // Still no errors? Punt
1583  $errors = [ [ 'message' => 'unknownerror-nocode', 'params' => [] ] ];
1584  }
1585 
1586  // Cannot use dieUsageMsg() because extensions might return custom
1587  // error messages.
1588  if ( $errors[0]['message'] instanceof Message ) {
1589  $msg = $errors[0]['message'];
1590  if ( $msg instanceof IApiMessage ) {
1591  $extraData = $msg->getApiData();
1592  $code = $msg->getApiCode();
1593  } else {
1594  $code = $msg->getKey();
1595  }
1596  } else {
1597  $code = $errors[0]['message'];
1598  $msg = wfMessage( $code, $errors[0]['params'] );
1599  }
1600  if ( isset( ApiBase::$messageMap[$code] ) ) {
1601  // Translate message to code, for backwards compatibility
1602  $code = ApiBase::$messageMap[$code]['code'];
1603  }
1604 
1605  return [ $code, $msg->inLanguage( 'en' )->useDatabase( false )->plain() ];
1606  }
1607 
1615  public function dieStatus( $status ) {
1616  $extraData = null;
1617  list( $code, $msg ) = $this->getErrorFromStatus( $status, $extraData );
1618  $this->dieUsage( $msg, $code, 0, $extraData );
1619  }
1620 
1621  // @codingStandardsIgnoreStart Allow long lines. Cannot split these.
1625  public static $messageMap = [
1626  // This one MUST be present, or dieUsageMsg() will recurse infinitely
1627  'unknownerror' => [ 'code' => 'unknownerror', 'info' => "Unknown error: \"\$1\"" ],
1628  'unknownerror-nocode' => [ 'code' => 'unknownerror', 'info' => 'Unknown error' ],
1629 
1630  // Messages from Title::getUserPermissionsErrors()
1631  'ns-specialprotected' => [
1632  'code' => 'unsupportednamespace',
1633  'info' => "Pages in the Special namespace can't be edited"
1634  ],
1635  'protectedinterface' => [
1636  'code' => 'protectednamespace-interface',
1637  'info' => "You're not allowed to edit interface messages"
1638  ],
1639  'namespaceprotected' => [
1640  'code' => 'protectednamespace',
1641  'info' => "You're not allowed to edit pages in the \"\$1\" namespace"
1642  ],
1643  'customcssprotected' => [
1644  'code' => 'customcssprotected',
1645  'info' => "You're not allowed to edit custom CSS pages"
1646  ],
1647  'customjsprotected' => [
1648  'code' => 'customjsprotected',
1649  'info' => "You're not allowed to edit custom JavaScript pages"
1650  ],
1651  'cascadeprotected' => [
1652  'code' => 'cascadeprotected',
1653  'info' => "The page you're trying to edit is protected because it's included in a cascade-protected page"
1654  ],
1655  'protectedpagetext' => [
1656  'code' => 'protectedpage',
1657  'info' => "The \"\$1\" right is required to edit this page"
1658  ],
1659  'protect-cantedit' => [
1660  'code' => 'cantedit',
1661  'info' => "You can't protect this page because you can't edit it"
1662  ],
1663  'deleteprotected' => [
1664  'code' => 'cantedit',
1665  'info' => "You can't delete this page because it has been protected"
1666  ],
1667  'badaccess-group0' => [
1668  'code' => 'permissiondenied',
1669  'info' => 'Permission denied'
1670  ], // Generic permission denied message
1671  'badaccess-groups' => [
1672  'code' => 'permissiondenied',
1673  'info' => 'Permission denied'
1674  ],
1675  'titleprotected' => [
1676  'code' => 'protectedtitle',
1677  'info' => 'This title has been protected from creation'
1678  ],
1679  'nocreate-loggedin' => [
1680  'code' => 'cantcreate',
1681  'info' => "You don't have permission to create new pages"
1682  ],
1683  'nocreatetext' => [
1684  'code' => 'cantcreate-anon',
1685  'info' => "Anonymous users can't create new pages"
1686  ],
1687  'movenologintext' => [
1688  'code' => 'cantmove-anon',
1689  'info' => "Anonymous users can't move pages"
1690  ],
1691  'movenotallowed' => [
1692  'code' => 'cantmove',
1693  'info' => "You don't have permission to move pages"
1694  ],
1695  'confirmedittext' => [
1696  'code' => 'confirmemail',
1697  'info' => 'You must confirm your email address before you can edit'
1698  ],
1699  'blockedtext' => [
1700  'code' => 'blocked',
1701  'info' => 'You have been blocked from editing'
1702  ],
1703  'autoblockedtext' => [
1704  'code' => 'autoblocked',
1705  'info' => 'Your IP address has been blocked automatically, because it was used by a blocked user'
1706  ],
1707 
1708  // Miscellaneous interface messages
1709  'actionthrottledtext' => [
1710  'code' => 'ratelimited',
1711  'info' => "You've exceeded your rate limit. Please wait some time and try again"
1712  ],
1713  'alreadyrolled' => [
1714  'code' => 'alreadyrolled',
1715  'info' => 'The page you tried to rollback was already rolled back'
1716  ],
1717  'cantrollback' => [
1718  'code' => 'onlyauthor',
1719  'info' => 'The page you tried to rollback only has one author'
1720  ],
1721  'readonlytext' => [
1722  'code' => 'readonly',
1723  'info' => 'The wiki is currently in read-only mode'
1724  ],
1725  'sessionfailure' => [
1726  'code' => 'badtoken',
1727  'info' => 'Invalid token' ],
1728  'cannotdelete' => [
1729  'code' => 'cantdelete',
1730  'info' => "Couldn't delete \"\$1\". Maybe it was deleted already by someone else"
1731  ],
1732  'notanarticle' => [
1733  'code' => 'missingtitle',
1734  'info' => "The page you requested doesn't exist"
1735  ],
1736  'selfmove' => [ 'code' => 'selfmove', 'info' => "Can't move a page to itself"
1737  ],
1738  'immobile_namespace' => [
1739  'code' => 'immobilenamespace',
1740  'info' => 'You tried to move pages from or to a namespace that is protected from moving'
1741  ],
1742  'articleexists' => [
1743  'code' => 'articleexists',
1744  'info' => 'The destination article already exists and is not a redirect to the source article'
1745  ],
1746  'protectedpage' => [
1747  'code' => 'protectedpage',
1748  'info' => "You don't have permission to perform this move"
1749  ],
1750  'hookaborted' => [
1751  'code' => 'hookaborted',
1752  'info' => 'The modification you tried to make was aborted by an extension hook'
1753  ],
1754  'cantmove-titleprotected' => [
1755  'code' => 'protectedtitle',
1756  'info' => 'The destination article has been protected from creation'
1757  ],
1758  'imagenocrossnamespace' => [
1759  'code' => 'nonfilenamespace',
1760  'info' => "Can't move a file to a non-file namespace"
1761  ],
1762  'imagetypemismatch' => [
1763  'code' => 'filetypemismatch',
1764  'info' => "The new file extension doesn't match its type"
1765  ],
1766  // 'badarticleerror' => shouldn't happen
1767  // 'badtitletext' => shouldn't happen
1768  'ip_range_invalid' => [ 'code' => 'invalidrange', 'info' => 'Invalid IP range' ],
1769  'range_block_disabled' => [
1770  'code' => 'rangedisabled',
1771  'info' => 'Blocking IP ranges has been disabled'
1772  ],
1773  'nosuchusershort' => [
1774  'code' => 'nosuchuser',
1775  'info' => "The user you specified doesn't exist"
1776  ],
1777  'badipaddress' => [ 'code' => 'invalidip', 'info' => 'Invalid IP address specified' ],
1778  'ipb_expiry_invalid' => [ 'code' => 'invalidexpiry', 'info' => 'Invalid expiry time' ],
1779  'ipb_already_blocked' => [
1780  'code' => 'alreadyblocked',
1781  'info' => 'The user you tried to block was already blocked'
1782  ],
1783  'ipb_blocked_as_range' => [
1784  'code' => 'blockedasrange',
1785  '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."
1786  ],
1787  'ipb_cant_unblock' => [
1788  'code' => 'cantunblock',
1789  'info' => 'The block you specified was not found. It may have been unblocked already'
1790  ],
1791  'mailnologin' => [
1792  'code' => 'cantsend',
1793  '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'
1794  ],
1795  'ipbblocked' => [
1796  'code' => 'ipbblocked',
1797  'info' => 'You cannot block or unblock users while you are yourself blocked'
1798  ],
1799  'ipbnounblockself' => [
1800  'code' => 'ipbnounblockself',
1801  'info' => 'You are not allowed to unblock yourself'
1802  ],
1803  'usermaildisabled' => [
1804  'code' => 'usermaildisabled',
1805  'info' => 'User email has been disabled'
1806  ],
1807  'blockedemailuser' => [
1808  'code' => 'blockedfrommail',
1809  'info' => 'You have been blocked from sending email'
1810  ],
1811  'notarget' => [
1812  'code' => 'notarget',
1813  'info' => 'You have not specified a valid target for this action'
1814  ],
1815  'noemail' => [
1816  'code' => 'noemail',
1817  'info' => 'The user has not specified a valid email address, or has chosen not to receive email from other users'
1818  ],
1819  'rcpatroldisabled' => [
1820  'code' => 'patroldisabled',
1821  'info' => 'Patrolling is disabled on this wiki'
1822  ],
1823  'markedaspatrollederror-noautopatrol' => [
1824  'code' => 'noautopatrol',
1825  'info' => "You don't have permission to patrol your own changes"
1826  ],
1827  'delete-toobig' => [
1828  'code' => 'bigdelete',
1829  'info' => "You can't delete this page because it has more than \$1 revisions"
1830  ],
1831  'movenotallowedfile' => [
1832  'code' => 'cantmovefile',
1833  'info' => "You don't have permission to move files"
1834  ],
1835  'userrights-no-interwiki' => [
1836  'code' => 'nointerwikiuserrights',
1837  'info' => "You don't have permission to change user rights on other wikis"
1838  ],
1839  'userrights-nodatabase' => [
1840  'code' => 'nosuchdatabase',
1841  'info' => "Database \"\$1\" does not exist or is not local"
1842  ],
1843  'nouserspecified' => [ 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ],
1844  'noname' => [ 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ],
1845  'summaryrequired' => [ 'code' => 'summaryrequired', 'info' => 'Summary required' ],
1846  'import-rootpage-invalid' => [
1847  'code' => 'import-rootpage-invalid',
1848  'info' => 'Root page is an invalid title'
1849  ],
1850  'import-rootpage-nosubpage' => [
1851  'code' => 'import-rootpage-nosubpage',
1852  'info' => 'Namespace "$1" of the root page does not allow subpages'
1853  ],
1854 
1855  // API-specific messages
1856  'readrequired' => [
1857  'code' => 'readapidenied',
1858  'info' => 'You need read permission to use this module'
1859  ],
1860  'writedisabled' => [
1861  'code' => 'noapiwrite',
1862  '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"
1863  ],
1864  'writerequired' => [
1865  'code' => 'writeapidenied',
1866  'info' => "You're not allowed to edit this wiki through the API"
1867  ],
1868  'missingparam' => [ 'code' => 'no$1', 'info' => "The \$1 parameter must be set" ],
1869  'invalidtitle' => [ 'code' => 'invalidtitle', 'info' => "Bad title \"\$1\"" ],
1870  'nosuchpageid' => [ 'code' => 'nosuchpageid', 'info' => "There is no page with ID \$1" ],
1871  'nosuchrevid' => [ 'code' => 'nosuchrevid', 'info' => "There is no revision with ID \$1" ],
1872  'nosuchuser' => [ 'code' => 'nosuchuser', 'info' => "User \"\$1\" doesn't exist" ],
1873  'invaliduser' => [ 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ],
1874  'invalidexpiry' => [ 'code' => 'invalidexpiry', 'info' => "Invalid expiry time \"\$1\"" ],
1875  'pastexpiry' => [ 'code' => 'pastexpiry', 'info' => "Expiry time \"\$1\" is in the past" ],
1876  'create-titleexists' => [
1877  'code' => 'create-titleexists',
1878  'info' => "Existing titles can't be protected with 'create'"
1879  ],
1880  'missingtitle-createonly' => [
1881  'code' => 'missingtitle-createonly',
1882  'info' => "Missing titles can only be protected with 'create'"
1883  ],
1884  'cantblock' => [ 'code' => 'cantblock',
1885  'info' => "You don't have permission to block users"
1886  ],
1887  'canthide' => [
1888  'code' => 'canthide',
1889  'info' => "You don't have permission to hide user names from the block log"
1890  ],
1891  'cantblock-email' => [
1892  'code' => 'cantblock-email',
1893  'info' => "You don't have permission to block users from sending email through the wiki"
1894  ],
1895  'unblock-notarget' => [
1896  'code' => 'notarget',
1897  'info' => 'Either the id or the user parameter must be set'
1898  ],
1899  'unblock-idanduser' => [
1900  'code' => 'idanduser',
1901  'info' => "The id and user parameters can't be used together"
1902  ],
1903  'cantunblock' => [
1904  'code' => 'permissiondenied',
1905  'info' => "You don't have permission to unblock users"
1906  ],
1907  'cannotundelete' => [
1908  'code' => 'cantundelete',
1909  'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already"
1910  ],
1911  'permdenied-undelete' => [
1912  'code' => 'permissiondenied',
1913  'info' => "You don't have permission to restore deleted revisions"
1914  ],
1915  'createonly-exists' => [
1916  'code' => 'articleexists',
1917  'info' => 'The article you tried to create has been created already'
1918  ],
1919  'nocreate-missing' => [
1920  'code' => 'missingtitle',
1921  'info' => "The article you tried to edit doesn't exist"
1922  ],
1923  'cantchangecontentmodel' => [
1924  'code' => 'cantchangecontentmodel',
1925  'info' => "You don't have permission to change the content model of a page"
1926  ],
1927  'nosuchrcid' => [
1928  'code' => 'nosuchrcid',
1929  'info' => "There is no change with rcid \"\$1\""
1930  ],
1931  'nosuchlogid' => [
1932  'code' => 'nosuchlogid',
1933  'info' => "There is no log entry with ID \"\$1\""
1934  ],
1935  'protect-invalidaction' => [
1936  'code' => 'protect-invalidaction',
1937  'info' => "Invalid protection type \"\$1\""
1938  ],
1939  'protect-invalidlevel' => [
1940  'code' => 'protect-invalidlevel',
1941  'info' => "Invalid protection level \"\$1\""
1942  ],
1943  'toofewexpiries' => [
1944  'code' => 'toofewexpiries',
1945  'info' => "\$1 expiry timestamps were provided where \$2 were needed"
1946  ],
1947  'cantimport' => [
1948  'code' => 'cantimport',
1949  'info' => "You don't have permission to import pages"
1950  ],
1951  'cantimport-upload' => [
1952  'code' => 'cantimport-upload',
1953  'info' => "You don't have permission to import uploaded pages"
1954  ],
1955  'importnofile' => [ 'code' => 'nofile', 'info' => "You didn't upload a file" ],
1956  'importuploaderrorsize' => [
1957  'code' => 'filetoobig',
1958  'info' => 'The file you uploaded is bigger than the maximum upload size'
1959  ],
1960  'importuploaderrorpartial' => [
1961  'code' => 'partialupload',
1962  'info' => 'The file was only partially uploaded'
1963  ],
1964  'importuploaderrortemp' => [
1965  'code' => 'notempdir',
1966  'info' => 'The temporary upload directory is missing'
1967  ],
1968  'importcantopen' => [
1969  'code' => 'cantopenfile',
1970  'info' => "Couldn't open the uploaded file"
1971  ],
1972  'import-noarticle' => [
1973  'code' => 'badinterwiki',
1974  'info' => 'Invalid interwiki title specified'
1975  ],
1976  'importbadinterwiki' => [
1977  'code' => 'badinterwiki',
1978  'info' => 'Invalid interwiki title specified'
1979  ],
1980  'import-unknownerror' => [
1981  'code' => 'import-unknownerror',
1982  'info' => "Unknown error on import: \"\$1\""
1983  ],
1984  'cantoverwrite-sharedfile' => [
1985  'code' => 'cantoverwrite-sharedfile',
1986  'info' => 'The target file exists on a shared repository and you do not have permission to override it'
1987  ],
1988  'sharedfile-exists' => [
1989  'code' => 'fileexists-sharedrepo-perm',
1990  'info' => 'The target file exists on a shared repository. Use the ignorewarnings parameter to override it.'
1991  ],
1992  'mustbeposted' => [
1993  'code' => 'mustbeposted',
1994  'info' => "The \$1 module requires a POST request"
1995  ],
1996  'show' => [
1997  'code' => 'show',
1998  'info' => 'Incorrect parameter - mutually exclusive values may not be supplied'
1999  ],
2000  'specialpage-cantexecute' => [
2001  'code' => 'specialpage-cantexecute',
2002  'info' => "You don't have permission to view the results of this special page"
2003  ],
2004  'invalidoldimage' => [
2005  'code' => 'invalidoldimage',
2006  'info' => 'The oldimage parameter has invalid format'
2007  ],
2008  'nodeleteablefile' => [
2009  'code' => 'nodeleteablefile',
2010  'info' => 'No such old version of the file'
2011  ],
2012  'fileexists-forbidden' => [
2013  'code' => 'fileexists-forbidden',
2014  'info' => 'A file with name "$1" already exists, and cannot be overwritten.'
2015  ],
2016  'fileexists-shared-forbidden' => [
2017  'code' => 'fileexists-shared-forbidden',
2018  'info' => 'A file with name "$1" already exists in the shared file repository, and cannot be overwritten.'
2019  ],
2020  'filerevert-badversion' => [
2021  'code' => 'filerevert-badversion',
2022  'info' => 'There is no previous local version of this file with the provided timestamp.'
2023  ],
2024 
2025  // ApiEditPage messages
2026  'noimageredirect-anon' => [
2027  'code' => 'noimageredirect-anon',
2028  'info' => "Anonymous users can't create image redirects"
2029  ],
2030  'noimageredirect-logged' => [
2031  'code' => 'noimageredirect',
2032  'info' => "You don't have permission to create image redirects"
2033  ],
2034  'spamdetected' => [
2035  'code' => 'spamdetected',
2036  'info' => "Your edit was refused because it contained a spam fragment: \"\$1\""
2037  ],
2038  'contenttoobig' => [
2039  'code' => 'contenttoobig',
2040  'info' => "The content you supplied exceeds the article size limit of \$1 kilobytes"
2041  ],
2042  'noedit-anon' => [ 'code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages" ],
2043  'noedit' => [ 'code' => 'noedit', 'info' => "You don't have permission to edit pages" ],
2044  'wasdeleted' => [
2045  'code' => 'pagedeleted',
2046  'info' => 'The page has been deleted since you fetched its timestamp'
2047  ],
2048  'blankpage' => [
2049  'code' => 'emptypage',
2050  'info' => 'Creating new, empty pages is not allowed'
2051  ],
2052  'editconflict' => [ 'code' => 'editconflict', 'info' => 'Edit conflict detected' ],
2053  'hashcheckfailed' => [ 'code' => 'badmd5', 'info' => 'The supplied MD5 hash was incorrect' ],
2054  'missingtext' => [
2055  'code' => 'notext',
2056  'info' => 'One of the text, appendtext, prependtext and undo parameters must be set'
2057  ],
2058  'emptynewsection' => [
2059  'code' => 'emptynewsection',
2060  'info' => 'Creating empty new sections is not possible.'
2061  ],
2062  'revwrongpage' => [
2063  'code' => 'revwrongpage',
2064  'info' => "r\$1 is not a revision of \"\$2\""
2065  ],
2066  'undo-failure' => [
2067  'code' => 'undofailure',
2068  'info' => 'Undo failed due to conflicting intermediate edits'
2069  ],
2070  'content-not-allowed-here' => [
2071  'code' => 'contentnotallowedhere',
2072  'info' => 'Content model "$1" is not allowed at title "$2"'
2073  ],
2074 
2075  // Messages from WikiPage::doEit(]
2076  'edit-hook-aborted' => [
2077  'code' => 'edit-hook-aborted',
2078  'info' => 'Your edit was aborted by an ArticleSave hook'
2079  ],
2080  'edit-gone-missing' => [
2081  'code' => 'edit-gone-missing',
2082  'info' => "The page you tried to edit doesn't seem to exist anymore"
2083  ],
2084  'edit-conflict' => [ 'code' => 'editconflict', 'info' => 'Edit conflict detected' ],
2085  'edit-already-exists' => [
2086  'code' => 'edit-already-exists',
2087  'info' => 'It seems the page you tried to create already exist'
2088  ],
2089 
2090  // uploadMsgs
2091  'invalid-file-key' => [ 'code' => 'invalid-file-key', 'info' => 'Not a valid file key' ],
2092  'nouploadmodule' => [ 'code' => 'nouploadmodule', 'info' => 'No upload module set' ],
2093  'uploaddisabled' => [
2094  'code' => 'uploaddisabled',
2095  'info' => 'Uploads are not enabled. Make sure $wgEnableUploads is set to true in LocalSettings.php and the PHP ini setting file_uploads is true'
2096  ],
2097  'copyuploaddisabled' => [
2098  'code' => 'copyuploaddisabled',
2099  'info' => 'Uploads by URL is not enabled. Make sure $wgAllowCopyUploads is set to true in LocalSettings.php.'
2100  ],
2101  'copyuploadbaddomain' => [
2102  'code' => 'copyuploadbaddomain',
2103  'info' => 'Uploads by URL are not allowed from this domain.'
2104  ],
2105  'copyuploadbadurl' => [
2106  'code' => 'copyuploadbadurl',
2107  'info' => 'Upload not allowed from this URL.'
2108  ],
2109 
2110  'filename-tooshort' => [
2111  'code' => 'filename-tooshort',
2112  'info' => 'The filename is too short'
2113  ],
2114  'filename-toolong' => [ 'code' => 'filename-toolong', 'info' => 'The filename is too long' ],
2115  'illegal-filename' => [
2116  'code' => 'illegal-filename',
2117  'info' => 'The filename is not allowed'
2118  ],
2119  'filetype-missing' => [
2120  'code' => 'filetype-missing',
2121  'info' => 'The file is missing an extension'
2122  ],
2123 
2124  'mustbeloggedin' => [ 'code' => 'mustbeloggedin', 'info' => 'You must be logged in to $1.' ]
2125  ];
2126  // @codingStandardsIgnoreEnd
2127 
2133  public function dieReadOnly() {
2134  $parsed = $this->parseMsg( [ 'readonlytext' ] );
2135  $this->dieUsage( $parsed['info'], $parsed['code'], /* http error */ 0,
2136  [ 'readonlyreason' => wfReadOnlyReason() ] );
2137  }
2138 
2144  public function dieUsageMsg( $error ) {
2145  # most of the time we send a 1 element, so we might as well send it as
2146  # a string and make this an array here.
2147  if ( is_string( $error ) ) {
2148  $error = [ $error ];
2149  }
2150  $parsed = $this->parseMsg( $error );
2151  $extraData = isset( $parsed['data'] ) ? $parsed['data'] : null;
2152  $this->dieUsage( $parsed['info'], $parsed['code'], 0, $extraData );
2153  }
2154 
2162  public function dieUsageMsgOrDebug( $error ) {
2163  if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
2164  $this->dieUsageMsg( $error );
2165  }
2166 
2167  if ( is_string( $error ) ) {
2168  $error = [ $error ];
2169  }
2170  $parsed = $this->parseMsg( $error );
2171  $this->setWarning( '$wgDebugAPI: ' . $parsed['code'] . ' - ' . $parsed['info'] );
2172  }
2173 
2181  protected function dieContinueUsageIf( $condition ) {
2182  if ( $condition ) {
2183  $this->dieUsage(
2184  'Invalid continue param. You should pass the original value returned by the previous query',
2185  'badcontinue' );
2186  }
2187  }
2188 
2194  public function parseMsg( $error ) {
2195  $error = (array)$error; // It seems strings sometimes make their way in here
2196  $key = array_shift( $error );
2197 
2198  // Check whether the error array was nested
2199  // array( array( <code>, <params> ), array( <another_code>, <params> ) )
2200  if ( is_array( $key ) ) {
2201  $error = $key;
2202  $key = array_shift( $error );
2203  }
2204 
2205  if ( $key instanceof IApiMessage ) {
2206  return [
2207  'code' => $key->getApiCode(),
2208  'info' => $key->inLanguage( 'en' )->useDatabase( false )->text(),
2209  'data' => $key->getApiData()
2210  ];
2211  }
2212 
2213  if ( isset( self::$messageMap[$key] ) ) {
2214  return [
2215  'code' => wfMsgReplaceArgs( self::$messageMap[$key]['code'], $error ),
2216  'info' => wfMsgReplaceArgs( self::$messageMap[$key]['info'], $error )
2217  ];
2218  }
2219 
2220  // If the key isn't present, throw an "unknown error"
2221  return $this->parseMsg( [ 'unknownerror', $key ] );
2222  }
2223 
2230  protected static function dieDebug( $method, $message ) {
2231  throw new MWException( "Internal error in $method: $message" );
2232  }
2233 
2239  public function logFeatureUsage( $feature ) {
2240  $request = $this->getRequest();
2241  $s = '"' . addslashes( $feature ) . '"' .
2242  ' "' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) . '"' .
2243  ' "' . $request->getIP() . '"' .
2244  ' "' . addslashes( $request->getHeader( 'Referer' ) ) . '"' .
2245  ' "' . addslashes( $this->getMain()->getUserAgent() ) . '"';
2246  wfDebugLog( 'api-feature-usage', $s, 'private' );
2247  }
2248 
2251  /************************************************************************/
2261  protected function getDescriptionMessage() {
2262  return "apihelp-{$this->getModulePath()}-description";
2263  }
2264 
2272  public function getFinalDescription() {
2273  $desc = $this->getDescription();
2274  Hooks::run( 'APIGetDescription', [ &$this, &$desc ] );
2275  $desc = self::escapeWikiText( $desc );
2276  if ( is_array( $desc ) ) {
2277  $desc = implode( "\n", $desc );
2278  } else {
2279  $desc = (string)$desc;
2280  }
2281 
2282  $msg = ApiBase::makeMessage( $this->getDescriptionMessage(), $this->getContext(), [
2283  $this->getModulePrefix(),
2284  $this->getModuleName(),
2285  $this->getModulePath(),
2286  ] );
2287  if ( !$msg->exists() ) {
2288  $msg = $this->msg( 'api-help-fallback-description', $desc );
2289  }
2290  $msgs = [ $msg ];
2291 
2292  Hooks::run( 'APIGetDescriptionMessages', [ $this, &$msgs ] );
2293 
2294  return $msgs;
2295  }
2296 
2305  public function getFinalParams( $flags = 0 ) {
2306  $params = $this->getAllowedParams( $flags );
2307  if ( !$params ) {
2308  $params = [];
2309  }
2310 
2311  if ( $this->needsToken() ) {
2312  $params['token'] = [
2313  ApiBase::PARAM_TYPE => 'string',
2314  ApiBase::PARAM_REQUIRED => true,
2315  ApiBase::PARAM_SENSITIVE => true,
2317  'api-help-param-token',
2318  $this->needsToken(),
2319  ],
2320  ] + ( isset( $params['token'] ) ? $params['token'] : [] );
2321  }
2322 
2323  Hooks::run( 'APIGetAllowedParams', [ &$this, &$params, $flags ] );
2324 
2325  return $params;
2326  }
2327 
2335  public function getFinalParamDescription() {
2336  $prefix = $this->getModulePrefix();
2337  $name = $this->getModuleName();
2338  $path = $this->getModulePath();
2339 
2340  $desc = $this->getParamDescription();
2341  Hooks::run( 'APIGetParamDescription', [ &$this, &$desc ] );
2342 
2343  if ( !$desc ) {
2344  $desc = [];
2345  }
2346  $desc = self::escapeWikiText( $desc );
2347 
2349  $msgs = [];
2350  foreach ( $params as $param => $settings ) {
2351  if ( !is_array( $settings ) ) {
2352  $settings = [];
2353  }
2354 
2355  $d = isset( $desc[$param] ) ? $desc[$param] : '';
2356  if ( is_array( $d ) ) {
2357  // Special handling for prop parameters
2358  $d = array_map( function ( $line ) {
2359  if ( preg_match( '/^\s+(\S+)\s+-\s+(.+)$/', $line, $m ) ) {
2360  $line = "\n;{$m[1]}:{$m[2]}";
2361  }
2362  return $line;
2363  }, $d );
2364  $d = implode( ' ', $d );
2365  }
2366 
2367  if ( isset( $settings[ApiBase::PARAM_HELP_MSG] ) ) {
2368  $msg = $settings[ApiBase::PARAM_HELP_MSG];
2369  } else {
2370  $msg = $this->msg( "apihelp-{$path}-param-{$param}" );
2371  if ( !$msg->exists() ) {
2372  $msg = $this->msg( 'api-help-fallback-parameter', $d );
2373  }
2374  }
2375  $msg = ApiBase::makeMessage( $msg, $this->getContext(),
2376  [ $prefix, $param, $name, $path ] );
2377  if ( !$msg ) {
2378  self::dieDebug( __METHOD__,
2379  'Value in ApiBase::PARAM_HELP_MSG is not valid' );
2380  }
2381  $msgs[$param] = [ $msg ];
2382 
2383  if ( isset( $settings[ApiBase::PARAM_HELP_MSG_PER_VALUE] ) ) {
2384  if ( !is_array( $settings[ApiBase::PARAM_HELP_MSG_PER_VALUE] ) ) {
2385  self::dieDebug( __METHOD__,
2386  'ApiBase::PARAM_HELP_MSG_PER_VALUE is not valid' );
2387  }
2388  if ( !is_array( $settings[ApiBase::PARAM_TYPE] ) ) {
2389  self::dieDebug( __METHOD__,
2390  'ApiBase::PARAM_HELP_MSG_PER_VALUE may only be used when ' .
2391  'ApiBase::PARAM_TYPE is an array' );
2392  }
2393 
2394  $valueMsgs = $settings[ApiBase::PARAM_HELP_MSG_PER_VALUE];
2395  foreach ( $settings[ApiBase::PARAM_TYPE] as $value ) {
2396  if ( isset( $valueMsgs[$value] ) ) {
2397  $msg = $valueMsgs[$value];
2398  } else {
2399  $msg = "apihelp-{$path}-paramvalue-{$param}-{$value}";
2400  }
2401  $m = ApiBase::makeMessage( $msg, $this->getContext(),
2402  [ $prefix, $param, $name, $path, $value ] );
2403  if ( $m ) {
2404  $m = new ApiHelpParamValueMessage(
2405  $value,
2406  [ $m->getKey(), 'api-help-param-no-description' ],
2407  $m->getParams()
2408  );
2409  $msgs[$param][] = $m->setContext( $this->getContext() );
2410  } else {
2411  self::dieDebug( __METHOD__,
2412  "Value in ApiBase::PARAM_HELP_MSG_PER_VALUE for $value is not valid" );
2413  }
2414  }
2415  }
2416 
2417  if ( isset( $settings[ApiBase::PARAM_HELP_MSG_APPEND] ) ) {
2418  if ( !is_array( $settings[ApiBase::PARAM_HELP_MSG_APPEND] ) ) {
2419  self::dieDebug( __METHOD__,
2420  'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
2421  }
2422  foreach ( $settings[ApiBase::PARAM_HELP_MSG_APPEND] as $m ) {
2423  $m = ApiBase::makeMessage( $m, $this->getContext(),
2424  [ $prefix, $param, $name, $path ] );
2425  if ( $m ) {
2426  $msgs[$param][] = $m;
2427  } else {
2428  self::dieDebug( __METHOD__,
2429  'Value in ApiBase::PARAM_HELP_MSG_APPEND is not valid' );
2430  }
2431  }
2432  }
2433  }
2434 
2435  Hooks::run( 'APIGetParamDescriptionMessages', [ $this, &$msgs ] );
2436 
2437  return $msgs;
2438  }
2439 
2449  protected function getHelpFlags() {
2450  $flags = [];
2451 
2452  if ( $this->isDeprecated() ) {
2453  $flags[] = 'deprecated';
2454  }
2455  if ( $this->isInternal() ) {
2456  $flags[] = 'internal';
2457  }
2458  if ( $this->isReadMode() ) {
2459  $flags[] = 'readrights';
2460  }
2461  if ( $this->isWriteMode() ) {
2462  $flags[] = 'writerights';
2463  }
2464  if ( $this->mustBePosted() ) {
2465  $flags[] = 'mustbeposted';
2466  }
2467 
2468  return $flags;
2469  }
2470 
2482  protected function getModuleSourceInfo() {
2483  global $IP;
2484 
2485  if ( $this->mModuleSource !== false ) {
2486  return $this->mModuleSource;
2487  }
2488 
2489  // First, try to find where the module comes from...
2490  $rClass = new ReflectionClass( $this );
2491  $path = $rClass->getFileName();
2492  if ( !$path ) {
2493  // No path known?
2494  $this->mModuleSource = null;
2495  return null;
2496  }
2497  $path = realpath( $path ) ?: $path;
2498 
2499  // Build map of extension directories to extension info
2500  if ( self::$extensionInfo === null ) {
2501  self::$extensionInfo = [
2502  realpath( __DIR__ ) ?: __DIR__ => [
2503  'path' => $IP,
2504  'name' => 'MediaWiki',
2505  'license-name' => 'GPL-2.0+',
2506  ],
2507  realpath( "$IP/extensions" ) ?: "$IP/extensions" => null,
2508  ];
2509  $keep = [
2510  'path' => null,
2511  'name' => null,
2512  'namemsg' => null,
2513  'license-name' => null,
2514  ];
2515  foreach ( $this->getConfig()->get( 'ExtensionCredits' ) as $group ) {
2516  foreach ( $group as $ext ) {
2517  if ( !isset( $ext['path'] ) || !isset( $ext['name'] ) ) {
2518  // This shouldn't happen, but does anyway.
2519  continue;
2520  }
2521 
2522  $extpath = $ext['path'];
2523  if ( !is_dir( $extpath ) ) {
2524  $extpath = dirname( $extpath );
2525  }
2526  self::$extensionInfo[realpath( $extpath ) ?: $extpath] =
2527  array_intersect_key( $ext, $keep );
2528  }
2529  }
2530  foreach ( ExtensionRegistry::getInstance()->getAllThings() as $ext ) {
2531  $extpath = $ext['path'];
2532  if ( !is_dir( $extpath ) ) {
2533  $extpath = dirname( $extpath );
2534  }
2535  self::$extensionInfo[realpath( $extpath ) ?: $extpath] =
2536  array_intersect_key( $ext, $keep );
2537  }
2538  }
2539 
2540  // Now traverse parent directories until we find a match or run out of
2541  // parents.
2542  do {
2543  if ( array_key_exists( $path, self::$extensionInfo ) ) {
2544  // Found it!
2545  $this->mModuleSource = self::$extensionInfo[$path];
2546  return $this->mModuleSource;
2547  }
2548 
2549  $oldpath = $path;
2550  $path = dirname( $path );
2551  } while ( $path !== $oldpath );
2552 
2553  // No idea what extension this might be.
2554  $this->mModuleSource = null;
2555  return null;
2556  }
2557 
2569  public function modifyHelp( array &$help, array $options, array &$tocData ) {
2570  }
2571 
2574  /************************************************************************/
2588  protected function getDescription() {
2589  return false;
2590  }
2591 
2604  protected function getParamDescription() {
2605  return [];
2606  }
2607 
2624  protected function getExamples() {
2625  return false;
2626  }
2627 
2633  public function makeHelpMsg() {
2634  wfDeprecated( __METHOD__, '1.25' );
2635  static $lnPrfx = "\n ";
2636 
2637  $msg = $this->getFinalDescription();
2638 
2639  if ( $msg !== false ) {
2640 
2641  if ( !is_array( $msg ) ) {
2642  $msg = [
2643  $msg
2644  ];
2645  }
2646  $msg = $lnPrfx . implode( $lnPrfx, $msg ) . "\n";
2647 
2648  $msg .= $this->makeHelpArrayToString( $lnPrfx, false, $this->getHelpUrls() );
2649 
2650  if ( $this->isReadMode() ) {
2651  $msg .= "\nThis module requires read rights";
2652  }
2653  if ( $this->isWriteMode() ) {
2654  $msg .= "\nThis module requires write rights";
2655  }
2656  if ( $this->mustBePosted() ) {
2657  $msg .= "\nThis module only accepts POST requests";
2658  }
2659  if ( $this->isReadMode() || $this->isWriteMode() ||
2660  $this->mustBePosted()
2661  ) {
2662  $msg .= "\n";
2663  }
2664 
2665  // Parameters
2666  $paramsMsg = $this->makeHelpMsgParameters();
2667  if ( $paramsMsg !== false ) {
2668  $msg .= "Parameters:\n$paramsMsg";
2669  }
2670 
2671  $examples = $this->getExamples();
2672  if ( $examples ) {
2673  if ( !is_array( $examples ) ) {
2674  $examples = [
2675  $examples
2676  ];
2677  }
2678  $msg .= 'Example' . ( count( $examples ) > 1 ? 's' : '' ) . ":\n";
2679  foreach ( $examples as $k => $v ) {
2680  if ( is_numeric( $k ) ) {
2681  $msg .= " $v\n";
2682  } else {
2683  if ( is_array( $v ) ) {
2684  $msgExample = implode( "\n", array_map( [ $this, 'indentExampleText' ], $v ) );
2685  } else {
2686  $msgExample = " $v";
2687  }
2688  $msgExample .= ':';
2689  $msg .= wordwrap( $msgExample, 100, "\n" ) . "\n $k\n";
2690  }
2691  }
2692  }
2693  }
2694 
2695  return $msg;
2696  }
2697 
2703  private function indentExampleText( $item ) {
2704  return ' ' . $item;
2705  }
2706 
2714  protected function makeHelpArrayToString( $prefix, $title, $input ) {
2715  wfDeprecated( __METHOD__, '1.25' );
2716  if ( $input === false ) {
2717  return '';
2718  }
2719  if ( !is_array( $input ) ) {
2720  $input = [ $input ];
2721  }
2722 
2723  if ( count( $input ) > 0 ) {
2724  if ( $title ) {
2725  $msg = $title . ( count( $input ) > 1 ? 's' : '' ) . ":\n ";
2726  } else {
2727  $msg = ' ';
2728  }
2729  $msg .= implode( $prefix, $input ) . "\n";
2730 
2731  return $msg;
2732  }
2733 
2734  return '';
2735  }
2736 
2743  public function makeHelpMsgParameters() {
2744  wfDeprecated( __METHOD__, '1.25' );
2746  if ( $params ) {
2747  $paramsDescription = $this->getFinalParamDescription();
2748  $msg = '';
2749  $paramPrefix = "\n" . str_repeat( ' ', 24 );
2750  $descWordwrap = "\n" . str_repeat( ' ', 28 );
2751  foreach ( $params as $paramName => $paramSettings ) {
2752  $desc = isset( $paramsDescription[$paramName] ) ? $paramsDescription[$paramName] : '';
2753  if ( is_array( $desc ) ) {
2754  $desc = implode( $paramPrefix, $desc );
2755  }
2756 
2757  // handle shorthand
2758  if ( !is_array( $paramSettings ) ) {
2759  $paramSettings = [
2760  self::PARAM_DFLT => $paramSettings,
2761  ];
2762  }
2763 
2764  // handle missing type
2765  if ( !isset( $paramSettings[ApiBase::PARAM_TYPE] ) ) {
2766  $dflt = isset( $paramSettings[ApiBase::PARAM_DFLT] )
2767  ? $paramSettings[ApiBase::PARAM_DFLT]
2768  : null;
2769  if ( is_bool( $dflt ) ) {
2770  $paramSettings[ApiBase::PARAM_TYPE] = 'boolean';
2771  } elseif ( is_string( $dflt ) || is_null( $dflt ) ) {
2772  $paramSettings[ApiBase::PARAM_TYPE] = 'string';
2773  } elseif ( is_int( $dflt ) ) {
2774  $paramSettings[ApiBase::PARAM_TYPE] = 'integer';
2775  }
2776  }
2777 
2778  if ( isset( $paramSettings[self::PARAM_DEPRECATED] )
2779  && $paramSettings[self::PARAM_DEPRECATED]
2780  ) {
2781  $desc = "DEPRECATED! $desc";
2782  }
2783 
2784  if ( isset( $paramSettings[self::PARAM_REQUIRED] )
2785  && $paramSettings[self::PARAM_REQUIRED]
2786  ) {
2787  $desc .= $paramPrefix . 'This parameter is required';
2788  }
2789 
2790  $type = isset( $paramSettings[self::PARAM_TYPE] )
2791  ? $paramSettings[self::PARAM_TYPE]
2792  : null;
2793  if ( isset( $type ) ) {
2794  $hintPipeSeparated = true;
2795  $multi = isset( $paramSettings[self::PARAM_ISMULTI] )
2796  ? $paramSettings[self::PARAM_ISMULTI]
2797  : false;
2798  if ( $multi ) {
2799  $prompt = 'Values (separate with \'|\'): ';
2800  } else {
2801  $prompt = 'One value: ';
2802  }
2803 
2804  if ( $type === 'submodule' ) {
2805  if ( isset( $paramSettings[self::PARAM_SUBMODULE_MAP] ) ) {
2806  $type = array_keys( $paramSettings[self::PARAM_SUBMODULE_MAP] );
2807  } else {
2808  $type = $this->getModuleManager()->getNames( $paramName );
2809  }
2810  sort( $type );
2811  }
2812  if ( is_array( $type ) ) {
2813  $choices = [];
2814  $nothingPrompt = '';
2815  foreach ( $type as $t ) {
2816  if ( $t === '' ) {
2817  $nothingPrompt = 'Can be empty, or ';
2818  } else {
2819  $choices[] = $t;
2820  }
2821  }
2822  $desc .= $paramPrefix . $nothingPrompt . $prompt;
2823  $choicesstring = implode( ', ', $choices );
2824  $desc .= wordwrap( $choicesstring, 100, $descWordwrap );
2825  $hintPipeSeparated = false;
2826  } else {
2827  switch ( $type ) {
2828  case 'namespace':
2829  // Special handling because namespaces are
2830  // type-limited, yet they are not given
2831  $desc .= $paramPrefix . $prompt;
2832  $desc .= wordwrap( implode( ', ', MWNamespace::getValidNamespaces() ),
2833  100, $descWordwrap );
2834  $hintPipeSeparated = false;
2835  break;
2836  case 'limit':
2837  $desc .= $paramPrefix . "No more than {$paramSettings[self::PARAM_MAX]}";
2838  if ( isset( $paramSettings[self::PARAM_MAX2] ) ) {
2839  $desc .= " ({$paramSettings[self::PARAM_MAX2]} for bots)";
2840  }
2841  $desc .= ' allowed';
2842  break;
2843  case 'integer':
2844  $s = $multi ? 's' : '';
2845  $hasMin = isset( $paramSettings[self::PARAM_MIN] );
2846  $hasMax = isset( $paramSettings[self::PARAM_MAX] );
2847  if ( $hasMin || $hasMax ) {
2848  if ( !$hasMax ) {
2849  $intRangeStr = "The value$s must be no less than " .
2850  "{$paramSettings[self::PARAM_MIN]}";
2851  } elseif ( !$hasMin ) {
2852  $intRangeStr = "The value$s must be no more than " .
2853  "{$paramSettings[self::PARAM_MAX]}";
2854  } else {
2855  $intRangeStr = "The value$s must be between " .
2856  "{$paramSettings[self::PARAM_MIN]} and {$paramSettings[self::PARAM_MAX]}";
2857  }
2858 
2859  $desc .= $paramPrefix . $intRangeStr;
2860  }
2861  break;
2862  case 'upload':
2863  $desc .= $paramPrefix . 'Must be posted as a file upload using multipart/form-data';
2864  break;
2865  }
2866  }
2867 
2868  if ( $multi ) {
2869  if ( $hintPipeSeparated ) {
2870  $desc .= $paramPrefix . "Separate values with '|'";
2871  }
2872 
2873  $isArray = is_array( $type );
2874  if ( !$isArray
2875  || $isArray && count( $type ) > self::LIMIT_SML1
2876  ) {
2877  $desc .= $paramPrefix . 'Maximum number of values ' .
2878  self::LIMIT_SML1 . ' (' . self::LIMIT_SML2 . ' for bots)';
2879  }
2880  }
2881  }
2882 
2883  $default = isset( $paramSettings[self::PARAM_DFLT] ) ? $paramSettings[self::PARAM_DFLT] : null;
2884  if ( !is_null( $default ) && $default !== false ) {
2885  $desc .= $paramPrefix . "Default: $default";
2886  }
2887 
2888  $msg .= sprintf( " %-19s - %s\n", $this->encodeParamName( $paramName ), $desc );
2889  }
2890 
2891  return $msg;
2892  }
2893 
2894  return false;
2895  }
2896 
2902  public function getModuleProfileName( $db = false ) {
2903  wfDeprecated( __METHOD__, '1.25' );
2904  return '';
2905  }
2906 
2910  public function profileIn() {
2911  // No wfDeprecated() yet because extensions call this and might need to
2912  // keep doing so for BC.
2913  }
2914 
2918  public function profileOut() {
2919  // No wfDeprecated() yet because extensions call this and might need to
2920  // keep doing so for BC.
2921  }
2922 
2926  public function safeProfileOut() {
2927  wfDeprecated( __METHOD__, '1.25' );
2928  }
2929 
2934  public function getProfileTime() {
2935  wfDeprecated( __METHOD__, '1.25' );
2936  return 0;
2937  }
2938 
2942  public function profileDBIn() {
2943  wfDeprecated( __METHOD__, '1.25' );
2944  }
2945 
2949  public function profileDBOut() {
2950  wfDeprecated( __METHOD__, '1.25' );
2951  }
2952 
2957  public function getProfileDBTime() {
2958  wfDeprecated( __METHOD__, '1.25' );
2959  return 0;
2960  }
2961 
2967  public function getResultData() {
2968  wfDeprecated( __METHOD__, '1.25' );
2969  return $this->getResult()->getData();
2970  }
2971 
2976  protected function useTransactionalTimeLimit() {
2977  if ( $this->getRequest()->wasPosted() ) {
2979  }
2980  }
2981 
2983 }
2984 
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:2162
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:2335
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:598
const LIMIT_BIG2
Fast query, apihighlimits limit.
Definition: ApiBase.php:186
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
Interface for objects which can provide a MediaWiki context on request.
wfGetDB($db, $groups=[], $wiki=false)
Get a Database object.
profileDBOut()
Definition: ApiBase.php:2949
isReadMode()
Indicates whether this module requires read rights.
Definition: ApiBase.php:363
the array() calling protocol came about after MediaWiki 1.4rc1.
validateTimestamp($value, $encParamName)
Validate and normalize of parameters of type 'timestamp'.
Definition: ApiBase.php:1276
getResult()
Get the result object.
Definition: ApiBase.php:584
static $messageMap
Array that maps message keys to error messages.
Definition: ApiBase.php:1625
getWatchlistUser($params)
Gets the user for whom to get the watchlist.
Definition: ApiBase.php:1406
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:709
getDescriptionMessage()
Return the description message.
Definition: ApiBase.php:2261
getModuleProfileName($db=false)
Definition: ApiBase.php:2902
getModuleSourceInfo()
Returns information about the source of this module, if known.
Definition: ApiBase.php:2482
$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:267
static array $extensionInfo
Maps extension paths to info arrays.
Definition: ApiBase.php:200
requireMaxOneParameter($params, $required)
Die if more than one of a certain set of parameters is set and not false.
Definition: ApiBase.php:747
useTransactionalTimeLimit()
Call wfTransactionalTimeLimit() if this request was POSTed.
Definition: ApiBase.php:2976
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:480
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:1439
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:197
const LIMIT_BIG1
Fast query, standard limit.
Definition: ApiBase.php:184
safeProfileOut()
Definition: ApiBase.php:2926
getDB()
Gets a default slave database connection object.
Definition: ApiBase.php:612
getResultData()
Get the result data array (read-only)
Definition: ApiBase.php:2967
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:1375
const PARAM_REQUIRED
(boolean) Is the parameter required?
Definition: ApiBase.php:112
ApiMain $mMainModule
Definition: ApiBase.php:203
getWatchlistValue($watchlist, $titleObj, $userOption=null)
Return true if we're to watch the page, false if not, null if no change.
Definition: ApiBase.php:877
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:512
extractRequestParams($parseLimit=true)
Using getAllowedParams(), this function makes an array of the values provided by the user...
Definition: ApiBase.php:685
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:498
requireOnlyOneParameter($params, $required)
Die if none or more than one of a certain set of parameters is set and not false. ...
Definition: ApiBase.php:721
static makeMessage($msg, IContextSource $context, array $params=null)
Create a Message from a string or array.
Definition: ApiBase.php:1463
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:388
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:329
string $mModuleName
Definition: ApiBase.php:205
needsToken()
Returns the token type this module requires in order to execute.
Definition: ApiBase.php:420
IContextSource $context
indentExampleText($item)
Definition: ApiBase.php:2703
getConditionalRequestData($condition)
Returns data for HTTP conditional request mechanisms.
Definition: ApiBase.php:449
getParameterFromSettings($paramName, $paramSettings, $parseLimit)
Using the settings determine the value for the given parameter.
Definition: ApiBase.php:919
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:840
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:1390
profileOut()
Definition: ApiBase.php:2918
validateToken($token, array $params)
Validate the supplied token.
Definition: ApiBase.php:1315
parameterNotEmpty($x)
Callback function used in requireOnlyOneParameter to check whether required parameters are set...
Definition: ApiBase.php:825
getProfileTime()
Definition: ApiBase.php:2934
getErrorFromStatus($status, &$extraData=null)
Get error (as code, string) from a Status object.
Definition: ApiBase.php:1571
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:2449
const PARAM_RANGE_ENFORCE
(boolean) For PARAM_TYPE 'integer', enforce PARAM_MIN and PARAM_MAX?
Definition: ApiBase.php:118
getProfileDBTime()
Definition: ApiBase.php:2957
getModulePath()
Get the path to this module.
Definition: ApiBase.php:528
getContinuationManager()
Get the continuation manager.
Definition: ApiBase.php:624
getConfig()
Get the Config object.
const LIMIT_SML2
Slow query, apihighlimits limit.
Definition: ApiBase.php:190
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:1350
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:398
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:662
getModuleName()
Get the name of the module being executed by this instance.
Definition: ApiBase.php:464
static dieReadOnly()
Helper function for readonly errors.
Definition: ApiBase.php:2133
static 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:205
const TYPE_AUTO
Definition: Block.php:78
setWarning($warning)
Set warning section for this module.
Definition: ApiBase.php:1495
modifyHelp(array &$help, array $options, array &$tocData)
Called from ApiHelp before the pieces are joined together and returned.
Definition: ApiBase.php:2569
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:2181
requirePostedParameters($params, $prefix= 'prefix')
Die if any of the specified parameters were found in the query part of the URL rather than the post b...
Definition: ApiBase.php:793
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 PARAM_SENSITIVE
(boolean) Is the parameter sensitive? Note 'password'-type fields are always sensitive regardless of ...
Definition: ApiBase.php:179
const TS_MW
MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
const LIMIT_SML1
Slow query, standard limit.
Definition: ApiBase.php:188
getModuleManager()
Get the module manager, or null if this module has no sub-modules.
Definition: ApiBase.php:254
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:379
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:472
validateLimit($paramName, &$value, $min, $max, $botMax=null, $enforceLimits=false)
Validate the value against the minimum and user/bot maximum limits.
Definition: ApiBase.php:1237
getDescription()
Returns the description string for this module.
Definition: ApiBase.php:2588
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:1173
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:2272
$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:770
makeHelpMsg()
Generates help message for this module, or false if there is no description.
Definition: ApiBase.php:2633
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:216
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: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 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:2624
profileIn()
Definition: ApiBase.php:2910
dieBlocked(Block $block)
Throw a UsageException, which will (if uncaught) call the main module's error handler and die with an...
Definition: ApiBase.php:1543
$mParamCache
Definition: ApiBase.php:207
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:433
const PARAM_DEPRECATED
(boolean) Is the parameter deprecated (will show a warning)?
Definition: ApiBase.php:106
array null bool $mModuleSource
Definition: ApiBase.php:209
getParamDescription()
Returns an array of parameter descriptions.
Definition: ApiBase.php:2604
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:282
parseMsg($error)
Return the error message related to a certain array.
Definition: ApiBase.php:2194
profileDBIn()
Definition: ApiBase.php:2942
makeHelpMsgParameters()
Generates the parameter descriptions for this module, to be displayed in the module's help...
Definition: ApiBase.php:2743
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:2230
logFeatureUsage($feature)
Write logging information for API features to a debug log, for usage analysis.
Definition: ApiBase.php:2239
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:1615
shouldCheckMaxlag()
Indicates if this module needs maxlag to be checked.
Definition: ApiBase.php:355
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:672
setContinuationManager($manager)
Set the continuation manager.
Definition: ApiBase.php:638
warnOrDie($msg, $enforceLimits=false)
Adds a warning to the output, else dies.
Definition: ApiBase.php:1506
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:2144
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:546
This exception will be thrown when dieUsage is called to stop module execution.
Definition: ApiMain.php:1888
getFinalParams($flags=0)
Get final list of parameters, after hooks have had a chance to tweak it as needed.
Definition: ApiBase.php:2305
isMain()
Returns true if this module is the main module ($this === $this->mMainModule), false otherwise...
Definition: ApiBase.php:489
isWriteMode()
Indicates whether this module requires write mode.
Definition: ApiBase.php:371
makeHelpArrayToString($prefix, $title, $input)
Definition: ApiBase.php:2714
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:345