Merge "Add tests for WikiMap and WikiReference"
[lhc/web/wiklou.git] / includes / api / ApiResult.php
1 <?php
2 /**
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.
7 *
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.
12 *
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
17 *
18 * @file
19 */
20
21 /**
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.
26 *
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.
29 *
30 * @since 1.25 this is no longer a subclass of ApiBase
31 * @ingroup API
32 */
33 class ApiResult implements ApiSerializable {
34
35 /**
36 * Override existing value in addValue(), setValue(), and similar functions
37 * @since 1.21
38 */
39 const OVERRIDE = 1;
40
41 /**
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.
45 * @since 1.21
46 */
47 const ADD_ON_TOP = 2;
48
49 /**
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.
54 * @since 1.24
55 */
56 const NO_SIZE_CHECK = 4;
57
58 /**
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
61 * probably wrong.
62 * @since 1.25
63 */
64 const NO_VALIDATE = 12;
65
66 /**
67 * Key for the 'indexed tag name' metadata item. Value is string.
68 * @since 1.25
69 */
70 const META_INDEXED_TAG_NAME = '_element';
71
72 /**
73 * Key for the 'subelements' metadata item. Value is string[].
74 * @since 1.25
75 */
76 const META_SUBELEMENTS = '_subelements';
77
78 /**
79 * Key for the 'preserve keys' metadata item. Value is string[].
80 * @since 1.25
81 */
82 const META_PRESERVE_KEYS = '_preservekeys';
83
84 /**
85 * Key for the 'content' metadata item. Value is string.
86 * @since 1.25
87 */
88 const META_CONTENT = '_content';
89
90 /**
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.
106 * @since 1.25
107 */
108 const META_TYPE = '_type';
109
110 /**
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>.
114 * Value is string.
115 * @since 1.25
116 */
117 const META_KVP_KEY_NAME = '_kvpkeyname';
118
119 /**
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"}}.
124 * Value is boolean.
125 * @since 1.26
126 */
127 const META_KVP_MERGE = '_kvpmerge';
128
129 /**
130 * Key for the 'BC bools' metadata item. Value is string[].
131 * Note no setter is provided.
132 * @since 1.25
133 */
134 const META_BC_BOOLS = '_BC_bools';
135
136 /**
137 * Key for the 'BC subelements' metadata item. Value is string[].
138 * Note no setter is provided.
139 * @since 1.25
140 */
141 const META_BC_SUBELEMENTS = '_BC_subelements';
142
143 private $data, $size, $maxSize;
144 private $errorFormatter;
145
146 // Deprecated fields
147 private $isRawMode, $checkingSize, $mainForContinuation;
148
149 /**
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
152 */
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' );
159 }
160
161 $this->maxSize = $maxSize;
162 $this->isRawMode = false;
163 $this->checkingSize = true;
164 $this->reset();
165 }
166
167 /**
168 * Set the error formatter
169 * @since 1.25
170 * @param ApiErrorFormatter $formatter
171 */
172 public function setErrorFormatter( ApiErrorFormatter $formatter ) {
173 $this->errorFormatter = $formatter;
174 }
175
176 /**
177 * Allow for adding one ApiResult into another
178 * @since 1.25
179 * @return mixed
180 */
181 public function serializeForApiResult() {
182 return $this->data;
183 }
184
185 /************************************************************************//**
186 * @name Content
187 * @{
188 */
189
190 /**
191 * Clear the current result data.
192 */
193 public function reset() {
194 $this->data = array(
195 self::META_TYPE => 'assoc', // Usually what's desired
196 );
197 $this->size = 0;
198 }
199
200 /**
201 * Get the result data array
202 *
203 * The returned value should be considered read-only.
204 *
205 * Transformations include:
206 *
207 * Custom: (callable) Applied before other transformations. Signature is
208 * function ( &$data, &$metadata ), return value is ignored. Called for
209 * each nested array.
210 *
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
219 * array.
220 * - Tags listed in META_BC_SUBELEMENTS will have their values changed to
221 * array( '*' => $value ). This may be skipped by including 'nosub' in
222 * the value array.
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).
227 *
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'
231 * as objects.
232 * - ArmorKVP: (string) If provided, transform arrays with META_TYPE 'kvp'
233 * and 'BCkvp' into arrays of two-element arrays, something like this:
234 * $output = array();
235 * foreach ( $input as $key => $value ) {
236 * $pair = array();
237 * $pair[$META_KVP_KEY_NAME ?: $ArmorKVP_value] = $key;
238 * ApiResult::setContentValue( $pair, 'value', $value );
239 * $output[] = $pair;
240 * }
241 *
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.
247 *
248 * @since 1.25
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
252 */
253 public function getResultData( $path = array(), $transforms = array() ) {
254 $path = (array)$path;
255 if ( !$path ) {
256 return self::applyTransformations( $this->data, $transforms );
257 }
258
259 $last = array_pop( $path );
260 $ret = &$this->path( $path, 'dummy' );
261 if ( !isset( $ret[$last] ) ) {
262 return null;
263 } elseif ( is_array( $ret[$last] ) ) {
264 return self::applyTransformations( $ret[$last], $transforms );
265 } else {
266 return $ret[$last];
267 }
268 }
269
270 /**
271 * Get the size of the result, i.e. the amount of bytes in it
272 * @return int
273 */
274 public function getSize() {
275 return $this->size;
276 }
277
278 /**
279 * Add an output value to the array by name.
280 *
281 * Verifies that value with the same name has not been added before.
282 *
283 * @since 1.25
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.
289 */
290 public static function setValue( array &$arr, $name, $value, $flags = 0 ) {
291 if ( ( $flags & ApiResult::NO_VALIDATE ) !== ApiResult::NO_VALIDATE ) {
292 $value = self::validateValue( $value );
293 }
294
295 if ( $name === null ) {
296 if ( $flags & ApiResult::ADD_ON_TOP ) {
297 array_unshift( $arr, $value );
298 } else {
299 array_push( $arr, $value );
300 }
301 return;
302 }
303
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;
308 } else {
309 $arr[$name] = $value;
310 }
311 } elseif ( is_array( $arr[$name] ) && is_array( $value ) ) {
312 $conflicts = array_intersect_key( $arr[$name], $value );
313 if ( !$conflicts ) {
314 $arr[$name] += $value;
315 } else {
316 $keys = join( ', ', array_keys( $conflicts ) );
317 throw new RuntimeException(
318 "Conflicting keys ($keys) when attempting to merge element $name"
319 );
320 }
321 } else {
322 throw new RuntimeException(
323 "Attempting to add element $name=$value, existing value is {$arr[$name]}"
324 );
325 }
326 }
327
328 /**
329 * Validate a value for addition to the result
330 * @param mixed $value
331 */
332 private static function validateValue( $value ) {
333 global $wgContLang;
334
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' ) ) ) {
339 $oldValue = $value;
340 $value = $value->serializeForApiResult();
341 if ( is_object( $value ) ) {
342 throw new UnexpectedValueException(
343 get_class( $oldValue ) . "::serializeForApiResult() returned an object of class " .
344 get_class( $value )
345 );
346 }
347
348 // Recursive call instead of fall-through so we can throw a
349 // better exception message.
350 try {
351 return self::validateValue( $value );
352 } catch ( Exception $ex ) {
353 throw new UnexpectedValueException(
354 get_class( $oldValue ) . "::serializeForApiResult() returned an invalid value: " .
355 $ex->getMessage(),
356 0,
357 $ex
358 );
359 }
360 } elseif ( is_callable( array( $value, '__toString' ) ) ) {
361 $value = (string)$value;
362 } else {
363 $value = (array)$value + array( self::META_TYPE => 'assoc' );
364 }
365 }
366 if ( is_array( $value ) ) {
367 foreach ( $value as $k => $v ) {
368 $value[$k] = self::validateValue( $v );
369 }
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 ) . ')';
378 }
379 throw new InvalidArgumentException( "Cannot add $type to ApiResult" );
380 }
381
382 return $value;
383 }
384
385 /**
386 * Add value to the output data at the given path.
387 *
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.
391 *
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
400 */
401 public function addValue( $path, $name, $value, $flags = 0 ) {
402 $arr = &$this->path( $path, ( $flags & ApiResult::ADD_ON_TOP ) ? 'prepend' : 'append' );
403
404 if ( $this->checkingSize && !( $flags & ApiResult::NO_SIZE_CHECK ) ) {
405 // self::valueSize needs the validated value. Then flag
406 // to not re-validate later.
407 $value = self::validateValue( $value );
408 $flags |= ApiResult::NO_VALIDATE;
409
410 $newsize = $this->size + self::valueSize( $value );
411 if ( $this->maxSize !== false && $newsize > $this->maxSize ) {
412 /// @todo Add i18n message when replacing calls to ->setWarning()
413 $msg = new ApiRawMessage( 'This result was truncated because it would otherwise ' .
414 ' be larger than the limit of $1 bytes', 'truncatedresult' );
415 $msg->numParams( $this->maxSize );
416 $this->errorFormatter->addWarning( 'result', $msg );
417 return false;
418 }
419 $this->size = $newsize;
420 }
421
422 self::setValue( $arr, $name, $value, $flags );
423 return true;
424 }
425
426 /**
427 * Remove an output value to the array by name.
428 * @param array &$arr To remove $value from
429 * @param string|int $name Index of $arr to remove
430 * @return mixed Old value, or null
431 */
432 public static function unsetValue( array &$arr, $name ) {
433 $ret = null;
434 if ( isset( $arr[$name] ) ) {
435 $ret = $arr[$name];
436 unset( $arr[$name] );
437 }
438 return $ret;
439 }
440
441 /**
442 * Remove value from the output data at the given path.
443 *
444 * @since 1.25
445 * @param array|string|null $path See ApiResult::addValue()
446 * @param string|int|null $name Index to remove at $path.
447 * If null, $path itself is removed.
448 * @param int $flags Flags used when adding the value
449 * @return mixed Old value, or null
450 */
451 public function removeValue( $path, $name, $flags = 0 ) {
452 $path = (array)$path;
453 if ( $name === null ) {
454 if ( !$path ) {
455 throw new InvalidArgumentException( 'Cannot remove the data root' );
456 }
457 $name = array_pop( $path );
458 }
459 $ret = self::unsetValue( $this->path( $path, 'dummy' ), $name );
460 if ( $this->checkingSize && !( $flags & ApiResult::NO_SIZE_CHECK ) ) {
461 $newsize = $this->size - self::valueSize( $ret );
462 $this->size = max( $newsize, 0 );
463 }
464 return $ret;
465 }
466
467 /**
468 * Add an output value to the array by name and mark as META_CONTENT.
469 *
470 * @since 1.25
471 * @param array &$arr To add $value to
472 * @param string|int $name Index of $arr to add $value at.
473 * @param mixed $value
474 * @param int $flags Zero or more OR-ed flags like OVERRIDE | ADD_ON_TOP.
475 */
476 public static function setContentValue( array &$arr, $name, $value, $flags = 0 ) {
477 if ( $name === null ) {
478 throw new InvalidArgumentException( 'Content value must be named' );
479 }
480 self::setContentField( $arr, $name, $flags );
481 self::setValue( $arr, $name, $value, $flags );
482 }
483
484 /**
485 * Add value to the output data at the given path and mark as META_CONTENT
486 *
487 * @since 1.25
488 * @param array|string|null $path See ApiResult::addValue()
489 * @param string|int $name See ApiResult::setValue()
490 * @param mixed $value
491 * @param int $flags Zero or more OR-ed flags like OVERRIDE | ADD_ON_TOP.
492 * @return bool True if $value fits in the result, false if not
493 */
494 public function addContentValue( $path, $name, $value, $flags = 0 ) {
495 if ( $name === null ) {
496 throw new InvalidArgumentException( 'Content value must be named' );
497 }
498 $this->addContentField( $path, $name, $flags );
499 $this->addValue( $path, $name, $value, $flags );
500 }
501
502 /**
503 * Add the numeric limit for a limit=max to the result.
504 *
505 * @since 1.25
506 * @param string $moduleName
507 * @param int $limit
508 */
509 public function addParsedLimit( $moduleName, $limit ) {
510 // Add value, allowing overwriting
511 $this->addValue( 'limits', $moduleName, $limit,
512 ApiResult::OVERRIDE | ApiResult::NO_SIZE_CHECK );
513 }
514
515 /**@}*/
516
517 /************************************************************************//**
518 * @name Metadata
519 * @{
520 */
521
522 /**
523 * Set the name of the content field name (META_CONTENT)
524 *
525 * @since 1.25
526 * @param array &$arr
527 * @param string|int $name Name of the field
528 * @param int $flags Zero or more OR-ed flags like OVERRIDE | ADD_ON_TOP.
529 */
530 public static function setContentField( array &$arr, $name, $flags = 0 ) {
531 if ( isset( $arr[self::META_CONTENT] ) &&
532 isset( $arr[$arr[self::META_CONTENT]] ) &&
533 !( $flags & self::OVERRIDE )
534 ) {
535 throw new RuntimeException(
536 "Attempting to set content element as $name when " . $arr[self::META_CONTENT] .
537 " is already set as the content element"
538 );
539 }
540 $arr[self::META_CONTENT] = $name;
541 }
542
543 /**
544 * Set the name of the content field name (META_CONTENT)
545 *
546 * @since 1.25
547 * @param array|string|null $path See ApiResult::addValue()
548 * @param string|int $name Name of the field
549 * @param int $flags Zero or more OR-ed flags like OVERRIDE | ADD_ON_TOP.
550 */
551 public function addContentField( $path, $name, $flags = 0 ) {
552 $arr = &$this->path( $path, ( $flags & ApiResult::ADD_ON_TOP ) ? 'prepend' : 'append' );
553 self::setContentField( $arr, $name, $flags );
554 }
555
556 /**
557 * Causes the elements with the specified names to be output as
558 * subelements rather than attributes.
559 * @since 1.25 is static
560 * @param array &$arr
561 * @param array|string|int $names The element name(s) to be output as subelements
562 */
563 public static function setSubelementsList( array &$arr, $names ) {
564 if ( !isset( $arr[self::META_SUBELEMENTS] ) ) {
565 $arr[self::META_SUBELEMENTS] = (array)$names;
566 } else {
567 $arr[self::META_SUBELEMENTS] = array_merge( $arr[self::META_SUBELEMENTS], (array)$names );
568 }
569 }
570
571 /**
572 * Causes the elements with the specified names to be output as
573 * subelements rather than attributes.
574 * @since 1.25
575 * @param array|string|null $path See ApiResult::addValue()
576 * @param array|string|int $names The element name(s) to be output as subelements
577 */
578 public function addSubelementsList( $path, $names ) {
579 $arr = &$this->path( $path );
580 self::setSubelementsList( $arr, $names );
581 }
582
583 /**
584 * Causes the elements with the specified names to be output as
585 * attributes (when possible) rather than as subelements.
586 * @since 1.25
587 * @param array &$arr
588 * @param array|string|int $names The element name(s) to not be output as subelements
589 */
590 public static function unsetSubelementsList( array &$arr, $names ) {
591 if ( isset( $arr[self::META_SUBELEMENTS] ) ) {
592 $arr[self::META_SUBELEMENTS] = array_diff( $arr[self::META_SUBELEMENTS], (array)$names );
593 }
594 }
595
596 /**
597 * Causes the elements with the specified names to be output as
598 * attributes (when possible) rather than as subelements.
599 * @since 1.25
600 * @param array|string|null $path See ApiResult::addValue()
601 * @param array|string|int $names The element name(s) to not be output as subelements
602 */
603 public function removeSubelementsList( $path, $names ) {
604 $arr = &$this->path( $path );
605 self::unsetSubelementsList( $arr, $names );
606 }
607
608 /**
609 * Set the tag name for numeric-keyed values in XML format
610 * @since 1.25 is static
611 * @param array &$arr
612 * @param string $tag Tag name
613 */
614 public static function setIndexedTagName( array &$arr, $tag ) {
615 if ( !is_string( $tag ) ) {
616 throw new InvalidArgumentException( 'Bad tag name' );
617 }
618 $arr[self::META_INDEXED_TAG_NAME] = $tag;
619 }
620
621 /**
622 * Set the tag name for numeric-keyed values in XML format
623 * @since 1.25
624 * @param array|string|null $path See ApiResult::addValue()
625 * @param string $tag Tag name
626 */
627 public function addIndexedTagName( $path, $tag ) {
628 $arr = &$this->path( $path );
629 self::setIndexedTagName( $arr, $tag );
630 }
631
632 /**
633 * Set indexed tag name on $arr and all subarrays
634 *
635 * @since 1.25
636 * @param array &$arr
637 * @param string $tag Tag name
638 */
639 public static function setIndexedTagNameRecursive( array &$arr, $tag ) {
640 if ( !is_string( $tag ) ) {
641 throw new InvalidArgumentException( 'Bad tag name' );
642 }
643 $arr[self::META_INDEXED_TAG_NAME] = $tag;
644 foreach ( $arr as $k => &$v ) {
645 if ( !self::isMetadataKey( $k ) && is_array( $v ) ) {
646 self::setIndexedTagNameRecursive( $v, $tag );
647 }
648 }
649 }
650
651 /**
652 * Set indexed tag name on $path and all subarrays
653 *
654 * @since 1.25
655 * @param array|string|null $path See ApiResult::addValue()
656 * @param string $tag Tag name
657 */
658 public function addIndexedTagNameRecursive( $path, $tag ) {
659 $arr = &$this->path( $path );
660 self::setIndexedTagNameRecursive( $arr, $tag );
661 }
662
663 /**
664 * Preserve specified keys.
665 *
666 * This prevents XML name mangling and preventing keys from being removed
667 * by self::stripMetadata().
668 *
669 * @since 1.25
670 * @param array &$arr
671 * @param array|string $names The element name(s) to preserve
672 */
673 public static function setPreserveKeysList( array &$arr, $names ) {
674 if ( !isset( $arr[self::META_PRESERVE_KEYS] ) ) {
675 $arr[self::META_PRESERVE_KEYS] = (array)$names;
676 } else {
677 $arr[self::META_PRESERVE_KEYS] = array_merge( $arr[self::META_PRESERVE_KEYS], (array)$names );
678 }
679 }
680
681 /**
682 * Preserve specified keys.
683 * @since 1.25
684 * @see self::setPreserveKeysList()
685 * @param array|string|null $path See ApiResult::addValue()
686 * @param array|string $names The element name(s) to preserve
687 */
688 public function addPreserveKeysList( $path, $names ) {
689 $arr = &$this->path( $path );
690 self::setPreserveKeysList( $arr, $names );
691 }
692
693 /**
694 * Don't preserve specified keys.
695 * @since 1.25
696 * @see self::setPreserveKeysList()
697 * @param array &$arr
698 * @param array|string $names The element name(s) to not preserve
699 */
700 public static function unsetPreserveKeysList( array &$arr, $names ) {
701 if ( isset( $arr[self::META_PRESERVE_KEYS] ) ) {
702 $arr[self::META_PRESERVE_KEYS] = array_diff( $arr[self::META_PRESERVE_KEYS], (array)$names );
703 }
704 }
705
706 /**
707 * Don't preserve specified keys.
708 * @since 1.25
709 * @see self::setPreserveKeysList()
710 * @param array|string|null $path See ApiResult::addValue()
711 * @param array|string $names The element name(s) to not preserve
712 */
713 public function removePreserveKeysList( $path, $names ) {
714 $arr = &$this->path( $path );
715 self::unsetPreserveKeysList( $arr, $names );
716 }
717
718 /**
719 * Set the array data type
720 *
721 * @since 1.25
722 * @param array &$arr
723 * @param string $type See ApiResult::META_TYPE
724 * @param string $kvpKeyName See ApiResult::META_KVP_KEY_NAME
725 */
726 public static function setArrayType( array &$arr, $type, $kvpKeyName = null ) {
727 if ( !in_array( $type, array(
728 'default', 'array', 'assoc', 'kvp', 'BCarray', 'BCassoc', 'BCkvp'
729 ), true ) ) {
730 throw new InvalidArgumentException( 'Bad type' );
731 }
732 $arr[self::META_TYPE] = $type;
733 if ( is_string( $kvpKeyName ) ) {
734 $arr[self::META_KVP_KEY_NAME] = $kvpKeyName;
735 }
736 }
737
738 /**
739 * Set the array data type for a path
740 * @since 1.25
741 * @param array|string|null $path See ApiResult::addValue()
742 * @param string $type See ApiResult::META_TYPE
743 * @param string $kvpKeyName See ApiResult::META_KVP_KEY_NAME
744 */
745 public function addArrayType( $path, $tag, $kvpKeyName = null ) {
746 $arr = &$this->path( $path );
747 self::setArrayType( $arr, $tag, $kvpKeyName );
748 }
749
750 /**
751 * Set the array data type recursively
752 * @since 1.25
753 * @param array &$arr
754 * @param string $type See ApiResult::META_TYPE
755 * @param string $kvpKeyName See ApiResult::META_KVP_KEY_NAME
756 */
757 public static function setArrayTypeRecursive( array &$arr, $type, $kvpKeyName = null ) {
758 self::setArrayType( $arr, $type, $kvpKeyName );
759 foreach ( $arr as $k => &$v ) {
760 if ( !self::isMetadataKey( $k ) && is_array( $v ) ) {
761 self::setArrayTypeRecursive( $v, $type, $kvpKeyName );
762 }
763 }
764 }
765
766 /**
767 * Set the array data type for a path recursively
768 * @since 1.25
769 * @param array|string|null $path See ApiResult::addValue()
770 * @param string $type See ApiResult::META_TYPE
771 * @param string $kvpKeyName See ApiResult::META_KVP_KEY_NAME
772 */
773 public function addArrayTypeRecursive( $path, $tag, $kvpKeyName = null ) {
774 $arr = &$this->path( $path );
775 self::setArrayTypeRecursive( $arr, $tag, $kvpKeyName );
776 }
777
778 /**@}*/
779
780 /************************************************************************//**
781 * @name Utility
782 * @{
783 */
784
785 /**
786 * Test whether a key should be considered metadata
787 *
788 * @param string $key
789 * @return bool
790 */
791 public static function isMetadataKey( $key ) {
792 return substr( $key, 0, 1 ) === '_';
793 }
794
795 /**
796 * Apply transformations to an array, returning the transformed array.
797 *
798 * @see ApiResult::getResultData()
799 * @since 1.25
800 * @param array $data
801 * @param array $transforms
802 * @return array|object
803 */
804 protected static function applyTransformations( array $dataIn, array $transforms ) {
805 $strip = isset( $transforms['Strip'] ) ? $transforms['Strip'] : 'none';
806 if ( $strip === 'base' ) {
807 $transforms['Strip'] = 'none';
808 }
809 $transformTypes = isset( $transforms['Types'] ) ? $transforms['Types'] : null;
810 if ( $transformTypes !== null && !is_array( $transformTypes ) ) {
811 throw new InvalidArgumentException( __METHOD__ . ':Value for "Types" must be an array' );
812 }
813
814 $metadata = array();
815 $data = self::stripMetadataNonRecursive( $dataIn, $metadata );
816
817 if ( isset( $transforms['Custom'] ) ) {
818 if ( !is_callable( $transforms['Custom'] ) ) {
819 throw new InvalidArgumentException( __METHOD__ . ': Value for "Custom" must be callable' );
820 }
821 call_user_func_array( $transforms['Custom'], array( &$data, &$metadata ) );
822 }
823
824 if ( ( isset( $transforms['BC'] ) || $transformTypes !== null ) &&
825 isset( $metadata[self::META_TYPE] ) && $metadata[self::META_TYPE] === 'BCkvp' &&
826 !isset( $metadata[self::META_KVP_KEY_NAME] )
827 ) {
828 throw new UnexpectedValueException( 'Type "BCkvp" used without setting ' .
829 'ApiResult::META_KVP_KEY_NAME metadata item' );
830 }
831
832 // BC transformations
833 $boolKeys = null;
834 $forceKVP = false;
835 if ( isset( $transforms['BC'] ) ) {
836 if ( !is_array( $transforms['BC'] ) ) {
837 throw new InvalidArgumentException( __METHOD__ . ':Value for "BC" must be an array' );
838 }
839 if ( !in_array( 'nobool', $transforms['BC'], true ) ) {
840 $boolKeys = isset( $metadata[self::META_BC_BOOLS] )
841 ? array_flip( $metadata[self::META_BC_BOOLS] )
842 : array();
843 }
844
845 if ( !in_array( 'no*', $transforms['BC'], true ) &&
846 isset( $metadata[self::META_CONTENT] ) && $metadata[self::META_CONTENT] !== '*'
847 ) {
848 $k = $metadata[self::META_CONTENT];
849 $data['*'] = $data[$k];
850 unset( $data[$k] );
851 $metadata[self::META_CONTENT] = '*';
852 }
853
854 if ( !in_array( 'nosub', $transforms['BC'], true ) &&
855 isset( $metadata[self::META_BC_SUBELEMENTS] )
856 ) {
857 foreach ( $metadata[self::META_BC_SUBELEMENTS] as $k ) {
858 if ( isset( $data[$k] ) ) {
859 $data[$k] = array(
860 '*' => $data[$k],
861 self::META_CONTENT => '*',
862 self::META_TYPE => 'assoc',
863 );
864 }
865 }
866 }
867
868 if ( isset( $metadata[self::META_TYPE] ) ) {
869 switch ( $metadata[self::META_TYPE] ) {
870 case 'BCarray':
871 case 'BCassoc':
872 $metadata[self::META_TYPE] = 'default';
873 break;
874 case 'BCkvp':
875 $transformTypes['ArmorKVP'] = $metadata[self::META_KVP_KEY_NAME];
876 break;
877 }
878 }
879 }
880
881 // Figure out type, do recursive calls, and do boolean transform if necessary
882 $defaultType = 'array';
883 $maxKey = -1;
884 foreach ( $data as $k => &$v ) {
885 $v = is_array( $v ) ? self::applyTransformations( $v, $transforms ) : $v;
886 if ( $boolKeys !== null && is_bool( $v ) && !isset( $boolKeys[$k] ) ) {
887 if ( !$v ) {
888 unset( $data[$k] );
889 continue;
890 }
891 $v = '';
892 }
893 if ( is_string( $k ) ) {
894 $defaultType = 'assoc';
895 } elseif ( $k > $maxKey ) {
896 $maxKey = $k;
897 }
898 }
899 unset( $v );
900
901 // Determine which metadata to keep
902 switch ( $strip ) {
903 case 'all':
904 case 'base':
905 $keepMetadata = array();
906 break;
907 case 'none':
908 $keepMetadata = &$metadata;
909 break;
910 case 'bc':
911 $keepMetadata = array_intersect_key( $metadata, array(
912 self::META_INDEXED_TAG_NAME => 1,
913 self::META_SUBELEMENTS => 1,
914 ) );
915 break;
916 default:
917 throw new InvalidArgumentException( __METHOD__ . ': Unknown value for "Strip"' );
918 }
919
920 // Type transformation
921 if ( $transformTypes !== null ) {
922 if ( $defaultType === 'array' && $maxKey !== count( $data ) - 1 ) {
923 $defaultType = 'assoc';
924 }
925
926 // Override type, if provided
927 $type = $defaultType;
928 if ( isset( $metadata[self::META_TYPE] ) && $metadata[self::META_TYPE] !== 'default' ) {
929 $type = $metadata[self::META_TYPE];
930 }
931 if ( ( $type === 'kvp' || $type === 'BCkvp' ) &&
932 empty( $transformTypes['ArmorKVP'] )
933 ) {
934 $type = 'assoc';
935 } elseif ( $type === 'BCarray' ) {
936 $type = 'array';
937 } elseif ( $type === 'BCassoc' ) {
938 $type = 'assoc';
939 }
940
941 // Apply transformation
942 switch ( $type ) {
943 case 'assoc':
944 $metadata[self::META_TYPE] = 'assoc';
945 $data += $keepMetadata;
946 return empty( $transformTypes['AssocAsObject'] ) ? $data : (object)$data;
947
948 case 'array':
949 ksort( $data );
950 $data = array_values( $data );
951 $metadata[self::META_TYPE] = 'array';
952 return $data + $keepMetadata;
953
954 case 'kvp':
955 case 'BCkvp':
956 $key = isset( $metadata[self::META_KVP_KEY_NAME] )
957 ? $metadata[self::META_KVP_KEY_NAME]
958 : $transformTypes['ArmorKVP'];
959 $valKey = isset( $transforms['BC'] ) ? '*' : 'value';
960 $assocAsObject = !empty( $transformTypes['AssocAsObject'] );
961 $merge = !empty( $metadata[self::META_KVP_MERGE] );
962
963 $ret = array();
964 foreach ( $data as $k => $v ) {
965 if ( $merge && ( is_array( $v ) || is_object( $v ) ) ) {
966 $vArr = (array)$v;
967 if ( isset( $vArr[self::META_TYPE] ) ) {
968 $mergeType = $vArr[self::META_TYPE];
969 } elseif ( is_object( $v ) ) {
970 $mergeType = 'assoc';
971 } else {
972 $keys = array_keys( $vArr );
973 sort( $keys, SORT_NUMERIC );
974 $mergeType = ( $keys === array_keys( $keys ) ) ? 'array' : 'assoc';
975 }
976 } else {
977 $mergeType = 'n/a';
978 }
979 if ( $mergeType === 'assoc' ) {
980 $item = $vArr + array(
981 $key => $k,
982 );
983 if ( $strip === 'none' ) {
984 self::setPreserveKeysList( $item, array( $key ) );
985 }
986 } else {
987 $item = array(
988 $key => $k,
989 $valKey => $v,
990 );
991 if ( $strip === 'none' ) {
992 $item += array(
993 self::META_PRESERVE_KEYS => array( $key ),
994 self::META_CONTENT => $valKey,
995 self::META_TYPE => 'assoc',
996 );
997 }
998 }
999 $ret[] = $assocAsObject ? (object)$item : $item;
1000 }
1001 $metadata[self::META_TYPE] = 'array';
1002
1003 return $ret + $keepMetadata;
1004
1005 default:
1006 throw new UnexpectedValueException( "Unknown type '$type'" );
1007 }
1008 } else {
1009 return $data + $keepMetadata;
1010 }
1011 }
1012
1013 /**
1014 * Recursively remove metadata keys from a data array or object
1015 *
1016 * Note this removes all potential metadata keys, not just the defined
1017 * ones.
1018 *
1019 * @since 1.25
1020 * @param array|object $data
1021 * @return array|object
1022 */
1023 public static function stripMetadata( $data ) {
1024 if ( is_array( $data ) || is_object( $data ) ) {
1025 $isObj = is_object( $data );
1026 if ( $isObj ) {
1027 $data = (array)$data;
1028 }
1029 $preserveKeys = isset( $data[self::META_PRESERVE_KEYS] )
1030 ? (array)$data[self::META_PRESERVE_KEYS]
1031 : array();
1032 foreach ( $data as $k => $v ) {
1033 if ( self::isMetadataKey( $k ) && !in_array( $k, $preserveKeys, true ) ) {
1034 unset( $data[$k] );
1035 } elseif ( is_array( $v ) || is_object( $v ) ) {
1036 $data[$k] = self::stripMetadata( $v );
1037 }
1038 }
1039 if ( $isObj ) {
1040 $data = (object)$data;
1041 }
1042 }
1043 return $data;
1044 }
1045
1046 /**
1047 * Remove metadata keys from a data array or object, non-recursive
1048 *
1049 * Note this removes all potential metadata keys, not just the defined
1050 * ones.
1051 *
1052 * @since 1.25
1053 * @param array|object $data
1054 * @param array &$metadata Store metadata here, if provided
1055 * @return array|object
1056 */
1057 public static function stripMetadataNonRecursive( $data, &$metadata = null ) {
1058 if ( !is_array( $metadata ) ) {
1059 $metadata = array();
1060 }
1061 if ( is_array( $data ) || is_object( $data ) ) {
1062 $isObj = is_object( $data );
1063 if ( $isObj ) {
1064 $data = (array)$data;
1065 }
1066 $preserveKeys = isset( $data[self::META_PRESERVE_KEYS] )
1067 ? (array)$data[self::META_PRESERVE_KEYS]
1068 : array();
1069 foreach ( $data as $k => $v ) {
1070 if ( self::isMetadataKey( $k ) && !in_array( $k, $preserveKeys, true ) ) {
1071 $metadata[$k] = $v;
1072 unset( $data[$k] );
1073 }
1074 }
1075 if ( $isObj ) {
1076 $data = (object)$data;
1077 }
1078 }
1079 return $data;
1080 }
1081
1082 /**
1083 * Get the 'real' size of a result item. This means the strlen() of the item,
1084 * or the sum of the strlen()s of the elements if the item is an array.
1085 * @note Once the deprecated public self::size is removed, we can rename
1086 * this back to a less awkward name.
1087 * @param mixed $value Validated value (see self::validateValue())
1088 * @return int
1089 */
1090 private static function valueSize( $value ) {
1091 $s = 0;
1092 if ( is_array( $value ) ) {
1093 foreach ( $value as $k => $v ) {
1094 if ( !self::isMetadataKey( $s ) ) {
1095 $s += self::valueSize( $v );
1096 }
1097 }
1098 } elseif ( is_scalar( $value ) ) {
1099 $s = strlen( $value );
1100 }
1101
1102 return $s;
1103 }
1104
1105 /**
1106 * Return a reference to the internal data at $path
1107 *
1108 * @param array|string|null $path
1109 * @param string $create
1110 * If 'append', append empty arrays.
1111 * If 'prepend', prepend empty arrays.
1112 * If 'dummy', return a dummy array.
1113 * Else, raise an error.
1114 * @return array
1115 */
1116 private function &path( $path, $create = 'append' ) {
1117 $path = (array)$path;
1118 $ret = &$this->data;
1119 foreach ( $path as $i => $k ) {
1120 if ( !isset( $ret[$k] ) ) {
1121 switch ( $create ) {
1122 case 'append':
1123 $ret[$k] = array();
1124 break;
1125 case 'prepend':
1126 $ret = array( $k => array() ) + $ret;
1127 break;
1128 case 'dummy':
1129 $tmp = array();
1130 return $tmp;
1131 default:
1132 $fail = join( '.', array_slice( $path, 0, $i + 1 ) );
1133 throw new InvalidArgumentException( "Path $fail does not exist" );
1134 }
1135 }
1136 if ( !is_array( $ret[$k] ) ) {
1137 $fail = join( '.', array_slice( $path, 0, $i + 1 ) );
1138 throw new InvalidArgumentException( "Path $fail is not an array" );
1139 }
1140 $ret = &$ret[$k];
1141 }
1142 return $ret;
1143 }
1144
1145 /**
1146 * Add the correct metadata to an array of vars we want to export through
1147 * the API.
1148 *
1149 * @param array $vars
1150 * @param boolean $forceHash
1151 * @return array
1152 */
1153 public static function addMetadataToResultVars( $vars, $forceHash = true ) {
1154 // Process subarrays and determine if this is a JS [] or {}
1155 $hash = $forceHash;
1156 $maxKey = -1;
1157 $bools = array();
1158 foreach ( $vars as $k => $v ) {
1159 if ( is_array( $v ) || is_object( $v ) ) {
1160 $vars[$k] = ApiResult::addMetadataToResultVars( (array)$v, is_object( $v ) );
1161 } elseif ( is_bool( $v ) ) {
1162 // Better here to use real bools even in BC formats
1163 $bools[] = $k;
1164 }
1165 if ( is_string( $k ) ) {
1166 $hash = true;
1167 } elseif ( $k > $maxKey ) {
1168 $maxKey = $k;
1169 }
1170 }
1171 if ( !$hash && $maxKey !== count( $vars ) - 1 ) {
1172 $hash = true;
1173 }
1174
1175 // Set metadata appropriately
1176 if ( $hash ) {
1177 // Get the list of keys we actually care about. Unfortunately, we can't support
1178 // certain keys that conflict with ApiResult metadata.
1179 $keys = array_diff( array_keys( $vars ), array(
1180 ApiResult::META_TYPE, ApiResult::META_PRESERVE_KEYS, ApiResult::META_KVP_KEY_NAME,
1181 ApiResult::META_INDEXED_TAG_NAME, ApiResult::META_BC_BOOLS
1182 ) );
1183
1184 return array(
1185 ApiResult::META_TYPE => 'kvp',
1186 ApiResult::META_KVP_KEY_NAME => 'key',
1187 ApiResult::META_PRESERVE_KEYS => $keys,
1188 ApiResult::META_BC_BOOLS => $bools,
1189 ApiResult::META_INDEXED_TAG_NAME => 'var',
1190 ) + $vars;
1191 } else {
1192 return array(
1193 ApiResult::META_TYPE => 'array',
1194 ApiResult::META_BC_BOOLS => $bools,
1195 ApiResult::META_INDEXED_TAG_NAME => 'value',
1196 ) + $vars;
1197 }
1198 }
1199
1200 /**@}*/
1201
1202 /************************************************************************//**
1203 * @name Deprecated
1204 * @{
1205 */
1206
1207 /**
1208 * Call this function when special elements such as '_element'
1209 * are needed by the formatter, for example in XML printing.
1210 * @deprecated since 1.25, you shouldn't have been using it in the first place
1211 * @since 1.23 $flag parameter added
1212 * @param bool $flag Set the raw mode flag to this state
1213 */
1214 public function setRawMode( $flag = true ) {
1215 // Can't wfDeprecated() here, since we need to set this flag from
1216 // ApiMain for BC with stuff using self::getIsRawMode as
1217 // "self::getIsXMLMode".
1218 $this->isRawMode = $flag;
1219 }
1220
1221 /**
1222 * Returns true whether the formatter requested raw data.
1223 * @deprecated since 1.25, you shouldn't have been using it in the first place
1224 * @return bool
1225 */
1226 public function getIsRawMode() {
1227 /// @todo: After Wikibase stops calling this, warn
1228 return $this->isRawMode;
1229 }
1230
1231 /**
1232 * Get the result's internal data array (read-only)
1233 * @deprecated since 1.25, use $this->getResultData() instead
1234 * @return array
1235 */
1236 public function getData() {
1237 wfDeprecated( __METHOD__, '1.25' );
1238 return $this->getResultData( null, array(
1239 'BC' => array(),
1240 'Types' => array(),
1241 'Strip' => $this->isRawMode ? 'bc' : 'all',
1242 ) );
1243 }
1244
1245 /**
1246 * Disable size checking in addValue(). Don't use this unless you
1247 * REALLY know what you're doing. Values added while size checking
1248 * was disabled will not be counted (ever)
1249 * @deprecated since 1.24, use ApiResult::NO_SIZE_CHECK
1250 */
1251 public function disableSizeCheck() {
1252 wfDeprecated( __METHOD__, '1.24' );
1253 $this->checkingSize = false;
1254 }
1255
1256 /**
1257 * Re-enable size checking in addValue()
1258 * @deprecated since 1.24, use ApiResult::NO_SIZE_CHECK
1259 */
1260 public function enableSizeCheck() {
1261 wfDeprecated( __METHOD__, '1.24' );
1262 $this->checkingSize = true;
1263 }
1264
1265 /**
1266 * Alias for self::setValue()
1267 *
1268 * @since 1.21 int $flags replaced boolean $override
1269 * @deprecated since 1.25, use self::setValue() instead
1270 * @param array $arr To add $value to
1271 * @param string $name Index of $arr to add $value at
1272 * @param mixed $value
1273 * @param int $flags Zero or more OR-ed flags like OVERRIDE | ADD_ON_TOP.
1274 * This parameter used to be boolean, and the value of OVERRIDE=1 was
1275 * specifically chosen so that it would be backwards compatible with the
1276 * new method signature.
1277 */
1278 public static function setElement( &$arr, $name, $value, $flags = 0 ) {
1279 wfDeprecated( __METHOD__, '1.25' );
1280 self::setValue( $arr, $name, $value, $flags );
1281 }
1282
1283 /**
1284 * Adds a content element to an array.
1285 * Use this function instead of hardcoding the '*' element.
1286 * @deprecated since 1.25, use self::setContentValue() instead
1287 * @param array $arr To add the content element to
1288 * @param mixed $value
1289 * @param string $subElemName When present, content element is created
1290 * as a sub item of $arr. Use this parameter to create elements in
1291 * format "<elem>text</elem>" without attributes.
1292 */
1293 public static function setContent( &$arr, $value, $subElemName = null ) {
1294 wfDeprecated( __METHOD__, '1.25' );
1295 if ( is_array( $value ) ) {
1296 throw new InvalidArgumentException( __METHOD__ . ': Bad parameter' );
1297 }
1298 if ( is_null( $subElemName ) ) {
1299 self::setContentValue( $arr, 'content', $value );
1300 } else {
1301 if ( !isset( $arr[$subElemName] ) ) {
1302 $arr[$subElemName] = array();
1303 }
1304 self::setContentValue( $arr[$subElemName], 'content', $value );
1305 }
1306 }
1307
1308 /**
1309 * Set indexed tag name on all subarrays of $arr
1310 *
1311 * Does not set the tag name for $arr itself.
1312 *
1313 * @deprecated since 1.25, use self::setIndexedTagNameRecursive() instead
1314 * @param array $arr
1315 * @param string $tag Tag name
1316 */
1317 public function setIndexedTagName_recursive( &$arr, $tag ) {
1318 wfDeprecated( __METHOD__, '1.25' );
1319 if ( !is_array( $arr ) ) {
1320 return;
1321 }
1322 if ( !is_string( $tag ) ) {
1323 throw new InvalidArgumentException( 'Bad tag name' );
1324 }
1325 foreach ( $arr as $k => &$v ) {
1326 if ( !self::isMetadataKey( $k ) && is_array( $v ) ) {
1327 $v[self::META_INDEXED_TAG_NAME] = $tag;
1328 $this->setIndexedTagName_recursive( $v, $tag );
1329 }
1330 }
1331 }
1332
1333 /**
1334 * Alias for self::addIndexedTagName()
1335 * @deprecated since 1.25, use $this->addIndexedTagName() instead
1336 * @param array $path Path to the array, like addValue()'s $path
1337 * @param string $tag
1338 */
1339 public function setIndexedTagName_internal( $path, $tag ) {
1340 wfDeprecated( __METHOD__, '1.25' );
1341 $this->addIndexedTagName( $path, $tag );
1342 }
1343
1344 /**
1345 * Alias for self::addParsedLimit()
1346 * @deprecated since 1.25, use $this->addParsedLimit() instead
1347 * @param string $moduleName
1348 * @param int $limit
1349 */
1350 public function setParsedLimit( $moduleName, $limit ) {
1351 wfDeprecated( __METHOD__, '1.25' );
1352 $this->addParsedLimit( $moduleName, $limit );
1353 }
1354
1355 /**
1356 * Set the ApiMain for use by $this->beginContinuation()
1357 * @since 1.25
1358 * @deprecated for backwards compatibility only, do not use
1359 * @param ApiMain $main
1360 */
1361 public function setMainForContinuation( ApiMain $main ) {
1362 $this->mainForContinuation = $main;
1363 }
1364
1365 /**
1366 * Parse a 'continue' parameter and return status information.
1367 *
1368 * This must be balanced by a call to endContinuation().
1369 *
1370 * @since 1.24
1371 * @deprecated since 1.25, use ApiContinuationManager instead
1372 * @param string|null $continue
1373 * @param ApiBase[] $allModules
1374 * @param array $generatedModules
1375 * @return array
1376 */
1377 public function beginContinuation(
1378 $continue, array $allModules = array(), array $generatedModules = array()
1379 ) {
1380 wfDeprecated( __METHOD__, '1.25' );
1381 if ( $this->mainForContinuation->getContinuationManager() ) {
1382 throw new UnexpectedValueException(
1383 __METHOD__ . ': Continuation already in progress from ' .
1384 $this->mainForContinuation->getContinuationManager()->getSource()
1385 );
1386 }
1387
1388 // Ugh. If $continue doesn't match that in the request, temporarily
1389 // replace the request when creating the ApiContinuationManager.
1390 if ( $continue === null ) {
1391 $continue = '';
1392 }
1393 if ( $this->mainForContinuation->getVal( 'continue', '' ) !== $continue ) {
1394 $oldCtx = $this->mainForContinuation->getContext();
1395 $newCtx = new DerivativeContext( $oldCtx );
1396 $newCtx->setRequest( new DerivativeRequest(
1397 $oldCtx->getRequest(),
1398 array( 'continue' => $continue ) + $oldCtx->getRequest()->getValues(),
1399 $oldCtx->getRequest()->wasPosted()
1400 ) );
1401 $this->mainForContinuation->setContext( $newCtx );
1402 $reset = new ScopedCallback(
1403 array( $this->mainForContinuation, 'setContext' ),
1404 array( $oldCtx )
1405 );
1406 }
1407 $manager = new ApiContinuationManager(
1408 $this->mainForContinuation, $allModules, $generatedModules
1409 );
1410 $reset = null;
1411
1412 $this->mainForContinuation->setContinuationManager( $manager );
1413
1414 return array(
1415 $manager->isGeneratorDone(),
1416 $manager->getRunModules(),
1417 );
1418 }
1419
1420 /**
1421 * @since 1.24
1422 * @deprecated since 1.25, use ApiContinuationManager instead
1423 * @param ApiBase $module
1424 * @param string $paramName
1425 * @param string|array $paramValue
1426 */
1427 public function setContinueParam( ApiBase $module, $paramName, $paramValue ) {
1428 wfDeprecated( __METHOD__, '1.25' );
1429 if ( $this->mainForContinuation->getContinuationManager() ) {
1430 $this->mainForContinuation->getContinuationManager()->addContinueParam(
1431 $module, $paramName, $paramValue
1432 );
1433 }
1434 }
1435
1436 /**
1437 * @since 1.24
1438 * @deprecated since 1.25, use ApiContinuationManager instead
1439 * @param ApiBase $module
1440 * @param string $paramName
1441 * @param string|array $paramValue
1442 */
1443 public function setGeneratorContinueParam( ApiBase $module, $paramName, $paramValue ) {
1444 wfDeprecated( __METHOD__, '1.25' );
1445 if ( $this->mainForContinuation->getContinuationManager() ) {
1446 $this->mainForContinuation->getContinuationManager()->addGeneratorContinueParam(
1447 $module, $paramName, $paramValue
1448 );
1449 }
1450 }
1451
1452 /**
1453 * Close continuation, writing the data into the result
1454 * @since 1.24
1455 * @deprecated since 1.25, use ApiContinuationManager instead
1456 * @param string $style 'standard' for the new style since 1.21, 'raw' for
1457 * the style used in 1.20 and earlier.
1458 */
1459 public function endContinuation( $style = 'standard' ) {
1460 wfDeprecated( __METHOD__, '1.25' );
1461 if ( !$this->mainForContinuation->getContinuationManager() ) {
1462 return;
1463 }
1464
1465 if ( $style === 'raw' ) {
1466 $data = $this->mainForContinuation->getContinuationManager()->getRawContinuation();
1467 if ( $data ) {
1468 $this->addValue( null, 'query-continue', $data, self::ADD_ON_TOP | self::NO_SIZE_CHECK );
1469 }
1470 } else {
1471 $this->mainForContinuation->getContinuationManager()->setContinuationIntoResult( $this );
1472 }
1473 }
1474
1475 /**
1476 * No-op, this is now checked on insert.
1477 * @deprecated since 1.25
1478 */
1479 public function cleanUpUTF8() {
1480 wfDeprecated( __METHOD__, '1.25' );
1481 }
1482
1483 /**
1484 * Get the 'real' size of a result item. This means the strlen() of the item,
1485 * or the sum of the strlen()s of the elements if the item is an array.
1486 * @deprecated since 1.25, no external users known and there doesn't seem
1487 * to be any case for such use over just checking the return value from the
1488 * add/set methods.
1489 * @param mixed $value
1490 * @return int
1491 */
1492 public static function size( $value ) {
1493 wfDeprecated( __METHOD__, '1.25' );
1494 return self::valueSize( self::validateValue( $value ) );
1495 }
1496
1497 /**
1498 * Converts a Status object to an array suitable for addValue
1499 * @deprecated since 1.25, use ApiErrorFormatter::arrayFromStatus()
1500 * @param Status $status
1501 * @param string $errorType
1502 * @return array
1503 */
1504 public function convertStatusToArray( $status, $errorType = 'error' ) {
1505 wfDeprecated( __METHOD__, '1.25' );
1506 return $this->errorFormatter->arrayFromStatus( $status, $errorType );
1507 }
1508
1509 /**@}*/
1510 }
1511
1512 /**
1513 * For really cool vim folding this needs to be at the end:
1514 * vim: foldmarker=@{,@} foldmethod=marker
1515 */