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