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