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