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