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