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