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