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