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