* API: Add documentation to important API classes
[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->mustBePosted())
222 $msg .= "\nThis module only accepts POST requests.\n";
223
224 // Parameters
225 $paramsMsg = $this->makeHelpMsgParameters();
226 if ($paramsMsg !== false) {
227 $msg .= "Parameters:\n$paramsMsg";
228 }
229
230 // Examples
231 $examples = $this->getExamples();
232 if ($examples !== false) {
233 if (!is_array($examples))
234 $examples = array (
235 $examples
236 );
237 $msg .= 'Example' . (count($examples) > 1 ? 's' : '') . ":\n ";
238 $msg .= implode($lnPrfx, $examples) . "\n";
239 }
240
241 if ($this->getMain()->getShowVersions()) {
242 $versions = $this->getVersion();
243 $pattern = '(\$.*) ([0-9a-z_]+\.php) (.*\$)';
244 $replacement = '\\0' . "\n " . 'http://svn.wikimedia.org/viewvc/mediawiki/trunk/phase3/includes/api/\\2';
245
246 if (is_array($versions)) {
247 foreach ($versions as &$v)
248 $v = eregi_replace($pattern, $replacement, $v);
249 $versions = implode("\n ", $versions);
250 }
251 else
252 $versions = eregi_replace($pattern, $replacement, $versions);
253
254 $msg .= "Version:\n $versions\n";
255 }
256 }
257
258 return $msg;
259 }
260
261 /**
262 * Generates the parameter descriptions for this module, to be displayed in the
263 * module's help.
264 * @return string
265 */
266 public function makeHelpMsgParameters() {
267 $params = $this->getFinalParams();
268 if ($params !== false) {
269
270 $paramsDescription = $this->getFinalParamDescription();
271 $msg = '';
272 $paramPrefix = "\n" . str_repeat(' ', 19);
273 foreach ($params as $paramName => $paramSettings) {
274 $desc = isset ($paramsDescription[$paramName]) ? $paramsDescription[$paramName] : '';
275 if (is_array($desc))
276 $desc = implode($paramPrefix, $desc);
277
278 $type = isset($paramSettings[self :: PARAM_TYPE])? $paramSettings[self :: PARAM_TYPE] : null;
279 if (isset ($type)) {
280 if (isset ($paramSettings[self :: PARAM_ISMULTI]))
281 $prompt = 'Values (separate with \'|\'): ';
282 else
283 $prompt = 'One value: ';
284
285 if (is_array($type)) {
286 $choices = array();
287 $nothingPrompt = false;
288 foreach ($type as $t)
289 if ($t === '')
290 $nothingPrompt = 'Can be empty, or ';
291 else
292 $choices[] = $t;
293 $desc .= $paramPrefix . $nothingPrompt . $prompt . implode(', ', $choices);
294 } else {
295 switch ($type) {
296 case 'namespace':
297 // Special handling because namespaces are type-limited, yet they are not given
298 $desc .= $paramPrefix . $prompt . implode(', ', ApiBase :: getValidNamespaces());
299 break;
300 case 'limit':
301 $desc .= $paramPrefix . "No more than {$paramSettings[self :: PARAM_MAX]} ({$paramSettings[self :: PARAM_MAX2]} for bots) allowed.";
302 break;
303 case 'integer':
304 $hasMin = isset($paramSettings[self :: PARAM_MIN]);
305 $hasMax = isset($paramSettings[self :: PARAM_MAX]);
306 if ($hasMin || $hasMax) {
307 if (!$hasMax)
308 $intRangeStr = "The value must be no less than {$paramSettings[self :: PARAM_MIN]}";
309 elseif (!$hasMin)
310 $intRangeStr = "The value must be no more than {$paramSettings[self :: PARAM_MAX]}";
311 else
312 $intRangeStr = "The value must be between {$paramSettings[self :: PARAM_MIN]} and {$paramSettings[self :: PARAM_MAX]}";
313
314 $desc .= $paramPrefix . $intRangeStr;
315 }
316 break;
317 }
318 }
319 }
320
321 $default = is_array($paramSettings) ? (isset ($paramSettings[self :: PARAM_DFLT]) ? $paramSettings[self :: PARAM_DFLT] : null) : $paramSettings;
322 if (!is_null($default) && $default !== false)
323 $desc .= $paramPrefix . "Default: $default";
324
325 $msg .= sprintf(" %-14s - %s\n", $this->encodeParamName($paramName), $desc);
326 }
327 return $msg;
328
329 } else
330 return false;
331 }
332
333 /**
334 * Returns the description string for this module
335 * @return mixed string or array of strings
336 */
337 protected function getDescription() {
338 return false;
339 }
340
341 /**
342 * Returns usage examples for this module. Return null if no examples are available.
343 * @return mixed string or array of strings
344 */
345 protected function getExamples() {
346 return false;
347 }
348
349 /**
350 * Returns an array of allowed parameters (parameter name) => (default
351 * value) or (parameter name) => (array with PARAM_* constants as keys)
352 * Don't call this function directly: use getFinalParams() to allow
353 * hooks to modify parameters as needed.
354 * @return array
355 */
356 protected function getAllowedParams() {
357 return false;
358 }
359
360 /**
361 * Returns an array of parameter descriptions.
362 * Don't call this functon directly: use getFinalParamDescription() to
363 * allow hooks to modify descriptions as needed.
364 * @return array
365 */
366 protected function getParamDescription() {
367 return false;
368 }
369
370 /**
371 * Get final list of parameters, after hooks have had a chance to
372 * tweak it as needed.
373 * @return array
374 */
375 public function getFinalParams() {
376 $params = $this->getAllowedParams();
377 wfRunHooks('APIGetAllowedParams', array(&$this, &$params));
378 return $params;
379 }
380
381 /**
382 * Get final description, after hooks have had a chance to tweak it as
383 * needed.
384 * @return array
385 */
386 public function getFinalParamDescription() {
387 $desc = $this->getParamDescription();
388 wfRunHooks('APIGetParamDescription', array(&$this, &$desc));
389 return $desc;
390 }
391
392 /**
393 * This method mangles parameter name based on the prefix supplied to the constructor.
394 * Override this method to change parameter name during runtime
395 * @param $paramName string Parameter name
396 * @return string Prefixed parameter name
397 */
398 public function encodeParamName($paramName) {
399 return $this->mModulePrefix . $paramName;
400 }
401
402 /**
403 * Using getAllowedParams(), this function makes an array of the values
404 * provided by the user, with key being the name of the variable, and
405 * value - validated value from user or default. limit=max will not be
406 * parsed if $parseMaxLimit is set to false; use this when the max
407 * limit is not definitive yet, e.g. when getting revisions.
408 * @param $parseMaxLimit bool
409 * @return array
410 */
411 public function extractRequestParams($parseMaxLimit = true) {
412 $params = $this->getFinalParams();
413 $results = array ();
414
415 foreach ($params as $paramName => $paramSettings)
416 $results[$paramName] = $this->getParameterFromSettings($paramName, $paramSettings, $parseMaxLimit);
417
418 return $results;
419 }
420
421 /**
422 * Get a value for the given parameter
423 * @param $paramName string Parameter name
424 * @param $parseMaxLimit bool see extractRequestParams()
425 * @return mixed Parameter value
426 */
427 protected function getParameter($paramName, $parseMaxLimit = true) {
428 $params = $this->getFinalParams();
429 $paramSettings = $params[$paramName];
430 return $this->getParameterFromSettings($paramName, $paramSettings, $parseMaxLimit);
431 }
432
433 /**
434 * Die if none or more than one of a certain set of parameters is set
435 * @param $params array of parameter names
436 */
437 public function requireOnlyOneParameter($params) {
438 $required = func_get_args();
439 array_shift($required);
440
441 $intersection = array_intersect(array_keys(array_filter($params,
442 create_function('$x', 'return !is_null($x);')
443 )), $required);
444 if (count($intersection) > 1) {
445 $this->dieUsage('The parameters '.implode(', ', $intersection).' can not be used together', 'invalidparammix');
446 } elseif (count($intersection) == 0) {
447 $this->dieUsage('One of the parameters '.implode(', ', $required).' is required', 'missingparam');
448 }
449 }
450
451 /**
452 * Returns an array of the namespaces (by integer id) that exist on the
453 * wiki. Used primarily in help documentation.
454 * @return array
455 */
456 public static function getValidNamespaces() {
457 static $mValidNamespaces = null;
458 if (is_null($mValidNamespaces)) {
459
460 global $wgContLang;
461 $mValidNamespaces = array ();
462 foreach (array_keys($wgContLang->getNamespaces()) as $ns) {
463 if ($ns >= 0)
464 $mValidNamespaces[] = $ns;
465 }
466 }
467 return $mValidNamespaces;
468 }
469
470 /**
471 * Using the settings determine the value for the given parameter
472 *
473 * @param $paramName String: parameter name
474 * @param $paramSettings Mixed: default value or an array of settings
475 * using PARAM_* constants.
476 * @param $parseMaxLimit Boolean: parse limit when max is given?
477 * @return mixed Parameter value
478 */
479 protected function getParameterFromSettings($paramName, $paramSettings, $parseMaxLimit) {
480
481 // Some classes may decide to change parameter names
482 $encParamName = $this->encodeParamName($paramName);
483
484 if (!is_array($paramSettings)) {
485 $default = $paramSettings;
486 $multi = false;
487 $type = gettype($paramSettings);
488 $dupes = false;
489 } else {
490 $default = isset ($paramSettings[self :: PARAM_DFLT]) ? $paramSettings[self :: PARAM_DFLT] : null;
491 $multi = isset ($paramSettings[self :: PARAM_ISMULTI]) ? $paramSettings[self :: PARAM_ISMULTI] : false;
492 $type = isset ($paramSettings[self :: PARAM_TYPE]) ? $paramSettings[self :: PARAM_TYPE] : null;
493 $dupes = isset ($paramSettings[self:: PARAM_ALLOW_DUPLICATES]) ? $paramSettings[self :: PARAM_ALLOW_DUPLICATES] : false;
494
495 // When type is not given, and no choices, the type is the same as $default
496 if (!isset ($type)) {
497 if (isset ($default))
498 $type = gettype($default);
499 else
500 $type = 'NULL'; // allow everything
501 }
502 }
503
504 if ($type == 'boolean') {
505 if (isset ($default) && $default !== false) {
506 // Having a default value of anything other than 'false' is pointless
507 ApiBase :: dieDebug(__METHOD__, "Boolean param $encParamName's default is set to '$default'");
508 }
509
510 $value = $this->getMain()->getRequest()->getCheck($encParamName);
511 } else {
512 $value = $this->getMain()->getRequest()->getVal($encParamName, $default);
513
514 if (isset ($value) && $type == 'namespace')
515 $type = ApiBase :: getValidNamespaces();
516 }
517
518 if (isset ($value) && ($multi || is_array($type)))
519 $value = $this->parseMultiValue($encParamName, $value, $multi, is_array($type) ? $type : null);
520
521 // More validation only when choices were not given
522 // choices were validated in parseMultiValue()
523 if (isset ($value)) {
524 if (!is_array($type)) {
525 switch ($type) {
526 case 'NULL' : // nothing to do
527 break;
528 case 'string' : // nothing to do
529 break;
530 case 'integer' : // Force everything using intval() and optionally validate limits
531
532 $value = is_array($value) ? array_map('intval', $value) : intval($value);
533 $min = isset ($paramSettings[self :: PARAM_MIN]) ? $paramSettings[self :: PARAM_MIN] : null;
534 $max = isset ($paramSettings[self :: PARAM_MAX]) ? $paramSettings[self :: PARAM_MAX] : null;
535
536 if (!is_null($min) || !is_null($max)) {
537 $values = is_array($value) ? $value : array($value);
538 foreach ($values as $v) {
539 $this->validateLimit($paramName, $v, $min, $max);
540 }
541 }
542 break;
543 case 'limit' :
544 if (!isset ($paramSettings[self :: PARAM_MAX]) || !isset ($paramSettings[self :: PARAM_MAX2]))
545 ApiBase :: dieDebug(__METHOD__, "MAX1 or MAX2 are not defined for the limit $encParamName");
546 if ($multi)
547 ApiBase :: dieDebug(__METHOD__, "Multi-values not supported for $encParamName");
548 $min = isset ($paramSettings[self :: PARAM_MIN]) ? $paramSettings[self :: PARAM_MIN] : 0;
549 if( $value == 'max' ) {
550 if( $parseMaxLimit ) {
551 $value = $this->getMain()->canApiHighLimits() ? $paramSettings[self :: PARAM_MAX2] : $paramSettings[self :: PARAM_MAX];
552 $this->getResult()->addValue( 'limits', $this->getModuleName(), $value );
553 $this->validateLimit($paramName, $value, $min, $paramSettings[self :: PARAM_MAX], $paramSettings[self :: PARAM_MAX2]);
554 }
555 }
556 else {
557 $value = intval($value);
558 $this->validateLimit($paramName, $value, $min, $paramSettings[self :: PARAM_MAX], $paramSettings[self :: PARAM_MAX2]);
559 }
560 break;
561 case 'boolean' :
562 if ($multi)
563 ApiBase :: dieDebug(__METHOD__, "Multi-values not supported for $encParamName");
564 break;
565 case 'timestamp' :
566 if ($multi)
567 ApiBase :: dieDebug(__METHOD__, "Multi-values not supported for $encParamName");
568 $value = wfTimestamp(TS_UNIX, $value);
569 if ($value === 0)
570 $this->dieUsage("Invalid value '$value' for timestamp parameter $encParamName", "badtimestamp_{$encParamName}");
571 $value = wfTimestamp(TS_MW, $value);
572 break;
573 case 'user' :
574 $title = Title::makeTitleSafe( NS_USER, $value );
575 if ( is_null( $title ) )
576 $this->dieUsage("Invalid value for user parameter $encParamName", "baduser_{$encParamName}");
577 $value = $title->getText();
578 break;
579 default :
580 ApiBase :: dieDebug(__METHOD__, "Param $encParamName's type is unknown - $type");
581 }
582 }
583
584 // Throw out duplicates if requested
585 if (is_array($value) && !$dupes)
586 $value = array_unique($value);
587 }
588
589 return $value;
590 }
591
592 /**
593 * Return an array of values that were given in a 'a|b|c' notation,
594 * after it optionally validates them against the list allowed values.
595 *
596 * @param $valueName string The name of the parameter (for error
597 * reporting)
598 * @param $value mixed The value being parsed
599 * @param $allowMultiple bool Can $value contain more than one value
600 * separated by '|'?
601 * @param $allowedValues mixed An array of values to check against. If
602 * null, all values are accepted.
603 * @return mixed (allowMultiple ? an_array_of_values : a_single_value)
604 */
605 protected function parseMultiValue($valueName, $value, $allowMultiple, $allowedValues) {
606 if( trim($value) === "" )
607 return array();
608 $sizeLimit = $this->mMainModule->canApiHighLimits() ? self::LIMIT_SML2 : self::LIMIT_SML1;
609 $valuesList = explode('|', $value, $sizeLimit + 1);
610 if( self::truncateArray($valuesList, $sizeLimit) ) {
611 $this->setWarning("Too many values supplied for parameter '$valueName': the limit is $sizeLimit");
612 }
613 if (!$allowMultiple && count($valuesList) != 1) {
614 $possibleValues = is_array($allowedValues) ? "of '" . implode("', '", $allowedValues) . "'" : '';
615 $this->dieUsage("Only one $possibleValues is allowed for parameter '$valueName'", "multival_$valueName");
616 }
617 if (is_array($allowedValues)) {
618 # Check for unknown values
619 $unknown = array_diff($valuesList, $allowedValues);
620 if(count($unknown))
621 {
622 if($allowMultiple)
623 {
624 $s = count($unknown) > 1 ? "s" : "";
625 $vals = implode(", ", $unknown);
626 $this->setWarning("Unrecognized value$s for parameter '$valueName': $vals");
627 }
628 else
629 $this->dieUsage("Unrecognized value for parameter '$valueName': {$valuesList[0]}", "unknown_$valueName");
630 }
631 # Now throw them out
632 $valuesList = array_intersect($valuesList, $allowedValues);
633 }
634
635 return $allowMultiple ? $valuesList : $valuesList[0];
636 }
637
638 /**
639 * Validate the value against the minimum and user/bot maximum limits.
640 * Prints usage info on failure.
641 * @param $paramName string Parameter name
642 * @param $value int Parameter value
643 * @param $min int Minimum value
644 * @param $max int Maximum value for users
645 * @param $botMax int Maximum value for sysops/bots
646 */
647 function validateLimit($paramName, $value, $min, $max, $botMax = null) {
648 if (!is_null($min) && $value < $min) {
649 $this->dieUsage($this->encodeParamName($paramName) . " may not be less than $min (set to $value)", $paramName);
650 }
651
652 // Minimum is always validated, whereas maximum is checked only if not running in internal call mode
653 if ($this->getMain()->isInternalMode())
654 return;
655
656 // Optimization: do not check user's bot status unless really needed -- skips db query
657 // assumes $botMax >= $max
658 if (!is_null($max) && $value > $max) {
659 if (!is_null($botMax) && $this->getMain()->canApiHighLimits()) {
660 if ($value > $botMax) {
661 $this->dieUsage($this->encodeParamName($paramName) . " may not be over $botMax (set to $value) for bots or sysops", $paramName);
662 }
663 } else {
664 $this->dieUsage($this->encodeParamName($paramName) . " may not be over $max (set to $value) for users", $paramName);
665 }
666 }
667 }
668
669 /**
670 * Truncate an array to a certain length.
671 * @param $arr array Array to truncate
672 * @param $limit int Maximum length
673 * @return bool True if the array was truncated, false otherwise
674 */
675 public static function truncateArray(&$arr, $limit)
676 {
677 $modified = false;
678 while(count($arr) > $limit)
679 {
680 $junk = array_pop($arr);
681 $modified = true;
682 }
683 return $modified;
684 }
685
686 /**
687 * Call the main module's error handler
688 * @param $description string Error text
689 * @param $errorCode string Error code
690 * @param $httpRespCode int HTTP response code
691 */
692 public function dieUsage($description, $errorCode, $httpRespCode = 0) {
693 wfProfileClose();
694 throw new UsageException($description, $this->encodeParamName($errorCode), $httpRespCode);
695 }
696
697 /**
698 * Array that maps message keys to error messages. $1 and friends are replaced.
699 */
700 public static $messageMap = array(
701 // This one MUST be present, or dieUsageMsg() will recurse infinitely
702 'unknownerror' => array('code' => 'unknownerror', 'info' => "Unknown error: ``\$1''"),
703 'unknownerror-nocode' => array('code' => 'unknownerror', 'info' => 'Unknown error'),
704
705 // Messages from Title::getUserPermissionsErrors()
706 'ns-specialprotected' => array('code' => 'unsupportednamespace', 'info' => "Pages in the Special namespace can't be edited"),
707 'protectedinterface' => array('code' => 'protectednamespace-interface', 'info' => "You're not allowed to edit interface messages"),
708 'namespaceprotected' => array('code' => 'protectednamespace', 'info' => "You're not allowed to edit pages in the ``\$1'' namespace"),
709 'customcssjsprotected' => array('code' => 'customcssjsprotected', 'info' => "You're not allowed to edit custom CSS and JavaScript pages"),
710 'cascadeprotected' => array('code' => 'cascadeprotected', 'info' =>"The page you're trying to edit is protected because it's included in a cascade-protected page"),
711 'protectedpagetext' => array('code' => 'protectedpage', 'info' => "The ``\$1'' right is required to edit this page"),
712 'protect-cantedit' => array('code' => 'cantedit', 'info' => "You can't protect this page because you can't edit it"),
713 'badaccess-group0' => array('code' => 'permissiondenied', 'info' => "Permission denied"), // Generic permission denied message
714 'badaccess-groups' => array('code' => 'permissiondenied', 'info' => "Permission denied"),
715 'titleprotected' => array('code' => 'protectedtitle', 'info' => "This title has been protected from creation"),
716 'nocreate-loggedin' => array('code' => 'cantcreate', 'info' => "You don't have permission to create new pages"),
717 'nocreatetext' => array('code' => 'cantcreate-anon', 'info' => "Anonymous users can't create new pages"),
718 'movenologintext' => array('code' => 'cantmove-anon', 'info' => "Anonymous users can't move pages"),
719 'movenotallowed' => array('code' => 'cantmove', 'info' => "You don't have permission to move pages"),
720 'confirmedittext' => array('code' => 'confirmemail', 'info' => "You must confirm your e-mail address before you can edit"),
721 'blockedtext' => array('code' => 'blocked', 'info' => "You have been blocked from editing"),
722 'autoblockedtext' => array('code' => 'autoblocked', 'info' => "Your IP address has been blocked automatically, because it was used by a blocked user"),
723
724 // Miscellaneous interface messages
725 'actionthrottledtext' => array('code' => 'ratelimited', 'info' => "You've exceeded your rate limit. Please wait some time and try again"),
726 'alreadyrolled' => array('code' => 'alreadyrolled', 'info' => "The page you tried to rollback was already rolled back"),
727 'cantrollback' => array('code' => 'onlyauthor', 'info' => "The page you tried to rollback only has one author"),
728 'readonlytext' => array('code' => 'readonly', 'info' => "The wiki is currently in read-only mode"),
729 'sessionfailure' => array('code' => 'badtoken', 'info' => "Invalid token"),
730 'cannotdelete' => array('code' => 'cantdelete', 'info' => "Couldn't delete ``\$1''. Maybe it was deleted already by someone else"),
731 'notanarticle' => array('code' => 'missingtitle', 'info' => "The page you requested doesn't exist"),
732 'selfmove' => array('code' => 'selfmove', 'info' => "Can't move a page to itself"),
733 'immobile_namespace' => array('code' => 'immobilenamespace', 'info' => "You tried to move pages from or to a namespace that is protected from moving"),
734 'articleexists' => array('code' => 'articleexists', 'info' => "The destination article already exists and is not a redirect to the source article"),
735 'protectedpage' => array('code' => 'protectedpage', 'info' => "You don't have permission to perform this move"),
736 'hookaborted' => array('code' => 'hookaborted', 'info' => "The modification you tried to make was aborted by an extension hook"),
737 'cantmove-titleprotected' => array('code' => 'protectedtitle', 'info' => "The destination article has been protected from creation"),
738 'imagenocrossnamespace' => array('code' => 'nonfilenamespace', 'info' => "Can't move a file to a non-file namespace"),
739 'imagetypemismatch' => array('code' => 'filetypemismatch', 'info' => "The new file extension doesn't match its type"),
740 // 'badarticleerror' => shouldn't happen
741 // 'badtitletext' => shouldn't happen
742 'ip_range_invalid' => array('code' => 'invalidrange', 'info' => "Invalid IP range"),
743 'range_block_disabled' => array('code' => 'rangedisabled', 'info' => "Blocking IP ranges has been disabled"),
744 'nosuchusershort' => array('code' => 'nosuchuser', 'info' => "The user you specified doesn't exist"),
745 'badipaddress' => array('code' => 'invalidip', 'info' => "Invalid IP address specified"),
746 'ipb_expiry_invalid' => array('code' => 'invalidexpiry', 'info' => "Invalid expiry time"),
747 'ipb_already_blocked' => array('code' => 'alreadyblocked', 'info' => "The user you tried to block was already blocked"),
748 '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."),
749 'ipb_cant_unblock' => array('code' => 'cantunblock', 'info' => "The block you specified was not found. It may have been unblocked already"),
750 '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"),
751 'usermaildisabled' => array('code' => 'usermaildisabled', 'info' => "User email has been disabled"),
752 'blockedemailuser' => array('code' => 'blockedfrommail', 'info' => "You have been blocked from sending e-mail"),
753 'notarget' => array('code' => 'notarget', 'info' => "You have not specified a valid target for this action"),
754 '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"),
755 'rcpatroldisabled' => array('code' => 'patroldisabled', 'info' => "Patrolling is disabled on this wiki"),
756 'markedaspatrollederror-noautopatrol' => array('code' => 'noautopatrol', 'info' => "You don't have permission to patrol your own changes"),
757 'delete-toobig' => array('code' => 'bigdelete', 'info' => "You can't delete this page because it has more than \$1 revisions"),
758 'movenotallowedfile' => array('code' => 'cantmovefile', 'info' => "You don't have permission to move files"),
759
760 // API-specific messages
761 'missingparam' => array('code' => 'no$1', 'info' => "The \$1 parameter must be set"),
762 'invalidtitle' => array('code' => 'invalidtitle', 'info' => "Bad title ``\$1''"),
763 'nosuchpageid' => array('code' => 'nosuchpageid', 'info' => "There is no page with ID \$1"),
764 'nosuchrevid' => array('code' => 'nosuchrevid', 'info' => "There is no revision with ID \$1"),
765 'invaliduser' => array('code' => 'invaliduser', 'info' => "Invalid username ``\$1''"),
766 'invalidexpiry' => array('code' => 'invalidexpiry', 'info' => "Invalid expiry time ``\$1''"),
767 'pastexpiry' => array('code' => 'pastexpiry', 'info' => "Expiry time ``\$1'' is in the past"),
768 'create-titleexists' => array('code' => 'create-titleexists', 'info' => "Existing titles can't be protected with 'create'"),
769 'missingtitle-createonly' => array('code' => 'missingtitle-createonly', 'info' => "Missing titles can only be protected with 'create'"),
770 'cantblock' => array('code' => 'cantblock', 'info' => "You don't have permission to block users"),
771 'canthide' => array('code' => 'canthide', 'info' => "You don't have permission to hide user names from the block log"),
772 'cantblock-email' => array('code' => 'cantblock-email', 'info' => "You don't have permission to block users from sending e-mail through the wiki"),
773 'unblock-notarget' => array('code' => 'notarget', 'info' => "Either the id or the user parameter must be set"),
774 'unblock-idanduser' => array('code' => 'idanduser', 'info' => "The id and user parameters can't be used together"),
775 'cantunblock' => array('code' => 'permissiondenied', 'info' => "You don't have permission to unblock users"),
776 'cannotundelete' => array('code' => 'cantundelete', 'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already"),
777 'permdenied-undelete' => array('code' => 'permissiondenied', 'info' => "You don't have permission to restore deleted revisions"),
778 'createonly-exists' => array('code' => 'articleexists', 'info' => "The article you tried to create has been created already"),
779 'nocreate-missing' => array('code' => 'missingtitle', 'info' => "The article you tried to edit doesn't exist"),
780 'nosuchrcid' => array('code' => 'nosuchrcid', 'info' => "There is no change with rcid ``\$1''"),
781 'cantpurge' => array('code' => 'cantpurge', 'info' => "Only users with the 'purge' right can purge pages via the API"),
782 'protect-invalidaction' => array('code' => 'protect-invalidaction', 'info' => "Invalid protection type ``\$1''"),
783 'protect-invalidlevel' => array('code' => 'protect-invalidlevel', 'info' => "Invalid protection level ``\$1''"),
784 'toofewexpiries' => array('code' => 'toofewexpiries', 'info' => "\$1 expiry timestamps were provided where \$2 were needed"),
785 'cantimport' => array('code' => 'cantimport', 'info' => "You don't have permission to import pages"),
786 'cantimport-upload' => array('code' => 'cantimport-upload', 'info' => "You don't have permission to import uploaded pages"),
787 'importnofile' => array('code' => 'nofile', 'info' => "You didn't upload a file"),
788 'importuploaderrorsize' => array('code' => 'filetoobig', 'info' => 'The file you uploaded is bigger than the maximum upload size'),
789 'importuploaderrorpartial' => array('code' => 'partialupload', 'info' => 'The file was only partially uploaded'),
790 'importuploaderrortemp' => array('code' => 'notempdir', 'info' => 'The temporary upload directory is missing'),
791 'importcantopen' => array('code' => 'cantopenfile', 'info' => "Couldn't open the uploaded file"),
792 'import-noarticle' => array('code' => 'badinterwiki', 'info' => 'Invalid interwiki title specified'),
793 'importbadinterwiki' => array('code' => 'badinterwiki', 'info' => 'Invalid interwiki title specified'),
794 'import-unknownerror' => array('code' => 'import-unknownerror', 'info' => "Unknown error on import: ``\$1''"),
795
796 // ApiEditPage messages
797 'noimageredirect-anon' => array('code' => 'noimageredirect-anon', 'info' => "Anonymous users can't create image redirects"),
798 'noimageredirect-logged' => array('code' => 'noimageredirect', 'info' => "You don't have permission to create image redirects"),
799 'spamdetected' => array('code' => 'spamdetected', 'info' => "Your edit was refused because it contained a spam fragment: ``\$1''"),
800 'filtered' => array('code' => 'filtered', 'info' => "The filter callback function refused your edit"),
801 'contenttoobig' => array('code' => 'contenttoobig', 'info' => "The content you supplied exceeds the article size limit of \$1 bytes"),
802 'noedit-anon' => array('code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages"),
803 'noedit' => array('code' => 'noedit', 'info' => "You don't have permission to edit pages"),
804 'wasdeleted' => array('code' => 'pagedeleted', 'info' => "The page has been deleted since you fetched its timestamp"),
805 'blankpage' => array('code' => 'emptypage', 'info' => "Creating new, empty pages is not allowed"),
806 'editconflict' => array('code' => 'editconflict', 'info' => "Edit conflict detected"),
807 'hashcheckfailed' => array('code' => 'badmd5', 'info' => "The supplied MD5 hash was incorrect"),
808 'missingtext' => array('code' => 'notext', 'info' => "One of the text, appendtext, prependtext and undo parameters must be set"),
809 'emptynewsection' => array('code' => 'emptynewsection', 'info' => 'Creating empty new sections is not possible.'),
810 'revwrongpage' => array('code' => 'revwrongpage', 'info' => "r\$1 is not a revision of ``\$2''"),
811 'undo-failure' => array('code' => 'undofailure', 'info' => 'Undo failed due to conflicting intermediate edits'),
812 );
813
814 /**
815 * Output the error message related to a certain array
816 * @param $error array Element of a getUserPermissionsErrors()-style array
817 */
818 public function dieUsageMsg($error) {
819 $parsed = $this->parseMsg($error);
820 $this->dieUsage($parsed['code'], $parsed['info']);
821 }
822
823 /**
824 * Return the error message related to a certain array
825 * @param $error array Element of a getUserPermissionsErrors()-style array
826 * @return array('code' => code, 'info' => info)
827 */
828 public function parseMsg($error) {
829 $key = array_shift($error);
830 if(isset(self::$messageMap[$key]))
831 return array( 'code' =>
832 wfMsgReplaceArgs(self::$messageMap[$key]['code'], $error),
833 'info' =>
834 wfMsgReplaceArgs(self::$messageMap[$key]['info'], $error)
835 );
836 // If the key isn't present, throw an "unknown error"
837 return $this->parseMsg(array('unknownerror', $key));
838 }
839
840 /**
841 * Internal code errors should be reported with this method
842 * @param $method string Method or function name
843 * @param $message string Error message
844 */
845 protected static function dieDebug($method, $message) {
846 wfDebugDieBacktrace("Internal error in $method: $message");
847 }
848
849 /**
850 * Indicates if this module needs maxlag to be checked
851 * @return bool
852 */
853 public function shouldCheckMaxlag() {
854 return true;
855 }
856
857 /**
858 * Indicates if this module requires edit mode
859 * @return bool
860 */
861 public function isEditMode() {
862 return false;
863 }
864
865 /**
866 * Indicates whether this module must be called with a POST request
867 * @return bool
868 */
869 public function mustBePosted() {
870 return false;
871 }
872
873
874 /**
875 * Profiling: total module execution time
876 */
877 private $mTimeIn = 0, $mModuleTime = 0;
878
879 /**
880 * Start module profiling
881 */
882 public function profileIn() {
883 if ($this->mTimeIn !== 0)
884 ApiBase :: dieDebug(__METHOD__, 'called twice without calling profileOut()');
885 $this->mTimeIn = microtime(true);
886 wfProfileIn($this->getModuleProfileName());
887 }
888
889 /**
890 * End module profiling
891 */
892 public function profileOut() {
893 if ($this->mTimeIn === 0)
894 ApiBase :: dieDebug(__METHOD__, 'called without calling profileIn() first');
895 if ($this->mDBTimeIn !== 0)
896 ApiBase :: dieDebug(__METHOD__, 'must be called after database profiling is done with profileDBOut()');
897
898 $this->mModuleTime += microtime(true) - $this->mTimeIn;
899 $this->mTimeIn = 0;
900 wfProfileOut($this->getModuleProfileName());
901 }
902
903 /**
904 * When modules crash, sometimes it is needed to do a profileOut() regardless
905 * of the profiling state the module was in. This method does such cleanup.
906 */
907 public function safeProfileOut() {
908 if ($this->mTimeIn !== 0) {
909 if ($this->mDBTimeIn !== 0)
910 $this->profileDBOut();
911 $this->profileOut();
912 }
913 }
914
915 /**
916 * Total time the module was executed
917 * @return float
918 */
919 public function getProfileTime() {
920 if ($this->mTimeIn !== 0)
921 ApiBase :: dieDebug(__METHOD__, 'called without calling profileOut() first');
922 return $this->mModuleTime;
923 }
924
925 /**
926 * Profiling: database execution time
927 */
928 private $mDBTimeIn = 0, $mDBTime = 0;
929
930 /**
931 * Start module profiling
932 */
933 public function profileDBIn() {
934 if ($this->mTimeIn === 0)
935 ApiBase :: dieDebug(__METHOD__, 'must be called while profiling the entire module with profileIn()');
936 if ($this->mDBTimeIn !== 0)
937 ApiBase :: dieDebug(__METHOD__, 'called twice without calling profileDBOut()');
938 $this->mDBTimeIn = microtime(true);
939 wfProfileIn($this->getModuleProfileName(true));
940 }
941
942 /**
943 * End database profiling
944 */
945 public function profileDBOut() {
946 if ($this->mTimeIn === 0)
947 ApiBase :: dieDebug(__METHOD__, 'must be called while profiling the entire module with profileIn()');
948 if ($this->mDBTimeIn === 0)
949 ApiBase :: dieDebug(__METHOD__, 'called without calling profileDBIn() first');
950
951 $time = microtime(true) - $this->mDBTimeIn;
952 $this->mDBTimeIn = 0;
953
954 $this->mDBTime += $time;
955 $this->getMain()->mDBTime += $time;
956 wfProfileOut($this->getModuleProfileName(true));
957 }
958
959 /**
960 * Total time the module used the database
961 * @return float
962 */
963 public function getProfileDBTime() {
964 if ($this->mDBTimeIn !== 0)
965 ApiBase :: dieDebug(__METHOD__, 'called without calling profileDBOut() first');
966 return $this->mDBTime;
967 }
968
969 /**
970 * Debugging function that prints a value and an optional backtrace
971 * @param $value mixed Value to print
972 * @param $name string Description of the printed value
973 * @param $backtrace bool If true, print a backtrace
974 */
975 public static function debugPrint($value, $name = 'unknown', $backtrace = false) {
976 print "\n\n<pre><b>Debugging value '$name':</b>\n\n";
977 var_export($value);
978 if ($backtrace)
979 print "\n" . wfBacktrace();
980 print "\n</pre>\n";
981 }
982
983
984 /**
985 * Returns a string that identifies the version of this class.
986 * @return string
987 */
988 public static function getBaseVersion() {
989 return __CLASS__ . ': $Id$';
990 }
991 }