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