MediaWiki  master
ApiBase.php
Go to the documentation of this file.
1 <?php
25 
38 abstract class ApiBase extends ContextSource {
39 
49  const PARAM_DFLT = 0;
50 
52  const PARAM_ISMULTI = 1;
53 
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 
159 
167 
174 
181  const PARAM_ALL = 17;
182 
188 
194  const PARAM_SENSITIVE = 19;
195 
204 
210 
217 
222  const PARAM_MAX_BYTES = 23;
223 
228  const PARAM_MAX_CHARS = 24;
229 
247 
250  const ALL_DEFAULT_STRING = '*';
251 
253  const LIMIT_BIG1 = 500;
255  const LIMIT_BIG2 = 5000;
257  const LIMIT_SML1 = 50;
259  const LIMIT_SML2 = 500;
260 
267 
269  private static $extensionInfo = null;
270 
272  private static $filterIDsCache = [];
273 
275  private $mMainModule;
278  private $mReplicaDB = null;
279  private $mParamCache = [];
281  private $mModuleSource = false;
282 
288  public function __construct( ApiMain $mainModule, $moduleName, $modulePrefix = '' ) {
289  $this->mMainModule = $mainModule;
290  $this->mModuleName = $moduleName;
291  $this->mModulePrefix = $modulePrefix;
292 
293  if ( !$this->isMain() ) {
294  $this->setContext( $mainModule->getContext() );
295  }
296  }
297 
298  /************************************************************************/
319  abstract public function execute();
320 
326  public function getModuleManager() {
327  return null;
328  }
329 
339  public function getCustomPrinter() {
340  return null;
341  }
342 
354  protected function getExamplesMessages() {
355  return [];
356  }
357 
363  public function getHelpUrls() {
364  return [];
365  }
366 
379  protected function getAllowedParams( /* $flags = 0 */ ) {
380  // int $flags is not declared because it causes "Strict standards"
381  // warning. Most derived classes do not implement it.
382  return [];
383  }
384 
389  public function shouldCheckMaxlag() {
390  return true;
391  }
392 
397  public function isReadMode() {
398  return true;
399  }
400 
412  public function isWriteMode() {
413  return false;
414  }
415 
420  public function mustBePosted() {
421  return $this->needsToken() !== false;
422  }
423 
429  public function isDeprecated() {
430  return false;
431  }
432 
439  public function isInternal() {
440  return false;
441  }
442 
461  public function needsToken() {
462  return false;
463  }
464 
474  protected function getWebUITokenSalt( array $params ) {
475  return null;
476  }
477 
490  public function getConditionalRequestData( $condition ) {
491  return null;
492  }
493 
496  /************************************************************************/
505  public function getModuleName() {
506  return $this->mModuleName;
507  }
508 
513  public function getModulePrefix() {
514  return $this->mModulePrefix;
515  }
516 
521  public function getMain() {
522  return $this->mMainModule;
523  }
524 
530  public function isMain() {
531  return $this === $this->mMainModule;
532  }
533 
539  public function getParent() {
540  return $this->isMain() ? null : $this->getMain();
541  }
542 
553  public function lacksSameOriginSecurity() {
554  // Main module has this method overridden
555  // Safety - avoid infinite loop:
556  if ( $this->isMain() ) {
557  self::dieDebug( __METHOD__, 'base method was called on main module.' );
558  }
559 
560  return $this->getMain()->lacksSameOriginSecurity();
561  }
562 
569  public function getModulePath() {
570  if ( $this->isMain() ) {
571  return 'main';
572  } elseif ( $this->getParent()->isMain() ) {
573  return $this->getModuleName();
574  } else {
575  return $this->getParent()->getModulePath() . '+' . $this->getModuleName();
576  }
577  }
578 
587  public function getModuleFromPath( $path ) {
588  $module = $this->getMain();
589  if ( $path === 'main' ) {
590  return $module;
591  }
592 
593  $parts = explode( '+', $path );
594  if ( count( $parts ) === 1 ) {
595  // In case the '+' was typed into URL, it resolves as a space
596  $parts = explode( ' ', $path );
597  }
598 
599  $count = count( $parts );
600  for ( $i = 0; $i < $count; $i++ ) {
601  $parent = $module;
602  $manager = $parent->getModuleManager();
603  if ( $manager === null ) {
604  $errorPath = implode( '+', array_slice( $parts, 0, $i ) );
605  $this->dieWithError( [ 'apierror-badmodule-nosubmodules', $errorPath ], 'badmodule' );
606  }
607  $module = $manager->getModule( $parts[$i] );
608 
609  if ( $module === null ) {
610  $errorPath = $i ? implode( '+', array_slice( $parts, 0, $i ) ) : $parent->getModuleName();
611  $this->dieWithError(
612  [ 'apierror-badmodule-badsubmodule', $errorPath, wfEscapeWikiText( $parts[$i] ) ],
613  'badmodule'
614  );
615  }
616  }
617 
618  return $module;
619  }
620 
625  public function getResult() {
626  // Main module has getResult() method overridden
627  // Safety - avoid infinite loop:
628  if ( $this->isMain() ) {
629  self::dieDebug( __METHOD__, 'base method was called on main module. ' );
630  }
631 
632  return $this->getMain()->getResult();
633  }
634 
639  public function getErrorFormatter() {
640  // Main module has getErrorFormatter() method overridden
641  // Safety - avoid infinite loop:
642  if ( $this->isMain() ) {
643  self::dieDebug( __METHOD__, 'base method was called on main module. ' );
644  }
645 
646  return $this->getMain()->getErrorFormatter();
647  }
648 
653  protected function getDB() {
654  if ( !isset( $this->mReplicaDB ) ) {
655  $this->mReplicaDB = wfGetDB( DB_REPLICA, 'api' );
656  }
657 
658  return $this->mReplicaDB;
659  }
660 
665  public function getContinuationManager() {
666  // Main module has getContinuationManager() method overridden
667  // Safety - avoid infinite loop:
668  if ( $this->isMain() ) {
669  self::dieDebug( __METHOD__, 'base method was called on main module. ' );
670  }
671 
672  return $this->getMain()->getContinuationManager();
673  }
674 
679  public function setContinuationManager( ApiContinuationManager $manager = null ) {
680  // Main module has setContinuationManager() method overridden
681  // Safety - avoid infinite loop:
682  if ( $this->isMain() ) {
683  self::dieDebug( __METHOD__, 'base method was called on main module. ' );
684  }
685 
686  $this->getMain()->setContinuationManager( $manager );
687  }
688 
691  /************************************************************************/
703  public function dynamicParameterDocumentation() {
704  return null;
705  }
706 
714  public function encodeParamName( $paramName ) {
715  if ( is_array( $paramName ) ) {
716  return array_map( function ( $name ) {
717  return $this->mModulePrefix . $name;
718  }, $paramName );
719  } else {
720  return $this->mModulePrefix . $paramName;
721  }
722  }
723 
736  public function extractRequestParams( $options = [] ) {
737  if ( is_bool( $options ) ) {
738  $options = [ 'parseLimit' => $options ];
739  }
740  $options += [
741  'parseLimit' => true,
742  'safeMode' => false,
743  ];
744 
745  $parseLimit = (bool)$options['parseLimit'];
746 
747  // Cache parameters, for performance and to avoid T26564.
748  if ( !isset( $this->mParamCache[$parseLimit] ) ) {
749  $params = $this->getFinalParams() ?: [];
750  $results = [];
751  $warned = [];
752 
753  // Process all non-templates and save templates for secondary
754  // processing.
755  $toProcess = [];
756  foreach ( $params as $paramName => $paramSettings ) {
757  if ( isset( $paramSettings[self::PARAM_TEMPLATE_VARS] ) ) {
758  $toProcess[] = [ $paramName, $paramSettings[self::PARAM_TEMPLATE_VARS], $paramSettings ];
759  } else {
760  try {
761  $results[$paramName] = $this->getParameterFromSettings(
762  $paramName, $paramSettings, $parseLimit
763  );
764  } catch ( ApiUsageException $ex ) {
765  $results[$paramName] = $ex;
766  }
767  }
768  }
769 
770  // Now process all the templates by successively replacing the
771  // placeholders with all client-supplied values.
772  // This bit duplicates JavaScript logic in
773  // ApiSandbox.PageLayout.prototype.updateTemplatedParams().
774  // If you update this, see if that needs updating too.
775  while ( $toProcess ) {
776  list( $name, $targets, $settings ) = array_shift( $toProcess );
777 
778  foreach ( $targets as $placeholder => $target ) {
779  if ( !array_key_exists( $target, $results ) ) {
780  // The target wasn't processed yet, try the next one.
781  // If all hit this case, the parameter has no expansions.
782  continue;
783  }
784  if ( !is_array( $results[$target] ) || !$results[$target] ) {
785  // The target was processed but has no (valid) values.
786  // That means it has no expansions.
787  break;
788  }
789 
790  // Expand this target in the name and all other targets,
791  // then requeue if there are more targets left or put in
792  // $results if all are done.
793  unset( $targets[$placeholder] );
794  $placeholder = '{' . $placeholder . '}';
795  foreach ( $results[$target] as $value ) {
796  if ( !preg_match( '/^[^{}]*$/', $value ) ) {
797  // Skip values that make invalid parameter names.
798  $encTargetName = $this->encodeParamName( $target );
799  if ( !isset( $warned[$encTargetName][$value] ) ) {
800  $warned[$encTargetName][$value] = true;
801  $this->addWarning( [
802  'apiwarn-ignoring-invalid-templated-value',
803  wfEscapeWikiText( $encTargetName ),
804  wfEscapeWikiText( $value ),
805  ] );
806  }
807  continue;
808  }
809 
810  $newName = str_replace( $placeholder, $value, $name );
811  if ( !$targets ) {
812  try {
813  $results[$newName] = $this->getParameterFromSettings( $newName, $settings, $parseLimit );
814  } catch ( ApiUsageException $ex ) {
815  $results[$newName] = $ex;
816  }
817  } else {
818  $newTargets = [];
819  foreach ( $targets as $k => $v ) {
820  $newTargets[$k] = str_replace( $placeholder, $value, $v );
821  }
822  $toProcess[] = [ $newName, $newTargets, $settings ];
823  }
824  }
825  break;
826  }
827  }
828 
829  $this->mParamCache[$parseLimit] = $results;
830  }
831 
832  $ret = $this->mParamCache[$parseLimit];
833  if ( !$options['safeMode'] ) {
834  foreach ( $ret as $v ) {
835  if ( $v instanceof ApiUsageException ) {
836  throw $v;
837  }
838  }
839  }
840 
841  return $this->mParamCache[$parseLimit];
842  }
843 
850  protected function getParameter( $paramName, $parseLimit = true ) {
851  $ret = $this->extractRequestParams( [
852  'parseLimit' => $parseLimit,
853  'safeMode' => true,
854  ] )[$paramName];
855  if ( $ret instanceof ApiUsageException ) {
856  throw $ret;
857  }
858  return $ret;
859  }
860 
867  public function requireOnlyOneParameter( $params, $required /*...*/ ) {
868  $required = func_get_args();
869  array_shift( $required );
870 
871  $intersection = array_intersect( array_keys( array_filter( $params,
872  [ $this, 'parameterNotEmpty' ] ) ), $required );
873 
874  if ( count( $intersection ) > 1 ) {
875  $this->dieWithError( [
876  'apierror-invalidparammix',
877  Message::listParam( array_map(
878  function ( $p ) {
879  return '<var>' . $this->encodeParamName( $p ) . '</var>';
880  },
881  array_values( $intersection )
882  ) ),
883  count( $intersection ),
884  ] );
885  } elseif ( count( $intersection ) == 0 ) {
886  $this->dieWithError( [
887  'apierror-missingparam-one-of',
888  Message::listParam( array_map(
889  function ( $p ) {
890  return '<var>' . $this->encodeParamName( $p ) . '</var>';
891  },
892  array_values( $required )
893  ) ),
894  count( $required ),
895  ], 'missingparam' );
896  }
897  }
898 
905  public function requireMaxOneParameter( $params, $required /*...*/ ) {
906  $required = func_get_args();
907  array_shift( $required );
908 
909  $intersection = array_intersect( array_keys( array_filter( $params,
910  [ $this, 'parameterNotEmpty' ] ) ), $required );
911 
912  if ( count( $intersection ) > 1 ) {
913  $this->dieWithError( [
914  'apierror-invalidparammix',
915  Message::listParam( array_map(
916  function ( $p ) {
917  return '<var>' . $this->encodeParamName( $p ) . '</var>';
918  },
919  array_values( $intersection )
920  ) ),
921  count( $intersection ),
922  ] );
923  }
924  }
925 
933  public function requireAtLeastOneParameter( $params, $required /*...*/ ) {
934  $required = func_get_args();
935  array_shift( $required );
936 
937  $intersection = array_intersect(
938  array_keys( array_filter( $params, [ $this, 'parameterNotEmpty' ] ) ),
939  $required
940  );
941 
942  if ( count( $intersection ) == 0 ) {
943  $this->dieWithError( [
944  'apierror-missingparam-at-least-one-of',
945  Message::listParam( array_map(
946  function ( $p ) {
947  return '<var>' . $this->encodeParamName( $p ) . '</var>';
948  },
949  array_values( $required )
950  ) ),
951  count( $required ),
952  ], 'missingparam' );
953  }
954  }
955 
963  public function requirePostedParameters( $params, $prefix = 'prefix' ) {
964  // Skip if $wgDebugAPI is set or we're in internal mode
965  if ( $this->getConfig()->get( 'DebugAPI' ) || $this->getMain()->isInternalMode() ) {
966  return;
967  }
968 
969  $queryValues = $this->getRequest()->getQueryValues();
970  $badParams = [];
971  foreach ( $params as $param ) {
972  if ( $prefix !== 'noprefix' ) {
973  $param = $this->encodeParamName( $param );
974  }
975  if ( array_key_exists( $param, $queryValues ) ) {
976  $badParams[] = $param;
977  }
978  }
979 
980  if ( $badParams ) {
981  $this->dieWithError(
982  [ 'apierror-mustpostparams', implode( ', ', $badParams ), count( $badParams ) ]
983  );
984  }
985  }
986 
993  private function parameterNotEmpty( $x ) {
994  return !is_null( $x ) && $x !== false;
995  }
996 
1008  public function getTitleOrPageId( $params, $load = false ) {
1009  $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
1010 
1011  $pageObj = null;
1012  if ( isset( $params['title'] ) ) {
1013  $titleObj = Title::newFromText( $params['title'] );
1014  if ( !$titleObj || $titleObj->isExternal() ) {
1015  $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
1016  }
1017  if ( !$titleObj->canExist() ) {
1018  $this->dieWithError( 'apierror-pagecannotexist' );
1019  }
1020  $pageObj = WikiPage::factory( $titleObj );
1021  if ( $load !== false ) {
1022  $pageObj->loadPageData( $load );
1023  }
1024  } elseif ( isset( $params['pageid'] ) ) {
1025  if ( $load === false ) {
1026  $load = 'fromdb';
1027  }
1028  $pageObj = WikiPage::newFromID( $params['pageid'], $load );
1029  if ( !$pageObj ) {
1030  $this->dieWithError( [ 'apierror-nosuchpageid', $params['pageid'] ] );
1031  }
1032  }
1033 
1034  return $pageObj;
1035  }
1036 
1045  public function getTitleFromTitleOrPageId( $params ) {
1046  $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
1047 
1048  $titleObj = null;
1049  if ( isset( $params['title'] ) ) {
1050  $titleObj = Title::newFromText( $params['title'] );
1051  if ( !$titleObj || $titleObj->isExternal() ) {
1052  $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
1053  }
1054  return $titleObj;
1055  } elseif ( isset( $params['pageid'] ) ) {
1056  $titleObj = Title::newFromID( $params['pageid'] );
1057  if ( !$titleObj ) {
1058  $this->dieWithError( [ 'apierror-nosuchpageid', $params['pageid'] ] );
1059  }
1060  }
1061 
1062  return $titleObj;
1063  }
1064 
1073  protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
1074  $userWatching = $this->getUser()->isWatched( $titleObj, User::IGNORE_USER_RIGHTS );
1075 
1076  switch ( $watchlist ) {
1077  case 'watch':
1078  return true;
1079 
1080  case 'unwatch':
1081  return false;
1082 
1083  case 'preferences':
1084  # If the user is already watching, don't bother checking
1085  if ( $userWatching ) {
1086  return true;
1087  }
1088  # If no user option was passed, use watchdefault and watchcreations
1089  if ( is_null( $userOption ) ) {
1090  return $this->getUser()->getBoolOption( 'watchdefault' ) ||
1091  $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
1092  }
1093 
1094  # Watch the article based on the user preference
1095  return $this->getUser()->getBoolOption( $userOption );
1096 
1097  case 'nochange':
1098  return $userWatching;
1099 
1100  default:
1101  return $userWatching;
1102  }
1103  }
1104 
1114  protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
1115  // Some classes may decide to change parameter names
1116  $encParamName = $this->encodeParamName( $paramName );
1117 
1118  // Shorthand
1119  if ( !is_array( $paramSettings ) ) {
1120  $paramSettings = [
1121  self::PARAM_DFLT => $paramSettings,
1122  ];
1123  }
1124 
1125  $default = $paramSettings[self::PARAM_DFLT] ?? null;
1126  $multi = $paramSettings[self::PARAM_ISMULTI] ?? false;
1127  $multiLimit1 = $paramSettings[self::PARAM_ISMULTI_LIMIT1] ?? null;
1128  $multiLimit2 = $paramSettings[self::PARAM_ISMULTI_LIMIT2] ?? null;
1129  $type = $paramSettings[self::PARAM_TYPE] ?? null;
1130  $dupes = $paramSettings[self::PARAM_ALLOW_DUPLICATES] ?? false;
1131  $deprecated = $paramSettings[self::PARAM_DEPRECATED] ?? false;
1132  $deprecatedValues = $paramSettings[self::PARAM_DEPRECATED_VALUES] ?? [];
1133  $required = $paramSettings[self::PARAM_REQUIRED] ?? false;
1134  $allowAll = $paramSettings[self::PARAM_ALL] ?? false;
1135 
1136  // When type is not given, and no choices, the type is the same as $default
1137  if ( !isset( $type ) ) {
1138  if ( isset( $default ) ) {
1139  $type = gettype( $default );
1140  } else {
1141  $type = 'NULL'; // allow everything
1142  }
1143  }
1144 
1145  if ( $type == 'password' || !empty( $paramSettings[self::PARAM_SENSITIVE] ) ) {
1146  $this->getMain()->markParamsSensitive( $encParamName );
1147  }
1148 
1149  if ( $type == 'boolean' ) {
1150  if ( isset( $default ) && $default !== false ) {
1151  // Having a default value of anything other than 'false' is not allowed
1152  self::dieDebug(
1153  __METHOD__,
1154  "Boolean param $encParamName's default is set to '$default'. " .
1155  'Boolean parameters must default to false.'
1156  );
1157  }
1158 
1159  $value = $this->getMain()->getCheck( $encParamName );
1160  } elseif ( $type == 'upload' ) {
1161  if ( isset( $default ) ) {
1162  // Having a default value is not allowed
1163  self::dieDebug(
1164  __METHOD__,
1165  "File upload param $encParamName's default is set to " .
1166  "'$default'. File upload parameters may not have a default." );
1167  }
1168  if ( $multi ) {
1169  self::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
1170  }
1171  $value = $this->getMain()->getUpload( $encParamName );
1172  if ( !$value->exists() ) {
1173  // This will get the value without trying to normalize it
1174  // (because trying to normalize a large binary file
1175  // accidentally uploaded as a field fails spectacularly)
1176  $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
1177  if ( $value !== null ) {
1178  $this->dieWithError(
1179  [ 'apierror-badupload', $encParamName ],
1180  "badupload_{$encParamName}"
1181  );
1182  }
1183  }
1184  } else {
1185  $value = $this->getMain()->getVal( $encParamName, $default );
1186 
1187  if ( isset( $value ) && $type == 'namespace' ) {
1189  if ( isset( $paramSettings[self::PARAM_EXTRA_NAMESPACES] ) &&
1190  is_array( $paramSettings[self::PARAM_EXTRA_NAMESPACES] )
1191  ) {
1192  $type = array_merge( $type, $paramSettings[self::PARAM_EXTRA_NAMESPACES] );
1193  }
1194  // Namespace parameters allow ALL_DEFAULT_STRING to be used to
1195  // specify all namespaces irrespective of PARAM_ALL.
1196  $allowAll = true;
1197  }
1198  if ( isset( $value ) && $type == 'submodule' ) {
1199  if ( isset( $paramSettings[self::PARAM_SUBMODULE_MAP] ) ) {
1200  $type = array_keys( $paramSettings[self::PARAM_SUBMODULE_MAP] );
1201  } else {
1202  $type = $this->getModuleManager()->getNames( $paramName );
1203  }
1204  }
1205 
1206  $request = $this->getMain()->getRequest();
1207  $rawValue = $request->getRawVal( $encParamName );
1208  if ( $rawValue === null ) {
1209  $rawValue = $default;
1210  }
1211 
1212  // Preserve U+001F for self::parseMultiValue(), or error out if that won't be called
1213  if ( isset( $value ) && substr( $rawValue, 0, 1 ) === "\x1f" ) {
1214  if ( $multi ) {
1215  // This loses the potential checkTitleEncoding() transformation done by
1216  // WebRequest for $_GET. Let's call that a feature.
1217  $value = implode( "\x1f", $request->normalizeUnicode( explode( "\x1f", $rawValue ) ) );
1218  } else {
1219  $this->dieWithError( 'apierror-badvalue-notmultivalue', 'badvalue_notmultivalue' );
1220  }
1221  }
1222 
1223  // Check for NFC normalization, and warn
1224  if ( $rawValue !== $value ) {
1225  $this->handleParamNormalization( $paramName, $value, $rawValue );
1226  }
1227  }
1228 
1229  $allSpecifier = ( is_string( $allowAll ) ? $allowAll : self::ALL_DEFAULT_STRING );
1230  if ( $allowAll && $multi && is_array( $type ) && in_array( $allSpecifier, $type, true ) ) {
1231  self::dieDebug(
1232  __METHOD__,
1233  "For param $encParamName, PARAM_ALL collides with a possible value" );
1234  }
1235  if ( isset( $value ) && ( $multi || is_array( $type ) ) ) {
1236  $value = $this->parseMultiValue(
1237  $encParamName,
1238  $value,
1239  $multi,
1240  is_array( $type ) ? $type : null,
1241  $allowAll ? $allSpecifier : null,
1242  $multiLimit1,
1243  $multiLimit2
1244  );
1245  }
1246 
1247  if ( isset( $value ) ) {
1248  // More validation only when choices were not given
1249  // choices were validated in parseMultiValue()
1250  if ( !is_array( $type ) ) {
1251  switch ( $type ) {
1252  case 'NULL': // nothing to do
1253  break;
1254  case 'string':
1255  case 'text':
1256  case 'password':
1257  if ( $required && $value === '' ) {
1258  $this->dieWithError( [ 'apierror-missingparam', $encParamName ] );
1259  }
1260  break;
1261  case 'integer': // Force everything using intval() and optionally validate limits
1262  $min = $paramSettings[self::PARAM_MIN] ?? null;
1263  $max = $paramSettings[self::PARAM_MAX] ?? null;
1264  $enforceLimits = $paramSettings[self::PARAM_RANGE_ENFORCE] ?? false;
1265 
1266  if ( is_array( $value ) ) {
1267  $value = array_map( 'intval', $value );
1268  if ( !is_null( $min ) || !is_null( $max ) ) {
1269  foreach ( $value as &$v ) {
1270  $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
1271  }
1272  }
1273  } else {
1274  $value = intval( $value );
1275  if ( !is_null( $min ) || !is_null( $max ) ) {
1276  $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
1277  }
1278  }
1279  break;
1280  case 'limit':
1281  if ( !$parseLimit ) {
1282  // Don't do any validation whatsoever
1283  break;
1284  }
1285  if ( !isset( $paramSettings[self::PARAM_MAX] )
1286  || !isset( $paramSettings[self::PARAM_MAX2] )
1287  ) {
1288  self::dieDebug(
1289  __METHOD__,
1290  "MAX1 or MAX2 are not defined for the limit $encParamName"
1291  );
1292  }
1293  if ( $multi ) {
1294  self::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
1295  }
1296  $min = $paramSettings[self::PARAM_MIN] ?? 0;
1297  if ( $value == 'max' ) {
1298  $value = $this->getMain()->canApiHighLimits()
1299  ? $paramSettings[self::PARAM_MAX2]
1300  : $paramSettings[self::PARAM_MAX];
1301  $this->getResult()->addParsedLimit( $this->getModuleName(), $value );
1302  } else {
1303  $value = intval( $value );
1304  $this->validateLimit(
1305  $paramName,
1306  $value,
1307  $min,
1308  $paramSettings[self::PARAM_MAX],
1309  $paramSettings[self::PARAM_MAX2]
1310  );
1311  }
1312  break;
1313  case 'boolean':
1314  if ( $multi ) {
1315  self::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
1316  }
1317  break;
1318  case 'timestamp':
1319  if ( is_array( $value ) ) {
1320  foreach ( $value as $key => $val ) {
1321  $value[$key] = $this->validateTimestamp( $val, $encParamName );
1322  }
1323  } else {
1324  $value = $this->validateTimestamp( $value, $encParamName );
1325  }
1326  break;
1327  case 'user':
1328  if ( is_array( $value ) ) {
1329  foreach ( $value as $key => $val ) {
1330  $value[$key] = $this->validateUser( $val, $encParamName );
1331  }
1332  } else {
1333  $value = $this->validateUser( $value, $encParamName );
1334  }
1335  break;
1336  case 'upload': // nothing to do
1337  break;
1338  case 'tags':
1339  // If change tagging was requested, check that the tags are valid.
1340  if ( !is_array( $value ) && !$multi ) {
1341  $value = [ $value ];
1342  }
1344  if ( !$tagsStatus->isGood() ) {
1345  $this->dieStatus( $tagsStatus );
1346  }
1347  break;
1348  default:
1349  self::dieDebug( __METHOD__, "Param $encParamName's type is unknown - $type" );
1350  }
1351  }
1352 
1353  // Throw out duplicates if requested
1354  if ( !$dupes && is_array( $value ) ) {
1355  $value = array_unique( $value );
1356  }
1357 
1358  if ( in_array( $type, [ 'NULL', 'string', 'text', 'password' ], true ) ) {
1359  foreach ( (array)$value as $val ) {
1360  if ( isset( $paramSettings[self::PARAM_MAX_BYTES] )
1361  && strlen( $val ) > $paramSettings[self::PARAM_MAX_BYTES]
1362  ) {
1363  $this->dieWithError( [ 'apierror-maxbytes', $encParamName,
1364  $paramSettings[self::PARAM_MAX_BYTES] ] );
1365  }
1366  if ( isset( $paramSettings[self::PARAM_MAX_CHARS] )
1367  && mb_strlen( $val, 'UTF-8' ) > $paramSettings[self::PARAM_MAX_CHARS]
1368  ) {
1369  $this->dieWithError( [ 'apierror-maxchars', $encParamName,
1370  $paramSettings[self::PARAM_MAX_CHARS] ] );
1371  }
1372  }
1373  }
1374 
1375  // Set a warning if a deprecated parameter has been passed
1376  if ( $deprecated && $value !== false ) {
1377  $feature = $encParamName;
1378  $m = $this;
1379  while ( !$m->isMain() ) {
1380  $p = $m->getParent();
1381  $name = $m->getModuleName();
1382  $param = $p->encodeParamName( $p->getModuleManager()->getModuleGroup( $name ) );
1383  $feature = "{$param}={$name}&{$feature}";
1384  $m = $p;
1385  }
1386  $this->addDeprecation( [ 'apiwarn-deprecation-parameter', $encParamName ], $feature );
1387  }
1388 
1389  // Set a warning if a deprecated parameter value has been passed
1390  $usedDeprecatedValues = $deprecatedValues && $value !== false
1391  ? array_intersect( array_keys( $deprecatedValues ), (array)$value )
1392  : [];
1393  if ( $usedDeprecatedValues ) {
1394  $feature = "$encParamName=";
1395  $m = $this;
1396  while ( !$m->isMain() ) {
1397  $p = $m->getParent();
1398  $name = $m->getModuleName();
1399  $param = $p->encodeParamName( $p->getModuleManager()->getModuleGroup( $name ) );
1400  $feature = "{$param}={$name}&{$feature}";
1401  $m = $p;
1402  }
1403  foreach ( $usedDeprecatedValues as $v ) {
1404  $msg = $deprecatedValues[$v];
1405  if ( $msg === true ) {
1406  $msg = [ 'apiwarn-deprecation-parameter', "$encParamName=$v" ];
1407  }
1408  $this->addDeprecation( $msg, "$feature$v" );
1409  }
1410  }
1411  } elseif ( $required ) {
1412  $this->dieWithError( [ 'apierror-missingparam', $encParamName ] );
1413  }
1414 
1415  return $value;
1416  }
1417 
1425  protected function handleParamNormalization( $paramName, $value, $rawValue ) {
1426  $encParamName = $this->encodeParamName( $paramName );
1427  $this->addWarning( [ 'apiwarn-badutf8', $encParamName ] );
1428  }
1429 
1437  protected function explodeMultiValue( $value, $limit ) {
1438  if ( substr( $value, 0, 1 ) === "\x1f" ) {
1439  $sep = "\x1f";
1440  $value = substr( $value, 1 );
1441  } else {
1442  $sep = '|';
1443  }
1444 
1445  return explode( $sep, $value, $limit );
1446  }
1447 
1465  protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues,
1466  $allSpecifier = null, $limit1 = null, $limit2 = null
1467  ) {
1468  if ( ( $value === '' || $value === "\x1f" ) && $allowMultiple ) {
1469  return [];
1470  }
1471  $limit1 = $limit1 ?: self::LIMIT_SML1;
1472  $limit2 = $limit2 ?: self::LIMIT_SML2;
1473 
1474  // This is a bit awkward, but we want to avoid calling canApiHighLimits()
1475  // because it unstubs $wgUser
1476  $valuesList = $this->explodeMultiValue( $value, $limit2 + 1 );
1477  $sizeLimit = count( $valuesList ) > $limit1 && $this->mMainModule->canApiHighLimits()
1478  ? $limit2
1479  : $limit1;
1480 
1481  if ( $allowMultiple && is_array( $allowedValues ) && $allSpecifier &&
1482  count( $valuesList ) === 1 && $valuesList[0] === $allSpecifier
1483  ) {
1484  return $allowedValues;
1485  }
1486 
1487  if ( count( $valuesList ) > $sizeLimit ) {
1488  $this->dieWithError(
1489  [ 'apierror-toomanyvalues', $valueName, $sizeLimit ],
1490  "too-many-$valueName"
1491  );
1492  }
1493 
1494  if ( !$allowMultiple && count( $valuesList ) != 1 ) {
1495  // T35482 - Allow entries with | in them for non-multiple values
1496  if ( in_array( $value, $allowedValues, true ) ) {
1497  return $value;
1498  }
1499 
1500  $values = array_map( function ( $v ) {
1501  return '<kbd>' . wfEscapeWikiText( $v ) . '</kbd>';
1502  }, $allowedValues );
1503  $this->dieWithError( [
1504  'apierror-multival-only-one-of',
1505  $valueName,
1506  Message::listParam( $values ),
1507  count( $values ),
1508  ], "multival_$valueName" );
1509  }
1510 
1511  if ( is_array( $allowedValues ) ) {
1512  // Check for unknown values
1513  $unknown = array_map( 'wfEscapeWikiText', array_diff( $valuesList, $allowedValues ) );
1514  if ( count( $unknown ) ) {
1515  if ( $allowMultiple ) {
1516  $this->addWarning( [
1517  'apiwarn-unrecognizedvalues',
1518  $valueName,
1519  Message::listParam( $unknown, 'comma' ),
1520  count( $unknown ),
1521  ] );
1522  } else {
1523  $this->dieWithError(
1524  [ 'apierror-unrecognizedvalue', $valueName, wfEscapeWikiText( $valuesList[0] ) ],
1525  "unknown_$valueName"
1526  );
1527  }
1528  }
1529  // Now throw them out
1530  $valuesList = array_intersect( $valuesList, $allowedValues );
1531  }
1532 
1533  return $allowMultiple ? $valuesList : $valuesList[0];
1534  }
1535 
1546  protected function validateLimit( $paramName, &$value, $min, $max, $botMax = null,
1547  $enforceLimits = false
1548  ) {
1549  if ( !is_null( $min ) && $value < $min ) {
1550  $msg = ApiMessage::create(
1551  [ 'apierror-integeroutofrange-belowminimum',
1552  $this->encodeParamName( $paramName ), $min, $value ],
1553  'integeroutofrange',
1554  [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?: $max ]
1555  );
1556  $this->warnOrDie( $msg, $enforceLimits );
1557  $value = $min;
1558  }
1559 
1560  // Minimum is always validated, whereas maximum is checked only if not
1561  // running in internal call mode
1562  if ( $this->getMain()->isInternalMode() ) {
1563  return;
1564  }
1565 
1566  // Optimization: do not check user's bot status unless really needed -- skips db query
1567  // assumes $botMax >= $max
1568  if ( !is_null( $max ) && $value > $max ) {
1569  if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1570  if ( $value > $botMax ) {
1571  $msg = ApiMessage::create(
1572  [ 'apierror-integeroutofrange-abovebotmax',
1573  $this->encodeParamName( $paramName ), $botMax, $value ],
1574  'integeroutofrange',
1575  [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?: $max ]
1576  );
1577  $this->warnOrDie( $msg, $enforceLimits );
1578  $value = $botMax;
1579  }
1580  } else {
1581  $msg = ApiMessage::create(
1582  [ 'apierror-integeroutofrange-abovemax',
1583  $this->encodeParamName( $paramName ), $max, $value ],
1584  'integeroutofrange',
1585  [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?: $max ]
1586  );
1587  $this->warnOrDie( $msg, $enforceLimits );
1588  $value = $max;
1589  }
1590  }
1591  }
1592 
1599  protected function validateTimestamp( $value, $encParamName ) {
1600  // Confusing synonyms for the current time accepted by wfTimestamp()
1601  // (wfTimestamp() also accepts various non-strings and the string of 14
1602  // ASCII NUL bytes, but those can't get here)
1603  if ( !$value ) {
1604  $this->addDeprecation(
1605  [ 'apiwarn-unclearnowtimestamp', $encParamName, wfEscapeWikiText( $value ) ],
1606  'unclear-"now"-timestamp'
1607  );
1608  return wfTimestamp( TS_MW );
1609  }
1610 
1611  // Explicit synonym for the current time
1612  if ( $value === 'now' ) {
1613  return wfTimestamp( TS_MW );
1614  }
1615 
1616  $timestamp = wfTimestamp( TS_MW, $value );
1617  if ( $timestamp === false ) {
1618  $this->dieWithError(
1619  [ 'apierror-badtimestamp', $encParamName, wfEscapeWikiText( $value ) ],
1620  "badtimestamp_{$encParamName}"
1621  );
1622  }
1623 
1624  return $timestamp;
1625  }
1626 
1636  final public function validateToken( $token, array $params ) {
1637  $tokenType = $this->needsToken();
1639  if ( !isset( $salts[$tokenType] ) ) {
1640  throw new MWException(
1641  "Module '{$this->getModuleName()}' tried to use token type '$tokenType' " .
1642  'without registering it'
1643  );
1644  }
1645 
1646  $tokenObj = ApiQueryTokens::getToken(
1647  $this->getUser(), $this->getRequest()->getSession(), $salts[$tokenType]
1648  );
1649  if ( $tokenObj->match( $token ) ) {
1650  return true;
1651  }
1652 
1653  $webUiSalt = $this->getWebUITokenSalt( $params );
1654  if ( $webUiSalt !== null && $this->getUser()->matchEditToken(
1655  $token,
1656  $webUiSalt,
1657  $this->getRequest()
1658  ) ) {
1659  return true;
1660  }
1661 
1662  return false;
1663  }
1664 
1671  private function validateUser( $value, $encParamName ) {
1673  return $value;
1674  }
1675 
1676  $name = User::getCanonicalName( $value, 'valid' );
1677  if ( $name !== false ) {
1678  return $name;
1679  }
1680 
1681  if (
1682  // We allow ranges as well, for blocks.
1683  IP::isIPAddress( $value ) ||
1684  // See comment for User::isIP. We don't just call that function
1685  // here because it also returns true for things like
1686  // 300.300.300.300 that are neither valid usernames nor valid IP
1687  // addresses.
1688  preg_match(
1689  '/^' . RE_IP_BYTE . '\.' . RE_IP_BYTE . '\.' . RE_IP_BYTE . '\.xxx$/',
1690  $value
1691  )
1692  ) {
1693  return IP::sanitizeIP( $value );
1694  }
1695 
1696  $this->dieWithError(
1697  [ 'apierror-baduser', $encParamName, wfEscapeWikiText( $value ) ],
1698  "baduser_{$encParamName}"
1699  );
1700  }
1701 
1704  /************************************************************************/
1715  protected function setWatch( $watch, $titleObj, $userOption = null ) {
1716  $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
1717  if ( $value === null ) {
1718  return;
1719  }
1720 
1721  WatchAction::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
1722  }
1723 
1730  public function getWatchlistUser( $params ) {
1731  if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1732  $user = User::newFromName( $params['owner'], false );
1733  if ( !( $user && $user->getId() ) ) {
1734  $this->dieWithError(
1735  [ 'nosuchusershort', wfEscapeWikiText( $params['owner'] ) ], 'bad_wlowner'
1736  );
1737  }
1738  $token = $user->getOption( 'watchlisttoken' );
1739  if ( $token == '' || !hash_equals( $token, $params['token'] ) ) {
1740  $this->dieWithError( 'apierror-bad-watchlist-token', 'bad_wltoken' );
1741  }
1742  } else {
1743  if ( !$this->getUser()->isLoggedIn() ) {
1744  $this->dieWithError( 'watchlistanontext', 'notloggedin' );
1745  }
1746  $this->checkUserRightsAny( 'viewmywatchlist' );
1747  $user = $this->getUser();
1748  }
1749 
1750  return $user;
1751  }
1752 
1765  public static function makeMessage( $msg, IContextSource $context, array $params = null ) {
1766  if ( is_string( $msg ) ) {
1767  $msg = wfMessage( $msg );
1768  } elseif ( is_array( $msg ) ) {
1769  $msg = wfMessage( ...$msg );
1770  }
1771  if ( !$msg instanceof Message ) {
1772  return null;
1773  }
1774 
1775  $msg->setContext( $context );
1776  if ( $params ) {
1777  $msg->params( $params );
1778  }
1779 
1780  return $msg;
1781  }
1782 
1790  public function errorArrayToStatus( array $errors, User $user = null ) {
1791  if ( $user === null ) {
1792  $user = $this->getUser();
1793  }
1794 
1796  foreach ( $errors as $error ) {
1797  if ( is_array( $error ) && $error[0] === 'blockedtext' && $user->getBlock() ) {
1798  $status->fatal( ApiMessage::create(
1799  'apierror-blocked',
1800  'blocked',
1801  [ 'blockinfo' => ApiQueryUserInfo::getBlockInfo( $user->getBlock() ) ]
1802  ) );
1803  } elseif ( is_array( $error ) && $error[0] === 'blockedtext-partial' && $user->getBlock() ) {
1804  $status->fatal( ApiMessage::create(
1805  'apierror-blocked-partial',
1806  'blocked',
1807  [ 'blockinfo' => ApiQueryUserInfo::getBlockInfo( $user->getBlock() ) ]
1808  ) );
1809  } elseif ( is_array( $error ) && $error[0] === 'autoblockedtext' && $user->getBlock() ) {
1810  $status->fatal( ApiMessage::create(
1811  'apierror-autoblocked',
1812  'autoblocked',
1813  [ 'blockinfo' => ApiQueryUserInfo::getBlockInfo( $user->getBlock() ) ]
1814  ) );
1815  } elseif ( is_array( $error ) && $error[0] === 'systemblockedtext' && $user->getBlock() ) {
1816  $status->fatal( ApiMessage::create(
1817  'apierror-systemblocked',
1818  'blocked',
1819  [ 'blockinfo' => ApiQueryUserInfo::getBlockInfo( $user->getBlock() ) ]
1820  ) );
1821  } else {
1822  $status->fatal( ...(array)$error );
1823  }
1824  }
1825  return $status;
1826  }
1827 
1832  protected function useTransactionalTimeLimit() {
1833  if ( $this->getRequest()->wasPosted() ) {
1835  }
1836  }
1837 
1846  protected function filterIDs( $fields, array $ids ) {
1847  $min = INF;
1848  $max = 0;
1849  foreach ( $fields as list( $table, $field ) ) {
1850  if ( isset( self::$filterIDsCache[$table][$field] ) ) {
1851  $row = self::$filterIDsCache[$table][$field];
1852  } else {
1853  $row = $this->getDB()->selectRow(
1854  $table,
1855  [
1856  'min_id' => "MIN($field)",
1857  'max_id' => "MAX($field)",
1858  ],
1859  null,
1860  __METHOD__
1861  );
1862  self::$filterIDsCache[$table][$field] = $row;
1863  }
1864  $min = min( $min, $row->min_id );
1865  $max = max( $max, $row->max_id );
1866  }
1867  return array_filter( $ids, function ( $id ) use ( $min, $max ) {
1868  return ( is_int( $id ) && $id >= 0 || ctype_digit( $id ) )
1869  && $id >= $min && $id <= $max;
1870  } );
1871  }
1872 
1875  /************************************************************************/
1894  public function addWarning( $msg, $code = null, $data = null ) {
1895  $this->getErrorFormatter()->addWarning( $this->getModulePath(), $msg, $code, $data );
1896  }
1897 
1908  public function addDeprecation( $msg, $feature, $data = [] ) {
1909  $data = (array)$data;
1910  if ( $feature !== null ) {
1911  $data['feature'] = $feature;
1912  $this->logFeatureUsage( $feature );
1913  }
1914  $this->addWarning( $msg, 'deprecation', $data );
1915 
1916  // No real need to deduplicate here, ApiErrorFormatter does that for
1917  // us (assuming the hook is deterministic).
1918  $msgs = [ $this->msg( 'api-usage-mailinglist-ref' ) ];
1919  Hooks::run( 'ApiDeprecationHelp', [ &$msgs ] );
1920  if ( count( $msgs ) > 1 ) {
1921  $key = '$' . implode( ' $', range( 1, count( $msgs ) ) );
1922  $msg = ( new RawMessage( $key ) )->params( $msgs );
1923  } else {
1924  $msg = reset( $msgs );
1925  }
1926  $this->getMain()->addWarning( $msg, 'deprecation-help' );
1927  }
1928 
1941  public function addError( $msg, $code = null, $data = null ) {
1942  $this->getErrorFormatter()->addError( $this->getModulePath(), $msg, $code, $data );
1943  }
1944 
1953  public function addMessagesFromStatus( StatusValue $status, $types = [ 'warning', 'error' ] ) {
1954  $this->getErrorFormatter()->addMessagesFromStatus( $this->getModulePath(), $status, $types );
1955  }
1956 
1970  public function dieWithError( $msg, $code = null, $data = null, $httpCode = null ) {
1971  throw ApiUsageException::newWithMessage( $this, $msg, $code, $data, $httpCode );
1972  }
1973 
1982  public function dieWithException( $exception, array $options = [] ) {
1983  $this->dieWithError(
1984  $this->getErrorFormatter()->getMessageFromException( $exception, $options )
1985  );
1986  }
1987 
1994  private function warnOrDie( ApiMessage $msg, $enforceLimits = false ) {
1995  if ( $enforceLimits ) {
1996  $this->dieWithError( $msg );
1997  } else {
1998  $this->addWarning( $msg );
1999  }
2000  }
2001 
2010  public function dieBlocked( Block $block ) {
2011  // Die using the appropriate message depending on block type
2012  if ( $block->getType() == Block::TYPE_AUTO ) {
2013  $this->dieWithError(
2014  'apierror-autoblocked',
2015  'autoblocked',
2016  [ 'blockinfo' => ApiQueryUserInfo::getBlockInfo( $block ) ]
2017  );
2018  } elseif ( !$block->isSitewide() ) {
2019  $this->dieWithError(
2020  'apierror-blocked-partial',
2021  'blocked',
2022  [ 'blockinfo' => ApiQueryUserInfo::getBlockInfo( $block ) ]
2023  );
2024  } else {
2025  $this->dieWithError(
2026  'apierror-blocked',
2027  'blocked',
2028  [ 'blockinfo' => ApiQueryUserInfo::getBlockInfo( $block ) ]
2029  );
2030  }
2031  }
2032 
2041  public function dieStatus( StatusValue $status ) {
2042  if ( $status->isGood() ) {
2043  throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
2044  }
2045 
2046  // ApiUsageException needs a fatal status, but this method has
2047  // historically accepted any non-good status. Convert it if necessary.
2048  $status->setOK( false );
2049  if ( !$status->getErrorsByType( 'error' ) ) {
2050  $newStatus = Status::newGood();
2051  foreach ( $status->getErrorsByType( 'warning' ) as $err ) {
2052  $newStatus->fatal( $err['message'], ...$err['params'] );
2053  }
2054  if ( !$newStatus->getErrorsByType( 'error' ) ) {
2055  $newStatus->fatal( 'unknownerror-nocode' );
2056  }
2057  $status = $newStatus;
2058  }
2059 
2060  throw new ApiUsageException( $this, $status );
2061  }
2062 
2068  public function dieReadOnly() {
2069  $this->dieWithError(
2070  'apierror-readonly',
2071  'readonly',
2072  [ 'readonlyreason' => wfReadOnlyReason() ]
2073  );
2074  }
2075 
2084  public function checkUserRightsAny( $rights, $user = null ) {
2085  if ( !$user ) {
2086  $user = $this->getUser();
2087  }
2088  $rights = (array)$rights;
2089  if ( !$user->isAllowedAny( ...$rights ) ) {
2090  $this->dieWithError( [ 'apierror-permissiondenied', $this->msg( "action-{$rights[0]}" ) ] );
2091  }
2092  }
2093 
2102  public function checkTitleUserPermissions( Title $title, $actions, $user = null ) {
2103  if ( !$user ) {
2104  $user = $this->getUser();
2105  }
2106 
2107  $errors = [];
2108  foreach ( (array)$actions as $action ) {
2109  $errors = array_merge( $errors, $title->getUserPermissionsErrors( $action, $user ) );
2110  }
2111 
2112  if ( $errors ) {
2113  // track block notices
2114  if ( $this->getConfig()->get( 'EnableBlockNoticeStats' ) ) {
2115  $this->trackBlockNotices( $errors );
2116  }
2117 
2118  $this->dieStatus( $this->errorArrayToStatus( $errors, $user ) );
2119  }
2120  }
2121 
2127  private function trackBlockNotices( array $errors ) {
2128  $errorMessageKeys = [
2129  'blockedtext',
2130  'blockedtext-partial',
2131  'autoblockedtext',
2132  'systemblockedtext',
2133  ];
2134 
2135  $statsd = MediaWikiServices::getInstance()->getStatsdDataFactory();
2136 
2137  foreach ( $errors as $error ) {
2138  if ( in_array( $error[0], $errorMessageKeys ) ) {
2139  $wiki = $this->getConfig()->get( 'DBname' );
2140  $statsd->increment( 'BlockNotices.' . $wiki . '.MediaWikiApi.returned' );
2141  break;
2142  }
2143  }
2144  }
2145 
2157  public function dieWithErrorOrDebug( $msg, $code = null, $data = null, $httpCode = null ) {
2158  if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
2159  $this->dieWithError( $msg, $code, $data, $httpCode );
2160  } else {
2161  $this->addWarning( $msg, $code, $data );
2162  }
2163  }
2164 
2174  protected function dieContinueUsageIf( $condition ) {
2175  if ( $condition ) {
2176  $this->dieWithError( 'apierror-badcontinue' );
2177  }
2178  }
2179 
2186  protected static function dieDebug( $method, $message ) {
2187  throw new MWException( "Internal error in $method: $message" );
2188  }
2189 
2196  public function logFeatureUsage( $feature ) {
2197  $request = $this->getRequest();
2198  $s = '"' . addslashes( $feature ) . '"' .
2199  ' "' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) . '"' .
2200  ' "' . $request->getIP() . '"' .
2201  ' "' . addslashes( $request->getHeader( 'Referer' ) ) . '"' .
2202  ' "' . addslashes( $this->getMain()->getUserAgent() ) . '"';
2203  wfDebugLog( 'api-feature-usage', $s, 'private' );
2204  }
2205 
2208  /************************************************************************/
2222  protected function getSummaryMessage() {
2223  return "apihelp-{$this->getModulePath()}-summary";
2224  }
2225 
2235  protected function getExtendedDescription() {
2236  return [ [
2237  "apihelp-{$this->getModulePath()}-extended-description",
2238  'api-help-no-extended-description',
2239  ] ];
2240  }
2241 
2248  public function getFinalSummary() {
2249  $msg = self::makeMessage( $this->getSummaryMessage(), $this->getContext(), [
2250  $this->getModulePrefix(),
2251  $this->getModuleName(),
2252  $this->getModulePath(),
2253  ] );
2254  return $msg;
2255  }
2256 
2264  public function getFinalDescription() {
2265  $summary = self::makeMessage( $this->getSummaryMessage(), $this->getContext(), [
2266  $this->getModulePrefix(),
2267  $this->getModuleName(),
2268  $this->getModulePath(),
2269  ] );
2270  $extendedDescription = self::makeMessage(
2271  $this->getExtendedDescription(), $this->getContext(), [
2272  $this->getModulePrefix(),
2273  $this->getModuleName(),
2274  $this->getModulePath(),
2275  ]
2276  );
2277 
2278  $msgs = [ $summary, $extendedDescription ];
2279 
2280  Hooks::run( 'APIGetDescriptionMessages', [ $this, &$msgs ] );
2281 
2282  return $msgs;
2283  }
2284 
2293  public function getFinalParams( $flags = 0 ) {
2294  $params = $this->getAllowedParams( $flags );
2295  if ( !$params ) {
2296  $params = [];
2297  }
2298 
2299  if ( $this->needsToken() ) {
2300  $params['token'] = [
2301  self::PARAM_TYPE => 'string',
2302  self::PARAM_REQUIRED => true,
2303  self::PARAM_SENSITIVE => true,
2304  self::PARAM_HELP_MSG => [
2305  'api-help-param-token',
2306  $this->needsToken(),
2307  ],
2308  ] + ( $params['token'] ?? [] );
2309  }
2310 
2311  // Avoid PHP 7.1 warning of passing $this by reference
2312  $apiModule = $this;
2313  Hooks::run( 'APIGetAllowedParams', [ &$apiModule, &$params, $flags ] );
2314 
2315  return $params;
2316  }
2317 
2325  public function getFinalParamDescription() {
2326  $prefix = $this->getModulePrefix();
2327  $name = $this->getModuleName();
2328  $path = $this->getModulePath();
2329 
2330  $params = $this->getFinalParams( self::GET_VALUES_FOR_HELP );
2331  $msgs = [];
2332  foreach ( $params as $param => $settings ) {
2333  if ( !is_array( $settings ) ) {
2334  $settings = [];
2335  }
2336 
2337  if ( isset( $settings[self::PARAM_HELP_MSG] ) ) {
2338  $msg = $settings[self::PARAM_HELP_MSG];
2339  } else {
2340  $msg = $this->msg( "apihelp-{$path}-param-{$param}" );
2341  }
2342  $msg = self::makeMessage( $msg, $this->getContext(),
2343  [ $prefix, $param, $name, $path ] );
2344  if ( !$msg ) {
2345  self::dieDebug( __METHOD__,
2346  'Value in ApiBase::PARAM_HELP_MSG is not valid' );
2347  }
2348  $msgs[$param] = [ $msg ];
2349 
2350  if ( isset( $settings[self::PARAM_TYPE] ) &&
2351  $settings[self::PARAM_TYPE] === 'submodule'
2352  ) {
2353  if ( isset( $settings[self::PARAM_SUBMODULE_MAP] ) ) {
2354  $map = $settings[self::PARAM_SUBMODULE_MAP];
2355  } else {
2356  $prefix = $this->isMain() ? '' : ( $this->getModulePath() . '+' );
2357  $map = [];
2358  foreach ( $this->getModuleManager()->getNames( $param ) as $submoduleName ) {
2359  $map[$submoduleName] = $prefix . $submoduleName;
2360  }
2361  }
2362  ksort( $map );
2363  $submodules = [];
2364  $deprecatedSubmodules = [];
2365  foreach ( $map as $v => $m ) {
2366  $arr = &$submodules;
2367  $isDeprecated = false;
2368  $summary = null;
2369  try {
2370  $submod = $this->getModuleFromPath( $m );
2371  if ( $submod ) {
2372  $summary = $submod->getFinalSummary();
2373  $isDeprecated = $submod->isDeprecated();
2374  if ( $isDeprecated ) {
2375  $arr = &$deprecatedSubmodules;
2376  }
2377  }
2378  } catch ( ApiUsageException $ex ) {
2379  // Ignore
2380  }
2381  if ( $summary ) {
2382  $key = $summary->getKey();
2383  $params = $summary->getParams();
2384  } else {
2385  $key = 'api-help-undocumented-module';
2386  $params = [ $m ];
2387  }
2388  $m = new ApiHelpParamValueMessage( "[[Special:ApiHelp/$m|$v]]", $key, $params, $isDeprecated );
2389  $arr[] = $m->setContext( $this->getContext() );
2390  }
2391  $msgs[$param] = array_merge( $msgs[$param], $submodules, $deprecatedSubmodules );
2392  } elseif ( isset( $settings[self::PARAM_HELP_MSG_PER_VALUE] ) ) {
2393  if ( !is_array( $settings[self::PARAM_HELP_MSG_PER_VALUE] ) ) {
2394  self::dieDebug( __METHOD__,
2395  'ApiBase::PARAM_HELP_MSG_PER_VALUE is not valid' );
2396  }
2397  if ( !is_array( $settings[self::PARAM_TYPE] ) ) {
2398  self::dieDebug( __METHOD__,
2399  'ApiBase::PARAM_HELP_MSG_PER_VALUE may only be used when ' .
2400  'ApiBase::PARAM_TYPE is an array' );
2401  }
2402 
2403  $valueMsgs = $settings[self::PARAM_HELP_MSG_PER_VALUE];
2404  $deprecatedValues = $settings[self::PARAM_DEPRECATED_VALUES] ?? [];
2405 
2406  foreach ( $settings[self::PARAM_TYPE] as $value ) {
2407  if ( isset( $valueMsgs[$value] ) ) {
2408  $msg = $valueMsgs[$value];
2409  } else {
2410  $msg = "apihelp-{$path}-paramvalue-{$param}-{$value}";
2411  }
2412  $m = self::makeMessage( $msg, $this->getContext(),
2413  [ $prefix, $param, $name, $path, $value ] );
2414  if ( $m ) {
2415  $m = new ApiHelpParamValueMessage(
2416  $value,
2417  [ $m->getKey(), 'api-help-param-no-description' ],
2418  $m->getParams(),
2419  isset( $deprecatedValues[$value] )
2420  );
2421  $msgs[$param][] = $m->setContext( $this->getContext() );
2422  } else {
2423  self::dieDebug( __METHOD__,
2424  "Value in ApiBase::PARAM_HELP_MSG_PER_VALUE for $value is not valid" );
2425  }
2426  }
2427  }
2428 
2429  if ( isset( $settings[self::PARAM_HELP_MSG_APPEND] ) ) {
2430  if ( !is_array( $settings[self::PARAM_HELP_MSG_APPEND] ) ) {
2431  self::dieDebug( __METHOD__,
2432  'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
2433  }
2434  foreach ( $settings[self::PARAM_HELP_MSG_APPEND] as $m ) {
2435  $m = self::makeMessage( $m, $this->getContext(),
2436  [ $prefix, $param, $name, $path ] );
2437  if ( $m ) {
2438  $msgs[$param][] = $m;
2439  } else {
2440  self::dieDebug( __METHOD__,
2441  'Value in ApiBase::PARAM_HELP_MSG_APPEND is not valid' );
2442  }
2443  }
2444  }
2445  }
2446 
2447  Hooks::run( 'APIGetParamDescriptionMessages', [ $this, &$msgs ] );
2448 
2449  return $msgs;
2450  }
2451 
2461  protected function getHelpFlags() {
2462  $flags = [];
2463 
2464  if ( $this->isDeprecated() ) {
2465  $flags[] = 'deprecated';
2466  }
2467  if ( $this->isInternal() ) {
2468  $flags[] = 'internal';
2469  }
2470  if ( $this->isReadMode() ) {
2471  $flags[] = 'readrights';
2472  }
2473  if ( $this->isWriteMode() ) {
2474  $flags[] = 'writerights';
2475  }
2476  if ( $this->mustBePosted() ) {
2477  $flags[] = 'mustbeposted';
2478  }
2479 
2480  return $flags;
2481  }
2482 
2494  protected function getModuleSourceInfo() {
2495  global $IP;
2496 
2497  if ( $this->mModuleSource !== false ) {
2498  return $this->mModuleSource;
2499  }
2500 
2501  // First, try to find where the module comes from...
2502  $rClass = new ReflectionClass( $this );
2503  $path = $rClass->getFileName();
2504  if ( !$path ) {
2505  // No path known?
2506  $this->mModuleSource = null;
2507  return null;
2508  }
2509  $path = realpath( $path ) ?: $path;
2510 
2511  // Build map of extension directories to extension info
2512  if ( self::$extensionInfo === null ) {
2513  $extDir = $this->getConfig()->get( 'ExtensionDirectory' );
2514  self::$extensionInfo = [
2515  realpath( __DIR__ ) ?: __DIR__ => [
2516  'path' => $IP,
2517  'name' => 'MediaWiki',
2518  'license-name' => 'GPL-2.0-or-later',
2519  ],
2520  realpath( "$IP/extensions" ) ?: "$IP/extensions" => null,
2521  realpath( $extDir ) ?: $extDir => null,
2522  ];
2523  $keep = [
2524  'path' => null,
2525  'name' => null,
2526  'namemsg' => null,
2527  'license-name' => null,
2528  ];
2529  foreach ( $this->getConfig()->get( 'ExtensionCredits' ) as $group ) {
2530  foreach ( $group as $ext ) {
2531  if ( !isset( $ext['path'] ) || !isset( $ext['name'] ) ) {
2532  // This shouldn't happen, but does anyway.
2533  continue;
2534  }
2535 
2536  $extpath = $ext['path'];
2537  if ( !is_dir( $extpath ) ) {
2538  $extpath = dirname( $extpath );
2539  }
2540  self::$extensionInfo[realpath( $extpath ) ?: $extpath] =
2541  array_intersect_key( $ext, $keep );
2542  }
2543  }
2544  foreach ( ExtensionRegistry::getInstance()->getAllThings() as $ext ) {
2545  $extpath = $ext['path'];
2546  if ( !is_dir( $extpath ) ) {
2547  $extpath = dirname( $extpath );
2548  }
2549  self::$extensionInfo[realpath( $extpath ) ?: $extpath] =
2550  array_intersect_key( $ext, $keep );
2551  }
2552  }
2553 
2554  // Now traverse parent directories until we find a match or run out of
2555  // parents.
2556  do {
2557  if ( array_key_exists( $path, self::$extensionInfo ) ) {
2558  // Found it!
2559  $this->mModuleSource = self::$extensionInfo[$path];
2560  return $this->mModuleSource;
2561  }
2562 
2563  $oldpath = $path;
2564  $path = dirname( $path );
2565  } while ( $path !== $oldpath );
2566 
2567  // No idea what extension this might be.
2568  $this->mModuleSource = null;
2569  return null;
2570  }
2571 
2583  public function modifyHelp( array &$help, array $options, array &$tocData ) {
2584  }
2585 
2588  /************************************************************************/
2602  protected function getDescription() {
2603  wfDeprecated( __METHOD__, '1.25' );
2604  return false;
2605  }
2606 
2619  protected function getParamDescription() {
2620  wfDeprecated( __METHOD__, '1.25' );
2621  return [];
2622  }
2623 
2640  protected function getExamples() {
2641  wfDeprecated( __METHOD__, '1.25' );
2642  return false;
2643  }
2644 
2653  protected function getDescriptionMessage() {
2654  wfDeprecated( __METHOD__, '1.30' );
2655  return [ [
2656  "apihelp-{$this->getModulePath()}-description",
2657  "apihelp-{$this->getModulePath()}-summary",
2658  ] ];
2659  }
2660 
2668  public static function truncateArray( &$arr, $limit ) {
2669  wfDeprecated( __METHOD__, '1.32' );
2670  $modified = false;
2671  while ( count( $arr ) > $limit ) {
2672  array_pop( $arr );
2673  $modified = true;
2674  }
2675 
2676  return $modified;
2677  }
2678 
2680 }
2681 
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
Definition: WikiPage.php:128
setContext(IContextSource $context)
parameterNotEmpty( $x)
Callback function used in requireOnlyOneParameter to check whether required parameters are set...
Definition: ApiBase.php:993
handleParamNormalization( $paramName, $value, $rawValue)
Handle when a parameter was Unicode-normalized.
Definition: ApiBase.php:1425
getTitleFromTitleOrPageId( $params)
Get a Title object from a title or pageid param, if possible.
Definition: ApiBase.php:1045
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:2325
const PARAM_TYPE
(string|string[]) Either an array of allowed value strings, or a string type as described below...
Definition: ApiBase.php:88
requireOnlyOneParameter( $params, $required)
Die if none or more than one of a certain set of parameters is set and not false. ...
Definition: ApiBase.php:867
static isIPAddress( $ip)
Determine if a string is as valid IP address or network (CIDR prefix).
Definition: IP.php:77
getErrorFormatter()
Get the error formatter.
Definition: ApiBase.php:639
const LIMIT_BIG2
Fast query, apihighlimits limit.
Definition: ApiBase.php:255
static int [][][] $filterIDsCache
Cache for self::filterIDs()
Definition: ApiBase.php:272
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
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking, formatting, etc.
const PARAM_MAX_BYTES
(integer) Maximum length of a string in bytes (in UTF-8 encoding).
Definition: ApiBase.php:222
isReadMode()
Indicates whether this module requires read rights.
Definition: ApiBase.php:397
getErrorsByType( $type)
Returns a list of status messages of the given type.
getResult()
Get the result object.
Definition: ApiBase.php:625
Message subclass that prepends wikitext for API help.
static newFromID( $id, $flags=0)
Create a new Title from an article ID.
Definition: Title.php:427
getDescriptionMessage()
Return the description message.
Definition: ApiBase.php:2653
getModuleSourceInfo()
Returns information about the source of this module, if known.
Definition: ApiBase.php:2494
$IP
Definition: WebStart.php:41
getCustomPrinter()
If the module may only be used with a certain format module, it should override this method to return...
Definition: ApiBase.php:339
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:1996
static array $extensionInfo
Maps extension paths to info arrays.
Definition: ApiBase.php:269
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
dieStatus(StatusValue $status)
Throw an ApiUsageException based on the Status object.
Definition: ApiBase.php:2041
addDeprecation( $msg, $feature, $data=[])
Add a deprecation warning for this module.
Definition: ApiBase.php:1908
useTransactionalTimeLimit()
Call wfTransactionalTimeLimit() if this request was POSTed.
Definition: ApiBase.php:1832
validateLimit( $paramName, &$value, $min, $max, $botMax=null, $enforceLimits=false)
Validate the value against the minimum and user/bot maximum limits.
Definition: ApiBase.php:1546
getMain()
Get the main module.
Definition: ApiBase.php:521
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
Definition: ApiBase.php:49
The simplest way of implementing IContextSource is to hold a RequestContext as a member variable and ...
trackBlockNotices(array $errors)
Keep track of errors messages resulting from a block.
Definition: ApiBase.php:2127
getType()
Get the type of target for this particular block.
Definition: Block.php:1541
const GET_VALUES_FOR_HELP
getAllowedParams() flag: When set, the result could take longer to generate, but should be more thoro...
Definition: ApiBase.php:266
const LIMIT_BIG1
Fast query, standard limit.
Definition: ApiBase.php:253
static newWithMessage(ApiBase $module=null, $msg, $code=null, $data=null, $httpCode=0)
checkTitleUserPermissions(Title $title, $actions, $user=null)
Helper function for permission-denied errors.
Definition: ApiBase.php:2102
Exception used to abort API execution with an error.
getDB()
Gets a default replica DB connection object.
Definition: ApiBase.php:653
Status::newGood()` to allow deletion, and then `return false` from the hook function. Ensure you consume the 'ChangeTagAfterDelete' hook to carry out custom deletion actions. $tag:name of the tag $user:user initiating the action & $status:Status object. See above. 'ChangeTagsListActive':Allows you to nominate which of the tags your extension uses are in active use. & $tags:list of all active tags. Append to this array. 'ChangeTagsAfterUpdateTags':Called after tags have been updated with the ChangeTags::updateTags function. Params:$addedTags:tags effectively added in the update $removedTags:tags effectively removed in the update $prevTags:tags that were present prior to the update $rc_id:recentchanges table id $rev_id:revision table id $log_id:logging table id $params:tag params $rc:RecentChange being tagged when the tagging accompanies the action, or null $user:User who performed the tagging when the tagging is subsequent to the action, or null 'ChangeTagsAllowedAdd':Called when checking if a user can add tags to a change. & $allowedTags:List of all the tags the user is allowed to add. Any tags the user wants to add( $addTags) that are not in this array will cause it to fail. You may add or remove tags to this array as required. $addTags:List of tags user intends to add. $user:User who is adding the tags. 'ChangeUserGroups':Called before user groups are changed. $performer:The User who will perform the change $user:The User whose groups will be changed & $add:The groups that will be added & $remove:The groups that will be removed 'Collation::factory':Called if $wgCategoryCollation is an unknown collation. $collationName:Name of the collation in question & $collationObject:Null. Replace with a subclass of the Collation class that implements the collation given in $collationName. 'ConfirmEmailComplete':Called after a user 's email has been confirmed successfully. $user:user(object) whose email is being confirmed 'ContentAlterParserOutput':Modify parser output for a given content object. Called by Content::getParserOutput after parsing has finished. Can be used for changes that depend on the result of the parsing but have to be done before LinksUpdate is called(such as adding tracking categories based on the rendered HTML). $content:The Content to render $title:Title of the page, as context $parserOutput:ParserOutput to manipulate 'ContentGetParserOutput':Customize parser output for a given content object, called by AbstractContent::getParserOutput. May be used to override the normal model-specific rendering of page content. $content:The Content to render $title:Title of the page, as context $revId:The revision ID, as context $options:ParserOptions for rendering. To avoid confusing the parser cache, the output can only depend on parameters provided to this hook function, not on global state. $generateHtml:boolean, indicating whether full HTML should be generated. If false, generation of HTML may be skipped, but other information should still be present in the ParserOutput object. & $output:ParserOutput, to manipulate or replace 'ContentHandlerDefaultModelFor':Called when the default content model is determined for a given title. May be used to assign a different model for that title. $title:the Title in question & $model:the model name. Use with CONTENT_MODEL_XXX constants. 'ContentHandlerForModelID':Called when a ContentHandler is requested for a given content model name, but no entry for that model exists in $wgContentHandlers. Note:if your extension implements additional models via this hook, please use GetContentModels hook to make them known to core. $modeName:the requested content model name & $handler:set this to a ContentHandler object, if desired. 'ContentModelCanBeUsedOn':Called to determine whether that content model can be used on a given page. This is especially useful to prevent some content models to be used in some special location. $contentModel:ID of the content model in question $title:the Title in question. & $ok:Output parameter, 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. 'ContribsPager::getQueryInfo':Before the contributions query is about to run & $pager:Pager object for contributions & $queryInfo:The query for the contribs Pager 'ContribsPager::reallyDoQuery':Called before really executing the query for My Contributions & $data:an array of results of all contribs queries $pager:The ContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'ContributionsLineEnding':Called before a contributions HTML line is finished $page:SpecialPage object for contributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'ContributionsToolLinks':Change tool links above Special:Contributions $id:User identifier $title:User page title & $tools:Array of tool links $specialPage:SpecialPage instance for context and services. Can be either SpecialContributions or DeletedContributionsPage. Extensions should type hint against a generic SpecialPage though. 'ConvertContent':Called by AbstractContent::convert when a conversion to another content model is requested. Handler functions that modify $result should generally return false to disable further attempts at conversion. $content:The Content object to be converted. $toModel:The ID of the content model to convert to. $lossy:boolean indicating whether lossy conversion is allowed. & $result:Output parameter, in case the handler function wants to provide a converted Content object. Note that $result->getContentModel() must return $toModel. 'ContentSecurityPolicyDefaultSource':Modify the allowed CSP load sources. This affects all directives except for the script directive. If you want to add a script source, see ContentSecurityPolicyScriptSource hook. & $defaultSrc:Array of Content-Security-Policy allowed sources $policyConfig:Current configuration for the Content-Security-Policy header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyDirectives':Modify the content security policy directives. Use this only if ContentSecurityPolicyDefaultSource and ContentSecurityPolicyScriptSource do not meet your needs. & $directives:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyScriptSource':Modify the allowed CSP script sources. Note that you also have to use ContentSecurityPolicyDefaultSource if you want non-script sources to be loaded from whatever you add. & $scriptSrc:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'CustomEditor':When invoking the page editor Return true to allow the normal editor to be used, or false if implementing a custom editor, e.g. for a special namespace, etc. $article:Article being edited $user:User performing the edit 'DatabaseOraclePostInit':Called after initialising an Oracle database $db:the DatabaseOracle object 'DeletedContribsPager::reallyDoQuery':Called before really executing the query for Special:DeletedContributions Similar to ContribsPager::reallyDoQuery & $data:an array of results of all contribs queries $pager:The DeletedContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'DeletedContributionsLineEnding':Called before a DeletedContributions HTML line is finished. Similar to ContributionsLineEnding $page:SpecialPage object for DeletedContributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'DeleteUnknownPreferences':Called by the cleanupPreferences.php maintenance script to build a WHERE clause with which to delete preferences that are not known about. This hook is used by extensions that have dynamically-named preferences that should not be deleted in the usual cleanup process. For example, the Gadgets extension creates preferences prefixed with 'gadget-', and so anything with that prefix is excluded from the deletion. &where:An array that will be passed as the $cond parameter to IDatabase::select() to determine what will be deleted from the user_properties table. $db:The IDatabase object, useful for accessing $db->buildLike() etc. 'DifferenceEngineAfterLoadNewText':called in DifferenceEngine::loadNewText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before returning true from this function. $differenceEngine:DifferenceEngine object 'DifferenceEngineLoadTextAfterNewContentIsLoaded':called in DifferenceEngine::loadText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before checking if the variable 's value is null. This hook can be used to inject content into said class member variable. $differenceEngine:DifferenceEngine object 'DifferenceEngineMarkPatrolledLink':Allows extensions to change the "mark as patrolled" link which is shown both on the diff header as well as on the bottom of a page, usually wrapped in a span element which has class="patrollink". $differenceEngine:DifferenceEngine object & $markAsPatrolledLink:The "mark as patrolled" link HTML(string) $rcid:Recent change ID(rc_id) for this change(int) 'DifferenceEngineMarkPatrolledRCID':Allows extensions to possibly change the rcid parameter. For example the rcid might be set to zero due to the user being the same as the performer of the change but an extension might still want to show it under certain conditions. & $rcid:rc_id(int) of the change or 0 $differenceEngine:DifferenceEngine object $change:RecentChange object $user:User object representing the current user 'DifferenceEngineNewHeader':Allows extensions to change the $newHeader variable, which contains information about the new revision, such as the revision 's author, whether the revision was marked as a minor edit or not, etc. $differenceEngine:DifferenceEngine object & $newHeader:The string containing the various #mw-diff-otitle[1-5] divs, which include things like revision author info, revision comment, RevisionDelete link and more $formattedRevisionTools:Array containing revision tools, some of which may have been injected with the DiffRevisionTools hook $nextlink:String containing the link to the next revision(if any) $status
Definition: hooks.txt:1277
const PARAM_MAX
(integer) Max value allowed for the parameter, for PARAM_TYPE &#39;integer&#39; and &#39;limit&#39;.
Definition: ApiBase.php:91
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
const PARAM_REQUIRED
(boolean) Is the parameter required?
Definition: ApiBase.php:112
ApiMain $mMainModule
Definition: ApiBase.php:275
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:553
This manages continuation state.
$value
getParent()
Get the parent of this module.
Definition: ApiBase.php:539
getUserPermissionsErrors( $action, $user, $rigor='secure', $ignoreErrors=[])
Can $user perform $action on this page?
Definition: Title.php:2204
dieWithError( $msg, $code=null, $data=null, $httpCode=null)
Abort execution with an error.
Definition: ApiBase.php:1970
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user...
Definition: ApiBase.php:736
isGood()
Returns whether the operation completed and didn&#39;t have any error or warnings.
dieWithException( $exception, array $options=[])
Abort execution with an error derived from an exception.
Definition: ApiBase.php:1982
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 MediaWikiServices
Definition: injection.txt:23
$mReplicaDB
Definition: ApiBase.php:278
validateTimestamp( $value, $encParamName)
Validate and normalize parameters of type &#39;timestamp&#39;.
Definition: ApiBase.php:1599
msg( $key)
Get a Message object with context set Parameters are the same as wfMessage()
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:158
validateUser( $value, $encParamName)
Validate and normalize parameters of type &#39;user&#39;.
Definition: ApiBase.php:1671
const PARAM_ALL
(boolean|string) When PARAM_TYPE has a defined set of values and PARAM_ISMULTI is true...
Definition: ApiBase.php:181
isDeprecated()
Indicates whether this module is deprecated.
Definition: ApiBase.php:429
getHelpUrls()
Return links to more detailed help pages about the module.
Definition: ApiBase.php:363
string $mModuleName
Definition: ApiBase.php:277
needsToken()
Returns the token type this module requires in order to execute.
Definition: ApiBase.php:461
IContextSource $context
logFeatureUsage( $feature)
Write logging information for API features to a debug log, for usage analysis.
Definition: ApiBase.php:2196
getFinalSummary()
Get final module summary.
Definition: ApiBase.php:2248
getParameter( $paramName, $parseLimit=true)
Get a value for the given parameter.
Definition: ApiBase.php:850
const PARAM_ISMULTI_LIMIT1
(integer) Maximum number of values, for normal users.
Definition: ApiBase.php:209
static getBlockInfo(Block $block)
Get basic info about a given block.
static makeMessage( $msg, IContextSource $context, array $params=null)
Create a Message from a string or array.
Definition: ApiBase.php:1765
const PARAM_MAX_CHARS
(integer) Maximum length of a string in characters (unicode codepoints).
Definition: ApiBase.php:228
The User object encapsulates all of the user-specific settings (user_id, name, rights, email address, options, last login time).
Definition: User.php:47
static getCanonicalName( $name, $validate='valid')
Given unvalidated user input, return a canonical username, or false if the username is invalid...
Definition: User.php:1233
const PARAM_HELP_MSG_APPEND
((string|array|Message)[]) Specify additional i18n messages to append to the normal message for this ...
Definition: ApiBase.php:132
parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues, $allSpecifier=null, $limit1=null, $limit2=null)
Return an array of values that were given in a &#39;a|b|c&#39; notation, after it optionally validates them a...
Definition: ApiBase.php:1465
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
getSummaryMessage()
Return the summary message.
Definition: ApiBase.php:2222
const PARAM_SUBMODULE_PARAM_PREFIX
(string) When PARAM_TYPE is &#39;submodule&#39;, used to indicate the &#39;g&#39; prefix added by ApiQueryGeneratorBa...
Definition: ApiBase.php:173
wfUrlencode( $s)
We want some things to be included as literal characters in our title URLs for prettiness, which urlencode encodes by default.
getWatchlistValue( $watchlist, $titleObj, $userOption=null)
Return true if we&#39;re to watch the page, false if not, null if no change.
Definition: ApiBase.php:1073
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation use $formDescriptor instead 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 unset offset - wrap String Wrap the message in html(usually something like "&lt
static truncateArray(&$arr, $limit)
Truncate an array to a certain length.
Definition: ApiBase.php:2668
const PARAM_ISMULTI_LIMIT2
(integer) Maximum number of values, for users with the apihighimits right.
Definition: ApiBase.php:216
static sanitizeIP( $ip)
Convert an IP into a verbose, uppercase, normalized form.
Definition: IP.php:152
setOK( $ok)
Change operation status.
static doWatchOrUnwatch( $watch, Title $title, User $user)
Watch or unwatch a page.
Definition: WatchAction.php:89
getHelpFlags()
Generates the list of flags for the help screen and for action=paraminfo.
Definition: ApiBase.php:2461
requireAtLeastOneParameter( $params, $required)
Die if none of a certain set of parameters is set and not false.
Definition: ApiBase.php:933
const PARAM_RANGE_ENFORCE
(boolean) For PARAM_TYPE &#39;integer&#39;, enforce PARAM_MIN and PARAM_MAX?
Definition: ApiBase.php:118
static newGood( $value=null)
Factory function for good results.
Definition: StatusValue.php:81
dieContinueUsageIf( $condition)
Die with the &#39;badcontinue&#39; error.
Definition: ApiBase.php:2174
getModulePath()
Get the path to this module.
Definition: ApiBase.php:569
getContinuationManager()
Get the continuation manager.
Definition: ApiBase.php:665
setContinuationManager(ApiContinuationManager $manager=null)
Set the continuation manager.
Definition: ApiBase.php:679
const LIMIT_SML2
Slow query, apihighlimits limit.
Definition: ApiBase.php:259
explodeMultiValue( $value, $limit)
Split a multi-valued parameter string, like explode()
Definition: ApiBase.php:1437
__construct(ApiMain $mainModule, $moduleName, $modulePrefix='')
Definition: ApiBase.php:288
const PARAM_SUBMODULE_MAP
(string[]) When PARAM_TYPE is &#39;submodule&#39;, map parameter values to submodule paths.
Definition: ApiBase.php:166
getContext()
Get the base IContextSource object.
const IGNORE_USER_RIGHTS
Definition: User.php:77
$params
This is the main API class, used for both external and internal processing.
Definition: ApiMain.php:41
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 & $options
Definition: hooks.txt:1996
Extension of Message implementing IApiMessage.
Definition: ApiMessage.php:26
isInternal()
Indicates whether this module is "internal" Internal API modules are not (yet) intended for 3rd party...
Definition: ApiBase.php:439
getParameterFromSettings( $paramName, $paramSettings, $parseLimit)
Using the settings determine the value for the given parameter.
Definition: ApiBase.php:1114
setContext(IContextSource $context)
Set the language and the title from a context object.
Definition: Message.php:725
isSitewide( $x=null)
Indicates that the block is a sitewide block.
Definition: Block.php:1138
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:936
dynamicParameterDocumentation()
Indicate if the module supports dynamically-determined parameters that cannot be included in self::ge...
Definition: ApiBase.php:703
getModuleName()
Get the name of the module being executed by this instance.
Definition: ApiBase.php:505
$help
Definition: mcc.php:32
const PARAM_MAX2
(integer) Max value allowed for the parameter for users with the apihighlimits right, for PARAM_TYPE &#39;limit&#39;.
Definition: ApiBase.php:97
getModuleFromPath( $path)
Get a module from its module path.
Definition: ApiBase.php:587
string $mModulePrefix
Definition: ApiBase.php:277
const TYPE_AUTO
Definition: Block.php:94
modifyHelp(array &$help, array $options, array &$tocData)
Called from ApiHelp before the pieces are joined together and returned.
Definition: ApiBase.php:2583
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:785
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
requireMaxOneParameter( $params, $required)
Die if more than one of a certain set of parameters is set and not false.
Definition: ApiBase.php:905
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter...
Definition: ApiBase.php:125
errorArrayToStatus(array $errors, User $user=null)
Turn an array of message keys or key+param arrays into a Status.
Definition: ApiBase.php:1790
const PARAM_SENSITIVE
(boolean) Is the parameter sensitive? Note &#39;password&#39;-type fields are always sensitive regardless of ...
Definition: ApiBase.php:194
const LIMIT_SML1
Slow query, standard limit.
Definition: ApiBase.php:257
const PARAM_TEMPLATE_VARS
(array) Indicate that this is a templated parameter, and specify replacements.
Definition: ApiBase.php:246
getModuleManager()
Get the module manager, or null if this module has no sub-modules.
Definition: ApiBase.php:326
getWatchlistUser( $params)
Gets the user for whom to get the watchlist.
Definition: ApiBase.php:1730
static newFromID( $id, $from='fromdb')
Constructor from a page id.
Definition: WikiPage.php:166
static getTokenTypeSalts()
Get the salts for known token types.
getTitleOrPageId( $params, $load=false)
Get a WikiPage object from a title or pageid param, if possible.
Definition: ApiBase.php:1008
encodeParamName( $paramName)
This method mangles parameter name based on the prefix supplied to the constructor.
Definition: ApiBase.php:714
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
warnOrDie(ApiMessage $msg, $enforceLimits=false)
Adds a warning to the output, else dies.
Definition: ApiBase.php:1994
mustBePosted()
Indicates whether this module must be called with a POST request.
Definition: ApiBase.php:420
getConditionalRequestData( $condition)
Returns data for HTTP conditional request mechanisms.
Definition: ApiBase.php:490
wfReadOnlyReason()
Check if the site is in read-only mode and return the message if so.
addError( $msg, $code=null, $data=null)
Add an error for this module without aborting.
Definition: ApiBase.php:1941
dieWithErrorOrDebug( $msg, $code=null, $data=null, $httpCode=null)
Will only set a warning instead of failing if the global $wgDebugAPI is set to true.
Definition: ApiBase.php:2157
filterIDs( $fields, array $ids)
Filter out-of-range values from a list of positive integer IDs.
Definition: ApiBase.php:1846
getModulePrefix()
Get parameter prefix (usually two letters or an empty string).
Definition: ApiBase.php:513
dieReadOnly()
Helper function for readonly errors.
Definition: ApiBase.php:2068
const RE_IP_BYTE
Definition: IP.php:29
getDescription()
Returns the description string for this module.
Definition: ApiBase.php:2602
$parent
Definition: pageupdater.txt:71
static getToken(User $user, MediaWiki\Session\Session $session, $salt)
Get a token from a salt.
Variant of the Message class.
Definition: RawMessage.php:34
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not...
getFinalDescription()
Get final module description, after hooks have had a chance to tweak it as needed.
Definition: ApiBase.php:2264
addWarning( $msg, $code=null, $data=null)
Add a warning for this module.
Definition: ApiBase.php:1894
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
const PARAM_DEPRECATED_VALUES
(array) When PARAM_TYPE is an array, this indicates which of the values are deprecated.
Definition: ApiBase.php:203
const PARAM_ISMULTI
(boolean) Accept multiple pipe-separated values for this parameter (e.g.
Definition: ApiBase.php:52
wfTransactionalTimeLimit()
Set PHP&#39;s time limit to the larger of php.ini or $wgTransactionalTimeLimit.
static dieDebug( $method, $message)
Internal code errors should be reported with this method.
Definition: ApiBase.php:2186
getExamples()
Returns usage examples for this module.
Definition: ApiBase.php:2640
const ALL_DEFAULT_STRING
Definition: ApiBase.php:250
dieBlocked(Block $block)
Throw an ApiUsageException, which will (if uncaught) call the main module&#39;s error handler and die wit...
Definition: ApiBase.php:2010
$mParamCache
Definition: ApiBase.php:279
This abstract class implements many basic API functions, and is the base of all API classes...
Definition: ApiBase.php:38
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:474
const PARAM_EXTRA_NAMESPACES
(int[]) When PARAM_TYPE is &#39;namespace&#39;, include these as additional possible values.
Definition: ApiBase.php:187
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:276
validateToken( $token, array $params)
Validate the supplied token.
Definition: ApiBase.php:1636
setWatch( $watch, $titleObj, $userOption=null)
Set a watch (or unwatch) based the based on a watchlist parameter.
Definition: ApiBase.php:1715
const PARAM_DEPRECATED
(boolean) Is the parameter deprecated (will show a warning)?
Definition: ApiBase.php:106
array null bool $mModuleSource
Definition: ApiBase.php:281
const DB_REPLICA
Definition: defines.php:25
getParamDescription()
Returns an array of parameter descriptions.
Definition: ApiBase.php:2619
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:525
getExamplesMessages()
Returns usage examples for this module.
Definition: ApiBase.php:354
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:963
const PARAM_MIN
(integer) Lowest value allowed for the parameter, for PARAM_TYPE &#39;integer&#39; and &#39;limit&#39;.
Definition: ApiBase.php:100
static newFromName( $name, $validate='valid')
Static factory method for creation from username.
Definition: User.php:585
$ext
Definition: router.php:55
shouldCheckMaxlag()
Indicates if this module needs maxlag to be checked.
Definition: ApiBase.php:389
static getValidNamespaces()
Returns an array of the namespaces (by integer id) that exist on the wiki.
getExtendedDescription()
Return the extended help text message.
Definition: ApiBase.php:2235
Definition: Block.php:29
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on $request
Definition: hooks.txt:2626
addMessagesFromStatus(StatusValue $status, $types=[ 'warning', 'error'])
Add warnings and/or errors from a Status.
Definition: ApiBase.php:1953
getFinalParams( $flags=0)
Get final list of parameters, after hooks have had a chance to tweak it as needed.
Definition: ApiBase.php:2293
checkUserRightsAny( $rights, $user=null)
Helper function for permission-denied errors.
Definition: ApiBase.php:2084
const PARAM_ALLOW_DUPLICATES
(boolean) Allow the same value to be set more than once when PARAM_ISMULTI is true?
Definition: ApiBase.php:103
return true to allow those checks to and false if checking is done & $user
Definition: hooks.txt:1487
static listParam(array $list, $type='text')
Definition: Message.php:1127
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:200
static create( $msg, $code=null, array $data=null)
Create an IApiMessage for the message.
Definition: ApiMessage.php:40
static isExternal( $username)
Tells whether the username is external or not.
isMain()
Returns true if this module is the main module ($this === $this->mMainModule), false otherwise...
Definition: ApiBase.php:530
isWriteMode()
Indicates whether this module requires write mode.
Definition: ApiBase.php:412
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:280
getAllowedParams()
Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (ar...
Definition: ApiBase.php:379