Add logic for "tags" in ApiBase
[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 if ( $this->getUser()->matchEditToken(
1276 $token,
1277 $salts[$tokenType],
1278 $this->getRequest()
1279 ) ) {
1280 return true;
1281 }
1282
1283 $webUiSalt = $this->getWebUITokenSalt( $params );
1284 if ( $webUiSalt !== null && $this->getUser()->matchEditToken(
1285 $token,
1286 $webUiSalt,
1287 $this->getRequest()
1288 ) ) {
1289 return true;
1290 }
1291
1292 return false;
1293 }
1294
1295 /**
1296 * Validate and normalize of parameters of type 'user'
1297 * @param string $value Parameter value
1298 * @param string $encParamName Parameter name
1299 * @return string Validated and normalized parameter
1300 */
1301 private function validateUser( $value, $encParamName ) {
1302 $title = Title::makeTitleSafe( NS_USER, $value );
1303 if ( $title === null ) {
1304 $this->dieUsage(
1305 "Invalid value '$value' for user parameter $encParamName",
1306 "baduser_{$encParamName}"
1307 );
1308 }
1309
1310 return $title->getText();
1311 }
1312
1313 /**@}*/
1314
1315 /************************************************************************//**
1316 * @name Utility methods
1317 * @{
1318 */
1319
1320 /**
1321 * Set a watch (or unwatch) based the based on a watchlist parameter.
1322 * @param string $watch Valid values: 'watch', 'unwatch', 'preferences', 'nochange'
1323 * @param Title $titleObj The article's title to change
1324 * @param string $userOption The user option to consider when $watch=preferences
1325 */
1326 protected function setWatch( $watch, $titleObj, $userOption = null ) {
1327 $value = $this->getWatchlistValue( $watch, $titleObj, $userOption );
1328 if ( $value === null ) {
1329 return;
1330 }
1331
1332 WatchAction::doWatchOrUnwatch( $value, $titleObj, $this->getUser() );
1333 }
1334
1335 /**
1336 * Truncate an array to a certain length.
1337 * @param array $arr Array to truncate
1338 * @param int $limit Maximum length
1339 * @return bool True if the array was truncated, false otherwise
1340 */
1341 public static function truncateArray( &$arr, $limit ) {
1342 $modified = false;
1343 while ( count( $arr ) > $limit ) {
1344 array_pop( $arr );
1345 $modified = true;
1346 }
1347
1348 return $modified;
1349 }
1350
1351 /**
1352 * Gets the user for whom to get the watchlist
1353 *
1354 * @param array $params
1355 * @return User
1356 */
1357 public function getWatchlistUser( $params ) {
1358 if ( !is_null( $params['owner'] ) && !is_null( $params['token'] ) ) {
1359 $user = User::newFromName( $params['owner'], false );
1360 if ( !( $user && $user->getId() ) ) {
1361 $this->dieUsage( 'Specified user does not exist', 'bad_wlowner' );
1362 }
1363 $token = $user->getOption( 'watchlisttoken' );
1364 if ( $token == '' || !hash_equals( $token, $params['token'] ) ) {
1365 $this->dieUsage(
1366 'Incorrect watchlist token provided -- please set a correct token in Special:Preferences',
1367 'bad_wltoken'
1368 );
1369 }
1370 } else {
1371 if ( !$this->getUser()->isLoggedIn() ) {
1372 $this->dieUsage( 'You must be logged-in to have a watchlist', 'notloggedin' );
1373 }
1374 if ( !$this->getUser()->isAllowed( 'viewmywatchlist' ) ) {
1375 $this->dieUsage( 'You don\'t have permission to view your watchlist', 'permissiondenied' );
1376 }
1377 $user = $this->getUser();
1378 }
1379
1380 return $user;
1381 }
1382
1383 /**
1384 * A subset of wfEscapeWikiText for BC texts
1385 *
1386 * @since 1.25
1387 * @param string|array $v
1388 * @return string|array
1389 */
1390 private static function escapeWikiText( $v ) {
1391 if ( is_array( $v ) ) {
1392 return array_map( 'self::escapeWikiText', $v );
1393 } else {
1394 return strtr( $v, array(
1395 '__' => '_&#95;', '{' => '&#123;', '}' => '&#125;',
1396 '[[Category:' => '[[:Category:',
1397 '[[File:' => '[[:File:', '[[Image:' => '[[:Image:',
1398 ) );
1399 }
1400 }
1401
1402 /**
1403 * Create a Message from a string or array
1404 *
1405 * A string is used as a message key. An array has the message key as the
1406 * first value and message parameters as subsequent values.
1407 *
1408 * @since 1.25
1409 * @param string|array|Message $msg
1410 * @param IContextSource $context
1411 * @param array $params
1412 * @return Message|null
1413 */
1414 public static function makeMessage( $msg, IContextSource $context, array $params = null ) {
1415 if ( is_string( $msg ) ) {
1416 $msg = wfMessage( $msg );
1417 } elseif ( is_array( $msg ) ) {
1418 $msg = call_user_func_array( 'wfMessage', $msg );
1419 }
1420 if ( !$msg instanceof Message ) {
1421 return null;
1422 }
1423
1424 $msg->setContext( $context );
1425 if ( $params ) {
1426 $msg->params( $params );
1427 }
1428
1429 return $msg;
1430 }
1431
1432 /**@}*/
1433
1434 /************************************************************************//**
1435 * @name Warning and error reporting
1436 * @{
1437 */
1438
1439 /**
1440 * Set warning section for this module. Users should monitor this
1441 * section to notice any changes in API. Multiple calls to this
1442 * function will result in the warning messages being separated by
1443 * newlines
1444 * @param string $warning Warning message
1445 */
1446 public function setWarning( $warning ) {
1447 $msg = new ApiRawMessage( $warning, 'warning' );
1448 $this->getErrorFormatter()->addWarning( $this->getModuleName(), $msg );
1449 }
1450
1451 /**
1452 * Adds a warning to the output, else dies
1453 *
1454 * @param string $msg Message to show as a warning, or error message if dying
1455 * @param bool $enforceLimits Whether this is an enforce (die)
1456 */
1457 private function warnOrDie( $msg, $enforceLimits = false ) {
1458 if ( $enforceLimits ) {
1459 $this->dieUsage( $msg, 'integeroutofrange' );
1460 }
1461
1462 $this->setWarning( $msg );
1463 }
1464
1465 /**
1466 * Throw a UsageException, which will (if uncaught) call the main module's
1467 * error handler and die with an error message.
1468 *
1469 * @param string $description One-line human-readable description of the
1470 * error condition, e.g., "The API requires a valid action parameter"
1471 * @param string $errorCode Brief, arbitrary, stable string to allow easy
1472 * automated identification of the error, e.g., 'unknown_action'
1473 * @param int $httpRespCode HTTP response code
1474 * @param array|null $extradata Data to add to the "<error>" element; array in ApiResult format
1475 * @throws UsageException always
1476 */
1477 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata = null ) {
1478 throw new UsageException(
1479 $description,
1480 $this->encodeParamName( $errorCode ),
1481 $httpRespCode,
1482 $extradata
1483 );
1484 }
1485
1486 /**
1487 * Throw a UsageException, which will (if uncaught) call the main module's
1488 * error handler and die with an error message including block info.
1489 *
1490 * @since 1.27
1491 * @param Block $block The block used to generate the UsageException
1492 * @throws UsageException always
1493 */
1494 public function dieBlocked( Block $block ) {
1495 // Die using the appropriate message depending on block type
1496 if ( $block->getType() == Block::TYPE_AUTO ) {
1497 $this->dieUsage(
1498 'Your IP address has been blocked automatically, because it was used by a blocked user',
1499 'autoblocked',
1500 0,
1501 array( 'blockinfo' => ApiQueryUserInfo::getBlockInfo( $block ) )
1502 );
1503 } else {
1504 $this->dieUsage(
1505 'You have been blocked from editing',
1506 'blocked',
1507 0,
1508 array( 'blockinfo' => ApiQueryUserInfo::getBlockInfo( $block ) )
1509 );
1510 }
1511 }
1512
1513 /**
1514 * Get error (as code, string) from a Status object.
1515 *
1516 * @since 1.23
1517 * @param Status $status
1518 * @param array|null &$extraData Set if extra data from IApiMessage is available (since 1.27)
1519 * @return array Array of code and error string
1520 * @throws MWException
1521 */
1522 public function getErrorFromStatus( $status, &$extraData = null ) {
1523 if ( $status->isGood() ) {
1524 throw new MWException( 'Successful status passed to ApiBase::dieStatus' );
1525 }
1526
1527 $errors = $status->getErrorsArray();
1528 if ( !$errors ) {
1529 // No errors? Assume the warnings should be treated as errors
1530 $errors = $status->getWarningsArray();
1531 }
1532 if ( !$errors ) {
1533 // Still no errors? Punt
1534 $errors = array( array( 'unknownerror-nocode' ) );
1535 }
1536
1537 // Cannot use dieUsageMsg() because extensions might return custom
1538 // error messages.
1539 if ( $errors[0] instanceof Message ) {
1540 $msg = $errors[0];
1541 if ( $msg instanceof IApiMessage ) {
1542 $extraData = $msg->getApiData();
1543 $code = $msg->getApiCode();
1544 } else {
1545 $code = $msg->getKey();
1546 }
1547 } else {
1548 $code = array_shift( $errors[0] );
1549 $msg = wfMessage( $code, $errors[0] );
1550 }
1551 if ( isset( ApiBase::$messageMap[$code] ) ) {
1552 // Translate message to code, for backwards compatibility
1553 $code = ApiBase::$messageMap[$code]['code'];
1554 }
1555
1556 return array( $code, $msg->inLanguage( 'en' )->useDatabase( false )->plain() );
1557 }
1558
1559 /**
1560 * Throw a UsageException based on the errors in the Status object.
1561 *
1562 * @since 1.22
1563 * @param Status $status
1564 * @throws UsageException always
1565 */
1566 public function dieStatus( $status ) {
1567 $extraData = null;
1568 list( $code, $msg ) = $this->getErrorFromStatus( $status, $extraData );
1569 $this->dieUsage( $msg, $code, 0, $extraData );
1570 }
1571
1572 // @codingStandardsIgnoreStart Allow long lines. Cannot split these.
1573 /**
1574 * Array that maps message keys to error messages. $1 and friends are replaced.
1575 */
1576 public static $messageMap = array(
1577 // This one MUST be present, or dieUsageMsg() will recurse infinitely
1578 'unknownerror' => array( 'code' => 'unknownerror', 'info' => "Unknown error: \"\$1\"" ),
1579 'unknownerror-nocode' => array( 'code' => 'unknownerror', 'info' => 'Unknown error' ),
1580
1581 // Messages from Title::getUserPermissionsErrors()
1582 'ns-specialprotected' => array(
1583 'code' => 'unsupportednamespace',
1584 'info' => "Pages in the Special namespace can't be edited"
1585 ),
1586 'protectedinterface' => array(
1587 'code' => 'protectednamespace-interface',
1588 'info' => "You're not allowed to edit interface messages"
1589 ),
1590 'namespaceprotected' => array(
1591 'code' => 'protectednamespace',
1592 'info' => "You're not allowed to edit pages in the \"\$1\" namespace"
1593 ),
1594 'customcssprotected' => array(
1595 'code' => 'customcssprotected',
1596 'info' => "You're not allowed to edit custom CSS pages"
1597 ),
1598 'customjsprotected' => array(
1599 'code' => 'customjsprotected',
1600 'info' => "You're not allowed to edit custom JavaScript pages"
1601 ),
1602 'cascadeprotected' => array(
1603 'code' => 'cascadeprotected',
1604 'info' => "The page you're trying to edit is protected because it's included in a cascade-protected page"
1605 ),
1606 'protectedpagetext' => array(
1607 'code' => 'protectedpage',
1608 'info' => "The \"\$1\" right is required to edit this page"
1609 ),
1610 'protect-cantedit' => array(
1611 'code' => 'cantedit',
1612 'info' => "You can't protect this page because you can't edit it"
1613 ),
1614 'deleteprotected' => array(
1615 'code' => 'cantedit',
1616 'info' => "You can't delete this page because it has been protected"
1617 ),
1618 'badaccess-group0' => array(
1619 'code' => 'permissiondenied',
1620 'info' => "Permission denied"
1621 ), // Generic permission denied message
1622 'badaccess-groups' => array(
1623 'code' => 'permissiondenied',
1624 'info' => "Permission denied"
1625 ),
1626 'titleprotected' => array(
1627 'code' => 'protectedtitle',
1628 'info' => "This title has been protected from creation"
1629 ),
1630 'nocreate-loggedin' => array(
1631 'code' => 'cantcreate',
1632 'info' => "You don't have permission to create new pages"
1633 ),
1634 'nocreatetext' => array(
1635 'code' => 'cantcreate-anon',
1636 'info' => "Anonymous users can't create new pages"
1637 ),
1638 'movenologintext' => array(
1639 'code' => 'cantmove-anon',
1640 'info' => "Anonymous users can't move pages"
1641 ),
1642 'movenotallowed' => array(
1643 'code' => 'cantmove',
1644 'info' => "You don't have permission to move pages"
1645 ),
1646 'confirmedittext' => array(
1647 'code' => 'confirmemail',
1648 'info' => "You must confirm your email address before you can edit"
1649 ),
1650 'blockedtext' => array(
1651 'code' => 'blocked',
1652 'info' => "You have been blocked from editing"
1653 ),
1654 'autoblockedtext' => array(
1655 'code' => 'autoblocked',
1656 'info' => "Your IP address has been blocked automatically, because it was used by a blocked user"
1657 ),
1658
1659 // Miscellaneous interface messages
1660 'actionthrottledtext' => array(
1661 'code' => 'ratelimited',
1662 'info' => "You've exceeded your rate limit. Please wait some time and try again"
1663 ),
1664 'alreadyrolled' => array(
1665 'code' => 'alreadyrolled',
1666 'info' => "The page you tried to rollback was already rolled back"
1667 ),
1668 'cantrollback' => array(
1669 'code' => 'onlyauthor',
1670 'info' => "The page you tried to rollback only has one author"
1671 ),
1672 'readonlytext' => array(
1673 'code' => 'readonly',
1674 'info' => "The wiki is currently in read-only mode"
1675 ),
1676 'sessionfailure' => array(
1677 'code' => 'badtoken',
1678 'info' => "Invalid token" ),
1679 'cannotdelete' => array(
1680 'code' => 'cantdelete',
1681 'info' => "Couldn't delete \"\$1\". Maybe it was deleted already by someone else"
1682 ),
1683 'notanarticle' => array(
1684 'code' => 'missingtitle',
1685 'info' => "The page you requested doesn't exist"
1686 ),
1687 'selfmove' => array( 'code' => 'selfmove', 'info' => "Can't move a page to itself"
1688 ),
1689 'immobile_namespace' => array(
1690 'code' => 'immobilenamespace',
1691 'info' => "You tried to move pages from or to a namespace that is protected from moving"
1692 ),
1693 'articleexists' => array(
1694 'code' => 'articleexists',
1695 'info' => "The destination article already exists and is not a redirect to the source article"
1696 ),
1697 'protectedpage' => array(
1698 'code' => 'protectedpage',
1699 'info' => "You don't have permission to perform this move"
1700 ),
1701 'hookaborted' => array(
1702 'code' => 'hookaborted',
1703 'info' => "The modification you tried to make was aborted by an extension hook"
1704 ),
1705 'cantmove-titleprotected' => array(
1706 'code' => 'protectedtitle',
1707 'info' => "The destination article has been protected from creation"
1708 ),
1709 'imagenocrossnamespace' => array(
1710 'code' => 'nonfilenamespace',
1711 'info' => "Can't move a file to a non-file namespace"
1712 ),
1713 'imagetypemismatch' => array(
1714 'code' => 'filetypemismatch',
1715 'info' => "The new file extension doesn't match its type"
1716 ),
1717 // 'badarticleerror' => shouldn't happen
1718 // 'badtitletext' => shouldn't happen
1719 'ip_range_invalid' => array( 'code' => 'invalidrange', 'info' => "Invalid IP range" ),
1720 'range_block_disabled' => array(
1721 'code' => 'rangedisabled',
1722 'info' => "Blocking IP ranges has been disabled"
1723 ),
1724 'nosuchusershort' => array(
1725 'code' => 'nosuchuser',
1726 'info' => "The user you specified doesn't exist"
1727 ),
1728 'badipaddress' => array( 'code' => 'invalidip', 'info' => "Invalid IP address specified" ),
1729 'ipb_expiry_invalid' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time" ),
1730 'ipb_already_blocked' => array(
1731 'code' => 'alreadyblocked',
1732 'info' => "The user you tried to block was already blocked"
1733 ),
1734 'ipb_blocked_as_range' => array(
1735 'code' => 'blockedasrange',
1736 '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."
1737 ),
1738 'ipb_cant_unblock' => array(
1739 'code' => 'cantunblock',
1740 'info' => "The block you specified was not found. It may have been unblocked already"
1741 ),
1742 'mailnologin' => array(
1743 'code' => 'cantsend',
1744 '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"
1745 ),
1746 'ipbblocked' => array(
1747 'code' => 'ipbblocked',
1748 'info' => 'You cannot block or unblock users while you are yourself blocked'
1749 ),
1750 'ipbnounblockself' => array(
1751 'code' => 'ipbnounblockself',
1752 'info' => 'You are not allowed to unblock yourself'
1753 ),
1754 'usermaildisabled' => array(
1755 'code' => 'usermaildisabled',
1756 'info' => "User email has been disabled"
1757 ),
1758 'blockedemailuser' => array(
1759 'code' => 'blockedfrommail',
1760 'info' => "You have been blocked from sending email"
1761 ),
1762 'notarget' => array(
1763 'code' => 'notarget',
1764 'info' => "You have not specified a valid target for this action"
1765 ),
1766 'noemail' => array(
1767 'code' => 'noemail',
1768 'info' => "The user has not specified a valid email address, or has chosen not to receive email from other users"
1769 ),
1770 'rcpatroldisabled' => array(
1771 'code' => 'patroldisabled',
1772 'info' => "Patrolling is disabled on this wiki"
1773 ),
1774 'markedaspatrollederror-noautopatrol' => array(
1775 'code' => 'noautopatrol',
1776 'info' => "You don't have permission to patrol your own changes"
1777 ),
1778 'delete-toobig' => array(
1779 'code' => 'bigdelete',
1780 'info' => "You can't delete this page because it has more than \$1 revisions"
1781 ),
1782 'movenotallowedfile' => array(
1783 'code' => 'cantmovefile',
1784 'info' => "You don't have permission to move files"
1785 ),
1786 'userrights-no-interwiki' => array(
1787 'code' => 'nointerwikiuserrights',
1788 'info' => "You don't have permission to change user rights on other wikis"
1789 ),
1790 'userrights-nodatabase' => array(
1791 'code' => 'nosuchdatabase',
1792 'info' => "Database \"\$1\" does not exist or is not local"
1793 ),
1794 'nouserspecified' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1795 'noname' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1796 'summaryrequired' => array( 'code' => 'summaryrequired', 'info' => 'Summary required' ),
1797 'import-rootpage-invalid' => array(
1798 'code' => 'import-rootpage-invalid',
1799 'info' => 'Root page is an invalid title'
1800 ),
1801 'import-rootpage-nosubpage' => array(
1802 'code' => 'import-rootpage-nosubpage',
1803 'info' => 'Namespace "$1" of the root page does not allow subpages'
1804 ),
1805
1806 // API-specific messages
1807 'readrequired' => array(
1808 'code' => 'readapidenied',
1809 'info' => "You need read permission to use this module"
1810 ),
1811 'writedisabled' => array(
1812 'code' => 'noapiwrite',
1813 '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"
1814 ),
1815 'writerequired' => array(
1816 'code' => 'writeapidenied',
1817 'info' => "You're not allowed to edit this wiki through the API"
1818 ),
1819 'missingparam' => array( 'code' => 'no$1', 'info' => "The \$1 parameter must be set" ),
1820 'invalidtitle' => array( 'code' => 'invalidtitle', 'info' => "Bad title \"\$1\"" ),
1821 'nosuchpageid' => array( 'code' => 'nosuchpageid', 'info' => "There is no page with ID \$1" ),
1822 'nosuchrevid' => array( 'code' => 'nosuchrevid', 'info' => "There is no revision with ID \$1" ),
1823 'nosuchuser' => array( 'code' => 'nosuchuser', 'info' => "User \"\$1\" doesn't exist" ),
1824 'invaliduser' => array( 'code' => 'invaliduser', 'info' => "Invalid username \"\$1\"" ),
1825 'invalidexpiry' => array( 'code' => 'invalidexpiry', 'info' => "Invalid expiry time \"\$1\"" ),
1826 'pastexpiry' => array( 'code' => 'pastexpiry', 'info' => "Expiry time \"\$1\" is in the past" ),
1827 'create-titleexists' => array(
1828 'code' => 'create-titleexists',
1829 'info' => "Existing titles can't be protected with 'create'"
1830 ),
1831 'missingtitle-createonly' => array(
1832 'code' => 'missingtitle-createonly',
1833 'info' => "Missing titles can only be protected with 'create'"
1834 ),
1835 'cantblock' => array( 'code' => 'cantblock',
1836 'info' => "You don't have permission to block users"
1837 ),
1838 'canthide' => array(
1839 'code' => 'canthide',
1840 'info' => "You don't have permission to hide user names from the block log"
1841 ),
1842 'cantblock-email' => array(
1843 'code' => 'cantblock-email',
1844 'info' => "You don't have permission to block users from sending email through the wiki"
1845 ),
1846 'unblock-notarget' => array(
1847 'code' => 'notarget',
1848 'info' => "Either the id or the user parameter must be set"
1849 ),
1850 'unblock-idanduser' => array(
1851 'code' => 'idanduser',
1852 'info' => "The id and user parameters can't be used together"
1853 ),
1854 'cantunblock' => array(
1855 'code' => 'permissiondenied',
1856 'info' => "You don't have permission to unblock users"
1857 ),
1858 'cannotundelete' => array(
1859 'code' => 'cantundelete',
1860 'info' => "Couldn't undelete: the requested revisions may not exist, or may have been undeleted already"
1861 ),
1862 'permdenied-undelete' => array(
1863 'code' => 'permissiondenied',
1864 'info' => "You don't have permission to restore deleted revisions"
1865 ),
1866 'createonly-exists' => array(
1867 'code' => 'articleexists',
1868 'info' => "The article you tried to create has been created already"
1869 ),
1870 'nocreate-missing' => array(
1871 'code' => 'missingtitle',
1872 'info' => "The article you tried to edit doesn't exist"
1873 ),
1874 'cantchangecontentmodel' => array(
1875 'code' => 'cantchangecontentmodel',
1876 'info' => "You don't have permission to change the content model of a page"
1877 ),
1878 'nosuchrcid' => array(
1879 'code' => 'nosuchrcid',
1880 'info' => "There is no change with rcid \"\$1\""
1881 ),
1882 'nosuchlogid' => array(
1883 'code' => 'nosuchlogid',
1884 'info' => "There is no log entry with ID \"\$1\""
1885 ),
1886 'protect-invalidaction' => array(
1887 'code' => 'protect-invalidaction',
1888 'info' => "Invalid protection type \"\$1\""
1889 ),
1890 'protect-invalidlevel' => array(
1891 'code' => 'protect-invalidlevel',
1892 'info' => "Invalid protection level \"\$1\""
1893 ),
1894 'toofewexpiries' => array(
1895 'code' => 'toofewexpiries',
1896 'info' => "\$1 expiry timestamps were provided where \$2 were needed"
1897 ),
1898 'cantimport' => array(
1899 'code' => 'cantimport',
1900 'info' => "You don't have permission to import pages"
1901 ),
1902 'cantimport-upload' => array(
1903 'code' => 'cantimport-upload',
1904 'info' => "You don't have permission to import uploaded pages"
1905 ),
1906 'importnofile' => array( 'code' => 'nofile', 'info' => "You didn't upload a file" ),
1907 'importuploaderrorsize' => array(
1908 'code' => 'filetoobig',
1909 'info' => 'The file you uploaded is bigger than the maximum upload size'
1910 ),
1911 'importuploaderrorpartial' => array(
1912 'code' => 'partialupload',
1913 'info' => 'The file was only partially uploaded'
1914 ),
1915 'importuploaderrortemp' => array(
1916 'code' => 'notempdir',
1917 'info' => 'The temporary upload directory is missing'
1918 ),
1919 'importcantopen' => array(
1920 'code' => 'cantopenfile',
1921 'info' => "Couldn't open the uploaded file"
1922 ),
1923 'import-noarticle' => array(
1924 'code' => 'badinterwiki',
1925 'info' => 'Invalid interwiki title specified'
1926 ),
1927 'importbadinterwiki' => array(
1928 'code' => 'badinterwiki',
1929 'info' => 'Invalid interwiki title specified'
1930 ),
1931 'import-unknownerror' => array(
1932 'code' => 'import-unknownerror',
1933 'info' => "Unknown error on import: \"\$1\""
1934 ),
1935 'cantoverwrite-sharedfile' => array(
1936 'code' => 'cantoverwrite-sharedfile',
1937 'info' => 'The target file exists on a shared repository and you do not have permission to override it'
1938 ),
1939 'sharedfile-exists' => array(
1940 'code' => 'fileexists-sharedrepo-perm',
1941 'info' => 'The target file exists on a shared repository. Use the ignorewarnings parameter to override it.'
1942 ),
1943 'mustbeposted' => array(
1944 'code' => 'mustbeposted',
1945 'info' => "The \$1 module requires a POST request"
1946 ),
1947 'show' => array(
1948 'code' => 'show',
1949 'info' => 'Incorrect parameter - mutually exclusive values may not be supplied'
1950 ),
1951 'specialpage-cantexecute' => array(
1952 'code' => 'specialpage-cantexecute',
1953 'info' => "You don't have permission to view the results of this special page"
1954 ),
1955 'invalidoldimage' => array(
1956 'code' => 'invalidoldimage',
1957 'info' => 'The oldimage parameter has invalid format'
1958 ),
1959 'nodeleteablefile' => array(
1960 'code' => 'nodeleteablefile',
1961 'info' => 'No such old version of the file'
1962 ),
1963 'fileexists-forbidden' => array(
1964 'code' => 'fileexists-forbidden',
1965 'info' => 'A file with name "$1" already exists, and cannot be overwritten.'
1966 ),
1967 'fileexists-shared-forbidden' => array(
1968 'code' => 'fileexists-shared-forbidden',
1969 'info' => 'A file with name "$1" already exists in the shared file repository, and cannot be overwritten.'
1970 ),
1971 'filerevert-badversion' => array(
1972 'code' => 'filerevert-badversion',
1973 'info' => 'There is no previous local version of this file with the provided timestamp.'
1974 ),
1975
1976 // ApiEditPage messages
1977 'noimageredirect-anon' => array(
1978 'code' => 'noimageredirect-anon',
1979 'info' => "Anonymous users can't create image redirects"
1980 ),
1981 'noimageredirect-logged' => array(
1982 'code' => 'noimageredirect',
1983 'info' => "You don't have permission to create image redirects"
1984 ),
1985 'spamdetected' => array(
1986 'code' => 'spamdetected',
1987 'info' => "Your edit was refused because it contained a spam fragment: \"\$1\""
1988 ),
1989 'contenttoobig' => array(
1990 'code' => 'contenttoobig',
1991 'info' => "The content you supplied exceeds the article size limit of \$1 kilobytes"
1992 ),
1993 'noedit-anon' => array( 'code' => 'noedit-anon', 'info' => "Anonymous users can't edit pages" ),
1994 'noedit' => array( 'code' => 'noedit', 'info' => "You don't have permission to edit pages" ),
1995 'wasdeleted' => array(
1996 'code' => 'pagedeleted',
1997 'info' => "The page has been deleted since you fetched its timestamp"
1998 ),
1999 'blankpage' => array(
2000 'code' => 'emptypage',
2001 'info' => "Creating new, empty pages is not allowed"
2002 ),
2003 'editconflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
2004 'hashcheckfailed' => array( 'code' => 'badmd5', 'info' => "The supplied MD5 hash was incorrect" ),
2005 'missingtext' => array(
2006 'code' => 'notext',
2007 'info' => "One of the text, appendtext, prependtext and undo parameters must be set"
2008 ),
2009 'emptynewsection' => array(
2010 'code' => 'emptynewsection',
2011 'info' => 'Creating empty new sections is not possible.'
2012 ),
2013 'revwrongpage' => array(
2014 'code' => 'revwrongpage',
2015 'info' => "r\$1 is not a revision of \"\$2\""
2016 ),
2017 'undo-failure' => array(
2018 'code' => 'undofailure',
2019 'info' => 'Undo failed due to conflicting intermediate edits'
2020 ),
2021 'content-not-allowed-here' => array(
2022 'code' => 'contentnotallowedhere',
2023 'info' => 'Content model "$1" is not allowed at title "$2"'
2024 ),
2025
2026 // Messages from WikiPage::doEit()
2027 'edit-hook-aborted' => array(
2028 'code' => 'edit-hook-aborted',
2029 'info' => "Your edit was aborted by an ArticleSave hook"
2030 ),
2031 'edit-gone-missing' => array(
2032 'code' => 'edit-gone-missing',
2033 'info' => "The page you tried to edit doesn't seem to exist anymore"
2034 ),
2035 'edit-conflict' => array( 'code' => 'editconflict', 'info' => "Edit conflict detected" ),
2036 'edit-already-exists' => array(
2037 'code' => 'edit-already-exists',
2038 'info' => 'It seems the page you tried to create already exist'
2039 ),
2040
2041 // uploadMsgs
2042 'invalid-file-key' => array( 'code' => 'invalid-file-key', 'info' => 'Not a valid file key' ),
2043 'nouploadmodule' => array( 'code' => 'nouploadmodule', 'info' => 'No upload module set' ),
2044 'uploaddisabled' => array(
2045 'code' => 'uploaddisabled',
2046 'info' => 'Uploads are not enabled. Make sure $wgEnableUploads is set to true in LocalSettings.php and the PHP ini setting file_uploads is true'
2047 ),
2048 'copyuploaddisabled' => array(
2049 'code' => 'copyuploaddisabled',
2050 'info' => 'Uploads by URL is not enabled. Make sure $wgAllowCopyUploads is set to true in LocalSettings.php.'
2051 ),
2052 'copyuploadbaddomain' => array(
2053 'code' => 'copyuploadbaddomain',
2054 'info' => 'Uploads by URL are not allowed from this domain.'
2055 ),
2056 'copyuploadbadurl' => array(
2057 'code' => 'copyuploadbadurl',
2058 'info' => 'Upload not allowed from this URL.'
2059 ),
2060
2061 'filename-tooshort' => array(
2062 'code' => 'filename-tooshort',
2063 'info' => 'The filename is too short'
2064 ),
2065 'filename-toolong' => array( 'code' => 'filename-toolong', 'info' => 'The filename is too long' ),
2066 'illegal-filename' => array(
2067 'code' => 'illegal-filename',
2068 'info' => 'The filename is not allowed'
2069 ),
2070 'filetype-missing' => array(
2071 'code' => 'filetype-missing',
2072 'info' => 'The file is missing an extension'
2073 ),
2074
2075 'mustbeloggedin' => array( 'code' => 'mustbeloggedin', 'info' => 'You must be logged in to $1.' )
2076 );
2077 // @codingStandardsIgnoreEnd
2078
2079 /**
2080 * Helper function for readonly errors
2081 *
2082 * @throws UsageException always
2083 */
2084 public function dieReadOnly() {
2085 $parsed = $this->parseMsg( array( 'readonlytext' ) );
2086 $this->dieUsage( $parsed['info'], $parsed['code'], /* http error */ 0,
2087 array( 'readonlyreason' => wfReadOnlyReason() ) );
2088 }
2089
2090 /**
2091 * Output the error message related to a certain array
2092 * @param array|string $error Element of a getUserPermissionsErrors()-style array
2093 * @throws UsageException always
2094 */
2095 public function dieUsageMsg( $error ) {
2096 # most of the time we send a 1 element, so we might as well send it as
2097 # a string and make this an array here.
2098 if ( is_string( $error ) ) {
2099 $error = array( $error );
2100 }
2101 $parsed = $this->parseMsg( $error );
2102 $extraData = isset( $parsed['data'] ) ? $parsed['data'] : null;
2103 $this->dieUsage( $parsed['info'], $parsed['code'], 0, $extraData );
2104 }
2105
2106 /**
2107 * Will only set a warning instead of failing if the global $wgDebugAPI
2108 * is set to true. Otherwise behaves exactly as dieUsageMsg().
2109 * @param array|string $error Element of a getUserPermissionsErrors()-style array
2110 * @throws UsageException
2111 * @since 1.21
2112 */
2113 public function dieUsageMsgOrDebug( $error ) {
2114 if ( $this->getConfig()->get( 'DebugAPI' ) !== true ) {
2115 $this->dieUsageMsg( $error );
2116 }
2117
2118 if ( is_string( $error ) ) {
2119 $error = array( $error );
2120 }
2121 $parsed = $this->parseMsg( $error );
2122 $this->setWarning( '$wgDebugAPI: ' . $parsed['code'] . ' - ' . $parsed['info'] );
2123 }
2124
2125 /**
2126 * Die with the $prefix.'badcontinue' error. This call is common enough to
2127 * make it into the base method.
2128 * @param bool $condition Will only die if this value is true
2129 * @throws UsageException
2130 * @since 1.21
2131 */
2132 protected function dieContinueUsageIf( $condition ) {
2133 if ( $condition ) {
2134 $this->dieUsage(
2135 'Invalid continue param. You should pass the original value returned by the previous query',
2136 'badcontinue' );
2137 }
2138 }
2139
2140 /**
2141 * Return the error message related to a certain array
2142 * @param array $error Element of a getUserPermissionsErrors()-style array
2143 * @return array('code' => code, 'info' => info)
2144 */
2145 public function parseMsg( $error ) {
2146 $error = (array)$error; // It seems strings sometimes make their way in here
2147 $key = array_shift( $error );
2148
2149 // Check whether the error array was nested
2150 // array( array( <code>, <params> ), array( <another_code>, <params> ) )
2151 if ( is_array( $key ) ) {
2152 $error = $key;
2153 $key = array_shift( $error );
2154 }
2155
2156 if ( $key instanceof IApiMessage ) {
2157 return array(
2158 'code' => $key->getApiCode(),
2159 'info' => $key->inLanguage( 'en' )->useDatabase( false )->text(),
2160 'data' => $key->getApiData()
2161 );
2162 }
2163
2164 if ( isset( self::$messageMap[$key] ) ) {
2165 return array(
2166 'code' => wfMsgReplaceArgs( self::$messageMap[$key]['code'], $error ),
2167 'info' => wfMsgReplaceArgs( self::$messageMap[$key]['info'], $error )
2168 );
2169 }
2170
2171 // If the key isn't present, throw an "unknown error"
2172 return $this->parseMsg( array( 'unknownerror', $key ) );
2173 }
2174
2175 /**
2176 * Internal code errors should be reported with this method
2177 * @param string $method Method or function name
2178 * @param string $message Error message
2179 * @throws MWException always
2180 */
2181 protected static function dieDebug( $method, $message ) {
2182 throw new MWException( "Internal error in $method: $message" );
2183 }
2184
2185 /**
2186 * Write logging information for API features to a debug log, for usage
2187 * analysis.
2188 * @param string $feature Feature being used.
2189 */
2190 protected function logFeatureUsage( $feature ) {
2191 $request = $this->getRequest();
2192 $s = '"' . addslashes( $feature ) . '"' .
2193 ' "' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) . '"' .
2194 ' "' . $request->getIP() . '"' .
2195 ' "' . addslashes( $request->getHeader( 'Referer' ) ) . '"' .
2196 ' "' . addslashes( $this->getMain()->getUserAgent() ) . '"';
2197 wfDebugLog( 'api-feature-usage', $s, 'private' );
2198 }
2199
2200 /**@}*/
2201
2202 /************************************************************************//**
2203 * @name Help message generation
2204 * @{
2205 */
2206
2207 /**
2208 * Return the description message.
2209 *
2210 * @return string|array|Message
2211 */
2212 protected function getDescriptionMessage() {
2213 return "apihelp-{$this->getModulePath()}-description";
2214 }
2215
2216 /**
2217 * Get final module description, after hooks have had a chance to tweak it as
2218 * needed.
2219 *
2220 * @since 1.25, returns Message[] rather than string[]
2221 * @return Message[]
2222 */
2223 public function getFinalDescription() {
2224 $desc = $this->getDescription();
2225 Hooks::run( 'APIGetDescription', array( &$this, &$desc ) );
2226 $desc = self::escapeWikiText( $desc );
2227 if ( is_array( $desc ) ) {
2228 $desc = join( "\n", $desc );
2229 } else {
2230 $desc = (string)$desc;
2231 }
2232
2233 $msg = ApiBase::makeMessage( $this->getDescriptionMessage(), $this->getContext(), array(
2234 $this->getModulePrefix(),
2235 $this->getModuleName(),
2236 $this->getModulePath(),
2237 ) );
2238 if ( !$msg->exists() ) {
2239 $msg = $this->msg( 'api-help-fallback-description', $desc );
2240 }
2241 $msgs = array( $msg );
2242
2243 Hooks::run( 'APIGetDescriptionMessages', array( $this, &$msgs ) );
2244
2245 return $msgs;
2246 }
2247
2248 /**
2249 * Get final list of parameters, after hooks have had a chance to
2250 * tweak it as needed.
2251 *
2252 * @param int $flags Zero or more flags like GET_VALUES_FOR_HELP
2253 * @return array|bool False on no parameters
2254 * @since 1.21 $flags param added
2255 */
2256 public function getFinalParams( $flags = 0 ) {
2257 $params = $this->getAllowedParams( $flags );
2258 if ( !$params ) {
2259 $params = array();
2260 }
2261
2262 if ( $this->needsToken() ) {
2263 $params['token'] = array(
2264 ApiBase::PARAM_TYPE => 'string',
2265 ApiBase::PARAM_REQUIRED => true,
2266 ApiBase::PARAM_HELP_MSG => array(
2267 'api-help-param-token',
2268 $this->needsToken(),
2269 ),
2270 ) + ( isset( $params['token'] ) ? $params['token'] : array() );
2271 }
2272
2273 Hooks::run( 'APIGetAllowedParams', array( &$this, &$params, $flags ) );
2274
2275 return $params;
2276 }
2277
2278 /**
2279 * Get final parameter descriptions, after hooks have had a chance to tweak it as
2280 * needed.
2281 *
2282 * @since 1.25, returns array of Message[] rather than array of string[]
2283 * @return array Keys are parameter names, values are arrays of Message objects
2284 */
2285 public function getFinalParamDescription() {
2286 $prefix = $this->getModulePrefix();
2287 $name = $this->getModuleName();
2288 $path = $this->getModulePath();
2289
2290 $desc = $this->getParamDescription();
2291 Hooks::run( 'APIGetParamDescription', array( &$this, &$desc ) );
2292
2293 if ( !$desc ) {
2294 $desc = array();
2295 }
2296 $desc = self::escapeWikiText( $desc );
2297
2298 $params = $this->getFinalParams( ApiBase::GET_VALUES_FOR_HELP );
2299 $msgs = array();
2300 foreach ( $params as $param => $settings ) {
2301 if ( !is_array( $settings ) ) {
2302 $settings = array();
2303 }
2304
2305 $d = isset( $desc[$param] ) ? $desc[$param] : '';
2306 if ( is_array( $d ) ) {
2307 // Special handling for prop parameters
2308 $d = array_map( function ( $line ) {
2309 if ( preg_match( '/^\s+(\S+)\s+-\s+(.+)$/', $line, $m ) ) {
2310 $line = "\n;{$m[1]}:{$m[2]}";
2311 }
2312 return $line;
2313 }, $d );
2314 $d = join( ' ', $d );
2315 }
2316
2317 if ( isset( $settings[ApiBase::PARAM_HELP_MSG] ) ) {
2318 $msg = $settings[ApiBase::PARAM_HELP_MSG];
2319 } else {
2320 $msg = $this->msg( "apihelp-{$path}-param-{$param}" );
2321 if ( !$msg->exists() ) {
2322 $msg = $this->msg( 'api-help-fallback-parameter', $d );
2323 }
2324 }
2325 $msg = ApiBase::makeMessage( $msg, $this->getContext(),
2326 array( $prefix, $param, $name, $path ) );
2327 if ( !$msg ) {
2328 $this->dieDebug( __METHOD__,
2329 'Value in ApiBase::PARAM_HELP_MSG is not valid' );
2330 }
2331 $msgs[$param] = array( $msg );
2332
2333 if ( isset( $settings[ApiBase::PARAM_HELP_MSG_PER_VALUE] ) ) {
2334 if ( !is_array( $settings[ApiBase::PARAM_HELP_MSG_PER_VALUE] ) ) {
2335 $this->dieDebug( __METHOD__,
2336 'ApiBase::PARAM_HELP_MSG_PER_VALUE is not valid' );
2337 }
2338 if ( !is_array( $settings[ApiBase::PARAM_TYPE] ) ) {
2339 $this->dieDebug( __METHOD__,
2340 'ApiBase::PARAM_HELP_MSG_PER_VALUE may only be used when ' .
2341 'ApiBase::PARAM_TYPE is an array' );
2342 }
2343
2344 $valueMsgs = $settings[ApiBase::PARAM_HELP_MSG_PER_VALUE];
2345 foreach ( $settings[ApiBase::PARAM_TYPE] as $value ) {
2346 if ( isset( $valueMsgs[$value] ) ) {
2347 $msg = $valueMsgs[$value];
2348 } else {
2349 $msg = "apihelp-{$path}-paramvalue-{$param}-{$value}";
2350 }
2351 $m = ApiBase::makeMessage( $msg, $this->getContext(),
2352 array( $prefix, $param, $name, $path, $value ) );
2353 if ( $m ) {
2354 $m = new ApiHelpParamValueMessage(
2355 $value,
2356 array( $m->getKey(), 'api-help-param-no-description' ),
2357 $m->getParams()
2358 );
2359 $msgs[$param][] = $m->setContext( $this->getContext() );
2360 } else {
2361 $this->dieDebug( __METHOD__,
2362 "Value in ApiBase::PARAM_HELP_MSG_PER_VALUE for $value is not valid" );
2363 }
2364 }
2365 }
2366
2367 if ( isset( $settings[ApiBase::PARAM_HELP_MSG_APPEND] ) ) {
2368 if ( !is_array( $settings[ApiBase::PARAM_HELP_MSG_APPEND] ) ) {
2369 $this->dieDebug( __METHOD__,
2370 'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
2371 }
2372 foreach ( $settings[ApiBase::PARAM_HELP_MSG_APPEND] as $m ) {
2373 $m = ApiBase::makeMessage( $m, $this->getContext(),
2374 array( $prefix, $param, $name, $path ) );
2375 if ( $m ) {
2376 $msgs[$param][] = $m;
2377 } else {
2378 $this->dieDebug( __METHOD__,
2379 'Value in ApiBase::PARAM_HELP_MSG_APPEND is not valid' );
2380 }
2381 }
2382 }
2383 }
2384
2385 Hooks::run( 'APIGetParamDescriptionMessages', array( $this, &$msgs ) );
2386
2387 return $msgs;
2388 }
2389
2390 /**
2391 * Generates the list of flags for the help screen and for action=paraminfo
2392 *
2393 * Corresponding messages: api-help-flag-deprecated,
2394 * api-help-flag-internal, api-help-flag-readrights,
2395 * api-help-flag-writerights, api-help-flag-mustbeposted
2396 *
2397 * @return string[]
2398 */
2399 protected function getHelpFlags() {
2400 $flags = array();
2401
2402 if ( $this->isDeprecated() ) {
2403 $flags[] = 'deprecated';
2404 }
2405 if ( $this->isInternal() ) {
2406 $flags[] = 'internal';
2407 }
2408 if ( $this->isReadMode() ) {
2409 $flags[] = 'readrights';
2410 }
2411 if ( $this->isWriteMode() ) {
2412 $flags[] = 'writerights';
2413 }
2414 if ( $this->mustBePosted() ) {
2415 $flags[] = 'mustbeposted';
2416 }
2417
2418 return $flags;
2419 }
2420
2421 /**
2422 * Returns information about the source of this module, if known
2423 *
2424 * Returned array is an array with the following keys:
2425 * - path: Install path
2426 * - name: Extension name, or "MediaWiki" for core
2427 * - namemsg: (optional) i18n message key for a display name
2428 * - license-name: (optional) Name of license
2429 *
2430 * @return array|null
2431 */
2432 protected function getModuleSourceInfo() {
2433 global $IP;
2434
2435 if ( $this->mModuleSource !== false ) {
2436 return $this->mModuleSource;
2437 }
2438
2439 // First, try to find where the module comes from...
2440 $rClass = new ReflectionClass( $this );
2441 $path = $rClass->getFileName();
2442 if ( !$path ) {
2443 // No path known?
2444 $this->mModuleSource = null;
2445 return null;
2446 }
2447 $path = realpath( $path ) ?: $path;
2448
2449 // Build map of extension directories to extension info
2450 if ( self::$extensionInfo === null ) {
2451 self::$extensionInfo = array(
2452 realpath( __DIR__ ) ?: __DIR__ => array(
2453 'path' => $IP,
2454 'name' => 'MediaWiki',
2455 'license-name' => 'GPL-2.0+',
2456 ),
2457 realpath( "$IP/extensions" ) ?: "$IP/extensions" => null,
2458 );
2459 $keep = array(
2460 'path' => null,
2461 'name' => null,
2462 'namemsg' => null,
2463 'license-name' => null,
2464 );
2465 foreach ( $this->getConfig()->get( 'ExtensionCredits' ) as $group ) {
2466 foreach ( $group as $ext ) {
2467 if ( !isset( $ext['path'] ) || !isset( $ext['name'] ) ) {
2468 // This shouldn't happen, but does anyway.
2469 continue;
2470 }
2471
2472 $extpath = $ext['path'];
2473 if ( !is_dir( $extpath ) ) {
2474 $extpath = dirname( $extpath );
2475 }
2476 self::$extensionInfo[realpath( $extpath ) ?: $extpath] =
2477 array_intersect_key( $ext, $keep );
2478 }
2479 }
2480 foreach ( ExtensionRegistry::getInstance()->getAllThings() as $ext ) {
2481 $extpath = $ext['path'];
2482 if ( !is_dir( $extpath ) ) {
2483 $extpath = dirname( $extpath );
2484 }
2485 self::$extensionInfo[realpath( $extpath ) ?: $extpath] =
2486 array_intersect_key( $ext, $keep );
2487 }
2488 }
2489
2490 // Now traverse parent directories until we find a match or run out of
2491 // parents.
2492 do {
2493 if ( array_key_exists( $path, self::$extensionInfo ) ) {
2494 // Found it!
2495 $this->mModuleSource = self::$extensionInfo[$path];
2496 return $this->mModuleSource;
2497 }
2498
2499 $oldpath = $path;
2500 $path = dirname( $path );
2501 } while ( $path !== $oldpath );
2502
2503 // No idea what extension this might be.
2504 $this->mModuleSource = null;
2505 return null;
2506 }
2507
2508 /**
2509 * Called from ApiHelp before the pieces are joined together and returned.
2510 *
2511 * This exists mainly for ApiMain to add the Permissions and Credits
2512 * sections. Other modules probably don't need it.
2513 *
2514 * @param string[] &$help Array of help data
2515 * @param array $options Options passed to ApiHelp::getHelp
2516 * @param array &$tocData If a TOC is being generated, this array has keys
2517 * as anchors in the page and values as for Linker::generateTOC().
2518 */
2519 public function modifyHelp( array &$help, array $options, array &$tocData ) {
2520 }
2521
2522 /**@}*/
2523
2524 /************************************************************************//**
2525 * @name Deprecated
2526 * @{
2527 */
2528
2529 /// @deprecated since 1.24
2530 const PROP_ROOT = 'ROOT';
2531 /// @deprecated since 1.24
2532 const PROP_LIST = 'LIST';
2533 /// @deprecated since 1.24
2534 const PROP_TYPE = 0;
2535 /// @deprecated since 1.24
2536 const PROP_NULLABLE = 1;
2537
2538 /**
2539 * Formerly returned a string that identifies the version of the extending
2540 * class. Typically included the class name, the svn revision, timestamp,
2541 * and last author. Usually done with SVN's Id keyword
2542 *
2543 * @deprecated since 1.21, version string is no longer supported
2544 * @return string
2545 */
2546 public function getVersion() {
2547 wfDeprecated( __METHOD__, '1.21' );
2548 return '';
2549 }
2550
2551 /**
2552 * Formerly used to fetch a list of possible properites in the result,
2553 * somehow organized with respect to the prop parameter that causes them to
2554 * be returned. The specific semantics of the return value was never
2555 * specified. Since this was never possible to be accurately updated, it
2556 * has been removed.
2557 *
2558 * @deprecated since 1.24
2559 * @return array|bool
2560 */
2561 protected function getResultProperties() {
2562 wfDeprecated( __METHOD__, '1.24' );
2563 return false;
2564 }
2565
2566 /**
2567 * @see self::getResultProperties()
2568 * @deprecated since 1.24
2569 * @return array|bool
2570 */
2571 public function getFinalResultProperties() {
2572 wfDeprecated( __METHOD__, '1.24' );
2573 return array();
2574 }
2575
2576 /**
2577 * @see self::getResultProperties()
2578 * @deprecated since 1.24
2579 */
2580 protected static function addTokenProperties( &$props, $tokenFunctions ) {
2581 wfDeprecated( __METHOD__, '1.24' );
2582 }
2583
2584 /**
2585 * @see self::getPossibleErrors()
2586 * @deprecated since 1.24
2587 * @return array
2588 */
2589 public function getRequireOnlyOneParameterErrorMessages( $params ) {
2590 wfDeprecated( __METHOD__, '1.24' );
2591 return array();
2592 }
2593
2594 /**
2595 * @see self::getPossibleErrors()
2596 * @deprecated since 1.24
2597 * @return array
2598 */
2599 public function getRequireMaxOneParameterErrorMessages( $params ) {
2600 wfDeprecated( __METHOD__, '1.24' );
2601 return array();
2602 }
2603
2604 /**
2605 * @see self::getPossibleErrors()
2606 * @deprecated since 1.24
2607 * @return array
2608 */
2609 public function getRequireAtLeastOneParameterErrorMessages( $params ) {
2610 wfDeprecated( __METHOD__, '1.24' );
2611 return array();
2612 }
2613
2614 /**
2615 * @see self::getPossibleErrors()
2616 * @deprecated since 1.24
2617 * @return array
2618 */
2619 public function getTitleOrPageIdErrorMessage() {
2620 wfDeprecated( __METHOD__, '1.24' );
2621 return array();
2622 }
2623
2624 /**
2625 * This formerly attempted to return a list of all possible errors returned
2626 * by the module. However, this was impossible to maintain in many cases
2627 * since errors could come from other areas of MediaWiki and in some cases
2628 * from arbitrary extension hooks. Since a partial list claiming to be
2629 * comprehensive is unlikely to be useful, it was removed.
2630 *
2631 * @deprecated since 1.24
2632 * @return array
2633 */
2634 public function getPossibleErrors() {
2635 wfDeprecated( __METHOD__, '1.24' );
2636 return array();
2637 }
2638
2639 /**
2640 * @see self::getPossibleErrors()
2641 * @deprecated since 1.24
2642 * @return array
2643 */
2644 public function getFinalPossibleErrors() {
2645 wfDeprecated( __METHOD__, '1.24' );
2646 return array();
2647 }
2648
2649 /**
2650 * @see self::getPossibleErrors()
2651 * @deprecated since 1.24
2652 * @return array
2653 */
2654 public function parseErrors( $errors ) {
2655 wfDeprecated( __METHOD__, '1.24' );
2656 return array();
2657 }
2658
2659 /**
2660 * Returns the description string for this module
2661 *
2662 * Ignored if an i18n message exists for
2663 * "apihelp-{$this->getModulePath()}-description".
2664 *
2665 * @deprecated since 1.25
2666 * @return Message|string|array
2667 */
2668 protected function getDescription() {
2669 return false;
2670 }
2671
2672 /**
2673 * Returns an array of parameter descriptions.
2674 *
2675 * For each parameter, ignored if an i18n message exists for the parameter.
2676 * By default that message is
2677 * "apihelp-{$this->getModulePath()}-param-{$param}", but it may be
2678 * overridden using ApiBase::PARAM_HELP_MSG in the data returned by
2679 * self::getFinalParams().
2680 *
2681 * @deprecated since 1.25
2682 * @return array|bool False on no parameter descriptions
2683 */
2684 protected function getParamDescription() {
2685 return array();
2686 }
2687
2688 /**
2689 * Returns usage examples for this module.
2690 *
2691 * Return value as an array is either:
2692 * - numeric keys with partial URLs ("api.php?" plus a query string) as
2693 * values
2694 * - sequential numeric keys with even-numbered keys being display-text
2695 * and odd-numbered keys being partial urls
2696 * - partial URLs as keys with display-text (string or array-to-be-joined)
2697 * as values
2698 * Return value as a string is the same as an array with a numeric key and
2699 * that value, and boolean false means "no examples".
2700 *
2701 * @deprecated since 1.25, use getExamplesMessages() instead
2702 * @return bool|string|array
2703 */
2704 protected function getExamples() {
2705 return false;
2706 }
2707
2708 /**
2709 * Generates help message for this module, or false if there is no description
2710 * @deprecated since 1.25
2711 * @return string|bool
2712 */
2713 public function makeHelpMsg() {
2714 wfDeprecated( __METHOD__, '1.25' );
2715 static $lnPrfx = "\n ";
2716
2717 $msg = $this->getFinalDescription();
2718
2719 if ( $msg !== false ) {
2720
2721 if ( !is_array( $msg ) ) {
2722 $msg = array(
2723 $msg
2724 );
2725 }
2726 $msg = $lnPrfx . implode( $lnPrfx, $msg ) . "\n";
2727
2728 $msg .= $this->makeHelpArrayToString( $lnPrfx, false, $this->getHelpUrls() );
2729
2730 if ( $this->isReadMode() ) {
2731 $msg .= "\nThis module requires read rights";
2732 }
2733 if ( $this->isWriteMode() ) {
2734 $msg .= "\nThis module requires write rights";
2735 }
2736 if ( $this->mustBePosted() ) {
2737 $msg .= "\nThis module only accepts POST requests";
2738 }
2739 if ( $this->isReadMode() || $this->isWriteMode() ||
2740 $this->mustBePosted()
2741 ) {
2742 $msg .= "\n";
2743 }
2744
2745 // Parameters
2746 $paramsMsg = $this->makeHelpMsgParameters();
2747 if ( $paramsMsg !== false ) {
2748 $msg .= "Parameters:\n$paramsMsg";
2749 }
2750
2751 $examples = $this->getExamples();
2752 if ( $examples ) {
2753 if ( !is_array( $examples ) ) {
2754 $examples = array(
2755 $examples
2756 );
2757 }
2758 $msg .= "Example" . ( count( $examples ) > 1 ? 's' : '' ) . ":\n";
2759 foreach ( $examples as $k => $v ) {
2760 if ( is_numeric( $k ) ) {
2761 $msg .= " $v\n";
2762 } else {
2763 if ( is_array( $v ) ) {
2764 $msgExample = implode( "\n", array_map( array( $this, 'indentExampleText' ), $v ) );
2765 } else {
2766 $msgExample = " $v";
2767 }
2768 $msgExample .= ":";
2769 $msg .= wordwrap( $msgExample, 100, "\n" ) . "\n $k\n";
2770 }
2771 }
2772 }
2773 }
2774
2775 return $msg;
2776 }
2777
2778 /**
2779 * @deprecated since 1.25
2780 * @param string $item
2781 * @return string
2782 */
2783 private function indentExampleText( $item ) {
2784 return " " . $item;
2785 }
2786
2787 /**
2788 * @deprecated since 1.25
2789 * @param string $prefix Text to split output items
2790 * @param string $title What is being output
2791 * @param string|array $input
2792 * @return string
2793 */
2794 protected function makeHelpArrayToString( $prefix, $title, $input ) {
2795 wfDeprecated( __METHOD__, '1.25' );
2796 if ( $input === false ) {
2797 return '';
2798 }
2799 if ( !is_array( $input ) ) {
2800 $input = array( $input );
2801 }
2802
2803 if ( count( $input ) > 0 ) {
2804 if ( $title ) {
2805 $msg = $title . ( count( $input ) > 1 ? 's' : '' ) . ":\n ";
2806 } else {
2807 $msg = ' ';
2808 }
2809 $msg .= implode( $prefix, $input ) . "\n";
2810
2811 return $msg;
2812 }
2813
2814 return '';
2815 }
2816
2817 /**
2818 * Generates the parameter descriptions for this module, to be displayed in the
2819 * module's help.
2820 * @deprecated since 1.25
2821 * @return string|bool
2822 */
2823 public function makeHelpMsgParameters() {
2824 wfDeprecated( __METHOD__, '1.25' );
2825 $params = $this->getFinalParams( ApiBase::GET_VALUES_FOR_HELP );
2826 if ( $params ) {
2827 $paramsDescription = $this->getFinalParamDescription();
2828 $msg = '';
2829 $paramPrefix = "\n" . str_repeat( ' ', 24 );
2830 $descWordwrap = "\n" . str_repeat( ' ', 28 );
2831 foreach ( $params as $paramName => $paramSettings ) {
2832 $desc = isset( $paramsDescription[$paramName] ) ? $paramsDescription[$paramName] : '';
2833 if ( is_array( $desc ) ) {
2834 $desc = implode( $paramPrefix, $desc );
2835 }
2836
2837 // handle shorthand
2838 if ( !is_array( $paramSettings ) ) {
2839 $paramSettings = array(
2840 self::PARAM_DFLT => $paramSettings,
2841 );
2842 }
2843
2844 // handle missing type
2845 if ( !isset( $paramSettings[ApiBase::PARAM_TYPE] ) ) {
2846 $dflt = isset( $paramSettings[ApiBase::PARAM_DFLT] )
2847 ? $paramSettings[ApiBase::PARAM_DFLT]
2848 : null;
2849 if ( is_bool( $dflt ) ) {
2850 $paramSettings[ApiBase::PARAM_TYPE] = 'boolean';
2851 } elseif ( is_string( $dflt ) || is_null( $dflt ) ) {
2852 $paramSettings[ApiBase::PARAM_TYPE] = 'string';
2853 } elseif ( is_int( $dflt ) ) {
2854 $paramSettings[ApiBase::PARAM_TYPE] = 'integer';
2855 }
2856 }
2857
2858 if ( isset( $paramSettings[self::PARAM_DEPRECATED] )
2859 && $paramSettings[self::PARAM_DEPRECATED]
2860 ) {
2861 $desc = "DEPRECATED! $desc";
2862 }
2863
2864 if ( isset( $paramSettings[self::PARAM_REQUIRED] )
2865 && $paramSettings[self::PARAM_REQUIRED]
2866 ) {
2867 $desc .= $paramPrefix . "This parameter is required";
2868 }
2869
2870 $type = isset( $paramSettings[self::PARAM_TYPE] )
2871 ? $paramSettings[self::PARAM_TYPE]
2872 : null;
2873 if ( isset( $type ) ) {
2874 $hintPipeSeparated = true;
2875 $multi = isset( $paramSettings[self::PARAM_ISMULTI] )
2876 ? $paramSettings[self::PARAM_ISMULTI]
2877 : false;
2878 if ( $multi ) {
2879 $prompt = 'Values (separate with \'|\'): ';
2880 } else {
2881 $prompt = 'One value: ';
2882 }
2883
2884 if ( $type === 'submodule' ) {
2885 if ( isset( $paramSettings[self::PARAM_SUBMODULE_MAP] ) ) {
2886 $type = array_keys( $paramSettings[self::PARAM_SUBMODULE_MAP] );
2887 } else {
2888 $type = $this->getModuleManager()->getNames( $paramName );
2889 }
2890 sort( $type );
2891 }
2892 if ( is_array( $type ) ) {
2893 $choices = array();
2894 $nothingPrompt = '';
2895 foreach ( $type as $t ) {
2896 if ( $t === '' ) {
2897 $nothingPrompt = 'Can be empty, or ';
2898 } else {
2899 $choices[] = $t;
2900 }
2901 }
2902 $desc .= $paramPrefix . $nothingPrompt . $prompt;
2903 $choicesstring = implode( ', ', $choices );
2904 $desc .= wordwrap( $choicesstring, 100, $descWordwrap );
2905 $hintPipeSeparated = false;
2906 } else {
2907 switch ( $type ) {
2908 case 'namespace':
2909 // Special handling because namespaces are
2910 // type-limited, yet they are not given
2911 $desc .= $paramPrefix . $prompt;
2912 $desc .= wordwrap( implode( ', ', MWNamespace::getValidNamespaces() ),
2913 100, $descWordwrap );
2914 $hintPipeSeparated = false;
2915 break;
2916 case 'limit':
2917 $desc .= $paramPrefix . "No more than {$paramSettings[self::PARAM_MAX]}";
2918 if ( isset( $paramSettings[self::PARAM_MAX2] ) ) {
2919 $desc .= " ({$paramSettings[self::PARAM_MAX2]} for bots)";
2920 }
2921 $desc .= ' allowed';
2922 break;
2923 case 'integer':
2924 $s = $multi ? 's' : '';
2925 $hasMin = isset( $paramSettings[self::PARAM_MIN] );
2926 $hasMax = isset( $paramSettings[self::PARAM_MAX] );
2927 if ( $hasMin || $hasMax ) {
2928 if ( !$hasMax ) {
2929 $intRangeStr = "The value$s must be no less than " .
2930 "{$paramSettings[self::PARAM_MIN]}";
2931 } elseif ( !$hasMin ) {
2932 $intRangeStr = "The value$s must be no more than " .
2933 "{$paramSettings[self::PARAM_MAX]}";
2934 } else {
2935 $intRangeStr = "The value$s must be between " .
2936 "{$paramSettings[self::PARAM_MIN]} and {$paramSettings[self::PARAM_MAX]}";
2937 }
2938
2939 $desc .= $paramPrefix . $intRangeStr;
2940 }
2941 break;
2942 case 'upload':
2943 $desc .= $paramPrefix . "Must be posted as a file upload using multipart/form-data";
2944 break;
2945 }
2946 }
2947
2948 if ( $multi ) {
2949 if ( $hintPipeSeparated ) {
2950 $desc .= $paramPrefix . "Separate values with '|'";
2951 }
2952
2953 $isArray = is_array( $type );
2954 if ( !$isArray
2955 || $isArray && count( $type ) > self::LIMIT_SML1
2956 ) {
2957 $desc .= $paramPrefix . "Maximum number of values " .
2958 self::LIMIT_SML1 . " (" . self::LIMIT_SML2 . " for bots)";
2959 }
2960 }
2961 }
2962
2963 $default = isset( $paramSettings[self::PARAM_DFLT] ) ? $paramSettings[self::PARAM_DFLT] : null;
2964 if ( !is_null( $default ) && $default !== false ) {
2965 $desc .= $paramPrefix . "Default: $default";
2966 }
2967
2968 $msg .= sprintf( " %-19s - %s\n", $this->encodeParamName( $paramName ), $desc );
2969 }
2970
2971 return $msg;
2972 }
2973
2974 return false;
2975 }
2976
2977 /**
2978 * @deprecated since 1.25, always returns empty string
2979 * @param IDatabase|bool $db
2980 * @return string
2981 */
2982 public function getModuleProfileName( $db = false ) {
2983 wfDeprecated( __METHOD__, '1.25' );
2984 return '';
2985 }
2986
2987 /**
2988 * @deprecated since 1.25
2989 */
2990 public function profileIn() {
2991 // No wfDeprecated() yet because extensions call this and might need to
2992 // keep doing so for BC.
2993 }
2994
2995 /**
2996 * @deprecated since 1.25
2997 */
2998 public function profileOut() {
2999 // No wfDeprecated() yet because extensions call this and might need to
3000 // keep doing so for BC.
3001 }
3002
3003 /**
3004 * @deprecated since 1.25
3005 */
3006 public function safeProfileOut() {
3007 wfDeprecated( __METHOD__, '1.25' );
3008 }
3009
3010 /**
3011 * @deprecated since 1.25, always returns 0
3012 * @return float
3013 */
3014 public function getProfileTime() {
3015 wfDeprecated( __METHOD__, '1.25' );
3016 return 0;
3017 }
3018
3019 /**
3020 * @deprecated since 1.25
3021 */
3022 public function profileDBIn() {
3023 wfDeprecated( __METHOD__, '1.25' );
3024 }
3025
3026 /**
3027 * @deprecated since 1.25
3028 */
3029 public function profileDBOut() {
3030 wfDeprecated( __METHOD__, '1.25' );
3031 }
3032
3033 /**
3034 * @deprecated since 1.25, always returns 0
3035 * @return float
3036 */
3037 public function getProfileDBTime() {
3038 wfDeprecated( __METHOD__, '1.25' );
3039 return 0;
3040 }
3041
3042 /**
3043 * Get the result data array (read-only)
3044 * @deprecated since 1.25, use $this->getResult() methods instead
3045 * @return array
3046 */
3047 public function getResultData() {
3048 wfDeprecated( __METHOD__, '1.25' );
3049 return $this->getResult()->getData();
3050 }
3051
3052 /**
3053 * Call wfTransactionalTimeLimit() if this request was POSTed
3054 * @since 1.26
3055 */
3056 protected function useTransactionalTimeLimit() {
3057 if ( $this->getRequest()->wasPosted() ) {
3058 wfTransactionalTimeLimit();
3059 }
3060 }
3061
3062 /**@}*/
3063 }
3064
3065 /**
3066 * For really cool vim folding this needs to be at the end:
3067 * vim: foldmarker=@{,@} foldmethod=marker
3068 */