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