3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
22 * This class represents the result of the API operations.
23 * It simply wraps a nested array() structure, adding some functions to simplify
24 * array's modifications. As various modules execute, they add different pieces
25 * of information to this result, structuring it as it will be given to the client.
27 * Each subarray may either be a dictionary - key-value pairs with unique keys,
28 * or lists, where the items are added using $data[] = $value notation.
30 * @since 1.25 this is no longer a subclass of ApiBase
33 class ApiResult
implements ApiSerializable
{
36 * Override existing value in addValue(), setValue(), and similar functions
42 * For addValue(), setValue() and similar functions, if the value does not
43 * exist, add it as the first element. In case the new value has no name
44 * (numerical index), all indexes will be renumbered.
50 * For addValue() and similar functions, do not check size while adding a value
51 * Don't use this unless you REALLY know what you're doing.
52 * Values added while the size checking was disabled will never be counted.
53 * Ignored for setValue() and similar functions.
56 const NO_SIZE_CHECK
= 4;
59 * For addValue(), setValue() and similar functions, do not validate data.
60 * Also disables size checking. If you think you need to use this, you're
64 const NO_VALIDATE
= 12;
67 * Key for the 'indexed tag name' metadata item. Value is string.
70 const META_INDEXED_TAG_NAME
= '_element';
73 * Key for the 'subelements' metadata item. Value is string[].
76 const META_SUBELEMENTS
= '_subelements';
79 * Key for the 'preserve keys' metadata item. Value is string[].
82 const META_PRESERVE_KEYS
= '_preservekeys';
85 * Key for the 'content' metadata item. Value is string.
88 const META_CONTENT
= '_content';
91 * Key for the 'type' metadata item. Value is one of the following strings:
92 * - default: Like 'array' if all (non-metadata) keys are numeric with no
93 * gaps, otherwise like 'assoc'.
94 * - array: Keys are used for ordering, but are not output. In a format
95 * like JSON, outputs as [].
96 * - assoc: In a format like JSON, outputs as {}.
97 * - kvp: For a format like XML where object keys have a restricted
98 * character set, use an alternative output format. For example,
99 * <container><item name="key">value</item></container> rather than
100 * <container key="value" />
101 * - BCarray: Like 'array' normally, 'default' in backwards-compatibility mode.
102 * - BCassoc: Like 'assoc' normally, 'default' in backwards-compatibility mode.
103 * - BCkvp: Like 'kvp' normally. In backwards-compatibility mode, forces
104 * the alternative output format for all formats, for example
105 * [{"name":key,"*":value}] in JSON. META_KVP_KEY_NAME must also be set.
108 const META_TYPE
= '_type';
111 * Key for the metadata item whose value specifies the name used for the
112 * kvp key in the alternative output format with META_TYPE 'kvp' or
113 * 'BCkvp', i.e. the "name" in <container><item name="key">value</item></container>.
117 const META_KVP_KEY_NAME
= '_kvpkeyname';
120 * Key for the metadata item that indicates that the KVP key should be
121 * added into an assoc value, i.e. {"key":{"val1":"a","val2":"b"}}
122 * transforms to {"name":"key","val1":"a","val2":"b"} rather than
123 * {"name":"key","value":{"val1":"a","val2":"b"}}.
127 const META_KVP_MERGE
= '_kvpmerge';
130 * Key for the 'BC bools' metadata item. Value is string[].
131 * Note no setter is provided.
134 const META_BC_BOOLS
= '_BC_bools';
137 * Key for the 'BC subelements' metadata item. Value is string[].
138 * Note no setter is provided.
141 const META_BC_SUBELEMENTS
= '_BC_subelements';
143 private $data, $size, $maxSize;
144 private $errorFormatter;
147 private $checkingSize, $mainForContinuation;
150 * @param int|bool $maxSize Maximum result "size", or false for no limit
151 * @since 1.25 Takes an integer|bool rather than an ApiMain
153 public function __construct( $maxSize ) {
154 if ( $maxSize instanceof ApiMain
) {
155 wfDeprecated( 'ApiMain to ' . __METHOD__
, '1.25' );
156 $this->errorFormatter
= $maxSize->getErrorFormatter();
157 $this->mainForContinuation
= $maxSize;
158 $maxSize = $maxSize->getConfig()->get( 'APIMaxResultSize' );
161 $this->maxSize
= $maxSize;
162 $this->checkingSize
= true;
167 * Set the error formatter
169 * @param ApiErrorFormatter $formatter
171 public function setErrorFormatter( ApiErrorFormatter
$formatter ) {
172 $this->errorFormatter
= $formatter;
176 * Allow for adding one ApiResult into another
180 public function serializeForApiResult() {
184 /************************************************************************//**
190 * Clear the current result data.
192 public function reset() {
194 self
::META_TYPE
=> 'assoc', // Usually what's desired
200 * Get the result data array
202 * The returned value should be considered read-only.
204 * Transformations include:
206 * Custom: (callable) Applied before other transformations. Signature is
207 * function ( &$data, &$metadata ), return value is ignored. Called for
210 * BC: (array) This transformation does various adjustments to bring the
211 * output in line with the pre-1.25 result format. The value array is a
212 * list of flags: 'nobool', 'no*', 'nosub'.
213 * - Boolean-valued items are changed to '' if true or removed if false,
214 * unless listed in META_BC_BOOLS. This may be skipped by including
215 * 'nobool' in the value array.
216 * - The tag named by META_CONTENT is renamed to '*', and META_CONTENT is
217 * set to '*'. This may be skipped by including 'no*' in the value
219 * - Tags listed in META_BC_SUBELEMENTS will have their values changed to
220 * array( '*' => $value ). This may be skipped by including 'nosub' in
222 * - If META_TYPE is 'BCarray', set it to 'default'
223 * - If META_TYPE is 'BCassoc', set it to 'default'
224 * - If META_TYPE is 'BCkvp', perform the transformation (even if
225 * the Types transformation is not being applied).
227 * Types: (assoc) Apply transformations based on META_TYPE. The values
228 * array is an associative array with the following possible keys:
229 * - AssocAsObject: (bool) If true, return arrays with META_TYPE 'assoc'
231 * - ArmorKVP: (string) If provided, transform arrays with META_TYPE 'kvp'
232 * and 'BCkvp' into arrays of two-element arrays, something like this:
234 * foreach ( $input as $key => $value ) {
236 * $pair[$META_KVP_KEY_NAME ?: $ArmorKVP_value] = $key;
237 * ApiResult::setContentValue( $pair, 'value', $value );
241 * Strip: (string) Strips metadata keys from the result.
242 * - 'all': Strip all metadata, recursively
243 * - 'base': Strip metadata at the top-level only.
244 * - 'none': Do not strip metadata.
245 * - 'bc': Like 'all', but leave certain pre-1.25 keys.
248 * @param array|string|null $path Path to fetch, see ApiResult::addValue
249 * @param array $transforms See above
250 * @return mixed Result data, or null if not found
252 public function getResultData( $path = array(), $transforms = array() ) {
253 $path = (array)$path;
255 return self
::applyTransformations( $this->data
, $transforms );
258 $last = array_pop( $path );
259 $ret = &$this->path( $path, 'dummy' );
260 if ( !isset( $ret[$last] ) ) {
262 } elseif ( is_array( $ret[$last] ) ) {
263 return self
::applyTransformations( $ret[$last], $transforms );
270 * Get the size of the result, i.e. the amount of bytes in it
273 public function getSize() {
278 * Add an output value to the array by name.
280 * Verifies that value with the same name has not been added before.
283 * @param array &$arr To add $value to
284 * @param string|int|null $name Index of $arr to add $value at,
285 * or null to use the next numeric index.
286 * @param mixed $value
287 * @param int $flags Zero or more OR-ed flags like OVERRIDE | ADD_ON_TOP.
289 public static function setValue( array &$arr, $name, $value, $flags = 0 ) {
290 if ( ( $flags & ApiResult
::NO_VALIDATE
) !== ApiResult
::NO_VALIDATE
) {
291 $value = self
::validateValue( $value );
294 if ( $name === null ) {
295 if ( $flags & ApiResult
::ADD_ON_TOP
) {
296 array_unshift( $arr, $value );
298 array_push( $arr, $value );
303 $exists = isset( $arr[$name] );
304 if ( !$exists ||
( $flags & ApiResult
::OVERRIDE
) ) {
305 if ( !$exists && ( $flags & ApiResult
::ADD_ON_TOP
) ) {
306 $arr = array( $name => $value ) +
$arr;
308 $arr[$name] = $value;
310 } elseif ( is_array( $arr[$name] ) && is_array( $value ) ) {
311 $conflicts = array_intersect_key( $arr[$name], $value );
313 $arr[$name] +
= $value;
315 $keys = join( ', ', array_keys( $conflicts ) );
316 throw new RuntimeException(
317 "Conflicting keys ($keys) when attempting to merge element $name"
321 throw new RuntimeException(
322 "Attempting to add element $name=$value, existing value is {$arr[$name]}"
328 * Validate a value for addition to the result
329 * @param mixed $value
331 private static function validateValue( $value ) {
334 if ( is_object( $value ) ) {
335 // Note we use is_callable() here instead of instanceof because
336 // ApiSerializable is an informal protocol (see docs there for details).
337 if ( is_callable( array( $value, 'serializeForApiResult' ) ) ) {
339 $value = $value->serializeForApiResult();
340 if ( is_object( $value ) ) {
341 throw new UnexpectedValueException(
342 get_class( $oldValue ) . "::serializeForApiResult() returned an object of class " .
347 // Recursive call instead of fall-through so we can throw a
348 // better exception message.
350 return self
::validateValue( $value );
351 } catch ( Exception
$ex ) {
352 throw new UnexpectedValueException(
353 get_class( $oldValue ) . "::serializeForApiResult() returned an invalid value: " .
359 } elseif ( is_callable( array( $value, '__toString' ) ) ) {
360 $value = (string)$value;
362 $value = (array)$value +
array( self
::META_TYPE
=> 'assoc' );
365 if ( is_array( $value ) ) {
366 foreach ( $value as $k => $v ) {
367 $value[$k] = self
::validateValue( $v );
369 } elseif ( is_float( $value ) && !is_finite( $value ) ) {
370 throw new InvalidArgumentException( "Cannot add non-finite floats to ApiResult" );
371 } elseif ( is_string( $value ) ) {
372 $value = $wgContLang->normalize( $value );
373 } elseif ( $value !== null && !is_scalar( $value ) ) {
374 $type = gettype( $value );
375 if ( is_resource( $value ) ) {
376 $type .= '(' . get_resource_type( $value ) . ')';
378 throw new InvalidArgumentException( "Cannot add $type to ApiResult" );
385 * Add value to the output data at the given path.
387 * Path can be an indexed array, each element specifying the branch at which to add the new
388 * value. Setting $path to array('a','b','c') is equivalent to data['a']['b']['c'] = $value.
389 * If $path is null, the value will be inserted at the data root.
391 * @param array|string|int|null $path
392 * @param string|int|null $name See ApiResult::setValue()
393 * @param mixed $value
394 * @param int $flags Zero or more OR-ed flags like OVERRIDE | ADD_ON_TOP.
395 * This parameter used to be boolean, and the value of OVERRIDE=1 was specifically
396 * chosen so that it would be backwards compatible with the new method signature.
397 * @return bool True if $value fits in the result, false if not
398 * @since 1.21 int $flags replaced boolean $override
400 public function addValue( $path, $name, $value, $flags = 0 ) {
401 $arr = &$this->path( $path, ( $flags & ApiResult
::ADD_ON_TOP
) ?
'prepend' : 'append' );
403 if ( $this->checkingSize
&& !( $flags & ApiResult
::NO_SIZE_CHECK
) ) {
404 // self::valueSize needs the validated value. Then flag
405 // to not re-validate later.
406 $value = self
::validateValue( $value );
407 $flags |
= ApiResult
::NO_VALIDATE
;
409 $newsize = $this->size + self
::valueSize( $value );
410 if ( $this->maxSize
!== false && $newsize > $this->maxSize
) {
411 /// @todo Add i18n message when replacing calls to ->setWarning()
412 $msg = new ApiRawMessage( 'This result was truncated because it would otherwise ' .
413 ' be larger than the limit of $1 bytes', 'truncatedresult' );
414 $msg->numParams( $this->maxSize
);
415 $this->errorFormatter
->addWarning( 'result', $msg );
418 $this->size
= $newsize;
421 self
::setValue( $arr, $name, $value, $flags );
426 * Remove an output value to the array by name.
427 * @param array &$arr To remove $value from
428 * @param string|int $name Index of $arr to remove
429 * @return mixed Old value, or null
431 public static function unsetValue( array &$arr, $name ) {
433 if ( isset( $arr[$name] ) ) {
435 unset( $arr[$name] );
441 * Remove value from the output data at the given path.
444 * @param array|string|null $path See ApiResult::addValue()
445 * @param string|int|null $name Index to remove at $path.
446 * If null, $path itself is removed.
447 * @param int $flags Flags used when adding the value
448 * @return mixed Old value, or null
450 public function removeValue( $path, $name, $flags = 0 ) {
451 $path = (array)$path;
452 if ( $name === null ) {
454 throw new InvalidArgumentException( 'Cannot remove the data root' );
456 $name = array_pop( $path );
458 $ret = self
::unsetValue( $this->path( $path, 'dummy' ), $name );
459 if ( $this->checkingSize
&& !( $flags & ApiResult
::NO_SIZE_CHECK
) ) {
460 $newsize = $this->size
- self
::valueSize( $ret );
461 $this->size
= max( $newsize, 0 );
467 * Add an output value to the array by name and mark as META_CONTENT.
470 * @param array &$arr To add $value to
471 * @param string|int $name Index of $arr to add $value at.
472 * @param mixed $value
473 * @param int $flags Zero or more OR-ed flags like OVERRIDE | ADD_ON_TOP.
475 public static function setContentValue( array &$arr, $name, $value, $flags = 0 ) {
476 if ( $name === null ) {
477 throw new InvalidArgumentException( 'Content value must be named' );
479 self
::setContentField( $arr, $name, $flags );
480 self
::setValue( $arr, $name, $value, $flags );
484 * Add value to the output data at the given path and mark as META_CONTENT
487 * @param array|string|null $path See ApiResult::addValue()
488 * @param string|int $name See ApiResult::setValue()
489 * @param mixed $value
490 * @param int $flags Zero or more OR-ed flags like OVERRIDE | ADD_ON_TOP.
491 * @return bool True if $value fits in the result, false if not
493 public function addContentValue( $path, $name, $value, $flags = 0 ) {
494 if ( $name === null ) {
495 throw new InvalidArgumentException( 'Content value must be named' );
497 $this->addContentField( $path, $name, $flags );
498 $this->addValue( $path, $name, $value, $flags );
502 * Add the numeric limit for a limit=max to the result.
505 * @param string $moduleName
508 public function addParsedLimit( $moduleName, $limit ) {
509 // Add value, allowing overwriting
510 $this->addValue( 'limits', $moduleName, $limit,
511 ApiResult
::OVERRIDE | ApiResult
::NO_SIZE_CHECK
);
516 /************************************************************************//**
522 * Set the name of the content field name (META_CONTENT)
526 * @param string|int $name Name of the field
527 * @param int $flags Zero or more OR-ed flags like OVERRIDE | ADD_ON_TOP.
529 public static function setContentField( array &$arr, $name, $flags = 0 ) {
530 if ( isset( $arr[self
::META_CONTENT
] ) &&
531 isset( $arr[$arr[self
::META_CONTENT
]] ) &&
532 !( $flags & self
::OVERRIDE
)
534 throw new RuntimeException(
535 "Attempting to set content element as $name when " . $arr[self
::META_CONTENT
] .
536 " is already set as the content element"
539 $arr[self
::META_CONTENT
] = $name;
543 * Set the name of the content field name (META_CONTENT)
546 * @param array|string|null $path See ApiResult::addValue()
547 * @param string|int $name Name of the field
548 * @param int $flags Zero or more OR-ed flags like OVERRIDE | ADD_ON_TOP.
550 public function addContentField( $path, $name, $flags = 0 ) {
551 $arr = &$this->path( $path, ( $flags & ApiResult
::ADD_ON_TOP
) ?
'prepend' : 'append' );
552 self
::setContentField( $arr, $name, $flags );
556 * Causes the elements with the specified names to be output as
557 * subelements rather than attributes.
558 * @since 1.25 is static
560 * @param array|string|int $names The element name(s) to be output as subelements
562 public static function setSubelementsList( array &$arr, $names ) {
563 if ( !isset( $arr[self
::META_SUBELEMENTS
] ) ) {
564 $arr[self
::META_SUBELEMENTS
] = (array)$names;
566 $arr[self
::META_SUBELEMENTS
] = array_merge( $arr[self
::META_SUBELEMENTS
], (array)$names );
571 * Causes the elements with the specified names to be output as
572 * subelements rather than attributes.
574 * @param array|string|null $path See ApiResult::addValue()
575 * @param array|string|int $names The element name(s) to be output as subelements
577 public function addSubelementsList( $path, $names ) {
578 $arr = &$this->path( $path );
579 self
::setSubelementsList( $arr, $names );
583 * Causes the elements with the specified names to be output as
584 * attributes (when possible) rather than as subelements.
587 * @param array|string|int $names The element name(s) to not be output as subelements
589 public static function unsetSubelementsList( array &$arr, $names ) {
590 if ( isset( $arr[self
::META_SUBELEMENTS
] ) ) {
591 $arr[self
::META_SUBELEMENTS
] = array_diff( $arr[self
::META_SUBELEMENTS
], (array)$names );
596 * Causes the elements with the specified names to be output as
597 * attributes (when possible) rather than as subelements.
599 * @param array|string|null $path See ApiResult::addValue()
600 * @param array|string|int $names The element name(s) to not be output as subelements
602 public function removeSubelementsList( $path, $names ) {
603 $arr = &$this->path( $path );
604 self
::unsetSubelementsList( $arr, $names );
608 * Set the tag name for numeric-keyed values in XML format
609 * @since 1.25 is static
611 * @param string $tag Tag name
613 public static function setIndexedTagName( array &$arr, $tag ) {
614 if ( !is_string( $tag ) ) {
615 throw new InvalidArgumentException( 'Bad tag name' );
617 $arr[self
::META_INDEXED_TAG_NAME
] = $tag;
621 * Set the tag name for numeric-keyed values in XML format
623 * @param array|string|null $path See ApiResult::addValue()
624 * @param string $tag Tag name
626 public function addIndexedTagName( $path, $tag ) {
627 $arr = &$this->path( $path );
628 self
::setIndexedTagName( $arr, $tag );
632 * Set indexed tag name on $arr and all subarrays
636 * @param string $tag Tag name
638 public static function setIndexedTagNameRecursive( array &$arr, $tag ) {
639 if ( !is_string( $tag ) ) {
640 throw new InvalidArgumentException( 'Bad tag name' );
642 $arr[self
::META_INDEXED_TAG_NAME
] = $tag;
643 foreach ( $arr as $k => &$v ) {
644 if ( !self
::isMetadataKey( $k ) && is_array( $v ) ) {
645 self
::setIndexedTagNameRecursive( $v, $tag );
651 * Set indexed tag name on $path and all subarrays
654 * @param array|string|null $path See ApiResult::addValue()
655 * @param string $tag Tag name
657 public function addIndexedTagNameRecursive( $path, $tag ) {
658 $arr = &$this->path( $path );
659 self
::setIndexedTagNameRecursive( $arr, $tag );
663 * Preserve specified keys.
665 * This prevents XML name mangling and preventing keys from being removed
666 * by self::stripMetadata().
670 * @param array|string $names The element name(s) to preserve
672 public static function setPreserveKeysList( array &$arr, $names ) {
673 if ( !isset( $arr[self
::META_PRESERVE_KEYS
] ) ) {
674 $arr[self
::META_PRESERVE_KEYS
] = (array)$names;
676 $arr[self
::META_PRESERVE_KEYS
] = array_merge( $arr[self
::META_PRESERVE_KEYS
], (array)$names );
681 * Preserve specified keys.
683 * @see self::setPreserveKeysList()
684 * @param array|string|null $path See ApiResult::addValue()
685 * @param array|string $names The element name(s) to preserve
687 public function addPreserveKeysList( $path, $names ) {
688 $arr = &$this->path( $path );
689 self
::setPreserveKeysList( $arr, $names );
693 * Don't preserve specified keys.
695 * @see self::setPreserveKeysList()
697 * @param array|string $names The element name(s) to not preserve
699 public static function unsetPreserveKeysList( array &$arr, $names ) {
700 if ( isset( $arr[self
::META_PRESERVE_KEYS
] ) ) {
701 $arr[self
::META_PRESERVE_KEYS
] = array_diff( $arr[self
::META_PRESERVE_KEYS
], (array)$names );
706 * Don't preserve specified keys.
708 * @see self::setPreserveKeysList()
709 * @param array|string|null $path See ApiResult::addValue()
710 * @param array|string $names The element name(s) to not preserve
712 public function removePreserveKeysList( $path, $names ) {
713 $arr = &$this->path( $path );
714 self
::unsetPreserveKeysList( $arr, $names );
718 * Set the array data type
722 * @param string $type See ApiResult::META_TYPE
723 * @param string $kvpKeyName See ApiResult::META_KVP_KEY_NAME
725 public static function setArrayType( array &$arr, $type, $kvpKeyName = null ) {
726 if ( !in_array( $type, array(
727 'default', 'array', 'assoc', 'kvp', 'BCarray', 'BCassoc', 'BCkvp'
729 throw new InvalidArgumentException( 'Bad type' );
731 $arr[self
::META_TYPE
] = $type;
732 if ( is_string( $kvpKeyName ) ) {
733 $arr[self
::META_KVP_KEY_NAME
] = $kvpKeyName;
738 * Set the array data type for a path
740 * @param array|string|null $path See ApiResult::addValue()
741 * @param string $type See ApiResult::META_TYPE
742 * @param string $kvpKeyName See ApiResult::META_KVP_KEY_NAME
744 public function addArrayType( $path, $tag, $kvpKeyName = null ) {
745 $arr = &$this->path( $path );
746 self
::setArrayType( $arr, $tag, $kvpKeyName );
750 * Set the array data type recursively
753 * @param string $type See ApiResult::META_TYPE
754 * @param string $kvpKeyName See ApiResult::META_KVP_KEY_NAME
756 public static function setArrayTypeRecursive( array &$arr, $type, $kvpKeyName = null ) {
757 self
::setArrayType( $arr, $type, $kvpKeyName );
758 foreach ( $arr as $k => &$v ) {
759 if ( !self
::isMetadataKey( $k ) && is_array( $v ) ) {
760 self
::setArrayTypeRecursive( $v, $type, $kvpKeyName );
766 * Set the array data type for a path recursively
768 * @param array|string|null $path See ApiResult::addValue()
769 * @param string $type See ApiResult::META_TYPE
770 * @param string $kvpKeyName See ApiResult::META_KVP_KEY_NAME
772 public function addArrayTypeRecursive( $path, $tag, $kvpKeyName = null ) {
773 $arr = &$this->path( $path );
774 self
::setArrayTypeRecursive( $arr, $tag, $kvpKeyName );
779 /************************************************************************//**
785 * Test whether a key should be considered metadata
790 public static function isMetadataKey( $key ) {
791 return substr( $key, 0, 1 ) === '_';
795 * Apply transformations to an array, returning the transformed array.
797 * @see ApiResult::getResultData()
800 * @param array $transforms
801 * @return array|object
803 protected static function applyTransformations( array $dataIn, array $transforms ) {
804 $strip = isset( $transforms['Strip'] ) ?
$transforms['Strip'] : 'none';
805 if ( $strip === 'base' ) {
806 $transforms['Strip'] = 'none';
808 $transformTypes = isset( $transforms['Types'] ) ?
$transforms['Types'] : null;
809 if ( $transformTypes !== null && !is_array( $transformTypes ) ) {
810 throw new InvalidArgumentException( __METHOD__
. ':Value for "Types" must be an array' );
814 $data = self
::stripMetadataNonRecursive( $dataIn, $metadata );
816 if ( isset( $transforms['Custom'] ) ) {
817 if ( !is_callable( $transforms['Custom'] ) ) {
818 throw new InvalidArgumentException( __METHOD__
. ': Value for "Custom" must be callable' );
820 call_user_func_array( $transforms['Custom'], array( &$data, &$metadata ) );
823 if ( ( isset( $transforms['BC'] ) ||
$transformTypes !== null ) &&
824 isset( $metadata[self
::META_TYPE
] ) && $metadata[self
::META_TYPE
] === 'BCkvp' &&
825 !isset( $metadata[self
::META_KVP_KEY_NAME
] )
827 throw new UnexpectedValueException( 'Type "BCkvp" used without setting ' .
828 'ApiResult::META_KVP_KEY_NAME metadata item' );
831 // BC transformations
833 if ( isset( $transforms['BC'] ) ) {
834 if ( !is_array( $transforms['BC'] ) ) {
835 throw new InvalidArgumentException( __METHOD__
. ':Value for "BC" must be an array' );
837 if ( !in_array( 'nobool', $transforms['BC'], true ) ) {
838 $boolKeys = isset( $metadata[self
::META_BC_BOOLS
] )
839 ?
array_flip( $metadata[self
::META_BC_BOOLS
] )
843 if ( !in_array( 'no*', $transforms['BC'], true ) &&
844 isset( $metadata[self
::META_CONTENT
] ) && $metadata[self
::META_CONTENT
] !== '*'
846 $k = $metadata[self
::META_CONTENT
];
847 $data['*'] = $data[$k];
849 $metadata[self
::META_CONTENT
] = '*';
852 if ( !in_array( 'nosub', $transforms['BC'], true ) &&
853 isset( $metadata[self
::META_BC_SUBELEMENTS
] )
855 foreach ( $metadata[self
::META_BC_SUBELEMENTS
] as $k ) {
856 if ( isset( $data[$k] ) ) {
859 self
::META_CONTENT
=> '*',
860 self
::META_TYPE
=> 'assoc',
866 if ( isset( $metadata[self
::META_TYPE
] ) ) {
867 switch ( $metadata[self
::META_TYPE
] ) {
870 $metadata[self
::META_TYPE
] = 'default';
873 $transformTypes['ArmorKVP'] = $metadata[self
::META_KVP_KEY_NAME
];
879 // Figure out type, do recursive calls, and do boolean transform if necessary
880 $defaultType = 'array';
882 foreach ( $data as $k => &$v ) {
883 $v = is_array( $v ) ? self
::applyTransformations( $v, $transforms ) : $v;
884 if ( $boolKeys !== null && is_bool( $v ) && !isset( $boolKeys[$k] ) ) {
891 if ( is_string( $k ) ) {
892 $defaultType = 'assoc';
893 } elseif ( $k > $maxKey ) {
899 // Determine which metadata to keep
903 $keepMetadata = array();
906 $keepMetadata = &$metadata;
909 $keepMetadata = array_intersect_key( $metadata, array(
910 self
::META_INDEXED_TAG_NAME
=> 1,
911 self
::META_SUBELEMENTS
=> 1,
915 throw new InvalidArgumentException( __METHOD__
. ': Unknown value for "Strip"' );
918 // Type transformation
919 if ( $transformTypes !== null ) {
920 if ( $defaultType === 'array' && $maxKey !== count( $data ) - 1 ) {
921 $defaultType = 'assoc';
924 // Override type, if provided
925 $type = $defaultType;
926 if ( isset( $metadata[self
::META_TYPE
] ) && $metadata[self
::META_TYPE
] !== 'default' ) {
927 $type = $metadata[self
::META_TYPE
];
929 if ( ( $type === 'kvp' ||
$type === 'BCkvp' ) &&
930 empty( $transformTypes['ArmorKVP'] )
933 } elseif ( $type === 'BCarray' ) {
935 } elseif ( $type === 'BCassoc' ) {
939 // Apply transformation
942 $metadata[self
::META_TYPE
] = 'assoc';
943 $data +
= $keepMetadata;
944 return empty( $transformTypes['AssocAsObject'] ) ?
$data : (object)$data;
948 $data = array_values( $data );
949 $metadata[self
::META_TYPE
] = 'array';
950 return $data +
$keepMetadata;
954 $key = isset( $metadata[self
::META_KVP_KEY_NAME
] )
955 ?
$metadata[self
::META_KVP_KEY_NAME
]
956 : $transformTypes['ArmorKVP'];
957 $valKey = isset( $transforms['BC'] ) ?
'*' : 'value';
958 $assocAsObject = !empty( $transformTypes['AssocAsObject'] );
959 $merge = !empty( $metadata[self
::META_KVP_MERGE
] );
962 foreach ( $data as $k => $v ) {
963 if ( $merge && ( is_array( $v ) ||
is_object( $v ) ) ) {
965 if ( isset( $vArr[self
::META_TYPE
] ) ) {
966 $mergeType = $vArr[self
::META_TYPE
];
967 } elseif ( is_object( $v ) ) {
968 $mergeType = 'assoc';
970 $keys = array_keys( $vArr );
971 sort( $keys, SORT_NUMERIC
);
972 $mergeType = ( $keys === array_keys( $keys ) ) ?
'array' : 'assoc';
977 if ( $mergeType === 'assoc' ) {
978 $item = $vArr +
array(
981 if ( $strip === 'none' ) {
982 self
::setPreserveKeysList( $item, array( $key ) );
989 if ( $strip === 'none' ) {
991 self
::META_PRESERVE_KEYS
=> array( $key ),
992 self
::META_CONTENT
=> $valKey,
993 self
::META_TYPE
=> 'assoc',
997 $ret[] = $assocAsObject ?
(object)$item : $item;
999 $metadata[self
::META_TYPE
] = 'array';
1001 return $ret +
$keepMetadata;
1004 throw new UnexpectedValueException( "Unknown type '$type'" );
1007 return $data +
$keepMetadata;
1012 * Recursively remove metadata keys from a data array or object
1014 * Note this removes all potential metadata keys, not just the defined
1018 * @param array|object $data
1019 * @return array|object
1021 public static function stripMetadata( $data ) {
1022 if ( is_array( $data ) ||
is_object( $data ) ) {
1023 $isObj = is_object( $data );
1025 $data = (array)$data;
1027 $preserveKeys = isset( $data[self
::META_PRESERVE_KEYS
] )
1028 ?
(array)$data[self
::META_PRESERVE_KEYS
]
1030 foreach ( $data as $k => $v ) {
1031 if ( self
::isMetadataKey( $k ) && !in_array( $k, $preserveKeys, true ) ) {
1033 } elseif ( is_array( $v ) ||
is_object( $v ) ) {
1034 $data[$k] = self
::stripMetadata( $v );
1038 $data = (object)$data;
1045 * Remove metadata keys from a data array or object, non-recursive
1047 * Note this removes all potential metadata keys, not just the defined
1051 * @param array|object $data
1052 * @param array &$metadata Store metadata here, if provided
1053 * @return array|object
1055 public static function stripMetadataNonRecursive( $data, &$metadata = null ) {
1056 if ( !is_array( $metadata ) ) {
1057 $metadata = array();
1059 if ( is_array( $data ) ||
is_object( $data ) ) {
1060 $isObj = is_object( $data );
1062 $data = (array)$data;
1064 $preserveKeys = isset( $data[self
::META_PRESERVE_KEYS
] )
1065 ?
(array)$data[self
::META_PRESERVE_KEYS
]
1067 foreach ( $data as $k => $v ) {
1068 if ( self
::isMetadataKey( $k ) && !in_array( $k, $preserveKeys, true ) ) {
1074 $data = (object)$data;
1081 * Get the 'real' size of a result item. This means the strlen() of the item,
1082 * or the sum of the strlen()s of the elements if the item is an array.
1083 * @note Once the deprecated public self::size is removed, we can rename
1084 * this back to a less awkward name.
1085 * @param mixed $value Validated value (see self::validateValue())
1088 private static function valueSize( $value ) {
1090 if ( is_array( $value ) ) {
1091 foreach ( $value as $k => $v ) {
1092 if ( !self
::isMetadataKey( $s ) ) {
1093 $s +
= self
::valueSize( $v );
1096 } elseif ( is_scalar( $value ) ) {
1097 $s = strlen( $value );
1104 * Return a reference to the internal data at $path
1106 * @param array|string|null $path
1107 * @param string $create
1108 * If 'append', append empty arrays.
1109 * If 'prepend', prepend empty arrays.
1110 * If 'dummy', return a dummy array.
1111 * Else, raise an error.
1114 private function &path( $path, $create = 'append' ) {
1115 $path = (array)$path;
1116 $ret = &$this->data
;
1117 foreach ( $path as $i => $k ) {
1118 if ( !isset( $ret[$k] ) ) {
1119 switch ( $create ) {
1124 $ret = array( $k => array() ) +
$ret;
1130 $fail = join( '.', array_slice( $path, 0, $i +
1 ) );
1131 throw new InvalidArgumentException( "Path $fail does not exist" );
1134 if ( !is_array( $ret[$k] ) ) {
1135 $fail = join( '.', array_slice( $path, 0, $i +
1 ) );
1136 throw new InvalidArgumentException( "Path $fail is not an array" );
1144 * Add the correct metadata to an array of vars we want to export through
1147 * @param array $vars
1148 * @param boolean $forceHash
1151 public static function addMetadataToResultVars( $vars, $forceHash = true ) {
1152 // Process subarrays and determine if this is a JS [] or {}
1156 foreach ( $vars as $k => $v ) {
1157 if ( is_array( $v ) ||
is_object( $v ) ) {
1158 $vars[$k] = ApiResult
::addMetadataToResultVars( (array)$v, is_object( $v ) );
1159 } elseif ( is_bool( $v ) ) {
1160 // Better here to use real bools even in BC formats
1163 if ( is_string( $k ) ) {
1165 } elseif ( $k > $maxKey ) {
1169 if ( !$hash && $maxKey !== count( $vars ) - 1 ) {
1173 // Set metadata appropriately
1175 // Get the list of keys we actually care about. Unfortunately, we can't support
1176 // certain keys that conflict with ApiResult metadata.
1177 $keys = array_diff( array_keys( $vars ), array(
1178 ApiResult
::META_TYPE
, ApiResult
::META_PRESERVE_KEYS
, ApiResult
::META_KVP_KEY_NAME
,
1179 ApiResult
::META_INDEXED_TAG_NAME
, ApiResult
::META_BC_BOOLS
1183 ApiResult
::META_TYPE
=> 'kvp',
1184 ApiResult
::META_KVP_KEY_NAME
=> 'key',
1185 ApiResult
::META_PRESERVE_KEYS
=> $keys,
1186 ApiResult
::META_BC_BOOLS
=> $bools,
1187 ApiResult
::META_INDEXED_TAG_NAME
=> 'var',
1191 ApiResult
::META_TYPE
=> 'array',
1192 ApiResult
::META_BC_BOOLS
=> $bools,
1193 ApiResult
::META_INDEXED_TAG_NAME
=> 'value',
1200 /************************************************************************//**
1206 * Formerly used to enable/disable "raw mode".
1207 * @deprecated since 1.25, you shouldn't have been using it in the first place
1208 * @since 1.23 $flag parameter added
1209 * @param bool $flag Set the raw mode flag to this state
1211 public function setRawMode( $flag = true ) {
1212 wfDeprecated( __METHOD__
, '1.25' );
1216 * Returns true, the equivalent of "raw mode" is always enabled now
1217 * @deprecated since 1.25, you shouldn't have been using it in the first place
1220 public function getIsRawMode() {
1221 wfDeprecated( __METHOD__
, '1.25' );
1226 * Get the result's internal data array (read-only)
1227 * @deprecated since 1.25, use $this->getResultData() instead
1230 public function getData() {
1231 wfDeprecated( __METHOD__
, '1.25' );
1232 return $this->getResultData( null, array(
1240 * Disable size checking in addValue(). Don't use this unless you
1241 * REALLY know what you're doing. Values added while size checking
1242 * was disabled will not be counted (ever)
1243 * @deprecated since 1.24, use ApiResult::NO_SIZE_CHECK
1245 public function disableSizeCheck() {
1246 wfDeprecated( __METHOD__
, '1.24' );
1247 $this->checkingSize
= false;
1251 * Re-enable size checking in addValue()
1252 * @deprecated since 1.24, use ApiResult::NO_SIZE_CHECK
1254 public function enableSizeCheck() {
1255 wfDeprecated( __METHOD__
, '1.24' );
1256 $this->checkingSize
= true;
1260 * Alias for self::setValue()
1262 * @since 1.21 int $flags replaced boolean $override
1263 * @deprecated since 1.25, use self::setValue() instead
1264 * @param array $arr To add $value to
1265 * @param string $name Index of $arr to add $value at
1266 * @param mixed $value
1267 * @param int $flags Zero or more OR-ed flags like OVERRIDE | ADD_ON_TOP.
1268 * This parameter used to be boolean, and the value of OVERRIDE=1 was
1269 * specifically chosen so that it would be backwards compatible with the
1270 * new method signature.
1272 public static function setElement( &$arr, $name, $value, $flags = 0 ) {
1273 wfDeprecated( __METHOD__
, '1.25' );
1274 self
::setValue( $arr, $name, $value, $flags );
1278 * Adds a content element to an array.
1279 * Use this function instead of hardcoding the '*' element.
1280 * @deprecated since 1.25, use self::setContentValue() instead
1281 * @param array $arr To add the content element to
1282 * @param mixed $value
1283 * @param string $subElemName When present, content element is created
1284 * as a sub item of $arr. Use this parameter to create elements in
1285 * format "<elem>text</elem>" without attributes.
1287 public static function setContent( &$arr, $value, $subElemName = null ) {
1288 wfDeprecated( __METHOD__
, '1.25' );
1289 if ( is_array( $value ) ) {
1290 throw new InvalidArgumentException( __METHOD__
. ': Bad parameter' );
1292 if ( is_null( $subElemName ) ) {
1293 self
::setContentValue( $arr, 'content', $value );
1295 if ( !isset( $arr[$subElemName] ) ) {
1296 $arr[$subElemName] = array();
1298 self
::setContentValue( $arr[$subElemName], 'content', $value );
1303 * Set indexed tag name on all subarrays of $arr
1305 * Does not set the tag name for $arr itself.
1307 * @deprecated since 1.25, use self::setIndexedTagNameRecursive() instead
1309 * @param string $tag Tag name
1311 public function setIndexedTagName_recursive( &$arr, $tag ) {
1312 wfDeprecated( __METHOD__
, '1.25' );
1313 if ( !is_array( $arr ) ) {
1316 if ( !is_string( $tag ) ) {
1317 throw new InvalidArgumentException( 'Bad tag name' );
1319 foreach ( $arr as $k => &$v ) {
1320 if ( !self
::isMetadataKey( $k ) && is_array( $v ) ) {
1321 $v[self
::META_INDEXED_TAG_NAME
] = $tag;
1322 $this->setIndexedTagName_recursive( $v, $tag );
1328 * Alias for self::addIndexedTagName()
1329 * @deprecated since 1.25, use $this->addIndexedTagName() instead
1330 * @param array $path Path to the array, like addValue()'s $path
1331 * @param string $tag
1333 public function setIndexedTagName_internal( $path, $tag ) {
1334 wfDeprecated( __METHOD__
, '1.25' );
1335 $this->addIndexedTagName( $path, $tag );
1339 * Alias for self::addParsedLimit()
1340 * @deprecated since 1.25, use $this->addParsedLimit() instead
1341 * @param string $moduleName
1344 public function setParsedLimit( $moduleName, $limit ) {
1345 wfDeprecated( __METHOD__
, '1.25' );
1346 $this->addParsedLimit( $moduleName, $limit );
1350 * Set the ApiMain for use by $this->beginContinuation()
1352 * @deprecated for backwards compatibility only, do not use
1353 * @param ApiMain $main
1355 public function setMainForContinuation( ApiMain
$main ) {
1356 $this->mainForContinuation
= $main;
1360 * Parse a 'continue' parameter and return status information.
1362 * This must be balanced by a call to endContinuation().
1365 * @deprecated since 1.25, use ApiContinuationManager instead
1366 * @param string|null $continue
1367 * @param ApiBase[] $allModules
1368 * @param array $generatedModules
1371 public function beginContinuation(
1372 $continue, array $allModules = array(), array $generatedModules = array()
1374 wfDeprecated( __METHOD__
, '1.25' );
1375 if ( $this->mainForContinuation
->getContinuationManager() ) {
1376 throw new UnexpectedValueException(
1377 __METHOD__
. ': Continuation already in progress from ' .
1378 $this->mainForContinuation
->getContinuationManager()->getSource()
1382 // Ugh. If $continue doesn't match that in the request, temporarily
1383 // replace the request when creating the ApiContinuationManager.
1384 if ( $continue === null ) {
1387 if ( $this->mainForContinuation
->getVal( 'continue', '' ) !== $continue ) {
1388 $oldCtx = $this->mainForContinuation
->getContext();
1389 $newCtx = new DerivativeContext( $oldCtx );
1390 $newCtx->setRequest( new DerivativeRequest(
1391 $oldCtx->getRequest(),
1392 array( 'continue' => $continue ) +
$oldCtx->getRequest()->getValues(),
1393 $oldCtx->getRequest()->wasPosted()
1395 $this->mainForContinuation
->setContext( $newCtx );
1396 $reset = new ScopedCallback(
1397 array( $this->mainForContinuation
, 'setContext' ),
1401 $manager = new ApiContinuationManager(
1402 $this->mainForContinuation
, $allModules, $generatedModules
1406 $this->mainForContinuation
->setContinuationManager( $manager );
1409 $manager->isGeneratorDone(),
1410 $manager->getRunModules(),
1416 * @deprecated since 1.25, use ApiContinuationManager instead
1417 * @param ApiBase $module
1418 * @param string $paramName
1419 * @param string|array $paramValue
1421 public function setContinueParam( ApiBase
$module, $paramName, $paramValue ) {
1422 wfDeprecated( __METHOD__
, '1.25' );
1423 if ( $this->mainForContinuation
->getContinuationManager() ) {
1424 $this->mainForContinuation
->getContinuationManager()->addContinueParam(
1425 $module, $paramName, $paramValue
1432 * @deprecated since 1.25, use ApiContinuationManager instead
1433 * @param ApiBase $module
1434 * @param string $paramName
1435 * @param string|array $paramValue
1437 public function setGeneratorContinueParam( ApiBase
$module, $paramName, $paramValue ) {
1438 wfDeprecated( __METHOD__
, '1.25' );
1439 if ( $this->mainForContinuation
->getContinuationManager() ) {
1440 $this->mainForContinuation
->getContinuationManager()->addGeneratorContinueParam(
1441 $module, $paramName, $paramValue
1447 * Close continuation, writing the data into the result
1449 * @deprecated since 1.25, use ApiContinuationManager instead
1450 * @param string $style 'standard' for the new style since 1.21, 'raw' for
1451 * the style used in 1.20 and earlier.
1453 public function endContinuation( $style = 'standard' ) {
1454 wfDeprecated( __METHOD__
, '1.25' );
1455 if ( !$this->mainForContinuation
->getContinuationManager() ) {
1459 if ( $style === 'raw' ) {
1460 $data = $this->mainForContinuation
->getContinuationManager()->getRawContinuation();
1462 $this->addValue( null, 'query-continue', $data, self
::ADD_ON_TOP | self
::NO_SIZE_CHECK
);
1465 $this->mainForContinuation
->getContinuationManager()->setContinuationIntoResult( $this );
1470 * No-op, this is now checked on insert.
1471 * @deprecated since 1.25
1473 public function cleanUpUTF8() {
1474 wfDeprecated( __METHOD__
, '1.25' );
1478 * Get the 'real' size of a result item. This means the strlen() of the item,
1479 * or the sum of the strlen()s of the elements if the item is an array.
1480 * @deprecated since 1.25, no external users known and there doesn't seem
1481 * to be any case for such use over just checking the return value from the
1483 * @param mixed $value
1486 public static function size( $value ) {
1487 wfDeprecated( __METHOD__
, '1.25' );
1488 return self
::valueSize( self
::validateValue( $value ) );
1492 * Converts a Status object to an array suitable for addValue
1493 * @deprecated since 1.25, use ApiErrorFormatter::arrayFromStatus()
1494 * @param Status $status
1495 * @param string $errorType
1498 public function convertStatusToArray( $status, $errorType = 'error' ) {
1499 wfDeprecated( __METHOD__
, '1.25' );
1500 return $this->errorFormatter
->arrayFromStatus( $status, $errorType );
1507 * For really cool vim folding this needs to be at the end:
1508 * vim: foldmarker=@{,@} foldmethod=marker