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 $isRawMode, $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->isRawMode
= false;
163 $this->checkingSize
= true;
168 * Set the error formatter
170 * @param ApiErrorFormatter $formatter
172 public function setErrorFormatter( ApiErrorFormatter
$formatter ) {
173 $this->errorFormatter
= $formatter;
177 * Allow for adding one ApiResult into another
181 public function serializeForApiResult() {
185 /************************************************************************//**
191 * Clear the current result data.
193 public function reset() {
195 self
::META_TYPE
=> 'assoc', // Usually what's desired
201 * Get the result data array
203 * The returned value should be considered read-only.
205 * Transformations include:
207 * Custom: (callable) Applied before other transformations. Signature is
208 * function ( &$data, &$metadata ), return value is ignored. Called for
211 * BC: (array) This transformation does various adjustments to bring the
212 * output in line with the pre-1.25 result format. The value array is a
213 * list of flags: 'nobool', 'no*', 'nosub'.
214 * - Boolean-valued items are changed to '' if true or removed if false,
215 * unless listed in META_BC_BOOLS. This may be skipped by including
216 * 'nobool' in the value array.
217 * - The tag named by META_CONTENT is renamed to '*', and META_CONTENT is
218 * set to '*'. This may be skipped by including 'no*' in the value
220 * - Tags listed in META_BC_SUBELEMENTS will have their values changed to
221 * array( '*' => $value ). This may be skipped by including 'nosub' in
223 * - If META_TYPE is 'BCarray', set it to 'default'
224 * - If META_TYPE is 'BCassoc', set it to 'default'
225 * - If META_TYPE is 'BCkvp', perform the transformation (even if
226 * the Types transformation is not being applied).
228 * Types: (assoc) Apply transformations based on META_TYPE. The values
229 * array is an associative array with the following possible keys:
230 * - AssocAsObject: (bool) If true, return arrays with META_TYPE 'assoc'
232 * - ArmorKVP: (string) If provided, transform arrays with META_TYPE 'kvp'
233 * and 'BCkvp' into arrays of two-element arrays, something like this:
235 * foreach ( $input as $key => $value ) {
237 * $pair[$META_KVP_KEY_NAME ?: $ArmorKVP_value] = $key;
238 * ApiResult::setContentValue( $pair, 'value', $value );
242 * Strip: (string) Strips metadata keys from the result.
243 * - 'all': Strip all metadata, recursively
244 * - 'base': Strip metadata at the top-level only.
245 * - 'none': Do not strip metadata.
246 * - 'bc': Like 'all', but leave certain pre-1.25 keys.
249 * @param array|string|null $path Path to fetch, see ApiResult::addValue
250 * @param array $transforms See above
251 * @return mixed Result data, or null if not found
253 public function getResultData( $path = array(), $transforms = array() ) {
254 $path = (array)$path;
256 return self
::applyTransformations( $this->data
, $transforms );
259 $last = array_pop( $path );
260 $ret = &$this->path( $path, 'dummy' );
261 if ( !isset( $ret[$last] ) ) {
263 } elseif ( is_array( $ret[$last] ) ) {
264 return self
::applyTransformations( $ret[$last], $transforms );
271 * Get the size of the result, i.e. the amount of bytes in it
274 public function getSize() {
279 * Add an output value to the array by name.
281 * Verifies that value with the same name has not been added before.
284 * @param array &$arr To add $value to
285 * @param string|int|null $name Index of $arr to add $value at,
286 * or null to use the next numeric index.
287 * @param mixed $value
288 * @param int $flags Zero or more OR-ed flags like OVERRIDE | ADD_ON_TOP.
290 public static function setValue( array &$arr, $name, $value, $flags = 0 ) {
291 if ( !( $flags & ApiResult
::NO_VALIDATE
) ) {
292 $value = self
::validateValue( $value );
295 if ( $name === null ) {
296 if ( $flags & ApiResult
::ADD_ON_TOP
) {
297 array_unshift( $arr, $value );
299 array_push( $arr, $value );
304 $exists = isset( $arr[$name] );
305 if ( !$exists ||
( $flags & ApiResult
::OVERRIDE
) ) {
306 if ( !$exists && ( $flags & ApiResult
::ADD_ON_TOP
) ) {
307 $arr = array( $name => $value ) +
$arr;
309 $arr[$name] = $value;
311 } elseif ( is_array( $arr[$name] ) && is_array( $value ) ) {
312 $conflicts = array_intersect_key( $arr[$name], $value );
314 $arr[$name] +
= $value;
316 $keys = join( ', ', array_keys( $conflicts ) );
317 throw new RuntimeException(
318 "Conflicting keys ($keys) when attempting to merge element $name"
322 throw new RuntimeException(
323 "Attempting to add element $name=$value, existing value is {$arr[$name]}"
329 * Validate a value for addition to the result
330 * @param mixed $value
332 private static function validateValue( $value ) {
335 if ( is_object( $value ) ) {
336 // Note we use is_callable() here instead of instanceof because
337 // ApiSerializable is an informal protocol (see docs there for details).
338 if ( is_callable( array( $value, 'serializeForApiResult' ) ) ) {
340 $value = $value->serializeForApiResult();
341 if ( is_object( $value ) ) {
342 throw new UnexpectedValueException(
343 get_class( $oldValue ) . "::serializeForApiResult() returned an object of class " .
348 // Recursive call instead of fall-through so we can throw a
349 // better exception message.
351 return self
::validateValue( $value );
352 } catch ( Exception
$ex ) {
353 throw new UnexpectedValueException(
354 get_class( $oldValue ) . "::serializeForApiResult() returned an invalid value: " .
360 } elseif ( is_callable( array( $value, '__toString' ) ) ) {
361 $value = (string)$value;
363 $value = (array)$value +
array( self
::META_TYPE
=> 'assoc' );
366 if ( is_array( $value ) ) {
367 foreach ( $value as $k => $v ) {
368 $value[$k] = self
::validateValue( $v );
370 } elseif ( is_float( $value ) && !is_finite( $value ) ) {
371 throw new InvalidArgumentException( "Cannot add non-finite floats to ApiResult" );
372 } elseif ( is_string( $value ) ) {
373 $value = $wgContLang->normalize( $value );
374 } elseif ( $value !== null && !is_scalar( $value ) ) {
375 $type = gettype( $value );
376 if ( is_resource( $value ) ) {
377 $type .= '(' . get_resource_type( $value ) . ')';
379 throw new InvalidArgumentException( "Cannot add $type to ApiResult" );
386 * Add value to the output data at the given path.
388 * Path can be an indexed array, each element specifying the branch at which to add the new
389 * value. Setting $path to array('a','b','c') is equivalent to data['a']['b']['c'] = $value.
390 * If $path is null, the value will be inserted at the data root.
392 * @param array|string|int|null $path
393 * @param string|int|null $name See ApiResult::setValue()
394 * @param mixed $value
395 * @param int $flags Zero or more OR-ed flags like OVERRIDE | ADD_ON_TOP.
396 * This parameter used to be boolean, and the value of OVERRIDE=1 was specifically
397 * chosen so that it would be backwards compatible with the new method signature.
398 * @return bool True if $value fits in the result, false if not
399 * @since 1.21 int $flags replaced boolean $override
401 public function addValue( $path, $name, $value, $flags = 0 ) {
402 $arr = &$this->path( $path, ( $flags & ApiResult
::ADD_ON_TOP
) ?
'prepend' : 'append' );
404 if ( $this->checkingSize
&& !( $flags & ApiResult
::NO_SIZE_CHECK
) ) {
405 $newsize = $this->size + self
::valueSize( $value );
406 if ( $this->maxSize
!== false && $newsize > $this->maxSize
) {
407 /// @todo Add i18n message when replacing calls to ->setWarning()
408 $msg = new ApiRawMessage( 'This result was truncated because it would otherwise ' .
409 ' be larger than the limit of $1 bytes', 'truncatedresult' );
410 $msg->numParams( $this->maxSize
);
411 $this->errorFormatter
->addWarning( 'result', $msg );
414 $this->size
= $newsize;
417 self
::setValue( $arr, $name, $value, $flags );
422 * Remove an output value to the array by name.
423 * @param array &$arr To remove $value from
424 * @param string|int $name Index of $arr to remove
425 * @return mixed Old value, or null
427 public static function unsetValue( array &$arr, $name ) {
429 if ( isset( $arr[$name] ) ) {
431 unset( $arr[$name] );
437 * Remove value from the output data at the given path.
440 * @param array|string|null $path See ApiResult::addValue()
441 * @param string|int|null $name Index to remove at $path.
442 * If null, $path itself is removed.
443 * @param int $flags Flags used when adding the value
444 * @return mixed Old value, or null
446 public function removeValue( $path, $name, $flags = 0 ) {
447 $path = (array)$path;
448 if ( $name === null ) {
450 throw new InvalidArgumentException( 'Cannot remove the data root' );
452 $name = array_pop( $path );
454 $ret = self
::unsetValue( $this->path( $path, 'dummy' ), $name );
455 if ( $this->checkingSize
&& !( $flags & ApiResult
::NO_SIZE_CHECK
) ) {
456 $newsize = $this->size
- self
::valueSize( $ret );
457 $this->size
= max( $newsize, 0 );
463 * Add an output value to the array by name and mark as META_CONTENT.
466 * @param array &$arr To add $value to
467 * @param string|int $name Index of $arr to add $value at.
468 * @param mixed $value
469 * @param int $flags Zero or more OR-ed flags like OVERRIDE | ADD_ON_TOP.
471 public static function setContentValue( array &$arr, $name, $value, $flags = 0 ) {
472 if ( $name === null ) {
473 throw new InvalidArgumentException( 'Content value must be named' );
475 self
::setContentField( $arr, $name, $flags );
476 self
::setValue( $arr, $name, $value, $flags );
480 * Add value to the output data at the given path and mark as META_CONTENT
483 * @param array|string|null $path See ApiResult::addValue()
484 * @param string|int $name See ApiResult::setValue()
485 * @param mixed $value
486 * @param int $flags Zero or more OR-ed flags like OVERRIDE | ADD_ON_TOP.
487 * @return bool True if $value fits in the result, false if not
489 public function addContentValue( $path, $name, $value, $flags = 0 ) {
490 if ( $name === null ) {
491 throw new InvalidArgumentException( 'Content value must be named' );
493 $this->addContentField( $path, $name, $flags );
494 $this->addValue( $path, $name, $value, $flags );
498 * Add the numeric limit for a limit=max to the result.
501 * @param string $moduleName
504 public function addParsedLimit( $moduleName, $limit ) {
505 // Add value, allowing overwriting
506 $this->addValue( 'limits', $moduleName, $limit,
507 ApiResult
::OVERRIDE | ApiResult
::NO_SIZE_CHECK
);
512 /************************************************************************//**
518 * Set the name of the content field name (META_CONTENT)
522 * @param string|int $name Name of the field
523 * @param int $flags Zero or more OR-ed flags like OVERRIDE | ADD_ON_TOP.
525 public static function setContentField( array &$arr, $name, $flags = 0 ) {
526 if ( isset( $arr[self
::META_CONTENT
] ) &&
527 isset( $arr[$arr[self
::META_CONTENT
]] ) &&
528 !( $flags & self
::OVERRIDE
)
530 throw new RuntimeException(
531 "Attempting to set content element as $name when " . $arr[self
::META_CONTENT
] .
532 " is already set as the content element"
535 $arr[self
::META_CONTENT
] = $name;
539 * Set the name of the content field name (META_CONTENT)
542 * @param array|string|null $path See ApiResult::addValue()
543 * @param string|int $name Name of the field
544 * @param int $flags Zero or more OR-ed flags like OVERRIDE | ADD_ON_TOP.
546 public function addContentField( $path, $name, $flags = 0 ) {
547 $arr = &$this->path( $path, ( $flags & ApiResult
::ADD_ON_TOP
) ?
'prepend' : 'append' );
548 self
::setContentField( $arr, $name, $flags );
552 * Causes the elements with the specified names to be output as
553 * subelements rather than attributes.
554 * @since 1.25 is static
556 * @param array|string|int $names The element name(s) to be output as subelements
558 public static function setSubelementsList( array &$arr, $names ) {
559 if ( !isset( $arr[self
::META_SUBELEMENTS
] ) ) {
560 $arr[self
::META_SUBELEMENTS
] = (array)$names;
562 $arr[self
::META_SUBELEMENTS
] = array_merge( $arr[self
::META_SUBELEMENTS
], (array)$names );
567 * Causes the elements with the specified names to be output as
568 * subelements rather than attributes.
570 * @param array|string|null $path See ApiResult::addValue()
571 * @param array|string|int $names The element name(s) to be output as subelements
573 public function addSubelementsList( $path, $names ) {
574 $arr = &$this->path( $path );
575 self
::setSubelementsList( $arr, $names );
579 * Causes the elements with the specified names to be output as
580 * attributes (when possible) rather than as subelements.
583 * @param array|string|int $names The element name(s) to not be output as subelements
585 public static function unsetSubelementsList( array &$arr, $names ) {
586 if ( isset( $arr[self
::META_SUBELEMENTS
] ) ) {
587 $arr[self
::META_SUBELEMENTS
] = array_diff( $arr[self
::META_SUBELEMENTS
], (array)$names );
592 * Causes the elements with the specified names to be output as
593 * attributes (when possible) rather than as subelements.
595 * @param array|string|null $path See ApiResult::addValue()
596 * @param array|string|int $names The element name(s) to not be output as subelements
598 public function removeSubelementsList( $path, $names ) {
599 $arr = &$this->path( $path );
600 self
::unsetSubelementsList( $arr, $names );
604 * Set the tag name for numeric-keyed values in XML format
605 * @since 1.25 is static
607 * @param string $tag Tag name
609 public static function setIndexedTagName( array &$arr, $tag ) {
610 if ( !is_string( $tag ) ) {
611 throw new InvalidArgumentException( 'Bad tag name' );
613 $arr[self
::META_INDEXED_TAG_NAME
] = $tag;
617 * Set the tag name for numeric-keyed values in XML format
619 * @param array|string|null $path See ApiResult::addValue()
620 * @param string $tag Tag name
622 public function addIndexedTagName( $path, $tag ) {
623 $arr = &$this->path( $path );
624 self
::setIndexedTagName( $arr, $tag );
628 * Set indexed tag name on $arr and all subarrays
632 * @param string $tag Tag name
634 public static function setIndexedTagNameRecursive( array &$arr, $tag ) {
635 if ( !is_string( $tag ) ) {
636 throw new InvalidArgumentException( 'Bad tag name' );
638 $arr[self
::META_INDEXED_TAG_NAME
] = $tag;
639 foreach ( $arr as $k => &$v ) {
640 if ( !self
::isMetadataKey( $k ) && is_array( $v ) ) {
641 self
::setIndexedTagNameRecursive( $v, $tag );
647 * Set indexed tag name on $path and all subarrays
650 * @param array|string|null $path See ApiResult::addValue()
651 * @param string $tag Tag name
653 public function addIndexedTagNameRecursive( $path, $tag ) {
654 $arr = &$this->path( $path );
655 self
::setIndexedTagNameRecursive( $arr, $tag );
659 * Preserve specified keys.
661 * This prevents XML name mangling and preventing keys from being removed
662 * by self::stripMetadata().
666 * @param array|string $names The element name(s) to preserve
668 public static function setPreserveKeysList( array &$arr, $names ) {
669 if ( !isset( $arr[self
::META_PRESERVE_KEYS
] ) ) {
670 $arr[self
::META_PRESERVE_KEYS
] = (array)$names;
672 $arr[self
::META_PRESERVE_KEYS
] = array_merge( $arr[self
::META_PRESERVE_KEYS
], (array)$names );
677 * Preserve specified keys.
679 * @see self::setPreserveKeysList()
680 * @param array|string|null $path See ApiResult::addValue()
681 * @param array|string $names The element name(s) to preserve
683 public function addPreserveKeysList( $path, $names ) {
684 $arr = &$this->path( $path );
685 self
::setPreserveKeysList( $arr, $names );
689 * Don't preserve specified keys.
691 * @see self::setPreserveKeysList()
693 * @param array|string $names The element name(s) to not preserve
695 public static function unsetPreserveKeysList( array &$arr, $names ) {
696 if ( isset( $arr[self
::META_PRESERVE_KEYS
] ) ) {
697 $arr[self
::META_PRESERVE_KEYS
] = array_diff( $arr[self
::META_PRESERVE_KEYS
], (array)$names );
702 * Don't preserve specified keys.
704 * @see self::setPreserveKeysList()
705 * @param array|string|null $path See ApiResult::addValue()
706 * @param array|string $names The element name(s) to not preserve
708 public function removePreserveKeysList( $path, $names ) {
709 $arr = &$this->path( $path );
710 self
::unsetPreserveKeysList( $arr, $names );
714 * Set the array data type
718 * @param string $type See ApiResult::META_TYPE
719 * @param string $kvpKeyName See ApiResult::META_KVP_KEY_NAME
721 public static function setArrayType( array &$arr, $type, $kvpKeyName = null ) {
722 if ( !in_array( $type, array(
723 'default', 'array', 'assoc', 'kvp', 'BCarray', 'BCassoc', 'BCkvp'
725 throw new InvalidArgumentException( 'Bad type' );
727 $arr[self
::META_TYPE
] = $type;
728 if ( is_string( $kvpKeyName ) ) {
729 $arr[self
::META_KVP_KEY_NAME
] = $kvpKeyName;
734 * Set the array data type for a path
736 * @param array|string|null $path See ApiResult::addValue()
737 * @param string $type See ApiResult::META_TYPE
738 * @param string $kvpKeyName See ApiResult::META_KVP_KEY_NAME
740 public function addArrayType( $path, $tag, $kvpKeyName = null ) {
741 $arr = &$this->path( $path );
742 self
::setArrayType( $arr, $tag, $kvpKeyName );
746 * Set the array data type recursively
749 * @param string $type See ApiResult::META_TYPE
750 * @param string $kvpKeyName See ApiResult::META_KVP_KEY_NAME
752 public static function setArrayTypeRecursive( array &$arr, $type, $kvpKeyName = null ) {
753 self
::setArrayType( $arr, $type, $kvpKeyName );
754 foreach ( $arr as $k => &$v ) {
755 if ( !self
::isMetadataKey( $k ) && is_array( $v ) ) {
756 self
::setArrayTypeRecursive( $v, $type, $kvpKeyName );
762 * Set the array data type for a path recursively
764 * @param array|string|null $path See ApiResult::addValue()
765 * @param string $type See ApiResult::META_TYPE
766 * @param string $kvpKeyName See ApiResult::META_KVP_KEY_NAME
768 public function addArrayTypeRecursive( $path, $tag, $kvpKeyName = null ) {
769 $arr = &$this->path( $path );
770 self
::setArrayTypeRecursive( $arr, $tag, $kvpKeyName );
775 /************************************************************************//**
781 * Test whether a key should be considered metadata
786 public static function isMetadataKey( $key ) {
787 return substr( $key, 0, 1 ) === '_';
791 * Apply transformations to an array, returning the transformed array.
793 * @see ApiResult::getResultData()
796 * @param array $transforms
797 * @return array|object
799 protected static function applyTransformations( array $dataIn, array $transforms ) {
800 $strip = isset( $transforms['Strip'] ) ?
$transforms['Strip'] : 'none';
801 if ( $strip === 'base' ) {
802 $transforms['Strip'] = 'none';
804 $transformTypes = isset( $transforms['Types'] ) ?
$transforms['Types'] : null;
805 if ( $transformTypes !== null && !is_array( $transformTypes ) ) {
806 throw new InvalidArgumentException( __METHOD__
. ':Value for "Types" must be an array' );
810 $data = self
::stripMetadataNonRecursive( $dataIn, $metadata );
812 if ( isset( $transforms['Custom'] ) ) {
813 if ( !is_callable( $transforms['Custom'] ) ) {
814 throw new InvalidArgumentException( __METHOD__
. ': Value for "Custom" must be callable' );
816 call_user_func_array( $transforms['Custom'], array( &$data, &$metadata ) );
819 if ( ( isset( $transforms['BC'] ) ||
$transformTypes !== null ) &&
820 isset( $metadata[self
::META_TYPE
] ) && $metadata[self
::META_TYPE
] === 'BCkvp' &&
821 !isset( $metadata[self
::META_KVP_KEY_NAME
] )
823 throw new UnexpectedValueException( 'Type "BCkvp" used without setting ' .
824 'ApiResult::META_KVP_KEY_NAME metadata item' );
827 // BC transformations
830 if ( isset( $transforms['BC'] ) ) {
831 if ( !is_array( $transforms['BC'] ) ) {
832 throw new InvalidArgumentException( __METHOD__
. ':Value for "BC" must be an array' );
834 if ( !in_array( 'nobool', $transforms['BC'], true ) ) {
835 $boolKeys = isset( $metadata[self
::META_BC_BOOLS
] )
836 ?
array_flip( $metadata[self
::META_BC_BOOLS
] )
840 if ( !in_array( 'no*', $transforms['BC'], true ) &&
841 isset( $metadata[self
::META_CONTENT
] ) && $metadata[self
::META_CONTENT
] !== '*'
843 $k = $metadata[self
::META_CONTENT
];
844 $data['*'] = $data[$k];
846 $metadata[self
::META_CONTENT
] = '*';
849 if ( !in_array( 'nosub', $transforms['BC'], true ) &&
850 isset( $metadata[self
::META_BC_SUBELEMENTS
] )
852 foreach ( $metadata[self
::META_BC_SUBELEMENTS
] as $k ) {
853 if ( isset( $data[$k] ) ) {
856 self
::META_CONTENT
=> '*',
857 self
::META_TYPE
=> 'assoc',
863 if ( isset( $metadata[self
::META_TYPE
] ) ) {
864 switch ( $metadata[self
::META_TYPE
] ) {
867 $metadata[self
::META_TYPE
] = 'default';
870 $transformTypes['ArmorKVP'] = $metadata[self
::META_KVP_KEY_NAME
];
876 // Figure out type, do recursive calls, and do boolean transform if necessary
877 $defaultType = 'array';
879 foreach ( $data as $k => &$v ) {
880 $v = is_array( $v ) ? self
::applyTransformations( $v, $transforms ) : $v;
881 if ( $boolKeys !== null && is_bool( $v ) && !isset( $boolKeys[$k] ) ) {
888 if ( is_string( $k ) ) {
889 $defaultType = 'assoc';
890 } elseif ( $k > $maxKey ) {
896 // Determine which metadata to keep
900 $keepMetadata = array();
903 $keepMetadata = &$metadata;
906 $keepMetadata = array_intersect_key( $metadata, array(
907 self
::META_INDEXED_TAG_NAME
=> 1,
908 self
::META_SUBELEMENTS
=> 1,
912 throw new InvalidArgumentException( __METHOD__
. ': Unknown value for "Strip"' );
915 // Type transformation
916 if ( $transformTypes !== null ) {
917 if ( $defaultType === 'array' && $maxKey !== count( $data ) - 1 ) {
918 $defaultType = 'assoc';
921 // Override type, if provided
922 $type = $defaultType;
923 if ( isset( $metadata[self
::META_TYPE
] ) && $metadata[self
::META_TYPE
] !== 'default' ) {
924 $type = $metadata[self
::META_TYPE
];
926 if ( ( $type === 'kvp' ||
$type === 'BCkvp' ) &&
927 empty( $transformTypes['ArmorKVP'] )
930 } elseif ( $type === 'BCarray' ) {
932 } elseif ( $type === 'BCassoc' ) {
936 // Apply transformation
939 $metadata[self
::META_TYPE
] = 'assoc';
940 $data +
= $keepMetadata;
941 return empty( $transformTypes['AssocAsObject'] ) ?
$data : (object)$data;
945 $data = array_values( $data );
946 $metadata[self
::META_TYPE
] = 'array';
947 return $data +
$keepMetadata;
951 $key = isset( $metadata[self
::META_KVP_KEY_NAME
] )
952 ?
$metadata[self
::META_KVP_KEY_NAME
]
953 : $transformTypes['ArmorKVP'];
954 $valKey = isset( $transforms['BC'] ) ?
'*' : 'value';
955 $assocAsObject = !empty( $transformTypes['AssocAsObject'] );
956 $merge = !empty( $metadata[self
::META_KVP_MERGE
] );
959 foreach ( $data as $k => $v ) {
960 if ( $merge && ( is_array( $v ) ||
is_object( $v ) ) ) {
962 if ( isset( $vArr[self
::META_TYPE
] ) ) {
963 $mergeType = $vArr[self
::META_TYPE
];
964 } elseif ( is_object( $v ) ) {
965 $mergeType = 'assoc';
967 $keys = array_keys( $vArr );
968 sort( $keys, SORT_NUMERIC
);
969 $mergeType = ( $keys === array_keys( $keys ) ) ?
'array' : 'assoc';
974 if ( $mergeType === 'assoc' ) {
975 $item = $vArr +
array(
978 if ( $strip === 'none' ) {
979 self
::setPreserveKeysList( $item, array( $key ) );
986 if ( $strip === 'none' ) {
988 self
::META_PRESERVE_KEYS
=> array( $key ),
989 self
::META_CONTENT
=> $valKey,
990 self
::META_TYPE
=> 'assoc',
994 $ret[] = $assocAsObject ?
(object)$item : $item;
996 $metadata[self
::META_TYPE
] = 'array';
998 return $ret +
$keepMetadata;
1001 throw new UnexpectedValueException( "Unknown type '$type'" );
1004 return $data +
$keepMetadata;
1009 * Recursively remove metadata keys from a data array or object
1011 * Note this removes all potential metadata keys, not just the defined
1015 * @param array|object $data
1016 * @return array|object
1018 public static function stripMetadata( $data ) {
1019 if ( is_array( $data ) ||
is_object( $data ) ) {
1020 $isObj = is_object( $data );
1022 $data = (array)$data;
1024 $preserveKeys = isset( $data[self
::META_PRESERVE_KEYS
] )
1025 ?
(array)$data[self
::META_PRESERVE_KEYS
]
1027 foreach ( $data as $k => $v ) {
1028 if ( self
::isMetadataKey( $k ) && !in_array( $k, $preserveKeys, true ) ) {
1030 } elseif ( is_array( $v ) ||
is_object( $v ) ) {
1031 $data[$k] = self
::stripMetadata( $v );
1035 $data = (object)$data;
1042 * Remove metadata keys from a data array or object, non-recursive
1044 * Note this removes all potential metadata keys, not just the defined
1048 * @param array|object $data
1049 * @param array &$metadata Store metadata here, if provided
1050 * @return array|object
1052 public static function stripMetadataNonRecursive( $data, &$metadata = null ) {
1053 if ( !is_array( $metadata ) ) {
1054 $metadata = array();
1056 if ( is_array( $data ) ||
is_object( $data ) ) {
1057 $isObj = is_object( $data );
1059 $data = (array)$data;
1061 $preserveKeys = isset( $data[self
::META_PRESERVE_KEYS
] )
1062 ?
(array)$data[self
::META_PRESERVE_KEYS
]
1064 foreach ( $data as $k => $v ) {
1065 if ( self
::isMetadataKey( $k ) && !in_array( $k, $preserveKeys, true ) ) {
1071 $data = (object)$data;
1078 * Get the 'real' size of a result item. This means the strlen() of the item,
1079 * or the sum of the strlen()s of the elements if the item is an array.
1080 * @note Once the deprecated public self::size is removed, we can rename
1081 * this back to a less awkward name.
1082 * @param mixed $value
1085 private static function valueSize( $value ) {
1087 if ( is_array( $value ) ||
1088 is_object( $value ) && !is_callable( array( $value, '__toString' ) )
1090 foreach ( $value as $k => $v ) {
1091 if ( !self
::isMetadataKey( $s ) ) {
1092 $s +
= self
::valueSize( $v );
1095 } elseif ( is_scalar( $value ) ) {
1096 $s = strlen( $value );
1103 * Return a reference to the internal data at $path
1105 * @param array|string|null $path
1106 * @param string $create
1107 * If 'append', append empty arrays.
1108 * If 'prepend', prepend empty arrays.
1109 * If 'dummy', return a dummy array.
1110 * Else, raise an error.
1113 private function &path( $path, $create = 'append' ) {
1114 $path = (array)$path;
1115 $ret = &$this->data
;
1116 foreach ( $path as $i => $k ) {
1117 if ( !isset( $ret[$k] ) ) {
1118 switch ( $create ) {
1123 $ret = array( $k => array() ) +
$ret;
1129 $fail = join( '.', array_slice( $path, 0, $i +
1 ) );
1130 throw new InvalidArgumentException( "Path $fail does not exist" );
1133 if ( !is_array( $ret[$k] ) ) {
1134 $fail = join( '.', array_slice( $path, 0, $i +
1 ) );
1135 throw new InvalidArgumentException( "Path $fail is not an array" );
1143 * Add the correct metadata to an array of vars we want to export through
1146 * @param array $vars
1147 * @param boolean $forceHash
1150 public static function addMetadataToResultVars( $vars, $forceHash = true ) {
1151 // Process subarrays and determine if this is a JS [] or {}
1155 foreach ( $vars as $k => $v ) {
1156 if ( is_array( $v ) ||
is_object( $v ) ) {
1157 $vars[$k] = ApiResult
::addMetadataToResultVars( (array)$v, is_object( $v ) );
1158 } elseif ( is_bool( $v ) ) {
1159 // Better here to use real bools even in BC formats
1162 if ( is_string( $k ) ) {
1164 } elseif ( $k > $maxKey ) {
1168 if ( !$hash && $maxKey !== count( $vars ) - 1 ) {
1172 // Set metadata appropriately
1174 // Get the list of keys we actually care about. Unfortunately, we can't support
1175 // certain keys that conflict with ApiResult metadata.
1176 $keys = array_diff( array_keys( $vars ), array(
1177 ApiResult
::META_TYPE
, ApiResult
::META_PRESERVE_KEYS
, ApiResult
::META_KVP_KEY_NAME
,
1178 ApiResult
::META_INDEXED_TAG_NAME
, ApiResult
::META_BC_BOOLS
1182 ApiResult
::META_TYPE
=> 'kvp',
1183 ApiResult
::META_KVP_KEY_NAME
=> 'key',
1184 ApiResult
::META_PRESERVE_KEYS
=> $keys,
1185 ApiResult
::META_BC_BOOLS
=> $bools,
1186 ApiResult
::META_INDEXED_TAG_NAME
=> 'var',
1190 ApiResult
::META_TYPE
=> 'array',
1191 ApiResult
::META_BC_BOOLS
=> $bools,
1192 ApiResult
::META_INDEXED_TAG_NAME
=> 'value',
1199 /************************************************************************//**
1205 * Call this function when special elements such as '_element'
1206 * are needed by the formatter, for example in XML printing.
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 // Can't wfDeprecated() here, since we need to set this flag from
1213 // ApiMain for BC with stuff using self::getIsRawMode as
1214 // "self::getIsXMLMode".
1215 $this->isRawMode
= $flag;
1219 * Returns true whether the formatter requested raw data.
1220 * @deprecated since 1.25, you shouldn't have been using it in the first place
1223 public function getIsRawMode() {
1224 /// @todo: After Wikibase stops calling this, warn
1225 return $this->isRawMode
;
1229 * Get the result's internal data array (read-only)
1230 * @deprecated since 1.25, use $this->getResultData() instead
1233 public function getData() {
1234 wfDeprecated( __METHOD__
, '1.25' );
1235 return $this->getResultData( null, array(
1238 'Strip' => $this->isRawMode ?
'bc' : 'all',
1243 * Disable size checking in addValue(). Don't use this unless you
1244 * REALLY know what you're doing. Values added while size checking
1245 * was disabled will not be counted (ever)
1246 * @deprecated since 1.24, use ApiResult::NO_SIZE_CHECK
1248 public function disableSizeCheck() {
1249 wfDeprecated( __METHOD__
, '1.24' );
1250 $this->checkingSize
= false;
1254 * Re-enable size checking in addValue()
1255 * @deprecated since 1.24, use ApiResult::NO_SIZE_CHECK
1257 public function enableSizeCheck() {
1258 wfDeprecated( __METHOD__
, '1.24' );
1259 $this->checkingSize
= true;
1263 * Alias for self::setValue()
1265 * @since 1.21 int $flags replaced boolean $override
1266 * @deprecated since 1.25, use self::setValue() instead
1267 * @param array $arr To add $value to
1268 * @param string $name Index of $arr to add $value at
1269 * @param mixed $value
1270 * @param int $flags Zero or more OR-ed flags like OVERRIDE | ADD_ON_TOP.
1271 * This parameter used to be boolean, and the value of OVERRIDE=1 was
1272 * specifically chosen so that it would be backwards compatible with the
1273 * new method signature.
1275 public static function setElement( &$arr, $name, $value, $flags = 0 ) {
1276 wfDeprecated( __METHOD__
, '1.25' );
1277 return self
::setValue( $arr, $name, $value, $flags );
1281 * Adds a content element to an array.
1282 * Use this function instead of hardcoding the '*' element.
1283 * @deprecated since 1.25, use self::setContentValue() instead
1284 * @param array $arr To add the content element to
1285 * @param mixed $value
1286 * @param string $subElemName When present, content element is created
1287 * as a sub item of $arr. Use this parameter to create elements in
1288 * format "<elem>text</elem>" without attributes.
1290 public static function setContent( &$arr, $value, $subElemName = null ) {
1291 wfDeprecated( __METHOD__
, '1.25' );
1292 if ( is_array( $value ) ) {
1293 throw new InvalidArgumentException( __METHOD__
. ': Bad parameter' );
1295 if ( is_null( $subElemName ) ) {
1296 self
::setContentValue( $arr, 'content', $value );
1298 if ( !isset( $arr[$subElemName] ) ) {
1299 $arr[$subElemName] = array();
1301 self
::setContentValue( $arr[$subElemName], 'content', $value );
1306 * Set indexed tag name on all subarrays of $arr
1308 * Does not set the tag name for $arr itself.
1310 * @deprecated since 1.25, use self::setIndexedTagNameRecursive() instead
1312 * @param string $tag Tag name
1314 public function setIndexedTagName_recursive( &$arr, $tag ) {
1315 wfDeprecated( __METHOD__
, '1.25' );
1316 if ( !is_array( $arr ) ) {
1319 if ( !is_string( $tag ) ) {
1320 throw new InvalidArgumentException( 'Bad tag name' );
1322 foreach ( $arr as $k => &$v ) {
1323 if ( !self
::isMetadataKey( $k ) && is_array( $v ) ) {
1324 $v[self
::META_INDEXED_TAG_NAME
] = $tag;
1325 $this->setIndexedTagName_recursive( $v, $tag );
1331 * Alias for self::addIndexedTagName()
1332 * @deprecated since 1.25, use $this->addIndexedTagName() instead
1333 * @param array $path Path to the array, like addValue()'s $path
1334 * @param string $tag
1336 public function setIndexedTagName_internal( $path, $tag ) {
1337 wfDeprecated( __METHOD__
, '1.25' );
1338 $this->addIndexedTagName( $path, $tag );
1342 * Alias for self::addParsedLimit()
1343 * @deprecated since 1.25, use $this->addParsedLimit() instead
1344 * @param string $moduleName
1347 public function setParsedLimit( $moduleName, $limit ) {
1348 wfDeprecated( __METHOD__
, '1.25' );
1349 $this->addParsedLimit( $moduleName, $limit );
1353 * Set the ApiMain for use by $this->beginContinuation()
1355 * @deprecated for backwards compatibility only, do not use
1356 * @param ApiMain $main
1358 public function setMainForContinuation( ApiMain
$main ) {
1359 $this->mainForContinuation
= $main;
1363 * Parse a 'continue' parameter and return status information.
1365 * This must be balanced by a call to endContinuation().
1368 * @deprecated since 1.25, use ApiContinuationManager instead
1369 * @param string|null $continue
1370 * @param ApiBase[] $allModules
1371 * @param array $generatedModules
1374 public function beginContinuation(
1375 $continue, array $allModules = array(), array $generatedModules = array()
1377 wfDeprecated( __METHOD__
, '1.25' );
1378 if ( $this->mainForContinuation
->getContinuationManager() ) {
1379 throw new UnexpectedValueException(
1380 __METHOD__
. ': Continuation already in progress from ' .
1381 $this->mainForContinuation
->getContinuationManager()->getSource()
1385 // Ugh. If $continue doesn't match that in the request, temporarily
1386 // replace the request when creating the ApiContinuationManager.
1387 if ( $continue === null ) {
1390 if ( $this->mainForContinuation
->getVal( 'continue', '' ) !== $continue ) {
1391 $oldCtx = $this->mainForContinuation
->getContext();
1392 $newCtx = new DerivativeContext( $oldCtx );
1393 $newCtx->setRequest( new DerivativeRequest(
1394 $oldCtx->getRequest(),
1395 array( 'continue' => $continue ) +
$oldCtx->getRequest()->getValues(),
1396 $oldCtx->getRequest()->wasPosted()
1398 $this->mainForContinuation
->setContext( $newCtx );
1399 $reset = new ScopedCallback(
1400 array( $this->mainForContinuation
, 'setContext' ),
1404 $manager = new ApiContinuationManager(
1405 $this->mainForContinuation
, $allModules, $generatedModules
1409 $this->mainForContinuation
->setContinuationManager( $manager );
1412 $manager->isGeneratorDone(),
1413 $manager->getRunModules(),
1419 * @deprecated since 1.25, use ApiContinuationManager instead
1420 * @param ApiBase $module
1421 * @param string $paramName
1422 * @param string|array $paramValue
1424 public function setContinueParam( ApiBase
$module, $paramName, $paramValue ) {
1425 wfDeprecated( __METHOD__
, '1.25' );
1426 if ( $this->mainForContinuation
->getContinuationManager() ) {
1427 $this->mainForContinuation
->getContinuationManager()->addContinueParam(
1428 $module, $paramName, $paramValue
1435 * @deprecated since 1.25, use ApiContinuationManager instead
1436 * @param ApiBase $module
1437 * @param string $paramName
1438 * @param string|array $paramValue
1440 public function setGeneratorContinueParam( ApiBase
$module, $paramName, $paramValue ) {
1441 wfDeprecated( __METHOD__
, '1.25' );
1442 if ( $this->mainForContinuation
->getContinuationManager() ) {
1443 $this->mainForContinuation
->getContinuationManager()->addGeneratorContinueParam(
1444 $module, $paramName, $paramValue
1450 * Close continuation, writing the data into the result
1452 * @deprecated since 1.25, use ApiContinuationManager instead
1453 * @param string $style 'standard' for the new style since 1.21, 'raw' for
1454 * the style used in 1.20 and earlier.
1456 public function endContinuation( $style = 'standard' ) {
1457 wfDeprecated( __METHOD__
, '1.25' );
1458 if ( !$this->mainForContinuation
->getContinuationManager() ) {
1462 if ( $style === 'raw' ) {
1463 $data = $this->mainForContinuation
->getContinuationManager()->getRawContinuation();
1465 $this->addValue( null, 'query-continue', $data, self
::ADD_ON_TOP | self
::NO_SIZE_CHECK
);
1468 $this->mainForContinuation
->getContinuationManager()->setContinuationIntoResult( $this );
1473 * No-op, this is now checked on insert.
1474 * @deprecated since 1.25
1476 public function cleanUpUTF8() {
1477 wfDeprecated( __METHOD__
, '1.25' );
1481 * Get the 'real' size of a result item. This means the strlen() of the item,
1482 * or the sum of the strlen()s of the elements if the item is an array.
1483 * @deprecated since 1.25, no external users known and there doesn't seem
1484 * to be any case for such use over just checking the return value from the
1486 * @param mixed $value
1489 public static function size( $value ) {
1490 wfDeprecated( __METHOD__
, '1.25' );
1491 return self
::valueSize( $value );
1495 * Converts a Status object to an array suitable for addValue
1496 * @deprecated since 1.25, use ApiErrorFormatter::arrayFromStatus()
1497 * @param Status $status
1498 * @param string $errorType
1501 public function convertStatusToArray( $status, $errorType = 'error' ) {
1502 wfDeprecated( __METHOD__
, '1.25' );
1503 return $this->errorFormatter
->arrayFromStatus( $status, $errorType );
1510 * For really cool vim folding this needs to be at the end:
1511 * vim: foldmarker=@{,@} foldmethod=marker