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