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