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