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