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