Apparently for certain (API) requests $this->getTitle() doesn't return a valid Title.
[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 array( 'code' => 'pagecannotexist', 'info' => "Namespace doesn't allow actual pages" ),
911 )
912 );
913 }
914
915 /**
916 * Callback function used in requireOnlyOneParameter to check whether required parameters are set
917 *
918 * @param object $x Parameter to check is not null/false
919 * @return bool
920 */
921 private function parameterNotEmpty( $x ) {
922 return !is_null( $x ) && $x !== false;
923 }
924
925 /**
926 * Return true if we're to watch the page, false if not, null if no change.
927 * @param string $watchlist Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
928 * @param Title $titleObj The page under consideration
929 * @param string $userOption The user option to consider when $watchlist=preferences.
930 * If not set will use watchdefault always and watchcreations if $titleObj doesn't exist.
931 * @return bool
932 */
933 protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
934
935 $userWatching = $this->getUser()->isWatched( $titleObj, WatchedItem::IGNORE_USER_RIGHTS );
936
937 switch ( $watchlist ) {
938 case 'watch':
939 return true;
940
941 case 'unwatch':
942 return false;
943
944 case 'preferences':
945 # If the user is already watching, don't bother checking
946 if ( $userWatching ) {
947 return true;
948 }
949 # If no user option was passed, use watchdefault and watchcreations
950 if ( is_null( $userOption ) ) {
951 return $this->getUser()->getBoolOption( 'watchdefault' ) ||
952 $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
953 }
954
955 # Watch the article based on the user preference
956 return $this->getUser()->getBoolOption( $userOption );
957
958 case 'nochange':
959 return $userWatching;
960
961 default:
962 return $userWatching;
963 }
964 }
965
966 /**
967 * Set a watch (or unwatch) based the based on a watchlist parameter.
968 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
969 * @param Title $titleObj The article's title to change
970 * @param string $userOption The user option to consider when $watch=preferences
971 */
972 protected function setWatch( $watch, $titleObj, $userOption = null ) {
973 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
974 if ( $value === null ) {
975 return;
976 }
977
978 WatchAction::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
979 }
980
981 /**
982 * Using the settings determine the value for the given parameter
983 *
984 * @param string $paramName Parameter name
985 * @param array|mixed $paramSettings Default value or an array of settings
986 * using PARAM_* constants.
987 * @param bool $parseLimit Parse limit?
988 * @return mixed Parameter value
989 */
990 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
991 // Some classes may decide to change parameter names
992 $encParamName = $this->encodeParamName( $paramName );
993
994 if ( !is_array( $paramSettings ) ) {
995 $default = $paramSettings;
996 $multi = false;
997 $type = gettype( $paramSettings );
998 $dupes = false;
999 $deprecated = false;
1000 $required = false;
1001 } else {
1002 $default = isset( $paramSettings[self::PARAM_DFLT] )
1003 ? $paramSettings[self::PARAM_DFLT]
1004 : null;
1005 $multi = isset( $paramSettings[self::PARAM_ISMULTI] )
1006 ? $paramSettings[self::PARAM_ISMULTI]
1007 : false;
1008 $type = isset( $paramSettings[self::PARAM_TYPE] )
1009 ? $paramSettings[self::PARAM_TYPE]
1010 : null;
1011 $dupes = isset( $paramSettings[self::PARAM_ALLOW_DUPLICATES] )
1012 ? $paramSettings[self::PARAM_ALLOW_DUPLICATES]
1013 : false;
1014 $deprecated = isset( $paramSettings[self::PARAM_DEPRECATED] )
1015 ? $paramSettings[self::PARAM_DEPRECATED]
1016 : false;
1017 $required = isset( $paramSettings[self::PARAM_REQUIRED] )
1018 ? $paramSettings[self::PARAM_REQUIRED]
1019 : false;
1020
1021 // When type is not given, and no choices, the type is the same as $default
1022 if ( !isset( $type ) ) {
1023 if ( isset( $default ) ) {
1024 $type = gettype( $default );
1025 } else {
1026 $type = 'NULL'; // allow everything
1027 }
1028 }
1029 }
1030
1031 if ( $type == 'boolean' ) {
1032 if ( isset( $default ) && $default !== false ) {
1033 // Having a default value of anything other than 'false' is not allowed
1034 ApiBase::dieDebug(
1035 __METHOD__,
1036 "Boolean param $encParamName's default is set to '$default'. " .
1037 "Boolean parameters must default to false."
1038 );
1039 }
1040
1041 $value = $this->getMain()->getCheck( $encParamName );
1042 } elseif ( $type == 'upload' ) {
1043 if ( isset( $default ) ) {
1044 // Having a default value is not allowed
1045 ApiBase::dieDebug(
1046 __METHOD__,
1047 "File upload param $encParamName's default is set to " .
1048 "'$default'. File upload parameters may not have a default." );
1049 }
1050 if ( $multi ) {
1051 ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
1052 }
1053 $value = $this->getMain()->getUpload( $encParamName );
1054 if ( !$value->exists() ) {
1055 // This will get the value without trying to normalize it
1056 // (because trying to normalize a large binary file
1057 // accidentally uploaded as a field fails spectacularly)
1058 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
1059 if ( $value !== null ) {
1060 $this->dieUsage(
1061 "File upload param $encParamName is not a file upload; " .
1062 "be sure to use multipart/form-data for your POST and include " .
1063 "a filename in the Content-Disposition header.",
1064 "badupload_{$encParamName}"
1065 );
1066 }
1067 }
1068 } else {
1069 $value = $this->getMain()->getVal( $encParamName, $default );
1070
1071 if ( isset( $value ) && $type == 'namespace' ) {
1072 $type = MWNamespace::getValidNamespaces();
1073 }
1074 }
1075
1076 if ( isset( $value ) && ( $multi || is_array( $type ) ) ) {
1077 $value = $this->parseMultiValue(
1078 $encParamName,
1079 $value,
1080 $multi,
1081 is_array( $type ) ? $type : null
1082 );
1083 }
1084
1085 // More validation only when choices were not given
1086 // choices were validated in parseMultiValue()
1087 if ( isset( $value ) ) {
1088 if ( !is_array( $type ) ) {
1089 switch ( $type ) {
1090 case 'NULL': // nothing to do
1091 break;
1092 case 'string':
1093 if ( $required && $value === '' ) {
1094 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
1095 }
1096 break;
1097 case 'integer': // Force everything using intval() and optionally validate limits
1098 $min = isset( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[self::PARAM_MIN] : null;
1099 $max = isset( $paramSettings[self::PARAM_MAX] ) ? $paramSettings[self::PARAM_MAX] : null;
1100 $enforceLimits = isset( $paramSettings[self::PARAM_RANGE_ENFORCE] )
1101 ? $paramSettings[self::PARAM_RANGE_ENFORCE] : false;
1102
1103 if ( is_array( $value ) ) {
1104 $value = array_map( 'intval', $value );
1105 if ( !is_null( $min ) || !is_null( $max ) ) {
1106 foreach ( $value as &$v ) {
1107 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
1108 }
1109 }
1110 } else {
1111 $value = intval( $value );
1112 if ( !is_null( $min ) || !is_null( $max ) ) {
1113 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
1114 }
1115 }
1116 break;
1117 case 'limit':
1118 if ( !$parseLimit ) {
1119 // Don't do any validation whatsoever
1120 break;
1121 }
1122 if ( !isset( $paramSettings[self::PARAM_MAX] )
1123 || !isset( $paramSettings[self::PARAM_MAX2] )
1124 ) {
1125 ApiBase::dieDebug(
1126 __METHOD__,
1127 "MAX1 or MAX2 are not defined for the limit $encParamName"
1128 );
1129 }
1130 if ( $multi ) {
1131 ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
1132 }
1133 $min = isset( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[self::PARAM_MIN] : 0;
1134 if ( $value == 'max' ) {
1135 $value = $this->getMain()->canApiHighLimits()
1136 ? $paramSettings[self::PARAM_MAX2]
1137 : $paramSettings[self::PARAM_MAX];
1138 $this->getResult()->setParsedLimit( $this->getModuleName(), $value );
1139 } else {
1140 $value = intval( $value );
1141 $this->validateLimit(
1142 $paramName,
1143 $value,
1144 $min,
1145 $paramSettings[self::PARAM_MAX],
1146 $paramSettings[self::PARAM_MAX2]
1147 );
1148 }
1149 break;
1150 case 'boolean':
1151 if ( $multi ) {
1152 ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
1153 }
1154 break;
1155 case 'timestamp':
1156 if ( is_array( $value ) ) {
1157 foreach ( $value as $key => $val ) {
1158 $value[$key] = $this->validateTimestamp( $val, $encParamName );
1159 }
1160 } else {
1161 $value = $this->validateTimestamp( $value, $encParamName );
1162 }
1163 break;
1164 case 'user':
1165 if ( is_array( $value ) ) {
1166 foreach ( $value as $key => $val ) {
1167 $value[$key] = $this->validateUser( $val, $encParamName );
1168 }
1169 } else {
1170 $value = $this->validateUser( $value, $encParamName );
1171 }
1172 break;
1173 case 'upload': // nothing to do
1174 break;
1175 default:
1176 ApiBase::dieDebug( __METHOD__, "Param $encParamName's type is unknown - $type" );
1177 }
1178 }
1179
1180 // Throw out duplicates if requested
1181 if ( !$dupes && is_array( $value ) ) {
1182 $value = array_unique( $value );
1183 }
1184
1185 // Set a warning if a deprecated parameter has been passed
1186 if ( $deprecated && $value !== false ) {
1187 $this->setWarning( "The $encParamName parameter has been deprecated." );
1188 }
1189 } elseif ( $required ) {
1190 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
1191 }
1192
1193 return $value;
1194 }
1195
1196 /**
1197 * Return an array of values that were given in a 'a|b|c' notation,
1198 * after it optionally validates them against the list allowed values.
1199 *
1200 * @param string $valueName The name of the parameter (for error
1201 * reporting)
1202 * @param mixed $value The value being parsed
1203 * @param bool $allowMultiple Can $value contain more than one value
1204 * separated by '|'?
1205 * @param mixed $allowedValues An array of values to check against. If
1206 * null, all values are accepted.
1207 * @return mixed (allowMultiple ? an_array_of_values : a_single_value)
1208 */
1209 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues ) {
1210 if ( trim( $value ) === '' && $allowMultiple ) {
1211 return array();
1212 }
1213
1214 // This is a bit awkward, but we want to avoid calling canApiHighLimits()
1215 // because it unstubs $wgUser
1216 $valuesList = explode( '|', $value, self::LIMIT_SML2 + 1 );
1217 $sizeLimit = count( $valuesList ) > self::LIMIT_SML1 && $this->mMainModule->canApiHighLimits()
1218 ? self::LIMIT_SML2
1219 : self::LIMIT_SML1;
1220
1221 if ( self::truncateArray( $valuesList, $sizeLimit ) ) {
1222 $this->setWarning( "Too many values supplied for parameter '$valueName': " .
1223 "the limit is $sizeLimit" );
1224 }
1225
1226 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
1227 // Bug 33482 - Allow entries with | in them for non-multiple values
1228 if ( in_array( $value, $allowedValues, true ) ) {
1229 return $value;
1230 }
1231
1232 $possibleValues = is_array( $allowedValues )
1233 ? "of '" . implode( "', '", $allowedValues ) . "'"
1234 : '';
1235 $this->dieUsage(
1236 "Only one $possibleValues is allowed for parameter '$valueName'",
1237 "multival_$valueName"
1238 );
1239 }
1240
1241 if ( is_array( $allowedValues ) ) {
1242 // Check for unknown values
1243 $unknown = array_diff( $valuesList, $allowedValues );
1244 if ( count( $unknown ) ) {
1245 if ( $allowMultiple ) {
1246 $s = count( $unknown ) > 1 ? 's' : '';
1247 $vals = implode( ", ", $unknown );
1248 $this->setWarning( "Unrecognized value$s for parameter '$valueName': $vals" );
1249 } else {
1250 $this->dieUsage(
1251 "Unrecognized value for parameter '$valueName': {$valuesList[0]}",
1252 "unknown_$valueName"
1253 );
1254 }
1255 }
1256 // Now throw them out
1257 $valuesList = array_intersect( $valuesList, $allowedValues );
1258 }
1259
1260 return $allowMultiple ? $valuesList : $valuesList[0];
1261 }
1262
1263 /**
1264 * Validate the value against the minimum and user/bot maximum limits.
1265 * Prints usage info on failure.
1266 * @param string $paramName Parameter name
1267 * @param int $value Parameter value
1268 * @param int|null $min Minimum value
1269 * @param int|null $max Maximum value for users
1270 * @param int $botMax Maximum value for sysops/bots
1271 * @param bool $enforceLimits Whether to enforce (die) if value is outside limits
1272 */
1273 function validateLimit( $paramName, &$value, $min, $max, $botMax = null, $enforceLimits = false ) {
1274 if ( !is_null( $min ) && $value < $min ) {
1275
1276 $msg = $this->encodeParamName( $paramName ) . " may not be less than $min (set to $value)";
1277 $this->warnOrDie( $msg, $enforceLimits );
1278 $value = $min;
1279 }
1280
1281 // Minimum is always validated, whereas maximum is checked only if not
1282 // running in internal call mode
1283 if ( $this->getMain()->isInternalMode() ) {
1284 return;
1285 }
1286
1287 // Optimization: do not check user's bot status unless really needed -- skips db query
1288 // assumes $botMax >= $max
1289 if ( !is_null( $max ) && $value > $max ) {
1290 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1291 if ( $value > $botMax ) {
1292 $msg = $this->encodeParamName( $paramName ) .
1293 " may not be over $botMax (set to $value) for bots or sysops";
1294 $this->warnOrDie( $msg, $enforceLimits );
1295 $value = $botMax;
1296 }
1297 } else {
1298 $msg = $this->encodeParamName( $paramName ) . " may not be over $max (set to $value) for users";
1299 $this->warnOrDie( $msg, $enforceLimits );
1300 $value = $max;
1301 }
1302 }
1303 }
1304
1305 /**
1306 * Validate and normalize of parameters of type 'timestamp'
1307 * @param string $value Parameter value
1308 * @param string $encParamName Parameter name
1309 * @return string Validated and normalized parameter
1310 */
1311 function validateTimestamp( $value, $encParamName ) {
1312 $unixTimestamp = wfTimestamp( TS_UNIX, $value );
1313 if ( $unixTimestamp === false ) {
1314 $this->dieUsage(
1315 "Invalid value '$value' for timestamp parameter $encParamName",
1316 "badtimestamp_{$encParamName}"
1317 );
1318 }
1319
1320 return wfTimestamp( TS_MW, $unixTimestamp );
1321 }
1322
1323 /**
1324 * Validate and normalize of parameters of type 'user'
1325 * @param string $value Parameter value
1326 * @param string $encParamName Parameter name
1327 * @return string Validated and normalized parameter
1328 */
1329 private function validateUser( $value, $encParamName ) {
1330 $title = Title::makeTitleSafe( NS_USER, $value );
1331 if ( $title === null ) {
1332 $this->dieUsage(
1333 "Invalid value '$value' for user parameter $encParamName",
1334 "baduser_{$encParamName}"
1335 );
1336 }
1337
1338 return $title->getText();
1339 }
1340
1341 /**
1342 * Adds a warning to the output, else dies
1343 *
1344 * @param string $msg Message to show as a warning, or error message if dying
1345 * @param bool $enforceLimits Whether this is an enforce (die)
1346 */
1347 private function warnOrDie( $msg, $enforceLimits = false ) {
1348 if ( $enforceLimits ) {
1349 $this->dieUsage( $msg, 'integeroutofrange' );
1350 }
1351
1352 $this->setWarning( $msg );
1353 }
1354
1355 /**
1356 * Truncate an array to a certain length.
1357 * @param array $arr Array to truncate
1358 * @param int $limit Maximum length
1359 * @return bool True if the array was truncated, false otherwise
1360 */
1361 public static function truncateArray( &$arr, $limit ) {
1362 $modified = false;
1363 while ( count( $arr ) > $limit ) {
1364 array_pop( $arr );
1365 $modified = true;
1366 }
1367
1368 return $modified;
1369 }
1370
1371 /**
1372 * Throw a UsageException, which will (if uncaught) call the main module's
1373 * error handler and die with an error message.
1374 *
1375 * @param string $description One-line human-readable description of the
1376 * error condition, e.g., "The API requires a valid action parameter"
1377 * @param string $errorCode Brief, arbitrary, stable string to allow easy
1378 * automated identification of the error, e.g., 'unknown_action'
1379 * @param int $httpRespCode HTTP response code
1380 * @param array $extradata Data to add to the "<error>" element; array in ApiResult format
1381 * @throws UsageException
1382 */
1383 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
1384 Profiler::instance()->close();
1385 throw new UsageException(
1386 $description,
1387 $this->encodeParamName( $errorCode ),
1388 $httpRespCode,
1389 $extradata
1390 );
1391 }
1392
1393 /**
1394 * Get error (as code, string) from a Status object.
1395 *
1396 * @since 1.23
1397 * @param Status $status
1398 * @return array Array of code and error string
1399 */
1400 public function getErrorFromStatus( $status ) {
1401 if ( $status->isGood() ) {
1402 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
1403 }
1404
1405 $errors = $status->getErrorsArray();
1406 if ( !$errors ) {
1407 // No errors? Assume the warnings should be treated as errors
1408 $errors = $status->getWarningsArray();
1409 }
1410 if ( !$errors ) {
1411 // Still no errors? Punt
1412 $errors = array( array( 'unknownerror-nocode' ) );
1413 }
1414
1415 // Cannot use dieUsageMsg() because extensions might return custom
1416 // error messages.
1417 if ( $errors[0] instanceof Message ) {
1418 $msg = $errors[0];
1419 $code = $msg->getKey();
1420 } else {
1421 $code = array_shift( $errors[0] );
1422 $msg = wfMessage( $code, $errors[0] );
1423 }
1424 if ( isset( ApiBase::$messageMap[$code] ) ) {
1425 // Translate message to code, for backwards compatability
1426 $code = ApiBase::$messageMap[$code]['code'];
1427 }
1428
1429 return array( $code, $msg->inLanguage( 'en' )->useDatabase( false )->plain() );
1430 }
1431
1432 /**
1433 * Throw a UsageException based on the errors in the Status object.
1434 *
1435 * @since 1.22
1436 * @param Status $status
1437 * @throws MWException
1438 */
1439 public function dieStatus( $status ) {
1440
1441 list( $code, $msg ) = $this->getErrorFromStatus( $status );
1442 $this->dieUsage( $msg, $code );
1443 }
1444
1445 // @codingStandardsIgnoreStart Allow long lines. Cannot split these.
1446 /**
1447 * Array that maps message keys to error messages. $1 and friends are replaced.
1448 */
1449 public static $messageMap = array(
1450 // This one MUST be present, or dieUsageMsg() will recurse infinitely
1451 'unknownerror' => array( 'code' => 'unknownerror', 'info' => "Unknown error: \"\$1\"" ),
1452 'unknownerror-nocode' => array( 'code' => 'unknownerror', 'info' => 'Unknown error' ),
1453
1454 // Messages from Title::getUserPermissionsErrors()
1455 'ns-specialprotected' => array(
1456 'code' => 'unsupportednamespace',
1457 'info' => "Pages in the Special namespace can't be edited"
1458 ),
1459 'protectedinterface' => array(
1460 'code' => 'protectednamespace-interface',
1461 'info' => "You're not allowed to edit interface messages"
1462 ),
1463 'namespaceprotected' => array(
1464 'code' => 'protectednamespace',
1465 'info' => "You're not allowed to edit pages in the \"\$1\" namespace"
1466 ),
1467 'customcssprotected' => array(
1468 'code' => 'customcssprotected',
1469 'info' => "You're not allowed to edit custom CSS pages"
1470 ),
1471 'customjsprotected' => array(
1472 'code' => 'customjsprotected',
1473 'info' => "You're not allowed to edit custom JavaScript pages"
1474 ),
1475 'cascadeprotected' => array(
1476 'code' => 'cascadeprotected',
1477 'info' => "The page you're trying to edit is protected because it's included in a cascade-protected page"
1478 ),
1479 'protectedpagetext' => array(
1480 'code' => 'protectedpage',
1481 'info' => "The \"\$1\" right is required to edit this page"
1482 ),
1483 'protect-cantedit' => array(
1484 'code' => 'cantedit',
1485 'info' => "You can't protect this page because you can't edit it"
1486 ),
1487 'badaccess-group0' => array(
1488 'code' => 'permissiondenied',
1489 'info' => "Permission denied"
1490 ), // Generic permission denied message
1491 'badaccess-groups' => array(
1492 'code' => 'permissiondenied',
1493 'info' => "Permission denied"
1494 ),
1495 'titleprotected' => array(
1496 'code' => 'protectedtitle',
1497 'info' => "This title has been protected from creation"
1498 ),
1499 'nocreate-loggedin' => array(
1500 'code' => 'cantcreate',
1501 'info' => "You don't have permission to create new pages"
1502 ),
1503 'nocreatetext' => array(
1504 'code' => 'cantcreate-anon',
1505 'info' => "Anonymous users can't create new pages"
1506 ),
1507 'movenologintext' => array(
1508 'code' => 'cantmove-anon',
1509 'info' => "Anonymous users can't move pages"
1510 ),
1511 'movenotallowed' => array(
1512 'code' => 'cantmove',
1513 'info' => "You don't have permission to move pages"
1514 ),
1515 'confirmedittext' => array(
1516 'code' => 'confirmemail',
1517 'info' => "You must confirm your email address before you can edit"
1518 ),
1519 'blockedtext' => array(
1520 'code' => 'blocked',
1521 'info' => "You have been blocked from editing"
1522 ),
1523 'autoblockedtext' => array(
1524 'code' => 'autoblocked',
1525 'info' => "Your IP address has been blocked automatically, because it was used by a blocked user"
1526 ),
1527
1528 // Miscellaneous interface messages
1529 'actionthrottledtext' => array(
1530 'code' => 'ratelimited',
1531 'info' => "You've exceeded your rate limit. Please wait some time and try again"
1532 ),
1533 'alreadyrolled' => array(
1534 'code' => 'alreadyrolled',
1535 'info' => "The page you tried to rollback was already rolled back"
1536 ),
1537 'cantrollback' => array(
1538 'code' => 'onlyauthor',
1539 'info' => "The page you tried to rollback only has one author"
1540 ),
1541 'readonlytext' => array(
1542 'code' => 'readonly',
1543 'info' => "The wiki is currently in read-only mode"
1544 ),
1545 'sessionfailure' => array(
1546 'code' => 'badtoken',
1547 'info' => "Invalid token" ),
1548 'cannotdelete' => array(
1549 'code' => 'cantdelete',
1550 'info' => "Couldn't delete \"\$1\". Maybe it was deleted already by someone else"
1551 ),
1552 'notanarticle' => array(
1553 'code' => 'missingtitle',
1554 'info' => "The page you requested doesn't exist"
1555 ),
1556 'selfmove' => array( 'code' => 'selfmove', 'info' => "Can't move a page to itself"
1557 ),
1558 'immobile_namespace' => array(
1559 'code' => 'immobilenamespace',
1560 'info' => "You tried to move pages from or to a namespace that is protected from moving"
1561 ),
1562 'articleexists' => array(
1563 'code' => 'articleexists',
1564 'info' => "The destination article already exists and is not a redirect to the source article"
1565 ),
1566 'protectedpage' => array(
1567 'code' => 'protectedpage',
1568 'info' => "You don't have permission to perform this move"
1569 ),
1570 'hookaborted' => array(
1571 'code' => 'hookaborted',
1572 'info' => "The modification you tried to make was aborted by an extension hook"
1573 ),
1574 'cantmove-titleprotected' => array(
1575 'code' => 'protectedtitle',
1576 'info' => "The destination article has been protected from creation"
1577 ),
1578 'imagenocrossnamespace' => array(
1579 'code' => 'nonfilenamespace',
1580 'info' => "Can't move a file to a non-file namespace"
1581 ),
1582 'imagetypemismatch' => array(
1583 'code' => 'filetypemismatch',
1584 'info' => "The new file extension doesn't match its type"
1585 ),
1586 // 'badarticleerror' => shouldn't happen
1587 // 'badtitletext' => shouldn't happen
1588 'ip_range_invalid' => array( 'code' => 'invalidrange', 'info' => "Invalid IP range" ),
1589 'range_block_disabled' => array(
1590 'code' => 'rangedisabled',
1591 'info' => "Blocking IP ranges has been disabled"
1592 ),
1593 'nosuchusershort' => array(
1594 'code' => 'nosuchuser',
1595 'info' => "The user you specified doesn't exist"
1596 ),
1597 'badipaddress' => array( 'code' => 'invalidip', 'info' => "Invalid IP address specified" ),
1598 'ipb_expiry_invalid' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time" ),
1599 'ipb_already_blocked' => array(
1600 'code' => 'alreadyblocked',
1601 'info' => "The user you tried to block was already blocked"
1602 ),
1603 'ipb_blocked_as_range' => array(
1604 'code' => 'blockedasrange',
1605 '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."
1606 ),
1607 'ipb_cant_unblock' => array(
1608 'code' => 'cantunblock',
1609 'info' => "The block you specified was not found. It may have been unblocked already"
1610 ),
1611 'mailnologin' => array(
1612 'code' => 'cantsend',
1613 '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"
1614 ),
1615 'ipbblocked' => array(
1616 'code' => 'ipbblocked',
1617 'info' => 'You cannot block or unblock users while you are yourself blocked'
1618 ),
1619 'ipbnounblockself' => array(
1620 'code' => 'ipbnounblockself',
1621 'info' => 'You are not allowed to unblock yourself'
1622 ),
1623 'usermaildisabled' => array(
1624 'code' => 'usermaildisabled',
1625 'info' => "User email has been disabled"
1626 ),
1627 'blockedemailuser' => array(
1628 'code' => 'blockedfrommail',
1629 'info' => "You have been blocked from sending email"
1630 ),
1631 'notarget' => array(
1632 'code' => 'notarget',
1633 'info' => "You have not specified a valid target for this action"
1634 ),
1635 'noemail' => array(
1636 'code' => 'noemail',
1637 'info' => "The user has not specified a valid email address, or has chosen not to receive email from other users"
1638 ),
1639 'rcpatroldisabled' => array(
1640 'code' => 'patroldisabled',
1641 'info' => "Patrolling is disabled on this wiki"
1642 ),
1643 'markedaspatrollederror-noautopatrol' => array(
1644 'code' => 'noautopatrol',
1645 'info' => "You don't have permission to patrol your own changes"
1646 ),
1647 'delete-toobig' => array(
1648 'code' => 'bigdelete',
1649 'info' => "You can't delete this page because it has more than \$1 revisions"
1650 ),
1651 'movenotallowedfile' => array(
1652 'code' => 'cantmovefile',
1653 'info' => "You don't have permission to move files"
1654 ),
1655 'userrights-no-interwiki' => array(
1656 'code' => 'nointerwikiuserrights',
1657 'info' => "You don't have permission to change user rights on other wikis"
1658 ),
1659 'userrights-nodatabase' => array(
1660 'code' => 'nosuchdatabase',
1661 'info' => "Database \"\$1\" does not exist or is not local"
1662 ),
1663 'nouserspecified' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1664 'noname' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1665 'summaryrequired' => array( 'code' => 'summaryrequired', 'info' => 'Summary required' ),
1666 'import-rootpage-invalid' => array(
1667 'code' => 'import-rootpage-invalid',
1668 'info' => 'Root page is an invalid title'
1669 ),
1670 'import-rootpage-nosubpage' => array(
1671 'code' => 'import-rootpage-nosubpage',
1672 'info' => 'Namespace "$1" of the root page does not allow subpages'
1673 ),
1674
1675 // API-specific messages
1676 'readrequired' => array(
1677 'code' => 'readapidenied',
1678 'info' => "You need read permission to use this module"
1679 ),
1680 'writedisabled' => array(
1681 'code' => 'noapiwrite',
1682 '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"
1683 ),
1684 'writerequired' => array(
1685 'code' => 'writeapidenied',
1686 'info' => "You're not allowed to edit this wiki through the API"
1687 ),
1688 'missingparam' => array( 'code' => 'no$1', 'info' => "The \$1 parameter must be set" ),
1689 'invalidtitle' => array( 'code' => 'invalidtitle', 'info' => "Bad title \"\$1\"" ),
1690 'nosuchpageid' => array( 'code' => 'nosuchpageid', 'info' => "There is no page with ID \$1" ),
1691 'nosuchrevid' => array( 'code' => 'nosuchrevid', 'info' => "There is no revision with ID \$1" ),
1692 'nosuchuser' => array( 'code' => 'nosuchuser', 'info' => "User \"\$1\" doesn't exist" ),
1693 'invaliduser' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1694 'invalidexpiry' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time \"\$1\"" ),
1695 'pastexpiry' => array( 'code' => 'pastexpiry', 'info' => "Expiry time \"\$1\" is in the past" ),
1696 'create-titleexists' => array(
1697 'code' => 'create-titleexists',
1698 'info' => "Existing titles can't be protected with 'create'"
1699 ),
1700 'missingtitle-createonly' => array(
1701 'code' => 'missingtitle-createonly',
1702 'info' => "Missing titles can only be protected with 'create'"
1703 ),
1704 'cantblock' => array( 'code' => 'cantblock',
1705 'info' => "You don't have permission to block users"
1706 ),
1707 'canthide' => array(
1708 'code' => 'canthide',
1709 'info' => "You don't have permission to hide user names from the block log"
1710 ),
1711 'cantblock-email' => array(
1712 'code' => 'cantblock-email',
1713 'info' => "You don't have permission to block users from sending email through the wiki"
1714 ),
1715 'unblock-notarget' => array(
1716 'code' => 'notarget',
1717 'info' => "Either the id or the user parameter must be set"
1718 ),
1719 'unblock-idanduser' => array(
1720 'code' => 'idanduser',
1721 'info' => "The id and user parameters can't be used together"
1722 ),
1723 'cantunblock' => array(
1724 'code' => 'permissiondenied',
1725 'info' => "You don't have permission to unblock users"
1726 ),
1727 'cannotundelete' => array(
1728 'code' => 'cantundelete',
1729 'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already"
1730 ),
1731 'permdenied-undelete' => array(
1732 'code' => 'permissiondenied',
1733 'info' => "You don't have permission to restore deleted revisions"
1734 ),
1735 'createonly-exists' => array(
1736 'code' => 'articleexists',
1737 'info' => "The article you tried to create has been created already"
1738 ),
1739 'nocreate-missing' => array(
1740 'code' => 'missingtitle',
1741 'info' => "The article you tried to edit doesn't exist"
1742 ),
1743 'nosuchrcid' => array(
1744 'code' => 'nosuchrcid',
1745 'info' => "There is no change with rcid \"\$1\""
1746 ),
1747 'protect-invalidaction' => array(
1748 'code' => 'protect-invalidaction',
1749 'info' => "Invalid protection type \"\$1\""
1750 ),
1751 'protect-invalidlevel' => array(
1752 'code' => 'protect-invalidlevel',
1753 'info' => "Invalid protection level \"\$1\""
1754 ),
1755 'toofewexpiries' => array(
1756 'code' => 'toofewexpiries',
1757 'info' => "\$1 expiry timestamps were provided where \$2 were needed"
1758 ),
1759 'cantimport' => array(
1760 'code' => 'cantimport',
1761 'info' => "You don't have permission to import pages"
1762 ),
1763 'cantimport-upload' => array(
1764 'code' => 'cantimport-upload',
1765 'info' => "You don't have permission to import uploaded pages"
1766 ),
1767 'importnofile' => array( 'code' => 'nofile', 'info' => "You didn't upload a file" ),
1768 'importuploaderrorsize' => array(
1769 'code' => 'filetoobig',
1770 'info' => 'The file you uploaded is bigger than the maximum upload size'
1771 ),
1772 'importuploaderrorpartial' => array(
1773 'code' => 'partialupload',
1774 'info' => 'The file was only partially uploaded'
1775 ),
1776 'importuploaderrortemp' => array(
1777 'code' => 'notempdir',
1778 'info' => 'The temporary upload directory is missing'
1779 ),
1780 'importcantopen' => array(
1781 'code' => 'cantopenfile',
1782 'info' => "Couldn't open the uploaded file"
1783 ),
1784 'import-noarticle' => array(
1785 'code' => 'badinterwiki',
1786 'info' => 'Invalid interwiki title specified'
1787 ),
1788 'importbadinterwiki' => array(
1789 'code' => 'badinterwiki',
1790 'info' => 'Invalid interwiki title specified'
1791 ),
1792 'import-unknownerror' => array(
1793 'code' => 'import-unknownerror',
1794 'info' => "Unknown error on import: \"\$1\""
1795 ),
1796 'cantoverwrite-sharedfile' => array(
1797 'code' => 'cantoverwrite-sharedfile',
1798 'info' => 'The target file exists on a shared repository and you do not have permission to override it'
1799 ),
1800 'sharedfile-exists' => array(
1801 'code' => 'fileexists-sharedrepo-perm',
1802 'info' => 'The target file exists on a shared repository. Use the ignorewarnings parameter to override it.'
1803 ),
1804 'mustbeposted' => array(
1805 'code' => 'mustbeposted',
1806 'info' => "The \$1 module requires a POST request"
1807 ),
1808 'show' => array(
1809 'code' => 'show',
1810 'info' => 'Incorrect parameter - mutually exclusive values may not be supplied'
1811 ),
1812 'specialpage-cantexecute' => array(
1813 'code' => 'specialpage-cantexecute',
1814 'info' => "You don't have permission to view the results of this special page"
1815 ),
1816 'invalidoldimage' => array(
1817 'code' => 'invalidoldimage',
1818 'info' => 'The oldimage parameter has invalid format'
1819 ),
1820 'nodeleteablefile' => array(
1821 'code' => 'nodeleteablefile',
1822 'info' => 'No such old version of the file'
1823 ),
1824 'fileexists-forbidden' => array(
1825 'code' => 'fileexists-forbidden',
1826 'info' => 'A file with name "$1" already exists, and cannot be overwritten.'
1827 ),
1828 'fileexists-shared-forbidden' => array(
1829 'code' => 'fileexists-shared-forbidden',
1830 'info' => 'A file with name "$1" already exists in the shared file repository, and cannot be overwritten.'
1831 ),
1832 'filerevert-badversion' => array(
1833 'code' => 'filerevert-badversion',
1834 'info' => 'There is no previous local version of this file with the provided timestamp.'
1835 ),
1836
1837 // ApiEditPage messages
1838 'noimageredirect-anon' => array(
1839 'code' => 'noimageredirect-anon',
1840 'info' => "Anonymous users can't create image redirects"
1841 ),
1842 'noimageredirect-logged' => array(
1843 'code' => 'noimageredirect',
1844 'info' => "You don't have permission to create image redirects"
1845 ),
1846 'spamdetected' => array(
1847 'code' => 'spamdetected',
1848 'info' => "Your edit was refused because it contained a spam fragment: \"\$1\""
1849 ),
1850 'contenttoobig' => array(
1851 'code' => 'contenttoobig',
1852 'info' => "The content you supplied exceeds the article size limit of \$1 kilobytes"
1853 ),
1854 'noedit-anon' => array( 'code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages" ),
1855 'noedit' => array( 'code' => 'noedit', 'info' => "You don't have permission to edit pages" ),
1856 'wasdeleted' => array(
1857 'code' => 'pagedeleted',
1858 'info' => "The page has been deleted since you fetched its timestamp"
1859 ),
1860 'blankpage' => array(
1861 'code' => 'emptypage',
1862 'info' => "Creating new, empty pages is not allowed"
1863 ),
1864 'editconflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1865 'hashcheckfailed' => array( 'code' => 'badmd5', 'info' => "The supplied MD5 hash was incorrect" ),
1866 'missingtext' => array(
1867 'code' => 'notext',
1868 'info' => "One of the text, appendtext, prependtext and undo parameters must be set"
1869 ),
1870 'emptynewsection' => array(
1871 'code' => 'emptynewsection',
1872 'info' => 'Creating empty new sections is not possible.'
1873 ),
1874 'revwrongpage' => array(
1875 'code' => 'revwrongpage',
1876 'info' => "r\$1 is not a revision of \"\$2\""
1877 ),
1878 'undo-failure' => array(
1879 'code' => 'undofailure',
1880 'info' => 'Undo failed due to conflicting intermediate edits'
1881 ),
1882
1883 // Messages from WikiPage::doEit()
1884 'edit-hook-aborted' => array(
1885 'code' => 'edit-hook-aborted',
1886 'info' => "Your edit was aborted by an ArticleSave hook"
1887 ),
1888 'edit-gone-missing' => array(
1889 'code' => 'edit-gone-missing',
1890 'info' => "The page you tried to edit doesn't seem to exist anymore"
1891 ),
1892 'edit-conflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1893 'edit-already-exists' => array(
1894 'code' => 'edit-already-exists',
1895 'info' => 'It seems the page you tried to create already exist'
1896 ),
1897
1898 // uploadMsgs
1899 'invalid-file-key' => array( 'code' => 'invalid-file-key', 'info' => 'Not a valid file key' ),
1900 'nouploadmodule' => array( 'code' => 'nouploadmodule', 'info' => 'No upload module set' ),
1901 'uploaddisabled' => array(
1902 'code' => 'uploaddisabled',
1903 'info' => 'Uploads are not enabled. Make sure $wgEnableUploads is set to true in LocalSettings.php and the PHP ini setting file_uploads is true'
1904 ),
1905 'copyuploaddisabled' => array(
1906 'code' => 'copyuploaddisabled',
1907 'info' => 'Uploads by URL is not enabled. Make sure $wgAllowCopyUploads is set to true in LocalSettings.php.'
1908 ),
1909 'copyuploadbaddomain' => array(
1910 'code' => 'copyuploadbaddomain',
1911 'info' => 'Uploads by URL are not allowed from this domain.'
1912 ),
1913 'copyuploadbadurl' => array(
1914 'code' => 'copyuploadbadurl',
1915 'info' => 'Upload not allowed from this URL.'
1916 ),
1917
1918 'filename-tooshort' => array(
1919 'code' => 'filename-tooshort',
1920 'info' => 'The filename is too short'
1921 ),
1922 'filename-toolong' => array( 'code' => 'filename-toolong', 'info' => 'The filename is too long' ),
1923 'illegal-filename' => array(
1924 'code' => 'illegal-filename',
1925 'info' => 'The filename is not allowed'
1926 ),
1927 'filetype-missing' => array(
1928 'code' => 'filetype-missing',
1929 'info' => 'The file is missing an extension'
1930 ),
1931
1932 'mustbeloggedin' => array( 'code' => 'mustbeloggedin', 'info' => 'You must be logged in to $1.' )
1933 );
1934 // @codingStandardsIgnoreEnd
1935
1936 /**
1937 * Helper function for readonly errors
1938 */
1939 public function dieReadOnly() {
1940 $parsed = $this->parseMsg( array( 'readonlytext' ) );
1941 $this->dieUsage( $parsed['info'], $parsed['code'], /* http error */ 0,
1942 array( 'readonlyreason' => wfReadOnlyReason() ) );
1943 }
1944
1945 /**
1946 * Output the error message related to a certain array
1947 * @param array|string $error Element of a getUserPermissionsErrors()-style array
1948 */
1949 public function dieUsageMsg( $error ) {
1950 # most of the time we send a 1 element, so we might as well send it as
1951 # a string and make this an array here.
1952 if ( is_string( $error ) ) {
1953 $error = array( $error );
1954 }
1955 $parsed = $this->parseMsg( $error );
1956 $this->dieUsage( $parsed['info'], $parsed['code'] );
1957 }
1958
1959 /**
1960 * Will only set a warning instead of failing if the global $wgDebugAPI
1961 * is set to true. Otherwise behaves exactly as dieUsageMsg().
1962 * @param array|string $error Element of a getUserPermissionsErrors()-style array
1963 * @since 1.21
1964 */
1965 public function dieUsageMsgOrDebug( $error ) {
1966 global $wgDebugAPI;
1967 if ( $wgDebugAPI !== true ) {
1968 $this->dieUsageMsg( $error );
1969 }
1970
1971 if ( is_string( $error ) ) {
1972 $error = array( $error );
1973 }
1974
1975 $parsed = $this->parseMsg( $error );
1976 $this->setWarning( '$wgDebugAPI: ' . $parsed['code'] . ' - ' . $parsed['info'] );
1977 }
1978
1979 /**
1980 * Die with the $prefix.'badcontinue' error. This call is common enough to
1981 * make it into the base method.
1982 * @param bool $condition Will only die if this value is true
1983 * @since 1.21
1984 */
1985 protected function dieContinueUsageIf( $condition ) {
1986 if ( $condition ) {
1987 $this->dieUsage(
1988 'Invalid continue param. You should pass the original value returned by the previous query',
1989 'badcontinue' );
1990 }
1991 }
1992
1993 /**
1994 * Return the error message related to a certain array
1995 * @param array $error Element of a getUserPermissionsErrors()-style array
1996 * @return array('code' => code, 'info' => info)
1997 */
1998 public function parseMsg( $error ) {
1999 $error = (array)$error; // It seems strings sometimes make their way in here
2000 $key = array_shift( $error );
2001
2002 // Check whether the error array was nested
2003 // array( array( <code>, <params> ), array( <another_code>, <params> ) )
2004 if ( is_array( $key ) ) {
2005 $error = $key;
2006 $key = array_shift( $error );
2007 }
2008
2009 if ( isset( self::$messageMap[$key] ) ) {
2010 return array(
2011 'code' => wfMsgReplaceArgs( self::$messageMap[$key]['code'], $error ),
2012 'info' => wfMsgReplaceArgs( self::$messageMap[$key]['info'], $error )
2013 );
2014 }
2015
2016 // If the key isn't present, throw an "unknown error"
2017 return $this->parseMsg( array( 'unknownerror', $key ) );
2018 }
2019
2020 /**
2021 * Internal code errors should be reported with this method
2022 * @param string $method Method or function name
2023 * @param string $message Error message
2024 * @throws MWException
2025 */
2026 protected static function dieDebug( $method, $message ) {
2027 throw new MWException( "Internal error in $method: $message" );
2028 }
2029
2030 /**
2031 * Indicates if this module needs maxlag to be checked
2032 * @return bool
2033 */
2034 public function shouldCheckMaxlag() {
2035 return true;
2036 }
2037
2038 /**
2039 * Indicates whether this module requires read rights
2040 * @return bool
2041 */
2042 public function isReadMode() {
2043 return true;
2044 }
2045
2046 /**
2047 * Indicates whether this module requires write mode
2048 * @return bool
2049 */
2050 public function isWriteMode() {
2051 return false;
2052 }
2053
2054 /**
2055 * Indicates whether this module must be called with a POST request
2056 * @return bool
2057 */
2058 public function mustBePosted() {
2059 return false;
2060 }
2061
2062 /**
2063 * Returns whether this module requires a token to execute
2064 * It is used to show possible errors in action=paraminfo
2065 * see bug 25248
2066 * @return bool
2067 */
2068 public function needsToken() {
2069 return false;
2070 }
2071
2072 /**
2073 * Returns the token salt if there is one,
2074 * '' if the module doesn't require a salt,
2075 * else false if the module doesn't need a token
2076 * You have also to override needsToken()
2077 * Value is passed to User::getEditToken
2078 * @return bool|string|array
2079 */
2080 public function getTokenSalt() {
2081 return false;
2082 }
2083
2084 /**
2085 * Gets the user for whom to get the watchlist
2086 *
2087 * @param array $params
2088 * @return User
2089 */
2090 public function getWatchlistUser( $params ) {
2091 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
2092 $user = User::newFromName( $params['owner'], false );
2093 if ( !( $user && $user->getId() ) ) {
2094 $this->dieUsage( 'Specified user does not exist', 'bad_wlowner' );
2095 }
2096 $token = $user->getOption( 'watchlisttoken' );
2097 if ( $token == '' || $token != $params['token'] ) {
2098 $this->dieUsage(
2099 'Incorrect watchlist token provided -- please set a correct token in Special:Preferences',
2100 'bad_wltoken'
2101 );
2102 }
2103 } else {
2104 if ( !$this->getUser()->isLoggedIn() ) {
2105 $this->dieUsage( 'You must be logged-in to have a watchlist', 'notloggedin' );
2106 }
2107 if ( !$this->getUser()->isAllowed( 'viewmywatchlist' ) ) {
2108 $this->dieUsage( 'You don\'t have permission to view your watchlist', 'permissiondenied' );
2109 }
2110 $user = $this->getUser();
2111 }
2112
2113 return $user;
2114 }
2115
2116 /**
2117 * @return bool|string|array Returns a false if the module has no help URL,
2118 * else returns a (array of) string
2119 */
2120 public function getHelpUrls() {
2121 return false;
2122 }
2123
2124 /**
2125 * Returns a list of all possible errors returned by the module
2126 *
2127 * Don't call this function directly: use getFinalPossibleErrors() to allow
2128 * hooks to modify parameters as needed.
2129 *
2130 * @return array Array in the format of array( key, param1, param2, ... )
2131 * or array( 'code' => ..., 'info' => ... )
2132 */
2133 public function getPossibleErrors() {
2134 $ret = array();
2135
2136 $params = $this->getFinalParams();
2137 if ( $params ) {
2138 foreach ( $params as $paramName => $paramSettings ) {
2139 if ( isset( $paramSettings[ApiBase::PARAM_REQUIRED] )
2140 && $paramSettings[ApiBase::PARAM_REQUIRED]
2141 ) {
2142 $ret[] = array( 'missingparam', $paramName );
2143 }
2144 }
2145 if ( array_key_exists( 'continue', $params ) ) {
2146 $ret[] = array(
2147 'code' => 'badcontinue',
2148 'info' => 'Invalid continue param. You should pass the ' .
2149 'original value returned by the previous query'
2150 );
2151 }
2152 }
2153
2154 if ( $this->mustBePosted() ) {
2155 $ret[] = array( 'mustbeposted', $this->getModuleName() );
2156 }
2157
2158 if ( $this->isReadMode() ) {
2159 $ret[] = array( 'readrequired' );
2160 }
2161
2162 if ( $this->isWriteMode() ) {
2163 $ret[] = array( 'writerequired' );
2164 $ret[] = array( 'writedisabled' );
2165 }
2166
2167 if ( $this->needsToken() ) {
2168 if ( !isset( $params['token'][ApiBase::PARAM_REQUIRED] )
2169 || !$params['token'][ApiBase::PARAM_REQUIRED]
2170 ) {
2171 // Add token as possible missing parameter, if not already done
2172 $ret[] = array( 'missingparam', 'token' );
2173 }
2174 $ret[] = array( 'sessionfailure' );
2175 }
2176
2177 return $ret;
2178 }
2179
2180 /**
2181 * Get final list of possible errors, after hooks have had a chance to
2182 * tweak it as needed.
2183 *
2184 * @return array
2185 * @since 1.22
2186 */
2187 public function getFinalPossibleErrors() {
2188 $possibleErrors = $this->getPossibleErrors();
2189 wfRunHooks( 'APIGetPossibleErrors', array( $this, &$possibleErrors ) );
2190
2191 return $possibleErrors;
2192 }
2193
2194 /**
2195 * Parses a list of errors into a standardised format
2196 * @param array $errors List of errors. Items can be in the for
2197 * array( key, param1, param2, ... ) or array( 'code' => ..., 'info' => ... )
2198 * @return array Parsed list of errors with items in the form array( 'code' => ..., 'info' => ... )
2199 */
2200 public function parseErrors( $errors ) {
2201 $ret = array();
2202
2203 foreach ( $errors as $row ) {
2204 if ( isset( $row['code'] ) && isset( $row['info'] ) ) {
2205 $ret[] = $row;
2206 } else {
2207 $ret[] = $this->parseMsg( $row );
2208 }
2209 }
2210
2211 return $ret;
2212 }
2213
2214 /**
2215 * Profiling: total module execution time
2216 */
2217 private $mTimeIn = 0, $mModuleTime = 0;
2218
2219 /**
2220 * Start module profiling
2221 */
2222 public function profileIn() {
2223 if ( $this->mTimeIn !== 0 ) {
2224 ApiBase::dieDebug( __METHOD__, 'Called twice without calling profileOut()' );
2225 }
2226 $this->mTimeIn = microtime( true );
2227 wfProfileIn( $this->getModuleProfileName() );
2228 }
2229
2230 /**
2231 * End module profiling
2232 */
2233 public function profileOut() {
2234 if ( $this->mTimeIn === 0 ) {
2235 ApiBase::dieDebug( __METHOD__, 'Called without calling profileIn() first' );
2236 }
2237 if ( $this->mDBTimeIn !== 0 ) {
2238 ApiBase::dieDebug(
2239 __METHOD__,
2240 'Must be called after database profiling is done with profileDBOut()'
2241 );
2242 }
2243
2244 $this->mModuleTime += microtime( true ) - $this->mTimeIn;
2245 $this->mTimeIn = 0;
2246 wfProfileOut( $this->getModuleProfileName() );
2247 }
2248
2249 /**
2250 * When modules crash, sometimes it is needed to do a profileOut() regardless
2251 * of the profiling state the module was in. This method does such cleanup.
2252 */
2253 public function safeProfileOut() {
2254 if ( $this->mTimeIn !== 0 ) {
2255 if ( $this->mDBTimeIn !== 0 ) {
2256 $this->profileDBOut();
2257 }
2258 $this->profileOut();
2259 }
2260 }
2261
2262 /**
2263 * Total time the module was executed
2264 * @return float
2265 */
2266 public function getProfileTime() {
2267 if ( $this->mTimeIn !== 0 ) {
2268 ApiBase::dieDebug( __METHOD__, 'Called without calling profileOut() first' );
2269 }
2270
2271 return $this->mModuleTime;
2272 }
2273
2274 /**
2275 * Profiling: database execution time
2276 */
2277 private $mDBTimeIn = 0, $mDBTime = 0;
2278
2279 /**
2280 * Start module profiling
2281 */
2282 public function profileDBIn() {
2283 if ( $this->mTimeIn === 0 ) {
2284 ApiBase::dieDebug(
2285 __METHOD__,
2286 'Must be called while profiling the entire module with profileIn()'
2287 );
2288 }
2289 if ( $this->mDBTimeIn !== 0 ) {
2290 ApiBase::dieDebug( __METHOD__, 'Called twice without calling profileDBOut()' );
2291 }
2292 $this->mDBTimeIn = microtime( true );
2293 wfProfileIn( $this->getModuleProfileName( true ) );
2294 }
2295
2296 /**
2297 * End database profiling
2298 */
2299 public function profileDBOut() {
2300 if ( $this->mTimeIn === 0 ) {
2301 ApiBase::dieDebug( __METHOD__, 'Must be called while profiling ' .
2302 'the entire module with profileIn()' );
2303 }
2304 if ( $this->mDBTimeIn === 0 ) {
2305 ApiBase::dieDebug( __METHOD__, 'Called without calling profileDBIn() first' );
2306 }
2307
2308 $time = microtime( true ) - $this->mDBTimeIn;
2309 $this->mDBTimeIn = 0;
2310
2311 $this->mDBTime += $time;
2312 $this->getMain()->mDBTime += $time;
2313 wfProfileOut( $this->getModuleProfileName( true ) );
2314 }
2315
2316 /**
2317 * Total time the module used the database
2318 * @return float
2319 */
2320 public function getProfileDBTime() {
2321 if ( $this->mDBTimeIn !== 0 ) {
2322 ApiBase::dieDebug( __METHOD__, 'Called without calling profileDBOut() first' );
2323 }
2324
2325 return $this->mDBTime;
2326 }
2327
2328 /**
2329 * Gets a default slave database connection object
2330 * @return DatabaseBase
2331 */
2332 protected function getDB() {
2333 if ( !isset( $this->mSlaveDB ) ) {
2334 $this->profileDBIn();
2335 $this->mSlaveDB = wfGetDB( DB_SLAVE, 'api' );
2336 $this->profileDBOut();
2337 }
2338
2339 return $this->mSlaveDB;
2340 }
2341
2342 /**
2343 * Debugging function that prints a value and an optional backtrace
2344 * @param mixed $value Value to print
2345 * @param string $name Description of the printed value
2346 * @param bool $backtrace If true, print a backtrace
2347 */
2348 public static function debugPrint( $value, $name = 'unknown', $backtrace = false ) {
2349 print "\n\n<pre><b>Debugging value '$name':</b>\n\n";
2350 var_export( $value );
2351 if ( $backtrace ) {
2352 print "\n" . wfBacktrace();
2353 }
2354 print "\n</pre>\n";
2355 }
2356 }