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