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