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