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