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