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