Merge "Workaround image magick issue with greyscale xcf files"
[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 three 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 * '_subelements' This key causes the specified elements to be returned as subelements rather than attributes.
40 * It is only inserted if the formatter returned true for getNeedsRawData()
41 * '*' This key has special meaning only to the XML formatter, and is outputted as is
42 * for all others. In XML it becomes the content of the current element.
43 *
44 * @ingroup API
45 */
46 class ApiResult extends ApiBase {
47
48 /**
49 * override existing value in addValue() and setElement()
50 * @since 1.21
51 */
52 const OVERRIDE = 1;
53
54 /**
55 * For addValue() and setElement(), if the value does not exist, add it as the first element.
56 * In case the new value has no name (numerical index), all indexes will be renumbered.
57 * @since 1.21
58 */
59 const ADD_ON_TOP = 2;
60
61 private $mData, $mIsRawMode, $mSize, $mCheckingSize;
62
63 /**
64 * @param ApiMain $main
65 */
66 public function __construct( ApiMain $main ) {
67 parent::__construct( $main, 'result' );
68 $this->mIsRawMode = false;
69 $this->mCheckingSize = true;
70 $this->reset();
71 }
72
73 /**
74 * Clear the current result data.
75 */
76 public function reset() {
77 $this->mData = array();
78 $this->mSize = 0;
79 }
80
81 /**
82 * Call this function when special elements such as '_element'
83 * are needed by the formatter, for example in XML printing.
84 * @since 1.23 $flag parameter added
85 * @param bool $flag Set the raw mode flag to this state
86 */
87 public function setRawMode( $flag = true ) {
88 $this->mIsRawMode = $flag;
89 }
90
91 /**
92 * Returns true whether the formatter requested raw data.
93 * @return bool
94 */
95 public function getIsRawMode() {
96 return $this->mIsRawMode;
97 }
98
99 /**
100 * Get the result's internal data array (read-only)
101 * @return array
102 */
103 public function getData() {
104 return $this->mData;
105 }
106
107 /**
108 * Get the 'real' size of a result item. This means the strlen() of the item,
109 * or the sum of the strlen()s of the elements if the item is an array.
110 * @param mixed $value
111 * @return int
112 */
113 public static function size( $value ) {
114 $s = 0;
115 if ( is_array( $value ) ) {
116 foreach ( $value as $v ) {
117 $s += self::size( $v );
118 }
119 } elseif ( !is_object( $value ) ) {
120 // Objects can't always be cast to string
121 $s = strlen( $value );
122 }
123
124 return $s;
125 }
126
127 /**
128 * Get the size of the result, i.e. the amount of bytes in it
129 * @return int
130 */
131 public function getSize() {
132 return $this->mSize;
133 }
134
135 /**
136 * Disable size checking in addValue(). Don't use this unless you
137 * REALLY know what you're doing. Values added while size checking
138 * was disabled will not be counted (ever)
139 */
140 public function disableSizeCheck() {
141 $this->mCheckingSize = false;
142 }
143
144 /**
145 * Re-enable size checking in addValue()
146 */
147 public function enableSizeCheck() {
148 $this->mCheckingSize = true;
149 }
150
151 /**
152 * Add an output value to the array by name.
153 * Verifies that value with the same name has not been added before.
154 * @param array $arr To add $value to
155 * @param string $name Index of $arr to add $value at
156 * @param mixed $value
157 * @param int $flags Zero or more OR-ed flags like OVERRIDE | ADD_ON_TOP.
158 * This parameter used to be boolean, and the value of OVERRIDE=1 was
159 * specifically chosen so that it would be backwards compatible with the
160 * new method signature.
161 *
162 * @since 1.21 int $flags replaced boolean $override
163 */
164 public static function setElement( &$arr, $name, $value, $flags = 0 ) {
165 if ( $arr === null || $name === null || $value === null
166 || !is_array( $arr ) || is_array( $name )
167 ) {
168 ApiBase::dieDebug( __METHOD__, 'Bad parameter' );
169 }
170
171 $exists = isset( $arr[$name] );
172 if ( !$exists || ( $flags & ApiResult::OVERRIDE ) ) {
173 if ( !$exists && ( $flags & ApiResult::ADD_ON_TOP ) ) {
174 $arr = array( $name => $value ) + $arr;
175 } else {
176 $arr[$name] = $value;
177 }
178 } elseif ( is_array( $arr[$name] ) && is_array( $value ) ) {
179 $merged = array_intersect_key( $arr[$name], $value );
180 if ( !count( $merged ) ) {
181 $arr[$name] += $value;
182 } else {
183 ApiBase::dieDebug( __METHOD__, "Attempting to merge element $name" );
184 }
185 } else {
186 ApiBase::dieDebug(
187 __METHOD__,
188 "Attempting to add element $name=$value, existing value is {$arr[$name]}"
189 );
190 }
191 }
192
193 /**
194 * Adds a content element to an array.
195 * Use this function instead of hardcoding the '*' element.
196 * @param array $arr To add the content element to
197 * @param mixed $value
198 * @param string $subElemName When present, content element is created
199 * as a sub item of $arr. Use this parameter to create elements in
200 * format "<elem>text</elem>" without attributes.
201 */
202 public static function setContent( &$arr, $value, $subElemName = null ) {
203 if ( is_array( $value ) ) {
204 ApiBase::dieDebug( __METHOD__, 'Bad parameter' );
205 }
206 if ( is_null( $subElemName ) ) {
207 ApiResult::setElement( $arr, '*', $value );
208 } else {
209 if ( !isset( $arr[$subElemName] ) ) {
210 $arr[$subElemName] = array();
211 }
212 ApiResult::setElement( $arr[$subElemName], '*', $value );
213 }
214 }
215
216 /**
217 * Causes the elements with the specified names to be output as
218 * subelements rather than attributes.
219 * @param array $arr
220 * @param array|string $names The element name(s) to be output as subelements
221 */
222 public function setSubelements( &$arr, $names ) {
223 // In raw mode, add the '_subelements', otherwise just ignore
224 if ( !$this->getIsRawMode() ) {
225 return;
226 }
227 if ( $arr === null || $names === null || !is_array( $arr ) ) {
228 ApiBase::dieDebug( __METHOD__, 'Bad parameter' );
229 }
230 if ( !is_array( $names ) ) {
231 $names = array( $names );
232 }
233 if ( !isset( $arr['_subelements'] ) ) {
234 $arr['_subelements'] = $names;
235 } else {
236 $arr['_subelements'] = array_merge( $arr['_subelements'], $names );
237 }
238 }
239
240 /**
241 * In case the array contains indexed values (in addition to named),
242 * give all indexed values the given tag name. This function MUST be
243 * called on every array that has numerical indexes.
244 * @param array $arr
245 * @param string $tag Tag name
246 */
247 public function setIndexedTagName( &$arr, $tag ) {
248 // In raw mode, add the '_element', otherwise just ignore
249 if ( !$this->getIsRawMode() ) {
250 return;
251 }
252 if ( $arr === null || $tag === null || !is_array( $arr ) || is_array( $tag ) ) {
253 ApiBase::dieDebug( __METHOD__, 'Bad parameter' );
254 }
255 // Do not use setElement() as it is ok to call this more than once
256 $arr['_element'] = $tag;
257 }
258
259 /**
260 * Calls setIndexedTagName() on each sub-array of $arr
261 * @param array $arr
262 * @param string $tag Tag name
263 */
264 public function setIndexedTagName_recursive( &$arr, $tag ) {
265 if ( !is_array( $arr ) ) {
266 return;
267 }
268 foreach ( $arr as &$a ) {
269 if ( !is_array( $a ) ) {
270 continue;
271 }
272 $this->setIndexedTagName( $a, $tag );
273 $this->setIndexedTagName_recursive( $a, $tag );
274 }
275 }
276
277 /**
278 * Calls setIndexedTagName() on an array already in the result.
279 * Don't specify a path to a value that's not in the result, or
280 * you'll get nasty errors.
281 * @param array $path Path to the array, like addValue()'s $path
282 * @param string $tag
283 */
284 public function setIndexedTagName_internal( $path, $tag ) {
285 $data = &$this->mData;
286 foreach ( (array)$path as $p ) {
287 if ( !isset( $data[$p] ) ) {
288 $data[$p] = array();
289 }
290 $data = &$data[$p];
291 }
292 if ( is_null( $data ) ) {
293 return;
294 }
295 $this->setIndexedTagName( $data, $tag );
296 }
297
298 /**
299 * Add value to the output data at the given path.
300 * Path can be an indexed array, each element specifying the branch at which to add the new
301 * value. Setting $path to array('a','b','c') is equivalent to data['a']['b']['c'] = $value.
302 * If $path is null, the value will be inserted at the data root.
303 * If $name is empty, the $value is added as a next list element data[] = $value.
304 *
305 * @param array|string|null $path
306 * @param string $name
307 * @param mixed $value
308 * @param int $flags Zero or more OR-ed flags like OVERRIDE | ADD_ON_TOP. This
309 * parameter used to be boolean, and the value of OVERRIDE=1 was specifically
310 * chosen so that it would be backwards compatible with the new method
311 * signature.
312 * @return bool True if $value fits in the result, false if not
313 *
314 * @since 1.21 int $flags replaced boolean $override
315 */
316 public function addValue( $path, $name, $value, $flags = 0 ) {
317 $data = &$this->mData;
318 if ( $this->mCheckingSize ) {
319 $newsize = $this->mSize + self::size( $value );
320 $maxResultSize = $this->getConfig()->get( 'APIMaxResultSize' );
321 if ( $newsize > $maxResultSize ) {
322 $this->setWarning(
323 "This result was truncated because it would otherwise be larger than the " .
324 "limit of {$maxResultSize} bytes" );
325
326 return false;
327 }
328 $this->mSize = $newsize;
329 }
330
331 $addOnTop = $flags & ApiResult::ADD_ON_TOP;
332 if ( $path !== null ) {
333 foreach ( (array)$path as $p ) {
334 if ( !isset( $data[$p] ) ) {
335 if ( $addOnTop ) {
336 $data = array( $p => array() ) + $data;
337 $addOnTop = false;
338 } else {
339 $data[$p] = array();
340 }
341 }
342 $data = &$data[$p];
343 }
344 }
345
346 if ( !$name ) {
347 // Add list element
348 if ( $addOnTop ) {
349 // This element needs to be inserted in the beginning
350 // Numerical indexes will be renumbered
351 array_unshift( $data, $value );
352 } else {
353 // Add new value at the end
354 $data[] = $value;
355 }
356 } else {
357 // Add named element
358 self::setElement( $data, $name, $value, $flags );
359 }
360
361 return true;
362 }
363
364 /**
365 * Add a parsed limit=max to the result.
366 *
367 * @param string $moduleName
368 * @param int $limit
369 */
370 public function setParsedLimit( $moduleName, $limit ) {
371 // Add value, allowing overwriting
372 $this->addValue( 'limits', $moduleName, $limit, ApiResult::OVERRIDE );
373 }
374
375 /**
376 * Unset a value previously added to the result set.
377 * Fails silently if the value isn't found.
378 * For parameters, see addValue()
379 * @param array|null $path
380 * @param string $name
381 */
382 public function unsetValue( $path, $name ) {
383 $data = &$this->mData;
384 if ( $path !== null ) {
385 foreach ( (array)$path as $p ) {
386 if ( !isset( $data[$p] ) ) {
387 return;
388 }
389 $data = &$data[$p];
390 }
391 }
392 $this->mSize -= self::size( $data[$name] );
393 unset( $data[$name] );
394 }
395
396 /**
397 * Ensure all values in this result are valid UTF-8.
398 */
399 public function cleanUpUTF8() {
400 array_walk_recursive( $this->mData, array( 'ApiResult', 'cleanUp_helper' ) );
401 }
402
403 /**
404 * Callback function for cleanUpUTF8()
405 *
406 * @param string $s
407 */
408 private static function cleanUp_helper( &$s ) {
409 if ( !is_string( $s ) ) {
410 return;
411 }
412 global $wgContLang;
413 $s = $wgContLang->normalize( $s );
414 }
415
416 /**
417 * Converts a Status object to an array suitable for addValue
418 * @param Status $status
419 * @param string $errorType
420 * @return array
421 */
422 public function convertStatusToArray( $status, $errorType = 'error' ) {
423 if ( $status->isGood() ) {
424 return array();
425 }
426
427 $result = array();
428 foreach ( $status->getErrorsByType( $errorType ) as $error ) {
429 $this->setIndexedTagName( $error['params'], 'param' );
430 $result[] = $error;
431 }
432 $this->setIndexedTagName( $result, $errorType );
433
434 return $result;
435 }
436
437 public function execute() {
438 ApiBase::dieDebug( __METHOD__, 'execute() is not supported on Result object' );
439 }
440 }