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