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