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