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