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