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