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