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