Localisation updates from https://translatewiki.net.
[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 // These constants allow modules to specify exactly how to treat incoming parameters.
44
45 // Default value of the parameter
46 const PARAM_DFLT = 0;
47 // Boolean, do we accept more than one item for this parameter (e.g.: titles)?
48 const PARAM_ISMULTI = 1;
49 // Can be either a string type (e.g.: 'integer') or an array of allowed values
50 const PARAM_TYPE = 2;
51 // Max value allowed for a parameter. Only applies if TYPE='integer'
52 const PARAM_MAX = 3;
53 // Max value allowed for a parameter for bots and sysops. Only applies if TYPE='integer'
54 const PARAM_MAX2 = 4;
55 // Lowest value allowed for a parameter. Only applies if TYPE='integer'
56 const PARAM_MIN = 5;
57 // Boolean, do we allow the same value to be set more than once when ISMULTI=true
58 const PARAM_ALLOW_DUPLICATES = 6;
59 // Boolean, is the parameter deprecated (will show a warning)
60 const PARAM_DEPRECATED = 7;
61 /// @since 1.17
62 const PARAM_REQUIRED = 8; // Boolean, is the parameter required?
63 /// @since 1.17
64 // Boolean, if MIN/MAX are set, enforce (die) these?
65 // Only applies if TYPE='integer' Use with extreme caution
66 const PARAM_RANGE_ENFORCE = 9;
67 /// @since 1.25
68 // Specify an alternative i18n message for this help parameter.
69 // Value is $msg for ApiBase::makeMessage()
70 const PARAM_HELP_MSG = 10;
71 /// @since 1.25
72 // Specify additional i18n messages to append to the normal message. Value
73 // is an array of $msg for ApiBase::makeMessage()
74 const PARAM_HELP_MSG_APPEND = 11;
75 /// @since 1.25
76 // Specify additional information tags for the parameter. Value is an array
77 // of arrays, with the first member being the 'tag' for the info and the
78 // remaining members being the values. In the help, this is formatted using
79 // apihelp-{$path}-paraminfo-{$tag}, which is passed $1 = count, $2 =
80 // comma-joined list of values, $3 = module prefix.
81 const PARAM_HELP_MSG_INFO = 12;
82 /// @since 1.25
83 // When PARAM_TYPE is an array, this may be an array mapping those values
84 // to page titles which will be linked in the help.
85 const PARAM_VALUE_LINKS = 13;
86 /// @since 1.25
87 // When PARAM_TYPE is an array, this is an array mapping those values to
88 // $msg for ApiBase::makeMessage(). Any value not having a mapping will use
89 // apihelp-{$path}-paramvalue-{$param}-{$value} is used.
90 const PARAM_HELP_MSG_PER_VALUE = 14;
91
92 const LIMIT_BIG1 = 500; // Fast query, std user limit
93 const LIMIT_BIG2 = 5000; // Fast query, bot/sysop limit
94 const LIMIT_SML1 = 50; // Slow query, std user limit
95 const LIMIT_SML2 = 500; // Slow query, bot/sysop limit
96
97 /**
98 * getAllowedParams() flag: When set, the result could take longer to generate,
99 * but should be more thorough. E.g. get the list of generators for ApiSandBox extension
100 * @since 1.21
101 */
102 const GET_VALUES_FOR_HELP = 1;
103
104 /** @var ApiMain */
105 private $mMainModule;
106 /** @var string */
107 private $mModuleName, $mModulePrefix;
108 private $mSlaveDB = null;
109 private $mParamCache = array();
110
111 /**
112 * @param ApiMain $mainModule
113 * @param string $moduleName Name of this module
114 * @param string $modulePrefix Prefix to use for parameter names
115 */
116 public function __construct( ApiMain $mainModule, $moduleName, $modulePrefix = '' ) {
117 $this->mMainModule = $mainModule;
118 $this->mModuleName = $moduleName;
119 $this->mModulePrefix = $modulePrefix;
120
121 if ( !$this->isMain() ) {
122 $this->setContext( $mainModule->getContext() );
123 }
124 }
125
126
127 /************************************************************************//**
128 * @name Methods to implement
129 * @{
130 */
131
132 /**
133 * Evaluates the parameters, performs the requested query, and sets up
134 * the result. Concrete implementations of ApiBase must override this
135 * method to provide whatever functionality their module offers.
136 * Implementations must not produce any output on their own and are not
137 * expected to handle any errors.
138 *
139 * The execute() method will be invoked directly by ApiMain immediately
140 * before the result of the module is output. Aside from the
141 * constructor, implementations should assume that no other methods
142 * will be called externally on the module before the result is
143 * processed.
144 *
145 * The result data should be stored in the ApiResult object available
146 * through getResult().
147 */
148 abstract public function execute();
149
150 /**
151 * Get the module manager, or null if this module has no sub-modules
152 * @since 1.21
153 * @return ApiModuleManager
154 */
155 public function getModuleManager() {
156 return null;
157 }
158
159 /**
160 * If the module may only be used with a certain format module,
161 * it should override this method to return an instance of that formatter.
162 * A value of null means the default format will be used.
163 * @return mixed Instance of a derived class of ApiFormatBase, or null
164 */
165 public function getCustomPrinter() {
166 return null;
167 }
168
169 /**
170 * Returns usage examples for this module.
171 *
172 * Return value has query strings as keys, with values being either strings
173 * (message key), arrays (message key + parameter), or Message objects.
174 *
175 * Do not call this base class implementation when overriding this method.
176 *
177 * @since 1.25
178 * @return array
179 */
180 protected function getExamplesMessages() {
181 // Fall back to old non-localised method
182 $ret = array();
183
184 $examples = $this->getExamples();
185 if ( $examples ) {
186 if ( !is_array( $examples ) ) {
187 $examples = array( $examples );
188 } elseif ( $examples && ( count( $examples ) & 1 ) == 0 &&
189 array_keys( $examples ) === range( 0, count( $examples ) - 1 ) &&
190 !preg_match( '/^\s*api\.php\?/', $examples[0] )
191 ) {
192 // Fix up the ugly "even numbered elements are description, odd
193 // numbered elemts are the link" format (see doc for self::getExamples)
194 $tmp = array();
195 for ( $i = 0; $i < count( $examples ); $i += 2 ) {
196 $tmp[$examples[$i + 1]] = $examples[$i];
197 }
198 $examples = $tmp;
199 }
200
201 foreach ( $examples as $k => $v ) {
202 if ( is_numeric( $k ) ) {
203 $qs = $v;
204 $msg = '';
205 } else {
206 $qs = $k;
207 $msg = self::escapeWikiText( $v );
208 if ( is_array( $msg ) ) {
209 $msg = join( " ", $msg );
210 }
211 }
212
213 $qs = preg_replace( '/^\s*api\.php\?/', '', $qs );
214 $ret[$qs] = $this->msg( 'api-help-fallback-example', array( $msg ) );
215 }
216 }
217
218 return $ret;
219 }
220
221 /**
222 * Return links to more detailed help pages about the module.
223 * @since 1.25, returning boolean false is deprecated
224 * @return string|array
225 */
226 public function getHelpUrls() {
227 return array();
228 }
229
230 /**
231 * Returns an array of allowed parameters (parameter name) => (default
232 * value) or (parameter name) => (array with PARAM_* constants as keys)
233 * Don't call this function directly: use getFinalParams() to allow
234 * hooks to modify parameters as needed.
235 *
236 * Some derived classes may choose to handle an integer $flags parameter
237 * in the overriding methods. Callers of this method can pass zero or
238 * more OR-ed flags like GET_VALUES_FOR_HELP.
239 *
240 * @return array
241 */
242 protected function getAllowedParams( /* $flags = 0 */ ) {
243 // int $flags is not declared because it causes "Strict standards"
244 // warning. Most derived classes do not implement it.
245 return array();
246 }
247
248 /**
249 * Indicates if this module needs maxlag to be checked
250 * @return bool
251 */
252 public function shouldCheckMaxlag() {
253 return true;
254 }
255
256 /**
257 * Indicates whether this module requires read rights
258 * @return bool
259 */
260 public function isReadMode() {
261 return true;
262 }
263
264 /**
265 * Indicates whether this module requires write mode
266 * @return bool
267 */
268 public function isWriteMode() {
269 return false;
270 }
271
272 /**
273 * Indicates whether this module must be called with a POST request
274 * @return bool
275 */
276 public function mustBePosted() {
277 return $this->needsToken() !== false;
278 }
279
280 /**
281 * Indicates whether this module is deprecated
282 * @since 1.25
283 * @return bool
284 */
285 public function isDeprecated() {
286 return false;
287 }
288
289 /**
290 * Indicates whether this module is "internal"
291 * Internal API modules are not (yet) intended for 3rd party use and may be unstable.
292 * @since 1.25
293 * @return bool
294 */
295 public function isInternal() {
296 return false;
297 }
298
299 /**
300 * Returns the token type this module requires in order to execute.
301 *
302 * Modules are strongly encouraged to use the core 'csrf' type unless they
303 * have specialized security needs. If the token type is not one of the
304 * core types, you must use the ApiQueryTokensRegisterTypes hook to
305 * register it.
306 *
307 * Returning a non-falsey value here will force the addition of an
308 * appropriate 'token' parameter in self::getFinalParams(). Also,
309 * self::mustBePosted() must return true when tokens are used.
310 *
311 * In previous versions of MediaWiki, true was a valid return value.
312 * Returning true will generate errors indicating that the API module needs
313 * updating.
314 *
315 * @return string|false
316 */
317 public function needsToken() {
318 return false;
319 }
320
321 /**
322 * Fetch the salt used in the Web UI corresponding to this module.
323 *
324 * Only override this if the Web UI uses a token with a non-constant salt.
325 *
326 * @since 1.24
327 * @param array $params All supplied parameters for the module
328 * @return string|array|null
329 */
330 protected function getWebUITokenSalt( array $params ) {
331 return null;
332 }
333
334 /**@}*/
335
336 /************************************************************************//**
337 * @name Data access methods
338 * @{
339 */
340
341 /**
342 * Get the name of the module being executed by this instance
343 * @return string
344 */
345 public function getModuleName() {
346 return $this->mModuleName;
347 }
348
349 /**
350 * Get parameter prefix (usually two letters or an empty string).
351 * @return string
352 */
353 public function getModulePrefix() {
354 return $this->mModulePrefix;
355 }
356
357 /**
358 * Get the main module
359 * @return ApiMain
360 */
361 public function getMain() {
362 return $this->mMainModule;
363 }
364
365 /**
366 * Returns true if this module is the main module ($this === $this->mMainModule),
367 * false otherwise.
368 * @return bool
369 */
370 public function isMain() {
371 return $this === $this->mMainModule;
372 }
373
374 /**
375 * Get the parent of this module
376 * @since 1.25
377 * @return ApiBase|null
378 */
379 public function getParent() {
380 return $this->isMain() ? null : $this->getMain();
381 }
382
383 /**
384 * Get the path to this module
385 *
386 * @since 1.25
387 * @return string
388 */
389 public function getModulePath() {
390 if ( $this->isMain() ) {
391 return 'main';
392 } elseif ( $this->getParent()->isMain() ) {
393 return $this->getModuleName();
394 } else {
395 return $this->getParent()->getModulePath() . '+' . $this->getModuleName();
396 }
397 }
398
399 /**
400 * Get a module from its module path
401 *
402 * @since 1.25
403 * @param string $path
404 * @return ApiBase|null
405 * @throws UsageException
406 */
407 public function getModuleFromPath( $path ) {
408 $module = $this->getMain();
409 if ( $path === 'main' ) {
410 return $module;
411 }
412
413 $parts = explode( '+', $path );
414 if ( count( $parts ) === 1 ) {
415 // In case the '+' was typed into URL, it resolves as a space
416 $parts = explode( ' ', $path );
417 }
418
419 $count = count( $parts );
420 for ( $i = 0; $i < $count; $i++ ) {
421 $parent = $module;
422 $manager = $parent->getModuleManager();
423 if ( $manager === null ) {
424 $errorPath = join( '+', array_slice( $parts, 0, $i ) );
425 $this->dieUsage( "The module \"$errorPath\" has no submodules", 'badmodule' );
426 }
427 $module = $manager->getModule( $parts[$i] );
428
429 if ( $module === null ) {
430 $errorPath = $i ? join( '+', array_slice( $parts, 0, $i ) ) : $parent->getModuleName();
431 $this->dieUsage(
432 "The module \"$errorPath\" does not have a submodule \"{$parts[$i]}\"",
433 'badmodule'
434 );
435 }
436 }
437
438 return $module;
439 }
440
441 /**
442 * Get the result object
443 * @return ApiResult
444 */
445 public function getResult() {
446 // Main module has getResult() method overridden
447 // Safety - avoid infinite loop:
448 if ( $this->isMain() ) {
449 ApiBase::dieDebug( __METHOD__, 'base method was called on main module. ' );
450 }
451
452 return $this->getMain()->getResult();
453 }
454
455 /**
456 * Get the result data array (read-only)
457 * @return array
458 */
459 public function getResultData() {
460 return $this->getResult()->getData();
461 }
462
463 /**
464 * Gets a default slave database connection object
465 * @return DatabaseBase
466 */
467 protected function getDB() {
468 if ( !isset( $this->mSlaveDB ) ) {
469 $this->profileDBIn();
470 $this->mSlaveDB = wfGetDB( DB_SLAVE, 'api' );
471 $this->profileDBOut();
472 }
473
474 return $this->mSlaveDB;
475 }
476
477 /**@}*/
478
479 /************************************************************************//**
480 * @name Parameter handling
481 * @{
482 */
483
484 /**
485 * This method mangles parameter name based on the prefix supplied to the constructor.
486 * Override this method to change parameter name during runtime
487 * @param string $paramName Parameter name
488 * @return string Prefixed parameter name
489 */
490 public function encodeParamName( $paramName ) {
491 return $this->mModulePrefix . $paramName;
492 }
493
494 /**
495 * Using getAllowedParams(), this function makes an array of the values
496 * provided by the user, with key being the name of the variable, and
497 * value - validated value from user or default. limits will not be
498 * parsed if $parseLimit is set to false; use this when the max
499 * limit is not definitive yet, e.g. when getting revisions.
500 * @param bool $parseLimit True by default
501 * @return array
502 */
503 public function extractRequestParams( $parseLimit = true ) {
504 // Cache parameters, for performance and to avoid bug 24564.
505 if ( !isset( $this->mParamCache[$parseLimit] ) ) {
506 $params = $this->getFinalParams();
507 $results = array();
508
509 if ( $params ) { // getFinalParams() can return false
510 foreach ( $params as $paramName => $paramSettings ) {
511 $results[$paramName] = $this->getParameterFromSettings(
512 $paramName, $paramSettings, $parseLimit );
513 }
514 }
515 $this->mParamCache[$parseLimit] = $results;
516 }
517
518 return $this->mParamCache[$parseLimit];
519 }
520
521 /**
522 * Get a value for the given parameter
523 * @param string $paramName Parameter name
524 * @param bool $parseLimit See extractRequestParams()
525 * @return mixed Parameter value
526 */
527 protected function getParameter( $paramName, $parseLimit = true ) {
528 $params = $this->getFinalParams();
529 $paramSettings = $params[$paramName];
530
531 return $this->getParameterFromSettings( $paramName, $paramSettings, $parseLimit );
532 }
533
534 /**
535 * Die if none or more than one of a certain set of parameters is set and not false.
536 *
537 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
538 * @param string $required,... Names of parameters of which exactly one must be set
539 */
540 public function requireOnlyOneParameter( $params, $required /*...*/ ) {
541 $required = func_get_args();
542 array_shift( $required );
543 $p = $this->getModulePrefix();
544
545 $intersection = array_intersect( array_keys( array_filter( $params,
546 array( $this, "parameterNotEmpty" ) ) ), $required );
547
548 if ( count( $intersection ) > 1 ) {
549 $this->dieUsage(
550 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
551 'invalidparammix' );
552 } elseif ( count( $intersection ) == 0 ) {
553 $this->dieUsage(
554 "One of the parameters {$p}" . implode( ", {$p}", $required ) . ' is required',
555 'missingparam'
556 );
557 }
558 }
559
560 /**
561 * Die if more than one of a certain set of parameters is set and not false.
562 *
563 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
564 * @param string $required,... Names of parameters of which at most one must be set
565 */
566 public function requireMaxOneParameter( $params, $required /*...*/ ) {
567 $required = func_get_args();
568 array_shift( $required );
569 $p = $this->getModulePrefix();
570
571 $intersection = array_intersect( array_keys( array_filter( $params,
572 array( $this, "parameterNotEmpty" ) ) ), $required );
573
574 if ( count( $intersection ) > 1 ) {
575 $this->dieUsage(
576 "The parameters {$p}" . implode( ", {$p}", $intersection ) . ' can not be used together',
577 'invalidparammix'
578 );
579 }
580 }
581
582 /**
583 * Die if none of a certain set of parameters is set and not false.
584 *
585 * @since 1.23
586 * @param array $params User provided set of parameters, as from $this->extractRequestParams()
587 * @param string $required,... Names of parameters of which at least one must be set
588 */
589 public function requireAtLeastOneParameter( $params, $required /*...*/ ) {
590 $required = func_get_args();
591 array_shift( $required );
592 $p = $this->getModulePrefix();
593
594 $intersection = array_intersect(
595 array_keys( array_filter( $params, array( $this, "parameterNotEmpty" ) ) ),
596 $required
597 );
598
599 if ( count( $intersection ) == 0 ) {
600 $this->dieUsage( "At least one of the parameters {$p}" .
601 implode( ", {$p}", $required ) . ' is required', "{$p}missingparam" );
602 }
603 }
604
605 /**
606 * Callback function used in requireOnlyOneParameter to check whether required parameters are set
607 *
608 * @param object $x Parameter to check is not null/false
609 * @return bool
610 */
611 private function parameterNotEmpty( $x ) {
612 return !is_null( $x ) && $x !== false;
613 }
614
615 /**
616 * Get a WikiPage object from a title or pageid param, if possible.
617 * Can die, if no param is set or if the title or page id is not valid.
618 *
619 * @param array $params
620 * @param bool|string $load Whether load the object's state from the database:
621 * - false: don't load (if the pageid is given, it will still be loaded)
622 * - 'fromdb': load from a slave database
623 * - 'fromdbmaster': load from the master database
624 * @return WikiPage
625 */
626 public function getTitleOrPageId( $params, $load = false ) {
627 $this->requireOnlyOneParameter( $params, 'title', 'pageid' );
628
629 $pageObj = null;
630 if ( isset( $params['title'] ) ) {
631 $titleObj = Title::newFromText( $params['title'] );
632 if ( !$titleObj || $titleObj->isExternal() ) {
633 $this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) );
634 }
635 if ( !$titleObj->canExist() ) {
636 $this->dieUsage( "Namespace doesn't allow actual pages", 'pagecannotexist' );
637 }
638 $pageObj = WikiPage::factory( $titleObj );
639 if ( $load !== false ) {
640 $pageObj->loadPageData( $load );
641 }
642 } elseif ( isset( $params['pageid'] ) ) {
643 if ( $load === false ) {
644 $load = 'fromdb';
645 }
646 $pageObj = WikiPage::newFromID( $params['pageid'], $load );
647 if ( !$pageObj ) {
648 $this->dieUsageMsg( array( 'nosuchpageid', $params['pageid'] ) );
649 }
650 }
651
652 return $pageObj;
653 }
654
655 /**
656 * Return true if we're to watch the page, false if not, null if no change.
657 * @param string $watchlist Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
658 * @param Title $titleObj The page under consideration
659 * @param string $userOption The user option to consider when $watchlist=preferences.
660 * If not set will use watchdefault always and watchcreations if $titleObj doesn't exist.
661 * @return bool
662 */
663 protected function getWatchlistValue( $watchlist, $titleObj, $userOption = null ) {
664
665 $userWatching = $this->getUser()->isWatched( $titleObj, WatchedItem::IGNORE_USER_RIGHTS );
666
667 switch ( $watchlist ) {
668 case 'watch':
669 return true;
670
671 case 'unwatch':
672 return false;
673
674 case 'preferences':
675 # If the user is already watching, don't bother checking
676 if ( $userWatching ) {
677 return true;
678 }
679 # If no user option was passed, use watchdefault and watchcreations
680 if ( is_null( $userOption ) ) {
681 return $this->getUser()->getBoolOption( 'watchdefault' ) ||
682 $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
683 }
684
685 # Watch the article based on the user preference
686 return $this->getUser()->getBoolOption( $userOption );
687
688 case 'nochange':
689 return $userWatching;
690
691 default:
692 return $userWatching;
693 }
694 }
695
696 /**
697 * Using the settings determine the value for the given parameter
698 *
699 * @param string $paramName Parameter name
700 * @param array|mixed $paramSettings Default value or an array of settings
701 * using PARAM_* constants.
702 * @param bool $parseLimit Parse limit?
703 * @return mixed Parameter value
704 */
705 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
706 // Some classes may decide to change parameter names
707 $encParamName = $this->encodeParamName( $paramName );
708
709 if ( !is_array( $paramSettings ) ) {
710 $default = $paramSettings;
711 $multi = false;
712 $type = gettype( $paramSettings );
713 $dupes = false;
714 $deprecated = false;
715 $required = false;
716 } else {
717 $default = isset( $paramSettings[self::PARAM_DFLT] )
718 ? $paramSettings[self::PARAM_DFLT]
719 : null;
720 $multi = isset( $paramSettings[self::PARAM_ISMULTI] )
721 ? $paramSettings[self::PARAM_ISMULTI]
722 : false;
723 $type = isset( $paramSettings[self::PARAM_TYPE] )
724 ? $paramSettings[self::PARAM_TYPE]
725 : null;
726 $dupes = isset( $paramSettings[self::PARAM_ALLOW_DUPLICATES] )
727 ? $paramSettings[self::PARAM_ALLOW_DUPLICATES]
728 : false;
729 $deprecated = isset( $paramSettings[self::PARAM_DEPRECATED] )
730 ? $paramSettings[self::PARAM_DEPRECATED]
731 : false;
732 $required = isset( $paramSettings[self::PARAM_REQUIRED] )
733 ? $paramSettings[self::PARAM_REQUIRED]
734 : false;
735
736 // When type is not given, and no choices, the type is the same as $default
737 if ( !isset( $type ) ) {
738 if ( isset( $default ) ) {
739 $type = gettype( $default );
740 } else {
741 $type = 'NULL'; // allow everything
742 }
743 }
744 }
745
746 if ( $type == 'boolean' ) {
747 if ( isset( $default ) && $default !== false ) {
748 // Having a default value of anything other than 'false' is not allowed
749 ApiBase::dieDebug(
750 __METHOD__,
751 "Boolean param $encParamName's default is set to '$default'. " .
752 "Boolean parameters must default to false."
753 );
754 }
755
756 $value = $this->getMain()->getCheck( $encParamName );
757 } elseif ( $type == 'upload' ) {
758 if ( isset( $default ) ) {
759 // Having a default value is not allowed
760 ApiBase::dieDebug(
761 __METHOD__,
762 "File upload param $encParamName's default is set to " .
763 "'$default'. File upload parameters may not have a default." );
764 }
765 if ( $multi ) {
766 ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
767 }
768 $value = $this->getMain()->getUpload( $encParamName );
769 if ( !$value->exists() ) {
770 // This will get the value without trying to normalize it
771 // (because trying to normalize a large binary file
772 // accidentally uploaded as a field fails spectacularly)
773 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
774 if ( $value !== null ) {
775 $this->dieUsage(
776 "File upload param $encParamName is not a file upload; " .
777 "be sure to use multipart/form-data for your POST and include " .
778 "a filename in the Content-Disposition header.",
779 "badupload_{$encParamName}"
780 );
781 }
782 }
783 } else {
784 $value = $this->getMain()->getVal( $encParamName, $default );
785
786 if ( isset( $value ) && $type == 'namespace' ) {
787 $type = MWNamespace::getValidNamespaces();
788 }
789 if ( isset( $value ) && $type == 'submodule' ) {
790 $type = $this->getModuleManager()->getNames( $paramName );
791 }
792 }
793
794 if ( isset( $value ) && ( $multi || is_array( $type ) ) ) {
795 $value = $this->parseMultiValue(
796 $encParamName,
797 $value,
798 $multi,
799 is_array( $type ) ? $type : null
800 );
801 }
802
803 // More validation only when choices were not given
804 // choices were validated in parseMultiValue()
805 if ( isset( $value ) ) {
806 if ( !is_array( $type ) ) {
807 switch ( $type ) {
808 case 'NULL': // nothing to do
809 break;
810 case 'string':
811 if ( $required && $value === '' ) {
812 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
813 }
814 break;
815 case 'integer': // Force everything using intval() and optionally validate limits
816 $min = isset( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[self::PARAM_MIN] : null;
817 $max = isset( $paramSettings[self::PARAM_MAX] ) ? $paramSettings[self::PARAM_MAX] : null;
818 $enforceLimits = isset( $paramSettings[self::PARAM_RANGE_ENFORCE] )
819 ? $paramSettings[self::PARAM_RANGE_ENFORCE] : false;
820
821 if ( is_array( $value ) ) {
822 $value = array_map( 'intval', $value );
823 if ( !is_null( $min ) || !is_null( $max ) ) {
824 foreach ( $value as &$v ) {
825 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
826 }
827 }
828 } else {
829 $value = intval( $value );
830 if ( !is_null( $min ) || !is_null( $max ) ) {
831 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
832 }
833 }
834 break;
835 case 'limit':
836 if ( !$parseLimit ) {
837 // Don't do any validation whatsoever
838 break;
839 }
840 if ( !isset( $paramSettings[self::PARAM_MAX] )
841 || !isset( $paramSettings[self::PARAM_MAX2] )
842 ) {
843 ApiBase::dieDebug(
844 __METHOD__,
845 "MAX1 or MAX2 are not defined for the limit $encParamName"
846 );
847 }
848 if ( $multi ) {
849 ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
850 }
851 $min = isset( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[self::PARAM_MIN] : 0;
852 if ( $value == 'max' ) {
853 $value = $this->getMain()->canApiHighLimits()
854 ? $paramSettings[self::PARAM_MAX2]
855 : $paramSettings[self::PARAM_MAX];
856 $this->getResult()->setParsedLimit( $this->getModuleName(), $value );
857 } else {
858 $value = intval( $value );
859 $this->validateLimit(
860 $paramName,
861 $value,
862 $min,
863 $paramSettings[self::PARAM_MAX],
864 $paramSettings[self::PARAM_MAX2]
865 );
866 }
867 break;
868 case 'boolean':
869 if ( $multi ) {
870 ApiBase::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
871 }
872 break;
873 case 'timestamp':
874 if ( is_array( $value ) ) {
875 foreach ( $value as $key => $val ) {
876 $value[$key] = $this->validateTimestamp( $val, $encParamName );
877 }
878 } else {
879 $value = $this->validateTimestamp( $value, $encParamName );
880 }
881 break;
882 case 'user':
883 if ( is_array( $value ) ) {
884 foreach ( $value as $key => $val ) {
885 $value[$key] = $this->validateUser( $val, $encParamName );
886 }
887 } else {
888 $value = $this->validateUser( $value, $encParamName );
889 }
890 break;
891 case 'upload': // nothing to do
892 break;
893 default:
894 ApiBase::dieDebug( __METHOD__, "Param $encParamName's type is unknown - $type" );
895 }
896 }
897
898 // Throw out duplicates if requested
899 if ( !$dupes && is_array( $value ) ) {
900 $value = array_unique( $value );
901 }
902
903 // Set a warning if a deprecated parameter has been passed
904 if ( $deprecated && $value !== false ) {
905 $this->setWarning( "The $encParamName parameter has been deprecated." );
906 }
907 } elseif ( $required ) {
908 $this->dieUsageMsg( array( 'missingparam', $paramName ) );
909 }
910
911 return $value;
912 }
913
914 /**
915 * Return an array of values that were given in a 'a|b|c' notation,
916 * after it optionally validates them against the list allowed values.
917 *
918 * @param string $valueName The name of the parameter (for error
919 * reporting)
920 * @param mixed $value The value being parsed
921 * @param bool $allowMultiple Can $value contain more than one value
922 * separated by '|'?
923 * @param string[]|null $allowedValues An array of values to check against. If
924 * null, all values are accepted.
925 * @return string|string[] (allowMultiple ? an_array_of_values : a_single_value)
926 */
927 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues ) {
928 if ( trim( $value ) === '' && $allowMultiple ) {
929 return array();
930 }
931
932 // This is a bit awkward, but we want to avoid calling canApiHighLimits()
933 // because it unstubs $wgUser
934 $valuesList = explode( '|', $value, self::LIMIT_SML2 + 1 );
935 $sizeLimit = count( $valuesList ) > self::LIMIT_SML1 && $this->mMainModule->canApiHighLimits()
936 ? self::LIMIT_SML2
937 : self::LIMIT_SML1;
938
939 if ( self::truncateArray( $valuesList, $sizeLimit ) ) {
940 $this->setWarning( "Too many values supplied for parameter '$valueName': " .
941 "the limit is $sizeLimit" );
942 }
943
944 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
945 // Bug 33482 - Allow entries with | in them for non-multiple values
946 if ( in_array( $value, $allowedValues, true ) ) {
947 return $value;
948 }
949
950 $possibleValues = is_array( $allowedValues )
951 ? "of '" . implode( "', '", $allowedValues ) . "'"
952 : '';
953 $this->dieUsage(
954 "Only one $possibleValues is allowed for parameter '$valueName'",
955 "multival_$valueName"
956 );
957 }
958
959 if ( is_array( $allowedValues ) ) {
960 // Check for unknown values
961 $unknown = array_diff( $valuesList, $allowedValues );
962 if ( count( $unknown ) ) {
963 if ( $allowMultiple ) {
964 $s = count( $unknown ) > 1 ? 's' : '';
965 $vals = implode( ", ", $unknown );
966 $this->setWarning( "Unrecognized value$s for parameter '$valueName': $vals" );
967 } else {
968 $this->dieUsage(
969 "Unrecognized value for parameter '$valueName': {$valuesList[0]}",
970 "unknown_$valueName"
971 );
972 }
973 }
974 // Now throw them out
975 $valuesList = array_intersect( $valuesList, $allowedValues );
976 }
977
978 return $allowMultiple ? $valuesList : $valuesList[0];
979 }
980
981 /**
982 * Validate the value against the minimum and user/bot maximum limits.
983 * Prints usage info on failure.
984 * @param string $paramName Parameter name
985 * @param int $value Parameter value
986 * @param int|null $min Minimum value
987 * @param int|null $max Maximum value for users
988 * @param int $botMax Maximum value for sysops/bots
989 * @param bool $enforceLimits Whether to enforce (die) if value is outside limits
990 */
991 protected function validateLimit( $paramName, &$value, $min, $max, $botMax = null, $enforceLimits = false ) {
992 if ( !is_null( $min ) && $value < $min ) {
993
994 $msg = $this->encodeParamName( $paramName ) . " may not be less than $min (set to $value)";
995 $this->warnOrDie( $msg, $enforceLimits );
996 $value = $min;
997 }
998
999 // Minimum is always validated, whereas maximum is checked only if not
1000 // running in internal call mode
1001 if ( $this->getMain()->isInternalMode() ) {
1002 return;
1003 }
1004
1005 // Optimization: do not check user's bot status unless really needed -- skips db query
1006 // assumes $botMax >= $max
1007 if ( !is_null( $max ) && $value > $max ) {
1008 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1009 if ( $value > $botMax ) {
1010 $msg = $this->encodeParamName( $paramName ) .
1011 " may not be over $botMax (set to $value) for bots or sysops";
1012 $this->warnOrDie( $msg, $enforceLimits );
1013 $value = $botMax;
1014 }
1015 } else {
1016 $msg = $this->encodeParamName( $paramName ) . " may not be over $max (set to $value) for users";
1017 $this->warnOrDie( $msg, $enforceLimits );
1018 $value = $max;
1019 }
1020 }
1021 }
1022
1023 /**
1024 * Validate and normalize of parameters of type 'timestamp'
1025 * @param string $value Parameter value
1026 * @param string $encParamName Parameter name
1027 * @return string Validated and normalized parameter
1028 */
1029 protected function validateTimestamp( $value, $encParamName ) {
1030 $unixTimestamp = wfTimestamp( TS_UNIX, $value );
1031 if ( $unixTimestamp === false ) {
1032 $this->dieUsage(
1033 "Invalid value '$value' for timestamp parameter $encParamName",
1034 "badtimestamp_{$encParamName}"
1035 );
1036 }
1037
1038 return wfTimestamp( TS_MW, $unixTimestamp );
1039 }
1040
1041 /**
1042 * Validate the supplied token.
1043 *
1044 * @since 1.24
1045 * @param string $token Supplied token
1046 * @param array $params All supplied parameters for the module
1047 * @return bool
1048 */
1049 final public function validateToken( $token, array $params ) {
1050 $tokenType = $this->needsToken();
1051 $salts = ApiQueryTokens::getTokenTypeSalts();
1052 if ( !isset( $salts[$tokenType] ) ) {
1053 throw new MWException(
1054 "Module '{$this->getModuleName()}' tried to use token type '$tokenType' " .
1055 'without registering it'
1056 );
1057 }
1058
1059 if ( $this->getUser()->matchEditToken(
1060 $token,
1061 $salts[$tokenType],
1062 $this->getRequest()
1063 ) ) {
1064 return true;
1065 }
1066
1067 $webUiSalt = $this->getWebUITokenSalt( $params );
1068 if ( $webUiSalt !== null && $this->getUser()->matchEditToken(
1069 $token,
1070 $webUiSalt,
1071 $this->getRequest()
1072 ) ) {
1073 return true;
1074 }
1075
1076 return false;
1077 }
1078
1079 /**
1080 * Validate and normalize of parameters of type 'user'
1081 * @param string $value Parameter value
1082 * @param string $encParamName Parameter name
1083 * @return string Validated and normalized parameter
1084 */
1085 private function validateUser( $value, $encParamName ) {
1086 $title = Title::makeTitleSafe( NS_USER, $value );
1087 if ( $title === null ) {
1088 $this->dieUsage(
1089 "Invalid value '$value' for user parameter $encParamName",
1090 "baduser_{$encParamName}"
1091 );
1092 }
1093
1094 return $title->getText();
1095 }
1096
1097 /**@}*/
1098
1099 /************************************************************************//**
1100 * @name Utility methods
1101 * @{
1102 */
1103
1104 /**
1105 * Set a watch (or unwatch) based the based on a watchlist parameter.
1106 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
1107 * @param Title $titleObj The article's title to change
1108 * @param string $userOption The user option to consider when $watch=preferences
1109 */
1110 protected function setWatch( $watch, $titleObj, $userOption = null ) {
1111 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
1112 if ( $value === null ) {
1113 return;
1114 }
1115
1116 WatchAction::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
1117 }
1118
1119 /**
1120 * Truncate an array to a certain length.
1121 * @param array $arr Array to truncate
1122 * @param int $limit Maximum length
1123 * @return bool True if the array was truncated, false otherwise
1124 */
1125 public static function truncateArray( &$arr, $limit ) {
1126 $modified = false;
1127 while ( count( $arr ) > $limit ) {
1128 array_pop( $arr );
1129 $modified = true;
1130 }
1131
1132 return $modified;
1133 }
1134
1135 /**
1136 * Gets the user for whom to get the watchlist
1137 *
1138 * @param array $params
1139 * @return User
1140 */
1141 public function getWatchlistUser( $params ) {
1142 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1143 $user = User::newFromName( $params['owner'], false );
1144 if ( !( $user && $user->getId() ) ) {
1145 $this->dieUsage( 'Specified user does not exist', 'bad_wlowner' );
1146 }
1147 $token = $user->getOption( 'watchlisttoken' );
1148 if ( $token == '' || $token != $params['token'] ) {
1149 $this->dieUsage(
1150 'Incorrect watchlist token provided -- please set a correct token in Special:Preferences',
1151 'bad_wltoken'
1152 );
1153 }
1154 } else {
1155 if ( !$this->getUser()->isLoggedIn() ) {
1156 $this->dieUsage( 'You must be logged-in to have a watchlist', 'notloggedin' );
1157 }
1158 if ( !$this->getUser()->isAllowed( 'viewmywatchlist' ) ) {
1159 $this->dieUsage( 'You don\'t have permission to view your watchlist', 'permissiondenied' );
1160 }
1161 $user = $this->getUser();
1162 }
1163
1164 return $user;
1165 }
1166
1167 /**
1168 * A subset of wfEscapeWikiText for BC texts
1169 *
1170 * @since 1.25
1171 * @param string|array $v
1172 * @return string|array
1173 */
1174 private static function escapeWikiText( $v ) {
1175 if ( is_array( $v ) ) {
1176 return array_map( 'self::escapeWikiText', $v );
1177 } else {
1178 return strtr( $v, array(
1179 '__' => '_&#95;', '{' => '&#123;', '}' => '&#125;',
1180 '[[Category:' => '[[:Category:',
1181 '[[File:' => '[[:File:', '[[Image:' => '[[:Image:',
1182 ) );
1183 }
1184 }
1185
1186 /**
1187 * Create a Message from a string or array
1188 *
1189 * A string is used as a message key. An array has the message key as the
1190 * first value and message parameters as subsequent values.
1191 *
1192 * @since 1.25
1193 * @param string|array|Message $msg
1194 * @param IContextSource $context
1195 * @param array $params
1196 * @return Message|null
1197 */
1198 public static function makeMessage( $msg, IContextSource $context, array $params = null ) {
1199 if ( is_string( $msg ) ) {
1200 $msg = wfMessage( $msg );
1201 } elseif ( is_array( $msg ) ) {
1202 $msg = call_user_func_array( 'wfMessage', $msg );
1203 }
1204 if ( !$msg instanceof Message ) {
1205 return null;
1206 }
1207
1208 $msg->setContext( $context );
1209 if ( $params ) {
1210 $msg->params( $params );
1211 }
1212
1213 return $msg;
1214 }
1215
1216 /**@}*/
1217
1218 /************************************************************************//**
1219 * @name Warning and error reporting
1220 * @{
1221 */
1222
1223 /**
1224 * Set warning section for this module. Users should monitor this
1225 * section to notice any changes in API. Multiple calls to this
1226 * function will result in the warning messages being separated by
1227 * newlines
1228 * @param string $warning Warning message
1229 */
1230 public function setWarning( $warning ) {
1231 $result = $this->getResult();
1232 $data = $result->getData();
1233 $moduleName = $this->getModuleName();
1234 if ( isset( $data['warnings'][$moduleName] ) ) {
1235 // Don't add duplicate warnings
1236 $oldWarning = $data['warnings'][$moduleName]['*'];
1237 $warnPos = strpos( $oldWarning, $warning );
1238 // If $warning was found in $oldWarning, check if it starts at 0 or after "\n"
1239 if ( $warnPos !== false && ( $warnPos === 0 || $oldWarning[$warnPos - 1] === "\n" ) ) {
1240 // Check if $warning is followed by "\n" or the end of the $oldWarning
1241 $warnPos += strlen( $warning );
1242 if ( strlen( $oldWarning ) <= $warnPos || $oldWarning[$warnPos] === "\n" ) {
1243 return;
1244 }
1245 }
1246 // If there is a warning already, append it to the existing one
1247 $warning = "$oldWarning\n$warning";
1248 }
1249 $msg = array();
1250 ApiResult::setContent( $msg, $warning );
1251 $result->addValue( 'warnings', $moduleName,
1252 $msg, ApiResult::OVERRIDE | ApiResult::ADD_ON_TOP | ApiResult::NO_SIZE_CHECK );
1253 }
1254
1255 /**
1256 * Adds a warning to the output, else dies
1257 *
1258 * @param string $msg Message to show as a warning, or error message if dying
1259 * @param bool $enforceLimits Whether this is an enforce (die)
1260 */
1261 private function warnOrDie( $msg, $enforceLimits = false ) {
1262 if ( $enforceLimits ) {
1263 $this->dieUsage( $msg, 'integeroutofrange' );
1264 }
1265
1266 $this->setWarning( $msg );
1267 }
1268
1269 /**
1270 * Throw a UsageException, which will (if uncaught) call the main module's
1271 * error handler and die with an error message.
1272 *
1273 * @param string $description One-line human-readable description of the
1274 * error condition, e.g., "The API requires a valid action parameter"
1275 * @param string $errorCode Brief, arbitrary, stable string to allow easy
1276 * automated identification of the error, e.g., 'unknown_action'
1277 * @param int $httpRespCode HTTP response code
1278 * @param array $extradata Data to add to the "<error>" element; array in ApiResult format
1279 * @throws UsageException
1280 */
1281 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
1282 Profiler::instance()->close();
1283 throw new UsageException(
1284 $description,
1285 $this->encodeParamName( $errorCode ),
1286 $httpRespCode,
1287 $extradata
1288 );
1289 }
1290
1291 /**
1292 * Get error (as code, string) from a Status object.
1293 *
1294 * @since 1.23
1295 * @param Status $status
1296 * @return array Array of code and error string
1297 */
1298 public function getErrorFromStatus( $status ) {
1299 if ( $status->isGood() ) {
1300 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
1301 }
1302
1303 $errors = $status->getErrorsArray();
1304 if ( !$errors ) {
1305 // No errors? Assume the warnings should be treated as errors
1306 $errors = $status->getWarningsArray();
1307 }
1308 if ( !$errors ) {
1309 // Still no errors? Punt
1310 $errors = array( array( 'unknownerror-nocode' ) );
1311 }
1312
1313 // Cannot use dieUsageMsg() because extensions might return custom
1314 // error messages.
1315 if ( $errors[0] instanceof Message ) {
1316 $msg = $errors[0];
1317 $code = $msg->getKey();
1318 } else {
1319 $code = array_shift( $errors[0] );
1320 $msg = wfMessage( $code, $errors[0] );
1321 }
1322 if ( isset( ApiBase::$messageMap[$code] ) ) {
1323 // Translate message to code, for backwards compatibility
1324 $code = ApiBase::$messageMap[$code]['code'];
1325 }
1326
1327 return array( $code, $msg->inLanguage( 'en' )->useDatabase( false )->plain() );
1328 }
1329
1330 /**
1331 * Throw a UsageException based on the errors in the Status object.
1332 *
1333 * @since 1.22
1334 * @param Status $status
1335 * @throws MWException
1336 */
1337 public function dieStatus( $status ) {
1338
1339 list( $code, $msg ) = $this->getErrorFromStatus( $status );
1340 $this->dieUsage( $msg, $code );
1341 }
1342
1343 // @codingStandardsIgnoreStart Allow long lines. Cannot split these.
1344 /**
1345 * Array that maps message keys to error messages. $1 and friends are replaced.
1346 */
1347 public static $messageMap = array(
1348 // This one MUST be present, or dieUsageMsg() will recurse infinitely
1349 'unknownerror' => array( 'code' => 'unknownerror', 'info' => "Unknown error: \"\$1\"" ),
1350 'unknownerror-nocode' => array( 'code' => 'unknownerror', 'info' => 'Unknown error' ),
1351
1352 // Messages from Title::getUserPermissionsErrors()
1353 'ns-specialprotected' => array(
1354 'code' => 'unsupportednamespace',
1355 'info' => "Pages in the Special namespace can't be edited"
1356 ),
1357 'protectedinterface' => array(
1358 'code' => 'protectednamespace-interface',
1359 'info' => "You're not allowed to edit interface messages"
1360 ),
1361 'namespaceprotected' => array(
1362 'code' => 'protectednamespace',
1363 'info' => "You're not allowed to edit pages in the \"\$1\" namespace"
1364 ),
1365 'customcssprotected' => array(
1366 'code' => 'customcssprotected',
1367 'info' => "You're not allowed to edit custom CSS pages"
1368 ),
1369 'customjsprotected' => array(
1370 'code' => 'customjsprotected',
1371 'info' => "You're not allowed to edit custom JavaScript pages"
1372 ),
1373 'cascadeprotected' => array(
1374 'code' => 'cascadeprotected',
1375 'info' => "The page you're trying to edit is protected because it's included in a cascade-protected page"
1376 ),
1377 'protectedpagetext' => array(
1378 'code' => 'protectedpage',
1379 'info' => "The \"\$1\" right is required to edit this page"
1380 ),
1381 'protect-cantedit' => array(
1382 'code' => 'cantedit',
1383 'info' => "You can't protect this page because you can't edit it"
1384 ),
1385 'deleteprotected' => array(
1386 'code' => 'cantedit',
1387 'info' => "You can't delete this page because it has been protected"
1388 ),
1389 'badaccess-group0' => array(
1390 'code' => 'permissiondenied',
1391 'info' => "Permission denied"
1392 ), // Generic permission denied message
1393 'badaccess-groups' => array(
1394 'code' => 'permissiondenied',
1395 'info' => "Permission denied"
1396 ),
1397 'titleprotected' => array(
1398 'code' => 'protectedtitle',
1399 'info' => "This title has been protected from creation"
1400 ),
1401 'nocreate-loggedin' => array(
1402 'code' => 'cantcreate',
1403 'info' => "You don't have permission to create new pages"
1404 ),
1405 'nocreatetext' => array(
1406 'code' => 'cantcreate-anon',
1407 'info' => "Anonymous users can't create new pages"
1408 ),
1409 'movenologintext' => array(
1410 'code' => 'cantmove-anon',
1411 'info' => "Anonymous users can't move pages"
1412 ),
1413 'movenotallowed' => array(
1414 'code' => 'cantmove',
1415 'info' => "You don't have permission to move pages"
1416 ),
1417 'confirmedittext' => array(
1418 'code' => 'confirmemail',
1419 'info' => "You must confirm your email address before you can edit"
1420 ),
1421 'blockedtext' => array(
1422 'code' => 'blocked',
1423 'info' => "You have been blocked from editing"
1424 ),
1425 'autoblockedtext' => array(
1426 'code' => 'autoblocked',
1427 'info' => "Your IP address has been blocked automatically, because it was used by a blocked user"
1428 ),
1429
1430 // Miscellaneous interface messages
1431 'actionthrottledtext' => array(
1432 'code' => 'ratelimited',
1433 'info' => "You've exceeded your rate limit. Please wait some time and try again"
1434 ),
1435 'alreadyrolled' => array(
1436 'code' => 'alreadyrolled',
1437 'info' => "The page you tried to rollback was already rolled back"
1438 ),
1439 'cantrollback' => array(
1440 'code' => 'onlyauthor',
1441 'info' => "The page you tried to rollback only has one author"
1442 ),
1443 'readonlytext' => array(
1444 'code' => 'readonly',
1445 'info' => "The wiki is currently in read-only mode"
1446 ),
1447 'sessionfailure' => array(
1448 'code' => 'badtoken',
1449 'info' => "Invalid token" ),
1450 'cannotdelete' => array(
1451 'code' => 'cantdelete',
1452 'info' => "Couldn't delete \"\$1\". Maybe it was deleted already by someone else"
1453 ),
1454 'notanarticle' => array(
1455 'code' => 'missingtitle',
1456 'info' => "The page you requested doesn't exist"
1457 ),
1458 'selfmove' => array( 'code' => 'selfmove', 'info' => "Can't move a page to itself"
1459 ),
1460 'immobile_namespace' => array(
1461 'code' => 'immobilenamespace',
1462 'info' => "You tried to move pages from or to a namespace that is protected from moving"
1463 ),
1464 'articleexists' => array(
1465 'code' => 'articleexists',
1466 'info' => "The destination article already exists and is not a redirect to the source article"
1467 ),
1468 'protectedpage' => array(
1469 'code' => 'protectedpage',
1470 'info' => "You don't have permission to perform this move"
1471 ),
1472 'hookaborted' => array(
1473 'code' => 'hookaborted',
1474 'info' => "The modification you tried to make was aborted by an extension hook"
1475 ),
1476 'cantmove-titleprotected' => array(
1477 'code' => 'protectedtitle',
1478 'info' => "The destination article has been protected from creation"
1479 ),
1480 'imagenocrossnamespace' => array(
1481 'code' => 'nonfilenamespace',
1482 'info' => "Can't move a file to a non-file namespace"
1483 ),
1484 'imagetypemismatch' => array(
1485 'code' => 'filetypemismatch',
1486 'info' => "The new file extension doesn't match its type"
1487 ),
1488 // 'badarticleerror' => shouldn't happen
1489 // 'badtitletext' => shouldn't happen
1490 'ip_range_invalid' => array( 'code' => 'invalidrange', 'info' => "Invalid IP range" ),
1491 'range_block_disabled' => array(
1492 'code' => 'rangedisabled',
1493 'info' => "Blocking IP ranges has been disabled"
1494 ),
1495 'nosuchusershort' => array(
1496 'code' => 'nosuchuser',
1497 'info' => "The user you specified doesn't exist"
1498 ),
1499 'badipaddress' => array( 'code' => 'invalidip', 'info' => "Invalid IP address specified" ),
1500 'ipb_expiry_invalid' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time" ),
1501 'ipb_already_blocked' => array(
1502 'code' => 'alreadyblocked',
1503 'info' => "The user you tried to block was already blocked"
1504 ),
1505 'ipb_blocked_as_range' => array(
1506 'code' => 'blockedasrange',
1507 'info' => "IP address \"\$1\" was blocked as part of range \"\$2\". You can't unblock the IP individually, but you can unblock the range as a whole."
1508 ),
1509 'ipb_cant_unblock' => array(
1510 'code' => 'cantunblock',
1511 'info' => "The block you specified was not found. It may have been unblocked already"
1512 ),
1513 'mailnologin' => array(
1514 'code' => 'cantsend',
1515 'info' => "You are not logged in, you do not have a confirmed email address, or you are not allowed to send email to other users, so you cannot send email"
1516 ),
1517 'ipbblocked' => array(
1518 'code' => 'ipbblocked',
1519 'info' => 'You cannot block or unblock users while you are yourself blocked'
1520 ),
1521 'ipbnounblockself' => array(
1522 'code' => 'ipbnounblockself',
1523 'info' => 'You are not allowed to unblock yourself'
1524 ),
1525 'usermaildisabled' => array(
1526 'code' => 'usermaildisabled',
1527 'info' => "User email has been disabled"
1528 ),
1529 'blockedemailuser' => array(
1530 'code' => 'blockedfrommail',
1531 'info' => "You have been blocked from sending email"
1532 ),
1533 'notarget' => array(
1534 'code' => 'notarget',
1535 'info' => "You have not specified a valid target for this action"
1536 ),
1537 'noemail' => array(
1538 'code' => 'noemail',
1539 'info' => "The user has not specified a valid email address, or has chosen not to receive email from other users"
1540 ),
1541 'rcpatroldisabled' => array(
1542 'code' => 'patroldisabled',
1543 'info' => "Patrolling is disabled on this wiki"
1544 ),
1545 'markedaspatrollederror-noautopatrol' => array(
1546 'code' => 'noautopatrol',
1547 'info' => "You don't have permission to patrol your own changes"
1548 ),
1549 'delete-toobig' => array(
1550 'code' => 'bigdelete',
1551 'info' => "You can't delete this page because it has more than \$1 revisions"
1552 ),
1553 'movenotallowedfile' => array(
1554 'code' => 'cantmovefile',
1555 'info' => "You don't have permission to move files"
1556 ),
1557 'userrights-no-interwiki' => array(
1558 'code' => 'nointerwikiuserrights',
1559 'info' => "You don't have permission to change user rights on other wikis"
1560 ),
1561 'userrights-nodatabase' => array(
1562 'code' => 'nosuchdatabase',
1563 'info' => "Database \"\$1\" does not exist or is not local"
1564 ),
1565 'nouserspecified' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1566 'noname' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1567 'summaryrequired' => array( 'code' => 'summaryrequired', 'info' => 'Summary required' ),
1568 'import-rootpage-invalid' => array(
1569 'code' => 'import-rootpage-invalid',
1570 'info' => 'Root page is an invalid title'
1571 ),
1572 'import-rootpage-nosubpage' => array(
1573 'code' => 'import-rootpage-nosubpage',
1574 'info' => 'Namespace "$1" of the root page does not allow subpages'
1575 ),
1576
1577 // API-specific messages
1578 'readrequired' => array(
1579 'code' => 'readapidenied',
1580 'info' => "You need read permission to use this module"
1581 ),
1582 'writedisabled' => array(
1583 'code' => 'noapiwrite',
1584 '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"
1585 ),
1586 'writerequired' => array(
1587 'code' => 'writeapidenied',
1588 'info' => "You're not allowed to edit this wiki through the API"
1589 ),
1590 'missingparam' => array( 'code' => 'no$1', 'info' => "The \$1 parameter must be set" ),
1591 'invalidtitle' => array( 'code' => 'invalidtitle', 'info' => "Bad title \"\$1\"" ),
1592 'nosuchpageid' => array( 'code' => 'nosuchpageid', 'info' => "There is no page with ID \$1" ),
1593 'nosuchrevid' => array( 'code' => 'nosuchrevid', 'info' => "There is no revision with ID \$1" ),
1594 'nosuchuser' => array( 'code' => 'nosuchuser', 'info' => "User \"\$1\" doesn't exist" ),
1595 'invaliduser' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1596 'invalidexpiry' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time \"\$1\"" ),
1597 'pastexpiry' => array( 'code' => 'pastexpiry', 'info' => "Expiry time \"\$1\" is in the past" ),
1598 'create-titleexists' => array(
1599 'code' => 'create-titleexists',
1600 'info' => "Existing titles can't be protected with 'create'"
1601 ),
1602 'missingtitle-createonly' => array(
1603 'code' => 'missingtitle-createonly',
1604 'info' => "Missing titles can only be protected with 'create'"
1605 ),
1606 'cantblock' => array( 'code' => 'cantblock',
1607 'info' => "You don't have permission to block users"
1608 ),
1609 'canthide' => array(
1610 'code' => 'canthide',
1611 'info' => "You don't have permission to hide user names from the block log"
1612 ),
1613 'cantblock-email' => array(
1614 'code' => 'cantblock-email',
1615 'info' => "You don't have permission to block users from sending email through the wiki"
1616 ),
1617 'unblock-notarget' => array(
1618 'code' => 'notarget',
1619 'info' => "Either the id or the user parameter must be set"
1620 ),
1621 'unblock-idanduser' => array(
1622 'code' => 'idanduser',
1623 'info' => "The id and user parameters can't be used together"
1624 ),
1625 'cantunblock' => array(
1626 'code' => 'permissiondenied',
1627 'info' => "You don't have permission to unblock users"
1628 ),
1629 'cannotundelete' => array(
1630 'code' => 'cantundelete',
1631 'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already"
1632 ),
1633 'permdenied-undelete' => array(
1634 'code' => 'permissiondenied',
1635 'info' => "You don't have permission to restore deleted revisions"
1636 ),
1637 'createonly-exists' => array(
1638 'code' => 'articleexists',
1639 'info' => "The article you tried to create has been created already"
1640 ),
1641 'nocreate-missing' => array(
1642 'code' => 'missingtitle',
1643 'info' => "The article you tried to edit doesn't exist"
1644 ),
1645 'cantchangecontentmodel' => array(
1646 'code' => 'cantchangecontentmodel',
1647 'info' => "You don't have permission to change the content model of a page"
1648 ),
1649 'nosuchrcid' => array(
1650 'code' => 'nosuchrcid',
1651 'info' => "There is no change with rcid \"\$1\""
1652 ),
1653 'protect-invalidaction' => array(
1654 'code' => 'protect-invalidaction',
1655 'info' => "Invalid protection type \"\$1\""
1656 ),
1657 'protect-invalidlevel' => array(
1658 'code' => 'protect-invalidlevel',
1659 'info' => "Invalid protection level \"\$1\""
1660 ),
1661 'toofewexpiries' => array(
1662 'code' => 'toofewexpiries',
1663 'info' => "\$1 expiry timestamps were provided where \$2 were needed"
1664 ),
1665 'cantimport' => array(
1666 'code' => 'cantimport',
1667 'info' => "You don't have permission to import pages"
1668 ),
1669 'cantimport-upload' => array(
1670 'code' => 'cantimport-upload',
1671 'info' => "You don't have permission to import uploaded pages"
1672 ),
1673 'importnofile' => array( 'code' => 'nofile', 'info' => "You didn't upload a file" ),
1674 'importuploaderrorsize' => array(
1675 'code' => 'filetoobig',
1676 'info' => 'The file you uploaded is bigger than the maximum upload size'
1677 ),
1678 'importuploaderrorpartial' => array(
1679 'code' => 'partialupload',
1680 'info' => 'The file was only partially uploaded'
1681 ),
1682 'importuploaderrortemp' => array(
1683 'code' => 'notempdir',
1684 'info' => 'The temporary upload directory is missing'
1685 ),
1686 'importcantopen' => array(
1687 'code' => 'cantopenfile',
1688 'info' => "Couldn't open the uploaded file"
1689 ),
1690 'import-noarticle' => array(
1691 'code' => 'badinterwiki',
1692 'info' => 'Invalid interwiki title specified'
1693 ),
1694 'importbadinterwiki' => array(
1695 'code' => 'badinterwiki',
1696 'info' => 'Invalid interwiki title specified'
1697 ),
1698 'import-unknownerror' => array(
1699 'code' => 'import-unknownerror',
1700 'info' => "Unknown error on import: \"\$1\""
1701 ),
1702 'cantoverwrite-sharedfile' => array(
1703 'code' => 'cantoverwrite-sharedfile',
1704 'info' => 'The target file exists on a shared repository and you do not have permission to override it'
1705 ),
1706 'sharedfile-exists' => array(
1707 'code' => 'fileexists-sharedrepo-perm',
1708 'info' => 'The target file exists on a shared repository. Use the ignorewarnings parameter to override it.'
1709 ),
1710 'mustbeposted' => array(
1711 'code' => 'mustbeposted',
1712 'info' => "The \$1 module requires a POST request"
1713 ),
1714 'show' => array(
1715 'code' => 'show',
1716 'info' => 'Incorrect parameter - mutually exclusive values may not be supplied'
1717 ),
1718 'specialpage-cantexecute' => array(
1719 'code' => 'specialpage-cantexecute',
1720 'info' => "You don't have permission to view the results of this special page"
1721 ),
1722 'invalidoldimage' => array(
1723 'code' => 'invalidoldimage',
1724 'info' => 'The oldimage parameter has invalid format'
1725 ),
1726 'nodeleteablefile' => array(
1727 'code' => 'nodeleteablefile',
1728 'info' => 'No such old version of the file'
1729 ),
1730 'fileexists-forbidden' => array(
1731 'code' => 'fileexists-forbidden',
1732 'info' => 'A file with name "$1" already exists, and cannot be overwritten.'
1733 ),
1734 'fileexists-shared-forbidden' => array(
1735 'code' => 'fileexists-shared-forbidden',
1736 'info' => 'A file with name "$1" already exists in the shared file repository, and cannot be overwritten.'
1737 ),
1738 'filerevert-badversion' => array(
1739 'code' => 'filerevert-badversion',
1740 'info' => 'There is no previous local version of this file with the provided timestamp.'
1741 ),
1742
1743 // ApiEditPage messages
1744 'noimageredirect-anon' => array(
1745 'code' => 'noimageredirect-anon',
1746 'info' => "Anonymous users can't create image redirects"
1747 ),
1748 'noimageredirect-logged' => array(
1749 'code' => 'noimageredirect',
1750 'info' => "You don't have permission to create image redirects"
1751 ),
1752 'spamdetected' => array(
1753 'code' => 'spamdetected',
1754 'info' => "Your edit was refused because it contained a spam fragment: \"\$1\""
1755 ),
1756 'contenttoobig' => array(
1757 'code' => 'contenttoobig',
1758 'info' => "The content you supplied exceeds the article size limit of \$1 kilobytes"
1759 ),
1760 'noedit-anon' => array( 'code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages" ),
1761 'noedit' => array( 'code' => 'noedit', 'info' => "You don't have permission to edit pages" ),
1762 'wasdeleted' => array(
1763 'code' => 'pagedeleted',
1764 'info' => "The page has been deleted since you fetched its timestamp"
1765 ),
1766 'blankpage' => array(
1767 'code' => 'emptypage',
1768 'info' => "Creating new, empty pages is not allowed"
1769 ),
1770 'editconflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1771 'hashcheckfailed' => array( 'code' => 'badmd5', 'info' => "The supplied MD5 hash was incorrect" ),
1772 'missingtext' => array(
1773 'code' => 'notext',
1774 'info' => "One of the text, appendtext, prependtext and undo parameters must be set"
1775 ),
1776 'emptynewsection' => array(
1777 'code' => 'emptynewsection',
1778 'info' => 'Creating empty new sections is not possible.'
1779 ),
1780 'revwrongpage' => array(
1781 'code' => 'revwrongpage',
1782 'info' => "r\$1 is not a revision of \"\$2\""
1783 ),
1784 'undo-failure' => array(
1785 'code' => 'undofailure',
1786 'info' => 'Undo failed due to conflicting intermediate edits'
1787 ),
1788 'content-not-allowed-here' => array(
1789 'code' => 'contentnotallowedhere',
1790 'info' => 'Content model "$1" is not allowed at title "$2"'
1791 ),
1792
1793 // Messages from WikiPage::doEit()
1794 'edit-hook-aborted' => array(
1795 'code' => 'edit-hook-aborted',
1796 'info' => "Your edit was aborted by an ArticleSave hook"
1797 ),
1798 'edit-gone-missing' => array(
1799 'code' => 'edit-gone-missing',
1800 'info' => "The page you tried to edit doesn't seem to exist anymore"
1801 ),
1802 'edit-conflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
1803 'edit-already-exists' => array(
1804 'code' => 'edit-already-exists',
1805 'info' => 'It seems the page you tried to create already exist'
1806 ),
1807
1808 // uploadMsgs
1809 'invalid-file-key' => array( 'code' => 'invalid-file-key', 'info' => 'Not a valid file key' ),
1810 'nouploadmodule' => array( 'code' => 'nouploadmodule', 'info' => 'No upload module set' ),
1811 'uploaddisabled' => array(
1812 'code' => 'uploaddisabled',
1813 'info' => 'Uploads are not enabled. Make sure $wgEnableUploads is set to true in LocalSettings.php and the PHP ini setting file_uploads is true'
1814 ),
1815 'copyuploaddisabled' => array(
1816 'code' => 'copyuploaddisabled',
1817 'info' => 'Uploads by URL is not enabled. Make sure $wgAllowCopyUploads is set to true in LocalSettings.php.'
1818 ),
1819 'copyuploadbaddomain' => array(
1820 'code' => 'copyuploadbaddomain',
1821 'info' => 'Uploads by URL are not allowed from this domain.'
1822 ),
1823 'copyuploadbadurl' => array(
1824 'code' => 'copyuploadbadurl',
1825 'info' => 'Upload not allowed from this URL.'
1826 ),
1827
1828 'filename-tooshort' => array(
1829 'code' => 'filename-tooshort',
1830 'info' => 'The filename is too short'
1831 ),
1832 'filename-toolong' => array( 'code' => 'filename-toolong', 'info' => 'The filename is too long' ),
1833 'illegal-filename' => array(
1834 'code' => 'illegal-filename',
1835 'info' => 'The filename is not allowed'
1836 ),
1837 'filetype-missing' => array(
1838 'code' => 'filetype-missing',
1839 'info' => 'The file is missing an extension'
1840 ),
1841
1842 'mustbeloggedin' => array( 'code' => 'mustbeloggedin', 'info' => 'You must be logged in to $1.' )
1843 );
1844 // @codingStandardsIgnoreEnd
1845
1846 /**
1847 * Helper function for readonly errors
1848 */
1849 public function dieReadOnly() {
1850 $parsed = $this->parseMsg( array( 'readonlytext' ) );
1851 $this->dieUsage( $parsed['info'], $parsed['code'], /* http error */ 0,
1852 array( 'readonlyreason' => wfReadOnlyReason() ) );
1853 }
1854
1855 /**
1856 * Output the error message related to a certain array
1857 * @param array|string $error Element of a getUserPermissionsErrors()-style array
1858 */
1859 public function dieUsageMsg( $error ) {
1860 # most of the time we send a 1 element, so we might as well send it as
1861 # a string and make this an array here.
1862 if ( is_string( $error ) ) {
1863 $error = array( $error );
1864 }
1865 $parsed = $this->parseMsg( $error );
1866 $this->dieUsage( $parsed['info'], $parsed['code'] );
1867 }
1868
1869 /**
1870 * Will only set a warning instead of failing if the global $wgDebugAPI
1871 * is set to true. Otherwise behaves exactly as dieUsageMsg().
1872 * @param array|string $error Element of a getUserPermissionsErrors()-style array
1873 * @since 1.21
1874 */
1875 public function dieUsageMsgOrDebug( $error ) {
1876 if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
1877 $this->dieUsageMsg( $error );
1878 }
1879
1880 if ( is_string( $error ) ) {
1881 $error = array( $error );
1882 }
1883 $parsed = $this->parseMsg( $error );
1884 $this->setWarning( '$wgDebugAPI: ' . $parsed['code'] . ' - ' . $parsed['info'] );
1885 }
1886
1887 /**
1888 * Die with the $prefix.'badcontinue' error. This call is common enough to
1889 * make it into the base method.
1890 * @param bool $condition Will only die if this value is true
1891 * @since 1.21
1892 */
1893 protected function dieContinueUsageIf( $condition ) {
1894 if ( $condition ) {
1895 $this->dieUsage(
1896 'Invalid continue param. You should pass the original value returned by the previous query',
1897 'badcontinue' );
1898 }
1899 }
1900
1901 /**
1902 * Return the error message related to a certain array
1903 * @param array $error Element of a getUserPermissionsErrors()-style array
1904 * @return array('code' => code, 'info' => info)
1905 */
1906 public function parseMsg( $error ) {
1907 $error = (array)$error; // It seems strings sometimes make their way in here
1908 $key = array_shift( $error );
1909
1910 // Check whether the error array was nested
1911 // array( array( <code>, <params> ), array( <another_code>, <params> ) )
1912 if ( is_array( $key ) ) {
1913 $error = $key;
1914 $key = array_shift( $error );
1915 }
1916
1917 if ( isset( self::$messageMap[$key] ) ) {
1918 return array(
1919 'code' => wfMsgReplaceArgs( self::$messageMap[$key]['code'], $error ),
1920 'info' => wfMsgReplaceArgs( self::$messageMap[$key]['info'], $error )
1921 );
1922 }
1923
1924 // If the key isn't present, throw an "unknown error"
1925 return $this->parseMsg( array( 'unknownerror', $key ) );
1926 }
1927
1928 /**
1929 * Internal code errors should be reported with this method
1930 * @param string $method Method or function name
1931 * @param string $message Error message
1932 * @throws MWException
1933 */
1934 protected static function dieDebug( $method, $message ) {
1935 throw new MWException( "Internal error in $method: $message" );
1936 }
1937
1938 /**@}*/
1939
1940 /************************************************************************//**
1941 * @name Help message generation
1942 * @{
1943 */
1944
1945 /**
1946 * Return the description message.
1947 *
1948 * @return string|array|Message
1949 */
1950 protected function getDescriptionMessage() {
1951 return "apihelp-{$this->getModulePath()}-description";
1952 }
1953
1954 /**
1955 * Get final module description, after hooks have had a chance to tweak it as
1956 * needed.
1957 *
1958 * @since 1.25, returns Message[] rather than string[]
1959 * @return Message[]
1960 */
1961 public function getFinalDescription() {
1962 $desc = $this->getDescription();
1963 Hooks::run( 'APIGetDescription', array( &$this, &$desc ) );
1964 $desc = self::escapeWikiText( $desc );
1965 if ( is_array( $desc ) ) {
1966 $desc = join( "\n", $desc );
1967 } else {
1968 $desc = (string)$desc;
1969 }
1970
1971 $msg = ApiBase::makeMessage( $this->getDescriptionMessage(), $this->getContext(), array(
1972 $this->getModulePrefix(),
1973 $this->getModuleName(),
1974 $this->getModulePath(),
1975 ) );
1976 if ( !$msg->exists() ) {
1977 $msg = $this->msg( 'api-help-fallback-description', $desc );
1978 }
1979 $msgs = array( $msg );
1980
1981 Hooks::run( 'APIGetDescriptionMessages', array( $this, &$msgs ) );
1982
1983 return $msgs;
1984 }
1985
1986 /**
1987 * Get final list of parameters, after hooks have had a chance to
1988 * tweak it as needed.
1989 *
1990 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
1991 * @return array|bool False on no parameters
1992 * @since 1.21 $flags param added
1993 */
1994 public function getFinalParams( $flags = 0 ) {
1995 $params = $this->getAllowedParams( $flags );
1996 if ( !$params ) {
1997 $params = array();
1998 }
1999
2000 if ( $this->needsToken() ) {
2001 $params['token'] = array(
2002 ApiBase::PARAM_TYPE => 'string',
2003 ApiBase::PARAM_REQUIRED => true,
2004 ApiBase::PARAM_HELP_MSG => array(
2005 'api-help-param-token',
2006 $this->needsToken(),
2007 ),
2008 ) + ( isset( $params['token'] ) ? $params['token'] : array() );
2009 }
2010
2011 Hooks::run( 'APIGetAllowedParams', array( &$this, &$params, $flags ) );
2012
2013 return $params;
2014 }
2015
2016 /**
2017 * Get final parameter descriptions, after hooks have had a chance to tweak it as
2018 * needed.
2019 *
2020 * @since 1.25, returns array of Message[] rather than array of string[]
2021 * @return array Keys are parameter names, values are arrays of Message objects
2022 */
2023 public function getFinalParamDescription() {
2024 $prefix = $this->getModulePrefix();
2025 $name = $this->getModuleName();
2026 $path = $this->getModulePath();
2027
2028 $desc = $this->getParamDescription();
2029 Hooks::run( 'APIGetParamDescription', array( &$this, &$desc ) );
2030
2031 if ( !$desc ) {
2032 $desc = array();
2033 }
2034 $desc = self::escapeWikiText( $desc );
2035
2036 $params = $this->getFinalParams( ApiBase::GET_VALUES_FOR_HELP );
2037 $msgs = array();
2038 foreach ( $params as $param => $settings ) {
2039 if ( !is_array( $settings ) ) {
2040 $settings = array();
2041 }
2042
2043 $d = isset( $desc[$param] ) ? $desc[$param] : '';
2044 if ( is_array( $d ) ) {
2045 // Special handling for prop parameters
2046 $d = array_map( function ( $line ) {
2047 if ( preg_match( '/^\s+(\S+)\s+-\s+(.+)$/', $line, $m ) ) {
2048 $line = "\n;{$m[1]}:{$m[2]}";
2049 }
2050 return $line;
2051 }, $d );
2052 $d = join( ' ', $d );
2053 }
2054
2055 if ( isset( $settings[ApiBase::PARAM_HELP_MSG] ) ) {
2056 $msg = $settings[ApiBase::PARAM_HELP_MSG];
2057 } else {
2058 $msg = $this->msg( "apihelp-{$path}-param-{$param}" );
2059 if ( !$msg->exists() ) {
2060 $msg = $this->msg( 'api-help-fallback-parameter', $d );
2061 }
2062 }
2063 $msg = ApiBase::makeMessage( $msg, $this->getContext(),
2064 array( $prefix, $param, $name, $path ) );
2065 if ( !$msg ) {
2066 $this->dieDebug( __METHOD__,
2067 'Value in ApiBase::PARAM_HELP_MSG is not valid' );
2068 }
2069 $msgs[$param] = array( $msg );
2070
2071 if ( isset( $settings[ApiBase::PARAM_HELP_MSG_PER_VALUE] ) ) {
2072 if ( !is_array( $settings[ApiBase::PARAM_HELP_MSG_PER_VALUE] ) ) {
2073 $this->dieDebug( __METHOD__,
2074 'ApiBase::PARAM_HELP_MSG_PER_VALUE is not valid' );
2075 }
2076 if ( !is_array( $settings[ApiBase::PARAM_TYPE] ) ) {
2077 $this->dieDebug( __METHOD__,
2078 'ApiBase::PARAM_HELP_MSG_PER_VALUE may only be used when ' .
2079 'ApiBase::PARAM_TYPE is an array' );
2080 }
2081
2082 $valueMsgs = $settings[ApiBase::PARAM_HELP_MSG_PER_VALUE];
2083 foreach ( $settings[ApiBase::PARAM_TYPE] as $value ) {
2084 if ( isset( $valueMsgs[$value] ) ) {
2085 $msg = $valueMsgs[$value];
2086 } else {
2087 $msg = "apihelp-{$path}-paramvalue-{$param}-{$value}";
2088 }
2089 $m = ApiBase::makeMessage( $msg, $this->getContext(),
2090 array( $prefix, $param, $name, $path, $value ) );
2091 if ( $m ) {
2092 $m = new ApiHelpParamValueMessage(
2093 $value,
2094 array( $m->getKey(), 'api-help-param-no-description' ),
2095 $m->getParams()
2096 );
2097 $msgs[$param][] = $m->setContext( $this->getContext() );
2098 } else {
2099 $this->dieDebug( __METHOD__,
2100 "Value in ApiBase::PARAM_HELP_MSG_PER_VALUE for $value is not valid" );
2101 }
2102 }
2103 }
2104
2105 if ( isset( $settings[ApiBase::PARAM_HELP_MSG_APPEND] ) ) {
2106 if ( !is_array( $settings[ApiBase::PARAM_HELP_MSG_APPEND] ) ) {
2107 $this->dieDebug( __METHOD__,
2108 'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
2109 }
2110 foreach ( $settings[ApiBase::PARAM_HELP_MSG_APPEND] as $m ) {
2111 $m = ApiBase::makeMessage( $m, $this->getContext(),
2112 array( $prefix, $param, $name, $path ) );
2113 if ( $m ) {
2114 $msgs[$param][] = $m;
2115 } else {
2116 $this->dieDebug( __METHOD__,
2117 'Value in ApiBase::PARAM_HELP_MSG_APPEND is not valid' );
2118 }
2119 }
2120 }
2121 }
2122
2123 Hooks::run( 'APIGetParamDescriptionMessages', array( $this, &$msgs ) );
2124
2125 return $msgs;
2126 }
2127
2128 /**
2129 * Generates the list of flags for the help screen and for action=paraminfo
2130 *
2131 * Corresponding messages: api-help-flag-deprecated,
2132 * api-help-flag-internal, api-help-flag-readrights,
2133 * api-help-flag-writerights, api-help-flag-mustbeposted
2134 *
2135 * @return string[]
2136 */
2137 protected function getHelpFlags() {
2138 $flags = array();
2139
2140 if ( $this->isDeprecated() ) {
2141 $flags[] = 'deprecated';
2142 }
2143 if ( $this->isInternal() ) {
2144 $flags[] = 'internal';
2145 }
2146 if ( $this->isReadMode() ) {
2147 $flags[] = 'readrights';
2148 }
2149 if ( $this->isWriteMode() ) {
2150 $flags[] = 'writerights';
2151 }
2152 if ( $this->mustBePosted() ) {
2153 $flags[] = 'mustbeposted';
2154 }
2155
2156 return $flags;
2157 }
2158
2159 /**
2160 * Called from ApiHelp before the pieces are joined together and returned.
2161 *
2162 * This exists mainly for ApiMain to add the Permissions and Credits
2163 * sections. Other modules probably don't need it.
2164 *
2165 * @param string[] &$help Array of help data
2166 * @param array $options Options passed to ApiHelp::getHelp
2167 */
2168 public function modifyHelp( array &$help, array $options ) {
2169 }
2170
2171 /**@}*/
2172
2173 /************************************************************************//**
2174 * @name Profiling
2175 * @{
2176 */
2177
2178 /**
2179 * Profiling: total module execution time
2180 */
2181 private $mTimeIn = 0, $mModuleTime = 0;
2182
2183 /**
2184 * Get the name of the module as shown in the profiler log
2185 *
2186 * @param DatabaseBase|bool $db
2187 *
2188 * @return string
2189 */
2190 public function getModuleProfileName( $db = false ) {
2191 if ( $db ) {
2192 return 'API:' . $this->mModuleName . '-DB';
2193 }
2194
2195 return 'API:' . $this->mModuleName;
2196 }
2197
2198 /**
2199 * Start module profiling
2200 */
2201 public function profileIn() {
2202 if ( $this->mTimeIn !== 0 ) {
2203 ApiBase::dieDebug( __METHOD__, 'Called twice without calling profileOut()' );
2204 }
2205 $this->mTimeIn = microtime( true );
2206 wfProfileIn( $this->getModuleProfileName() );
2207 }
2208
2209 /**
2210 * End module profiling
2211 */
2212 public function profileOut() {
2213 if ( $this->mTimeIn === 0 ) {
2214 ApiBase::dieDebug( __METHOD__, 'Called without calling profileIn() first' );
2215 }
2216 if ( $this->mDBTimeIn !== 0 ) {
2217 ApiBase::dieDebug(
2218 __METHOD__,
2219 'Must be called after database profiling is done with profileDBOut()'
2220 );
2221 }
2222
2223 $this->mModuleTime += microtime( true ) - $this->mTimeIn;
2224 $this->mTimeIn = 0;
2225 wfProfileOut( $this->getModuleProfileName() );
2226 }
2227
2228 /**
2229 * When modules crash, sometimes it is needed to do a profileOut() regardless
2230 * of the profiling state the module was in. This method does such cleanup.
2231 */
2232 public function safeProfileOut() {
2233 if ( $this->mTimeIn !== 0 ) {
2234 if ( $this->mDBTimeIn !== 0 ) {
2235 $this->profileDBOut();
2236 }
2237 $this->profileOut();
2238 }
2239 }
2240
2241 /**
2242 * Total time the module was executed
2243 * @return float
2244 */
2245 public function getProfileTime() {
2246 if ( $this->mTimeIn !== 0 ) {
2247 ApiBase::dieDebug( __METHOD__, 'Called without calling profileOut() first' );
2248 }
2249
2250 return $this->mModuleTime;
2251 }
2252
2253 /**
2254 * Profiling: database execution time
2255 */
2256 private $mDBTimeIn = 0, $mDBTime = 0;
2257
2258 /**
2259 * Start module profiling
2260 */
2261 public function profileDBIn() {
2262 if ( $this->mTimeIn === 0 ) {
2263 ApiBase::dieDebug(
2264 __METHOD__,
2265 'Must be called while profiling the entire module with profileIn()'
2266 );
2267 }
2268 if ( $this->mDBTimeIn !== 0 ) {
2269 ApiBase::dieDebug( __METHOD__, 'Called twice without calling profileDBOut()' );
2270 }
2271 $this->mDBTimeIn = microtime( true );
2272 wfProfileIn( $this->getModuleProfileName( true ) );
2273 }
2274
2275 /**
2276 * End database profiling
2277 */
2278 public function profileDBOut() {
2279 if ( $this->mTimeIn === 0 ) {
2280 ApiBase::dieDebug( __METHOD__, 'Must be called while profiling ' .
2281 'the entire module with profileIn()' );
2282 }
2283 if ( $this->mDBTimeIn === 0 ) {
2284 ApiBase::dieDebug( __METHOD__, 'Called without calling profileDBIn() first' );
2285 }
2286
2287 $time = microtime( true ) - $this->mDBTimeIn;
2288 $this->mDBTimeIn = 0;
2289
2290 $this->mDBTime += $time;
2291 $this->getMain()->mDBTime += $time;
2292 wfProfileOut( $this->getModuleProfileName( true ) );
2293 }
2294
2295 /**
2296 * Total time the module used the database
2297 * @return float
2298 */
2299 public function getProfileDBTime() {
2300 if ( $this->mDBTimeIn !== 0 ) {
2301 ApiBase::dieDebug( __METHOD__, 'Called without calling profileDBOut() first' );
2302 }
2303
2304 return $this->mDBTime;
2305 }
2306
2307 /**
2308 * Write logging information for API features to a debug log, for usage
2309 * analysis.
2310 * @param string $feature Feature being used.
2311 */
2312 protected function logFeatureUsage( $feature ) {
2313 $request = $this->getRequest();
2314 $s = '"' . addslashes( $feature ) . '"' .
2315 ' "' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) . '"' .
2316 ' "' . $request->getIP() . '"' .
2317 ' "' . addslashes( $request->getHeader( 'Referer' ) ) . '"' .
2318 ' "' . addslashes( $this->getMain()->getUserAgent() ) . '"';
2319 wfDebugLog( 'api-feature-usage', $s, 'private' );
2320 }
2321
2322 /**@}*/
2323
2324 /************************************************************************//**
2325 * @name Deprecated
2326 * @{
2327 */
2328
2329 /// @deprecated since 1.24
2330 const PROP_ROOT = 'ROOT';
2331 /// @deprecated since 1.24
2332 const PROP_LIST = 'LIST';
2333 /// @deprecated since 1.24
2334 const PROP_TYPE = 0;
2335 /// @deprecated since 1.24
2336 const PROP_NULLABLE = 1;
2337
2338 /**
2339 * Formerly returned a string that identifies the version of the extending
2340 * class. Typically included the class name, the svn revision, timestamp,
2341 * and last author. Usually done with SVN's Id keyword
2342 *
2343 * @deprecated since 1.21, version string is no longer supported
2344 * @return string
2345 */
2346 public function getVersion() {
2347 wfDeprecated( __METHOD__, '1.21' );
2348 return '';
2349 }
2350
2351 /**
2352 * Formerly used to fetch a list of possible properites in the result,
2353 * somehow organized with respect to the prop parameter that causes them to
2354 * be returned. The specific semantics of the return value was never
2355 * specified. Since this was never possible to be accurately updated, it
2356 * has been removed.
2357 *
2358 * @deprecated since 1.24
2359 * @return array|bool
2360 */
2361 protected function getResultProperties() {
2362 wfDeprecated( __METHOD__, '1.24' );
2363 return false;
2364 }
2365
2366 /**
2367 * @see self::getResultProperties()
2368 * @deprecated since 1.24
2369 * @return array|bool
2370 */
2371 public function getFinalResultProperties() {
2372 wfDeprecated( __METHOD__, '1.24' );
2373 return array();
2374 }
2375
2376 /**
2377 * @see self::getResultProperties()
2378 * @deprecated since 1.24
2379 */
2380 protected static function addTokenProperties( &$props, $tokenFunctions ) {
2381 wfDeprecated( __METHOD__, '1.24' );
2382 }
2383
2384 /**
2385 * @see self::getPossibleErrors()
2386 * @deprecated since 1.24
2387 * @return array
2388 */
2389 public function getRequireOnlyOneParameterErrorMessages( $params ) {
2390 wfDeprecated( __METHOD__, '1.24' );
2391 return array();
2392 }
2393
2394 /**
2395 * @see self::getPossibleErrors()
2396 * @deprecated since 1.24
2397 * @return array
2398 */
2399 public function getRequireMaxOneParameterErrorMessages( $params ) {
2400 wfDeprecated( __METHOD__, '1.24' );
2401 return array();
2402 }
2403
2404 /**
2405 * @see self::getPossibleErrors()
2406 * @deprecated since 1.24
2407 * @return array
2408 */
2409 public function getRequireAtLeastOneParameterErrorMessages( $params ) {
2410 wfDeprecated( __METHOD__, '1.24' );
2411 return array();
2412 }
2413
2414 /**
2415 * @see self::getPossibleErrors()
2416 * @deprecated since 1.24
2417 * @return array
2418 */
2419 public function getTitleOrPageIdErrorMessage() {
2420 wfDeprecated( __METHOD__, '1.24' );
2421 return array();
2422 }
2423
2424 /**
2425 * This formerly attempted to return a list of all possible errors returned
2426 * by the module. However, this was impossible to maintain in many cases
2427 * since errors could come from other areas of MediaWiki and in some cases
2428 * from arbitrary extension hooks. Since a partial list claiming to be
2429 * comprehensive is unlikely to be useful, it was removed.
2430 *
2431 * @deprecated since 1.24
2432 * @return array
2433 */
2434 public function getPossibleErrors() {
2435 wfDeprecated( __METHOD__, '1.24' );
2436 return array();
2437 }
2438
2439 /**
2440 * @see self::getPossibleErrors()
2441 * @deprecated since 1.24
2442 * @return array
2443 */
2444 public function getFinalPossibleErrors() {
2445 wfDeprecated( __METHOD__, '1.24' );
2446 return array();
2447 }
2448
2449 /**
2450 * @see self::getPossibleErrors()
2451 * @deprecated since 1.24
2452 * @return array
2453 */
2454 public function parseErrors( $errors ) {
2455 wfDeprecated( __METHOD__, '1.24' );
2456 return array();
2457 }
2458
2459 /**
2460 * Returns the description string for this module
2461 *
2462 * Ignored if an i18n message exists for
2463 * "apihelp-{$this->getModulePathString()}-description".
2464 *
2465 * @deprecated since 1.25
2466 * @return Message|string|array
2467 */
2468 protected function getDescription() {
2469 return false;
2470 }
2471
2472 /**
2473 * Returns an array of parameter descriptions.
2474 *
2475 * For each parameter, ignored if an i18n message exists for the parameter.
2476 * By default that message is
2477 * "apihelp-{$this->getModulePathString()}-param-{$param}", but it may be
2478 * overridden using ApiBase::PARAM_HELP_MSG in the data returned by
2479 * self::getFinalParams().
2480 *
2481 * @deprecated since 1.25
2482 * @return array|bool False on no parameter descriptions
2483 */
2484 protected function getParamDescription() {
2485 return array();
2486 }
2487
2488 /**
2489 * Returns usage examples for this module.
2490 *
2491 * Return value as an array is either:
2492 * - numeric keys with partial URLs ("api.php?" plus a query string) as
2493 * values
2494 * - sequential numeric keys with even-numbered keys being display-text
2495 * and odd-numbered keys being partial urls
2496 * - partial URLs as keys with display-text (string or array-to-be-joined)
2497 * as values
2498 * Return value as a string is the same as an array with a numeric key and
2499 * that value, and boolean false means "no examples".
2500 *
2501 * @deprecated since 1.25, use getExamplesMessages() instead
2502 * @return bool|string|array
2503 */
2504 protected function getExamples() {
2505 return false;
2506 }
2507
2508 /**
2509 * Generates help message for this module, or false if there is no description
2510 * @deprecated since 1.25
2511 * @return string|bool
2512 */
2513 public function makeHelpMsg() {
2514 wfDeprecated( __METHOD__, '1.25' );
2515 static $lnPrfx = "\n ";
2516
2517 $msg = $this->getFinalDescription();
2518
2519 if ( $msg !== false ) {
2520
2521 if ( !is_array( $msg ) ) {
2522 $msg = array(
2523 $msg
2524 );
2525 }
2526 $msg = $lnPrfx . implode( $lnPrfx, $msg ) . "\n";
2527
2528 $msg .= $this->makeHelpArrayToString( $lnPrfx, false, $this->getHelpUrls() );
2529
2530 if ( $this->isReadMode() ) {
2531 $msg .= "\nThis module requires read rights";
2532 }
2533 if ( $this->isWriteMode() ) {
2534 $msg .= "\nThis module requires write rights";
2535 }
2536 if ( $this->mustBePosted() ) {
2537 $msg .= "\nThis module only accepts POST requests";
2538 }
2539 if ( $this->isReadMode() || $this->isWriteMode() ||
2540 $this->mustBePosted()
2541 ) {
2542 $msg .= "\n";
2543 }
2544
2545 // Parameters
2546 $paramsMsg = $this->makeHelpMsgParameters();
2547 if ( $paramsMsg !== false ) {
2548 $msg .= "Parameters:\n$paramsMsg";
2549 }
2550
2551 $examples = $this->getExamples();
2552 if ( $examples ) {
2553 if ( !is_array( $examples ) ) {
2554 $examples = array(
2555 $examples
2556 );
2557 }
2558 $msg .= "Example" . ( count( $examples ) > 1 ? 's' : '' ) . ":\n";
2559 foreach ( $examples as $k => $v ) {
2560 if ( is_numeric( $k ) ) {
2561 $msg .= " $v\n";
2562 } else {
2563 if ( is_array( $v ) ) {
2564 $msgExample = implode( "\n", array_map( array( $this, 'indentExampleText' ), $v ) );
2565 } else {
2566 $msgExample = " $v";
2567 }
2568 $msgExample .= ":";
2569 $msg .= wordwrap( $msgExample, 100, "\n" ) . "\n $k\n";
2570 }
2571 }
2572 }
2573 }
2574
2575 return $msg;
2576 }
2577
2578 /**
2579 * @deprecated since 1.25
2580 * @param string $item
2581 * @return string
2582 */
2583 private function indentExampleText( $item ) {
2584 return " " . $item;
2585 }
2586
2587 /**
2588 * @deprecated since 1.25
2589 * @param string $prefix Text to split output items
2590 * @param string $title What is being output
2591 * @param string|array $input
2592 * @return string
2593 */
2594 protected function makeHelpArrayToString( $prefix, $title, $input ) {
2595 wfDeprecated( __METHOD__, '1.25' );
2596 if ( $input === false ) {
2597 return '';
2598 }
2599 if ( !is_array( $input ) ) {
2600 $input = array( $input );
2601 }
2602
2603 if ( count( $input ) > 0 ) {
2604 if ( $title ) {
2605 $msg = $title . ( count( $input ) > 1 ? 's' : '' ) . ":\n ";
2606 } else {
2607 $msg = ' ';
2608 }
2609 $msg .= implode( $prefix, $input ) . "\n";
2610
2611 return $msg;
2612 }
2613
2614 return '';
2615 }
2616
2617 /**
2618 * Generates the parameter descriptions for this module, to be displayed in the
2619 * module's help.
2620 * @deprecated since 1.25
2621 * @return string|bool
2622 */
2623 public function makeHelpMsgParameters() {
2624 wfDeprecated( __METHOD__, '1.25' );
2625 $params = $this->getFinalParams( ApiBase::GET_VALUES_FOR_HELP );
2626 if ( $params ) {
2627
2628 $paramsDescription = $this->getFinalParamDescription();
2629 $msg = '';
2630 $paramPrefix = "\n" . str_repeat( ' ', 24 );
2631 $descWordwrap = "\n" . str_repeat( ' ', 28 );
2632 foreach ( $params as $paramName => $paramSettings ) {
2633 $desc = isset( $paramsDescription[$paramName] ) ? $paramsDescription[$paramName] : '';
2634 if ( is_array( $desc ) ) {
2635 $desc = implode( $paramPrefix, $desc );
2636 }
2637
2638 //handle shorthand
2639 if ( !is_array( $paramSettings ) ) {
2640 $paramSettings = array(
2641 self::PARAM_DFLT => $paramSettings,
2642 );
2643 }
2644
2645 //handle missing type
2646 if ( !isset( $paramSettings[ApiBase::PARAM_TYPE] ) ) {
2647 $dflt = isset( $paramSettings[ApiBase::PARAM_DFLT] )
2648 ? $paramSettings[ApiBase::PARAM_DFLT]
2649 : null;
2650 if ( is_bool( $dflt ) ) {
2651 $paramSettings[ApiBase::PARAM_TYPE] = 'boolean';
2652 } elseif ( is_string( $dflt ) || is_null( $dflt ) ) {
2653 $paramSettings[ApiBase::PARAM_TYPE] = 'string';
2654 } elseif ( is_int( $dflt ) ) {
2655 $paramSettings[ApiBase::PARAM_TYPE] = 'integer';
2656 }
2657 }
2658
2659 if ( isset( $paramSettings[self::PARAM_DEPRECATED] )
2660 && $paramSettings[self::PARAM_DEPRECATED]
2661 ) {
2662 $desc = "DEPRECATED! $desc";
2663 }
2664
2665 if ( isset( $paramSettings[self::PARAM_REQUIRED] )
2666 && $paramSettings[self::PARAM_REQUIRED]
2667 ) {
2668 $desc .= $paramPrefix . "This parameter is required";
2669 }
2670
2671 $type = isset( $paramSettings[self::PARAM_TYPE] )
2672 ? $paramSettings[self::PARAM_TYPE]
2673 : null;
2674 if ( isset( $type ) ) {
2675 $hintPipeSeparated = true;
2676 $multi = isset( $paramSettings[self::PARAM_ISMULTI] )
2677 ? $paramSettings[self::PARAM_ISMULTI]
2678 : false;
2679 if ( $multi ) {
2680 $prompt = 'Values (separate with \'|\'): ';
2681 } else {
2682 $prompt = 'One value: ';
2683 }
2684
2685 if ( $type === 'submodule' ) {
2686 $type = $this->getModuleManager()->getNames( $paramName );
2687 sort( $type );
2688 }
2689 if ( is_array( $type ) ) {
2690 $choices = array();
2691 $nothingPrompt = '';
2692 foreach ( $type as $t ) {
2693 if ( $t === '' ) {
2694 $nothingPrompt = 'Can be empty, or ';
2695 } else {
2696 $choices[] = $t;
2697 }
2698 }
2699 $desc .= $paramPrefix . $nothingPrompt . $prompt;
2700 $choicesstring = implode( ', ', $choices );
2701 $desc .= wordwrap( $choicesstring, 100, $descWordwrap );
2702 $hintPipeSeparated = false;
2703 } else {
2704 switch ( $type ) {
2705 case 'namespace':
2706 // Special handling because namespaces are
2707 // type-limited, yet they are not given
2708 $desc .= $paramPrefix . $prompt;
2709 $desc .= wordwrap( implode( ', ', MWNamespace::getValidNamespaces() ),
2710 100, $descWordwrap );
2711 $hintPipeSeparated = false;
2712 break;
2713 case 'limit':
2714 $desc .= $paramPrefix . "No more than {$paramSettings[self::PARAM_MAX]}";
2715 if ( isset( $paramSettings[self::PARAM_MAX2] ) ) {
2716 $desc .= " ({$paramSettings[self::PARAM_MAX2]} for bots)";
2717 }
2718 $desc .= ' allowed';
2719 break;
2720 case 'integer':
2721 $s = $multi ? 's' : '';
2722 $hasMin = isset( $paramSettings[self::PARAM_MIN] );
2723 $hasMax = isset( $paramSettings[self::PARAM_MAX] );
2724 if ( $hasMin || $hasMax ) {
2725 if ( !$hasMax ) {
2726 $intRangeStr = "The value$s must be no less than " .
2727 "{$paramSettings[self::PARAM_MIN]}";
2728 } elseif ( !$hasMin ) {
2729 $intRangeStr = "The value$s must be no more than " .
2730 "{$paramSettings[self::PARAM_MAX]}";
2731 } else {
2732 $intRangeStr = "The value$s must be between " .
2733 "{$paramSettings[self::PARAM_MIN]} and {$paramSettings[self::PARAM_MAX]}";
2734 }
2735
2736 $desc .= $paramPrefix . $intRangeStr;
2737 }
2738 break;
2739 case 'upload':
2740 $desc .= $paramPrefix . "Must be posted as a file upload using multipart/form-data";
2741 break;
2742 }
2743 }
2744
2745 if ( $multi ) {
2746 if ( $hintPipeSeparated ) {
2747 $desc .= $paramPrefix . "Separate values with '|'";
2748 }
2749
2750 $isArray = is_array( $type );
2751 if ( !$isArray
2752 || $isArray && count( $type ) > self::LIMIT_SML1
2753 ) {
2754 $desc .= $paramPrefix . "Maximum number of values " .
2755 self::LIMIT_SML1 . " (" . self::LIMIT_SML2 . " for bots)";
2756 }
2757 }
2758 }
2759
2760 $default = isset( $paramSettings[self::PARAM_DFLT] ) ? $paramSettings[self::PARAM_DFLT] : null;
2761 if ( !is_null( $default ) && $default !== false ) {
2762 $desc .= $paramPrefix . "Default: $default";
2763 }
2764
2765 $msg .= sprintf( " %-19s - %s\n", $this->encodeParamName( $paramName ), $desc );
2766 }
2767
2768 return $msg;
2769 }
2770
2771 return false;
2772 }
2773
2774 /**@}*/
2775 }
2776
2777 /**
2778 * For really cool vim folding this needs to be at the end:
2779 * vim: foldmarker=@{,@} foldmethod=marker
2780 */