Merge "RCFilters: Filter duplicates when filtering for multiple tags"
[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 self::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 self::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 self::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 self::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 self::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 User provided set of parameters, as from $this->extractRequestParams()
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 User provided set of parameters, as from $this->extractRequestParams()
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 $userWatching = $this->getUser()->isWatched( $titleObj, User::IGNORE_USER_RIGHTS );
971
972 switch ( $watchlist ) {
973 case 'watch':
974 return true;
975
976 case 'unwatch':
977 return false;
978
979 case 'preferences':
980 # If the user is already watching, don't bother checking
981 if ( $userWatching ) {
982 return true;
983 }
984 # If no user option was passed, use watchdefault and watchcreations
985 if ( is_null( $userOption ) ) {
986 return $this->getUser()->getBoolOption( 'watchdefault' ) ||
987 $this->getUser()->getBoolOption( 'watchcreations' ) && !$titleObj->exists();
988 }
989
990 # Watch the article based on the user preference
991 return $this->getUser()->getBoolOption( $userOption );
992
993 case 'nochange':
994 return $userWatching;
995
996 default:
997 return $userWatching;
998 }
999 }
1000
1001 /**
1002 * Using the settings determine the value for the given parameter
1003 *
1004 * @param string $paramName Parameter name
1005 * @param array|mixed $paramSettings Default value or an array of settings
1006 * using PARAM_* constants.
1007 * @param bool $parseLimit Parse limit?
1008 * @return mixed Parameter value
1009 */
1010 protected function getParameterFromSettings( $paramName, $paramSettings, $parseLimit ) {
1011 // Some classes may decide to change parameter names
1012 $encParamName = $this->encodeParamName( $paramName );
1013
1014 // Shorthand
1015 if ( !is_array( $paramSettings ) ) {
1016 $paramSettings = [
1017 self::PARAM_DFLT => $paramSettings,
1018 ];
1019 }
1020
1021 $default = isset( $paramSettings[self::PARAM_DFLT] )
1022 ? $paramSettings[self::PARAM_DFLT]
1023 : null;
1024 $multi = isset( $paramSettings[self::PARAM_ISMULTI] )
1025 ? $paramSettings[self::PARAM_ISMULTI]
1026 : false;
1027 $type = isset( $paramSettings[self::PARAM_TYPE] )
1028 ? $paramSettings[self::PARAM_TYPE]
1029 : null;
1030 $dupes = isset( $paramSettings[self::PARAM_ALLOW_DUPLICATES] )
1031 ? $paramSettings[self::PARAM_ALLOW_DUPLICATES]
1032 : false;
1033 $deprecated = isset( $paramSettings[self::PARAM_DEPRECATED] )
1034 ? $paramSettings[self::PARAM_DEPRECATED]
1035 : false;
1036 $deprecatedValues = isset( $paramSettings[self::PARAM_DEPRECATED_VALUES] )
1037 ? $paramSettings[self::PARAM_DEPRECATED_VALUES]
1038 : [];
1039 $required = isset( $paramSettings[self::PARAM_REQUIRED] )
1040 ? $paramSettings[self::PARAM_REQUIRED]
1041 : false;
1042 $allowAll = isset( $paramSettings[self::PARAM_ALL] )
1043 ? $paramSettings[self::PARAM_ALL]
1044 : false;
1045
1046 // When type is not given, and no choices, the type is the same as $default
1047 if ( !isset( $type ) ) {
1048 if ( isset( $default ) ) {
1049 $type = gettype( $default );
1050 } else {
1051 $type = 'NULL'; // allow everything
1052 }
1053
1054 if ( $type == 'password' || !empty( $paramSettings[self::PARAM_SENSITIVE] ) ) {
1055 $this->getMain()->markParamsSensitive( $encParamName );
1056 }
1057 }
1058
1059 if ( $type == 'boolean' ) {
1060 if ( isset( $default ) && $default !== false ) {
1061 // Having a default value of anything other than 'false' is not allowed
1062 self::dieDebug(
1063 __METHOD__,
1064 "Boolean param $encParamName's default is set to '$default'. " .
1065 'Boolean parameters must default to false.'
1066 );
1067 }
1068
1069 $value = $this->getMain()->getCheck( $encParamName );
1070 } elseif ( $type == 'upload' ) {
1071 if ( isset( $default ) ) {
1072 // Having a default value is not allowed
1073 self::dieDebug(
1074 __METHOD__,
1075 "File upload param $encParamName's default is set to " .
1076 "'$default'. File upload parameters may not have a default." );
1077 }
1078 if ( $multi ) {
1079 self::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
1080 }
1081 $value = $this->getMain()->getUpload( $encParamName );
1082 if ( !$value->exists() ) {
1083 // This will get the value without trying to normalize it
1084 // (because trying to normalize a large binary file
1085 // accidentally uploaded as a field fails spectacularly)
1086 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
1087 if ( $value !== null ) {
1088 $this->dieWithError(
1089 [ 'apierror-badupload', $encParamName ],
1090 "badupload_{$encParamName}"
1091 );
1092 }
1093 }
1094 } else {
1095 $value = $this->getMain()->getVal( $encParamName, $default );
1096
1097 if ( isset( $value ) && $type == 'namespace' ) {
1098 $type = MWNamespace::getValidNamespaces();
1099 if ( isset( $paramSettings[self::PARAM_EXTRA_NAMESPACES] ) &&
1100 is_array( $paramSettings[self::PARAM_EXTRA_NAMESPACES] )
1101 ) {
1102 $type = array_merge( $type, $paramSettings[self::PARAM_EXTRA_NAMESPACES] );
1103 }
1104 // By default, namespace parameters allow ALL_DEFAULT_STRING to be used to specify
1105 // all namespaces.
1106 $allowAll = true;
1107 }
1108 if ( isset( $value ) && $type == 'submodule' ) {
1109 if ( isset( $paramSettings[self::PARAM_SUBMODULE_MAP] ) ) {
1110 $type = array_keys( $paramSettings[self::PARAM_SUBMODULE_MAP] );
1111 } else {
1112 $type = $this->getModuleManager()->getNames( $paramName );
1113 }
1114 }
1115
1116 $request = $this->getMain()->getRequest();
1117 $rawValue = $request->getRawVal( $encParamName );
1118 if ( $rawValue === null ) {
1119 $rawValue = $default;
1120 }
1121
1122 // Preserve U+001F for self::parseMultiValue(), or error out if that won't be called
1123 if ( isset( $value ) && substr( $rawValue, 0, 1 ) === "\x1f" ) {
1124 if ( $multi ) {
1125 // This loses the potential $wgContLang->checkTitleEncoding() transformation
1126 // done by WebRequest for $_GET. Let's call that a feature.
1127 $value = join( "\x1f", $request->normalizeUnicode( explode( "\x1f", $rawValue ) ) );
1128 } else {
1129 $this->dieWithError( 'apierror-badvalue-notmultivalue', 'badvalue_notmultivalue' );
1130 }
1131 }
1132
1133 // Check for NFC normalization, and warn
1134 if ( $rawValue !== $value ) {
1135 $this->handleParamNormalization( $paramName, $value, $rawValue );
1136 }
1137 }
1138
1139 $allSpecifier = ( is_string( $allowAll ) ? $allowAll : self::ALL_DEFAULT_STRING );
1140 if ( $allowAll && $multi && is_array( $type ) && in_array( $allSpecifier, $type, true ) ) {
1141 self::dieDebug(
1142 __METHOD__,
1143 "For param $encParamName, PARAM_ALL collides with a possible value" );
1144 }
1145 if ( isset( $value ) && ( $multi || is_array( $type ) ) ) {
1146 $value = $this->parseMultiValue(
1147 $encParamName,
1148 $value,
1149 $multi,
1150 is_array( $type ) ? $type : null,
1151 $allowAll ? $allSpecifier : null
1152 );
1153 }
1154
1155 // More validation only when choices were not given
1156 // choices were validated in parseMultiValue()
1157 if ( isset( $value ) ) {
1158 if ( !is_array( $type ) ) {
1159 switch ( $type ) {
1160 case 'NULL': // nothing to do
1161 break;
1162 case 'string':
1163 case 'text':
1164 case 'password':
1165 if ( $required && $value === '' ) {
1166 $this->dieWithError( [ 'apierror-missingparam', $paramName ] );
1167 }
1168 break;
1169 case 'integer': // Force everything using intval() and optionally validate limits
1170 $min = isset( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[self::PARAM_MIN] : null;
1171 $max = isset( $paramSettings[self::PARAM_MAX] ) ? $paramSettings[self::PARAM_MAX] : null;
1172 $enforceLimits = isset( $paramSettings[self::PARAM_RANGE_ENFORCE] )
1173 ? $paramSettings[self::PARAM_RANGE_ENFORCE] : false;
1174
1175 if ( is_array( $value ) ) {
1176 $value = array_map( 'intval', $value );
1177 if ( !is_null( $min ) || !is_null( $max ) ) {
1178 foreach ( $value as &$v ) {
1179 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
1180 }
1181 }
1182 } else {
1183 $value = intval( $value );
1184 if ( !is_null( $min ) || !is_null( $max ) ) {
1185 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
1186 }
1187 }
1188 break;
1189 case 'limit':
1190 if ( !$parseLimit ) {
1191 // Don't do any validation whatsoever
1192 break;
1193 }
1194 if ( !isset( $paramSettings[self::PARAM_MAX] )
1195 || !isset( $paramSettings[self::PARAM_MAX2] )
1196 ) {
1197 self::dieDebug(
1198 __METHOD__,
1199 "MAX1 or MAX2 are not defined for the limit $encParamName"
1200 );
1201 }
1202 if ( $multi ) {
1203 self::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
1204 }
1205 $min = isset( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[self::PARAM_MIN] : 0;
1206 if ( $value == 'max' ) {
1207 $value = $this->getMain()->canApiHighLimits()
1208 ? $paramSettings[self::PARAM_MAX2]
1209 : $paramSettings[self::PARAM_MAX];
1210 $this->getResult()->addParsedLimit( $this->getModuleName(), $value );
1211 } else {
1212 $value = intval( $value );
1213 $this->validateLimit(
1214 $paramName,
1215 $value,
1216 $min,
1217 $paramSettings[self::PARAM_MAX],
1218 $paramSettings[self::PARAM_MAX2]
1219 );
1220 }
1221 break;
1222 case 'boolean':
1223 if ( $multi ) {
1224 self::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
1225 }
1226 break;
1227 case 'timestamp':
1228 if ( is_array( $value ) ) {
1229 foreach ( $value as $key => $val ) {
1230 $value[$key] = $this->validateTimestamp( $val, $encParamName );
1231 }
1232 } else {
1233 $value = $this->validateTimestamp( $value, $encParamName );
1234 }
1235 break;
1236 case 'user':
1237 if ( is_array( $value ) ) {
1238 foreach ( $value as $key => $val ) {
1239 $value[$key] = $this->validateUser( $val, $encParamName );
1240 }
1241 } else {
1242 $value = $this->validateUser( $value, $encParamName );
1243 }
1244 break;
1245 case 'upload': // nothing to do
1246 break;
1247 case 'tags':
1248 // If change tagging was requested, check that the tags are valid.
1249 if ( !is_array( $value ) && !$multi ) {
1250 $value = [ $value ];
1251 }
1252 $tagsStatus = ChangeTags::canAddTagsAccompanyingChange( $value );
1253 if ( !$tagsStatus->isGood() ) {
1254 $this->dieStatus( $tagsStatus );
1255 }
1256 break;
1257 default:
1258 self::dieDebug( __METHOD__, "Param $encParamName's type is unknown - $type" );
1259 }
1260 }
1261
1262 // Throw out duplicates if requested
1263 if ( !$dupes && is_array( $value ) ) {
1264 $value = array_unique( $value );
1265 }
1266
1267 // Set a warning if a deprecated parameter has been passed
1268 if ( $deprecated && $value !== false ) {
1269 $feature = $encParamName;
1270 $m = $this;
1271 while ( !$m->isMain() ) {
1272 $p = $m->getParent();
1273 $name = $m->getModuleName();
1274 $param = $p->encodeParamName( $p->getModuleManager()->getModuleGroup( $name ) );
1275 $feature = "{$param}={$name}&{$feature}";
1276 $m = $p;
1277 }
1278 $this->addDeprecation( [ 'apiwarn-deprecation-parameter', $encParamName ], $feature );
1279 }
1280
1281 // Set a warning if a deprecated parameter value has been passed
1282 $usedDeprecatedValues = $deprecatedValues && $value !== false
1283 ? array_intersect( array_keys( $deprecatedValues ), (array)$value )
1284 : [];
1285 if ( $usedDeprecatedValues ) {
1286 $feature = "$encParamName=";
1287 $m = $this;
1288 while ( !$m->isMain() ) {
1289 $p = $m->getParent();
1290 $name = $m->getModuleName();
1291 $param = $p->encodeParamName( $p->getModuleManager()->getModuleGroup( $name ) );
1292 $feature = "{$param}={$name}&{$feature}";
1293 $m = $p;
1294 }
1295 foreach ( $usedDeprecatedValues as $v ) {
1296 $msg = $deprecatedValues[$v];
1297 if ( $msg === true ) {
1298 $msg = [ 'apiwarn-deprecation-parameter', "$encParamName=$v" ];
1299 }
1300 $this->addDeprecation( $msg, "$feature$v" );
1301 }
1302 }
1303 } elseif ( $required ) {
1304 $this->dieWithError( [ 'apierror-missingparam', $paramName ] );
1305 }
1306
1307 return $value;
1308 }
1309
1310 /**
1311 * Handle when a parameter was Unicode-normalized
1312 * @since 1.28
1313 * @param string $paramName Unprefixed parameter name
1314 * @param string $value Input that will be used.
1315 * @param string $rawValue Input before normalization.
1316 */
1317 protected function handleParamNormalization( $paramName, $value, $rawValue ) {
1318 $encParamName = $this->encodeParamName( $paramName );
1319 $this->addWarning( [ 'apiwarn-badutf8', $encParamName ] );
1320 }
1321
1322 /**
1323 * Split a multi-valued parameter string, like explode()
1324 * @since 1.28
1325 * @param string $value
1326 * @param int $limit
1327 * @return string[]
1328 */
1329 protected function explodeMultiValue( $value, $limit ) {
1330 if ( substr( $value, 0, 1 ) === "\x1f" ) {
1331 $sep = "\x1f";
1332 $value = substr( $value, 1 );
1333 } else {
1334 $sep = '|';
1335 }
1336
1337 return explode( $sep, $value, $limit );
1338 }
1339
1340 /**
1341 * Return an array of values that were given in a 'a|b|c' notation,
1342 * after it optionally validates them against the list allowed values.
1343 *
1344 * @param string $valueName The name of the parameter (for error
1345 * reporting)
1346 * @param mixed $value The value being parsed
1347 * @param bool $allowMultiple Can $value contain more than one value
1348 * separated by '|'?
1349 * @param string[]|null $allowedValues An array of values to check against. If
1350 * null, all values are accepted.
1351 * @param string|null $allSpecifier String to use to specify all allowed values, or null
1352 * if this behavior should not be allowed
1353 * @return string|string[] (allowMultiple ? an_array_of_values : a_single_value)
1354 */
1355 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues,
1356 $allSpecifier = null
1357 ) {
1358 if ( ( trim( $value ) === '' || trim( $value ) === "\x1f" ) && $allowMultiple ) {
1359 return [];
1360 }
1361
1362 // This is a bit awkward, but we want to avoid calling canApiHighLimits()
1363 // because it unstubs $wgUser
1364 $valuesList = $this->explodeMultiValue( $value, self::LIMIT_SML2 + 1 );
1365 $sizeLimit = count( $valuesList ) > self::LIMIT_SML1 && $this->mMainModule->canApiHighLimits()
1366 ? self::LIMIT_SML2
1367 : self::LIMIT_SML1;
1368
1369 if ( $allowMultiple && is_array( $allowedValues ) && $allSpecifier &&
1370 count( $valuesList ) === 1 && $valuesList[0] === $allSpecifier
1371 ) {
1372 return $allowedValues;
1373 }
1374
1375 if ( self::truncateArray( $valuesList, $sizeLimit ) ) {
1376 $this->addDeprecation(
1377 [ 'apiwarn-toomanyvalues', $valueName, $sizeLimit ],
1378 "too-many-$valueName-for-{$this->getModulePath()}"
1379 );
1380 }
1381
1382 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
1383 // T35482 - Allow entries with | in them for non-multiple values
1384 if ( in_array( $value, $allowedValues, true ) ) {
1385 return $value;
1386 }
1387
1388 if ( is_array( $allowedValues ) ) {
1389 $values = array_map( function ( $v ) {
1390 return '<kbd>' . wfEscapeWikiText( $v ) . '</kbd>';
1391 }, $allowedValues );
1392 $this->dieWithError( [
1393 'apierror-multival-only-one-of',
1394 $valueName,
1395 Message::listParam( $values ),
1396 count( $values ),
1397 ], "multival_$valueName" );
1398 } else {
1399 $this->dieWithError( [
1400 'apierror-multival-only-one',
1401 $valueName,
1402 ], "multival_$valueName" );
1403 }
1404 }
1405
1406 if ( is_array( $allowedValues ) ) {
1407 // Check for unknown values
1408 $unknown = array_map( 'wfEscapeWikiText', array_diff( $valuesList, $allowedValues ) );
1409 if ( count( $unknown ) ) {
1410 if ( $allowMultiple ) {
1411 $this->addWarning( [
1412 'apiwarn-unrecognizedvalues',
1413 $valueName,
1414 Message::listParam( $unknown, 'comma' ),
1415 count( $unknown ),
1416 ] );
1417 } else {
1418 $this->dieWithError(
1419 [ 'apierror-unrecognizedvalue', $valueName, wfEscapeWikiText( $valuesList[0] ) ],
1420 "unknown_$valueName"
1421 );
1422 }
1423 }
1424 // Now throw them out
1425 $valuesList = array_intersect( $valuesList, $allowedValues );
1426 }
1427
1428 return $allowMultiple ? $valuesList : $valuesList[0];
1429 }
1430
1431 /**
1432 * Validate the value against the minimum and user/bot maximum limits.
1433 * Prints usage info on failure.
1434 * @param string $paramName Parameter name
1435 * @param int $value Parameter value
1436 * @param int|null $min Minimum value
1437 * @param int|null $max Maximum value for users
1438 * @param int $botMax Maximum value for sysops/bots
1439 * @param bool $enforceLimits Whether to enforce (die) if value is outside limits
1440 */
1441 protected function validateLimit( $paramName, &$value, $min, $max, $botMax = null,
1442 $enforceLimits = false
1443 ) {
1444 if ( !is_null( $min ) && $value < $min ) {
1445 $msg = ApiMessage::create(
1446 [ 'apierror-integeroutofrange-belowminimum',
1447 $this->encodeParamName( $paramName ), $min, $value ],
1448 'integeroutofrange',
1449 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?: $max ]
1450 );
1451 $this->warnOrDie( $msg, $enforceLimits );
1452 $value = $min;
1453 }
1454
1455 // Minimum is always validated, whereas maximum is checked only if not
1456 // running in internal call mode
1457 if ( $this->getMain()->isInternalMode() ) {
1458 return;
1459 }
1460
1461 // Optimization: do not check user's bot status unless really needed -- skips db query
1462 // assumes $botMax >= $max
1463 if ( !is_null( $max ) && $value > $max ) {
1464 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1465 if ( $value > $botMax ) {
1466 $msg = ApiMessage::create(
1467 [ 'apierror-integeroutofrange-abovebotmax',
1468 $this->encodeParamName( $paramName ), $botMax, $value ],
1469 'integeroutofrange',
1470 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?: $max ]
1471 );
1472 $this->warnOrDie( $msg, $enforceLimits );
1473 $value = $botMax;
1474 }
1475 } else {
1476 $msg = ApiMessage::create(
1477 [ 'apierror-integeroutofrange-abovemax',
1478 $this->encodeParamName( $paramName ), $max, $value ],
1479 'integeroutofrange',
1480 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?: $max ]
1481 );
1482 $this->warnOrDie( $msg, $enforceLimits );
1483 $value = $max;
1484 }
1485 }
1486 }
1487
1488 /**
1489 * Validate and normalize of parameters of type 'timestamp'
1490 * @param string $value Parameter value
1491 * @param string $encParamName Parameter name
1492 * @return string Validated and normalized parameter
1493 */
1494 protected function validateTimestamp( $value, $encParamName ) {
1495 // Confusing synonyms for the current time accepted by wfTimestamp()
1496 // (wfTimestamp() also accepts various non-strings and the string of 14
1497 // ASCII NUL bytes, but those can't get here)
1498 if ( !$value ) {
1499 $this->addDeprecation(
1500 [ 'apiwarn-unclearnowtimestamp', $encParamName, wfEscapeWikiText( $value ) ],
1501 'unclear-"now"-timestamp'
1502 );
1503 return wfTimestamp( TS_MW );
1504 }
1505
1506 // Explicit synonym for the current time
1507 if ( $value === 'now' ) {
1508 return wfTimestamp( TS_MW );
1509 }
1510
1511 $unixTimestamp = wfTimestamp( TS_UNIX, $value );
1512 if ( $unixTimestamp === false ) {
1513 $this->dieWithError(
1514 [ 'apierror-badtimestamp', $encParamName, wfEscapeWikiText( $value ) ],
1515 "badtimestamp_{$encParamName}"
1516 );
1517 }
1518
1519 return wfTimestamp( TS_MW, $unixTimestamp );
1520 }
1521
1522 /**
1523 * Validate the supplied token.
1524 *
1525 * @since 1.24
1526 * @param string $token Supplied token
1527 * @param array $params All supplied parameters for the module
1528 * @return bool
1529 * @throws MWException
1530 */
1531 final public function validateToken( $token, array $params ) {
1532 $tokenType = $this->needsToken();
1533 $salts = ApiQueryTokens::getTokenTypeSalts();
1534 if ( !isset( $salts[$tokenType] ) ) {
1535 throw new MWException(
1536 "Module '{$this->getModuleName()}' tried to use token type '$tokenType' " .
1537 'without registering it'
1538 );
1539 }
1540
1541 $tokenObj = ApiQueryTokens::getToken(
1542 $this->getUser(), $this->getRequest()->getSession(), $salts[$tokenType]
1543 );
1544 if ( $tokenObj->match( $token ) ) {
1545 return true;
1546 }
1547
1548 $webUiSalt = $this->getWebUITokenSalt( $params );
1549 if ( $webUiSalt !== null && $this->getUser()->matchEditToken(
1550 $token,
1551 $webUiSalt,
1552 $this->getRequest()
1553 ) ) {
1554 return true;
1555 }
1556
1557 return false;
1558 }
1559
1560 /**
1561 * Validate and normalize of parameters of type 'user'
1562 * @param string $value Parameter value
1563 * @param string $encParamName Parameter name
1564 * @return string Validated and normalized parameter
1565 */
1566 private function validateUser( $value, $encParamName ) {
1567 $title = Title::makeTitleSafe( NS_USER, $value );
1568 if ( $title === null || $title->hasFragment() ) {
1569 $this->dieWithError(
1570 [ 'apierror-baduser', $encParamName, wfEscapeWikiText( $value ) ],
1571 "baduser_{$encParamName}"
1572 );
1573 }
1574
1575 return $title->getText();
1576 }
1577
1578 /**@}*/
1579
1580 /************************************************************************//**
1581 * @name Utility methods
1582 * @{
1583 */
1584
1585 /**
1586 * Set a watch (or unwatch) based the based on a watchlist parameter.
1587 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
1588 * @param Title $titleObj The article's title to change
1589 * @param string $userOption The user option to consider when $watch=preferences
1590 */
1591 protected function setWatch( $watch, $titleObj, $userOption = null ) {
1592 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
1593 if ( $value === null ) {
1594 return;
1595 }
1596
1597 WatchAction::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
1598 }
1599
1600 /**
1601 * Truncate an array to a certain length.
1602 * @param array $arr Array to truncate
1603 * @param int $limit Maximum length
1604 * @return bool True if the array was truncated, false otherwise
1605 */
1606 public static function truncateArray( &$arr, $limit ) {
1607 $modified = false;
1608 while ( count( $arr ) > $limit ) {
1609 array_pop( $arr );
1610 $modified = true;
1611 }
1612
1613 return $modified;
1614 }
1615
1616 /**
1617 * Gets the user for whom to get the watchlist
1618 *
1619 * @param array $params
1620 * @return User
1621 */
1622 public function getWatchlistUser( $params ) {
1623 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1624 $user = User::newFromName( $params['owner'], false );
1625 if ( !( $user && $user->getId() ) ) {
1626 $this->dieWithError(
1627 [ 'nosuchusershort', wfEscapeWikiText( $params['owner'] ) ], 'bad_wlowner'
1628 );
1629 }
1630 $token = $user->getOption( 'watchlisttoken' );
1631 if ( $token == '' || !hash_equals( $token, $params['token'] ) ) {
1632 $this->dieWithError( 'apierror-bad-watchlist-token', 'bad_wltoken' );
1633 }
1634 } else {
1635 if ( !$this->getUser()->isLoggedIn() ) {
1636 $this->dieWithError( 'watchlistanontext', 'notloggedin' );
1637 }
1638 $this->checkUserRightsAny( 'viewmywatchlist' );
1639 $user = $this->getUser();
1640 }
1641
1642 return $user;
1643 }
1644
1645 /**
1646 * A subset of wfEscapeWikiText for BC texts
1647 *
1648 * @since 1.25
1649 * @param string|array $v
1650 * @return string|array
1651 */
1652 private static function escapeWikiText( $v ) {
1653 if ( is_array( $v ) ) {
1654 return array_map( 'self::escapeWikiText', $v );
1655 } else {
1656 return strtr( $v, [
1657 '__' => '_&#95;', '{' => '&#123;', '}' => '&#125;',
1658 '[[Category:' => '[[:Category:',
1659 '[[File:' => '[[:File:', '[[Image:' => '[[:Image:',
1660 ] );
1661 }
1662 }
1663
1664 /**
1665 * Create a Message from a string or array
1666 *
1667 * A string is used as a message key. An array has the message key as the
1668 * first value and message parameters as subsequent values.
1669 *
1670 * @since 1.25
1671 * @param string|array|Message $msg
1672 * @param IContextSource $context
1673 * @param array $params
1674 * @return Message|null
1675 */
1676 public static function makeMessage( $msg, IContextSource $context, array $params = null ) {
1677 if ( is_string( $msg ) ) {
1678 $msg = wfMessage( $msg );
1679 } elseif ( is_array( $msg ) ) {
1680 $msg = call_user_func_array( 'wfMessage', $msg );
1681 }
1682 if ( !$msg instanceof Message ) {
1683 return null;
1684 }
1685
1686 $msg->setContext( $context );
1687 if ( $params ) {
1688 $msg->params( $params );
1689 }
1690
1691 return $msg;
1692 }
1693
1694 /**
1695 * Turn an array of message keys or key+param arrays into a Status
1696 * @since 1.29
1697 * @param array $errors
1698 * @param User|null $user
1699 * @return Status
1700 */
1701 public function errorArrayToStatus( array $errors, User $user = null ) {
1702 if ( $user === null ) {
1703 $user = $this->getUser();
1704 }
1705
1706 $status = Status::newGood();
1707 foreach ( $errors as $error ) {
1708 if ( is_array( $error ) && $error[0] === 'blockedtext' && $user->getBlock() ) {
1709 $status->fatal( ApiMessage::create(
1710 'apierror-blocked',
1711 'blocked',
1712 [ 'blockinfo' => ApiQueryUserInfo::getBlockInfo( $user->getBlock() ) ]
1713 ) );
1714 } elseif ( is_array( $error ) && $error[0] === 'autoblockedtext' && $user->getBlock() ) {
1715 $status->fatal( ApiMessage::create(
1716 'apierror-autoblocked',
1717 'autoblocked',
1718 [ 'blockinfo' => ApiQueryUserInfo::getBlockInfo( $user->getBlock() ) ]
1719 ) );
1720 } elseif ( is_array( $error ) && $error[0] === 'systemblockedtext' && $user->getBlock() ) {
1721 $status->fatal( ApiMessage::create(
1722 'apierror-systemblocked',
1723 'blocked',
1724 [ 'blockinfo' => ApiQueryUserInfo::getBlockInfo( $user->getBlock() ) ]
1725 ) );
1726 } else {
1727 call_user_func_array( [ $status, 'fatal' ], (array)$error );
1728 }
1729 }
1730 return $status;
1731 }
1732
1733 /**@}*/
1734
1735 /************************************************************************//**
1736 * @name Warning and error reporting
1737 * @{
1738 */
1739
1740 /**
1741 * Add a warning for this module.
1742 *
1743 * Users should monitor this section to notice any changes in API. Multiple
1744 * calls to this function will result in multiple warning messages.
1745 *
1746 * If $msg is not an ApiMessage, the message code will be derived from the
1747 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1748 *
1749 * @since 1.29
1750 * @param string|array|Message $msg See ApiErrorFormatter::addWarning()
1751 * @param string|null $code See ApiErrorFormatter::addWarning()
1752 * @param array|null $data See ApiErrorFormatter::addWarning()
1753 */
1754 public function addWarning( $msg, $code = null, $data = null ) {
1755 $this->getErrorFormatter()->addWarning( $this->getModulePath(), $msg, $code, $data );
1756 }
1757
1758 /**
1759 * Add a deprecation warning for this module.
1760 *
1761 * A combination of $this->addWarning() and $this->logFeatureUsage()
1762 *
1763 * @since 1.29
1764 * @param string|array|Message $msg See ApiErrorFormatter::addWarning()
1765 * @param string|null $feature See ApiBase::logFeatureUsage()
1766 * @param array|null $data See ApiErrorFormatter::addWarning()
1767 */
1768 public function addDeprecation( $msg, $feature, $data = [] ) {
1769 $data = (array)$data;
1770 if ( $feature !== null ) {
1771 $data['feature'] = $feature;
1772 $this->logFeatureUsage( $feature );
1773 }
1774 $this->addWarning( $msg, 'deprecation', $data );
1775
1776 // No real need to deduplicate here, ApiErrorFormatter does that for
1777 // us (assuming the hook is deterministic).
1778 $msgs = [ $this->msg( 'api-usage-mailinglist-ref' ) ];
1779 Hooks::run( 'ApiDeprecationHelp', [ &$msgs ] );
1780 if ( count( $msgs ) > 1 ) {
1781 $key = '$' . join( ' $', range( 1, count( $msgs ) ) );
1782 $msg = ( new RawMessage( $key ) )->params( $msgs );
1783 } else {
1784 $msg = reset( $msgs );
1785 }
1786 $this->getMain()->addWarning( $msg, 'deprecation-help' );
1787 }
1788
1789 /**
1790 * Add an error for this module without aborting
1791 *
1792 * If $msg is not an ApiMessage, the message code will be derived from the
1793 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1794 *
1795 * @note If you want to abort processing, use self::dieWithError() instead.
1796 * @since 1.29
1797 * @param string|array|Message $msg See ApiErrorFormatter::addError()
1798 * @param string|null $code See ApiErrorFormatter::addError()
1799 * @param array|null $data See ApiErrorFormatter::addError()
1800 */
1801 public function addError( $msg, $code = null, $data = null ) {
1802 $this->getErrorFormatter()->addError( $this->getModulePath(), $msg, $code, $data );
1803 }
1804
1805 /**
1806 * Add warnings and/or errors from a Status
1807 *
1808 * @note If you want to abort processing, use self::dieStatus() instead.
1809 * @since 1.29
1810 * @param StatusValue $status
1811 * @param string[] $types 'warning' and/or 'error'
1812 */
1813 public function addMessagesFromStatus( StatusValue $status, $types = [ 'warning', 'error' ] ) {
1814 $this->getErrorFormatter()->addMessagesFromStatus( $this->getModulePath(), $status, $types );
1815 }
1816
1817 /**
1818 * Abort execution with an error
1819 *
1820 * If $msg is not an ApiMessage, the message code will be derived from the
1821 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1822 *
1823 * @since 1.29
1824 * @param string|array|Message $msg See ApiErrorFormatter::addError()
1825 * @param string|null $code See ApiErrorFormatter::addError()
1826 * @param array|null $data See ApiErrorFormatter::addError()
1827 * @param int|null $httpCode HTTP error code to use
1828 * @throws ApiUsageException always
1829 */
1830 public function dieWithError( $msg, $code = null, $data = null, $httpCode = null ) {
1831 throw ApiUsageException::newWithMessage( $this, $msg, $code, $data, $httpCode );
1832 }
1833
1834 /**
1835 * Abort execution with an error derived from an exception
1836 *
1837 * @since 1.29
1838 * @param Exception|Throwable $exception See ApiErrorFormatter::getMessageFromException()
1839 * @param array $options See ApiErrorFormatter::getMessageFromException()
1840 * @throws ApiUsageException always
1841 */
1842 public function dieWithException( $exception, array $options = [] ) {
1843 $this->dieWithError(
1844 $this->getErrorFormatter()->getMessageFromException( $exception, $options )
1845 );
1846 }
1847
1848 /**
1849 * Adds a warning to the output, else dies
1850 *
1851 * @param ApiMessage $msg Message to show as a warning, or error message if dying
1852 * @param bool $enforceLimits Whether this is an enforce (die)
1853 */
1854 private function warnOrDie( ApiMessage $msg, $enforceLimits = false ) {
1855 if ( $enforceLimits ) {
1856 $this->dieWithError( $msg );
1857 } else {
1858 $this->addWarning( $msg );
1859 }
1860 }
1861
1862 /**
1863 * Throw an ApiUsageException, which will (if uncaught) call the main module's
1864 * error handler and die with an error message including block info.
1865 *
1866 * @since 1.27
1867 * @param Block $block The block used to generate the ApiUsageException
1868 * @throws ApiUsageException always
1869 */
1870 public function dieBlocked( Block $block ) {
1871 // Die using the appropriate message depending on block type
1872 if ( $block->getType() == Block::TYPE_AUTO ) {
1873 $this->dieWithError(
1874 'apierror-autoblocked',
1875 'autoblocked',
1876 [ 'blockinfo' => ApiQueryUserInfo::getBlockInfo( $block ) ]
1877 );
1878 } else {
1879 $this->dieWithError(
1880 'apierror-blocked',
1881 'blocked',
1882 [ 'blockinfo' => ApiQueryUserInfo::getBlockInfo( $block ) ]
1883 );
1884 }
1885 }
1886
1887 /**
1888 * Throw an ApiUsageException based on the Status object.
1889 *
1890 * @since 1.22
1891 * @since 1.29 Accepts a StatusValue
1892 * @param StatusValue $status
1893 * @throws ApiUsageException always
1894 */
1895 public function dieStatus( StatusValue $status ) {
1896 if ( $status->isGood() ) {
1897 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
1898 }
1899
1900 // ApiUsageException needs a fatal status, but this method has
1901 // historically accepted any non-good status. Convert it if necessary.
1902 $status->setOK( false );
1903 if ( !$status->getErrorsByType( 'error' ) ) {
1904 $newStatus = Status::newGood();
1905 foreach ( $status->getErrorsByType( 'warning' ) as $err ) {
1906 call_user_func_array(
1907 [ $newStatus, 'fatal' ],
1908 array_merge( [ $err['message'] ], $err['params'] )
1909 );
1910 }
1911 if ( !$newStatus->getErrorsByType( 'error' ) ) {
1912 $newStatus->fatal( 'unknownerror-nocode' );
1913 }
1914 $status = $newStatus;
1915 }
1916
1917 throw new ApiUsageException( $this, $status );
1918 }
1919
1920 /**
1921 * Helper function for readonly errors
1922 *
1923 * @throws ApiUsageException always
1924 */
1925 public function dieReadOnly() {
1926 $this->dieWithError(
1927 'apierror-readonly',
1928 'readonly',
1929 [ 'readonlyreason' => wfReadOnlyReason() ]
1930 );
1931 }
1932
1933 /**
1934 * Helper function for permission-denied errors
1935 * @since 1.29
1936 * @param string|string[] $rights
1937 * @param User|null $user
1938 * @throws ApiUsageException if the user doesn't have any of the rights.
1939 * The error message is based on $rights[0].
1940 */
1941 public function checkUserRightsAny( $rights, $user = null ) {
1942 if ( !$user ) {
1943 $user = $this->getUser();
1944 }
1945 $rights = (array)$rights;
1946 if ( !call_user_func_array( [ $user, 'isAllowedAny' ], $rights ) ) {
1947 $this->dieWithError( [ 'apierror-permissiondenied', $this->msg( "action-{$rights[0]}" ) ] );
1948 }
1949 }
1950
1951 /**
1952 * Helper function for permission-denied errors
1953 * @since 1.29
1954 * @param Title $title
1955 * @param string|string[] $actions
1956 * @param User|null $user
1957 * @throws ApiUsageException if the user doesn't have all of the rights.
1958 */
1959 public function checkTitleUserPermissions( Title $title, $actions, $user = null ) {
1960 if ( !$user ) {
1961 $user = $this->getUser();
1962 }
1963
1964 $errors = [];
1965 foreach ( (array)$actions as $action ) {
1966 $errors = array_merge( $errors, $title->getUserPermissionsErrors( $action, $user ) );
1967 }
1968 if ( $errors ) {
1969 $this->dieStatus( $this->errorArrayToStatus( $errors, $user ) );
1970 }
1971 }
1972
1973 /**
1974 * Will only set a warning instead of failing if the global $wgDebugAPI
1975 * is set to true. Otherwise behaves exactly as self::dieWithError().
1976 *
1977 * @since 1.29
1978 * @param string|array|Message $msg
1979 * @param string|null $code
1980 * @param array|null $data
1981 * @param int|null $httpCode
1982 * @throws ApiUsageException
1983 */
1984 public function dieWithErrorOrDebug( $msg, $code = null, $data = null, $httpCode = null ) {
1985 if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
1986 $this->dieWithError( $msg, $code, $data, $httpCode );
1987 } else {
1988 $this->addWarning( $msg, $code, $data );
1989 }
1990 }
1991
1992 /**
1993 * Die with the 'badcontinue' error.
1994 *
1995 * This call is common enough to make it into the base method.
1996 *
1997 * @param bool $condition Will only die if this value is true
1998 * @throws ApiUsageException
1999 * @since 1.21
2000 */
2001 protected function dieContinueUsageIf( $condition ) {
2002 if ( $condition ) {
2003 $this->dieWithError( 'apierror-badcontinue' );
2004 }
2005 }
2006
2007 /**
2008 * Internal code errors should be reported with this method
2009 * @param string $method Method or function name
2010 * @param string $message Error message
2011 * @throws MWException always
2012 */
2013 protected static function dieDebug( $method, $message ) {
2014 throw new MWException( "Internal error in $method: $message" );
2015 }
2016
2017 /**
2018 * Write logging information for API features to a debug log, for usage
2019 * analysis.
2020 * @note Consider using $this->addDeprecation() instead to both warn and log.
2021 * @param string $feature Feature being used.
2022 */
2023 public function logFeatureUsage( $feature ) {
2024 $request = $this->getRequest();
2025 $s = '"' . addslashes( $feature ) . '"' .
2026 ' "' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) . '"' .
2027 ' "' . $request->getIP() . '"' .
2028 ' "' . addslashes( $request->getHeader( 'Referer' ) ) . '"' .
2029 ' "' . addslashes( $this->getMain()->getUserAgent() ) . '"';
2030 wfDebugLog( 'api-feature-usage', $s, 'private' );
2031 }
2032
2033 /**@}*/
2034
2035 /************************************************************************//**
2036 * @name Help message generation
2037 * @{
2038 */
2039
2040 /**
2041 * Return the summary message.
2042 *
2043 * This is a one-line description of the module, suitable for display in a
2044 * list of modules.
2045 *
2046 * @since 1.30
2047 * @return string|array|Message
2048 */
2049 protected function getSummaryMessage() {
2050 return "apihelp-{$this->getModulePath()}-summary";
2051 }
2052
2053 /**
2054 * Return the extended help text message.
2055 *
2056 * This is additional text to display at the top of the help section, below
2057 * the summary.
2058 *
2059 * @since 1.30
2060 * @return string|array|Message
2061 */
2062 protected function getExtendedDescription() {
2063 return [ [
2064 "apihelp-{$this->getModulePath()}-extended-description",
2065 'api-help-no-extended-description',
2066 ] ];
2067 }
2068
2069 /**
2070 * Get final module summary
2071 *
2072 * Ideally this will just be the getSummaryMessage(). However, for
2073 * backwards compatibility, if that message does not exist then the first
2074 * line of wikitext from the description message will be used instead.
2075 *
2076 * @since 1.30
2077 * @return Message
2078 */
2079 public function getFinalSummary() {
2080 $msg = self::makeMessage( $this->getSummaryMessage(), $this->getContext(), [
2081 $this->getModulePrefix(),
2082 $this->getModuleName(),
2083 $this->getModulePath(),
2084 ] );
2085 if ( !$msg->exists() ) {
2086 wfDeprecated( 'API help "description" messages', '1.30' );
2087 $msg = self::makeMessage( $this->getDescriptionMessage(), $this->getContext(), [
2088 $this->getModulePrefix(),
2089 $this->getModuleName(),
2090 $this->getModulePath(),
2091 ] );
2092 $msg = self::makeMessage( 'rawmessage', $this->getContext(), [
2093 preg_replace( '/\n.*/s', '', $msg->text() )
2094 ] );
2095 }
2096 return $msg;
2097 }
2098
2099 /**
2100 * Get final module description, after hooks have had a chance to tweak it as
2101 * needed.
2102 *
2103 * @since 1.25, returns Message[] rather than string[]
2104 * @return Message[]
2105 */
2106 public function getFinalDescription() {
2107 $desc = $this->getDescription();
2108
2109 // Avoid PHP 7.1 warning of passing $this by reference
2110 $apiModule = $this;
2111 Hooks::run( 'APIGetDescription', [ &$apiModule, &$desc ] );
2112 $desc = self::escapeWikiText( $desc );
2113 if ( is_array( $desc ) ) {
2114 $desc = implode( "\n", $desc );
2115 } else {
2116 $desc = (string)$desc;
2117 }
2118
2119 $summary = self::makeMessage( $this->getSummaryMessage(), $this->getContext(), [
2120 $this->getModulePrefix(),
2121 $this->getModuleName(),
2122 $this->getModulePath(),
2123 ] );
2124 $extendedDescription = self::makeMessage(
2125 $this->getExtendedDescription(), $this->getContext(), [
2126 $this->getModulePrefix(),
2127 $this->getModuleName(),
2128 $this->getModulePath(),
2129 ]
2130 );
2131
2132 if ( $summary->exists() ) {
2133 $msgs = [ $summary, $extendedDescription ];
2134 } else {
2135 wfDeprecated( 'API help "description" messages', '1.30' );
2136 $description = self::makeMessage( $this->getDescriptionMessage(), $this->getContext(), [
2137 $this->getModulePrefix(),
2138 $this->getModuleName(),
2139 $this->getModulePath(),
2140 ] );
2141 if ( !$description->exists() ) {
2142 $description = $this->msg( 'api-help-fallback-description', $desc );
2143 }
2144 $msgs = [ $description ];
2145 }
2146
2147 Hooks::run( 'APIGetDescriptionMessages', [ $this, &$msgs ] );
2148
2149 return $msgs;
2150 }
2151
2152 /**
2153 * Get final list of parameters, after hooks have had a chance to
2154 * tweak it as needed.
2155 *
2156 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
2157 * @return array|bool False on no parameters
2158 * @since 1.21 $flags param added
2159 */
2160 public function getFinalParams( $flags = 0 ) {
2161 $params = $this->getAllowedParams( $flags );
2162 if ( !$params ) {
2163 $params = [];
2164 }
2165
2166 if ( $this->needsToken() ) {
2167 $params['token'] = [
2168 self::PARAM_TYPE => 'string',
2169 self::PARAM_REQUIRED => true,
2170 self::PARAM_SENSITIVE => true,
2171 self::PARAM_HELP_MSG => [
2172 'api-help-param-token',
2173 $this->needsToken(),
2174 ],
2175 ] + ( isset( $params['token'] ) ? $params['token'] : [] );
2176 }
2177
2178 // Avoid PHP 7.1 warning of passing $this by reference
2179 $apiModule = $this;
2180 Hooks::run( 'APIGetAllowedParams', [ &$apiModule, &$params, $flags ] );
2181
2182 return $params;
2183 }
2184
2185 /**
2186 * Get final parameter descriptions, after hooks have had a chance to tweak it as
2187 * needed.
2188 *
2189 * @since 1.25, returns array of Message[] rather than array of string[]
2190 * @return array Keys are parameter names, values are arrays of Message objects
2191 */
2192 public function getFinalParamDescription() {
2193 $prefix = $this->getModulePrefix();
2194 $name = $this->getModuleName();
2195 $path = $this->getModulePath();
2196
2197 $desc = $this->getParamDescription();
2198
2199 // Avoid PHP 7.1 warning of passing $this by reference
2200 $apiModule = $this;
2201 Hooks::run( 'APIGetParamDescription', [ &$apiModule, &$desc ] );
2202
2203 if ( !$desc ) {
2204 $desc = [];
2205 }
2206 $desc = self::escapeWikiText( $desc );
2207
2208 $params = $this->getFinalParams( self::GET_VALUES_FOR_HELP );
2209 $msgs = [];
2210 foreach ( $params as $param => $settings ) {
2211 if ( !is_array( $settings ) ) {
2212 $settings = [];
2213 }
2214
2215 $d = isset( $desc[$param] ) ? $desc[$param] : '';
2216 if ( is_array( $d ) ) {
2217 // Special handling for prop parameters
2218 $d = array_map( function ( $line ) {
2219 if ( preg_match( '/^\s+(\S+)\s+-\s+(.+)$/', $line, $m ) ) {
2220 $line = "\n;{$m[1]}:{$m[2]}";
2221 }
2222 return $line;
2223 }, $d );
2224 $d = implode( ' ', $d );
2225 }
2226
2227 if ( isset( $settings[self::PARAM_HELP_MSG] ) ) {
2228 $msg = $settings[self::PARAM_HELP_MSG];
2229 } else {
2230 $msg = $this->msg( "apihelp-{$path}-param-{$param}" );
2231 if ( !$msg->exists() ) {
2232 $msg = $this->msg( 'api-help-fallback-parameter', $d );
2233 }
2234 }
2235 $msg = self::makeMessage( $msg, $this->getContext(),
2236 [ $prefix, $param, $name, $path ] );
2237 if ( !$msg ) {
2238 self::dieDebug( __METHOD__,
2239 'Value in ApiBase::PARAM_HELP_MSG is not valid' );
2240 }
2241 $msgs[$param] = [ $msg ];
2242
2243 if ( isset( $settings[self::PARAM_TYPE] ) &&
2244 $settings[self::PARAM_TYPE] === 'submodule'
2245 ) {
2246 if ( isset( $settings[self::PARAM_SUBMODULE_MAP] ) ) {
2247 $map = $settings[self::PARAM_SUBMODULE_MAP];
2248 } else {
2249 $prefix = $this->isMain() ? '' : ( $this->getModulePath() . '+' );
2250 $map = [];
2251 foreach ( $this->getModuleManager()->getNames( $param ) as $submoduleName ) {
2252 $map[$submoduleName] = $prefix . $submoduleName;
2253 }
2254 }
2255 ksort( $map );
2256 $submodules = [];
2257 $deprecatedSubmodules = [];
2258 foreach ( $map as $v => $m ) {
2259 $arr = &$submodules;
2260 $isDeprecated = false;
2261 $summary = null;
2262 try {
2263 $submod = $this->getModuleFromPath( $m );
2264 if ( $submod ) {
2265 $summary = $submod->getFinalSummary();
2266 $isDeprecated = $submod->isDeprecated();
2267 if ( $isDeprecated ) {
2268 $arr = &$deprecatedSubmodules;
2269 }
2270 }
2271 } catch ( ApiUsageException $ex ) {
2272 // Ignore
2273 }
2274 if ( $summary ) {
2275 $key = $summary->getKey();
2276 $params = $summary->getParams();
2277 } else {
2278 $key = 'api-help-undocumented-module';
2279 $params = [ $m ];
2280 }
2281 $m = new ApiHelpParamValueMessage( "[[Special:ApiHelp/$m|$v]]", $key, $params, $isDeprecated );
2282 $arr[] = $m->setContext( $this->getContext() );
2283 }
2284 $msgs[$param] = array_merge( $msgs[$param], $submodules, $deprecatedSubmodules );
2285 } elseif ( isset( $settings[self::PARAM_HELP_MSG_PER_VALUE] ) ) {
2286 if ( !is_array( $settings[self::PARAM_HELP_MSG_PER_VALUE] ) ) {
2287 self::dieDebug( __METHOD__,
2288 'ApiBase::PARAM_HELP_MSG_PER_VALUE is not valid' );
2289 }
2290 if ( !is_array( $settings[self::PARAM_TYPE] ) ) {
2291 self::dieDebug( __METHOD__,
2292 'ApiBase::PARAM_HELP_MSG_PER_VALUE may only be used when ' .
2293 'ApiBase::PARAM_TYPE is an array' );
2294 }
2295
2296 $valueMsgs = $settings[self::PARAM_HELP_MSG_PER_VALUE];
2297 $deprecatedValues = isset( $settings[self::PARAM_DEPRECATED_VALUES] )
2298 ? $settings[self::PARAM_DEPRECATED_VALUES]
2299 : [];
2300
2301 foreach ( $settings[self::PARAM_TYPE] as $value ) {
2302 if ( isset( $valueMsgs[$value] ) ) {
2303 $msg = $valueMsgs[$value];
2304 } else {
2305 $msg = "apihelp-{$path}-paramvalue-{$param}-{$value}";
2306 }
2307 $m = self::makeMessage( $msg, $this->getContext(),
2308 [ $prefix, $param, $name, $path, $value ] );
2309 if ( $m ) {
2310 $m = new ApiHelpParamValueMessage(
2311 $value,
2312 [ $m->getKey(), 'api-help-param-no-description' ],
2313 $m->getParams(),
2314 isset( $deprecatedValues[$value] )
2315 );
2316 $msgs[$param][] = $m->setContext( $this->getContext() );
2317 } else {
2318 self::dieDebug( __METHOD__,
2319 "Value in ApiBase::PARAM_HELP_MSG_PER_VALUE for $value is not valid" );
2320 }
2321 }
2322 }
2323
2324 if ( isset( $settings[self::PARAM_HELP_MSG_APPEND] ) ) {
2325 if ( !is_array( $settings[self::PARAM_HELP_MSG_APPEND] ) ) {
2326 self::dieDebug( __METHOD__,
2327 'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
2328 }
2329 foreach ( $settings[self::PARAM_HELP_MSG_APPEND] as $m ) {
2330 $m = self::makeMessage( $m, $this->getContext(),
2331 [ $prefix, $param, $name, $path ] );
2332 if ( $m ) {
2333 $msgs[$param][] = $m;
2334 } else {
2335 self::dieDebug( __METHOD__,
2336 'Value in ApiBase::PARAM_HELP_MSG_APPEND is not valid' );
2337 }
2338 }
2339 }
2340 }
2341
2342 Hooks::run( 'APIGetParamDescriptionMessages', [ $this, &$msgs ] );
2343
2344 return $msgs;
2345 }
2346
2347 /**
2348 * Generates the list of flags for the help screen and for action=paraminfo
2349 *
2350 * Corresponding messages: api-help-flag-deprecated,
2351 * api-help-flag-internal, api-help-flag-readrights,
2352 * api-help-flag-writerights, api-help-flag-mustbeposted
2353 *
2354 * @return string[]
2355 */
2356 protected function getHelpFlags() {
2357 $flags = [];
2358
2359 if ( $this->isDeprecated() ) {
2360 $flags[] = 'deprecated';
2361 }
2362 if ( $this->isInternal() ) {
2363 $flags[] = 'internal';
2364 }
2365 if ( $this->isReadMode() ) {
2366 $flags[] = 'readrights';
2367 }
2368 if ( $this->isWriteMode() ) {
2369 $flags[] = 'writerights';
2370 }
2371 if ( $this->mustBePosted() ) {
2372 $flags[] = 'mustbeposted';
2373 }
2374
2375 return $flags;
2376 }
2377
2378 /**
2379 * Returns information about the source of this module, if known
2380 *
2381 * Returned array is an array with the following keys:
2382 * - path: Install path
2383 * - name: Extension name, or "MediaWiki" for core
2384 * - namemsg: (optional) i18n message key for a display name
2385 * - license-name: (optional) Name of license
2386 *
2387 * @return array|null
2388 */
2389 protected function getModuleSourceInfo() {
2390 global $IP;
2391
2392 if ( $this->mModuleSource !== false ) {
2393 return $this->mModuleSource;
2394 }
2395
2396 // First, try to find where the module comes from...
2397 $rClass = new ReflectionClass( $this );
2398 $path = $rClass->getFileName();
2399 if ( !$path ) {
2400 // No path known?
2401 $this->mModuleSource = null;
2402 return null;
2403 }
2404 $path = realpath( $path ) ?: $path;
2405
2406 // Build map of extension directories to extension info
2407 if ( self::$extensionInfo === null ) {
2408 $extDir = $this->getConfig()->get( 'ExtensionDirectory' );
2409 self::$extensionInfo = [
2410 realpath( __DIR__ ) ?: __DIR__ => [
2411 'path' => $IP,
2412 'name' => 'MediaWiki',
2413 'license-name' => 'GPL-2.0+',
2414 ],
2415 realpath( "$IP/extensions" ) ?: "$IP/extensions" => null,
2416 realpath( $extDir ) ?: $extDir => null,
2417 ];
2418 $keep = [
2419 'path' => null,
2420 'name' => null,
2421 'namemsg' => null,
2422 'license-name' => null,
2423 ];
2424 foreach ( $this->getConfig()->get( 'ExtensionCredits' ) as $group ) {
2425 foreach ( $group as $ext ) {
2426 if ( !isset( $ext['path'] ) || !isset( $ext['name'] ) ) {
2427 // This shouldn't happen, but does anyway.
2428 continue;
2429 }
2430
2431 $extpath = $ext['path'];
2432 if ( !is_dir( $extpath ) ) {
2433 $extpath = dirname( $extpath );
2434 }
2435 self::$extensionInfo[realpath( $extpath ) ?: $extpath] =
2436 array_intersect_key( $ext, $keep );
2437 }
2438 }
2439 foreach ( ExtensionRegistry::getInstance()->getAllThings() as $ext ) {
2440 $extpath = $ext['path'];
2441 if ( !is_dir( $extpath ) ) {
2442 $extpath = dirname( $extpath );
2443 }
2444 self::$extensionInfo[realpath( $extpath ) ?: $extpath] =
2445 array_intersect_key( $ext, $keep );
2446 }
2447 }
2448
2449 // Now traverse parent directories until we find a match or run out of
2450 // parents.
2451 do {
2452 if ( array_key_exists( $path, self::$extensionInfo ) ) {
2453 // Found it!
2454 $this->mModuleSource = self::$extensionInfo[$path];
2455 return $this->mModuleSource;
2456 }
2457
2458 $oldpath = $path;
2459 $path = dirname( $path );
2460 } while ( $path !== $oldpath );
2461
2462 // No idea what extension this might be.
2463 $this->mModuleSource = null;
2464 return null;
2465 }
2466
2467 /**
2468 * Called from ApiHelp before the pieces are joined together and returned.
2469 *
2470 * This exists mainly for ApiMain to add the Permissions and Credits
2471 * sections. Other modules probably don't need it.
2472 *
2473 * @param string[] &$help Array of help data
2474 * @param array $options Options passed to ApiHelp::getHelp
2475 * @param array &$tocData If a TOC is being generated, this array has keys
2476 * as anchors in the page and values as for Linker::generateTOC().
2477 */
2478 public function modifyHelp( array &$help, array $options, array &$tocData ) {
2479 }
2480
2481 /**@}*/
2482
2483 /************************************************************************//**
2484 * @name Deprecated
2485 * @{
2486 */
2487
2488 /**
2489 * Returns the description string for this module
2490 *
2491 * Ignored if an i18n message exists for
2492 * "apihelp-{$this->getModulePath()}-description".
2493 *
2494 * @deprecated since 1.25
2495 * @return Message|string|array|false
2496 */
2497 protected function getDescription() {
2498 return false;
2499 }
2500
2501 /**
2502 * Returns an array of parameter descriptions.
2503 *
2504 * For each parameter, ignored if an i18n message exists for the parameter.
2505 * By default that message is
2506 * "apihelp-{$this->getModulePath()}-param-{$param}", but it may be
2507 * overridden using ApiBase::PARAM_HELP_MSG in the data returned by
2508 * self::getFinalParams().
2509 *
2510 * @deprecated since 1.25
2511 * @return array|bool False on no parameter descriptions
2512 */
2513 protected function getParamDescription() {
2514 return [];
2515 }
2516
2517 /**
2518 * Returns usage examples for this module.
2519 *
2520 * Return value as an array is either:
2521 * - numeric keys with partial URLs ("api.php?" plus a query string) as
2522 * values
2523 * - sequential numeric keys with even-numbered keys being display-text
2524 * and odd-numbered keys being partial urls
2525 * - partial URLs as keys with display-text (string or array-to-be-joined)
2526 * as values
2527 * Return value as a string is the same as an array with a numeric key and
2528 * that value, and boolean false means "no examples".
2529 *
2530 * @deprecated since 1.25, use getExamplesMessages() instead
2531 * @return bool|string|array
2532 */
2533 protected function getExamples() {
2534 return false;
2535 }
2536
2537 /**
2538 * @deprecated since 1.25, always returns empty string
2539 * @param IDatabase|bool $db
2540 * @return string
2541 */
2542 public function getModuleProfileName( $db = false ) {
2543 wfDeprecated( __METHOD__, '1.25' );
2544 return '';
2545 }
2546
2547 /**
2548 * @deprecated since 1.25
2549 */
2550 public function profileIn() {
2551 // No wfDeprecated() yet because extensions call this and might need to
2552 // keep doing so for BC.
2553 }
2554
2555 /**
2556 * @deprecated since 1.25
2557 */
2558 public function profileOut() {
2559 // No wfDeprecated() yet because extensions call this and might need to
2560 // keep doing so for BC.
2561 }
2562
2563 /**
2564 * @deprecated since 1.25
2565 */
2566 public function safeProfileOut() {
2567 wfDeprecated( __METHOD__, '1.25' );
2568 }
2569
2570 /**
2571 * @deprecated since 1.25, always returns 0
2572 * @return float
2573 */
2574 public function getProfileTime() {
2575 wfDeprecated( __METHOD__, '1.25' );
2576 return 0;
2577 }
2578
2579 /**
2580 * @deprecated since 1.25
2581 */
2582 public function profileDBIn() {
2583 wfDeprecated( __METHOD__, '1.25' );
2584 }
2585
2586 /**
2587 * @deprecated since 1.25
2588 */
2589 public function profileDBOut() {
2590 wfDeprecated( __METHOD__, '1.25' );
2591 }
2592
2593 /**
2594 * @deprecated since 1.25, always returns 0
2595 * @return float
2596 */
2597 public function getProfileDBTime() {
2598 wfDeprecated( __METHOD__, '1.25' );
2599 return 0;
2600 }
2601
2602 /**
2603 * Call wfTransactionalTimeLimit() if this request was POSTed
2604 * @since 1.26
2605 */
2606 protected function useTransactionalTimeLimit() {
2607 if ( $this->getRequest()->wasPosted() ) {
2608 wfTransactionalTimeLimit();
2609 }
2610 }
2611
2612 /**
2613 * @deprecated since 1.29, use ApiBase::addWarning() instead
2614 * @param string $warning Warning message
2615 */
2616 public function setWarning( $warning ) {
2617 wfDeprecated( __METHOD__, '1.29' );
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 wfDeprecated( __METHOD__, '1.29' );
2637 $this->dieWithError(
2638 new RawMessage( '$1', [ $description ] ),
2639 $errorCode,
2640 $extradata,
2641 $httpRespCode
2642 );
2643 }
2644
2645 /**
2646 * Get error (as code, string) from a Status object.
2647 *
2648 * @since 1.23
2649 * @deprecated since 1.29, use ApiErrorFormatter::arrayFromStatus instead
2650 * @param Status $status
2651 * @param array|null &$extraData Set if extra data from IApiMessage is available (since 1.27)
2652 * @return array Array of code and error string
2653 * @throws MWException
2654 */
2655 public function getErrorFromStatus( $status, &$extraData = null ) {
2656 wfDeprecated( __METHOD__, '1.29' );
2657 if ( $status->isGood() ) {
2658 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
2659 }
2660
2661 $errors = $status->getErrorsByType( 'error' );
2662 if ( !$errors ) {
2663 // No errors? Assume the warnings should be treated as errors
2664 $errors = $status->getErrorsByType( 'warning' );
2665 }
2666 if ( !$errors ) {
2667 // Still no errors? Punt
2668 $errors = [ [ 'message' => 'unknownerror-nocode', 'params' => [] ] ];
2669 }
2670
2671 if ( $errors[0]['message'] instanceof MessageSpecifier ) {
2672 $msg = $errors[0]['message'];
2673 } else {
2674 $msg = new Message( $errors[0]['message'], $errors[0]['params'] );
2675 }
2676 if ( !$msg instanceof IApiMessage ) {
2677 $key = $msg->getKey();
2678 $params = $msg->getParams();
2679 array_unshift( $params, isset( self::$messageMap[$key] ) ? self::$messageMap[$key] : $key );
2680 $msg = ApiMessage::create( $params );
2681 }
2682
2683 return [
2684 $msg->getApiCode(),
2685 ApiErrorFormatter::stripMarkup( $msg->inLanguage( 'en' )->useDatabase( false )->text() )
2686 ];
2687 }
2688
2689 /**
2690 * @deprecated since 1.29. Prior to 1.29, this was a public mapping from
2691 * arbitrary strings (often message keys used elsewhere in MediaWiki) to
2692 * API codes and message texts, and a few interfaces required poking
2693 * something in here. Now we're repurposing it to map those same strings
2694 * to i18n messages, and declaring that any interface that requires poking
2695 * at this is broken and needs replacing ASAP.
2696 */
2697 private static $messageMap = [
2698 'unknownerror' => 'apierror-unknownerror',
2699 'unknownerror-nocode' => 'apierror-unknownerror-nocode',
2700 'ns-specialprotected' => 'ns-specialprotected',
2701 'protectedinterface' => 'protectedinterface',
2702 'namespaceprotected' => 'namespaceprotected',
2703 'customcssprotected' => 'customcssprotected',
2704 'customjsprotected' => 'customjsprotected',
2705 'cascadeprotected' => 'cascadeprotected',
2706 'protectedpagetext' => 'protectedpagetext',
2707 'protect-cantedit' => 'protect-cantedit',
2708 'deleteprotected' => 'deleteprotected',
2709 'badaccess-group0' => 'badaccess-group0',
2710 'badaccess-groups' => 'badaccess-groups',
2711 'titleprotected' => 'titleprotected',
2712 'nocreate-loggedin' => 'nocreate-loggedin',
2713 'nocreatetext' => 'nocreatetext',
2714 'movenologintext' => 'movenologintext',
2715 'movenotallowed' => 'movenotallowed',
2716 'confirmedittext' => 'confirmedittext',
2717 'blockedtext' => 'apierror-blocked',
2718 'autoblockedtext' => 'apierror-autoblocked',
2719 'systemblockedtext' => 'apierror-systemblocked',
2720 'actionthrottledtext' => 'apierror-ratelimited',
2721 'alreadyrolled' => 'alreadyrolled',
2722 'cantrollback' => 'cantrollback',
2723 'readonlytext' => 'readonlytext',
2724 'sessionfailure' => 'sessionfailure',
2725 'cannotdelete' => 'cannotdelete',
2726 'notanarticle' => 'apierror-missingtitle',
2727 'selfmove' => 'selfmove',
2728 'immobile_namespace' => 'apierror-immobilenamespace',
2729 'articleexists' => 'articleexists',
2730 'hookaborted' => 'hookaborted',
2731 'cantmove-titleprotected' => 'cantmove-titleprotected',
2732 'imagenocrossnamespace' => 'imagenocrossnamespace',
2733 'imagetypemismatch' => 'imagetypemismatch',
2734 'ip_range_invalid' => 'ip_range_invalid',
2735 'range_block_disabled' => 'range_block_disabled',
2736 'nosuchusershort' => 'nosuchusershort',
2737 'badipaddress' => 'badipaddress',
2738 'ipb_expiry_invalid' => 'ipb_expiry_invalid',
2739 'ipb_already_blocked' => 'ipb_already_blocked',
2740 'ipb_blocked_as_range' => 'ipb_blocked_as_range',
2741 'ipb_cant_unblock' => 'ipb_cant_unblock',
2742 'mailnologin' => 'apierror-cantsend',
2743 'ipbblocked' => 'ipbblocked',
2744 'ipbnounblockself' => 'ipbnounblockself',
2745 'usermaildisabled' => 'usermaildisabled',
2746 'blockedemailuser' => 'apierror-blockedfrommail',
2747 'notarget' => 'apierror-notarget',
2748 'noemail' => 'noemail',
2749 'rcpatroldisabled' => 'rcpatroldisabled',
2750 'markedaspatrollederror-noautopatrol' => 'markedaspatrollederror-noautopatrol',
2751 'delete-toobig' => 'delete-toobig',
2752 'movenotallowedfile' => 'movenotallowedfile',
2753 'userrights-no-interwiki' => 'userrights-no-interwiki',
2754 'userrights-nodatabase' => 'userrights-nodatabase',
2755 'nouserspecified' => 'nouserspecified',
2756 'noname' => 'noname',
2757 'summaryrequired' => 'apierror-summaryrequired',
2758 'import-rootpage-invalid' => 'import-rootpage-invalid',
2759 'import-rootpage-nosubpage' => 'import-rootpage-nosubpage',
2760 'readrequired' => 'apierror-readapidenied',
2761 'writedisabled' => 'apierror-noapiwrite',
2762 'writerequired' => 'apierror-writeapidenied',
2763 'missingparam' => 'apierror-missingparam',
2764 'invalidtitle' => 'apierror-invalidtitle',
2765 'nosuchpageid' => 'apierror-nosuchpageid',
2766 'nosuchrevid' => 'apierror-nosuchrevid',
2767 'nosuchuser' => 'nosuchusershort',
2768 'invaliduser' => 'apierror-invaliduser',
2769 'invalidexpiry' => 'apierror-invalidexpiry',
2770 'pastexpiry' => 'apierror-pastexpiry',
2771 'create-titleexists' => 'apierror-create-titleexists',
2772 'missingtitle-createonly' => 'apierror-missingtitle-createonly',
2773 'cantblock' => 'apierror-cantblock',
2774 'canthide' => 'apierror-canthide',
2775 'cantblock-email' => 'apierror-cantblock-email',
2776 'cantunblock' => 'apierror-permissiondenied-generic',
2777 'cannotundelete' => 'cannotundelete',
2778 'permdenied-undelete' => 'apierror-permissiondenied-generic',
2779 'createonly-exists' => 'apierror-articleexists',
2780 'nocreate-missing' => 'apierror-missingtitle',
2781 'cantchangecontentmodel' => 'apierror-cantchangecontentmodel',
2782 'nosuchrcid' => 'apierror-nosuchrcid',
2783 'nosuchlogid' => 'apierror-nosuchlogid',
2784 'protect-invalidaction' => 'apierror-protect-invalidaction',
2785 'protect-invalidlevel' => 'apierror-protect-invalidlevel',
2786 'toofewexpiries' => 'apierror-toofewexpiries',
2787 'cantimport' => 'apierror-cantimport',
2788 'cantimport-upload' => 'apierror-cantimport-upload',
2789 'importnofile' => 'importnofile',
2790 'importuploaderrorsize' => 'importuploaderrorsize',
2791 'importuploaderrorpartial' => 'importuploaderrorpartial',
2792 'importuploaderrortemp' => 'importuploaderrortemp',
2793 'importcantopen' => 'importcantopen',
2794 'import-noarticle' => 'import-noarticle',
2795 'importbadinterwiki' => 'importbadinterwiki',
2796 'import-unknownerror' => 'apierror-import-unknownerror',
2797 'cantoverwrite-sharedfile' => 'apierror-cantoverwrite-sharedfile',
2798 'sharedfile-exists' => 'apierror-fileexists-sharedrepo-perm',
2799 'mustbeposted' => 'apierror-mustbeposted',
2800 'show' => 'apierror-show',
2801 'specialpage-cantexecute' => 'apierror-specialpage-cantexecute',
2802 'invalidoldimage' => 'apierror-invalidoldimage',
2803 'nodeleteablefile' => 'apierror-nodeleteablefile',
2804 'fileexists-forbidden' => 'fileexists-forbidden',
2805 'fileexists-shared-forbidden' => 'fileexists-shared-forbidden',
2806 'filerevert-badversion' => 'filerevert-badversion',
2807 'noimageredirect-anon' => 'apierror-noimageredirect-anon',
2808 'noimageredirect-logged' => 'apierror-noimageredirect',
2809 'spamdetected' => 'apierror-spamdetected',
2810 'contenttoobig' => 'apierror-contenttoobig',
2811 'noedit-anon' => 'apierror-noedit-anon',
2812 'noedit' => 'apierror-noedit',
2813 'wasdeleted' => 'apierror-pagedeleted',
2814 'blankpage' => 'apierror-emptypage',
2815 'editconflict' => 'editconflict',
2816 'hashcheckfailed' => 'apierror-badmd5',
2817 'missingtext' => 'apierror-notext',
2818 'emptynewsection' => 'apierror-emptynewsection',
2819 'revwrongpage' => 'apierror-revwrongpage',
2820 'undo-failure' => 'undo-failure',
2821 'content-not-allowed-here' => 'content-not-allowed-here',
2822 'edit-hook-aborted' => 'edit-hook-aborted',
2823 'edit-gone-missing' => 'edit-gone-missing',
2824 'edit-conflict' => 'edit-conflict',
2825 'edit-already-exists' => 'edit-already-exists',
2826 'invalid-file-key' => 'apierror-invalid-file-key',
2827 'nouploadmodule' => 'apierror-nouploadmodule',
2828 'uploaddisabled' => 'uploaddisabled',
2829 'copyuploaddisabled' => 'copyuploaddisabled',
2830 'copyuploadbaddomain' => 'apierror-copyuploadbaddomain',
2831 'copyuploadbadurl' => 'apierror-copyuploadbadurl',
2832 'filename-tooshort' => 'filename-tooshort',
2833 'filename-toolong' => 'filename-toolong',
2834 'illegal-filename' => 'illegal-filename',
2835 'filetype-missing' => 'filetype-missing',
2836 'mustbeloggedin' => 'apierror-mustbeloggedin',
2837 ];
2838
2839 /**
2840 * @deprecated do not use
2841 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2842 * @return ApiMessage
2843 */
2844 private function parseMsgInternal( $error ) {
2845 $msg = Message::newFromSpecifier( $error );
2846 if ( !$msg instanceof IApiMessage ) {
2847 $key = $msg->getKey();
2848 if ( isset( self::$messageMap[$key] ) ) {
2849 $params = $msg->getParams();
2850 array_unshift( $params, self::$messageMap[$key] );
2851 } else {
2852 $params = [ 'apierror-unknownerror', wfEscapeWikiText( $key ) ];
2853 }
2854 $msg = ApiMessage::create( $params );
2855 }
2856 return $msg;
2857 }
2858
2859 /**
2860 * Return the error message related to a certain array
2861 * @deprecated since 1.29
2862 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2863 * @return [ 'code' => code, 'info' => info ]
2864 */
2865 public function parseMsg( $error ) {
2866 wfDeprecated( __METHOD__, '1.29' );
2867 // Check whether someone passed the whole array, instead of one element as
2868 // documented. This breaks if it's actually an array of fallback keys, but
2869 // that's long-standing misbehavior introduced in r87627 to incorrectly
2870 // fix T30797.
2871 if ( is_array( $error ) ) {
2872 $first = reset( $error );
2873 if ( is_array( $first ) ) {
2874 wfDebug( __METHOD__ . ' was passed an array of arrays. ' . wfGetAllCallers( 5 ) );
2875 $error = $first;
2876 }
2877 }
2878
2879 $msg = $this->parseMsgInternal( $error );
2880 return [
2881 'code' => $msg->getApiCode(),
2882 'info' => ApiErrorFormatter::stripMarkup(
2883 $msg->inLanguage( 'en' )->useDatabase( false )->text()
2884 ),
2885 'data' => $msg->getApiData()
2886 ];
2887 }
2888
2889 /**
2890 * Output the error message related to a certain array
2891 * @deprecated since 1.29, use ApiBase::dieWithError() instead
2892 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2893 * @throws ApiUsageException always
2894 */
2895 public function dieUsageMsg( $error ) {
2896 wfDeprecated( __METHOD__, '1.29' );
2897 $this->dieWithError( $this->parseMsgInternal( $error ) );
2898 }
2899
2900 /**
2901 * Will only set a warning instead of failing if the global $wgDebugAPI
2902 * is set to true. Otherwise behaves exactly as dieUsageMsg().
2903 * @deprecated since 1.29, use ApiBase::dieWithErrorOrDebug() instead
2904 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2905 * @throws ApiUsageException
2906 * @since 1.21
2907 */
2908 public function dieUsageMsgOrDebug( $error ) {
2909 wfDeprecated( __METHOD__, '1.29' );
2910 $this->dieWithErrorOrDebug( $this->parseMsgInternal( $error ) );
2911 }
2912
2913 /**
2914 * Return the description message.
2915 *
2916 * This is additional text to display on the help page after the summary.
2917 *
2918 * @deprecated since 1.30
2919 * @return string|array|Message
2920 */
2921 protected function getDescriptionMessage() {
2922 return [ [
2923 "apihelp-{$this->getModulePath()}-description",
2924 "apihelp-{$this->getModulePath()}-summary",
2925 ] ];
2926 }
2927
2928 /**@}*/
2929 }
2930
2931 /**
2932 * For really cool vim folding this needs to be at the end:
2933 * vim: foldmarker=@{,@} foldmethod=marker
2934 */