Merge "Installer: output css correctly when session errors occur"
[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 // These constants allow modules to specify exactly how to treat incoming parameters.
44
45 // Default value of the parameter
46 const PARAM_DFLT = 0;
47 // Boolean, do we accept more than one item for this parameter (e.g.: titles)?
48 const PARAM_ISMULTI = 1;
49 // Can be either a string type (e.g.: 'integer') or an array of allowed values
50 const PARAM_TYPE = 2;
51 // Max value allowed for a parameter. Only applies if TYPE='integer'
52 const PARAM_MAX = 3;
53 // Max value allowed for a parameter for bots and sysops. Only applies if TYPE='integer'
54 const PARAM_MAX2 = 4;
55 // Lowest value allowed for a parameter. Only applies if TYPE='integer'
56 const PARAM_MIN = 5;
57 // Boolean, do we allow the same value to be set more than once when ISMULTI=true
58 const PARAM_ALLOW_DUPLICATES = 6;
59 // Boolean, is the parameter deprecated (will show a warning)
60 const PARAM_DEPRECATED = 7;
61 /// @since 1.17
62 const PARAM_REQUIRED = 8; // Boolean, is the parameter required?
63 /// @since 1.17
64 // Boolean, if MIN/MAX are set, enforce (die) these?
65 // Only applies if TYPE='integer' Use with extreme caution
66 const PARAM_RANGE_ENFORCE = 9;
67
68 // Name of property group that is on the root element of the result,
69 // i.e. not part of a list
70 const PROP_ROOT = 'ROOT';
71 // Boolean, is the result multiple items? Defaults to true for query modules,
72 // to false for other modules
73 const PROP_LIST = 'LIST';
74 const PROP_TYPE = 0; // Type of the property, uses same format as PARAM_TYPE
75 // Boolean, can the property be not included in the result? Defaults to false
76 const PROP_NULLABLE = 1;
77
78 const LIMIT_BIG1 = 500; // Fast query, std user limit
79 const LIMIT_BIG2 = 5000; // Fast query, bot/sysop limit
80 const LIMIT_SML1 = 50; // Slow query, std user limit
81 const LIMIT_SML2 = 500; // Slow query, bot/sysop limit
82
83 /**
84 * getAllowedParams() flag: When set, the result could take longer to generate,
85 * but should be more thorough. E.g. get the list of generators for ApiSandBox extension
86 * @since 1.21
87 */
88 const GET_VALUES_FOR_HELP = 1;
89
90 private $mMainModule, $mModuleName, $mModulePrefix;
91 private $mSlaveDB = null;
92 private $mParamCache = array();
93
94 /**
95 * Constructor
96 * @param ApiMain $mainModule
97 * @param string $moduleName Name of this module
98 * @param string $modulePrefix Prefix to use for parameter names
99 */
100 public function __construct( $mainModule, $moduleName, $modulePrefix = '' ) {
101 $this->mMainModule = $mainModule;
102 $this->mModuleName = $moduleName;
103 $this->mModulePrefix = $modulePrefix;
104
105 if ( !$this->isMain() ) {
106 $this->setContext( $mainModule->getContext() );
107 }
108 }
109
110 /*****************************************************************************
111 * ABSTRACT METHODS *
112 *****************************************************************************/
113
114 /**
115 * Evaluates the parameters, performs the requested query, and sets up
116 * the result. Concrete implementations of ApiBase must override this
117 * method to provide whatever functionality their module offers.
118 * Implementations must not produce any output on their own and are not
119 * expected to handle any errors.
120 *
121 * The execute() method will be invoked directly by ApiMain immediately
122 * before the result of the module is output. Aside from the
123 * constructor, implementations should assume that no other methods
124 * will be called externally on the module before the result is
125 * processed.
126 *
127 * The result data should be stored in the ApiResult object available
128 * through getResult().
129 */
130 abstract public function execute();
131
132 /**
133 * Returns a string that identifies the version of the extending class.
134 * Typically includes the class name, the svn revision, timestamp, and
135 * last author. Usually done with SVN's Id keyword
136 * @return string
137 * @deprecated since 1.21, version string is no longer supported
138 */
139 public function getVersion() {
140 wfDeprecated( __METHOD__, '1.21' );
141
142 return '';
143 }
144
145 /**
146 * Get the name of the module being executed by this instance
147 * @return string
148 */
149 public function getModuleName() {
150 return $this->mModuleName;
151 }
152
153 /**
154 * Get the module manager, or null if this module has no sub-modules
155 * @since 1.21
156 * @return ApiModuleManager
157 */
158 public function getModuleManager() {
159 return null;
160 }
161
162 /**
163 * Get parameter prefix (usually two letters or an empty string).
164 * @return string
165 */
166 public function getModulePrefix() {
167 return $this->mModulePrefix;
168 }
169
170 /**
171 * Get the name of the module as shown in the profiler log
172 *
173 * @param DatabaseBase|bool $db
174 *
175 * @return string
176 */
177 public function getModuleProfileName( $db = false ) {
178 if ( $db ) {
179 return 'API:' . $this->mModuleName . '-DB';
180 }
181
182 return 'API:' . $this->mModuleName;
183 }
184
185 /**
186 * Get the main module
187 * @return ApiMain
188 */
189 public function getMain() {
190 return $this->mMainModule;
191 }
192
193 /**
194 * Returns true if this module is the main module ($this === $this->mMainModule),
195 * false otherwise.
196 * @return bool
197 */
198 public function isMain() {
199 return $this === $this->mMainModule;
200 }
201
202 /**
203 * Get the result object
204 * @return ApiResult
205 */
206 public function getResult() {
207 // Main module has getResult() method overridden
208 // Safety - avoid infinite loop:
209 if ( $this->isMain() ) {
210 ApiBase::dieDebug( __METHOD__, 'base method was called on main module. ' );
211 }
212
213 return $this->getMain()->getResult();
214 }
215
216 /**
217 * Get the result data array (read-only)
218 * @return array
219 */
220 public function getResultData() {
221 return $this->getResult()->getData();
222 }
223
224 /**
225 * Create a new RequestContext object to use e.g. for calls to other parts
226 * the software.
227 * The object will have the WebRequest and the User object set to the ones
228 * used in this instance.
229 *
230 * @deprecated since 1.19 use getContext to get the current context
231 * @return DerivativeContext
232 */
233 public function createContext() {
234 wfDeprecated( __METHOD__, '1.19' );
235
236 return new DerivativeContext( $this->getContext() );
237 }
238
239 /**
240 * Set warning section for this module. Users should monitor this
241 * section to notice any changes in API. Multiple calls to this
242 * function will result in the warning messages being separated by
243 * newlines
244 * @param string $warning Warning message
245 */
246 public function setWarning( $warning ) {
247 $result = $this->getResult();
248 $data = $result->getData();
249 $moduleName = $this->getModuleName();
250 if ( isset( $data['warnings'][$moduleName] ) ) {
251 // Don't add duplicate warnings
252 $oldWarning = $data['warnings'][$moduleName]['*'];
253 $warnPos = strpos( $oldWarning, $warning );
254 // If $warning was found in $oldWarning, check if it starts at 0 or after "\n"
255 if ( $warnPos !== false && ( $warnPos === 0 || $oldWarning[$warnPos - 1] === "\n" ) ) {
256 // Check if $warning is followed by "\n" or the end of the $oldWarning
257 $warnPos += strlen( $warning );
258 if ( strlen( $oldWarning ) <= $warnPos || $oldWarning[$warnPos] === "\n" ) {
259 return;
260 }
261 }
262 // If there is a warning already, append it to the existing one
263 $warning = "$oldWarning\n$warning";
264 }
265 $msg = array();
266 ApiResult::setContent( $msg, $warning );
267 $result->disableSizeCheck();
268 $result->addValue( 'warnings', $moduleName,
269 $msg, ApiResult::OVERRIDE | ApiResult::ADD_ON_TOP );
270 $result->enableSizeCheck();
271 }
272
273 /**
274 * If the module may only be used with a certain format module,
275 * it should override this method to return an instance of that formatter.
276 * A value of null means the default format will be used.
277 * @return mixed Instance of a derived class of ApiFormatBase, or null
278 */
279 public function getCustomPrinter() {
280 return null;
281 }
282
283 /**
284 * Generates help message for this module, or false if there is no description
285 * @return string|bool
286 */
287 public function makeHelpMsg() {
288 static $lnPrfx = "\n ";
289
290 $msg = $this->getFinalDescription();
291
292 if ( $msg !== false ) {
293
294 if ( !is_array( $msg ) ) {
295 $msg = array(
296 $msg
297 );
298 }
299 $msg = $lnPrfx . implode( $lnPrfx, $msg ) . "\n";
300
301 $msg .= $this->makeHelpArrayToString( $lnPrfx, false, $this->getHelpUrls() );
302
303 if ( $this->isReadMode() ) {
304 $msg .= "\nThis module requires read rights";
305 }
306 if ( $this->isWriteMode() ) {
307 $msg .= "\nThis module requires write rights";
308 }
309 if ( $this->mustBePosted() ) {
310 $msg .= "\nThis module only accepts POST requests";
311 }
312 if ( $this->isReadMode() || $this->isWriteMode() ||
313 $this->mustBePosted()
314 ) {
315 $msg .= "\n";
316 }
317
318 // Parameters
319 $paramsMsg = $this->makeHelpMsgParameters();
320 if ( $paramsMsg !== false ) {
321 $msg .= "Parameters:\n$paramsMsg";
322 }
323
324 $examples = $this->getExamples();
325 if ( $examples ) {
326 if ( !is_array( $examples ) ) {
327 $examples = array(
328 $examples
329 );
330 }
331 $msg .= "Example" . ( count( $examples ) > 1 ? 's' : '' ) . ":\n";
332 foreach ( $examples as $k => $v ) {
333 if ( is_numeric( $k ) ) {
334 $msg .= " $v\n";
335 } else {
336 if ( is_array( $v ) ) {
337 $msgExample = implode( "\n", array_map( array( $this, 'indentExampleText' ), $v ) );
338 } else {
339 $msgExample = " $v";
340 }
341 $msgExample .= ":";
342 $msg .= wordwrap( $msgExample, 100, "\n" ) . "\n $k\n";
343 }
344 }
345 }
346 }
347
348 return $msg;
349 }
350
351 /**
352 * @param string $item
353 * @return string
354 */
355 private function indentExampleText( $item ) {
356 return " " . $item;
357 }
358
359 /**
360 * @param string $prefix Text to split output items
361 * @param string $title What is being output
362 * @param string|array $input
363 * @return string
364 */
365 protected function makeHelpArrayToString( $prefix, $title, $input ) {
366 if ( $input === false ) {
367 return '';
368 }
369 if ( !is_array( $input ) ) {
370 $input = array( $input );
371 }
372
373 if ( count( $input ) > 0 ) {
374 if ( $title ) {
375 $msg = $title . ( count( $input ) > 1 ? 's' : '' ) . ":\n ";
376 } else {
377 $msg = ' ';
378 }
379 $msg .= implode( $prefix, $input ) . "\n";
380
381 return $msg;
382 }
383
384 return '';
385 }
386
387 /**
388 * Generates the parameter descriptions for this module, to be displayed in the
389 * module's help.
390 * @return string|bool
391 */
392 public function makeHelpMsgParameters() {
393 $params = $this->getFinalParams( ApiBase::GET_VALUES_FOR_HELP );
394 if ( $params ) {
395
396 $paramsDescription = $this->getFinalParamDescription();
397 $msg = '';
398 $paramPrefix = "\n" . str_repeat( ' ', 24 );
399 $descWordwrap = "\n" . str_repeat( ' ', 28 );
400 foreach ( $params as $paramName => $paramSettings ) {
401 $desc = isset( $paramsDescription[$paramName] ) ? $paramsDescription[$paramName] : '';
402 if ( is_array( $desc ) ) {
403 $desc = implode( $paramPrefix, $desc );
404 }
405
406 //handle shorthand
407 if ( !is_array( $paramSettings ) ) {
408 $paramSettings = array(
409 self::PARAM_DFLT => $paramSettings,
410 );
411 }
412
413 //handle missing type
414 if ( !isset( $paramSettings[ApiBase::PARAM_TYPE] ) ) {
415 $dflt = isset( $paramSettings[ApiBase::PARAM_DFLT] )
416 ? $paramSettings[ApiBase::PARAM_DFLT]
417 : null;
418 if ( is_bool( $dflt ) ) {
419 $paramSettings[ApiBase::PARAM_TYPE] = 'boolean';
420 } elseif ( is_string( $dflt ) || is_null( $dflt ) ) {
421 $paramSettings[ApiBase::PARAM_TYPE] = 'string';
422 } elseif ( is_int( $dflt ) ) {
423 $paramSettings[ApiBase::PARAM_TYPE] = 'integer';
424 }
425 }
426
427 if ( isset( $paramSettings[self::PARAM_DEPRECATED] )
428 && $paramSettings[self::PARAM_DEPRECATED]
429 ) {
430 $desc = "DEPRECATED! $desc";
431 }
432
433 if ( isset( $paramSettings[self::PARAM_REQUIRED] )
434 && $paramSettings[self::PARAM_REQUIRED]
435 ) {
436 $desc .= $paramPrefix . "This parameter is required";
437 }
438
439 $type = isset( $paramSettings[self::PARAM_TYPE] )
440 ? $paramSettings[self::PARAM_TYPE]
441 : null;
442 if ( isset( $type ) ) {
443 $hintPipeSeparated = true;
444 $multi = isset( $paramSettings[self::PARAM_ISMULTI] )
445 ? $paramSettings[self::PARAM_ISMULTI]
446 : false;
447 if ( $multi ) {
448 $prompt = 'Values (separate with \'|\'): ';
449 } else {
450 $prompt = 'One value: ';
451 }
452
453 if ( is_array( $type ) ) {
454 $choices = array();
455 $nothingPrompt = '';
456 foreach ( $type as $t ) {
457 if ( $t === '' ) {
458 $nothingPrompt = 'Can be empty, or ';
459 } else {
460 $choices[] = $t;
461 }
462 }
463 $desc .= $paramPrefix . $nothingPrompt . $prompt;
464 $choicesstring = implode( ', ', $choices );
465 $desc .= wordwrap( $choicesstring, 100, $descWordwrap );
466 $hintPipeSeparated = false;
467 } else {
468 switch ( $type ) {
469 case 'namespace':
470 // Special handling because namespaces are
471 // type-limited, yet they are not given
472 $desc .= $paramPrefix . $prompt;
473 $desc .= wordwrap( implode( ', ', MWNamespace::getValidNamespaces() ),
474 100, $descWordwrap );
475 $hintPipeSeparated = false;
476 break;
477 case 'limit':
478 $desc .= $paramPrefix . "No more than {$paramSettings[self::PARAM_MAX]}";
479 if ( isset( $paramSettings[self::PARAM_MAX2] ) ) {
480 $desc .= " ({$paramSettings[self::PARAM_MAX2]} for bots)";
481 }
482 $desc .= ' allowed';
483 break;
484 case 'integer':
485 $s = $multi ? 's' : '';
486 $hasMin = isset( $paramSettings[self::PARAM_MIN] );
487 $hasMax = isset( $paramSettings[self::PARAM_MAX] );
488 if ( $hasMin || $hasMax ) {
489 if ( !$hasMax ) {
490 $intRangeStr = "The value$s must be no less than " .
491 "{$paramSettings[self::PARAM_MIN]}";
492 } elseif ( !$hasMin ) {
493 $intRangeStr = "The value$s must be no more than " .
494 "{$paramSettings[self::PARAM_MAX]}";
495 } else {
496 $intRangeStr = "The value$s must be between " .
497 "{$paramSettings[self::PARAM_MIN]} and {$paramSettings[self::PARAM_MAX]}";
498 }
499
500 $desc .= $paramPrefix . $intRangeStr;
501 }
502 break;
503 case 'upload':
504 $desc .= $paramPrefix . "Must be posted as a file upload using multipart/form-data";
505 break;
506 }
507 }
508
509 if ( $multi ) {
510 if ( $hintPipeSeparated ) {
511 $desc .= $paramPrefix . "Separate values with '|'";
512 }
513
514 $isArray = is_array( $type );
515 if ( !$isArray
516 || $isArray && count( $type ) > self::LIMIT_SML1
517 ) {
518 $desc .= $paramPrefix . "Maximum number of values " .
519 self::LIMIT_SML1 . " (" . self::LIMIT_SML2 . " for bots)";
520 }
521 }
522 }
523
524 $default = isset( $paramSettings[self::PARAM_DFLT] ) ? $paramSettings[self::PARAM_DFLT] : null;
525 if ( !is_null( $default ) && $default !== false ) {
526 $desc .= $paramPrefix . "Default: $default";
527 }
528
529 $msg .= sprintf( " %-19s - %s\n", $this->encodeParamName( $paramName ), $desc );
530 }
531
532 return $msg;
533 }
534
535 return false;
536 }
537
538 /**
539 * Returns the description string for this module
540 * @return string|array
541 */
542 protected function getDescription() {
543 return false;
544 }
545
546 /**
547 * Returns usage examples for this module. Return false if no examples are available.
548 * @return bool|string|array
549 */
550 protected function getExamples() {
551 return false;
552 }
553
554 /**
555 * Returns an array of allowed parameters (parameter name) => (default
556 * value) or (parameter name) => (array with PARAM_* constants as keys)
557 * Don't call this function directly: use getFinalParams() to allow
558 * hooks to modify parameters as needed.
559 *
560 * Some derived classes may choose to handle an integer $flags parameter
561 * in the overriding methods. Callers of this method can pass zero or
562 * more OR-ed flags like GET_VALUES_FOR_HELP.
563 *
564 * @return array|bool
565 */
566 protected function getAllowedParams( /* $flags = 0 */ ) {
567 // int $flags is not declared because it causes "Strict standards"
568 // warning. Most derived classes do not implement it.
569 return false;
570 }
571
572 /**
573 * Returns an array of parameter descriptions.
574 * Don't call this function directly: use getFinalParamDescription() to
575 * allow hooks to modify descriptions as needed.
576 * @return array|bool False on no parameter descriptions
577 */
578 protected function getParamDescription() {
579 return false;
580 }
581
582 /**
583 * Get final list of parameters, after hooks have had a chance to
584 * tweak it as needed.
585 *
586 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
587 * @return array|bool False on no parameters
588 * @since 1.21 $flags param added
589 */
590 public function getFinalParams( $flags = 0 ) {
591 $params = $this->getAllowedParams( $flags );
592 wfRunHooks( 'APIGetAllowedParams', array( &$this, &$params, $flags ) );
593
594 return $params;
595 }
596
597 /**
598 * Get final parameter descriptions, after hooks have had a chance to tweak it as
599 * needed.
600 *
601 * @return array|bool False on no parameter descriptions
602 */
603 public function getFinalParamDescription() {
604 $desc = $this->getParamDescription();
605 wfRunHooks( 'APIGetParamDescription', array( &$this, &$desc ) );
606
607 return $desc;
608 }
609
610 /**
611 * Returns possible properties in the result, grouped by the value of the prop parameter
612 * that shows them.
613 *
614 * Properties that are shown always are in a group with empty string as a key.
615 * Properties that can be shown by several values of prop are included multiple times.
616 * If some properties are part of a list and some are on the root object (see ApiQueryQueryPage),
617 * those on the root object are under the key PROP_ROOT.
618 * The array can also contain a boolean under the key PROP_LIST,
619 * indicating whether the result is a list.
620 *
621 * Don't call this function directly: use getFinalResultProperties() to
622 * allow hooks to modify descriptions as needed.
623 *
624 * @return array|bool False on no properties
625 */
626 protected function getResultProperties() {
627 return false;
628 }
629
630 /**
631 * Get final possible result properties, after hooks have had a chance to tweak it as
632 * needed.
633 *
634 * @return array
635 */
636 public function getFinalResultProperties() {
637 $properties = $this->getResultProperties();
638 wfRunHooks( 'APIGetResultProperties', array( $this, &$properties ) );
639
640 return $properties;
641 }
642
643 /**
644 * Add token properties to the array used by getResultProperties,
645 * based on a token functions mapping.
646 * @param array $props
647 * @param array $tokenFunctions
648 */
649 protected static function addTokenProperties( &$props, $tokenFunctions ) {
650 foreach ( array_keys( $tokenFunctions ) as $token ) {
651 $props[''][$token . 'token'] = array(
652 ApiBase::PROP_TYPE => 'string',
653 ApiBase::PROP_NULLABLE => true
654 );
655 }
656 }
657
658 /**
659 * Get final module description, after hooks have had a chance to tweak it as
660 * needed.
661 *
662 * @return array|bool False on no parameters
663 */
664 public function getFinalDescription() {
665 $desc = $this->getDescription();
666 wfRunHooks( 'APIGetDescription', array( &$this, &$desc ) );
667
668 return $desc;
669 }
670
671 /**
672 * This method mangles parameter name based on the prefix supplied to the constructor.
673 * Override this method to change parameter name during runtime
674 * @param string $paramName Parameter name
675 * @return string Prefixed parameter name
676 */
677 public function encodeParamName( $paramName ) {
678 return $this->mModulePrefix . $paramName;
679 }
680
681 /**
682 * Using getAllowedParams(), this function makes an array of the values
683 * provided by the user, with key being the name of the variable, and
684 * value - validated value from user or default. limits will not be
685 * parsed if $parseLimit is set to false; use this when the max
686 * limit is not definitive yet, e.g. when getting revisions.
687 * @param bool $parseLimit True by default
688 * @return array
689 */
690 public function extractRequestParams( $parseLimit = true ) {
691 // Cache parameters, for performance and to avoid bug 24564.
692 if ( !isset( $this->mParamCache[$parseLimit] ) ) {
693 $params = $this->getFinalParams();
694 $results = array();
695
696 if ( $params ) { // getFinalParams() can return false
697 foreach ( $params as $paramName => $paramSettings ) {
698 $results[$paramName] = $this->getParameterFromSettings(
699 $paramName, $paramSettings, $parseLimit );
700 }
701 }
702 $this->mParamCache[$parseLimit] = $results;
703 }
704
705 return $this->mParamCache[$parseLimit];
706 }
707
708 /**
709 * Get a value for the given parameter
710 * @param string $paramName Parameter name
711 * @param bool $parseLimit See extractRequestParams()
712 * @return mixed Parameter value
713 */
714 protected function getParameter( $paramName, $parseLimit = true ) {
715 $params = $this->getFinalParams();
716 $paramSettings = $params[$paramName];
717
718 return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
719 }
720
721 /**
722 * Die if none or more than one of a certain set of parameters is set and not false.
723 *
724 * Call getRequireOnlyOneParameterErrorMessages() to get a list of possible errors.
725 *
726 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
727 * @param string $required,... Names of parameters of which exactly one must be set
728 */
729 public function requireOnlyOneParameter( $params, $required /*...*/ ) {
730 $required = func_get_args();
731 array_shift( $required );
732 $p = $this->getModulePrefix();
733
734 $intersection = array_intersect( array_keys( array_filter( $params,
735 array( $this, "parameterNotEmpty" ) ) ), $required );
736
737 if ( count( $intersection ) > 1 ) {
738 $this->dieUsage(
739 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
740 'invalidparammix' );
741 } elseif ( count( $intersection ) == 0 ) {
742 $this->dieUsage(
743 "One of the parameters {$p}" . implode( ", {$p}", $required ) . ' is required',
744 'missingparam'
745 );
746 }
747 }
748
749 /**
750 * Generates the possible errors requireOnlyOneParameter() can die with
751 *
752 * @param array $params
753 * @return array
754 */
755 public function getRequireOnlyOneParameterErrorMessages( $params ) {
756 $p = $this->getModulePrefix();
757 $params = implode( ", {$p}", $params );
758
759 return array(
760 array(
761 'code' => "{$p}missingparam",
762 'info' => "One of the parameters {$p}{$params} is required"
763 ),
764 array(
765 'code' => "{$p}invalidparammix",
766 'info' => "The parameters {$p}{$params} can not be used together"
767 )
768 );
769 }
770
771 /**
772 * Die if more than one of a certain set of parameters is set and not false.
773 *
774 * Call getRequireMaxOneParameterErrorMessages() to get a list of possible errors.
775 *
776 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
777 * @param string $required,... Names of parameters of which at most one must be set
778 */
779 public function requireMaxOneParameter( $params, $required /*...*/ ) {
780 $required = func_get_args();
781 array_shift( $required );
782 $p = $this->getModulePrefix();
783
784 $intersection = array_intersect( array_keys( array_filter( $params,
785 array( $this, "parameterNotEmpty" ) ) ), $required );
786
787 if ( count( $intersection ) > 1 ) {
788 $this->dieUsage(
789 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
790 'invalidparammix'
791 );
792 }
793 }
794
795 /**
796 * Generates the possible error requireMaxOneParameter() can die with
797 *
798 * @param array $params
799 * @return array
800 */
801 public function getRequireMaxOneParameterErrorMessages( $params ) {
802 $p = $this->getModulePrefix();
803 $params = implode( ", {$p}", $params );
804
805 return array(
806 array(
807 'code' => "{$p}invalidparammix",
808 'info' => "The parameters {$p}{$params} can not be used together"
809 )
810 );
811 }
812
813 /**
814 * Die if none of a certain set of parameters is set and not false.
815 *
816 * Call getRequireAtLeastOneParameterErrorMessages() to get a list of possible errors.
817 *
818 * @since 1.23
819 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
820 * @param string $required,... Names of parameters of which at least one must be set
821 */
822 public function requireAtLeastOneParameter( $params, $required /*...*/ ) {
823 $required = func_get_args();
824 array_shift( $required );
825 $p = $this->getModulePrefix();
826
827 $intersection = array_intersect(
828 array_keys( array_filter( $params, array( $this, "parameterNotEmpty" ) ) ),
829 $required
830 );
831
832 if ( count( $intersection ) == 0 ) {
833 $this->dieUsage( "At least one of the parameters {$p}" .
834 implode( ", {$p}", $required ) . ' is required', "{$p}missingparam" );
835 }
836 }
837
838 /**
839 * Generates the possible errors requireAtLeastOneParameter() can die with
840 *
841 * @since 1.23
842 * @param array $params Array of parameter key names
843 * @return array
844 */
845 public function getRequireAtLeastOneParameterErrorMessages( $params ) {
846 $p = $this->getModulePrefix();
847 $params = implode( ", {$p}", $params );
848
849 return array(
850 array(
851 'code' => "{$p}missingparam",
852 'info' => "At least one of the parameters {$p}{$params} is required",
853 ),
854 );
855 }
856
857 /**
858 * Get a WikiPage object from a title or pageid param, if possible.
859 * Can die, if no param is set or if the title or page id is not valid.
860 *
861 * Call getTitleOrPageIdErrorMessage() to get a list of possible errors.
862 *
863 * @param array $params
864 * @param bool|string $load Whether load the object's state from the database:
865 * - false: don't load (if the pageid is given, it will still be loaded)
866 * - 'fromdb': load from a slave database
867 * - 'fromdbmaster': load from the master database
868 * @return WikiPage
869 */
870 public function getTitleOrPageId( $params, $load = false ) {
871 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
872
873 $pageObj = null;
874 if ( isset( $params['title'] ) ) {
875 $titleObj = Title::newFromText( $params['title'] );
876 if ( !$titleObj || $titleObj->isExternal() ) {
877 $this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) );
878 }
879 if ( !$titleObj->canExist() ) {
880 $this->dieUsage( "Namespace doesn't allow actual pages", 'pagecannotexist' );
881 }
882 $pageObj = WikiPage::factory( $titleObj );
883 if ( $load !== false ) {
884 $pageObj->loadPageData( $load );
885 }
886 } elseif ( isset( $params['pageid'] ) ) {
887 if ( $load === false ) {
888 $load = 'fromdb';
889 }
890 $pageObj = WikiPage::newFromID( $params['pageid'], $load );
891 if ( !$pageObj ) {
892 $this->dieUsageMsg( array( 'nosuchpageid', $params['pageid'] ) );
893 }
894 }
895
896 return $pageObj;
897 }
898
899 /**
900 * Generates the possible error getTitleOrPageId() can die with
901 *
902 * @return array
903 */
904 public function getTitleOrPageIdErrorMessage() {
905 return array_merge(
906 $this->getRequireOnlyOneParameterErrorMessages( array( 'title', 'pageid' ) ),
907 array(
908 array( 'invalidtitle', 'title' ),
909 array( 'nosuchpageid', 'pageid' ),
910 )
911 );
912 }
913
914 /**
915 * Callback function used in requireOnlyOneParameter to check whether required parameters are set
916 *
917 * @param object $x Parameter to check is not null/false
918 * @return bool
919 */
920 private function parameterNotEmpty( $x ) {
921 return !is_null( $x ) && $x !== false;
922 }
923
924 /**
925 * Return true if we're to watch the page, false if not, null if no change.
926 * @param string $watchlist Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
927 * @param Title $titleObj The page under consideration
928 * @param string $userOption The user option to consider when $watchlist=preferences.
929 * If not set will use watchdefault always and watchcreations if $titleObj doesn't exist.
930 * @return bool
931 */
932 protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
933
934 $userWatching = $this->getUser()->isWatched( $titleObj, WatchedItem::IGNORE_USER_RIGHTS );
935
936 switch ( $watchlist ) {
937 case 'watch':
938 return true;
939
940 case 'unwatch':
941 return false;
942
943 case 'preferences':
944 # If the user is already watching, don't bother checking
945 if ( $userWatching ) {
946 return true;
947 }
948 # If no user option was passed, use watchdefault and watchcreations
949 if ( is_null( $userOption ) ) {
950 return $this->getUser()->getBoolOption( 'watchdefault' ) ||
951 $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
952 }
953
954 # Watch the article based on the user preference
955 return $this->getUser()->getBoolOption( $userOption );
956
957 case 'nochange':
958 return $userWatching;
959
960 default:
961 return $userWatching;
962 }
963 }
964
965 /**
966 * Set a watch (or unwatch) based the based on a watchlist parameter.
967 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
968 * @param Title $titleObj The article's title to change
969 * @param string $userOption The user option to consider when $watch=preferences
970 */
971 protected function setWatch( $watch, $titleObj, $userOption = null ) {
972 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
973 if ( $value === null ) {
974 return;
975 }
976
977 WatchAction::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
978 }
979
980 /**
981 * Using the settings determine the value for the given parameter
982 *
983 * @param string $paramName Parameter name
984 * @param array|mixed $paramSettings Default value or an array of settings
985 * using PARAM_* constants.
986 * @param bool $parseLimit Parse limit?
987 * @return mixed Parameter value
988 */
989 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
990 // Some classes may decide to change parameter names
991 $encParamName = $this->encodeParamName( $paramName );
992
993 if ( !is_array( $paramSettings ) ) {
994 $default = $paramSettings;
995 $multi = false;
996 $type = gettype( $paramSettings );
997 $dupes = false;
998 $deprecated = false;
999 $required = false;
1000 } else {
1001 $default = isset( $paramSettings[self::PARAM_DFLT] )
1002 ? $paramSettings[self::PARAM_DFLT]
1003 : null;
1004 $multi = isset( $paramSettings[self::PARAM_ISMULTI] )
1005 ? $paramSettings[self::PARAM_ISMULTI]
1006 : false;
1007 $type = isset( $paramSettings[self::PARAM_TYPE] )
1008 ? $paramSettings[self::PARAM_TYPE]
1009 : null;
1010 $dupes = isset( $paramSettings[self::PARAM_ALLOW_DUPLICATES] )
1011 ? $paramSettings[self::PARAM_ALLOW_DUPLICATES]
1012 : false;
1013 $deprecated = isset( $paramSettings[self::PARAM_DEPRECATED] )
1014 ? $paramSettings[self::PARAM_DEPRECATED]
1015 : false;
1016 $required = isset( $paramSettings[self::PARAM_REQUIRED] )
1017 ? $paramSettings[self::PARAM_REQUIRED]
1018 : false;
1019
1020 // When type is not given, and no choices, the type is the same as $default
1021 if ( !isset( $type ) ) {
1022 if ( isset( $default ) ) {
1023 $type = gettype( $default );
1024 } else {
1025 $type = 'NULL'; // allow everything
1026 }
1027 }
1028 }
1029
1030 if ( $type == 'boolean' ) {
1031 if ( isset( $default ) && $default !== false ) {
1032 // Having a default value of anything other than 'false' is not allowed
1033 ApiBase::dieDebug(
1034 __METHOD__,
1035 "Boolean param $encParamName's default is set to '$default'. " .
1036 "Boolean parameters must default to false."
1037 );
1038 }
1039
1040 $value = $this->getMain()->getCheck( $encParamName );
1041 } elseif ( $type == 'upload' ) {
1042 if ( isset( $default ) ) {
1043 // Having a default value is not allowed
1044 ApiBase::dieDebug(
1045 __METHOD__,
1046 "File upload param $encParamName's default is set to " .
1047 "'$default'. File upload parameters may not have a default." );
1048 }
1049 if ( $multi ) {
1050 ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
1051 }
1052 $value = $this->getMain()->getUpload( $encParamName );
1053 if ( !$value->exists() ) {
1054 // This will get the value without trying to normalize it
1055 // (because trying to normalize a large binary file
1056 // accidentally uploaded as a field fails spectacularly)
1057 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
1058 if ( $value !== null ) {
1059 $this->dieUsage(
1060 "File upload param $encParamName is not a file upload; " .
1061 "be sure to use multipart/form-data for your POST and include " .
1062 "a filename in the Content-Disposition header.",
1063 "badupload_{$encParamName}"
1064 );
1065 }
1066 }
1067 } else {
1068 $value = $this->getMain()->getVal( $encParamName, $default );
1069
1070 if ( isset( $value ) && $type == 'namespace' ) {
1071 $type = MWNamespace::getValidNamespaces();
1072 }
1073 }
1074
1075 if ( isset( $value ) && ( $multi || is_array( $type ) ) ) {
1076 $value = $this->parseMultiValue(
1077 $encParamName,
1078 $value,
1079 $multi,
1080 is_array( $type ) ? $type : null
1081 );
1082 }
1083
1084 // More validation only when choices were not given
1085 // choices were validated in parseMultiValue()
1086 if ( isset( $value ) ) {
1087 if ( !is_array( $type ) ) {
1088 switch ( $type ) {
1089 case 'NULL': // nothing to do
1090 break;
1091 case 'string':
1092 if ( $required && $value === '' ) {
1093 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
1094 }
1095 break;
1096 case 'integer': // Force everything using intval() and optionally validate limits
1097 $min = isset( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[self::PARAM_MIN] : null;
1098 $max = isset( $paramSettings[self::PARAM_MAX] ) ? $paramSettings[self::PARAM_MAX] : null;
1099 $enforceLimits = isset( $paramSettings[self::PARAM_RANGE_ENFORCE] )
1100 ? $paramSettings[self::PARAM_RANGE_ENFORCE] : false;
1101
1102 if ( is_array( $value ) ) {
1103 $value = array_map( 'intval', $value );
1104 if ( !is_null( $min ) || !is_null( $max ) ) {
1105 foreach ( $value as &$v ) {
1106 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
1107 }
1108 }
1109 } else {
1110 $value = intval( $value );
1111 if ( !is_null( $min ) || !is_null( $max ) ) {
1112 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
1113 }
1114 }
1115 break;
1116 case 'limit':
1117 if ( !$parseLimit ) {
1118 // Don't do any validation whatsoever
1119 break;
1120 }
1121 if ( !isset( $paramSettings[self::PARAM_MAX] )
1122 || !isset( $paramSettings[self::PARAM_MAX2] )
1123 ) {
1124 ApiBase::dieDebug(
1125 __METHOD__,
1126 "MAX1 or MAX2 are not defined for the limit $encParamName"
1127 );
1128 }
1129 if ( $multi ) {
1130 ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
1131 }
1132 $min = isset( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[self::PARAM_MIN] : 0;
1133 if ( $value == 'max' ) {
1134 $value = $this->getMain()->canApiHighLimits()
1135 ? $paramSettings[self::PARAM_MAX2]
1136 : $paramSettings[self::PARAM_MAX];
1137 $this->getResult()->setParsedLimit( $this->getModuleName(), $value );
1138 } else {
1139 $value = intval( $value );
1140 $this->validateLimit(
1141 $paramName,
1142 $value,
1143 $min,
1144 $paramSettings[self::PARAM_MAX],
1145 $paramSettings[self::PARAM_MAX2]
1146 );
1147 }
1148 break;
1149 case 'boolean':
1150 if ( $multi ) {
1151 ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
1152 }
1153 break;
1154 case 'timestamp':
1155 if ( is_array( $value ) ) {
1156 foreach ( $value as $key => $val ) {
1157 $value[$key] = $this->validateTimestamp( $val, $encParamName );
1158 }
1159 } else {
1160 $value = $this->validateTimestamp( $value, $encParamName );
1161 }
1162 break;
1163 case 'user':
1164 if ( is_array( $value ) ) {
1165 foreach ( $value as $key => $val ) {
1166 $value[$key] = $this->validateUser( $val, $encParamName );
1167 }
1168 } else {
1169 $value = $this->validateUser( $value, $encParamName );
1170 }
1171 break;
1172 case 'upload': // nothing to do
1173 break;
1174 default:
1175 ApiBase::dieDebug( __METHOD__, "Param $encParamName's type is unknown - $type" );
1176 }
1177 }
1178
1179 // Throw out duplicates if requested
1180 if ( !$dupes && is_array( $value ) ) {
1181 $value = array_unique( $value );
1182 }
1183
1184 // Set a warning if a deprecated parameter has been passed
1185 if ( $deprecated && $value !== false ) {
1186 $this->setWarning( "The $encParamName parameter has been deprecated." );
1187 }
1188 } elseif ( $required ) {
1189 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
1190 }
1191
1192 return $value;
1193 }
1194
1195 /**
1196 * Return an array of values that were given in a 'a|b|c' notation,
1197 * after it optionally validates them against the list allowed values.
1198 *
1199 * @param string $valueName The name of the parameter (for error
1200 * reporting)
1201 * @param mixed $value The value being parsed
1202 * @param bool $allowMultiple Can $value contain more than one value
1203 * separated by '|'?
1204 * @param mixed $allowedValues An array of values to check against. If
1205 * null, all values are accepted.
1206 * @return mixed (allowMultiple ? an_array_of_values : a_single_value)
1207 */
1208 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues ) {
1209 if ( trim( $value ) === '' && $allowMultiple ) {
1210 return array();
1211 }
1212
1213 // This is a bit awkward, but we want to avoid calling canApiHighLimits()
1214 // because it unstubs $wgUser
1215 $valuesList = explode( '|', $value, self::LIMIT_SML2 + 1 );
1216 $sizeLimit = count( $valuesList ) > self::LIMIT_SML1 && $this->mMainModule->canApiHighLimits()
1217 ? self::LIMIT_SML2
1218 : self::LIMIT_SML1;
1219
1220 if ( self::truncateArray( $valuesList, $sizeLimit ) ) {
1221 $this->setWarning( "Too many values supplied for parameter '$valueName': " .
1222 "the limit is $sizeLimit" );
1223 }
1224
1225 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
1226 // Bug 33482 - Allow entries with | in them for non-multiple values
1227 if ( in_array( $value, $allowedValues, true ) ) {
1228 return $value;
1229 }
1230
1231 $possibleValues = is_array( $allowedValues )
1232 ? "of '" . implode( "', '", $allowedValues ) . "'"
1233 : '';
1234 $this->dieUsage(
1235 "Only one $possibleValues is allowed for parameter '$valueName'",
1236 "multival_$valueName"
1237 );
1238 }
1239
1240 if ( is_array( $allowedValues ) ) {
1241 // Check for unknown values
1242 $unknown = array_diff( $valuesList, $allowedValues );
1243 if ( count( $unknown ) ) {
1244 if ( $allowMultiple ) {
1245 $s = count( $unknown ) > 1 ? 's' : '';
1246 $vals = implode( ", ", $unknown );
1247 $this->setWarning( "Unrecognized value$s for parameter '$valueName': $vals" );
1248 } else {
1249 $this->dieUsage(
1250 "Unrecognized value for parameter '$valueName': {$valuesList[0]}",
1251 "unknown_$valueName"
1252 );
1253 }
1254 }
1255 // Now throw them out
1256 $valuesList = array_intersect( $valuesList, $allowedValues );
1257 }
1258
1259 return $allowMultiple ? $valuesList : $valuesList[0];
1260 }
1261
1262 /**
1263 * Validate the value against the minimum and user/bot maximum limits.
1264 * Prints usage info on failure.
1265 * @param string $paramName Parameter name
1266 * @param int $value Parameter value
1267 * @param int|null $min Minimum value
1268 * @param int|null $max Maximum value for users
1269 * @param int $botMax Maximum value for sysops/bots
1270 * @param bool $enforceLimits Whether to enforce (die) if value is outside limits
1271 */
1272 function validateLimit( $paramName, &$value, $min, $max, $botMax = null, $enforceLimits = false ) {
1273 if ( !is_null( $min ) && $value < $min ) {
1274
1275 $msg = $this->encodeParamName( $paramName ) . " may not be less than $min (set to $value)";
1276 $this->warnOrDie( $msg, $enforceLimits );
1277 $value = $min;
1278 }
1279
1280 // Minimum is always validated, whereas maximum is checked only if not
1281 // running in internal call mode
1282 if ( $this->getMain()->isInternalMode() ) {
1283 return;
1284 }
1285
1286 // Optimization: do not check user's bot status unless really needed -- skips db query
1287 // assumes $botMax >= $max
1288 if ( !is_null( $max ) && $value > $max ) {
1289 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1290 if ( $value > $botMax ) {
1291 $msg = $this->encodeParamName( $paramName ) .
1292 " may not be over $botMax (set to $value) for bots or sysops";
1293 $this->warnOrDie( $msg, $enforceLimits );
1294 $value = $botMax;
1295 }
1296 } else {
1297 $msg = $this->encodeParamName( $paramName ) . " may not be over $max (set to $value) for users";
1298 $this->warnOrDie( $msg, $enforceLimits );
1299 $value = $max;
1300 }
1301 }
1302 }
1303
1304 /**
1305 * Validate and normalize of parameters of type 'timestamp'
1306 * @param string $value Parameter value
1307 * @param string $encParamName Parameter name
1308 * @return string Validated and normalized parameter
1309 */
1310 function validateTimestamp( $value, $encParamName ) {
1311 $unixTimestamp = wfTimestamp( TS_UNIX, $value );
1312 if ( $unixTimestamp === false ) {
1313 $this->dieUsage(
1314 "Invalid value '$value' for timestamp parameter $encParamName",
1315 "badtimestamp_{$encParamName}"
1316 );
1317 }
1318
1319 return wfTimestamp( TS_MW, $unixTimestamp );
1320 }
1321
1322 /**
1323 * Validate and normalize of parameters of type 'user'
1324 * @param string $value Parameter value
1325 * @param string $encParamName Parameter name
1326 * @return string Validated and normalized parameter
1327 */
1328 private function validateUser( $value, $encParamName ) {
1329 $title = Title::makeTitleSafe( NS_USER, $value );
1330 if ( $title === null ) {
1331 $this->dieUsage(
1332 "Invalid value '$value' for user parameter $encParamName",
1333 "baduser_{$encParamName}"
1334 );
1335 }
1336
1337 return $title->getText();
1338 }
1339
1340 /**
1341 * Adds a warning to the output, else dies
1342 *
1343 * @param string $msg Message to show as a warning, or error message if dying
1344 * @param bool $enforceLimits Whether this is an enforce (die)
1345 */
1346 private function warnOrDie( $msg, $enforceLimits = false ) {
1347 if ( $enforceLimits ) {
1348 $this->dieUsage( $msg, 'integeroutofrange' );
1349 }
1350
1351 $this->setWarning( $msg );
1352 }
1353
1354 /**
1355 * Truncate an array to a certain length.
1356 * @param array $arr Array to truncate
1357 * @param int $limit Maximum length
1358 * @return bool True if the array was truncated, false otherwise
1359 */
1360 public static function truncateArray( &$arr, $limit ) {
1361 $modified = false;
1362 while ( count( $arr ) > $limit ) {
1363 array_pop( $arr );
1364 $modified = true;
1365 }
1366
1367 return $modified;
1368 }
1369
1370 /**
1371 * Throw a UsageException, which will (if uncaught) call the main module's
1372 * error handler and die with an error message.
1373 *
1374 * @param string $description One-line human-readable description of the
1375 * error condition, e.g., "The API requires a valid action parameter"
1376 * @param string $errorCode Brief, arbitrary, stable string to allow easy
1377 * automated identification of the error, e.g., 'unknown_action'
1378 * @param int $httpRespCode HTTP response code
1379 * @param array $extradata Data to add to the "<error>" element; array in ApiResult format
1380 * @throws UsageException
1381 */
1382 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
1383 Profiler::instance()->close();
1384 throw new UsageException(
1385 $description,
1386 $this->encodeParamName( $errorCode ),
1387 $httpRespCode,
1388 $extradata
1389 );
1390 }
1391
1392 /**
1393 * Get error (as code, string) from a Status object.
1394 *
1395 * @since 1.23
1396 * @param Status $status
1397 * @return array Array of code and error string
1398 */
1399 public function getErrorFromStatus( $status ) {
1400 if ( $status->isGood() ) {
1401 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
1402 }
1403
1404 $errors = $status->getErrorsArray();
1405 if ( !$errors ) {
1406 // No errors? Assume the warnings should be treated as errors
1407 $errors = $status->getWarningsArray();
1408 }
1409 if ( !$errors ) {
1410 // Still no errors? Punt
1411 $errors = array( array( 'unknownerror-nocode' ) );
1412 }
1413
1414 // Cannot use dieUsageMsg() because extensions might return custom
1415 // error messages.
1416 if ( $errors[0] instanceof Message ) {
1417 $msg = $errors[0];
1418 $code = $msg->getKey();
1419 } else {
1420 $code = array_shift( $errors[0] );
1421 $msg = wfMessage( $code, $errors[0] );
1422 }
1423 if ( isset( ApiBase::$messageMap[$code] ) ) {
1424 // Translate message to code, for backwards compatability
1425 $code = ApiBase::$messageMap[$code]['code'];
1426 }
1427
1428 return array( $code, $msg->inLanguage( 'en' )->useDatabase( false )->plain() );
1429 }
1430
1431 /**
1432 * Throw a UsageException based on the errors in the Status object.
1433 *
1434 * @since 1.22
1435 * @param Status $status
1436 * @throws MWException
1437 */
1438 public function dieStatus( $status ) {
1439
1440 list( $code, $msg ) = $this->getErrorFromStatus( $status );
1441 $this->dieUsage( $msg, $code );
1442 }
1443
1444 // @codingStandardsIgnoreStart Allow long lines. Cannot split these.
1445 /**
1446 * Array that maps message keys to error messages. $1 and friends are replaced.
1447 */
1448 public static $messageMap = array(
1449 // This one MUST be present, or dieUsageMsg() will recurse infinitely
1450 'unknownerror' => array( 'code' => 'unknownerror', 'info' => "Unknown error: \"\$1\"" ),
1451 'unknownerror-nocode' => array( 'code' => 'unknownerror', 'info' => 'Unknown error' ),
1452
1453 // Messages from Title::getUserPermissionsErrors()
1454 'ns-specialprotected' => array(
1455 'code' => 'unsupportednamespace',
1456 'info' => "Pages in the Special namespace can't be edited"
1457 ),
1458 'protectedinterface' => array(
1459 'code' => 'protectednamespace-interface',
1460 'info' => "You're not allowed to edit interface messages"
1461 ),
1462 'namespaceprotected' => array(
1463 'code' => 'protectednamespace',
1464 'info' => "You're not allowed to edit pages in the \"\$1\" namespace"
1465 ),
1466 'customcssprotected' => array(
1467 'code' => 'customcssprotected',
1468 'info' => "You're not allowed to edit custom CSS pages"
1469 ),
1470 'customjsprotected' => array(
1471 'code' => 'customjsprotected',
1472 'info' => "You're not allowed to edit custom JavaScript pages"
1473 ),
1474 'cascadeprotected' => array(
1475 'code' => 'cascadeprotected',
1476 'info' => "The page you're trying to edit is protected because it's included in a cascade-protected page"
1477 ),
1478 'protectedpagetext' => array(
1479 'code' => 'protectedpage',
1480 'info' => "The \"\$1\" right is required to edit this page"
1481 ),
1482 'protect-cantedit' => array(
1483 'code' => 'cantedit',
1484 'info' => "You can't protect this page because you can't edit it"
1485 ),
1486 'badaccess-group0' => array(
1487 'code' => 'permissiondenied',
1488 'info' => "Permission denied"
1489 ), // Generic permission denied message
1490 'badaccess-groups' => array(
1491 'code' => 'permissiondenied',
1492 'info' => "Permission denied"
1493 ),
1494 'titleprotected' => array(
1495 'code' => 'protectedtitle',
1496 'info' => "This title has been protected from creation"
1497 ),
1498 'nocreate-loggedin' => array(
1499 'code' => 'cantcreate',
1500 'info' => "You don't have permission to create new pages"
1501 ),
1502 'nocreatetext' => array(
1503 'code' => 'cantcreate-anon',
1504 'info' => "Anonymous users can't create new pages"
1505 ),
1506 'movenologintext' => array(
1507 'code' => 'cantmove-anon',
1508 'info' => "Anonymous users can't move pages"
1509 ),
1510 'movenotallowed' => array(
1511 'code' => 'cantmove',
1512 'info' => "You don't have permission to move pages"
1513 ),
1514 'confirmedittext' => array(
1515 'code' => 'confirmemail',
1516 'info' => "You must confirm your email address before you can edit"
1517 ),
1518 'blockedtext' => array(
1519 'code' => 'blocked',
1520 'info' => "You have been blocked from editing"
1521 ),
1522 'autoblockedtext' => array(
1523 'code' => 'autoblocked',
1524 'info' => "Your IP address has been blocked automatically, because it was used by a blocked user"
1525 ),
1526
1527 // Miscellaneous interface messages
1528 'actionthrottledtext' => array(
1529 'code' => 'ratelimited',
1530 'info' => "You've exceeded your rate limit. Please wait some time and try again"
1531 ),
1532 'alreadyrolled' => array(
1533 'code' => 'alreadyrolled',
1534 'info' => "The page you tried to rollback was already rolled back"
1535 ),
1536 'cantrollback' => array(
1537 'code' => 'onlyauthor',
1538 'info' => "The page you tried to rollback only has one author"
1539 ),
1540 'readonlytext' => array(
1541 'code' => 'readonly',
1542 'info' => "The wiki is currently in read-only mode"
1543 ),
1544 'sessionfailure' => array(
1545 'code' => 'badtoken',
1546 'info' => "Invalid token" ),
1547 'cannotdelete' => array(
1548 'code' => 'cantdelete',
1549 'info' => "Couldn't delete \"\$1\". Maybe it was deleted already by someone else"
1550 ),
1551 'notanarticle' => array(
1552 'code' => 'missingtitle',
1553 'info' => "The page you requested doesn't exist"
1554 ),
1555 'selfmove' => array( 'code' => 'selfmove', 'info' => "Can't move a page to itself"
1556 ),
1557 'immobile_namespace' => array(
1558 'code' => 'immobilenamespace',
1559 'info' => "You tried to move pages from or to a namespace that is protected from moving"
1560 ),
1561 'articleexists' => array(
1562 'code' => 'articleexists',
1563 'info' => "The destination article already exists and is not a redirect to the source article"
1564 ),
1565 'protectedpage' => array(
1566 'code' => 'protectedpage',
1567 'info' => "You don't have permission to perform this move"
1568 ),
1569 'hookaborted' => array(
1570 'code' => 'hookaborted',
1571 'info' => "The modification you tried to make was aborted by an extension hook"
1572 ),
1573 'cantmove-titleprotected' => array(
1574 'code' => 'protectedtitle',
1575 'info' => "The destination article has been protected from creation"
1576 ),
1577 'imagenocrossnamespace' => array(
1578 'code' => 'nonfilenamespace',
1579 'info' => "Can't move a file to a non-file namespace"
1580 ),
1581 'imagetypemismatch' => array(
1582 'code' => 'filetypemismatch',
1583 'info' => "The new file extension doesn't match its type"
1584 ),
1585 // 'badarticleerror' => shouldn't happen
1586 // 'badtitletext' => shouldn't happen
1587 'ip_range_invalid' => array( 'code' => 'invalidrange', 'info' => "Invalid IP range" ),
1588 'range_block_disabled' => array(
1589 'code' => 'rangedisabled',
1590 'info' => "Blocking IP ranges has been disabled"
1591 ),
1592 'nosuchusershort' => array(
1593 'code' => 'nosuchuser',
1594 'info' => "The user you specified doesn't exist"
1595 ),
1596 'badipaddress' => array( 'code' => 'invalidip', 'info' => "Invalid IP address specified" ),
1597 'ipb_expiry_invalid' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time" ),
1598 'ipb_already_blocked' => array(
1599 'code' => 'alreadyblocked',
1600 'info' => "The user you tried to block was already blocked"
1601 ),
1602 'ipb_blocked_as_range' => array(
1603 'code' => 'blockedasrange',
1604 'info' => "IP address \"\$1\" was blocked as part of range \"\$2\". You can't unblock the IP individually, but you can unblock the range as a whole."
1605 ),
1606 'ipb_cant_unblock' => array(
1607 'code' => 'cantunblock',
1608 'info' => "The block you specified was not found. It may have been unblocked already"
1609 ),
1610 'mailnologin' => array(
1611 'code' => 'cantsend',
1612 'info' => "You are not logged in, you do not have a confirmed email address, or you are not allowed to send email to other users, so you cannot send email"
1613 ),
1614 'ipbblocked' => array(
1615 'code' => 'ipbblocked',
1616 'info' => 'You cannot block or unblock users while you are yourself blocked'
1617 ),
1618 'ipbnounblockself' => array(
1619 'code' => 'ipbnounblockself',
1620 'info' => 'You are not allowed to unblock yourself'
1621 ),
1622 'usermaildisabled' => array(
1623 'code' => 'usermaildisabled',
1624 'info' => "User email has been disabled"
1625 ),
1626 'blockedemailuser' => array(
1627 'code' => 'blockedfrommail',
1628 'info' => "You have been blocked from sending email"
1629 ),
1630 'notarget' => array(
1631 'code' => 'notarget',
1632 'info' => "You have not specified a valid target for this action"
1633 ),
1634 'noemail' => array(
1635 'code' => 'noemail',
1636 'info' => "The user has not specified a valid email address, or has chosen not to receive email from other users"
1637 ),
1638 'rcpatroldisabled' => array(
1639 'code' => 'patroldisabled',
1640 'info' => "Patrolling is disabled on this wiki"
1641 ),
1642 'markedaspatrollederror-noautopatrol' => array(
1643 'code' => 'noautopatrol',
1644 'info' => "You don't have permission to patrol your own changes"
1645 ),
1646 'delete-toobig' => array(
1647 'code' => 'bigdelete',
1648 'info' => "You can't delete this page because it has more than \$1 revisions"
1649 ),
1650 'movenotallowedfile' => array(
1651 'code' => 'cantmovefile',
1652 'info' => "You don't have permission to move files"
1653 ),
1654 'userrights-no-interwiki' => array(
1655 'code' => 'nointerwikiuserrights',
1656 'info' => "You don't have permission to change user rights on other wikis"
1657 ),
1658 'userrights-nodatabase' => array(
1659 'code' => 'nosuchdatabase',
1660 'info' => "Database \"\$1\" does not exist or is not local"
1661 ),
1662 'nouserspecified' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1663 'noname' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1664 'summaryrequired' => array( 'code' => 'summaryrequired', 'info' => 'Summary required' ),
1665 'import-rootpage-invalid' => array(
1666 'code' => 'import-rootpage-invalid',
1667 'info' => 'Root page is an invalid title'
1668 ),
1669 'import-rootpage-nosubpage' => array(
1670 'code' => 'import-rootpage-nosubpage',
1671 'info' => 'Namespace "$1" of the root page does not allow subpages'
1672 ),
1673
1674 // API-specific messages
1675 'readrequired' => array(
1676 'code' => 'readapidenied',
1677 'info' => "You need read permission to use this module"
1678 ),
1679 'writedisabled' => array(
1680 'code' => 'noapiwrite',
1681 '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"
1682 ),
1683 'writerequired' => array(
1684 'code' => 'writeapidenied',
1685 'info' => "You're not allowed to edit this wiki through the API"
1686 ),
1687 'missingparam' => array( 'code' => 'no$1', 'info' => "The \$1 parameter must be set" ),
1688 'invalidtitle' => array( 'code' => 'invalidtitle', 'info' => "Bad title \"\$1\"" ),
1689 'nosuchpageid' => array( 'code' => 'nosuchpageid', 'info' => "There is no page with ID \$1" ),
1690 'nosuchrevid' => array( 'code' => 'nosuchrevid', 'info' => "There is no revision with ID \$1" ),
1691 'nosuchuser' => array( 'code' => 'nosuchuser', 'info' => "User \"\$1\" doesn't exist" ),
1692 'invaliduser' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1693 'invalidexpiry' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time \"\$1\"" ),
1694 'pastexpiry' => array( 'code' => 'pastexpiry', 'info' => "Expiry time \"\$1\" is in the past" ),
1695 'create-titleexists' => array(
1696 'code' => 'create-titleexists',
1697 'info' => "Existing titles can't be protected with 'create'"
1698 ),
1699 'missingtitle-createonly' => array(
1700 'code' => 'missingtitle-createonly',
1701 'info' => "Missing titles can only be protected with 'create'"
1702 ),
1703 'cantblock' => array( 'code' => 'cantblock',
1704 'info' => "You don't have permission to block users"
1705 ),
1706 'canthide' => array(
1707 'code' => 'canthide',
1708 'info' => "You don't have permission to hide user names from the block log"
1709 ),
1710 'cantblock-email' => array(
1711 'code' => 'cantblock-email',
1712 'info' => "You don't have permission to block users from sending email through the wiki"
1713 ),
1714 'unblock-notarget' => array(
1715 'code' => 'notarget',
1716 'info' => "Either the id or the user parameter must be set"
1717 ),
1718 'unblock-idanduser' => array(
1719 'code' => 'idanduser',
1720 'info' => "The id and user parameters can't be used together"
1721 ),
1722 'cantunblock' => array(
1723 'code' => 'permissiondenied',
1724 'info' => "You don't have permission to unblock users"
1725 ),
1726 'cannotundelete' => array(
1727 'code' => 'cantundelete',
1728 'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already"
1729 ),
1730 'permdenied-undelete' => array(
1731 'code' => 'permissiondenied',
1732 'info' => "You don't have permission to restore deleted revisions"
1733 ),
1734 'createonly-exists' => array(
1735 'code' => 'articleexists',
1736 'info' => "The article you tried to create has been created already"
1737 ),
1738 'nocreate-missing' => array(
1739 'code' => 'missingtitle',
1740 'info' => "The article you tried to edit doesn't exist"
1741 ),
1742 'nosuchrcid' => array(
1743 'code' => 'nosuchrcid',
1744 'info' => "There is no change with rcid \"\$1\""
1745 ),
1746 'protect-invalidaction' => array(
1747 'code' => 'protect-invalidaction',
1748 'info' => "Invalid protection type \"\$1\""
1749 ),
1750 'protect-invalidlevel' => array(
1751 'code' => 'protect-invalidlevel',
1752 'info' => "Invalid protection level \"\$1\""
1753 ),
1754 'toofewexpiries' => array(
1755 'code' => 'toofewexpiries',
1756 'info' => "\$1 expiry timestamps were provided where \$2 were needed"
1757 ),
1758 'cantimport' => array(
1759 'code' => 'cantimport',
1760 'info' => "You don't have permission to import pages"
1761 ),
1762 'cantimport-upload' => array(
1763 'code' => 'cantimport-upload',
1764 'info' => "You don't have permission to import uploaded pages"
1765 ),
1766 'importnofile' => array( 'code' => 'nofile', 'info' => "You didn't upload a file" ),
1767 'importuploaderrorsize' => array(
1768 'code' => 'filetoobig',
1769 'info' => 'The file you uploaded is bigger than the maximum upload size'
1770 ),
1771 'importuploaderrorpartial' => array(
1772 'code' => 'partialupload',
1773 'info' => 'The file was only partially uploaded'
1774 ),
1775 'importuploaderrortemp' => array(
1776 'code' => 'notempdir',
1777 'info' => 'The temporary upload directory is missing'
1778 ),
1779 'importcantopen' => array(
1780 'code' => 'cantopenfile',
1781 'info' => "Couldn't open the uploaded file"
1782 ),
1783 'import-noarticle' => array(
1784 'code' => 'badinterwiki',
1785 'info' => 'Invalid interwiki title specified'
1786 ),
1787 'importbadinterwiki' => array(
1788 'code' => 'badinterwiki',
1789 'info' => 'Invalid interwiki title specified'
1790 ),
1791 'import-unknownerror' => array(
1792 'code' => 'import-unknownerror',
1793 'info' => "Unknown error on import: \"\$1\""
1794 ),
1795 'cantoverwrite-sharedfile' => array(
1796 'code' => 'cantoverwrite-sharedfile',
1797 'info' => 'The target file exists on a shared repository and you do not have permission to override it'
1798 ),
1799 'sharedfile-exists' => array(
1800 'code' => 'fileexists-sharedrepo-perm',
1801 'info' => 'The target file exists on a shared repository. Use the ignorewarnings parameter to override it.'
1802 ),
1803 'mustbeposted' => array(
1804 'code' => 'mustbeposted',
1805 'info' => "The \$1 module requires a POST request"
1806 ),
1807 'show' => array(
1808 'code' => 'show',
1809 'info' => 'Incorrect parameter - mutually exclusive values may not be supplied'
1810 ),
1811 'specialpage-cantexecute' => array(
1812 'code' => 'specialpage-cantexecute',
1813 'info' => "You don't have permission to view the results of this special page"
1814 ),
1815 'invalidoldimage' => array(
1816 'code' => 'invalidoldimage',
1817 'info' => 'The oldimage parameter has invalid format'
1818 ),
1819 'nodeleteablefile' => array(
1820 'code' => 'nodeleteablefile',
1821 'info' => 'No such old version of the file'
1822 ),
1823 'fileexists-forbidden' => array(
1824 'code' => 'fileexists-forbidden',
1825 'info' => 'A file with name "$1" already exists, and cannot be overwritten.'
1826 ),
1827 'fileexists-shared-forbidden' => array(
1828 'code' => 'fileexists-shared-forbidden',
1829 'info' => 'A file with name "$1" already exists in the shared file repository, and cannot be overwritten.'
1830 ),
1831 'filerevert-badversion' => array(
1832 'code' => 'filerevert-badversion',
1833 'info' => 'There is no previous local version of this file with the provided timestamp.'
1834 ),
1835
1836 // ApiEditPage messages
1837 'noimageredirect-anon' => array(
1838 'code' => 'noimageredirect-anon',
1839 'info' => "Anonymous users can't create image redirects"
1840 ),
1841 'noimageredirect-logged' => array(
1842 'code' => 'noimageredirect',
1843 'info' => "You don't have permission to create image redirects"
1844 ),
1845 'spamdetected' => array(
1846 'code' => 'spamdetected',
1847 'info' => "Your edit was refused because it contained a spam fragment: \"\$1\""
1848 ),
1849 'contenttoobig' => array(
1850 'code' => 'contenttoobig',
1851 'info' => "The content you supplied exceeds the article size limit of \$1 kilobytes"
1852 ),
1853 'noedit-anon' => array( 'code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages" ),
1854 'noedit' => array( 'code' => 'noedit', 'info' => "You don't have permission to edit pages" ),
1855 'wasdeleted' => array(
1856 'code' => 'pagedeleted',
1857 'info' => "The page has been deleted since you fetched its timestamp"
1858 ),
1859 'blankpage' => array(
1860 'code' => 'emptypage',
1861 'info' => "Creating new, empty pages is not allowed"
1862 ),
1863 'editconflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1864 'hashcheckfailed' => array( 'code' => 'badmd5', 'info' => "The supplied MD5 hash was incorrect" ),
1865 'missingtext' => array(
1866 'code' => 'notext',
1867 'info' => "One of the text, appendtext, prependtext and undo parameters must be set"
1868 ),
1869 'emptynewsection' => array(
1870 'code' => 'emptynewsection',
1871 'info' => 'Creating empty new sections is not possible.'
1872 ),
1873 'revwrongpage' => array(
1874 'code' => 'revwrongpage',
1875 'info' => "r\$1 is not a revision of \"\$2\""
1876 ),
1877 'undo-failure' => array(
1878 'code' => 'undofailure',
1879 'info' => 'Undo failed due to conflicting intermediate edits'
1880 ),
1881
1882 // Messages from WikiPage::doEit()
1883 'edit-hook-aborted' => array(
1884 'code' => 'edit-hook-aborted',
1885 'info' => "Your edit was aborted by an ArticleSave hook"
1886 ),
1887 'edit-gone-missing' => array(
1888 'code' => 'edit-gone-missing',
1889 'info' => "The page you tried to edit doesn't seem to exist anymore"
1890 ),
1891 'edit-conflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1892 'edit-already-exists' => array(
1893 'code' => 'edit-already-exists',
1894 'info' => 'It seems the page you tried to create already exist'
1895 ),
1896
1897 // uploadMsgs
1898 'invalid-file-key' => array( 'code' => 'invalid-file-key', 'info' => 'Not a valid file key' ),
1899 'nouploadmodule' => array( 'code' => 'nouploadmodule', 'info' => 'No upload module set' ),
1900 'uploaddisabled' => array(
1901 'code' => 'uploaddisabled',
1902 'info' => 'Uploads are not enabled. Make sure $wgEnableUploads is set to true in LocalSettings.php and the PHP ini setting file_uploads is true'
1903 ),
1904 'copyuploaddisabled' => array(
1905 'code' => 'copyuploaddisabled',
1906 'info' => 'Uploads by URL is not enabled. Make sure $wgAllowCopyUploads is set to true in LocalSettings.php.'
1907 ),
1908 'copyuploadbaddomain' => array(
1909 'code' => 'copyuploadbaddomain',
1910 'info' => 'Uploads by URL are not allowed from this domain.'
1911 ),
1912 'copyuploadbadurl' => array(
1913 'code' => 'copyuploadbadurl',
1914 'info' => 'Upload not allowed from this URL.'
1915 ),
1916
1917 'filename-tooshort' => array(
1918 'code' => 'filename-tooshort',
1919 'info' => 'The filename is too short'
1920 ),
1921 'filename-toolong' => array( 'code' => 'filename-toolong', 'info' => 'The filename is too long' ),
1922 'illegal-filename' => array(
1923 'code' => 'illegal-filename',
1924 'info' => 'The filename is not allowed'
1925 ),
1926 'filetype-missing' => array(
1927 'code' => 'filetype-missing',
1928 'info' => 'The file is missing an extension'
1929 ),
1930
1931 'mustbeloggedin' => array( 'code' => 'mustbeloggedin', 'info' => 'You must be logged in to $1.' )
1932 );
1933 // @codingStandardsIgnoreEnd
1934
1935 /**
1936 * Helper function for readonly errors
1937 */
1938 public function dieReadOnly() {
1939 $parsed = $this->parseMsg( array( 'readonlytext' ) );
1940 $this->dieUsage( $parsed['info'], $parsed['code'], /* http error */ 0,
1941 array( 'readonlyreason' => wfReadOnlyReason() ) );
1942 }
1943
1944 /**
1945 * Output the error message related to a certain array
1946 * @param array|string $error Element of a getUserPermissionsErrors()-style array
1947 */
1948 public function dieUsageMsg( $error ) {
1949 # most of the time we send a 1 element, so we might as well send it as
1950 # a string and make this an array here.
1951 if ( is_string( $error ) ) {
1952 $error = array( $error );
1953 }
1954 $parsed = $this->parseMsg( $error );
1955 $this->dieUsage( $parsed['info'], $parsed['code'] );
1956 }
1957
1958 /**
1959 * Will only set a warning instead of failing if the global $wgDebugAPI
1960 * is set to true. Otherwise behaves exactly as dieUsageMsg().
1961 * @param array|string $error Element of a getUserPermissionsErrors()-style array
1962 * @since 1.21
1963 */
1964 public function dieUsageMsgOrDebug( $error ) {
1965 global $wgDebugAPI;
1966 if ( $wgDebugAPI !== true ) {
1967 $this->dieUsageMsg( $error );
1968 }
1969
1970 if ( is_string( $error ) ) {
1971 $error = array( $error );
1972 }
1973
1974 $parsed = $this->parseMsg( $error );
1975 $this->setWarning( '$wgDebugAPI: ' . $parsed['code'] . ' - ' . $parsed['info'] );
1976 }
1977
1978 /**
1979 * Die with the $prefix.'badcontinue' error. This call is common enough to
1980 * make it into the base method.
1981 * @param bool $condition Will only die if this value is true
1982 * @since 1.21
1983 */
1984 protected function dieContinueUsageIf( $condition ) {
1985 if ( $condition ) {
1986 $this->dieUsage(
1987 'Invalid continue param. You should pass the original value returned by the previous query',
1988 'badcontinue' );
1989 }
1990 }
1991
1992 /**
1993 * Return the error message related to a certain array
1994 * @param array $error Element of a getUserPermissionsErrors()-style array
1995 * @return array('code' => code, 'info' => info)
1996 */
1997 public function parseMsg( $error ) {
1998 $error = (array)$error; // It seems strings sometimes make their way in here
1999 $key = array_shift( $error );
2000
2001 // Check whether the error array was nested
2002 // array( array( <code>, <params> ), array( <another_code>, <params> ) )
2003 if ( is_array( $key ) ) {
2004 $error = $key;
2005 $key = array_shift( $error );
2006 }
2007
2008 if ( isset( self::$messageMap[$key] ) ) {
2009 return array(
2010 'code' => wfMsgReplaceArgs( self::$messageMap[$key]['code'], $error ),
2011 'info' => wfMsgReplaceArgs( self::$messageMap[$key]['info'], $error )
2012 );
2013 }
2014
2015 // If the key isn't present, throw an "unknown error"
2016 return $this->parseMsg( array( 'unknownerror', $key ) );
2017 }
2018
2019 /**
2020 * Internal code errors should be reported with this method
2021 * @param string $method Method or function name
2022 * @param string $message Error message
2023 * @throws MWException
2024 */
2025 protected static function dieDebug( $method, $message ) {
2026 throw new MWException( "Internal error in $method: $message" );
2027 }
2028
2029 /**
2030 * Indicates if this module needs maxlag to be checked
2031 * @return bool
2032 */
2033 public function shouldCheckMaxlag() {
2034 return true;
2035 }
2036
2037 /**
2038 * Indicates whether this module requires read rights
2039 * @return bool
2040 */
2041 public function isReadMode() {
2042 return true;
2043 }
2044
2045 /**
2046 * Indicates whether this module requires write mode
2047 * @return bool
2048 */
2049 public function isWriteMode() {
2050 return false;
2051 }
2052
2053 /**
2054 * Indicates whether this module must be called with a POST request
2055 * @return bool
2056 */
2057 public function mustBePosted() {
2058 return false;
2059 }
2060
2061 /**
2062 * Returns whether this module requires a token to execute
2063 * It is used to show possible errors in action=paraminfo
2064 * see bug 25248
2065 * @return bool
2066 */
2067 public function needsToken() {
2068 return false;
2069 }
2070
2071 /**
2072 * Returns the token salt if there is one,
2073 * '' if the module doesn't require a salt,
2074 * else false if the module doesn't need a token
2075 * You have also to override needsToken()
2076 * Value is passed to User::getEditToken
2077 * @return bool|string|array
2078 */
2079 public function getTokenSalt() {
2080 return false;
2081 }
2082
2083 /**
2084 * Gets the user for whom to get the watchlist
2085 *
2086 * @param array $params
2087 * @return User
2088 */
2089 public function getWatchlistUser( $params ) {
2090 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
2091 $user = User::newFromName( $params['owner'], false );
2092 if ( !( $user && $user->getId() ) ) {
2093 $this->dieUsage( 'Specified user does not exist', 'bad_wlowner' );
2094 }
2095 $token = $user->getOption( 'watchlisttoken' );
2096 if ( $token == '' || $token != $params['token'] ) {
2097 $this->dieUsage(
2098 'Incorrect watchlist token provided -- please set a correct token in Special:Preferences',
2099 'bad_wltoken'
2100 );
2101 }
2102 } else {
2103 if ( !$this->getUser()->isLoggedIn() ) {
2104 $this->dieUsage( 'You must be logged-in to have a watchlist', 'notloggedin' );
2105 }
2106 if ( !$this->getUser()->isAllowed( 'viewmywatchlist' ) ) {
2107 $this->dieUsage( 'You don\'t have permission to view your watchlist', 'permissiondenied' );
2108 }
2109 $user = $this->getUser();
2110 }
2111
2112 return $user;
2113 }
2114
2115 /**
2116 * @return bool|string|array Returns a false if the module has no help URL,
2117 * else returns a (array of) string
2118 */
2119 public function getHelpUrls() {
2120 return false;
2121 }
2122
2123 /**
2124 * Returns a list of all possible errors returned by the module
2125 *
2126 * Don't call this function directly: use getFinalPossibleErrors() to allow
2127 * hooks to modify parameters as needed.
2128 *
2129 * @return array Array in the format of array( key, param1, param2, ... )
2130 * or array( 'code' => ..., 'info' => ... )
2131 */
2132 public function getPossibleErrors() {
2133 $ret = array();
2134
2135 $params = $this->getFinalParams();
2136 if ( $params ) {
2137 foreach ( $params as $paramName => $paramSettings ) {
2138 if ( isset( $paramSettings[ApiBase::PARAM_REQUIRED] )
2139 && $paramSettings[ApiBase::PARAM_REQUIRED]
2140 ) {
2141 $ret[] = array( 'missingparam', $paramName );
2142 }
2143 }
2144 if ( array_key_exists( 'continue', $params ) ) {
2145 $ret[] = array(
2146 'code' => 'badcontinue',
2147 'info' => 'Invalid continue param. You should pass the ' .
2148 'original value returned by the previous query'
2149 );
2150 }
2151 }
2152
2153 if ( $this->mustBePosted() ) {
2154 $ret[] = array( 'mustbeposted', $this->getModuleName() );
2155 }
2156
2157 if ( $this->isReadMode() ) {
2158 $ret[] = array( 'readrequired' );
2159 }
2160
2161 if ( $this->isWriteMode() ) {
2162 $ret[] = array( 'writerequired' );
2163 $ret[] = array( 'writedisabled' );
2164 }
2165
2166 if ( $this->needsToken() ) {
2167 if ( !isset( $params['token'][ApiBase::PARAM_REQUIRED] )
2168 || !$params['token'][ApiBase::PARAM_REQUIRED]
2169 ) {
2170 // Add token as possible missing parameter, if not already done
2171 $ret[] = array( 'missingparam', 'token' );
2172 }
2173 $ret[] = array( 'sessionfailure' );
2174 }
2175
2176 return $ret;
2177 }
2178
2179 /**
2180 * Get final list of possible errors, after hooks have had a chance to
2181 * tweak it as needed.
2182 *
2183 * @return array
2184 * @since 1.22
2185 */
2186 public function getFinalPossibleErrors() {
2187 $possibleErrors = $this->getPossibleErrors();
2188 wfRunHooks( 'APIGetPossibleErrors', array( $this, &$possibleErrors ) );
2189
2190 return $possibleErrors;
2191 }
2192
2193 /**
2194 * Parses a list of errors into a standardised format
2195 * @param array $errors List of errors. Items can be in the for
2196 * array( key, param1, param2, ... ) or array( 'code' => ..., 'info' => ... )
2197 * @return array Parsed list of errors with items in the form array( 'code' => ..., 'info' => ... )
2198 */
2199 public function parseErrors( $errors ) {
2200 $ret = array();
2201
2202 foreach ( $errors as $row ) {
2203 if ( isset( $row['code'] ) && isset( $row['info'] ) ) {
2204 $ret[] = $row;
2205 } else {
2206 $ret[] = $this->parseMsg( $row );
2207 }
2208 }
2209
2210 return $ret;
2211 }
2212
2213 /**
2214 * Profiling: total module execution time
2215 */
2216 private $mTimeIn = 0, $mModuleTime = 0;
2217
2218 /**
2219 * Start module profiling
2220 */
2221 public function profileIn() {
2222 if ( $this->mTimeIn !== 0 ) {
2223 ApiBase::dieDebug( __METHOD__, 'Called twice without calling profileOut()' );
2224 }
2225 $this->mTimeIn = microtime( true );
2226 wfProfileIn( $this->getModuleProfileName() );
2227 }
2228
2229 /**
2230 * End module profiling
2231 */
2232 public function profileOut() {
2233 if ( $this->mTimeIn === 0 ) {
2234 ApiBase::dieDebug( __METHOD__, 'Called without calling profileIn() first' );
2235 }
2236 if ( $this->mDBTimeIn !== 0 ) {
2237 ApiBase::dieDebug(
2238 __METHOD__,
2239 'Must be called after database profiling is done with profileDBOut()'
2240 );
2241 }
2242
2243 $this->mModuleTime += microtime( true ) - $this->mTimeIn;
2244 $this->mTimeIn = 0;
2245 wfProfileOut( $this->getModuleProfileName() );
2246 }
2247
2248 /**
2249 * When modules crash, sometimes it is needed to do a profileOut() regardless
2250 * of the profiling state the module was in. This method does such cleanup.
2251 */
2252 public function safeProfileOut() {
2253 if ( $this->mTimeIn !== 0 ) {
2254 if ( $this->mDBTimeIn !== 0 ) {
2255 $this->profileDBOut();
2256 }
2257 $this->profileOut();
2258 }
2259 }
2260
2261 /**
2262 * Total time the module was executed
2263 * @return float
2264 */
2265 public function getProfileTime() {
2266 if ( $this->mTimeIn !== 0 ) {
2267 ApiBase::dieDebug( __METHOD__, 'Called without calling profileOut() first' );
2268 }
2269
2270 return $this->mModuleTime;
2271 }
2272
2273 /**
2274 * Profiling: database execution time
2275 */
2276 private $mDBTimeIn = 0, $mDBTime = 0;
2277
2278 /**
2279 * Start module profiling
2280 */
2281 public function profileDBIn() {
2282 if ( $this->mTimeIn === 0 ) {
2283 ApiBase::dieDebug(
2284 __METHOD__,
2285 'Must be called while profiling the entire module with profileIn()'
2286 );
2287 }
2288 if ( $this->mDBTimeIn !== 0 ) {
2289 ApiBase::dieDebug( __METHOD__, 'Called twice without calling profileDBOut()' );
2290 }
2291 $this->mDBTimeIn = microtime( true );
2292 wfProfileIn( $this->getModuleProfileName( true ) );
2293 }
2294
2295 /**
2296 * End database profiling
2297 */
2298 public function profileDBOut() {
2299 if ( $this->mTimeIn === 0 ) {
2300 ApiBase::dieDebug( __METHOD__, 'Must be called while profiling ' .
2301 'the entire module with profileIn()' );
2302 }
2303 if ( $this->mDBTimeIn === 0 ) {
2304 ApiBase::dieDebug( __METHOD__, 'Called without calling profileDBIn() first' );
2305 }
2306
2307 $time = microtime( true ) - $this->mDBTimeIn;
2308 $this->mDBTimeIn = 0;
2309
2310 $this->mDBTime += $time;
2311 $this->getMain()->mDBTime += $time;
2312 wfProfileOut( $this->getModuleProfileName( true ) );
2313 }
2314
2315 /**
2316 * Total time the module used the database
2317 * @return float
2318 */
2319 public function getProfileDBTime() {
2320 if ( $this->mDBTimeIn !== 0 ) {
2321 ApiBase::dieDebug( __METHOD__, 'Called without calling profileDBOut() first' );
2322 }
2323
2324 return $this->mDBTime;
2325 }
2326
2327 /**
2328 * Gets a default slave database connection object
2329 * @return DatabaseBase
2330 */
2331 protected function getDB() {
2332 if ( !isset( $this->mSlaveDB ) ) {
2333 $this->profileDBIn();
2334 $this->mSlaveDB = wfGetDB( DB_SLAVE, 'api' );
2335 $this->profileDBOut();
2336 }
2337
2338 return $this->mSlaveDB;
2339 }
2340
2341 /**
2342 * Debugging function that prints a value and an optional backtrace
2343 * @param mixed $value Value to print
2344 * @param string $name Description of the printed value
2345 * @param bool $backtrace If true, print a backtrace
2346 */
2347 public static function debugPrint( $value, $name = 'unknown', $backtrace = false ) {
2348 print "\n\n<pre><b>Debugging value '$name':</b>\n\n";
2349 var_export( $value );
2350 if ( $backtrace ) {
2351 print "\n" . wfBacktrace();
2352 }
2353 print "\n</pre>\n";
2354 }
2355 }