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