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