Merge "Make sql.php exit status more informative"
[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 } elseif ( $type == 'upload' ) {
1161 if ( isset( $default ) ) {
1162 // Having a default value is not allowed
1163 self::dieDebug(
1164 __METHOD__,
1165 "File upload param $encParamName's default is set to " .
1166 "'$default'. File upload parameters may not have a default." );
1167 }
1168 if ( $multi ) {
1169 self::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
1170 }
1171 $value = $this->getMain()->getUpload( $encParamName );
1172 if ( !$value->exists() ) {
1173 // This will get the value without trying to normalize it
1174 // (because trying to normalize a large binary file
1175 // accidentally uploaded as a field fails spectacularly)
1176 $value = $this->getMain()->getRequest()->unsetVal( $encParamName );
1177 if ( $value !== null ) {
1178 $this->dieWithError(
1179 [ 'apierror-badupload', $encParamName ],
1180 "badupload_{$encParamName}"
1181 );
1182 }
1183 }
1184 } else {
1185 $value = $this->getMain()->getVal( $encParamName, $default );
1186
1187 if ( isset( $value ) && $type == 'namespace' ) {
1188 $type = MWNamespace::getValidNamespaces();
1189 if ( isset( $paramSettings[self::PARAM_EXTRA_NAMESPACES] ) &&
1190 is_array( $paramSettings[self::PARAM_EXTRA_NAMESPACES] )
1191 ) {
1192 $type = array_merge( $type, $paramSettings[self::PARAM_EXTRA_NAMESPACES] );
1193 }
1194 // Namespace parameters allow ALL_DEFAULT_STRING to be used to
1195 // specify all namespaces irrespective of PARAM_ALL.
1196 $allowAll = true;
1197 }
1198 if ( isset( $value ) && $type == 'submodule' ) {
1199 if ( isset( $paramSettings[self::PARAM_SUBMODULE_MAP] ) ) {
1200 $type = array_keys( $paramSettings[self::PARAM_SUBMODULE_MAP] );
1201 } else {
1202 $type = $this->getModuleManager()->getNames( $paramName );
1203 }
1204 }
1205
1206 $request = $this->getMain()->getRequest();
1207 $rawValue = $request->getRawVal( $encParamName );
1208 if ( $rawValue === null ) {
1209 $rawValue = $default;
1210 }
1211
1212 // Preserve U+001F for self::parseMultiValue(), or error out if that won't be called
1213 if ( isset( $value ) && substr( $rawValue, 0, 1 ) === "\x1f" ) {
1214 if ( $multi ) {
1215 // This loses the potential checkTitleEncoding() transformation done by
1216 // WebRequest for $_GET. Let's call that a feature.
1217 $value = implode( "\x1f", $request->normalizeUnicode( explode( "\x1f", $rawValue ) ) );
1218 } else {
1219 $this->dieWithError( 'apierror-badvalue-notmultivalue', 'badvalue_notmultivalue' );
1220 }
1221 }
1222
1223 // Check for NFC normalization, and warn
1224 if ( $rawValue !== $value ) {
1225 $this->handleParamNormalization( $paramName, $value, $rawValue );
1226 }
1227 }
1228
1229 $allSpecifier = ( is_string( $allowAll ) ? $allowAll : self::ALL_DEFAULT_STRING );
1230 if ( $allowAll && $multi && is_array( $type ) && in_array( $allSpecifier, $type, true ) ) {
1231 self::dieDebug(
1232 __METHOD__,
1233 "For param $encParamName, PARAM_ALL collides with a possible value" );
1234 }
1235 if ( isset( $value ) && ( $multi || is_array( $type ) ) ) {
1236 $value = $this->parseMultiValue(
1237 $encParamName,
1238 $value,
1239 $multi,
1240 is_array( $type ) ? $type : null,
1241 $allowAll ? $allSpecifier : null,
1242 $multiLimit1,
1243 $multiLimit2
1244 );
1245 }
1246
1247 if ( isset( $value ) ) {
1248 // More validation only when choices were not given
1249 // choices were validated in parseMultiValue()
1250 if ( !is_array( $type ) ) {
1251 switch ( $type ) {
1252 case 'NULL': // nothing to do
1253 break;
1254 case 'string':
1255 case 'text':
1256 case 'password':
1257 if ( $required && $value === '' ) {
1258 $this->dieWithError( [ 'apierror-missingparam', $encParamName ] );
1259 }
1260 break;
1261 case 'integer': // Force everything using intval() and optionally validate limits
1262 $min = $paramSettings[self::PARAM_MIN] ?? null;
1263 $max = $paramSettings[self::PARAM_MAX] ?? null;
1264 $enforceLimits = $paramSettings[self::PARAM_RANGE_ENFORCE] ?? false;
1265
1266 if ( is_array( $value ) ) {
1267 $value = array_map( 'intval', $value );
1268 if ( !is_null( $min ) || !is_null( $max ) ) {
1269 foreach ( $value as &$v ) {
1270 $this->validateLimit( $paramName, $v, $min, $max, null, $enforceLimits );
1271 }
1272 }
1273 } else {
1274 $value = intval( $value );
1275 if ( !is_null( $min ) || !is_null( $max ) ) {
1276 $this->validateLimit( $paramName, $value, $min, $max, null, $enforceLimits );
1277 }
1278 }
1279 break;
1280 case 'limit':
1281 if ( !$parseLimit ) {
1282 // Don't do any validation whatsoever
1283 break;
1284 }
1285 if ( !isset( $paramSettings[self::PARAM_MAX] )
1286 || !isset( $paramSettings[self::PARAM_MAX2] )
1287 ) {
1288 self::dieDebug(
1289 __METHOD__,
1290 "MAX1 or MAX2 are not defined for the limit $encParamName"
1291 );
1292 }
1293 if ( $multi ) {
1294 self::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
1295 }
1296 $min = $paramSettings[self::PARAM_MIN] ?? 0;
1297 if ( $value == 'max' ) {
1298 $value = $this->getMain()->canApiHighLimits()
1299 ? $paramSettings[self::PARAM_MAX2]
1300 : $paramSettings[self::PARAM_MAX];
1301 $this->getResult()->addParsedLimit( $this->getModuleName(), $value );
1302 } else {
1303 $value = intval( $value );
1304 $this->validateLimit(
1305 $paramName,
1306 $value,
1307 $min,
1308 $paramSettings[self::PARAM_MAX],
1309 $paramSettings[self::PARAM_MAX2]
1310 );
1311 }
1312 break;
1313 case 'boolean':
1314 if ( $multi ) {
1315 self::dieDebug( __METHOD__, "Multi-values not supported for $encParamName" );
1316 }
1317 break;
1318 case 'timestamp':
1319 if ( is_array( $value ) ) {
1320 foreach ( $value as $key => $val ) {
1321 $value[$key] = $this->validateTimestamp( $val, $encParamName );
1322 }
1323 } else {
1324 $value = $this->validateTimestamp( $value, $encParamName );
1325 }
1326 break;
1327 case 'user':
1328 if ( is_array( $value ) ) {
1329 foreach ( $value as $key => $val ) {
1330 $value[$key] = $this->validateUser( $val, $encParamName );
1331 }
1332 } else {
1333 $value = $this->validateUser( $value, $encParamName );
1334 }
1335 break;
1336 case 'upload': // nothing to do
1337 break;
1338 case 'tags':
1339 // If change tagging was requested, check that the tags are valid.
1340 if ( !is_array( $value ) && !$multi ) {
1341 $value = [ $value ];
1342 }
1343 $tagsStatus = ChangeTags::canAddTagsAccompanyingChange( $value );
1344 if ( !$tagsStatus->isGood() ) {
1345 $this->dieStatus( $tagsStatus );
1346 }
1347 break;
1348 default:
1349 self::dieDebug( __METHOD__, "Param $encParamName's type is unknown - $type" );
1350 }
1351 }
1352
1353 // Throw out duplicates if requested
1354 if ( !$dupes && is_array( $value ) ) {
1355 $value = array_unique( $value );
1356 }
1357
1358 if ( in_array( $type, [ 'NULL', 'string', 'text', 'password' ], true ) ) {
1359 foreach ( (array)$value as $val ) {
1360 if ( isset( $paramSettings[self::PARAM_MAX_BYTES] )
1361 && strlen( $val ) > $paramSettings[self::PARAM_MAX_BYTES]
1362 ) {
1363 $this->dieWithError( [ 'apierror-maxbytes', $encParamName,
1364 $paramSettings[self::PARAM_MAX_BYTES] ] );
1365 }
1366 if ( isset( $paramSettings[self::PARAM_MAX_CHARS] )
1367 && mb_strlen( $val, 'UTF-8' ) > $paramSettings[self::PARAM_MAX_CHARS]
1368 ) {
1369 $this->dieWithError( [ 'apierror-maxchars', $encParamName,
1370 $paramSettings[self::PARAM_MAX_CHARS] ] );
1371 }
1372 }
1373 }
1374
1375 // Set a warning if a deprecated parameter has been passed
1376 if ( $deprecated && $value !== false ) {
1377 $feature = $encParamName;
1378 $m = $this;
1379 while ( !$m->isMain() ) {
1380 $p = $m->getParent();
1381 $name = $m->getModuleName();
1382 $param = $p->encodeParamName( $p->getModuleManager()->getModuleGroup( $name ) );
1383 $feature = "{$param}={$name}&{$feature}";
1384 $m = $p;
1385 }
1386 $this->addDeprecation( [ 'apiwarn-deprecation-parameter', $encParamName ], $feature );
1387 }
1388
1389 // Set a warning if a deprecated parameter value has been passed
1390 $usedDeprecatedValues = $deprecatedValues && $value !== false
1391 ? array_intersect( array_keys( $deprecatedValues ), (array)$value )
1392 : [];
1393 if ( $usedDeprecatedValues ) {
1394 $feature = "$encParamName=";
1395 $m = $this;
1396 while ( !$m->isMain() ) {
1397 $p = $m->getParent();
1398 $name = $m->getModuleName();
1399 $param = $p->encodeParamName( $p->getModuleManager()->getModuleGroup( $name ) );
1400 $feature = "{$param}={$name}&{$feature}";
1401 $m = $p;
1402 }
1403 foreach ( $usedDeprecatedValues as $v ) {
1404 $msg = $deprecatedValues[$v];
1405 if ( $msg === true ) {
1406 $msg = [ 'apiwarn-deprecation-parameter', "$encParamName=$v" ];
1407 }
1408 $this->addDeprecation( $msg, "$feature$v" );
1409 }
1410 }
1411 } elseif ( $required ) {
1412 $this->dieWithError( [ 'apierror-missingparam', $encParamName ] );
1413 }
1414
1415 return $value;
1416 }
1417
1418 /**
1419 * Handle when a parameter was Unicode-normalized
1420 * @since 1.28
1421 * @param string $paramName Unprefixed parameter name
1422 * @param string $value Input that will be used.
1423 * @param string $rawValue Input before normalization.
1424 */
1425 protected function handleParamNormalization( $paramName, $value, $rawValue ) {
1426 $encParamName = $this->encodeParamName( $paramName );
1427 $this->addWarning( [ 'apiwarn-badutf8', $encParamName ] );
1428 }
1429
1430 /**
1431 * Split a multi-valued parameter string, like explode()
1432 * @since 1.28
1433 * @param string $value
1434 * @param int $limit
1435 * @return string[]
1436 */
1437 protected function explodeMultiValue( $value, $limit ) {
1438 if ( substr( $value, 0, 1 ) === "\x1f" ) {
1439 $sep = "\x1f";
1440 $value = substr( $value, 1 );
1441 } else {
1442 $sep = '|';
1443 }
1444
1445 return explode( $sep, $value, $limit );
1446 }
1447
1448 /**
1449 * Return an array of values that were given in a 'a|b|c' notation,
1450 * after it optionally validates them against the list allowed values.
1451 *
1452 * @param string $valueName The name of the parameter (for error
1453 * reporting)
1454 * @param mixed $value The value being parsed
1455 * @param bool $allowMultiple Can $value contain more than one value
1456 * separated by '|'?
1457 * @param string[]|null $allowedValues An array of values to check against. If
1458 * null, all values are accepted.
1459 * @param string|null $allSpecifier String to use to specify all allowed values, or null
1460 * if this behavior should not be allowed
1461 * @param int|null $limit1 Maximum number of values, for normal users.
1462 * @param int|null $limit2 Maximum number of values, for users with the apihighlimits right.
1463 * @return string|string[] (allowMultiple ? an_array_of_values : a_single_value)
1464 */
1465 protected function parseMultiValue( $valueName, $value, $allowMultiple, $allowedValues,
1466 $allSpecifier = null, $limit1 = null, $limit2 = null
1467 ) {
1468 if ( ( $value === '' || $value === "\x1f" ) && $allowMultiple ) {
1469 return [];
1470 }
1471 $limit1 = $limit1 ?: self::LIMIT_SML1;
1472 $limit2 = $limit2 ?: self::LIMIT_SML2;
1473
1474 // This is a bit awkward, but we want to avoid calling canApiHighLimits()
1475 // because it unstubs $wgUser
1476 $valuesList = $this->explodeMultiValue( $value, $limit2 + 1 );
1477 $sizeLimit = count( $valuesList ) > $limit1 && $this->mMainModule->canApiHighLimits()
1478 ? $limit2
1479 : $limit1;
1480
1481 if ( $allowMultiple && is_array( $allowedValues ) && $allSpecifier &&
1482 count( $valuesList ) === 1 && $valuesList[0] === $allSpecifier
1483 ) {
1484 return $allowedValues;
1485 }
1486
1487 if ( count( $valuesList ) > $sizeLimit ) {
1488 $this->dieWithError(
1489 [ 'apierror-toomanyvalues', $valueName, $sizeLimit ],
1490 "too-many-$valueName"
1491 );
1492 }
1493
1494 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
1495 // T35482 - Allow entries with | in them for non-multiple values
1496 if ( in_array( $value, $allowedValues, true ) ) {
1497 return $value;
1498 }
1499
1500 $values = array_map( function ( $v ) {
1501 return '<kbd>' . wfEscapeWikiText( $v ) . '</kbd>';
1502 }, $allowedValues );
1503 $this->dieWithError( [
1504 'apierror-multival-only-one-of',
1505 $valueName,
1506 Message::listParam( $values ),
1507 count( $values ),
1508 ], "multival_$valueName" );
1509 }
1510
1511 if ( is_array( $allowedValues ) ) {
1512 // Check for unknown values
1513 $unknown = array_map( 'wfEscapeWikiText', array_diff( $valuesList, $allowedValues ) );
1514 if ( count( $unknown ) ) {
1515 if ( $allowMultiple ) {
1516 $this->addWarning( [
1517 'apiwarn-unrecognizedvalues',
1518 $valueName,
1519 Message::listParam( $unknown, 'comma' ),
1520 count( $unknown ),
1521 ] );
1522 } else {
1523 $this->dieWithError(
1524 [ 'apierror-unrecognizedvalue', $valueName, wfEscapeWikiText( $valuesList[0] ) ],
1525 "unknown_$valueName"
1526 );
1527 }
1528 }
1529 // Now throw them out
1530 $valuesList = array_intersect( $valuesList, $allowedValues );
1531 }
1532
1533 return $allowMultiple ? $valuesList : $valuesList[0];
1534 }
1535
1536 /**
1537 * Validate the value against the minimum and user/bot maximum limits.
1538 * Prints usage info on failure.
1539 * @param string $paramName Parameter name
1540 * @param int &$value Parameter value
1541 * @param int|null $min Minimum value
1542 * @param int|null $max Maximum value for users
1543 * @param int|null $botMax Maximum value for sysops/bots
1544 * @param bool $enforceLimits Whether to enforce (die) if value is outside limits
1545 */
1546 protected function validateLimit( $paramName, &$value, $min, $max, $botMax = null,
1547 $enforceLimits = false
1548 ) {
1549 if ( !is_null( $min ) && $value < $min ) {
1550 $msg = ApiMessage::create(
1551 [ 'apierror-integeroutofrange-belowminimum',
1552 $this->encodeParamName( $paramName ), $min, $value ],
1553 'integeroutofrange',
1554 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?: $max ]
1555 );
1556 $this->warnOrDie( $msg, $enforceLimits );
1557 $value = $min;
1558 }
1559
1560 // Minimum is always validated, whereas maximum is checked only if not
1561 // running in internal call mode
1562 if ( $this->getMain()->isInternalMode() ) {
1563 return;
1564 }
1565
1566 // Optimization: do not check user's bot status unless really needed -- skips db query
1567 // assumes $botMax >= $max
1568 if ( !is_null( $max ) && $value > $max ) {
1569 if ( !is_null( $botMax ) && $this->getMain()->canApiHighLimits() ) {
1570 if ( $value > $botMax ) {
1571 $msg = ApiMessage::create(
1572 [ 'apierror-integeroutofrange-abovebotmax',
1573 $this->encodeParamName( $paramName ), $botMax, $value ],
1574 'integeroutofrange',
1575 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?: $max ]
1576 );
1577 $this->warnOrDie( $msg, $enforceLimits );
1578 $value = $botMax;
1579 }
1580 } else {
1581 $msg = ApiMessage::create(
1582 [ 'apierror-integeroutofrange-abovemax',
1583 $this->encodeParamName( $paramName ), $max, $value ],
1584 'integeroutofrange',
1585 [ 'min' => $min, 'max' => $max, 'botMax' => $botMax ?: $max ]
1586 );
1587 $this->warnOrDie( $msg, $enforceLimits );
1588 $value = $max;
1589 }
1590 }
1591 }
1592
1593 /**
1594 * Validate and normalize parameters of type 'timestamp'
1595 * @param string $value Parameter value
1596 * @param string $encParamName Parameter name
1597 * @return string Validated and normalized parameter
1598 */
1599 protected function validateTimestamp( $value, $encParamName ) {
1600 // Confusing synonyms for the current time accepted by wfTimestamp()
1601 // (wfTimestamp() also accepts various non-strings and the string of 14
1602 // ASCII NUL bytes, but those can't get here)
1603 if ( !$value ) {
1604 $this->addDeprecation(
1605 [ 'apiwarn-unclearnowtimestamp', $encParamName, wfEscapeWikiText( $value ) ],
1606 'unclear-"now"-timestamp'
1607 );
1608 return wfTimestamp( TS_MW );
1609 }
1610
1611 // Explicit synonym for the current time
1612 if ( $value === 'now' ) {
1613 return wfTimestamp( TS_MW );
1614 }
1615
1616 $timestamp = wfTimestamp( TS_MW, $value );
1617 if ( $timestamp === false ) {
1618 $this->dieWithError(
1619 [ 'apierror-badtimestamp', $encParamName, wfEscapeWikiText( $value ) ],
1620 "badtimestamp_{$encParamName}"
1621 );
1622 }
1623
1624 return $timestamp;
1625 }
1626
1627 /**
1628 * Validate the supplied token.
1629 *
1630 * @since 1.24
1631 * @param string $token Supplied token
1632 * @param array $params All supplied parameters for the module
1633 * @return bool
1634 * @throws MWException
1635 */
1636 final public function validateToken( $token, array $params ) {
1637 $tokenType = $this->needsToken();
1638 $salts = ApiQueryTokens::getTokenTypeSalts();
1639 if ( !isset( $salts[$tokenType] ) ) {
1640 throw new MWException(
1641 "Module '{$this->getModuleName()}' tried to use token type '$tokenType' " .
1642 'without registering it'
1643 );
1644 }
1645
1646 $tokenObj = ApiQueryTokens::getToken(
1647 $this->getUser(), $this->getRequest()->getSession(), $salts[$tokenType]
1648 );
1649 if ( $tokenObj->match( $token ) ) {
1650 return true;
1651 }
1652
1653 $webUiSalt = $this->getWebUITokenSalt( $params );
1654 if ( $webUiSalt !== null && $this->getUser()->matchEditToken(
1655 $token,
1656 $webUiSalt,
1657 $this->getRequest()
1658 ) ) {
1659 return true;
1660 }
1661
1662 return false;
1663 }
1664
1665 /**
1666 * Validate and normalize parameters of type 'user'
1667 * @param string $value Parameter value
1668 * @param string $encParamName Parameter name
1669 * @return string Validated and normalized parameter
1670 */
1671 private function validateUser( $value, $encParamName ) {
1672 if ( ExternalUserNames::isExternal( $value ) && User::newFromName( $value, false ) ) {
1673 return $value;
1674 }
1675
1676 $name = User::getCanonicalName( $value, 'valid' );
1677 if ( $name !== false ) {
1678 return $name;
1679 }
1680
1681 if (
1682 // We allow ranges as well, for blocks.
1683 IP::isIPAddress( $value ) ||
1684 // See comment for User::isIP. We don't just call that function
1685 // here because it also returns true for things like
1686 // 300.300.300.300 that are neither valid usernames nor valid IP
1687 // addresses.
1688 preg_match(
1689 '/^' . RE_IP_BYTE . '\.' . RE_IP_BYTE . '\.' . RE_IP_BYTE . '\.xxx$/',
1690 $value
1691 )
1692 ) {
1693 return IP::sanitizeIP( $value );
1694 }
1695
1696 $this->dieWithError(
1697 [ 'apierror-baduser', $encParamName, wfEscapeWikiText( $value ) ],
1698 "baduser_{$encParamName}"
1699 );
1700 }
1701
1702 /**@}*/
1703
1704 /************************************************************************//**
1705 * @name Utility methods
1706 * @{
1707 */
1708
1709 /**
1710 * Set a watch (or unwatch) based the based on a watchlist parameter.
1711 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
1712 * @param Title $titleObj The article's title to change
1713 * @param string|null $userOption The user option to consider when $watch=preferences
1714 */
1715 protected function setWatch( $watch, $titleObj, $userOption = null ) {
1716 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
1717 if ( $value === null ) {
1718 return;
1719 }
1720
1721 WatchAction::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
1722 }
1723
1724 /**
1725 * Gets the user for whom to get the watchlist
1726 *
1727 * @param array $params
1728 * @return User
1729 */
1730 public function getWatchlistUser( $params ) {
1731 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1732 $user = User::newFromName( $params['owner'], false );
1733 if ( !( $user && $user->getId() ) ) {
1734 $this->dieWithError(
1735 [ 'nosuchusershort', wfEscapeWikiText( $params['owner'] ) ], 'bad_wlowner'
1736 );
1737 }
1738 $token = $user->getOption( 'watchlisttoken' );
1739 if ( $token == '' || !hash_equals( $token, $params['token'] ) ) {
1740 $this->dieWithError( 'apierror-bad-watchlist-token', 'bad_wltoken' );
1741 }
1742 } else {
1743 if ( !$this->getUser()->isLoggedIn() ) {
1744 $this->dieWithError( 'watchlistanontext', 'notloggedin' );
1745 }
1746 $this->checkUserRightsAny( 'viewmywatchlist' );
1747 $user = $this->getUser();
1748 }
1749
1750 return $user;
1751 }
1752
1753 /**
1754 * Create a Message from a string or array
1755 *
1756 * A string is used as a message key. An array has the message key as the
1757 * first value and message parameters as subsequent values.
1758 *
1759 * @since 1.25
1760 * @param string|array|Message $msg
1761 * @param IContextSource $context
1762 * @param array|null $params
1763 * @return Message|null
1764 */
1765 public static function makeMessage( $msg, IContextSource $context, array $params = null ) {
1766 if ( is_string( $msg ) ) {
1767 $msg = wfMessage( $msg );
1768 } elseif ( is_array( $msg ) ) {
1769 $msg = wfMessage( ...$msg );
1770 }
1771 if ( !$msg instanceof Message ) {
1772 return null;
1773 }
1774
1775 $msg->setContext( $context );
1776 if ( $params ) {
1777 $msg->params( $params );
1778 }
1779
1780 return $msg;
1781 }
1782
1783 /**
1784 * Turn an array of message keys or key+param arrays into a Status
1785 * @since 1.29
1786 * @param array $errors
1787 * @param User|null $user
1788 * @return Status
1789 */
1790 public function errorArrayToStatus( array $errors, User $user = null ) {
1791 if ( $user === null ) {
1792 $user = $this->getUser();
1793 }
1794
1795 $status = Status::newGood();
1796 foreach ( $errors as $error ) {
1797 if ( is_array( $error ) && $error[0] === 'blockedtext' && $user->getBlock() ) {
1798 $status->fatal( ApiMessage::create(
1799 'apierror-blocked',
1800 'blocked',
1801 [ 'blockinfo' => ApiQueryUserInfo::getBlockInfo( $user->getBlock() ) ]
1802 ) );
1803 } elseif ( is_array( $error ) && $error[0] === 'blockedtext-partial' && $user->getBlock() ) {
1804 $status->fatal( ApiMessage::create(
1805 'apierror-blocked-partial',
1806 'blocked',
1807 [ 'blockinfo' => ApiQueryUserInfo::getBlockInfo( $user->getBlock() ) ]
1808 ) );
1809 } elseif ( is_array( $error ) && $error[0] === 'autoblockedtext' && $user->getBlock() ) {
1810 $status->fatal( ApiMessage::create(
1811 'apierror-autoblocked',
1812 'autoblocked',
1813 [ 'blockinfo' => ApiQueryUserInfo::getBlockInfo( $user->getBlock() ) ]
1814 ) );
1815 } elseif ( is_array( $error ) && $error[0] === 'systemblockedtext' && $user->getBlock() ) {
1816 $status->fatal( ApiMessage::create(
1817 'apierror-systemblocked',
1818 'blocked',
1819 [ 'blockinfo' => ApiQueryUserInfo::getBlockInfo( $user->getBlock() ) ]
1820 ) );
1821 } else {
1822 $status->fatal( ...(array)$error );
1823 }
1824 }
1825 return $status;
1826 }
1827
1828 /**
1829 * Call wfTransactionalTimeLimit() if this request was POSTed
1830 * @since 1.26
1831 */
1832 protected function useTransactionalTimeLimit() {
1833 if ( $this->getRequest()->wasPosted() ) {
1834 wfTransactionalTimeLimit();
1835 }
1836 }
1837
1838 /**
1839 * Filter out-of-range values from a list of positive integer IDs
1840 * @since 1.33
1841 * @param array $fields Array of pairs of table and field to check
1842 * @param (string|int)[] $ids IDs to filter. Strings in the array are
1843 * expected to be stringified ints.
1844 * @return (string|int)[] Filtered IDs.
1845 */
1846 protected function filterIDs( $fields, array $ids ) {
1847 $min = INF;
1848 $max = 0;
1849 foreach ( $fields as list( $table, $field ) ) {
1850 if ( isset( self::$filterIDsCache[$table][$field] ) ) {
1851 $row = self::$filterIDsCache[$table][$field];
1852 } else {
1853 $row = $this->getDB()->selectRow(
1854 $table,
1855 [
1856 'min_id' => "MIN($field)",
1857 'max_id' => "MAX($field)",
1858 ],
1859 '',
1860 __METHOD__
1861 );
1862 self::$filterIDsCache[$table][$field] = $row;
1863 }
1864 $min = min( $min, $row->min_id );
1865 $max = max( $max, $row->max_id );
1866 }
1867 return array_filter( $ids, function ( $id ) use ( $min, $max ) {
1868 return ( is_int( $id ) && $id >= 0 || ctype_digit( $id ) )
1869 && $id >= $min && $id <= $max;
1870 } );
1871 }
1872
1873 /**@}*/
1874
1875 /************************************************************************//**
1876 * @name Warning and error reporting
1877 * @{
1878 */
1879
1880 /**
1881 * Add a warning for this module.
1882 *
1883 * Users should monitor this section to notice any changes in API. Multiple
1884 * calls to this function will result in multiple warning messages.
1885 *
1886 * If $msg is not an ApiMessage, the message code will be derived from the
1887 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1888 *
1889 * @since 1.29
1890 * @param string|array|Message $msg See ApiErrorFormatter::addWarning()
1891 * @param string|null $code See ApiErrorFormatter::addWarning()
1892 * @param array|null $data See ApiErrorFormatter::addWarning()
1893 */
1894 public function addWarning( $msg, $code = null, $data = null ) {
1895 $this->getErrorFormatter()->addWarning( $this->getModulePath(), $msg, $code, $data );
1896 }
1897
1898 /**
1899 * Add a deprecation warning for this module.
1900 *
1901 * A combination of $this->addWarning() and $this->logFeatureUsage()
1902 *
1903 * @since 1.29
1904 * @param string|array|Message $msg See ApiErrorFormatter::addWarning()
1905 * @param string|null $feature See ApiBase::logFeatureUsage()
1906 * @param array|null $data See ApiErrorFormatter::addWarning()
1907 */
1908 public function addDeprecation( $msg, $feature, $data = [] ) {
1909 $data = (array)$data;
1910 if ( $feature !== null ) {
1911 $data['feature'] = $feature;
1912 $this->logFeatureUsage( $feature );
1913 }
1914 $this->addWarning( $msg, 'deprecation', $data );
1915
1916 // No real need to deduplicate here, ApiErrorFormatter does that for
1917 // us (assuming the hook is deterministic).
1918 $msgs = [ $this->msg( 'api-usage-mailinglist-ref' ) ];
1919 Hooks::run( 'ApiDeprecationHelp', [ &$msgs ] );
1920 if ( count( $msgs ) > 1 ) {
1921 $key = '$' . implode( ' $', range( 1, count( $msgs ) ) );
1922 $msg = ( new RawMessage( $key ) )->params( $msgs );
1923 } else {
1924 $msg = reset( $msgs );
1925 }
1926 $this->getMain()->addWarning( $msg, 'deprecation-help' );
1927 }
1928
1929 /**
1930 * Add an error for this module without aborting
1931 *
1932 * If $msg is not an ApiMessage, the message code will be derived from the
1933 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1934 *
1935 * @note If you want to abort processing, use self::dieWithError() instead.
1936 * @since 1.29
1937 * @param string|array|Message $msg See ApiErrorFormatter::addError()
1938 * @param string|null $code See ApiErrorFormatter::addError()
1939 * @param array|null $data See ApiErrorFormatter::addError()
1940 */
1941 public function addError( $msg, $code = null, $data = null ) {
1942 $this->getErrorFormatter()->addError( $this->getModulePath(), $msg, $code, $data );
1943 }
1944
1945 /**
1946 * Add warnings and/or errors from a Status
1947 *
1948 * @note If you want to abort processing, use self::dieStatus() instead.
1949 * @since 1.29
1950 * @param StatusValue $status
1951 * @param string[] $types 'warning' and/or 'error'
1952 * @param string[] $filter Message keys to filter out (since 1.33)
1953 */
1954 public function addMessagesFromStatus(
1955 StatusValue $status, $types = [ 'warning', 'error' ], array $filter = []
1956 ) {
1957 $this->getErrorFormatter()->addMessagesFromStatus(
1958 $this->getModulePath(), $status, $types, $filter
1959 );
1960 }
1961
1962 /**
1963 * Abort execution with an error
1964 *
1965 * If $msg is not an ApiMessage, the message code will be derived from the
1966 * message key by stripping any "apiwarn-" or "apierror-" prefix.
1967 *
1968 * @since 1.29
1969 * @param string|array|Message $msg See ApiErrorFormatter::addError()
1970 * @param string|null $code See ApiErrorFormatter::addError()
1971 * @param array|null $data See ApiErrorFormatter::addError()
1972 * @param int|null $httpCode HTTP error code to use
1973 * @throws ApiUsageException always
1974 */
1975 public function dieWithError( $msg, $code = null, $data = null, $httpCode = null ) {
1976 throw ApiUsageException::newWithMessage( $this, $msg, $code, $data, $httpCode );
1977 }
1978
1979 /**
1980 * Abort execution with an error derived from an exception
1981 *
1982 * @since 1.29
1983 * @param Exception|Throwable $exception See ApiErrorFormatter::getMessageFromException()
1984 * @param array $options See ApiErrorFormatter::getMessageFromException()
1985 * @throws ApiUsageException always
1986 */
1987 public function dieWithException( $exception, array $options = [] ) {
1988 $this->dieWithError(
1989 $this->getErrorFormatter()->getMessageFromException( $exception, $options )
1990 );
1991 }
1992
1993 /**
1994 * Adds a warning to the output, else dies
1995 *
1996 * @param ApiMessage $msg Message to show as a warning, or error message if dying
1997 * @param bool $enforceLimits Whether this is an enforce (die)
1998 */
1999 private function warnOrDie( ApiMessage $msg, $enforceLimits = false ) {
2000 if ( $enforceLimits ) {
2001 $this->dieWithError( $msg );
2002 } else {
2003 $this->addWarning( $msg );
2004 }
2005 }
2006
2007 /**
2008 * Throw an ApiUsageException, which will (if uncaught) call the main module's
2009 * error handler and die with an error message including block info.
2010 *
2011 * @since 1.27
2012 * @param Block $block The block used to generate the ApiUsageException
2013 * @throws ApiUsageException always
2014 */
2015 public function dieBlocked( Block $block ) {
2016 // Die using the appropriate message depending on block type
2017 if ( $block->getType() == Block::TYPE_AUTO ) {
2018 $this->dieWithError(
2019 'apierror-autoblocked',
2020 'autoblocked',
2021 [ 'blockinfo' => ApiQueryUserInfo::getBlockInfo( $block ) ]
2022 );
2023 } elseif ( !$block->isSitewide() ) {
2024 $this->dieWithError(
2025 'apierror-blocked-partial',
2026 'blocked',
2027 [ 'blockinfo' => ApiQueryUserInfo::getBlockInfo( $block ) ]
2028 );
2029 } else {
2030 $this->dieWithError(
2031 'apierror-blocked',
2032 'blocked',
2033 [ 'blockinfo' => ApiQueryUserInfo::getBlockInfo( $block ) ]
2034 );
2035 }
2036 }
2037
2038 /**
2039 * Throw an ApiUsageException based on the Status object.
2040 *
2041 * @since 1.22
2042 * @since 1.29 Accepts a StatusValue
2043 * @param StatusValue $status
2044 * @throws ApiUsageException always
2045 */
2046 public function dieStatus( StatusValue $status ) {
2047 if ( $status->isGood() ) {
2048 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
2049 }
2050
2051 // ApiUsageException needs a fatal status, but this method has
2052 // historically accepted any non-good status. Convert it if necessary.
2053 $status->setOK( false );
2054 if ( !$status->getErrorsByType( 'error' ) ) {
2055 $newStatus = Status::newGood();
2056 foreach ( $status->getErrorsByType( 'warning' ) as $err ) {
2057 $newStatus->fatal( $err['message'], ...$err['params'] );
2058 }
2059 if ( !$newStatus->getErrorsByType( 'error' ) ) {
2060 $newStatus->fatal( 'unknownerror-nocode' );
2061 }
2062 $status = $newStatus;
2063 }
2064
2065 throw new ApiUsageException( $this, $status );
2066 }
2067
2068 /**
2069 * Helper function for readonly errors
2070 *
2071 * @throws ApiUsageException always
2072 */
2073 public function dieReadOnly() {
2074 $this->dieWithError(
2075 'apierror-readonly',
2076 'readonly',
2077 [ 'readonlyreason' => wfReadOnlyReason() ]
2078 );
2079 }
2080
2081 /**
2082 * Helper function for permission-denied errors
2083 * @since 1.29
2084 * @param string|string[] $rights
2085 * @param User|null $user
2086 * @throws ApiUsageException if the user doesn't have any of the rights.
2087 * The error message is based on $rights[0].
2088 */
2089 public function checkUserRightsAny( $rights, $user = null ) {
2090 if ( !$user ) {
2091 $user = $this->getUser();
2092 }
2093 $rights = (array)$rights;
2094 if ( !$user->isAllowedAny( ...$rights ) ) {
2095 $this->dieWithError( [ 'apierror-permissiondenied', $this->msg( "action-{$rights[0]}" ) ] );
2096 }
2097 }
2098
2099 /**
2100 * Helper function for permission-denied errors
2101 * @since 1.29
2102 * @param Title $title
2103 * @param string|string[] $actions
2104 * @param User|null $user
2105 * @throws ApiUsageException if the user doesn't have all of the rights.
2106 */
2107 public function checkTitleUserPermissions( Title $title, $actions, $user = null ) {
2108 if ( !$user ) {
2109 $user = $this->getUser();
2110 }
2111
2112 $errors = [];
2113 foreach ( (array)$actions as $action ) {
2114 $errors = array_merge( $errors, $title->getUserPermissionsErrors( $action, $user ) );
2115 }
2116
2117 if ( $errors ) {
2118 // track block notices
2119 if ( $this->getConfig()->get( 'EnableBlockNoticeStats' ) ) {
2120 $this->trackBlockNotices( $errors );
2121 }
2122
2123 $this->dieStatus( $this->errorArrayToStatus( $errors, $user ) );
2124 }
2125 }
2126
2127 /**
2128 * Keep track of errors messages resulting from a block
2129 *
2130 * @param array $errors
2131 */
2132 private function trackBlockNotices( array $errors ) {
2133 $errorMessageKeys = [
2134 'blockedtext',
2135 'blockedtext-partial',
2136 'autoblockedtext',
2137 'systemblockedtext',
2138 ];
2139
2140 $statsd = MediaWikiServices::getInstance()->getStatsdDataFactory();
2141
2142 foreach ( $errors as $error ) {
2143 if ( in_array( $error[0], $errorMessageKeys ) ) {
2144 $wiki = $this->getConfig()->get( 'DBname' );
2145 $statsd->increment( 'BlockNotices.' . $wiki . '.MediaWikiApi.returned' );
2146 break;
2147 }
2148 }
2149 }
2150
2151 /**
2152 * Will only set a warning instead of failing if the global $wgDebugAPI
2153 * is set to true. Otherwise behaves exactly as self::dieWithError().
2154 *
2155 * @since 1.29
2156 * @param string|array|Message $msg
2157 * @param string|null $code
2158 * @param array|null $data
2159 * @param int|null $httpCode
2160 * @throws ApiUsageException
2161 */
2162 public function dieWithErrorOrDebug( $msg, $code = null, $data = null, $httpCode = null ) {
2163 if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
2164 $this->dieWithError( $msg, $code, $data, $httpCode );
2165 } else {
2166 $this->addWarning( $msg, $code, $data );
2167 }
2168 }
2169
2170 /**
2171 * Die with the 'badcontinue' error.
2172 *
2173 * This call is common enough to make it into the base method.
2174 *
2175 * @param bool $condition Will only die if this value is true
2176 * @throws ApiUsageException
2177 * @since 1.21
2178 */
2179 protected function dieContinueUsageIf( $condition ) {
2180 if ( $condition ) {
2181 $this->dieWithError( 'apierror-badcontinue' );
2182 }
2183 }
2184
2185 /**
2186 * Internal code errors should be reported with this method
2187 * @param string $method Method or function name
2188 * @param string $message Error message
2189 * @throws MWException always
2190 */
2191 protected static function dieDebug( $method, $message ) {
2192 throw new MWException( "Internal error in $method: $message" );
2193 }
2194
2195 /**
2196 * Write logging information for API features to a debug log, for usage
2197 * analysis.
2198 * @note Consider using $this->addDeprecation() instead to both warn and log.
2199 * @param string $feature Feature being used.
2200 */
2201 public function logFeatureUsage( $feature ) {
2202 $request = $this->getRequest();
2203 $s = '"' . addslashes( $feature ) . '"' .
2204 ' "' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) . '"' .
2205 ' "' . $request->getIP() . '"' .
2206 ' "' . addslashes( $request->getHeader( 'Referer' ) ) . '"' .
2207 ' "' . addslashes( $this->getMain()->getUserAgent() ) . '"';
2208 wfDebugLog( 'api-feature-usage', $s, 'private' );
2209 }
2210
2211 /**@}*/
2212
2213 /************************************************************************//**
2214 * @name Help message generation
2215 * @{
2216 */
2217
2218 /**
2219 * Return the summary message.
2220 *
2221 * This is a one-line description of the module, suitable for display in a
2222 * list of modules.
2223 *
2224 * @since 1.30
2225 * @return string|array|Message
2226 */
2227 protected function getSummaryMessage() {
2228 return "apihelp-{$this->getModulePath()}-summary";
2229 }
2230
2231 /**
2232 * Return the extended help text message.
2233 *
2234 * This is additional text to display at the top of the help section, below
2235 * the summary.
2236 *
2237 * @since 1.30
2238 * @return string|array|Message
2239 */
2240 protected function getExtendedDescription() {
2241 return [ [
2242 "apihelp-{$this->getModulePath()}-extended-description",
2243 'api-help-no-extended-description',
2244 ] ];
2245 }
2246
2247 /**
2248 * Get final module summary
2249 *
2250 * @since 1.30
2251 * @return Message
2252 */
2253 public function getFinalSummary() {
2254 $msg = self::makeMessage( $this->getSummaryMessage(), $this->getContext(), [
2255 $this->getModulePrefix(),
2256 $this->getModuleName(),
2257 $this->getModulePath(),
2258 ] );
2259 return $msg;
2260 }
2261
2262 /**
2263 * Get final module description, after hooks have had a chance to tweak it as
2264 * needed.
2265 *
2266 * @since 1.25, returns Message[] rather than string[]
2267 * @return Message[]
2268 */
2269 public function getFinalDescription() {
2270 $summary = self::makeMessage( $this->getSummaryMessage(), $this->getContext(), [
2271 $this->getModulePrefix(),
2272 $this->getModuleName(),
2273 $this->getModulePath(),
2274 ] );
2275 $extendedDescription = self::makeMessage(
2276 $this->getExtendedDescription(), $this->getContext(), [
2277 $this->getModulePrefix(),
2278 $this->getModuleName(),
2279 $this->getModulePath(),
2280 ]
2281 );
2282
2283 $msgs = [ $summary, $extendedDescription ];
2284
2285 Hooks::run( 'APIGetDescriptionMessages', [ $this, &$msgs ] );
2286
2287 return $msgs;
2288 }
2289
2290 /**
2291 * Get final list of parameters, after hooks have had a chance to
2292 * tweak it as needed.
2293 *
2294 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
2295 * @return array|bool False on no parameters
2296 * @since 1.21 $flags param added
2297 */
2298 public function getFinalParams( $flags = 0 ) {
2299 $params = $this->getAllowedParams( $flags );
2300 if ( !$params ) {
2301 $params = [];
2302 }
2303
2304 if ( $this->needsToken() ) {
2305 $params['token'] = [
2306 self::PARAM_TYPE => 'string',
2307 self::PARAM_REQUIRED => true,
2308 self::PARAM_SENSITIVE => true,
2309 self::PARAM_HELP_MSG => [
2310 'api-help-param-token',
2311 $this->needsToken(),
2312 ],
2313 ] + ( $params['token'] ?? [] );
2314 }
2315
2316 // Avoid PHP 7.1 warning of passing $this by reference
2317 $apiModule = $this;
2318 Hooks::run( 'APIGetAllowedParams', [ &$apiModule, &$params, $flags ] );
2319
2320 return $params;
2321 }
2322
2323 /**
2324 * Get final parameter descriptions, after hooks have had a chance to tweak it as
2325 * needed.
2326 *
2327 * @since 1.25, returns array of Message[] rather than array of string[]
2328 * @return array Keys are parameter names, values are arrays of Message objects
2329 */
2330 public function getFinalParamDescription() {
2331 $prefix = $this->getModulePrefix();
2332 $name = $this->getModuleName();
2333 $path = $this->getModulePath();
2334
2335 $params = $this->getFinalParams( self::GET_VALUES_FOR_HELP );
2336 $msgs = [];
2337 foreach ( $params as $param => $settings ) {
2338 if ( !is_array( $settings ) ) {
2339 $settings = [];
2340 }
2341
2342 if ( isset( $settings[self::PARAM_HELP_MSG] ) ) {
2343 $msg = $settings[self::PARAM_HELP_MSG];
2344 } else {
2345 $msg = $this->msg( "apihelp-{$path}-param-{$param}" );
2346 }
2347 $msg = self::makeMessage( $msg, $this->getContext(),
2348 [ $prefix, $param, $name, $path ] );
2349 if ( !$msg ) {
2350 self::dieDebug( __METHOD__,
2351 'Value in ApiBase::PARAM_HELP_MSG is not valid' );
2352 }
2353 $msgs[$param] = [ $msg ];
2354
2355 if ( isset( $settings[self::PARAM_TYPE] ) &&
2356 $settings[self::PARAM_TYPE] === 'submodule'
2357 ) {
2358 if ( isset( $settings[self::PARAM_SUBMODULE_MAP] ) ) {
2359 $map = $settings[self::PARAM_SUBMODULE_MAP];
2360 } else {
2361 $prefix = $this->isMain() ? '' : ( $this->getModulePath() . '+' );
2362 $map = [];
2363 foreach ( $this->getModuleManager()->getNames( $param ) as $submoduleName ) {
2364 $map[$submoduleName] = $prefix . $submoduleName;
2365 }
2366 }
2367 ksort( $map );
2368 $submodules = [];
2369 $deprecatedSubmodules = [];
2370 foreach ( $map as $v => $m ) {
2371 $arr = &$submodules;
2372 $isDeprecated = false;
2373 $summary = null;
2374 try {
2375 $submod = $this->getModuleFromPath( $m );
2376 if ( $submod ) {
2377 $summary = $submod->getFinalSummary();
2378 $isDeprecated = $submod->isDeprecated();
2379 if ( $isDeprecated ) {
2380 $arr = &$deprecatedSubmodules;
2381 }
2382 }
2383 } catch ( ApiUsageException $ex ) {
2384 // Ignore
2385 }
2386 if ( $summary ) {
2387 $key = $summary->getKey();
2388 $params = $summary->getParams();
2389 } else {
2390 $key = 'api-help-undocumented-module';
2391 $params = [ $m ];
2392 }
2393 $m = new ApiHelpParamValueMessage( "[[Special:ApiHelp/$m|$v]]", $key, $params, $isDeprecated );
2394 $arr[] = $m->setContext( $this->getContext() );
2395 }
2396 $msgs[$param] = array_merge( $msgs[$param], $submodules, $deprecatedSubmodules );
2397 } elseif ( isset( $settings[self::PARAM_HELP_MSG_PER_VALUE] ) ) {
2398 if ( !is_array( $settings[self::PARAM_HELP_MSG_PER_VALUE] ) ) {
2399 self::dieDebug( __METHOD__,
2400 'ApiBase::PARAM_HELP_MSG_PER_VALUE is not valid' );
2401 }
2402 if ( !is_array( $settings[self::PARAM_TYPE] ) ) {
2403 self::dieDebug( __METHOD__,
2404 'ApiBase::PARAM_HELP_MSG_PER_VALUE may only be used when ' .
2405 'ApiBase::PARAM_TYPE is an array' );
2406 }
2407
2408 $valueMsgs = $settings[self::PARAM_HELP_MSG_PER_VALUE];
2409 $deprecatedValues = $settings[self::PARAM_DEPRECATED_VALUES] ?? [];
2410
2411 foreach ( $settings[self::PARAM_TYPE] as $value ) {
2412 if ( isset( $valueMsgs[$value] ) ) {
2413 $msg = $valueMsgs[$value];
2414 } else {
2415 $msg = "apihelp-{$path}-paramvalue-{$param}-{$value}";
2416 }
2417 $m = self::makeMessage( $msg, $this->getContext(),
2418 [ $prefix, $param, $name, $path, $value ] );
2419 if ( $m ) {
2420 $m = new ApiHelpParamValueMessage(
2421 $value,
2422 [ $m->getKey(), 'api-help-param-no-description' ],
2423 $m->getParams(),
2424 isset( $deprecatedValues[$value] )
2425 );
2426 $msgs[$param][] = $m->setContext( $this->getContext() );
2427 } else {
2428 self::dieDebug( __METHOD__,
2429 "Value in ApiBase::PARAM_HELP_MSG_PER_VALUE for $value is not valid" );
2430 }
2431 }
2432 }
2433
2434 if ( isset( $settings[self::PARAM_HELP_MSG_APPEND] ) ) {
2435 if ( !is_array( $settings[self::PARAM_HELP_MSG_APPEND] ) ) {
2436 self::dieDebug( __METHOD__,
2437 'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
2438 }
2439 foreach ( $settings[self::PARAM_HELP_MSG_APPEND] as $m ) {
2440 $m = self::makeMessage( $m, $this->getContext(),
2441 [ $prefix, $param, $name, $path ] );
2442 if ( $m ) {
2443 $msgs[$param][] = $m;
2444 } else {
2445 self::dieDebug( __METHOD__,
2446 'Value in ApiBase::PARAM_HELP_MSG_APPEND is not valid' );
2447 }
2448 }
2449 }
2450 }
2451
2452 Hooks::run( 'APIGetParamDescriptionMessages', [ $this, &$msgs ] );
2453
2454 return $msgs;
2455 }
2456
2457 /**
2458 * Generates the list of flags for the help screen and for action=paraminfo
2459 *
2460 * Corresponding messages: api-help-flag-deprecated,
2461 * api-help-flag-internal, api-help-flag-readrights,
2462 * api-help-flag-writerights, api-help-flag-mustbeposted
2463 *
2464 * @return string[]
2465 */
2466 protected function getHelpFlags() {
2467 $flags = [];
2468
2469 if ( $this->isDeprecated() ) {
2470 $flags[] = 'deprecated';
2471 }
2472 if ( $this->isInternal() ) {
2473 $flags[] = 'internal';
2474 }
2475 if ( $this->isReadMode() ) {
2476 $flags[] = 'readrights';
2477 }
2478 if ( $this->isWriteMode() ) {
2479 $flags[] = 'writerights';
2480 }
2481 if ( $this->mustBePosted() ) {
2482 $flags[] = 'mustbeposted';
2483 }
2484
2485 return $flags;
2486 }
2487
2488 /**
2489 * Returns information about the source of this module, if known
2490 *
2491 * Returned array is an array with the following keys:
2492 * - path: Install path
2493 * - name: Extension name, or "MediaWiki" for core
2494 * - namemsg: (optional) i18n message key for a display name
2495 * - license-name: (optional) Name of license
2496 *
2497 * @return array|null
2498 */
2499 protected function getModuleSourceInfo() {
2500 global $IP;
2501
2502 if ( $this->mModuleSource !== false ) {
2503 return $this->mModuleSource;
2504 }
2505
2506 // First, try to find where the module comes from...
2507 $rClass = new ReflectionClass( $this );
2508 $path = $rClass->getFileName();
2509 if ( !$path ) {
2510 // No path known?
2511 $this->mModuleSource = null;
2512 return null;
2513 }
2514 $path = realpath( $path ) ?: $path;
2515
2516 // Build map of extension directories to extension info
2517 if ( self::$extensionInfo === null ) {
2518 $extDir = $this->getConfig()->get( 'ExtensionDirectory' );
2519 self::$extensionInfo = [
2520 realpath( __DIR__ ) ?: __DIR__ => [
2521 'path' => $IP,
2522 'name' => 'MediaWiki',
2523 'license-name' => 'GPL-2.0-or-later',
2524 ],
2525 realpath( "$IP/extensions" ) ?: "$IP/extensions" => null,
2526 realpath( $extDir ) ?: $extDir => null,
2527 ];
2528 $keep = [
2529 'path' => null,
2530 'name' => null,
2531 'namemsg' => null,
2532 'license-name' => null,
2533 ];
2534 foreach ( $this->getConfig()->get( 'ExtensionCredits' ) as $group ) {
2535 foreach ( $group as $ext ) {
2536 if ( !isset( $ext['path'] ) || !isset( $ext['name'] ) ) {
2537 // This shouldn't happen, but does anyway.
2538 continue;
2539 }
2540
2541 $extpath = $ext['path'];
2542 if ( !is_dir( $extpath ) ) {
2543 $extpath = dirname( $extpath );
2544 }
2545 self::$extensionInfo[realpath( $extpath ) ?: $extpath] =
2546 array_intersect_key( $ext, $keep );
2547 }
2548 }
2549 foreach ( ExtensionRegistry::getInstance()->getAllThings() as $ext ) {
2550 $extpath = $ext['path'];
2551 if ( !is_dir( $extpath ) ) {
2552 $extpath = dirname( $extpath );
2553 }
2554 self::$extensionInfo[realpath( $extpath ) ?: $extpath] =
2555 array_intersect_key( $ext, $keep );
2556 }
2557 }
2558
2559 // Now traverse parent directories until we find a match or run out of
2560 // parents.
2561 do {
2562 if ( array_key_exists( $path, self::$extensionInfo ) ) {
2563 // Found it!
2564 $this->mModuleSource = self::$extensionInfo[$path];
2565 return $this->mModuleSource;
2566 }
2567
2568 $oldpath = $path;
2569 $path = dirname( $path );
2570 } while ( $path !== $oldpath );
2571
2572 // No idea what extension this might be.
2573 $this->mModuleSource = null;
2574 return null;
2575 }
2576
2577 /**
2578 * Called from ApiHelp before the pieces are joined together and returned.
2579 *
2580 * This exists mainly for ApiMain to add the Permissions and Credits
2581 * sections. Other modules probably don't need it.
2582 *
2583 * @param string[] &$help Array of help data
2584 * @param array $options Options passed to ApiHelp::getHelp
2585 * @param array &$tocData If a TOC is being generated, this array has keys
2586 * as anchors in the page and values as for Linker::generateTOC().
2587 */
2588 public function modifyHelp( array &$help, array $options, array &$tocData ) {
2589 }
2590
2591 /**@}*/
2592
2593 /************************************************************************//**
2594 * @name Deprecated
2595 * @{
2596 */
2597
2598 /**
2599 * Returns the description string for this module
2600 *
2601 * Ignored if an i18n message exists for
2602 * "apihelp-{$this->getModulePath()}-description".
2603 *
2604 * @deprecated since 1.25
2605 * @return Message|string|array|false
2606 */
2607 protected function getDescription() {
2608 wfDeprecated( __METHOD__, '1.25' );
2609 return false;
2610 }
2611
2612 /**
2613 * Returns an array of parameter descriptions.
2614 *
2615 * For each parameter, ignored if an i18n message exists for the parameter.
2616 * By default that message is
2617 * "apihelp-{$this->getModulePath()}-param-{$param}", but it may be
2618 * overridden using ApiBase::PARAM_HELP_MSG in the data returned by
2619 * self::getFinalParams().
2620 *
2621 * @deprecated since 1.25
2622 * @return array|bool False on no parameter descriptions
2623 */
2624 protected function getParamDescription() {
2625 wfDeprecated( __METHOD__, '1.25' );
2626 return [];
2627 }
2628
2629 /**
2630 * Returns usage examples for this module.
2631 *
2632 * Return value as an array is either:
2633 * - numeric keys with partial URLs ("api.php?" plus a query string) as
2634 * values
2635 * - sequential numeric keys with even-numbered keys being display-text
2636 * and odd-numbered keys being partial urls
2637 * - partial URLs as keys with display-text (string or array-to-be-joined)
2638 * as values
2639 * Return value as a string is the same as an array with a numeric key and
2640 * that value, and boolean false means "no examples".
2641 *
2642 * @deprecated since 1.25, use getExamplesMessages() instead
2643 * @return bool|string|array
2644 */
2645 protected function getExamples() {
2646 wfDeprecated( __METHOD__, '1.25' );
2647 return false;
2648 }
2649
2650 /**
2651 * Return the description message.
2652 *
2653 * This is additional text to display on the help page after the summary.
2654 *
2655 * @deprecated since 1.30
2656 * @return string|array|Message
2657 */
2658 protected function getDescriptionMessage() {
2659 wfDeprecated( __METHOD__, '1.30' );
2660 return [ [
2661 "apihelp-{$this->getModulePath()}-description",
2662 "apihelp-{$this->getModulePath()}-summary",
2663 ] ];
2664 }
2665
2666 /**
2667 * Truncate an array to a certain length.
2668 * @deprecated since 1.32, no replacement
2669 * @param array &$arr Array to truncate
2670 * @param int $limit Maximum length
2671 * @return bool True if the array was truncated, false otherwise
2672 */
2673 public static function truncateArray( &$arr, $limit ) {
2674 wfDeprecated( __METHOD__, '1.32' );
2675 $modified = false;
2676 while ( count( $arr ) > $limit ) {
2677 array_pop( $arr );
2678 $modified = true;
2679 }
2680
2681 return $modified;
2682 }
2683
2684 /**@}*/
2685 }
2686
2687 /**
2688 * For really cool vim folding this needs to be at the end:
2689 * vim: foldmarker=@{,@} foldmethod=marker
2690 */