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