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