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