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