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