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