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