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