Merge "Add 'since <version>' to @deprecated annotations"
[lhc/web/wiklou.git] / includes / api / ApiResult.php
1 <?php
2 /**
3 *
4 *
5 * Created on Sep 4, 2006
6 *
7 * Copyright © 2006 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
23 *
24 * @file
25 */
26
27 /**
28 * This class represents the result of the API operations.
29 * It simply wraps a nested array() structure, adding some functions to simplify
30 * array's modifications. As various modules execute, they add different pieces
31 * of information to this result, structuring it as it will be given to the client.
32 *
33 * Each subarray may either be a dictionary - key-value pairs with unique keys,
34 * or lists, where the items are added using $data[] = $value notation.
35 *
36 * There are two special key values that change how XML output is generated:
37 * '_element' This key sets the tag name for the rest of the elements in the current array.
38 * It is only inserted if the formatter returned true for getNeedsRawData()
39 * '*' This key has special meaning only to the XML formatter, and is outputted as is
40 * for all others. In XML it becomes the content of the current element.
41 *
42 * @ingroup API
43 */
44 class ApiResult extends ApiBase {
45
46 /**
47 * override existing value in addValue() and setElement()
48 * @since 1.21
49 */
50 const OVERRIDE = 1;
51
52 /**
53 * For addValue() and setElement(), if the value does not exist, add it as the first element.
54 * In case the new value has no name (numerical index), all indexes will be renumbered.
55 * @since 1.21
56 */
57 const ADD_ON_TOP = 2;
58
59 private $mData, $mIsRawMode, $mSize, $mCheckingSize;
60
61 /**
62 * Constructor
63 * @param ApiMain $main
64 */
65 public function __construct( $main ) {
66 parent::__construct( $main, 'result' );
67 $this->mIsRawMode = false;
68 $this->mCheckingSize = true;
69 $this->reset();
70 }
71
72 /**
73 * Clear the current result data.
74 */
75 public function reset() {
76 $this->mData = array();
77 $this->mSize = 0;
78 }
79
80 /**
81 * Call this function when special elements such as '_element'
82 * are needed by the formatter, for example in XML printing.
83 * @since 1.23 $flag parameter added
84 * @param bool $flag Set the raw mode flag to this state
85 */
86 public function setRawMode( $flag = true ) {
87 $this->mIsRawMode = $flag;
88 }
89
90 /**
91 * Returns true whether the formatter requested raw data.
92 * @return bool
93 */
94 public function getIsRawMode() {
95 return $this->mIsRawMode;
96 }
97
98 /**
99 * Get the result's internal data array (read-only)
100 * @return array
101 */
102 public function getData() {
103 return $this->mData;
104 }
105
106 /**
107 * Get the 'real' size of a result item. This means the strlen() of the item,
108 * or the sum of the strlen()s of the elements if the item is an array.
109 * @param mixed $value
110 * @return int
111 */
112 public static function size( $value ) {
113 $s = 0;
114 if ( is_array( $value ) ) {
115 foreach ( $value as $v ) {
116 $s += self::size( $v );
117 }
118 } elseif ( !is_object( $value ) ) {
119 // Objects can't always be cast to string
120 $s = strlen( $value );
121 }
122
123 return $s;
124 }
125
126 /**
127 * Get the size of the result, i.e. the amount of bytes in it
128 * @return int
129 */
130 public function getSize() {
131 return $this->mSize;
132 }
133
134 /**
135 * Disable size checking in addValue(). Don't use this unless you
136 * REALLY know what you're doing. Values added while size checking
137 * was disabled will not be counted (ever)
138 */
139 public function disableSizeCheck() {
140 $this->mCheckingSize = false;
141 }
142
143 /**
144 * Re-enable size checking in addValue()
145 */
146 public function enableSizeCheck() {
147 $this->mCheckingSize = true;
148 }
149
150 /**
151 * Add an output value to the array by name.
152 * Verifies that value with the same name has not been added before.
153 * @param array $arr To add $value to
154 * @param string $name Index of $arr to add $value at
155 * @param mixed $value
156 * @param int $flags Zero or more OR-ed flags like OVERRIDE | ADD_ON_TOP.
157 * This parameter used to be boolean, and the value of OVERRIDE=1 was
158 * specifically chosen so that it would be backwards compatible with the
159 * new method signature.
160 *
161 * @since 1.21 int $flags replaced boolean $override
162 */
163 public static function setElement( &$arr, $name, $value, $flags = 0 ) {
164 if ( $arr === null || $name === null || $value === null
165 || !is_array( $arr ) || is_array( $name )
166 ) {
167 ApiBase::dieDebug( __METHOD__, 'Bad parameter' );
168 }
169
170 $exists = isset( $arr[$name] );
171 if ( !$exists || ( $flags & ApiResult::OVERRIDE ) ) {
172 if ( !$exists && ( $flags & ApiResult::ADD_ON_TOP ) ) {
173 $arr = array( $name => $value ) + $arr;
174 } else {
175 $arr[$name] = $value;
176 }
177 } elseif ( is_array( $arr[$name] ) && is_array( $value ) ) {
178 $merged = array_intersect_key( $arr[$name], $value );
179 if ( !count( $merged ) ) {
180 $arr[$name] += $value;
181 } else {
182 ApiBase::dieDebug( __METHOD__, "Attempting to merge element $name" );
183 }
184 } else {
185 ApiBase::dieDebug(
186 __METHOD__,
187 "Attempting to add element $name=$value, existing value is {$arr[$name]}"
188 );
189 }
190 }
191
192 /**
193 * Adds a content element to an array.
194 * Use this function instead of hardcoding the '*' element.
195 * @param array $arr To add the content element to
196 * @param mixed $value
197 * @param string $subElemName When present, content element is created
198 * as a sub item of $arr. Use this parameter to create elements in
199 * format "<elem>text</elem>" without attributes.
200 */
201 public static function setContent( &$arr, $value, $subElemName = null ) {
202 if ( is_array( $value ) ) {
203 ApiBase::dieDebug( __METHOD__, 'Bad parameter' );
204 }
205 if ( is_null( $subElemName ) ) {
206 ApiResult::setElement( $arr, '*', $value );
207 } else {
208 if ( !isset( $arr[$subElemName] ) ) {
209 $arr[$subElemName] = array();
210 }
211 ApiResult::setElement( $arr[$subElemName], '*', $value );
212 }
213 }
214
215 /**
216 * In case the array contains indexed values (in addition to named),
217 * give all indexed values the given tag name. This function MUST be
218 * called on every array that has numerical indexes.
219 * @param array $arr
220 * @param string $tag Tag name
221 */
222 public function setIndexedTagName( &$arr, $tag ) {
223 // In raw mode, add the '_element', otherwise just ignore
224 if ( !$this->getIsRawMode() ) {
225 return;
226 }
227 if ( $arr === null || $tag === null || !is_array( $arr ) || is_array( $tag ) ) {
228 ApiBase::dieDebug( __METHOD__, 'Bad parameter' );
229 }
230 // Do not use setElement() as it is ok to call this more than once
231 $arr['_element'] = $tag;
232 }
233
234 /**
235 * Calls setIndexedTagName() on each sub-array of $arr
236 * @param array $arr
237 * @param string $tag Tag name
238 */
239 public function setIndexedTagName_recursive( &$arr, $tag ) {
240 if ( !is_array( $arr ) ) {
241 return;
242 }
243 foreach ( $arr as &$a ) {
244 if ( !is_array( $a ) ) {
245 continue;
246 }
247 $this->setIndexedTagName( $a, $tag );
248 $this->setIndexedTagName_recursive( $a, $tag );
249 }
250 }
251
252 /**
253 * Calls setIndexedTagName() on an array already in the result.
254 * Don't specify a path to a value that's not in the result, or
255 * you'll get nasty errors.
256 * @param array $path Path to the array, like addValue()'s $path
257 * @param string $tag
258 */
259 public function setIndexedTagName_internal( $path, $tag ) {
260 $data = &$this->mData;
261 foreach ( (array)$path as $p ) {
262 if ( !isset( $data[$p] ) ) {
263 $data[$p] = array();
264 }
265 $data = &$data[$p];
266 }
267 if ( is_null( $data ) ) {
268 return;
269 }
270 $this->setIndexedTagName( $data, $tag );
271 }
272
273 /**
274 * Add value to the output data at the given path.
275 * Path can be an indexed array, each element specifying the branch at which to add the new
276 * value. Setting $path to array('a','b','c') is equivalent to data['a']['b']['c'] = $value.
277 * If $path is null, the value will be inserted at the data root.
278 * If $name is empty, the $value is added as a next list element data[] = $value.
279 *
280 * @param array|string|null $path
281 * @param string $name
282 * @param mixed $value
283 * @param int $flags Zero or more OR-ed flags like OVERRIDE | ADD_ON_TOP. This
284 * parameter used to be boolean, and the value of OVERRIDE=1 was specifically
285 * chosen so that it would be backwards compatible with the new method
286 * signature.
287 * @return bool True if $value fits in the result, false if not
288 *
289 * @since 1.21 int $flags replaced boolean $override
290 */
291 public function addValue( $path, $name, $value, $flags = 0 ) {
292 global $wgAPIMaxResultSize;
293
294 $data = &$this->mData;
295 if ( $this->mCheckingSize ) {
296 $newsize = $this->mSize + self::size( $value );
297 if ( $newsize > $wgAPIMaxResultSize ) {
298 $this->setWarning(
299 "This result was truncated because it would otherwise be larger than the " .
300 "limit of {$wgAPIMaxResultSize} bytes" );
301
302 return false;
303 }
304 $this->mSize = $newsize;
305 }
306
307 $addOnTop = $flags & ApiResult::ADD_ON_TOP;
308 if ( $path !== null ) {
309 foreach ( (array)$path as $p ) {
310 if ( !isset( $data[$p] ) ) {
311 if ( $addOnTop ) {
312 $data = array( $p => array() ) + $data;
313 $addOnTop = false;
314 } else {
315 $data[$p] = array();
316 }
317 }
318 $data = &$data[$p];
319 }
320 }
321
322 if ( !$name ) {
323 // Add list element
324 if ( $addOnTop ) {
325 // This element needs to be inserted in the beginning
326 // Numerical indexes will be renumbered
327 array_unshift( $data, $value );
328 } else {
329 // Add new value at the end
330 $data[] = $value;
331 }
332 } else {
333 // Add named element
334 self::setElement( $data, $name, $value, $flags );
335 }
336
337 return true;
338 }
339
340 /**
341 * Add a parsed limit=max to the result.
342 *
343 * @param string $moduleName
344 * @param int $limit
345 */
346 public function setParsedLimit( $moduleName, $limit ) {
347 // Add value, allowing overwriting
348 $this->addValue( 'limits', $moduleName, $limit, ApiResult::OVERRIDE );
349 }
350
351 /**
352 * Unset a value previously added to the result set.
353 * Fails silently if the value isn't found.
354 * For parameters, see addValue()
355 * @param array|null $path
356 * @param string $name
357 */
358 public function unsetValue( $path, $name ) {
359 $data = &$this->mData;
360 if ( $path !== null ) {
361 foreach ( (array)$path as $p ) {
362 if ( !isset( $data[$p] ) ) {
363 return;
364 }
365 $data = &$data[$p];
366 }
367 }
368 $this->mSize -= self::size( $data[$name] );
369 unset( $data[$name] );
370 }
371
372 /**
373 * Ensure all values in this result are valid UTF-8.
374 */
375 public function cleanUpUTF8() {
376 array_walk_recursive( $this->mData, array( 'ApiResult', 'cleanUp_helper' ) );
377 }
378
379 /**
380 * Callback function for cleanUpUTF8()
381 *
382 * @param string $s
383 */
384 private static function cleanUp_helper( &$s ) {
385 if ( !is_string( $s ) ) {
386 return;
387 }
388 global $wgContLang;
389 $s = $wgContLang->normalize( $s );
390 }
391
392 /**
393 * Converts a Status object to an array suitable for addValue
394 * @param Status $status
395 * @param string $errorType
396 * @return array
397 */
398 public function convertStatusToArray( $status, $errorType = 'error' ) {
399 if ( $status->isGood() ) {
400 return array();
401 }
402
403 $result = array();
404 foreach ( $status->getErrorsByType( $errorType ) as $error ) {
405 $this->setIndexedTagName( $error['params'], 'param' );
406 $result[] = $error;
407 }
408 $this->setIndexedTagName( $result, $errorType );
409
410 return $result;
411 }
412
413 public function execute() {
414 ApiBase::dieDebug( __METHOD__, 'execute() is not supported on Result object' );
415 }
416 }