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