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