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