Merge "(bug 46059) giving #p-personal a higher z-index than #content in monobook"
[lhc/web/wiklou.git] / includes / api / ApiBase.php
1 <?php
2 /**
3 *
4 *
5 * Created on Sep 5, 2006
6 *
7 * Copyright © 2006, 2010 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
23 *
24 * @file
25 */
26
27 /**
28 * This abstract class implements many basic API functions, and is the base of
29 * all API classes.
30 * The class functions are divided into several areas of functionality:
31 *
32 * Module parameters: Derived classes can define getAllowedParams() to specify
33 * which parameters to expect, how to parse and validate them.
34 *
35 * Profiling: various methods to allow keeping tabs on various tasks and their
36 * time costs
37 *
38 * Self-documentation: code to allow the API to document its own state
39 *
40 * @ingroup API
41 */
42 abstract class ApiBase extends ContextSource {
43
44 // These constants allow modules to specify exactly how to treat incoming parameters.
45
46 const PARAM_DFLT = 0; // Default value of the parameter
47 const PARAM_ISMULTI = 1; // Boolean, do we accept more than one item for this parameter (e.g.: titles)?
48 const PARAM_TYPE = 2; // Can be either a string type (e.g.: 'integer') or an array of allowed values
49 const PARAM_MAX = 3; // Max value allowed for a parameter. Only applies if TYPE='integer'
50 const PARAM_MAX2 = 4; // Max value allowed for a parameter for bots and sysops. Only applies if TYPE='integer'
51 const PARAM_MIN = 5; // Lowest value allowed for a parameter. Only applies if TYPE='integer'
52 const PARAM_ALLOW_DUPLICATES = 6; // Boolean, do we allow the same value to be set more than once when ISMULTI=true
53 const PARAM_DEPRECATED = 7; // Boolean, is the parameter deprecated (will show a warning)
54 /// @since 1.17
55 const PARAM_REQUIRED = 8; // Boolean, is the parameter required?
56 /// @since 1.17
57 const PARAM_RANGE_ENFORCE = 9; // Boolean, if MIN/MAX are set, enforce (die) these? Only applies if TYPE='integer' Use with extreme caution
58
59 const PROP_ROOT = 'ROOT'; // Name of property group that is on the root element of the result, i.e. not part of a list
60 const PROP_LIST = 'LIST'; // Boolean, is the result multiple items? Defaults to true for query modules, to false for other modules
61 const PROP_TYPE = 0; // Type of the property, uses same format as PARAM_TYPE
62 const PROP_NULLABLE = 1; // Boolean, can the property be not included in the result? Defaults to false
63
64 const LIMIT_BIG1 = 500; // Fast query, std user limit
65 const LIMIT_BIG2 = 5000; // Fast query, bot/sysop limit
66 const LIMIT_SML1 = 50; // Slow query, std user limit
67 const LIMIT_SML2 = 500; // Slow query, bot/sysop limit
68
69 /**
70 * getAllowedParams() flag: When set, the result could take longer to generate,
71 * but should be more thorough. E.g. get the list of generators for ApiSandBox extension
72 * @since 1.21
73 */
74 const GET_VALUES_FOR_HELP = 1;
75
76 private $mMainModule, $mModuleName, $mModulePrefix;
77 private $mSlaveDB = null;
78 private $mParamCache = array();
79
80 /**
81 * Constructor
82 * @param $mainModule ApiMain object
83 * @param string $moduleName Name of this module
84 * @param string $modulePrefix Prefix to use for parameter names
85 */
86 public function __construct( $mainModule, $moduleName, $modulePrefix = '' ) {
87 $this->mMainModule = $mainModule;
88 $this->mModuleName = $moduleName;
89 $this->mModulePrefix = $modulePrefix;
90
91 if ( !$this->isMain() ) {
92 $this->setContext( $mainModule->getContext() );
93 }
94 }
95
96 /*****************************************************************************
97 * ABSTRACT METHODS *
98 *****************************************************************************/
99
100 /**
101 * Evaluates the parameters, performs the requested query, and sets up
102 * the result. Concrete implementations of ApiBase must override this
103 * method to provide whatever functionality their module offers.
104 * Implementations must not produce any output on their own and are not
105 * expected to handle any errors.
106 *
107 * The execute() method will be invoked directly by ApiMain immediately
108 * before the result of the module is output. Aside from the
109 * constructor, implementations should assume that no other methods
110 * will be called externally on the module before the result is
111 * processed.
112 *
113 * The result data should be stored in the ApiResult object available
114 * through getResult().
115 */
116 abstract public function execute();
117
118 /**
119 * Returns a string that identifies the version of the extending class.
120 * Typically includes the class name, the svn revision, timestamp, and
121 * last author. Usually done with SVN's Id keyword
122 * @return string
123 * @deprecated since 1.21, version string is no longer supported
124 */
125 public function getVersion() {
126 wfDeprecated( __METHOD__, '1.21' );
127 return '';
128 }
129
130 /**
131 * Get the name of the module being executed by this instance
132 * @return string
133 */
134 public function getModuleName() {
135 return $this->mModuleName;
136 }
137
138 /**
139 * Get the module manager, or null if this module has no sub-modules
140 * @since 1.21
141 * @return ApiModuleManager
142 */
143 public function getModuleManager() {
144 return null;
145 }
146
147 /**
148 * Get parameter prefix (usually two letters or an empty string).
149 * @return string
150 */
151 public function getModulePrefix() {
152 return $this->mModulePrefix;
153 }
154
155 /**
156 * Get the name of the module as shown in the profiler log
157 *
158 * @param $db DatabaseBase|bool
159 *
160 * @return string
161 */
162 public function getModuleProfileName( $db = false ) {
163 if ( $db ) {
164 return 'API:' . $this->mModuleName . '-DB';
165 } else {
166 return 'API:' . $this->mModuleName;
167 }
168 }
169
170 /**
171 * Get the main module
172 * @return ApiMain object
173 */
174 public function getMain() {
175 return $this->mMainModule;
176 }
177
178 /**
179 * Returns true if this module is the main module ($this === $this->mMainModule),
180 * false otherwise.
181 * @return bool
182 */
183 public function isMain() {
184 return $this === $this->mMainModule;
185 }
186
187 /**
188 * Get the result object
189 * @return ApiResult
190 */
191 public function getResult() {
192 // Main module has getResult() method overridden
193 // Safety - avoid infinite loop:
194 if ( $this->isMain() ) {
195 ApiBase::dieDebug( __METHOD__, 'base method was called on main module. ' );
196 }
197 return $this->getMain()->getResult();
198 }
199
200 /**
201 * Get the result data array (read-only)
202 * @return array
203 */
204 public function getResultData() {
205 return $this->getResult()->getData();
206 }
207
208 /**
209 * Create a new RequestContext object to use e.g. for calls to other parts
210 * the software.
211 * The object will have the WebRequest and the User object set to the ones
212 * used in this instance.
213 *
214 * @deprecated since 1.19 use getContext to get the current context
215 * @return DerivativeContext
216 */
217 public function createContext() {
218 wfDeprecated( __METHOD__, '1.19' );
219 return new DerivativeContext( $this->getContext() );
220 }
221
222 /**
223 * Set warning section for this module. Users should monitor this
224 * section to notice any changes in API. Multiple calls to this
225 * function will result in the warning messages being separated by
226 * newlines
227 * @param string $warning Warning message
228 */
229 public function setWarning( $warning ) {
230 $result = $this->getResult();
231 $data = $result->getData();
232 $moduleName = $this->getModuleName();
233 if ( isset( $data['warnings'][$moduleName] ) ) {
234 // Don't add duplicate warnings
235 $oldWarning = $data['warnings'][$moduleName]['*'];
236 $warnPos = strpos( $oldWarning, $warning );
237 // If $warning was found in $oldWarning, check if it starts at 0 or after "\n"
238 if ( $warnPos !== false && ( $warnPos === 0 || $oldWarning[$warnPos - 1] === "\n" ) ) {
239 // Check if $warning is followed by "\n" or the end of the $oldWarning
240 $warnPos += strlen( $warning );
241 if ( strlen( $oldWarning ) <= $warnPos || $oldWarning[$warnPos] === "\n" ) {
242 return;
243 }
244 }
245 // If there is a warning already, append it to the existing one
246 $warning = "$oldWarning\n$warning";
247 }
248 $msg = array();
249 ApiResult::setContent( $msg, $warning );
250 $result->disableSizeCheck();
251 $result->addValue( 'warnings', $moduleName,
252 $msg, ApiResult::OVERRIDE | ApiResult::ADD_ON_TOP );
253 $result->enableSizeCheck();
254 }
255
256 /**
257 * If the module may only be used with a certain format module,
258 * it should override this method to return an instance of that formatter.
259 * A value of null means the default format will be used.
260 * @return mixed instance of a derived class of ApiFormatBase, or null
261 */
262 public function getCustomPrinter() {
263 return null;
264 }
265
266 /**
267 * Generates help message for this module, or false if there is no description
268 * @return mixed string or false
269 */
270 public function makeHelpMsg() {
271 static $lnPrfx = "\n ";
272
273 $msg = $this->getFinalDescription();
274
275 if ( $msg !== false ) {
276
277 if ( !is_array( $msg ) ) {
278 $msg = array(
279 $msg
280 );
281 }
282 $msg = $lnPrfx . implode( $lnPrfx, $msg ) . "\n";
283
284 $msg .= $this->makeHelpArrayToString( $lnPrfx, false, $this->getHelpUrls() );
285
286 if ( $this->isReadMode() ) {
287 $msg .= "\nThis module requires read rights";
288 }
289 if ( $this->isWriteMode() ) {
290 $msg .= "\nThis module requires write rights";
291 }
292 if ( $this->mustBePosted() ) {
293 $msg .= "\nThis module only accepts POST requests";
294 }
295 if ( $this->isReadMode() || $this->isWriteMode() ||
296 $this->mustBePosted() ) {
297 $msg .= "\n";
298 }
299
300 // Parameters
301 $paramsMsg = $this->makeHelpMsgParameters();
302 if ( $paramsMsg !== false ) {
303 $msg .= "Parameters:\n$paramsMsg";
304 }
305
306 $examples = $this->getExamples();
307 if ( $examples !== 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 string $prefix Text to split output items
344 * @param string $title 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 int $flags 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 function 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 string $paramName 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 string $paramName Parameter name
670 * @param bool $parseLimit 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 array $params 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 bool|string $load 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 required 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 string $watchlist Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
820 * @param $titleObj Title the page under consideration
821 * @param string $userOption 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 watchcreations
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 string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
860 * @param $titleObj Title the article's title to change
861 * @param string $userOption 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 string $paramName parameter name
881 * @param array|mixed $paramSettings 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 break;
969 case 'integer': // Force everything using intval() and optionally validate limits
970 $min = isset ( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[self::PARAM_MIN] : null;
971 $max = isset ( $paramSettings[self::PARAM_MAX] ) ? $paramSettings[self::PARAM_MAX] : null;
972 $enforceLimits = isset ( $paramSettings[self::PARAM_RANGE_ENFORCE] )
973 ? $paramSettings[self::PARAM_RANGE_ENFORCE] : false;
974
975 if ( is_array( $value ) ) {
976 $value = array_map( 'intval', $value );
977 if ( !is_null( $min ) || !is_null( $max ) ) {
978 foreach ( $value as &$v ) {
979 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
980 }
981 }
982 } else {
983 $value = intval( $value );
984 if ( !is_null( $min ) || !is_null( $max ) ) {
985 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
986 }
987 }
988 break;
989 case 'limit':
990 if ( !$parseLimit ) {
991 // Don't do any validation whatsoever
992 break;
993 }
994 if ( !isset( $paramSettings[self::PARAM_MAX] ) || !isset( $paramSettings[self::PARAM_MAX2] ) ) {
995 ApiBase::dieDebug( __METHOD__, "MAX1 or MAX2 are not defined for the limit $encParamName" );
996 }
997 if ( $multi ) {
998 ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
999 }
1000 $min = isset( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[self::PARAM_MIN] : 0;
1001 if ( $value == 'max' ) {
1002 $value = $this->getMain()->canApiHighLimits() ? $paramSettings[self::PARAM_MAX2] : $paramSettings[self::PARAM_MAX];
1003 $this->getResult()->setParsedLimit( $this->getModuleName(), $value );
1004 } else {
1005 $value = intval( $value );
1006 $this->validateLimit( $paramName, $value, $min, $paramSettings[self::PARAM_MAX], $paramSettings[self::PARAM_MAX2] );
1007 }
1008 break;
1009 case 'boolean':
1010 if ( $multi ) {
1011 ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
1012 }
1013 break;
1014 case 'timestamp':
1015 if ( is_array( $value ) ) {
1016 foreach ( $value as $key => $val ) {
1017 $value[$key] = $this->validateTimestamp( $val, $encParamName );
1018 }
1019 } else {
1020 $value = $this->validateTimestamp( $value, $encParamName );
1021 }
1022 break;
1023 case 'user':
1024 if ( is_array( $value ) ) {
1025 foreach ( $value as $key => $val ) {
1026 $value[$key] = $this->validateUser( $val, $encParamName );
1027 }
1028 } else {
1029 $value = $this->validateUser( $value, $encParamName );
1030 }
1031 break;
1032 case 'upload': // nothing to do
1033 break;
1034 default:
1035 ApiBase::dieDebug( __METHOD__, "Param $encParamName's type is unknown - $type" );
1036 }
1037 }
1038
1039 // Throw out duplicates if requested
1040 if ( !$dupes && is_array( $value ) ) {
1041 $value = array_unique( $value );
1042 }
1043
1044 // Set a warning if a deprecated parameter has been passed
1045 if ( $deprecated && $value !== false ) {
1046 $this->setWarning( "The $encParamName parameter has been deprecated." );
1047 }
1048 } elseif ( $required ) {
1049 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
1050 }
1051
1052 return $value;
1053 }
1054
1055 /**
1056 * Return an array of values that were given in a 'a|b|c' notation,
1057 * after it optionally validates them against the list allowed values.
1058 *
1059 * @param string $valueName The name of the parameter (for error
1060 * reporting)
1061 * @param $value mixed The value being parsed
1062 * @param bool $allowMultiple Can $value contain more than one value
1063 * separated by '|'?
1064 * @param $allowedValues mixed An array of values to check against. If
1065 * null, all values are accepted.
1066 * @return mixed (allowMultiple ? an_array_of_values : a_single_value)
1067 */
1068 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues ) {
1069 if ( trim( $value ) === '' && $allowMultiple ) {
1070 return array();
1071 }
1072
1073 // This is a bit awkward, but we want to avoid calling canApiHighLimits() because it unstubs $wgUser
1074 $valuesList = explode( '|', $value, self::LIMIT_SML2 + 1 );
1075 $sizeLimit = count( $valuesList ) > self::LIMIT_SML1 && $this->mMainModule->canApiHighLimits() ?
1076 self::LIMIT_SML2 : self::LIMIT_SML1;
1077
1078 if ( self::truncateArray( $valuesList, $sizeLimit ) ) {
1079 $this->setWarning( "Too many values supplied for parameter '$valueName': the limit is $sizeLimit" );
1080 }
1081
1082 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
1083 // Bug 33482 - Allow entries with | in them for non-multiple values
1084 if ( in_array( $value, $allowedValues ) ) {
1085 return $value;
1086 }
1087
1088 $possibleValues = is_array( $allowedValues ) ? "of '" . implode( "', '", $allowedValues ) . "'" : '';
1089 $this->dieUsage( "Only one $possibleValues is allowed for parameter '$valueName'", "multival_$valueName" );
1090 }
1091
1092 if ( is_array( $allowedValues ) ) {
1093 // Check for unknown values
1094 $unknown = array_diff( $valuesList, $allowedValues );
1095 if ( count( $unknown ) ) {
1096 if ( $allowMultiple ) {
1097 $s = count( $unknown ) > 1 ? 's' : '';
1098 $vals = implode( ", ", $unknown );
1099 $this->setWarning( "Unrecognized value$s for parameter '$valueName': $vals" );
1100 } else {
1101 $this->dieUsage( "Unrecognized value for parameter '$valueName': {$valuesList[0]}", "unknown_$valueName" );
1102 }
1103 }
1104 // Now throw them out
1105 $valuesList = array_intersect( $valuesList, $allowedValues );
1106 }
1107
1108 return $allowMultiple ? $valuesList : $valuesList[0];
1109 }
1110
1111 /**
1112 * Validate the value against the minimum and user/bot maximum limits.
1113 * Prints usage info on failure.
1114 * @param string $paramName Parameter name
1115 * @param int $value Parameter value
1116 * @param int|null $min Minimum value
1117 * @param int|null $max Maximum value for users
1118 * @param int $botMax Maximum value for sysops/bots
1119 * @param $enforceLimits Boolean Whether to enforce (die) if value is outside limits
1120 */
1121 function validateLimit( $paramName, &$value, $min, $max, $botMax = null, $enforceLimits = false ) {
1122 if ( !is_null( $min ) && $value < $min ) {
1123
1124 $msg = $this->encodeParamName( $paramName ) . " may not be less than $min (set to $value)";
1125 $this->warnOrDie( $msg, $enforceLimits );
1126 $value = $min;
1127 }
1128
1129 // Minimum is always validated, whereas maximum is checked only if not running in internal call mode
1130 if ( $this->getMain()->isInternalMode() ) {
1131 return;
1132 }
1133
1134 // Optimization: do not check user's bot status unless really needed -- skips db query
1135 // assumes $botMax >= $max
1136 if ( !is_null( $max ) && $value > $max ) {
1137 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1138 if ( $value > $botMax ) {
1139 $msg = $this->encodeParamName( $paramName ) . " may not be over $botMax (set to $value) for bots or sysops";
1140 $this->warnOrDie( $msg, $enforceLimits );
1141 $value = $botMax;
1142 }
1143 } else {
1144 $msg = $this->encodeParamName( $paramName ) . " may not be over $max (set to $value) for users";
1145 $this->warnOrDie( $msg, $enforceLimits );
1146 $value = $max;
1147 }
1148 }
1149 }
1150
1151 /**
1152 * Validate and normalize of parameters of type 'timestamp'
1153 * @param string $value Parameter value
1154 * @param string $encParamName Parameter name
1155 * @return string Validated and normalized parameter
1156 */
1157 function validateTimestamp( $value, $encParamName ) {
1158 $unixTimestamp = wfTimestamp( TS_UNIX, $value );
1159 if ( $unixTimestamp === false ) {
1160 $this->dieUsage( "Invalid value '$value' for timestamp parameter $encParamName", "badtimestamp_{$encParamName}" );
1161 }
1162 return wfTimestamp( TS_MW, $unixTimestamp );
1163 }
1164
1165 /**
1166 * Validate and normalize of parameters of type 'user'
1167 * @param string $value Parameter value
1168 * @param string $encParamName Parameter value
1169 * @return string Validated and normalized parameter
1170 */
1171 private function validateUser( $value, $encParamName ) {
1172 $title = Title::makeTitleSafe( NS_USER, $value );
1173 if ( $title === null ) {
1174 $this->dieUsage( "Invalid value '$value' for user parameter $encParamName", "baduser_{$encParamName}" );
1175 }
1176 return $title->getText();
1177 }
1178
1179 /**
1180 * Adds a warning to the output, else dies
1181 *
1182 * @param $msg String Message to show as a warning, or error message if dying
1183 * @param $enforceLimits Boolean Whether this is an enforce (die)
1184 */
1185 private function warnOrDie( $msg, $enforceLimits = false ) {
1186 if ( $enforceLimits ) {
1187 $this->dieUsage( $msg, 'integeroutofrange' );
1188 } else {
1189 $this->setWarning( $msg );
1190 }
1191 }
1192
1193 /**
1194 * Truncate an array to a certain length.
1195 * @param array $arr Array to truncate
1196 * @param int $limit Maximum length
1197 * @return bool True if the array was truncated, false otherwise
1198 */
1199 public static function truncateArray( &$arr, $limit ) {
1200 $modified = false;
1201 while ( count( $arr ) > $limit ) {
1202 array_pop( $arr );
1203 $modified = true;
1204 }
1205 return $modified;
1206 }
1207
1208 /**
1209 * Throw a UsageException, which will (if uncaught) call the main module's
1210 * error handler and die with an error message.
1211 *
1212 * @param string $description One-line human-readable description of the
1213 * error condition, e.g., "The API requires a valid action parameter"
1214 * @param string $errorCode Brief, arbitrary, stable string to allow easy
1215 * automated identification of the error, e.g., 'unknown_action'
1216 * @param int $httpRespCode HTTP response code
1217 * @param array $extradata Data to add to the "<error>" element; array in ApiResult format
1218 * @throws UsageException
1219 */
1220 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
1221 Profiler::instance()->close();
1222 throw new UsageException( $description, $this->encodeParamName( $errorCode ), $httpRespCode, $extradata );
1223 }
1224
1225 /**
1226 * Array that maps message keys to error messages. $1 and friends are replaced.
1227 */
1228 public static $messageMap = array(
1229 // This one MUST be present, or dieUsageMsg() will recurse infinitely
1230 'unknownerror' => array( 'code' => 'unknownerror', 'info' => "Unknown error: \"\$1\"" ),
1231 'unknownerror-nocode' => array( 'code' => 'unknownerror', 'info' => 'Unknown error' ),
1232
1233 // Messages from Title::getUserPermissionsErrors()
1234 'ns-specialprotected' => array( 'code' => 'unsupportednamespace', 'info' => "Pages in the Special namespace can't be edited" ),
1235 'protectedinterface' => array( 'code' => 'protectednamespace-interface', 'info' => "You're not allowed to edit interface messages" ),
1236 'namespaceprotected' => array( 'code' => 'protectednamespace', 'info' => "You're not allowed to edit pages in the \"\$1\" namespace" ),
1237 'customcssprotected' => array( 'code' => 'customcssprotected', 'info' => "You're not allowed to edit custom CSS pages" ),
1238 'customjsprotected' => array( 'code' => 'customjsprotected', 'info' => "You're not allowed to edit custom JavaScript pages" ),
1239 'cascadeprotected' => array( 'code' => 'cascadeprotected', 'info' => "The page you're trying to edit is protected because it's included in a cascade-protected page" ),
1240 'protectedpagetext' => array( 'code' => 'protectedpage', 'info' => "The \"\$1\" right is required to edit this page" ),
1241 'protect-cantedit' => array( 'code' => 'cantedit', 'info' => "You can't protect this page because you can't edit it" ),
1242 'badaccess-group0' => array( 'code' => 'permissiondenied', 'info' => "Permission denied" ), // Generic permission denied message
1243 'badaccess-groups' => array( 'code' => 'permissiondenied', 'info' => "Permission denied" ),
1244 'titleprotected' => array( 'code' => 'protectedtitle', 'info' => "This title has been protected from creation" ),
1245 'nocreate-loggedin' => array( 'code' => 'cantcreate', 'info' => "You don't have permission to create new pages" ),
1246 'nocreatetext' => array( 'code' => 'cantcreate-anon', 'info' => "Anonymous users can't create new pages" ),
1247 'movenologintext' => array( 'code' => 'cantmove-anon', 'info' => "Anonymous users can't move pages" ),
1248 'movenotallowed' => array( 'code' => 'cantmove', 'info' => "You don't have permission to move pages" ),
1249 'confirmedittext' => array( 'code' => 'confirmemail', 'info' => "You must confirm your email address before you can edit" ),
1250 'blockedtext' => array( 'code' => 'blocked', 'info' => "You have been blocked from editing" ),
1251 'autoblockedtext' => array( 'code' => 'autoblocked', 'info' => "Your IP address has been blocked automatically, because it was used by a blocked user" ),
1252
1253 // Miscellaneous interface messages
1254 'actionthrottledtext' => array( 'code' => 'ratelimited', 'info' => "You've exceeded your rate limit. Please wait some time and try again" ),
1255 'alreadyrolled' => array( 'code' => 'alreadyrolled', 'info' => "The page you tried to rollback was already rolled back" ),
1256 'cantrollback' => array( 'code' => 'onlyauthor', 'info' => "The page you tried to rollback only has one author" ),
1257 'readonlytext' => array( 'code' => 'readonly', 'info' => "The wiki is currently in read-only mode" ),
1258 'sessionfailure' => array( 'code' => 'badtoken', 'info' => "Invalid token" ),
1259 'cannotdelete' => array( 'code' => 'cantdelete', 'info' => "Couldn't delete \"\$1\". Maybe it was deleted already by someone else" ),
1260 'notanarticle' => array( 'code' => 'missingtitle', 'info' => "The page you requested doesn't exist" ),
1261 'selfmove' => array( 'code' => 'selfmove', 'info' => "Can't move a page to itself" ),
1262 'immobile_namespace' => array( 'code' => 'immobilenamespace', 'info' => "You tried to move pages from or to a namespace that is protected from moving" ),
1263 'articleexists' => array( 'code' => 'articleexists', 'info' => "The destination article already exists and is not a redirect to the source article" ),
1264 'protectedpage' => array( 'code' => 'protectedpage', 'info' => "You don't have permission to perform this move" ),
1265 'hookaborted' => array( 'code' => 'hookaborted', 'info' => "The modification you tried to make was aborted by an extension hook" ),
1266 'cantmove-titleprotected' => array( 'code' => 'protectedtitle', 'info' => "The destination article has been protected from creation" ),
1267 'imagenocrossnamespace' => array( 'code' => 'nonfilenamespace', 'info' => "Can't move a file to a non-file namespace" ),
1268 'imagetypemismatch' => array( 'code' => 'filetypemismatch', 'info' => "The new file extension doesn't match its type" ),
1269 // 'badarticleerror' => shouldn't happen
1270 // 'badtitletext' => shouldn't happen
1271 'ip_range_invalid' => array( 'code' => 'invalidrange', 'info' => "Invalid IP range" ),
1272 'range_block_disabled' => array( 'code' => 'rangedisabled', 'info' => "Blocking IP ranges has been disabled" ),
1273 'nosuchusershort' => array( 'code' => 'nosuchuser', 'info' => "The user you specified doesn't exist" ),
1274 'badipaddress' => array( 'code' => 'invalidip', 'info' => "Invalid IP address specified" ),
1275 'ipb_expiry_invalid' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time" ),
1276 'ipb_already_blocked' => array( 'code' => 'alreadyblocked', 'info' => "The user you tried to block was already blocked" ),
1277 'ipb_blocked_as_range' => array( 'code' => 'blockedasrange', 'info' => "IP address \"\$1\" was blocked as part of range \"\$2\". You can't unblock the IP individually, but you can unblock the range as a whole." ),
1278 'ipb_cant_unblock' => array( 'code' => 'cantunblock', 'info' => "The block you specified was not found. It may have been unblocked already" ),
1279 '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" ),
1280 'ipbblocked' => array( 'code' => 'ipbblocked', 'info' => 'You cannot block or unblock users while you are yourself blocked' ),
1281 'ipbnounblockself' => array( 'code' => 'ipbnounblockself', 'info' => 'You are not allowed to unblock yourself' ),
1282 'usermaildisabled' => array( 'code' => 'usermaildisabled', 'info' => "User email has been disabled" ),
1283 'blockedemailuser' => array( 'code' => 'blockedfrommail', 'info' => "You have been blocked from sending email" ),
1284 'notarget' => array( 'code' => 'notarget', 'info' => "You have not specified a valid target for this action" ),
1285 'noemail' => array( 'code' => 'noemail', 'info' => "The user has not specified a valid email address, or has chosen not to receive email from other users" ),
1286 'rcpatroldisabled' => array( 'code' => 'patroldisabled', 'info' => "Patrolling is disabled on this wiki" ),
1287 'markedaspatrollederror-noautopatrol' => array( 'code' => 'noautopatrol', 'info' => "You don't have permission to patrol your own changes" ),
1288 'delete-toobig' => array( 'code' => 'bigdelete', 'info' => "You can't delete this page because it has more than \$1 revisions" ),
1289 'movenotallowedfile' => array( 'code' => 'cantmovefile', 'info' => "You don't have permission to move files" ),
1290 'userrights-no-interwiki' => array( 'code' => 'nointerwikiuserrights', 'info' => "You don't have permission to change user rights on other wikis" ),
1291 'userrights-nodatabase' => array( 'code' => 'nosuchdatabase', 'info' => "Database \"\$1\" does not exist or is not local" ),
1292 'nouserspecified' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1293 'noname' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1294 'summaryrequired' => array( 'code' => 'summaryrequired', 'info' => 'Summary required' ),
1295 'import-rootpage-invalid' => array( 'code' => 'import-rootpage-invalid', 'info' => 'Root page is an invalid title' ),
1296 'import-rootpage-nosubpage' => array( 'code' => 'import-rootpage-nosubpage', 'info' => 'Namespace "$1" of the root page does not allow subpages' ),
1297
1298 // API-specific messages
1299 'readrequired' => array( 'code' => 'readapidenied', 'info' => "You need read permission to use this module" ),
1300 '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" ),
1301 'writerequired' => array( 'code' => 'writeapidenied', 'info' => "You're not allowed to edit this wiki through the API" ),
1302 'missingparam' => array( 'code' => 'no$1', 'info' => "The \$1 parameter must be set" ),
1303 'invalidtitle' => array( 'code' => 'invalidtitle', 'info' => "Bad title \"\$1\"" ),
1304 'nosuchpageid' => array( 'code' => 'nosuchpageid', 'info' => "There is no page with ID \$1" ),
1305 'nosuchrevid' => array( 'code' => 'nosuchrevid', 'info' => "There is no revision with ID \$1" ),
1306 'nosuchuser' => array( 'code' => 'nosuchuser', 'info' => "User \"\$1\" doesn't exist" ),
1307 'invaliduser' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1308 'invalidexpiry' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time \"\$1\"" ),
1309 'pastexpiry' => array( 'code' => 'pastexpiry', 'info' => "Expiry time \"\$1\" is in the past" ),
1310 'create-titleexists' => array( 'code' => 'create-titleexists', 'info' => "Existing titles can't be protected with 'create'" ),
1311 'missingtitle-createonly' => array( 'code' => 'missingtitle-createonly', 'info' => "Missing titles can only be protected with 'create'" ),
1312 'cantblock' => array( 'code' => 'cantblock', 'info' => "You don't have permission to block users" ),
1313 'canthide' => array( 'code' => 'canthide', 'info' => "You don't have permission to hide user names from the block log" ),
1314 'cantblock-email' => array( 'code' => 'cantblock-email', 'info' => "You don't have permission to block users from sending email through the wiki" ),
1315 'unblock-notarget' => array( 'code' => 'notarget', 'info' => "Either the id or the user parameter must be set" ),
1316 'unblock-idanduser' => array( 'code' => 'idanduser', 'info' => "The id and user parameters can't be used together" ),
1317 'cantunblock' => array( 'code' => 'permissiondenied', 'info' => "You don't have permission to unblock users" ),
1318 'cannotundelete' => array( 'code' => 'cantundelete', 'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already" ),
1319 'permdenied-undelete' => array( 'code' => 'permissiondenied', 'info' => "You don't have permission to restore deleted revisions" ),
1320 'createonly-exists' => array( 'code' => 'articleexists', 'info' => "The article you tried to create has been created already" ),
1321 'nocreate-missing' => array( 'code' => 'missingtitle', 'info' => "The article you tried to edit doesn't exist" ),
1322 'nosuchrcid' => array( 'code' => 'nosuchrcid', 'info' => "There is no change with rcid \"\$1\"" ),
1323 'protect-invalidaction' => array( 'code' => 'protect-invalidaction', 'info' => "Invalid protection type \"\$1\"" ),
1324 'protect-invalidlevel' => array( 'code' => 'protect-invalidlevel', 'info' => "Invalid protection level \"\$1\"" ),
1325 'toofewexpiries' => array( 'code' => 'toofewexpiries', 'info' => "\$1 expiry timestamps were provided where \$2 were needed" ),
1326 'cantimport' => array( 'code' => 'cantimport', 'info' => "You don't have permission to import pages" ),
1327 'cantimport-upload' => array( 'code' => 'cantimport-upload', 'info' => "You don't have permission to import uploaded pages" ),
1328 'importnofile' => array( 'code' => 'nofile', 'info' => "You didn't upload a file" ),
1329 'importuploaderrorsize' => array( 'code' => 'filetoobig', 'info' => 'The file you uploaded is bigger than the maximum upload size' ),
1330 'importuploaderrorpartial' => array( 'code' => 'partialupload', 'info' => 'The file was only partially uploaded' ),
1331 'importuploaderrortemp' => array( 'code' => 'notempdir', 'info' => 'The temporary upload directory is missing' ),
1332 'importcantopen' => array( 'code' => 'cantopenfile', 'info' => "Couldn't open the uploaded file" ),
1333 'import-noarticle' => array( 'code' => 'badinterwiki', 'info' => 'Invalid interwiki title specified' ),
1334 'importbadinterwiki' => array( 'code' => 'badinterwiki', 'info' => 'Invalid interwiki title specified' ),
1335 'import-unknownerror' => array( 'code' => 'import-unknownerror', 'info' => "Unknown error on import: \"\$1\"" ),
1336 'cantoverwrite-sharedfile' => array( 'code' => 'cantoverwrite-sharedfile', 'info' => 'The target file exists on a shared repository and you do not have permission to override it' ),
1337 'sharedfile-exists' => array( 'code' => 'fileexists-sharedrepo-perm', 'info' => 'The target file exists on a shared repository. Use the ignorewarnings parameter to override it.' ),
1338 'mustbeposted' => array( 'code' => 'mustbeposted', 'info' => "The \$1 module requires a POST request" ),
1339 'show' => array( 'code' => 'show', 'info' => 'Incorrect parameter - mutually exclusive values may not be supplied' ),
1340 'specialpage-cantexecute' => array( 'code' => 'specialpage-cantexecute', 'info' => "You don't have permission to view the results of this special page" ),
1341 'invalidoldimage' => array( 'code' => 'invalidoldimage', 'info' => 'The oldimage parameter has invalid format' ),
1342 'nodeleteablefile' => array( 'code' => 'nodeleteablefile', 'info' => 'No such old version of the file' ),
1343 'fileexists-forbidden' => array( 'code' => 'fileexists-forbidden', 'info' => 'A file with name "$1" already exists, and cannot be overwritten.' ),
1344 '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.' ),
1345 'filerevert-badversion' => array( 'code' => 'filerevert-badversion', 'info' => 'There is no previous local version of this file with the provided timestamp.' ),
1346
1347 // ApiEditPage messages
1348 'noimageredirect-anon' => array( 'code' => 'noimageredirect-anon', 'info' => "Anonymous users can't create image redirects" ),
1349 'noimageredirect-logged' => array( 'code' => 'noimageredirect', 'info' => "You don't have permission to create image redirects" ),
1350 'spamdetected' => array( 'code' => 'spamdetected', 'info' => "Your edit was refused because it contained a spam fragment: \"\$1\"" ),
1351 'contenttoobig' => array( 'code' => 'contenttoobig', 'info' => "The content you supplied exceeds the article size limit of \$1 kilobytes" ),
1352 'noedit-anon' => array( 'code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages" ),
1353 'noedit' => array( 'code' => 'noedit', 'info' => "You don't have permission to edit pages" ),
1354 'wasdeleted' => array( 'code' => 'pagedeleted', 'info' => "The page has been deleted since you fetched its timestamp" ),
1355 'blankpage' => array( 'code' => 'emptypage', 'info' => "Creating new, empty pages is not allowed" ),
1356 'editconflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1357 'hashcheckfailed' => array( 'code' => 'badmd5', 'info' => "The supplied MD5 hash was incorrect" ),
1358 'missingtext' => array( 'code' => 'notext', 'info' => "One of the text, appendtext, prependtext and undo parameters must be set" ),
1359 'emptynewsection' => array( 'code' => 'emptynewsection', 'info' => 'Creating empty new sections is not possible.' ),
1360 'revwrongpage' => array( 'code' => 'revwrongpage', 'info' => "r\$1 is not a revision of \"\$2\"" ),
1361 'undo-failure' => array( 'code' => 'undofailure', 'info' => 'Undo failed due to conflicting intermediate edits' ),
1362
1363 // Messages from WikiPage::doEit()
1364 'edit-hook-aborted' => array( 'code' => 'edit-hook-aborted', 'info' => "Your edit was aborted by an ArticleSave hook" ),
1365 'edit-gone-missing' => array( 'code' => 'edit-gone-missing', 'info' => "The page you tried to edit doesn't seem to exist anymore" ),
1366 'edit-conflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1367 'edit-already-exists' => array( 'code' => 'edit-already-exists', 'info' => "It seems the page you tried to create already exist" ),
1368
1369 // uploadMsgs
1370 'invalid-file-key' => array( 'code' => 'invalid-file-key', 'info' => 'Not a valid file key' ),
1371 'nouploadmodule' => array( 'code' => 'nouploadmodule', 'info' => 'No upload module set' ),
1372 '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' ),
1373 'copyuploaddisabled' => array( 'code' => 'copyuploaddisabled', 'info' => 'Uploads by URL is not enabled. Make sure $wgAllowCopyUploads is set to true in LocalSettings.php.' ),
1374 'copyuploadbaddomain' => array( 'code' => 'copyuploadbaddomain', 'info' => 'Uploads by URL are not allowed from this domain.' ),
1375
1376 'filename-tooshort' => array( 'code' => 'filename-tooshort', 'info' => 'The filename is too short' ),
1377 'filename-toolong' => array( 'code' => 'filename-toolong', 'info' => 'The filename is too long' ),
1378 'illegal-filename' => array( 'code' => 'illegal-filename', 'info' => 'The filename is not allowed' ),
1379 'filetype-missing' => array( 'code' => 'filetype-missing', 'info' => 'The file is missing an extension' ),
1380
1381 'mustbeloggedin' => array( 'code' => 'mustbeloggedin', 'info' => 'You must be logged in to $1.' )
1382 );
1383
1384 /**
1385 * Helper function for readonly errors
1386 */
1387 public function dieReadOnly() {
1388 $parsed = $this->parseMsg( array( 'readonlytext' ) );
1389 $this->dieUsage( $parsed['info'], $parsed['code'], /* http error */ 0,
1390 array( 'readonlyreason' => wfReadOnlyReason() ) );
1391 }
1392
1393 /**
1394 * Output the error message related to a certain array
1395 * @param $error (array|string) Element of a getUserPermissionsErrors()-style array
1396 */
1397 public function dieUsageMsg( $error ) {
1398 # most of the time we send a 1 element, so we might as well send it as
1399 # a string and make this an array here.
1400 if( is_string( $error ) ) {
1401 $error = array( $error );
1402 }
1403 $parsed = $this->parseMsg( $error );
1404 $this->dieUsage( $parsed['info'], $parsed['code'] );
1405 }
1406
1407 /**
1408 * Will only set a warning instead of failing if the global $wgDebugAPI
1409 * is set to true. Otherwise behaves exactly as dieUsageMsg().
1410 * @param $error (array|string) Element of a getUserPermissionsErrors()-style array
1411 * @since 1.21
1412 */
1413 public function dieUsageMsgOrDebug( $error ) {
1414 global $wgDebugAPI;
1415 if( $wgDebugAPI !== true ) {
1416 $this->dieUsageMsg( $error );
1417 } else {
1418 if( is_string( $error ) ) {
1419 $error = array( $error );
1420 }
1421 $parsed = $this->parseMsg( $error );
1422 $this->setWarning( '$wgDebugAPI: ' . $parsed['code']
1423 . ' - ' . $parsed['info'] );
1424 }
1425 }
1426
1427 /**
1428 * Die with the $prefix.'badcontinue' error. This call is common enough to make it into the base method.
1429 * @param $condition boolean will only die if this value is true
1430 * @since 1.21
1431 */
1432 protected function dieContinueUsageIf( $condition ) {
1433 if ( $condition ) {
1434 $this->dieUsage(
1435 'Invalid continue param. You should pass the original value returned by the previous query',
1436 'badcontinue' );
1437 }
1438 }
1439
1440 /**
1441 * Return the error message related to a certain array
1442 * @param array $error Element of a getUserPermissionsErrors()-style array
1443 * @return array('code' => code, 'info' => info)
1444 */
1445 public function parseMsg( $error ) {
1446 $error = (array)$error; // It seems strings sometimes make their way in here
1447 $key = array_shift( $error );
1448
1449 // Check whether the error array was nested
1450 // array( array( <code>, <params> ), array( <another_code>, <params> ) )
1451 if( is_array( $key ) ) {
1452 $error = $key;
1453 $key = array_shift( $error );
1454 }
1455
1456 if ( isset( self::$messageMap[$key] ) ) {
1457 return array(
1458 'code' => wfMsgReplaceArgs( self::$messageMap[$key]['code'], $error ),
1459 'info' => wfMsgReplaceArgs( self::$messageMap[$key]['info'], $error )
1460 );
1461 }
1462
1463 // If the key isn't present, throw an "unknown error"
1464 return $this->parseMsg( array( 'unknownerror', $key ) );
1465 }
1466
1467 /**
1468 * Internal code errors should be reported with this method
1469 * @param string $method Method or function name
1470 * @param string $message Error message
1471 */
1472 protected static function dieDebug( $method, $message ) {
1473 wfDebugDieBacktrace( "Internal error in $method: $message" );
1474 }
1475
1476 /**
1477 * Indicates if this module needs maxlag to be checked
1478 * @return bool
1479 */
1480 public function shouldCheckMaxlag() {
1481 return true;
1482 }
1483
1484 /**
1485 * Indicates whether this module requires read rights
1486 * @return bool
1487 */
1488 public function isReadMode() {
1489 return true;
1490 }
1491 /**
1492 * Indicates whether this module requires write mode
1493 * @return bool
1494 */
1495 public function isWriteMode() {
1496 return false;
1497 }
1498
1499 /**
1500 * Indicates whether this module must be called with a POST request
1501 * @return bool
1502 */
1503 public function mustBePosted() {
1504 return false;
1505 }
1506
1507 /**
1508 * Returns whether this module requires a token to execute
1509 * It is used to show possible errors in action=paraminfo
1510 * see bug 25248
1511 * @return bool
1512 */
1513 public function needsToken() {
1514 return false;
1515 }
1516
1517 /**
1518 * Returns the token salt if there is one,
1519 * '' if the module doesn't require a salt,
1520 * else false if the module doesn't need a token
1521 * You have also to override needsToken()
1522 * Value is passed to User::getEditToken
1523 * @return bool|string|array
1524 */
1525 public function getTokenSalt() {
1526 return false;
1527 }
1528
1529 /**
1530 * Gets the user for whom to get the watchlist
1531 *
1532 * @param $params array
1533 * @return User
1534 */
1535 public function getWatchlistUser( $params ) {
1536 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1537 $user = User::newFromName( $params['owner'], false );
1538 if ( !( $user && $user->getId() ) ) {
1539 $this->dieUsage( 'Specified user does not exist', 'bad_wlowner' );
1540 }
1541 $token = $user->getOption( 'watchlisttoken' );
1542 if ( $token == '' || $token != $params['token'] ) {
1543 $this->dieUsage( 'Incorrect watchlist token provided -- please set a correct token in Special:Preferences', 'bad_wltoken' );
1544 }
1545 } else {
1546 if ( !$this->getUser()->isLoggedIn() ) {
1547 $this->dieUsage( 'You must be logged-in to have a watchlist', 'notloggedin' );
1548 }
1549 $user = $this->getUser();
1550 }
1551 return $user;
1552 }
1553
1554 /**
1555 * @return bool|string|array Returns a false if the module has no help url, else returns a (array of) string
1556 */
1557 public function getHelpUrls() {
1558 return false;
1559 }
1560
1561 /**
1562 * Returns a list of all possible errors returned by the module
1563 * @return array in the format of array( key, param1, param2, ... ) or array( 'code' => ..., 'info' => ... )
1564 */
1565 public function getPossibleErrors() {
1566 $ret = array();
1567
1568 $params = $this->getFinalParams();
1569 if ( $params ) {
1570 foreach ( $params as $paramName => $paramSettings ) {
1571 if ( isset( $paramSettings[ApiBase::PARAM_REQUIRED] ) && $paramSettings[ApiBase::PARAM_REQUIRED] ) {
1572 $ret[] = array( 'missingparam', $paramName );
1573 }
1574 }
1575 if ( array_key_exists( 'continue', $params ) ) {
1576 $ret[] = array(
1577 array(
1578 'code' => 'badcontinue',
1579 'info' => 'Invalid continue param. You should pass the original value returned by the previous query'
1580 ) );
1581 }
1582 }
1583
1584 if ( $this->mustBePosted() ) {
1585 $ret[] = array( 'mustbeposted', $this->getModuleName() );
1586 }
1587
1588 if ( $this->isReadMode() ) {
1589 $ret[] = array( 'readrequired' );
1590 }
1591
1592 if ( $this->isWriteMode() ) {
1593 $ret[] = array( 'writerequired' );
1594 $ret[] = array( 'writedisabled' );
1595 }
1596
1597 if ( $this->needsToken() ) {
1598 $ret[] = array( 'missingparam', 'token' );
1599 $ret[] = array( 'sessionfailure' );
1600 }
1601
1602 return $ret;
1603 }
1604
1605 /**
1606 * Parses a list of errors into a standardised format
1607 * @param array $errors List of errors. Items can be in the for array( key, param1, param2, ... ) or array( 'code' => ..., 'info' => ... )
1608 * @return array Parsed list of errors with items in the form array( 'code' => ..., 'info' => ... )
1609 */
1610 public function parseErrors( $errors ) {
1611 $ret = array();
1612
1613 foreach ( $errors as $row ) {
1614 if ( isset( $row['code'] ) && isset( $row['info'] ) ) {
1615 $ret[] = $row;
1616 } else {
1617 $ret[] = $this->parseMsg( $row );
1618 }
1619 }
1620 return $ret;
1621 }
1622
1623 /**
1624 * Profiling: total module execution time
1625 */
1626 private $mTimeIn = 0, $mModuleTime = 0;
1627
1628 /**
1629 * Start module profiling
1630 */
1631 public function profileIn() {
1632 if ( $this->mTimeIn !== 0 ) {
1633 ApiBase::dieDebug( __METHOD__, 'called twice without calling profileOut()' );
1634 }
1635 $this->mTimeIn = microtime( true );
1636 wfProfileIn( $this->getModuleProfileName() );
1637 }
1638
1639 /**
1640 * End module profiling
1641 */
1642 public function profileOut() {
1643 if ( $this->mTimeIn === 0 ) {
1644 ApiBase::dieDebug( __METHOD__, 'called without calling profileIn() first' );
1645 }
1646 if ( $this->mDBTimeIn !== 0 ) {
1647 ApiBase::dieDebug( __METHOD__, 'must be called after database profiling is done with profileDBOut()' );
1648 }
1649
1650 $this->mModuleTime += microtime( true ) - $this->mTimeIn;
1651 $this->mTimeIn = 0;
1652 wfProfileOut( $this->getModuleProfileName() );
1653 }
1654
1655 /**
1656 * When modules crash, sometimes it is needed to do a profileOut() regardless
1657 * of the profiling state the module was in. This method does such cleanup.
1658 */
1659 public function safeProfileOut() {
1660 if ( $this->mTimeIn !== 0 ) {
1661 if ( $this->mDBTimeIn !== 0 ) {
1662 $this->profileDBOut();
1663 }
1664 $this->profileOut();
1665 }
1666 }
1667
1668 /**
1669 * Total time the module was executed
1670 * @return float
1671 */
1672 public function getProfileTime() {
1673 if ( $this->mTimeIn !== 0 ) {
1674 ApiBase::dieDebug( __METHOD__, 'called without calling profileOut() first' );
1675 }
1676 return $this->mModuleTime;
1677 }
1678
1679 /**
1680 * Profiling: database execution time
1681 */
1682 private $mDBTimeIn = 0, $mDBTime = 0;
1683
1684 /**
1685 * Start module profiling
1686 */
1687 public function profileDBIn() {
1688 if ( $this->mTimeIn === 0 ) {
1689 ApiBase::dieDebug( __METHOD__, 'must be called while profiling the entire module with profileIn()' );
1690 }
1691 if ( $this->mDBTimeIn !== 0 ) {
1692 ApiBase::dieDebug( __METHOD__, 'called twice without calling profileDBOut()' );
1693 }
1694 $this->mDBTimeIn = microtime( true );
1695 wfProfileIn( $this->getModuleProfileName( true ) );
1696 }
1697
1698 /**
1699 * End database profiling
1700 */
1701 public function profileDBOut() {
1702 if ( $this->mTimeIn === 0 ) {
1703 ApiBase::dieDebug( __METHOD__, 'must be called while profiling the entire module with profileIn()' );
1704 }
1705 if ( $this->mDBTimeIn === 0 ) {
1706 ApiBase::dieDebug( __METHOD__, 'called without calling profileDBIn() first' );
1707 }
1708
1709 $time = microtime( true ) - $this->mDBTimeIn;
1710 $this->mDBTimeIn = 0;
1711
1712 $this->mDBTime += $time;
1713 $this->getMain()->mDBTime += $time;
1714 wfProfileOut( $this->getModuleProfileName( true ) );
1715 }
1716
1717 /**
1718 * Total time the module used the database
1719 * @return float
1720 */
1721 public function getProfileDBTime() {
1722 if ( $this->mDBTimeIn !== 0 ) {
1723 ApiBase::dieDebug( __METHOD__, 'called without calling profileDBOut() first' );
1724 }
1725 return $this->mDBTime;
1726 }
1727
1728 /**
1729 * Gets a default slave database connection object
1730 * @return DatabaseBase
1731 */
1732 protected function getDB() {
1733 if ( !isset( $this->mSlaveDB ) ) {
1734 $this->profileDBIn();
1735 $this->mSlaveDB = wfGetDB( DB_SLAVE, 'api' );
1736 $this->profileDBOut();
1737 }
1738 return $this->mSlaveDB;
1739 }
1740
1741 /**
1742 * Debugging function that prints a value and an optional backtrace
1743 * @param $value mixed Value to print
1744 * @param string $name Description of the printed value
1745 * @param bool $backtrace If true, print a backtrace
1746 */
1747 public static function debugPrint( $value, $name = 'unknown', $backtrace = false ) {
1748 print "\n\n<pre><b>Debugging value '$name':</b>\n\n";
1749 var_export( $value );
1750 if ( $backtrace ) {
1751 print "\n" . wfBacktrace();
1752 }
1753 print "\n</pre>\n";
1754 }
1755 }