a6c4b2ad19e80c0aace1ae97365c7dcd5cfd8137
[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 throw new ApiUsageException( $this, $status );
1867 }
1868
1869 /**
1870 * Helper function for readonly errors
1871 *
1872 * @throws ApiUsageException always
1873 */
1874 public function dieReadOnly() {
1875 $this->dieWithError(
1876 'apierror-readonly',
1877 'readonly',
1878 [ 'readonlyreason' => wfReadOnlyReason() ]
1879 );
1880 }
1881
1882 /**
1883 * Helper function for permission-denied errors
1884 * @since 1.29
1885 * @param string|string[] $rights
1886 * @param User|null $user
1887 * @throws ApiUsageException if the user doesn't have any of the rights.
1888 * The error message is based on $rights[0].
1889 */
1890 public function checkUserRightsAny( $rights, $user = null ) {
1891 if ( !$user ) {
1892 $user = $this->getUser();
1893 }
1894 $rights = (array)$rights;
1895 if ( !call_user_func_array( [ $user, 'isAllowedAny' ], $rights ) ) {
1896 $this->dieWithError( [ 'apierror-permissiondenied', $this->msg( "action-{$rights[0]}" ) ] );
1897 }
1898 }
1899
1900 /**
1901 * Helper function for permission-denied errors
1902 * @since 1.29
1903 * @param Title $title
1904 * @param string|string[] $actions
1905 * @param User|null $user
1906 * @throws ApiUsageException if the user doesn't have all of the rights.
1907 */
1908 public function checkTitleUserPermissions( Title $title, $actions, $user = null ) {
1909 if ( !$user ) {
1910 $user = $this->getUser();
1911 }
1912
1913 $errors = [];
1914 foreach ( (array)$actions as $action ) {
1915 $errors = array_merge( $errors, $title->getUserPermissionsErrors( $action, $user ) );
1916 }
1917 if ( $errors ) {
1918 $this->dieStatus( $this->errorArrayToStatus( $errors, $user ) );
1919 }
1920 }
1921
1922 /**
1923 * Will only set a warning instead of failing if the global $wgDebugAPI
1924 * is set to true. Otherwise behaves exactly as self::dieWithError().
1925 *
1926 * @since 1.29
1927 * @param string|array|Message $msg
1928 * @param string|null $code
1929 * @param array|null $data
1930 * @param int|null $httpCode
1931 * @throws ApiUsageException
1932 */
1933 public function dieWithErrorOrDebug( $msg, $code = null, $data = null, $httpCode = null ) {
1934 if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
1935 $this->dieWithError( $msg, $code, $data, $httpCode );
1936 } else {
1937 $this->addWarning( $msg, $code, $data );
1938 }
1939 }
1940
1941 /**
1942 * Die with the 'badcontinue' error.
1943 *
1944 * This call is common enough to make it into the base method.
1945 *
1946 * @param bool $condition Will only die if this value is true
1947 * @throws ApiUsageException
1948 * @since 1.21
1949 */
1950 protected function dieContinueUsageIf( $condition ) {
1951 if ( $condition ) {
1952 $this->dieWithError( 'apierror-badcontinue' );
1953 }
1954 }
1955
1956 /**
1957 * Internal code errors should be reported with this method
1958 * @param string $method Method or function name
1959 * @param string $message Error message
1960 * @throws MWException always
1961 */
1962 protected static function dieDebug( $method, $message ) {
1963 throw new MWException( "Internal error in $method: $message" );
1964 }
1965
1966 /**
1967 * Write logging information for API features to a debug log, for usage
1968 * analysis.
1969 * @note Consider using $this->addDeprecation() instead to both warn and log.
1970 * @param string $feature Feature being used.
1971 */
1972 public function logFeatureUsage( $feature ) {
1973 $request = $this->getRequest();
1974 $s = '"' . addslashes( $feature ) . '"' .
1975 ' "' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) . '"' .
1976 ' "' . $request->getIP() . '"' .
1977 ' "' . addslashes( $request->getHeader( 'Referer' ) ) . '"' .
1978 ' "' . addslashes( $this->getMain()->getUserAgent() ) . '"';
1979 wfDebugLog( 'api-feature-usage', $s, 'private' );
1980 }
1981
1982 /**@}*/
1983
1984 /************************************************************************//**
1985 * @name Help message generation
1986 * @{
1987 */
1988
1989 /**
1990 * Return the description message.
1991 *
1992 * @return string|array|Message
1993 */
1994 protected function getDescriptionMessage() {
1995 return "apihelp-{$this->getModulePath()}-description";
1996 }
1997
1998 /**
1999 * Get final module description, after hooks have had a chance to tweak it as
2000 * needed.
2001 *
2002 * @since 1.25, returns Message[] rather than string[]
2003 * @return Message[]
2004 */
2005 public function getFinalDescription() {
2006 $desc = $this->getDescription();
2007
2008 // Avoid PHP 7.1 warning of passing $this by reference
2009 $apiModule = $this;
2010 Hooks::run( 'APIGetDescription', [ &$apiModule, &$desc ] );
2011 $desc = self::escapeWikiText( $desc );
2012 if ( is_array( $desc ) ) {
2013 $desc = implode( "\n", $desc );
2014 } else {
2015 $desc = (string)$desc;
2016 }
2017
2018 $msg = ApiBase::makeMessage( $this->getDescriptionMessage(), $this->getContext(), [
2019 $this->getModulePrefix(),
2020 $this->getModuleName(),
2021 $this->getModulePath(),
2022 ] );
2023 if ( !$msg->exists() ) {
2024 $msg = $this->msg( 'api-help-fallback-description', $desc );
2025 }
2026 $msgs = [ $msg ];
2027
2028 Hooks::run( 'APIGetDescriptionMessages', [ $this, &$msgs ] );
2029
2030 return $msgs;
2031 }
2032
2033 /**
2034 * Get final list of parameters, after hooks have had a chance to
2035 * tweak it as needed.
2036 *
2037 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
2038 * @return array|bool False on no parameters
2039 * @since 1.21 $flags param added
2040 */
2041 public function getFinalParams( $flags = 0 ) {
2042 $params = $this->getAllowedParams( $flags );
2043 if ( !$params ) {
2044 $params = [];
2045 }
2046
2047 if ( $this->needsToken() ) {
2048 $params['token'] = [
2049 ApiBase::PARAM_TYPE => 'string',
2050 ApiBase::PARAM_REQUIRED => true,
2051 ApiBase::PARAM_SENSITIVE => true,
2052 ApiBase::PARAM_HELP_MSG => [
2053 'api-help-param-token',
2054 $this->needsToken(),
2055 ],
2056 ] + ( isset( $params['token'] ) ? $params['token'] : [] );
2057 }
2058
2059 // Avoid PHP 7.1 warning of passing $this by reference
2060 $apiModule = $this;
2061 Hooks::run( 'APIGetAllowedParams', [ &$apiModule, &$params, $flags ] );
2062
2063 return $params;
2064 }
2065
2066 /**
2067 * Get final parameter descriptions, after hooks have had a chance to tweak it as
2068 * needed.
2069 *
2070 * @since 1.25, returns array of Message[] rather than array of string[]
2071 * @return array Keys are parameter names, values are arrays of Message objects
2072 */
2073 public function getFinalParamDescription() {
2074 $prefix = $this->getModulePrefix();
2075 $name = $this->getModuleName();
2076 $path = $this->getModulePath();
2077
2078 $desc = $this->getParamDescription();
2079
2080 // Avoid PHP 7.1 warning of passing $this by reference
2081 $apiModule = $this;
2082 Hooks::run( 'APIGetParamDescription', [ &$apiModule, &$desc ] );
2083
2084 if ( !$desc ) {
2085 $desc = [];
2086 }
2087 $desc = self::escapeWikiText( $desc );
2088
2089 $params = $this->getFinalParams( ApiBase::GET_VALUES_FOR_HELP );
2090 $msgs = [];
2091 foreach ( $params as $param => $settings ) {
2092 if ( !is_array( $settings ) ) {
2093 $settings = [];
2094 }
2095
2096 $d = isset( $desc[$param] ) ? $desc[$param] : '';
2097 if ( is_array( $d ) ) {
2098 // Special handling for prop parameters
2099 $d = array_map( function ( $line ) {
2100 if ( preg_match( '/^\s+(\S+)\s+-\s+(.+)$/', $line, $m ) ) {
2101 $line = "\n;{$m[1]}:{$m[2]}";
2102 }
2103 return $line;
2104 }, $d );
2105 $d = implode( ' ', $d );
2106 }
2107
2108 if ( isset( $settings[ApiBase::PARAM_HELP_MSG] ) ) {
2109 $msg = $settings[ApiBase::PARAM_HELP_MSG];
2110 } else {
2111 $msg = $this->msg( "apihelp-{$path}-param-{$param}" );
2112 if ( !$msg->exists() ) {
2113 $msg = $this->msg( 'api-help-fallback-parameter', $d );
2114 }
2115 }
2116 $msg = ApiBase::makeMessage( $msg, $this->getContext(),
2117 [ $prefix, $param, $name, $path ] );
2118 if ( !$msg ) {
2119 self::dieDebug( __METHOD__,
2120 'Value in ApiBase::PARAM_HELP_MSG is not valid' );
2121 }
2122 $msgs[$param] = [ $msg ];
2123
2124 if ( isset( $settings[ApiBase::PARAM_HELP_MSG_PER_VALUE] ) ) {
2125 if ( !is_array( $settings[ApiBase::PARAM_HELP_MSG_PER_VALUE] ) ) {
2126 self::dieDebug( __METHOD__,
2127 'ApiBase::PARAM_HELP_MSG_PER_VALUE is not valid' );
2128 }
2129 if ( !is_array( $settings[ApiBase::PARAM_TYPE] ) ) {
2130 self::dieDebug( __METHOD__,
2131 'ApiBase::PARAM_HELP_MSG_PER_VALUE may only be used when ' .
2132 'ApiBase::PARAM_TYPE is an array' );
2133 }
2134
2135 $valueMsgs = $settings[ApiBase::PARAM_HELP_MSG_PER_VALUE];
2136 foreach ( $settings[ApiBase::PARAM_TYPE] as $value ) {
2137 if ( isset( $valueMsgs[$value] ) ) {
2138 $msg = $valueMsgs[$value];
2139 } else {
2140 $msg = "apihelp-{$path}-paramvalue-{$param}-{$value}";
2141 }
2142 $m = ApiBase::makeMessage( $msg, $this->getContext(),
2143 [ $prefix, $param, $name, $path, $value ] );
2144 if ( $m ) {
2145 $m = new ApiHelpParamValueMessage(
2146 $value,
2147 [ $m->getKey(), 'api-help-param-no-description' ],
2148 $m->getParams()
2149 );
2150 $msgs[$param][] = $m->setContext( $this->getContext() );
2151 } else {
2152 self::dieDebug( __METHOD__,
2153 "Value in ApiBase::PARAM_HELP_MSG_PER_VALUE for $value is not valid" );
2154 }
2155 }
2156 }
2157
2158 if ( isset( $settings[ApiBase::PARAM_HELP_MSG_APPEND] ) ) {
2159 if ( !is_array( $settings[ApiBase::PARAM_HELP_MSG_APPEND] ) ) {
2160 self::dieDebug( __METHOD__,
2161 'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
2162 }
2163 foreach ( $settings[ApiBase::PARAM_HELP_MSG_APPEND] as $m ) {
2164 $m = ApiBase::makeMessage( $m, $this->getContext(),
2165 [ $prefix, $param, $name, $path ] );
2166 if ( $m ) {
2167 $msgs[$param][] = $m;
2168 } else {
2169 self::dieDebug( __METHOD__,
2170 'Value in ApiBase::PARAM_HELP_MSG_APPEND is not valid' );
2171 }
2172 }
2173 }
2174 }
2175
2176 Hooks::run( 'APIGetParamDescriptionMessages', [ $this, &$msgs ] );
2177
2178 return $msgs;
2179 }
2180
2181 /**
2182 * Generates the list of flags for the help screen and for action=paraminfo
2183 *
2184 * Corresponding messages: api-help-flag-deprecated,
2185 * api-help-flag-internal, api-help-flag-readrights,
2186 * api-help-flag-writerights, api-help-flag-mustbeposted
2187 *
2188 * @return string[]
2189 */
2190 protected function getHelpFlags() {
2191 $flags = [];
2192
2193 if ( $this->isDeprecated() ) {
2194 $flags[] = 'deprecated';
2195 }
2196 if ( $this->isInternal() ) {
2197 $flags[] = 'internal';
2198 }
2199 if ( $this->isReadMode() ) {
2200 $flags[] = 'readrights';
2201 }
2202 if ( $this->isWriteMode() ) {
2203 $flags[] = 'writerights';
2204 }
2205 if ( $this->mustBePosted() ) {
2206 $flags[] = 'mustbeposted';
2207 }
2208
2209 return $flags;
2210 }
2211
2212 /**
2213 * Returns information about the source of this module, if known
2214 *
2215 * Returned array is an array with the following keys:
2216 * - path: Install path
2217 * - name: Extension name, or "MediaWiki" for core
2218 * - namemsg: (optional) i18n message key for a display name
2219 * - license-name: (optional) Name of license
2220 *
2221 * @return array|null
2222 */
2223 protected function getModuleSourceInfo() {
2224 global $IP;
2225
2226 if ( $this->mModuleSource !== false ) {
2227 return $this->mModuleSource;
2228 }
2229
2230 // First, try to find where the module comes from...
2231 $rClass = new ReflectionClass( $this );
2232 $path = $rClass->getFileName();
2233 if ( !$path ) {
2234 // No path known?
2235 $this->mModuleSource = null;
2236 return null;
2237 }
2238 $path = realpath( $path ) ?: $path;
2239
2240 // Build map of extension directories to extension info
2241 if ( self::$extensionInfo === null ) {
2242 $extDir = $this->getConfig()->get( 'ExtensionDirectory' );
2243 self::$extensionInfo = [
2244 realpath( __DIR__ ) ?: __DIR__ => [
2245 'path' => $IP,
2246 'name' => 'MediaWiki',
2247 'license-name' => 'GPL-2.0+',
2248 ],
2249 realpath( "$IP/extensions" ) ?: "$IP/extensions" => null,
2250 realpath( $extDir ) ?: $extDir => null,
2251 ];
2252 $keep = [
2253 'path' => null,
2254 'name' => null,
2255 'namemsg' => null,
2256 'license-name' => null,
2257 ];
2258 foreach ( $this->getConfig()->get( 'ExtensionCredits' ) as $group ) {
2259 foreach ( $group as $ext ) {
2260 if ( !isset( $ext['path'] ) || !isset( $ext['name'] ) ) {
2261 // This shouldn't happen, but does anyway.
2262 continue;
2263 }
2264
2265 $extpath = $ext['path'];
2266 if ( !is_dir( $extpath ) ) {
2267 $extpath = dirname( $extpath );
2268 }
2269 self::$extensionInfo[realpath( $extpath ) ?: $extpath] =
2270 array_intersect_key( $ext, $keep );
2271 }
2272 }
2273 foreach ( ExtensionRegistry::getInstance()->getAllThings() as $ext ) {
2274 $extpath = $ext['path'];
2275 if ( !is_dir( $extpath ) ) {
2276 $extpath = dirname( $extpath );
2277 }
2278 self::$extensionInfo[realpath( $extpath ) ?: $extpath] =
2279 array_intersect_key( $ext, $keep );
2280 }
2281 }
2282
2283 // Now traverse parent directories until we find a match or run out of
2284 // parents.
2285 do {
2286 if ( array_key_exists( $path, self::$extensionInfo ) ) {
2287 // Found it!
2288 $this->mModuleSource = self::$extensionInfo[$path];
2289 return $this->mModuleSource;
2290 }
2291
2292 $oldpath = $path;
2293 $path = dirname( $path );
2294 } while ( $path !== $oldpath );
2295
2296 // No idea what extension this might be.
2297 $this->mModuleSource = null;
2298 return null;
2299 }
2300
2301 /**
2302 * Called from ApiHelp before the pieces are joined together and returned.
2303 *
2304 * This exists mainly for ApiMain to add the Permissions and Credits
2305 * sections. Other modules probably don't need it.
2306 *
2307 * @param string[] &$help Array of help data
2308 * @param array $options Options passed to ApiHelp::getHelp
2309 * @param array &$tocData If a TOC is being generated, this array has keys
2310 * as anchors in the page and values as for Linker::generateTOC().
2311 */
2312 public function modifyHelp( array &$help, array $options, array &$tocData ) {
2313 }
2314
2315 /**@}*/
2316
2317 /************************************************************************//**
2318 * @name Deprecated
2319 * @{
2320 */
2321
2322 /**
2323 * Returns the description string for this module
2324 *
2325 * Ignored if an i18n message exists for
2326 * "apihelp-{$this->getModulePath()}-description".
2327 *
2328 * @deprecated since 1.25
2329 * @return Message|string|array|false
2330 */
2331 protected function getDescription() {
2332 return false;
2333 }
2334
2335 /**
2336 * Returns an array of parameter descriptions.
2337 *
2338 * For each parameter, ignored if an i18n message exists for the parameter.
2339 * By default that message is
2340 * "apihelp-{$this->getModulePath()}-param-{$param}", but it may be
2341 * overridden using ApiBase::PARAM_HELP_MSG in the data returned by
2342 * self::getFinalParams().
2343 *
2344 * @deprecated since 1.25
2345 * @return array|bool False on no parameter descriptions
2346 */
2347 protected function getParamDescription() {
2348 return [];
2349 }
2350
2351 /**
2352 * Returns usage examples for this module.
2353 *
2354 * Return value as an array is either:
2355 * - numeric keys with partial URLs ("api.php?" plus a query string) as
2356 * values
2357 * - sequential numeric keys with even-numbered keys being display-text
2358 * and odd-numbered keys being partial urls
2359 * - partial URLs as keys with display-text (string or array-to-be-joined)
2360 * as values
2361 * Return value as a string is the same as an array with a numeric key and
2362 * that value, and boolean false means "no examples".
2363 *
2364 * @deprecated since 1.25, use getExamplesMessages() instead
2365 * @return bool|string|array
2366 */
2367 protected function getExamples() {
2368 return false;
2369 }
2370
2371 /**
2372 * @deprecated since 1.25, always returns empty string
2373 * @param IDatabase|bool $db
2374 * @return string
2375 */
2376 public function getModuleProfileName( $db = false ) {
2377 wfDeprecated( __METHOD__, '1.25' );
2378 return '';
2379 }
2380
2381 /**
2382 * @deprecated since 1.25
2383 */
2384 public function profileIn() {
2385 // No wfDeprecated() yet because extensions call this and might need to
2386 // keep doing so for BC.
2387 }
2388
2389 /**
2390 * @deprecated since 1.25
2391 */
2392 public function profileOut() {
2393 // No wfDeprecated() yet because extensions call this and might need to
2394 // keep doing so for BC.
2395 }
2396
2397 /**
2398 * @deprecated since 1.25
2399 */
2400 public function safeProfileOut() {
2401 wfDeprecated( __METHOD__, '1.25' );
2402 }
2403
2404 /**
2405 * @deprecated since 1.25, always returns 0
2406 * @return float
2407 */
2408 public function getProfileTime() {
2409 wfDeprecated( __METHOD__, '1.25' );
2410 return 0;
2411 }
2412
2413 /**
2414 * @deprecated since 1.25
2415 */
2416 public function profileDBIn() {
2417 wfDeprecated( __METHOD__, '1.25' );
2418 }
2419
2420 /**
2421 * @deprecated since 1.25
2422 */
2423 public function profileDBOut() {
2424 wfDeprecated( __METHOD__, '1.25' );
2425 }
2426
2427 /**
2428 * @deprecated since 1.25, always returns 0
2429 * @return float
2430 */
2431 public function getProfileDBTime() {
2432 wfDeprecated( __METHOD__, '1.25' );
2433 return 0;
2434 }
2435
2436 /**
2437 * Call wfTransactionalTimeLimit() if this request was POSTed
2438 * @since 1.26
2439 */
2440 protected function useTransactionalTimeLimit() {
2441 if ( $this->getRequest()->wasPosted() ) {
2442 wfTransactionalTimeLimit();
2443 }
2444 }
2445
2446 /**
2447 * @deprecated since 1.29, use ApiBase::addWarning() instead
2448 * @param string $warning Warning message
2449 */
2450 public function setWarning( $warning ) {
2451 $msg = new ApiRawMessage( $warning, 'warning' );
2452 $this->getErrorFormatter()->addWarning( $this->getModulePath(), $msg );
2453 }
2454
2455 /**
2456 * Throw an ApiUsageException, which will (if uncaught) call the main module's
2457 * error handler and die with an error message.
2458 *
2459 * @deprecated since 1.29, use self::dieWithError() instead
2460 * @param string $description One-line human-readable description of the
2461 * error condition, e.g., "The API requires a valid action parameter"
2462 * @param string $errorCode Brief, arbitrary, stable string to allow easy
2463 * automated identification of the error, e.g., 'unknown_action'
2464 * @param int $httpRespCode HTTP response code
2465 * @param array|null $extradata Data to add to the "<error>" element; array in ApiResult format
2466 * @throws ApiUsageException always
2467 */
2468 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
2469 $this->dieWithError(
2470 new RawMessage( '$1', [ $description ] ),
2471 $errorCode,
2472 $extradata,
2473 $httpRespCode
2474 );
2475 }
2476
2477 /**
2478 * Get error (as code, string) from a Status object.
2479 *
2480 * @since 1.23
2481 * @deprecated since 1.29, use ApiErrorFormatter::arrayFromStatus instead
2482 * @param Status $status
2483 * @param array|null &$extraData Set if extra data from IApiMessage is available (since 1.27)
2484 * @return array Array of code and error string
2485 * @throws MWException
2486 */
2487 public function getErrorFromStatus( $status, &$extraData = null ) {
2488 if ( $status->isGood() ) {
2489 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
2490 }
2491
2492 $errors = $status->getErrorsByType( 'error' );
2493 if ( !$errors ) {
2494 // No errors? Assume the warnings should be treated as errors
2495 $errors = $status->getErrorsByType( 'warning' );
2496 }
2497 if ( !$errors ) {
2498 // Still no errors? Punt
2499 $errors = [ [ 'message' => 'unknownerror-nocode', 'params' => [] ] ];
2500 }
2501
2502 if ( $errors[0]['message'] instanceof MessageSpecifier ) {
2503 $msg = $errors[0]['message'];
2504 } else {
2505 $msg = new Message( $errors[0]['message'], $errors[0]['params'] );
2506 }
2507 if ( !$msg instanceof IApiMessage ) {
2508 $key = $msg->getKey();
2509 $params = $msg->getParams();
2510 array_unshift( $params, isset( self::$messageMap[$key] ) ? self::$messageMap[$key] : $key );
2511 $msg = ApiMessage::create( $params );
2512 }
2513
2514 return [
2515 $msg->getApiCode(),
2516 ApiErrorFormatter::stripMarkup( $msg->inLanguage( 'en' )->useDatabase( false )->text() )
2517 ];
2518 }
2519
2520 /**
2521 * @deprecated since 1.29. Prior to 1.29, this was a public mapping from
2522 * arbitrary strings (often message keys used elsewhere in MediaWiki) to
2523 * API codes and message texts, and a few interfaces required poking
2524 * something in here. Now we're repurposing it to map those same strings
2525 * to i18n messages, and declaring that any interface that requires poking
2526 * at this is broken and needs replacing ASAP.
2527 */
2528 private static $messageMap = [
2529 'unknownerror' => 'apierror-unknownerror',
2530 'unknownerror-nocode' => 'apierror-unknownerror-nocode',
2531 'ns-specialprotected' => 'ns-specialprotected',
2532 'protectedinterface' => 'protectedinterface',
2533 'namespaceprotected' => 'namespaceprotected',
2534 'customcssprotected' => 'customcssprotected',
2535 'customjsprotected' => 'customjsprotected',
2536 'cascadeprotected' => 'cascadeprotected',
2537 'protectedpagetext' => 'protectedpagetext',
2538 'protect-cantedit' => 'protect-cantedit',
2539 'deleteprotected' => 'deleteprotected',
2540 'badaccess-group0' => 'badaccess-group0',
2541 'badaccess-groups' => 'badaccess-groups',
2542 'titleprotected' => 'titleprotected',
2543 'nocreate-loggedin' => 'nocreate-loggedin',
2544 'nocreatetext' => 'nocreatetext',
2545 'movenologintext' => 'movenologintext',
2546 'movenotallowed' => 'movenotallowed',
2547 'confirmedittext' => 'confirmedittext',
2548 'blockedtext' => 'apierror-blocked',
2549 'autoblockedtext' => 'apierror-autoblocked',
2550 'systemblockedtext' => 'apierror-systemblocked',
2551 'actionthrottledtext' => 'apierror-ratelimited',
2552 'alreadyrolled' => 'alreadyrolled',
2553 'cantrollback' => 'cantrollback',
2554 'readonlytext' => 'readonlytext',
2555 'sessionfailure' => 'sessionfailure',
2556 'cannotdelete' => 'cannotdelete',
2557 'notanarticle' => 'apierror-missingtitle',
2558 'selfmove' => 'selfmove',
2559 'immobile_namespace' => 'apierror-immobilenamespace',
2560 'articleexists' => 'articleexists',
2561 'hookaborted' => 'hookaborted',
2562 'cantmove-titleprotected' => 'cantmove-titleprotected',
2563 'imagenocrossnamespace' => 'imagenocrossnamespace',
2564 'imagetypemismatch' => 'imagetypemismatch',
2565 'ip_range_invalid' => 'ip_range_invalid',
2566 'range_block_disabled' => 'range_block_disabled',
2567 'nosuchusershort' => 'nosuchusershort',
2568 'badipaddress' => 'badipaddress',
2569 'ipb_expiry_invalid' => 'ipb_expiry_invalid',
2570 'ipb_already_blocked' => 'ipb_already_blocked',
2571 'ipb_blocked_as_range' => 'ipb_blocked_as_range',
2572 'ipb_cant_unblock' => 'ipb_cant_unblock',
2573 'mailnologin' => 'apierror-cantsend',
2574 'ipbblocked' => 'ipbblocked',
2575 'ipbnounblockself' => 'ipbnounblockself',
2576 'usermaildisabled' => 'usermaildisabled',
2577 'blockedemailuser' => 'apierror-blockedfrommail',
2578 'notarget' => 'apierror-notarget',
2579 'noemail' => 'noemail',
2580 'rcpatroldisabled' => 'rcpatroldisabled',
2581 'markedaspatrollederror-noautopatrol' => 'markedaspatrollederror-noautopatrol',
2582 'delete-toobig' => 'delete-toobig',
2583 'movenotallowedfile' => 'movenotallowedfile',
2584 'userrights-no-interwiki' => 'userrights-no-interwiki',
2585 'userrights-nodatabase' => 'userrights-nodatabase',
2586 'nouserspecified' => 'nouserspecified',
2587 'noname' => 'noname',
2588 'summaryrequired' => 'apierror-summaryrequired',
2589 'import-rootpage-invalid' => 'import-rootpage-invalid',
2590 'import-rootpage-nosubpage' => 'import-rootpage-nosubpage',
2591 'readrequired' => 'apierror-readapidenied',
2592 'writedisabled' => 'apierror-noapiwrite',
2593 'writerequired' => 'apierror-writeapidenied',
2594 'missingparam' => 'apierror-missingparam',
2595 'invalidtitle' => 'apierror-invalidtitle',
2596 'nosuchpageid' => 'apierror-nosuchpageid',
2597 'nosuchrevid' => 'apierror-nosuchrevid',
2598 'nosuchuser' => 'nosuchusershort',
2599 'invaliduser' => 'apierror-invaliduser',
2600 'invalidexpiry' => 'apierror-invalidexpiry',
2601 'pastexpiry' => 'apierror-pastexpiry',
2602 'create-titleexists' => 'apierror-create-titleexists',
2603 'missingtitle-createonly' => 'apierror-missingtitle-createonly',
2604 'cantblock' => 'apierror-cantblock',
2605 'canthide' => 'apierror-canthide',
2606 'cantblock-email' => 'apierror-cantblock-email',
2607 'cantunblock' => 'apierror-permissiondenied-generic',
2608 'cannotundelete' => 'cannotundelete',
2609 'permdenied-undelete' => 'apierror-permissiondenied-generic',
2610 'createonly-exists' => 'apierror-articleexists',
2611 'nocreate-missing' => 'apierror-missingtitle',
2612 'cantchangecontentmodel' => 'apierror-cantchangecontentmodel',
2613 'nosuchrcid' => 'apierror-nosuchrcid',
2614 'nosuchlogid' => 'apierror-nosuchlogid',
2615 'protect-invalidaction' => 'apierror-protect-invalidaction',
2616 'protect-invalidlevel' => 'apierror-protect-invalidlevel',
2617 'toofewexpiries' => 'apierror-toofewexpiries',
2618 'cantimport' => 'apierror-cantimport',
2619 'cantimport-upload' => 'apierror-cantimport-upload',
2620 'importnofile' => 'importnofile',
2621 'importuploaderrorsize' => 'importuploaderrorsize',
2622 'importuploaderrorpartial' => 'importuploaderrorpartial',
2623 'importuploaderrortemp' => 'importuploaderrortemp',
2624 'importcantopen' => 'importcantopen',
2625 'import-noarticle' => 'import-noarticle',
2626 'importbadinterwiki' => 'importbadinterwiki',
2627 'import-unknownerror' => 'apierror-import-unknownerror',
2628 'cantoverwrite-sharedfile' => 'apierror-cantoverwrite-sharedfile',
2629 'sharedfile-exists' => 'apierror-fileexists-sharedrepo-perm',
2630 'mustbeposted' => 'apierror-mustbeposted',
2631 'show' => 'apierror-show',
2632 'specialpage-cantexecute' => 'apierror-specialpage-cantexecute',
2633 'invalidoldimage' => 'apierror-invalidoldimage',
2634 'nodeleteablefile' => 'apierror-nodeleteablefile',
2635 'fileexists-forbidden' => 'fileexists-forbidden',
2636 'fileexists-shared-forbidden' => 'fileexists-shared-forbidden',
2637 'filerevert-badversion' => 'filerevert-badversion',
2638 'noimageredirect-anon' => 'apierror-noimageredirect-anon',
2639 'noimageredirect-logged' => 'apierror-noimageredirect',
2640 'spamdetected' => 'apierror-spamdetected',
2641 'contenttoobig' => 'apierror-contenttoobig',
2642 'noedit-anon' => 'apierror-noedit-anon',
2643 'noedit' => 'apierror-noedit',
2644 'wasdeleted' => 'apierror-pagedeleted',
2645 'blankpage' => 'apierror-emptypage',
2646 'editconflict' => 'editconflict',
2647 'hashcheckfailed' => 'apierror-badmd5',
2648 'missingtext' => 'apierror-notext',
2649 'emptynewsection' => 'apierror-emptynewsection',
2650 'revwrongpage' => 'apierror-revwrongpage',
2651 'undo-failure' => 'undo-failure',
2652 'content-not-allowed-here' => 'content-not-allowed-here',
2653 'edit-hook-aborted' => 'edit-hook-aborted',
2654 'edit-gone-missing' => 'edit-gone-missing',
2655 'edit-conflict' => 'edit-conflict',
2656 'edit-already-exists' => 'edit-already-exists',
2657 'invalid-file-key' => 'apierror-invalid-file-key',
2658 'nouploadmodule' => 'apierror-nouploadmodule',
2659 'uploaddisabled' => 'uploaddisabled',
2660 'copyuploaddisabled' => 'copyuploaddisabled',
2661 'copyuploadbaddomain' => 'apierror-copyuploadbaddomain',
2662 'copyuploadbadurl' => 'apierror-copyuploadbadurl',
2663 'filename-tooshort' => 'filename-tooshort',
2664 'filename-toolong' => 'filename-toolong',
2665 'illegal-filename' => 'illegal-filename',
2666 'filetype-missing' => 'filetype-missing',
2667 'mustbeloggedin' => 'apierror-mustbeloggedin',
2668 ];
2669
2670 /**
2671 * @deprecated do not use
2672 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2673 * @return ApiMessage
2674 */
2675 private function parseMsgInternal( $error ) {
2676 $msg = Message::newFromSpecifier( $error );
2677 if ( !$msg instanceof IApiMessage ) {
2678 $key = $msg->getKey();
2679 if ( isset( self::$messageMap[$key] ) ) {
2680 $params = $msg->getParams();
2681 array_unshift( $params, self::$messageMap[$key] );
2682 } else {
2683 $params = [ 'apierror-unknownerror', wfEscapeWikiText( $key ) ];
2684 }
2685 $msg = ApiMessage::create( $params );
2686 }
2687 return $msg;
2688 }
2689
2690 /**
2691 * Return the error message related to a certain array
2692 * @deprecated since 1.29
2693 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2694 * @return [ 'code' => code, 'info' => info ]
2695 */
2696 public function parseMsg( $error ) {
2697 // Check whether someone passed the whole array, instead of one element as
2698 // documented. This breaks if it's actually an array of fallback keys, but
2699 // that's long-standing misbehavior introduced in r87627 to incorrectly
2700 // fix T30797.
2701 if ( is_array( $error ) ) {
2702 $first = reset( $error );
2703 if ( is_array( $first ) ) {
2704 wfDebug( __METHOD__ . ' was passed an array of arrays. ' . wfGetAllCallers( 5 ) );
2705 $error = $first;
2706 }
2707 }
2708
2709 $msg = $this->parseMsgInternal( $error );
2710 return [
2711 'code' => $msg->getApiCode(),
2712 'info' => ApiErrorFormatter::stripMarkup(
2713 $msg->inLanguage( 'en' )->useDatabase( false )->text()
2714 ),
2715 'data' => $msg->getApiData()
2716 ];
2717 }
2718
2719 /**
2720 * Output the error message related to a certain array
2721 * @deprecated since 1.29, use ApiBase::dieWithError() instead
2722 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2723 * @throws ApiUsageException always
2724 */
2725 public function dieUsageMsg( $error ) {
2726 $this->dieWithError( $this->parseMsgInternal( $error ) );
2727 }
2728
2729 /**
2730 * Will only set a warning instead of failing if the global $wgDebugAPI
2731 * is set to true. Otherwise behaves exactly as dieUsageMsg().
2732 * @deprecated since 1.29, use ApiBase::dieWithErrorOrDebug() instead
2733 * @param array|string|MessageSpecifier $error Element of a getUserPermissionsErrors()-style array
2734 * @throws ApiUsageException
2735 * @since 1.21
2736 */
2737 public function dieUsageMsgOrDebug( $error ) {
2738 $this->dieWithErrorOrDebug( $this->parseMsgInternal( $error ) );
2739 }
2740
2741 /**@}*/
2742 }
2743
2744 /**
2745 * For really cool vim folding this needs to be at the end:
2746 * vim: foldmarker=@{,@} foldmethod=marker
2747 */