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