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