ApiBase.php 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009
  1. <?php
  2. /*
  3. * Created on Sep 5, 2006
  4. *
  5. * API for MediaWiki 1.8+
  6. *
  7. * Copyright (C) 2006 Yuri Astrakhan <Firstname><Lastname>@gmail.com
  8. *
  9. * This program is free software; you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License as published by
  11. * the Free Software Foundation; either version 2 of the License, or
  12. * (at your option) any later version.
  13. *
  14. * This program is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. * GNU General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU General Public License along
  20. * with this program; if not, write to the Free Software Foundation, Inc.,
  21. * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  22. * http://www.gnu.org/copyleft/gpl.html
  23. */
  24. /**
  25. * This abstract class implements many basic API functions, and is the base of
  26. * all API classes.
  27. * The class functions are divided into several areas of functionality:
  28. *
  29. * Module parameters: Derived classes can define getAllowedParams() to specify
  30. * which parameters to expect,h ow to parse and validate them.
  31. *
  32. * Profiling: various methods to allow keeping tabs on various tasks and their
  33. * time costs
  34. *
  35. * Self-documentation: code to allow the API to document its own state
  36. *
  37. * @ingroup API
  38. */
  39. abstract class ApiBase {
  40. // These constants allow modules to specify exactly how to treat incoming parameters.
  41. const PARAM_DFLT = 0; // Default value of the parameter
  42. const PARAM_ISMULTI = 1; // Boolean, do we accept more than one item for this parameter (e.g.: titles)?
  43. const PARAM_TYPE = 2; // Can be either a string type (e.g.: 'integer') or an array of allowed values
  44. const PARAM_MAX = 3; // Max value allowed for a parameter. Only applies if TYPE='integer'
  45. const PARAM_MAX2 = 4; // Max value allowed for a parameter for bots and sysops. Only applies if TYPE='integer'
  46. const PARAM_MIN = 5; // Lowest value allowed for a parameter. Only applies if TYPE='integer'
  47. const PARAM_ALLOW_DUPLICATES = 6; // Boolean, do we allow the same value to be set more than once when ISMULTI=true
  48. const LIMIT_BIG1 = 500; // Fast query, std user limit
  49. const LIMIT_BIG2 = 5000; // Fast query, bot/sysop limit
  50. const LIMIT_SML1 = 50; // Slow query, std user limit
  51. const LIMIT_SML2 = 500; // Slow query, bot/sysop limit
  52. private $mMainModule, $mModuleName, $mModulePrefix;
  53. /**
  54. * Constructor
  55. * @param $mainModule ApiMain object
  56. * @param $moduleName string Name of this module
  57. * @param $modulePrefix string Prefix to use for parameter names
  58. */
  59. public function __construct($mainModule, $moduleName, $modulePrefix = '') {
  60. $this->mMainModule = $mainModule;
  61. $this->mModuleName = $moduleName;
  62. $this->mModulePrefix = $modulePrefix;
  63. }
  64. /*****************************************************************************
  65. * ABSTRACT METHODS *
  66. *****************************************************************************/
  67. /**
  68. * Evaluates the parameters, performs the requested query, and sets up
  69. * the result. Concrete implementations of ApiBase must override this
  70. * method to provide whatever functionality their module offers.
  71. * Implementations must not produce any output on their own and are not
  72. * expected to handle any errors.
  73. *
  74. * The execute() method will be invoked directly by ApiMain immediately
  75. * before the result of the module is output. Aside from the
  76. * constructor, implementations should assume that no other methods
  77. * will be called externally on the module before the result is
  78. * processed.
  79. *
  80. * The result data should be stored in the ApiResult object available
  81. * through getResult().
  82. */
  83. public abstract function execute();
  84. /**
  85. * Returns a string that identifies the version of the extending class.
  86. * Typically includes the class name, the svn revision, timestamp, and
  87. * last author. Usually done with SVN's Id keyword
  88. * @return string
  89. */
  90. public abstract function getVersion();
  91. /**
  92. * Get the name of the module being executed by this instance
  93. * @return string
  94. */
  95. public function getModuleName() {
  96. return $this->mModuleName;
  97. }
  98. /**
  99. * Get parameter prefix (usually two letters or an empty string).
  100. * @return string
  101. */
  102. public function getModulePrefix() {
  103. return $this->mModulePrefix;
  104. }
  105. /**
  106. * Get the name of the module as shown in the profiler log
  107. * @return string
  108. */
  109. public function getModuleProfileName($db = false) {
  110. if ($db)
  111. return 'API:' . $this->mModuleName . '-DB';
  112. else
  113. return 'API:' . $this->mModuleName;
  114. }
  115. /**
  116. * Get the main module
  117. * @return ApiMain object
  118. */
  119. public function getMain() {
  120. return $this->mMainModule;
  121. }
  122. /**
  123. * Returns true if this module is the main module ($this === $this->mMainModule),
  124. * false otherwise.
  125. * @return bool
  126. */
  127. public function isMain() {
  128. return $this === $this->mMainModule;
  129. }
  130. /**
  131. * Get the result object
  132. * @return ApiResult
  133. */
  134. public function getResult() {
  135. // Main module has getResult() method overriden
  136. // Safety - avoid infinite loop:
  137. if ($this->isMain())
  138. ApiBase :: dieDebug(__METHOD__, 'base method was called on main module. ');
  139. return $this->getMain()->getResult();
  140. }
  141. /**
  142. * Get the result data array (read-only)
  143. * @return array
  144. */
  145. public function getResultData() {
  146. return $this->getResult()->getData();
  147. }
  148. /**
  149. * Set warning section for this module. Users should monitor this
  150. * section to notice any changes in API. Multiple calls to this
  151. * function will result in the warning messages being separated by
  152. * newlines
  153. * @param $warning string Warning message
  154. */
  155. public function setWarning($warning) {
  156. $data = $this->getResult()->getData();
  157. if(isset($data['warnings'][$this->getModuleName()]))
  158. {
  159. # Don't add duplicate warnings
  160. $warn_regex = preg_quote($warning, '/');
  161. if(preg_match("/{$warn_regex}(\\n|$)/", $data['warnings'][$this->getModuleName()]['*']))
  162. return;
  163. $oldwarning = $data['warnings'][$this->getModuleName()]['*'];
  164. # If there is a warning already, append it to the existing one
  165. $warning = "$oldwarning\n$warning";
  166. $this->getResult()->unsetValue('warnings', $this->getModuleName());
  167. }
  168. $msg = array();
  169. ApiResult :: setContent($msg, $warning);
  170. $this->getResult()->disableSizeCheck();
  171. $this->getResult()->addValue('warnings', $this->getModuleName(), $msg);
  172. $this->getResult()->enableSizeCheck();
  173. }
  174. /**
  175. * If the module may only be used with a certain format module,
  176. * it should override this method to return an instance of that formatter.
  177. * A value of null means the default format will be used.
  178. * @return mixed instance of a derived class of ApiFormatBase, or null
  179. */
  180. public function getCustomPrinter() {
  181. return null;
  182. }
  183. /**
  184. * Generates help message for this module, or false if there is no description
  185. * @return mixed string or false
  186. */
  187. public function makeHelpMsg() {
  188. static $lnPrfx = "\n ";
  189. $msg = $this->getDescription();
  190. if ($msg !== false) {
  191. if (!is_array($msg))
  192. $msg = array (
  193. $msg
  194. );
  195. $msg = $lnPrfx . implode($lnPrfx, $msg) . "\n";
  196. if ($this->isReadMode())
  197. $msg .= "\nThis module requires read rights.";
  198. if ($this->isWriteMode())
  199. $msg .= "\nThis module requires write rights.";
  200. if ($this->mustBePosted())
  201. $msg .= "\nThis module only accepts POST requests.";
  202. if ($this->isReadMode() || $this->isWriteMode() ||
  203. $this->mustBePosted())
  204. $msg .= "\n";
  205. // Parameters
  206. $paramsMsg = $this->makeHelpMsgParameters();
  207. if ($paramsMsg !== false) {
  208. $msg .= "Parameters:\n$paramsMsg";
  209. }
  210. // Examples
  211. $examples = $this->getExamples();
  212. if ($examples !== false) {
  213. if (!is_array($examples))
  214. $examples = array (
  215. $examples
  216. );
  217. $msg .= 'Example' . (count($examples) > 1 ? 's' : '') . ":\n ";
  218. $msg .= implode($lnPrfx, $examples) . "\n";
  219. }
  220. if ($this->getMain()->getShowVersions()) {
  221. $versions = $this->getVersion();
  222. $pattern = '/(\$.*) ([0-9a-z_]+\.php) (.*\$)/i';
  223. $replacement = '\\0' . "\n " . 'http://svn.wikimedia.org/viewvc/mediawiki/trunk/phase3/includes/api/\\2';
  224. if (is_array($versions)) {
  225. foreach ($versions as &$v)
  226. $v = preg_replace($pattern, $replacement, $v);
  227. $versions = implode("\n ", $versions);
  228. }
  229. else
  230. $versions = preg_replace($pattern, $replacement, $versions);
  231. $msg .= "Version:\n $versions\n";
  232. }
  233. }
  234. return $msg;
  235. }
  236. /**
  237. * Generates the parameter descriptions for this module, to be displayed in the
  238. * module's help.
  239. * @return string
  240. */
  241. public function makeHelpMsgParameters() {
  242. $params = $this->getFinalParams();
  243. if ($params !== false) {
  244. $paramsDescription = $this->getFinalParamDescription();
  245. $msg = '';
  246. $paramPrefix = "\n" . str_repeat(' ', 19);
  247. foreach ($params as $paramName => $paramSettings) {
  248. $desc = isset ($paramsDescription[$paramName]) ? $paramsDescription[$paramName] : '';
  249. if (is_array($desc))
  250. $desc = implode($paramPrefix, $desc);
  251. $type = isset($paramSettings[self :: PARAM_TYPE])? $paramSettings[self :: PARAM_TYPE] : null;
  252. if (isset ($type)) {
  253. if (isset ($paramSettings[self :: PARAM_ISMULTI]))
  254. $prompt = 'Values (separate with \'|\'): ';
  255. else
  256. $prompt = 'One value: ';
  257. if (is_array($type)) {
  258. $choices = array();
  259. $nothingPrompt = false;
  260. foreach ($type as $t)
  261. if ($t === '')
  262. $nothingPrompt = 'Can be empty, or ';
  263. else
  264. $choices[] = $t;
  265. $desc .= $paramPrefix . $nothingPrompt . $prompt . implode(', ', $choices);
  266. } else {
  267. switch ($type) {
  268. case 'namespace':
  269. // Special handling because namespaces are type-limited, yet they are not given
  270. $desc .= $paramPrefix . $prompt . implode(', ', ApiBase :: getValidNamespaces());
  271. break;
  272. case 'limit':
  273. $desc .= $paramPrefix . "No more than {$paramSettings[self :: PARAM_MAX]} ({$paramSettings[self :: PARAM_MAX2]} for bots) allowed.";
  274. break;
  275. case 'integer':
  276. $hasMin = isset($paramSettings[self :: PARAM_MIN]);
  277. $hasMax = isset($paramSettings[self :: PARAM_MAX]);
  278. if ($hasMin || $hasMax) {
  279. if (!$hasMax)
  280. $intRangeStr = "The value must be no less than {$paramSettings[self :: PARAM_MIN]}";
  281. elseif (!$hasMin)
  282. $intRangeStr = "The value must be no more than {$paramSettings[self :: PARAM_MAX]}";
  283. else
  284. $intRangeStr = "The value must be between {$paramSettings[self :: PARAM_MIN]} and {$paramSettings[self :: PARAM_MAX]}";
  285. $desc .= $paramPrefix . $intRangeStr;
  286. }
  287. break;
  288. }
  289. }
  290. }
  291. $default = is_array($paramSettings) ? (isset ($paramSettings[self :: PARAM_DFLT]) ? $paramSettings[self :: PARAM_DFLT] : null) : $paramSettings;
  292. if (!is_null($default) && $default !== false)
  293. $desc .= $paramPrefix . "Default: $default";
  294. $msg .= sprintf(" %-14s - %s\n", $this->encodeParamName($paramName), $desc);
  295. }
  296. return $msg;
  297. } else
  298. return false;
  299. }
  300. /**
  301. * Returns the description string for this module
  302. * @return mixed string or array of strings
  303. */
  304. protected function getDescription() {
  305. return false;
  306. }
  307. /**
  308. * Returns usage examples for this module. Return null if no examples are available.
  309. * @return mixed string or array of strings
  310. */
  311. protected function getExamples() {
  312. return false;
  313. }
  314. /**
  315. * Returns an array of allowed parameters (parameter name) => (default
  316. * value) or (parameter name) => (array with PARAM_* constants as keys)
  317. * Don't call this function directly: use getFinalParams() to allow
  318. * hooks to modify parameters as needed.
  319. * @return array
  320. */
  321. protected function getAllowedParams() {
  322. return false;
  323. }
  324. /**
  325. * Returns an array of parameter descriptions.
  326. * Don't call this functon directly: use getFinalParamDescription() to
  327. * allow hooks to modify descriptions as needed.
  328. * @return array
  329. */
  330. protected function getParamDescription() {
  331. return false;
  332. }
  333. /**
  334. * Get final list of parameters, after hooks have had a chance to
  335. * tweak it as needed.
  336. * @return array
  337. */
  338. public function getFinalParams() {
  339. $params = $this->getAllowedParams();
  340. wfRunHooks('APIGetAllowedParams', array(&$this, &$params));
  341. return $params;
  342. }
  343. /**
  344. * Get final description, after hooks have had a chance to tweak it as
  345. * needed.
  346. * @return array
  347. */
  348. public function getFinalParamDescription() {
  349. $desc = $this->getParamDescription();
  350. wfRunHooks('APIGetParamDescription', array(&$this, &$desc));
  351. return $desc;
  352. }
  353. /**
  354. * This method mangles parameter name based on the prefix supplied to the constructor.
  355. * Override this method to change parameter name during runtime
  356. * @param $paramName string Parameter name
  357. * @return string Prefixed parameter name
  358. */
  359. public function encodeParamName($paramName) {
  360. return $this->mModulePrefix . $paramName;
  361. }
  362. /**
  363. * Using getAllowedParams(), this function makes an array of the values
  364. * provided by the user, with key being the name of the variable, and
  365. * value - validated value from user or default. limit=max will not be
  366. * parsed if $parseMaxLimit is set to false; use this when the max
  367. * limit is not definitive yet, e.g. when getting revisions.
  368. * @param $parseMaxLimit bool
  369. * @return array
  370. */
  371. public function extractRequestParams($parseMaxLimit = true) {
  372. $params = $this->getFinalParams();
  373. $results = array ();
  374. foreach ($params as $paramName => $paramSettings)
  375. $results[$paramName] = $this->getParameterFromSettings($paramName, $paramSettings, $parseMaxLimit);
  376. return $results;
  377. }
  378. /**
  379. * Get a value for the given parameter
  380. * @param $paramName string Parameter name
  381. * @param $parseMaxLimit bool see extractRequestParams()
  382. * @return mixed Parameter value
  383. */
  384. protected function getParameter($paramName, $parseMaxLimit = true) {
  385. $params = $this->getFinalParams();
  386. $paramSettings = $params[$paramName];
  387. return $this->getParameterFromSettings($paramName, $paramSettings, $parseMaxLimit);
  388. }
  389. /**
  390. * Die if none or more than one of a certain set of parameters is set
  391. * @param $params array of parameter names
  392. */
  393. public function requireOnlyOneParameter($params) {
  394. $required = func_get_args();
  395. array_shift($required);
  396. $intersection = array_intersect(array_keys(array_filter($params,
  397. create_function('$x', 'return !is_null($x);')
  398. )), $required);
  399. if (count($intersection) > 1) {
  400. $this->dieUsage('The parameters '.implode(', ', $intersection).' can not be used together', 'invalidparammix');
  401. } elseif (count($intersection) == 0) {
  402. $this->dieUsage('One of the parameters '.implode(', ', $required).' is required', 'missingparam');
  403. }
  404. }
  405. /**
  406. * Returns an array of the namespaces (by integer id) that exist on the
  407. * wiki. Used primarily in help documentation.
  408. * @return array
  409. */
  410. public static function getValidNamespaces() {
  411. static $mValidNamespaces = null;
  412. if (is_null($mValidNamespaces)) {
  413. global $wgContLang;
  414. $mValidNamespaces = array ();
  415. foreach (array_keys($wgContLang->getNamespaces()) as $ns) {
  416. if ($ns >= 0)
  417. $mValidNamespaces[] = $ns;
  418. }
  419. }
  420. return $mValidNamespaces;
  421. }
  422. /**
  423. * Using the settings determine the value for the given parameter
  424. *
  425. * @param $paramName String: parameter name
  426. * @param $paramSettings Mixed: default value or an array of settings
  427. * using PARAM_* constants.
  428. * @param $parseMaxLimit Boolean: parse limit when max is given?
  429. * @return mixed Parameter value
  430. */
  431. protected function getParameterFromSettings($paramName, $paramSettings, $parseMaxLimit) {
  432. // Some classes may decide to change parameter names
  433. $encParamName = $this->encodeParamName($paramName);
  434. if (!is_array($paramSettings)) {
  435. $default = $paramSettings;
  436. $multi = false;
  437. $type = gettype($paramSettings);
  438. $dupes = false;
  439. } else {
  440. $default = isset ($paramSettings[self :: PARAM_DFLT]) ? $paramSettings[self :: PARAM_DFLT] : null;
  441. $multi = isset ($paramSettings[self :: PARAM_ISMULTI]) ? $paramSettings[self :: PARAM_ISMULTI] : false;
  442. $type = isset ($paramSettings[self :: PARAM_TYPE]) ? $paramSettings[self :: PARAM_TYPE] : null;
  443. $dupes = isset ($paramSettings[self:: PARAM_ALLOW_DUPLICATES]) ? $paramSettings[self :: PARAM_ALLOW_DUPLICATES] : false;
  444. // When type is not given, and no choices, the type is the same as $default
  445. if (!isset ($type)) {
  446. if (isset ($default))
  447. $type = gettype($default);
  448. else
  449. $type = 'NULL'; // allow everything
  450. }
  451. }
  452. if ($type == 'boolean') {
  453. if (isset ($default) && $default !== false) {
  454. // Having a default value of anything other than 'false' is pointless
  455. ApiBase :: dieDebug(__METHOD__, "Boolean param $encParamName's default is set to '$default'");
  456. }
  457. $value = $this->getMain()->getRequest()->getCheck($encParamName);
  458. } else {
  459. $value = $this->getMain()->getRequest()->getVal($encParamName, $default);
  460. if (isset ($value) && $type == 'namespace')
  461. $type = ApiBase :: getValidNamespaces();
  462. }
  463. if (isset ($value) && ($multi || is_array($type)))
  464. $value = $this->parseMultiValue($encParamName, $value, $multi, is_array($type) ? $type : null);
  465. // More validation only when choices were not given
  466. // choices were validated in parseMultiValue()
  467. if (isset ($value)) {
  468. if (!is_array($type)) {
  469. switch ($type) {
  470. case 'NULL' : // nothing to do
  471. break;
  472. case 'string' : // nothing to do
  473. break;
  474. case 'integer' : // Force everything using intval() and optionally validate limits
  475. $value = is_array($value) ? array_map('intval', $value) : intval($value);
  476. $min = isset ($paramSettings[self :: PARAM_MIN]) ? $paramSettings[self :: PARAM_MIN] : null;
  477. $max = isset ($paramSettings[self :: PARAM_MAX]) ? $paramSettings[self :: PARAM_MAX] : null;
  478. if (!is_null($min) || !is_null($max)) {
  479. $values = is_array($value) ? $value : array($value);
  480. foreach ($values as $v) {
  481. $this->validateLimit($paramName, $v, $min, $max);
  482. }
  483. }
  484. break;
  485. case 'limit' :
  486. if (!isset ($paramSettings[self :: PARAM_MAX]) || !isset ($paramSettings[self :: PARAM_MAX2]))
  487. ApiBase :: dieDebug(__METHOD__, "MAX1 or MAX2 are not defined for the limit $encParamName");
  488. if ($multi)
  489. ApiBase :: dieDebug(__METHOD__, "Multi-values not supported for $encParamName");
  490. $min = isset ($paramSettings[self :: PARAM_MIN]) ? $paramSettings[self :: PARAM_MIN] : 0;
  491. if( $value == 'max' ) {
  492. if( $parseMaxLimit ) {
  493. $value = $this->getMain()->canApiHighLimits() ? $paramSettings[self :: PARAM_MAX2] : $paramSettings[self :: PARAM_MAX];
  494. $this->getResult()->addValue( 'limits', $this->getModuleName(), $value );
  495. $this->validateLimit($paramName, $value, $min, $paramSettings[self :: PARAM_MAX], $paramSettings[self :: PARAM_MAX2]);
  496. }
  497. }
  498. else {
  499. $value = intval($value);
  500. $this->validateLimit($paramName, $value, $min, $paramSettings[self :: PARAM_MAX], $paramSettings[self :: PARAM_MAX2]);
  501. }
  502. break;
  503. case 'boolean' :
  504. if ($multi)
  505. ApiBase :: dieDebug(__METHOD__, "Multi-values not supported for $encParamName");
  506. break;
  507. case 'timestamp' :
  508. if ($multi)
  509. ApiBase :: dieDebug(__METHOD__, "Multi-values not supported for $encParamName");
  510. $value = wfTimestamp(TS_UNIX, $value);
  511. if ($value === 0)
  512. $this->dieUsage("Invalid value '$value' for timestamp parameter $encParamName", "badtimestamp_{$encParamName}");
  513. $value = wfTimestamp(TS_MW, $value);
  514. break;
  515. case 'user' :
  516. $title = Title::makeTitleSafe( NS_USER, $value );
  517. if ( is_null( $title ) )
  518. $this->dieUsage("Invalid value for user parameter $encParamName", "baduser_{$encParamName}");
  519. $value = $title->getText();
  520. break;
  521. default :
  522. ApiBase :: dieDebug(__METHOD__, "Param $encParamName's type is unknown - $type");
  523. }
  524. }
  525. // Throw out duplicates if requested
  526. if (is_array($value) && !$dupes)
  527. $value = array_unique($value);
  528. }
  529. return $value;
  530. }
  531. /**
  532. * Return an array of values that were given in a 'a|b|c' notation,
  533. * after it optionally validates them against the list allowed values.
  534. *
  535. * @param $valueName string The name of the parameter (for error
  536. * reporting)
  537. * @param $value mixed The value being parsed
  538. * @param $allowMultiple bool Can $value contain more than one value
  539. * separated by '|'?
  540. * @param $allowedValues mixed An array of values to check against. If
  541. * null, all values are accepted.
  542. * @return mixed (allowMultiple ? an_array_of_values : a_single_value)
  543. */
  544. protected function parseMultiValue($valueName, $value, $allowMultiple, $allowedValues) {
  545. if( trim($value) === "" && $allowMultiple)
  546. return array();
  547. $sizeLimit = $this->mMainModule->canApiHighLimits() ? self::LIMIT_SML2 : self::LIMIT_SML1;
  548. $valuesList = explode('|', $value, $sizeLimit + 1);
  549. if( self::truncateArray($valuesList, $sizeLimit) ) {
  550. $this->setWarning("Too many values supplied for parameter '$valueName': the limit is $sizeLimit");
  551. }
  552. if (!$allowMultiple && count($valuesList) != 1) {
  553. $possibleValues = is_array($allowedValues) ? "of '" . implode("', '", $allowedValues) . "'" : '';
  554. $this->dieUsage("Only one $possibleValues is allowed for parameter '$valueName'", "multival_$valueName");
  555. }
  556. if (is_array($allowedValues)) {
  557. # Check for unknown values
  558. $unknown = array_diff($valuesList, $allowedValues);
  559. if(count($unknown))
  560. {
  561. if($allowMultiple)
  562. {
  563. $s = count($unknown) > 1 ? "s" : "";
  564. $vals = implode(", ", $unknown);
  565. $this->setWarning("Unrecognized value$s for parameter '$valueName': $vals");
  566. }
  567. else
  568. $this->dieUsage("Unrecognized value for parameter '$valueName': {$valuesList[0]}", "unknown_$valueName");
  569. }
  570. # Now throw them out
  571. $valuesList = array_intersect($valuesList, $allowedValues);
  572. }
  573. return $allowMultiple ? $valuesList : $valuesList[0];
  574. }
  575. /**
  576. * Validate the value against the minimum and user/bot maximum limits.
  577. * Prints usage info on failure.
  578. * @param $paramName string Parameter name
  579. * @param $value int Parameter value
  580. * @param $min int Minimum value
  581. * @param $max int Maximum value for users
  582. * @param $botMax int Maximum value for sysops/bots
  583. */
  584. function validateLimit($paramName, $value, $min, $max, $botMax = null) {
  585. if (!is_null($min) && $value < $min) {
  586. $this->dieUsage($this->encodeParamName($paramName) . " may not be less than $min (set to $value)", $paramName);
  587. }
  588. // Minimum is always validated, whereas maximum is checked only if not running in internal call mode
  589. if ($this->getMain()->isInternalMode())
  590. return;
  591. // Optimization: do not check user's bot status unless really needed -- skips db query
  592. // assumes $botMax >= $max
  593. if (!is_null($max) && $value > $max) {
  594. if (!is_null($botMax) && $this->getMain()->canApiHighLimits()) {
  595. if ($value > $botMax) {
  596. $this->dieUsage($this->encodeParamName($paramName) . " may not be over $botMax (set to $value) for bots or sysops", $paramName);
  597. }
  598. } else {
  599. $this->dieUsage($this->encodeParamName($paramName) . " may not be over $max (set to $value) for users", $paramName);
  600. }
  601. }
  602. }
  603. /**
  604. * Truncate an array to a certain length.
  605. * @param $arr array Array to truncate
  606. * @param $limit int Maximum length
  607. * @return bool True if the array was truncated, false otherwise
  608. */
  609. public static function truncateArray(&$arr, $limit)
  610. {
  611. $modified = false;
  612. while(count($arr) > $limit)
  613. {
  614. $junk = array_pop($arr);
  615. $modified = true;
  616. }
  617. return $modified;
  618. }
  619. /**
  620. * Call the main module's error handler
  621. * @param $description string Error text
  622. * @param $errorCode string Error code
  623. * @param $httpRespCode int HTTP response code
  624. */
  625. public function dieUsage($description, $errorCode, $httpRespCode = 0) {
  626. wfProfileClose();
  627. throw new UsageException($description, $this->encodeParamName($errorCode), $httpRespCode);
  628. }
  629. /**
  630. * Array that maps message keys to error messages. $1 and friends are replaced.
  631. */
  632. public static $messageMap = array(
  633. // This one MUST be present, or dieUsageMsg() will recurse infinitely
  634. 'unknownerror' => array('code' => 'unknownerror', 'info' => "Unknown error: ``\$1''"),
  635. 'unknownerror-nocode' => array('code' => 'unknownerror', 'info' => 'Unknown error'),
  636. // Messages from Title::getUserPermissionsErrors()
  637. 'ns-specialprotected' => array('code' => 'unsupportednamespace', 'info' => "Pages in the Special namespace can't be edited"),
  638. 'protectedinterface' => array('code' => 'protectednamespace-interface', 'info' => "You're not allowed to edit interface messages"),
  639. 'namespaceprotected' => array('code' => 'protectednamespace', 'info' => "You're not allowed to edit pages in the ``\$1'' namespace"),
  640. 'customcssjsprotected' => array('code' => 'customcssjsprotected', 'info' => "You're not allowed to edit custom CSS and JavaScript pages"),
  641. 'cascadeprotected' => array('code' => 'cascadeprotected', 'info' =>"The page you're trying to edit is protected because it's included in a cascade-protected page"),
  642. 'protectedpagetext' => array('code' => 'protectedpage', 'info' => "The ``\$1'' right is required to edit this page"),
  643. 'protect-cantedit' => array('code' => 'cantedit', 'info' => "You can't protect this page because you can't edit it"),
  644. 'badaccess-group0' => array('code' => 'permissiondenied', 'info' => "Permission denied"), // Generic permission denied message
  645. 'badaccess-groups' => array('code' => 'permissiondenied', 'info' => "Permission denied"),
  646. 'titleprotected' => array('code' => 'protectedtitle', 'info' => "This title has been protected from creation"),
  647. 'nocreate-loggedin' => array('code' => 'cantcreate', 'info' => "You don't have permission to create new pages"),
  648. 'nocreatetext' => array('code' => 'cantcreate-anon', 'info' => "Anonymous users can't create new pages"),
  649. 'movenologintext' => array('code' => 'cantmove-anon', 'info' => "Anonymous users can't move pages"),
  650. 'movenotallowed' => array('code' => 'cantmove', 'info' => "You don't have permission to move pages"),
  651. 'confirmedittext' => array('code' => 'confirmemail', 'info' => "You must confirm your e-mail address before you can edit"),
  652. 'blockedtext' => array('code' => 'blocked', 'info' => "You have been blocked from editing"),
  653. 'autoblockedtext' => array('code' => 'autoblocked', 'info' => "Your IP address has been blocked automatically, because it was used by a blocked user"),
  654. // Miscellaneous interface messages
  655. 'actionthrottledtext' => array('code' => 'ratelimited', 'info' => "You've exceeded your rate limit. Please wait some time and try again"),
  656. 'alreadyrolled' => array('code' => 'alreadyrolled', 'info' => "The page you tried to rollback was already rolled back"),
  657. 'cantrollback' => array('code' => 'onlyauthor', 'info' => "The page you tried to rollback only has one author"),
  658. 'readonlytext' => array('code' => 'readonly', 'info' => "The wiki is currently in read-only mode"),
  659. 'sessionfailure' => array('code' => 'badtoken', 'info' => "Invalid token"),
  660. 'cannotdelete' => array('code' => 'cantdelete', 'info' => "Couldn't delete ``\$1''. Maybe it was deleted already by someone else"),
  661. 'notanarticle' => array('code' => 'missingtitle', 'info' => "The page you requested doesn't exist"),
  662. 'selfmove' => array('code' => 'selfmove', 'info' => "Can't move a page to itself"),
  663. 'immobile_namespace' => array('code' => 'immobilenamespace', 'info' => "You tried to move pages from or to a namespace that is protected from moving"),
  664. 'articleexists' => array('code' => 'articleexists', 'info' => "The destination article already exists and is not a redirect to the source article"),
  665. 'protectedpage' => array('code' => 'protectedpage', 'info' => "You don't have permission to perform this move"),
  666. 'hookaborted' => array('code' => 'hookaborted', 'info' => "The modification you tried to make was aborted by an extension hook"),
  667. 'cantmove-titleprotected' => array('code' => 'protectedtitle', 'info' => "The destination article has been protected from creation"),
  668. 'imagenocrossnamespace' => array('code' => 'nonfilenamespace', 'info' => "Can't move a file to a non-file namespace"),
  669. 'imagetypemismatch' => array('code' => 'filetypemismatch', 'info' => "The new file extension doesn't match its type"),
  670. // 'badarticleerror' => shouldn't happen
  671. // 'badtitletext' => shouldn't happen
  672. 'ip_range_invalid' => array('code' => 'invalidrange', 'info' => "Invalid IP range"),
  673. 'range_block_disabled' => array('code' => 'rangedisabled', 'info' => "Blocking IP ranges has been disabled"),
  674. 'nosuchusershort' => array('code' => 'nosuchuser', 'info' => "The user you specified doesn't exist"),
  675. 'badipaddress' => array('code' => 'invalidip', 'info' => "Invalid IP address specified"),
  676. 'ipb_expiry_invalid' => array('code' => 'invalidexpiry', 'info' => "Invalid expiry time"),
  677. 'ipb_already_blocked' => array('code' => 'alreadyblocked', 'info' => "The user you tried to block was already blocked"),
  678. 'ipb_blocked_as_range' => array('code' => 'blockedasrange', 'info' => "IP address ``\$1'' was blocked as part of range ``\$2''. You can't unblock the IP invidually, but you can unblock the range as a whole."),
  679. 'ipb_cant_unblock' => array('code' => 'cantunblock', 'info' => "The block you specified was not found. It may have been unblocked already"),
  680. 'mailnologin' => array('code' => 'cantsend', 'info' => "You're not logged in or you don't have a confirmed e-mail address, so you can't send e-mail"),
  681. 'usermaildisabled' => array('code' => 'usermaildisabled', 'info' => "User email has been disabled"),
  682. 'blockedemailuser' => array('code' => 'blockedfrommail', 'info' => "You have been blocked from sending e-mail"),
  683. 'notarget' => array('code' => 'notarget', 'info' => "You have not specified a valid target for this action"),
  684. 'noemail' => array('code' => 'noemail', 'info' => "The user has not specified a valid e-mail address, or has chosen not to receive e-mail from other users"),
  685. 'rcpatroldisabled' => array('code' => 'patroldisabled', 'info' => "Patrolling is disabled on this wiki"),
  686. 'markedaspatrollederror-noautopatrol' => array('code' => 'noautopatrol', 'info' => "You don't have permission to patrol your own changes"),
  687. 'delete-toobig' => array('code' => 'bigdelete', 'info' => "You can't delete this page because it has more than \$1 revisions"),
  688. 'movenotallowedfile' => array('code' => 'cantmovefile', 'info' => "You don't have permission to move files"),
  689. // API-specific messages
  690. 'readrequired' => array('code' => 'readapidenied', 'info' => "You need read permission to use this module"),
  691. 'writedisabled' => array('code' => 'noapiwrite', '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"),
  692. 'writerequired' => array('code' => 'writeapidenied', 'info' => "You're not allowed to edit this wiki through the API"),
  693. 'missingparam' => array('code' => 'no$1', 'info' => "The \$1 parameter must be set"),
  694. 'invalidtitle' => array('code' => 'invalidtitle', 'info' => "Bad title ``\$1''"),
  695. 'nosuchpageid' => array('code' => 'nosuchpageid', 'info' => "There is no page with ID \$1"),
  696. 'nosuchrevid' => array('code' => 'nosuchrevid', 'info' => "There is no revision with ID \$1"),
  697. 'invaliduser' => array('code' => 'invaliduser', 'info' => "Invalid username ``\$1''"),
  698. 'invalidexpiry' => array('code' => 'invalidexpiry', 'info' => "Invalid expiry time ``\$1''"),
  699. 'pastexpiry' => array('code' => 'pastexpiry', 'info' => "Expiry time ``\$1'' is in the past"),
  700. 'create-titleexists' => array('code' => 'create-titleexists', 'info' => "Existing titles can't be protected with 'create'"),
  701. 'missingtitle-createonly' => array('code' => 'missingtitle-createonly', 'info' => "Missing titles can only be protected with 'create'"),
  702. 'cantblock' => array('code' => 'cantblock', 'info' => "You don't have permission to block users"),
  703. 'canthide' => array('code' => 'canthide', 'info' => "You don't have permission to hide user names from the block log"),
  704. 'cantblock-email' => array('code' => 'cantblock-email', 'info' => "You don't have permission to block users from sending e-mail through the wiki"),
  705. 'unblock-notarget' => array('code' => 'notarget', 'info' => "Either the id or the user parameter must be set"),
  706. 'unblock-idanduser' => array('code' => 'idanduser', 'info' => "The id and user parameters can't be used together"),
  707. 'cantunblock' => array('code' => 'permissiondenied', 'info' => "You don't have permission to unblock users"),
  708. 'cannotundelete' => array('code' => 'cantundelete', 'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already"),
  709. 'permdenied-undelete' => array('code' => 'permissiondenied', 'info' => "You don't have permission to restore deleted revisions"),
  710. 'createonly-exists' => array('code' => 'articleexists', 'info' => "The article you tried to create has been created already"),
  711. 'nocreate-missing' => array('code' => 'missingtitle', 'info' => "The article you tried to edit doesn't exist"),
  712. 'nosuchrcid' => array('code' => 'nosuchrcid', 'info' => "There is no change with rcid ``\$1''"),
  713. 'cantpurge' => array('code' => 'cantpurge', 'info' => "Only users with the 'purge' right can purge pages via the API"),
  714. 'protect-invalidaction' => array('code' => 'protect-invalidaction', 'info' => "Invalid protection type ``\$1''"),
  715. 'protect-invalidlevel' => array('code' => 'protect-invalidlevel', 'info' => "Invalid protection level ``\$1''"),
  716. 'toofewexpiries' => array('code' => 'toofewexpiries', 'info' => "\$1 expiry timestamps were provided where \$2 were needed"),
  717. 'cantimport' => array('code' => 'cantimport', 'info' => "You don't have permission to import pages"),
  718. 'cantimport-upload' => array('code' => 'cantimport-upload', 'info' => "You don't have permission to import uploaded pages"),
  719. 'importnofile' => array('code' => 'nofile', 'info' => "You didn't upload a file"),
  720. 'importuploaderrorsize' => array('code' => 'filetoobig', 'info' => 'The file you uploaded is bigger than the maximum upload size'),
  721. 'importuploaderrorpartial' => array('code' => 'partialupload', 'info' => 'The file was only partially uploaded'),
  722. 'importuploaderrortemp' => array('code' => 'notempdir', 'info' => 'The temporary upload directory is missing'),
  723. 'importcantopen' => array('code' => 'cantopenfile', 'info' => "Couldn't open the uploaded file"),
  724. 'import-noarticle' => array('code' => 'badinterwiki', 'info' => 'Invalid interwiki title specified'),
  725. 'importbadinterwiki' => array('code' => 'badinterwiki', 'info' => 'Invalid interwiki title specified'),
  726. 'import-unknownerror' => array('code' => 'import-unknownerror', 'info' => "Unknown error on import: ``\$1''"),
  727. // ApiEditPage messages
  728. 'noimageredirect-anon' => array('code' => 'noimageredirect-anon', 'info' => "Anonymous users can't create image redirects"),
  729. 'noimageredirect-logged' => array('code' => 'noimageredirect', 'info' => "You don't have permission to create image redirects"),
  730. 'spamdetected' => array('code' => 'spamdetected', 'info' => "Your edit was refused because it contained a spam fragment: ``\$1''"),
  731. 'filtered' => array('code' => 'filtered', 'info' => "The filter callback function refused your edit"),
  732. 'contenttoobig' => array('code' => 'contenttoobig', 'info' => "The content you supplied exceeds the article size limit of \$1 kilobytes"),
  733. 'noedit-anon' => array('code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages"),
  734. 'noedit' => array('code' => 'noedit', 'info' => "You don't have permission to edit pages"),
  735. 'wasdeleted' => array('code' => 'pagedeleted', 'info' => "The page has been deleted since you fetched its timestamp"),
  736. 'blankpage' => array('code' => 'emptypage', 'info' => "Creating new, empty pages is not allowed"),
  737. 'editconflict' => array('code' => 'editconflict', 'info' => "Edit conflict detected"),
  738. 'hashcheckfailed' => array('code' => 'badmd5', 'info' => "The supplied MD5 hash was incorrect"),
  739. 'missingtext' => array('code' => 'notext', 'info' => "One of the text, appendtext, prependtext and undo parameters must be set"),
  740. 'emptynewsection' => array('code' => 'emptynewsection', 'info' => 'Creating empty new sections is not possible.'),
  741. 'revwrongpage' => array('code' => 'revwrongpage', 'info' => "r\$1 is not a revision of ``\$2''"),
  742. 'undo-failure' => array('code' => 'undofailure', 'info' => 'Undo failed due to conflicting intermediate edits'),
  743. );
  744. /**
  745. * Output the error message related to a certain array
  746. * @param $error array Element of a getUserPermissionsErrors()-style array
  747. */
  748. public function dieUsageMsg($error) {
  749. $parsed = $this->parseMsg($error);
  750. $this->dieUsage($parsed['info'], $parsed['code']);
  751. }
  752. /**
  753. * Return the error message related to a certain array
  754. * @param $error array Element of a getUserPermissionsErrors()-style array
  755. * @return array('code' => code, 'info' => info)
  756. */
  757. public function parseMsg($error) {
  758. $key = array_shift($error);
  759. if(isset(self::$messageMap[$key]))
  760. return array( 'code' =>
  761. wfMsgReplaceArgs(self::$messageMap[$key]['code'], $error),
  762. 'info' =>
  763. wfMsgReplaceArgs(self::$messageMap[$key]['info'], $error)
  764. );
  765. // If the key isn't present, throw an "unknown error"
  766. return $this->parseMsg(array('unknownerror', $key));
  767. }
  768. /**
  769. * Internal code errors should be reported with this method
  770. * @param $method string Method or function name
  771. * @param $message string Error message
  772. */
  773. protected static function dieDebug($method, $message) {
  774. wfDebugDieBacktrace("Internal error in $method: $message");
  775. }
  776. /**
  777. * Indicates if this module needs maxlag to be checked
  778. * @return bool
  779. */
  780. public function shouldCheckMaxlag() {
  781. return true;
  782. }
  783. /**
  784. * Indicates whether this module requires read rights
  785. * @return bool
  786. */
  787. public function isReadMode() {
  788. return true;
  789. }
  790. /**
  791. * Indicates whether this module requires write mode
  792. * @return bool
  793. */
  794. public function isWriteMode() {
  795. return false;
  796. }
  797. /**
  798. * Indicates whether this module must be called with a POST request
  799. * @return bool
  800. */
  801. public function mustBePosted() {
  802. return false;
  803. }
  804. /**
  805. * Profiling: total module execution time
  806. */
  807. private $mTimeIn = 0, $mModuleTime = 0;
  808. /**
  809. * Start module profiling
  810. */
  811. public function profileIn() {
  812. if ($this->mTimeIn !== 0)
  813. ApiBase :: dieDebug(__METHOD__, 'called twice without calling profileOut()');
  814. $this->mTimeIn = microtime(true);
  815. wfProfileIn($this->getModuleProfileName());
  816. }
  817. /**
  818. * End module profiling
  819. */
  820. public function profileOut() {
  821. if ($this->mTimeIn === 0)
  822. ApiBase :: dieDebug(__METHOD__, 'called without calling profileIn() first');
  823. if ($this->mDBTimeIn !== 0)
  824. ApiBase :: dieDebug(__METHOD__, 'must be called after database profiling is done with profileDBOut()');
  825. $this->mModuleTime += microtime(true) - $this->mTimeIn;
  826. $this->mTimeIn = 0;
  827. wfProfileOut($this->getModuleProfileName());
  828. }
  829. /**
  830. * When modules crash, sometimes it is needed to do a profileOut() regardless
  831. * of the profiling state the module was in. This method does such cleanup.
  832. */
  833. public function safeProfileOut() {
  834. if ($this->mTimeIn !== 0) {
  835. if ($this->mDBTimeIn !== 0)
  836. $this->profileDBOut();
  837. $this->profileOut();
  838. }
  839. }
  840. /**
  841. * Total time the module was executed
  842. * @return float
  843. */
  844. public function getProfileTime() {
  845. if ($this->mTimeIn !== 0)
  846. ApiBase :: dieDebug(__METHOD__, 'called without calling profileOut() first');
  847. return $this->mModuleTime;
  848. }
  849. /**
  850. * Profiling: database execution time
  851. */
  852. private $mDBTimeIn = 0, $mDBTime = 0;
  853. /**
  854. * Start module profiling
  855. */
  856. public function profileDBIn() {
  857. if ($this->mTimeIn === 0)
  858. ApiBase :: dieDebug(__METHOD__, 'must be called while profiling the entire module with profileIn()');
  859. if ($this->mDBTimeIn !== 0)
  860. ApiBase :: dieDebug(__METHOD__, 'called twice without calling profileDBOut()');
  861. $this->mDBTimeIn = microtime(true);
  862. wfProfileIn($this->getModuleProfileName(true));
  863. }
  864. /**
  865. * End database profiling
  866. */
  867. public function profileDBOut() {
  868. if ($this->mTimeIn === 0)
  869. ApiBase :: dieDebug(__METHOD__, 'must be called while profiling the entire module with profileIn()');
  870. if ($this->mDBTimeIn === 0)
  871. ApiBase :: dieDebug(__METHOD__, 'called without calling profileDBIn() first');
  872. $time = microtime(true) - $this->mDBTimeIn;
  873. $this->mDBTimeIn = 0;
  874. $this->mDBTime += $time;
  875. $this->getMain()->mDBTime += $time;
  876. wfProfileOut($this->getModuleProfileName(true));
  877. }
  878. /**
  879. * Total time the module used the database
  880. * @return float
  881. */
  882. public function getProfileDBTime() {
  883. if ($this->mDBTimeIn !== 0)
  884. ApiBase :: dieDebug(__METHOD__, 'called without calling profileDBOut() first');
  885. return $this->mDBTime;
  886. }
  887. /**
  888. * Debugging function that prints a value and an optional backtrace
  889. * @param $value mixed Value to print
  890. * @param $name string Description of the printed value
  891. * @param $backtrace bool If true, print a backtrace
  892. */
  893. public static function debugPrint($value, $name = 'unknown', $backtrace = false) {
  894. print "\n\n<pre><b>Debugging value '$name':</b>\n\n";
  895. var_export($value);
  896. if ($backtrace)
  897. print "\n" . wfBacktrace();
  898. print "\n</pre>\n";
  899. }
  900. /**
  901. * Returns a string that identifies the version of this class.
  902. * @return string
  903. */
  904. public static function getBaseVersion() {
  905. return __CLASS__ . ': $Id: ApiBase.php 50217 2009-05-05 13:12:16Z tstarling $';
  906. }
  907. }