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