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