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