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