Call Linker methods statically
[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 if ( !defined( 'MEDIAWIKI' ) ) {
28 // Eclipse helper - will be ignored in production
29 require_once( 'ApiBase.php' );
30 }
31
32 /**
33 * This class represents the result of the API operations.
34 * It simply wraps a nested array() structure, adding some functions to simplify array's modifications.
35 * As various modules execute, they add different pieces of information to this result,
36 * structuring it as it will be given to the client.
37 *
38 * Each subarray may either be a dictionary - key-value pairs with unique keys,
39 * or lists, where the items are added using $data[] = $value notation.
40 *
41 * There are two special key values that change how XML output is generated:
42 * '_element' This key sets the tag name for the rest of the elements in the current array.
43 * It is only inserted if the formatter returned true for getNeedsRawData()
44 * '*' This key has special meaning only to the XML formatter, and is outputed as is
45 * for all others. In XML it becomes the content of the current element.
46 *
47 * @ingroup API
48 */
49 class ApiResult extends ApiBase {
50
51 private $mData, $mIsRawMode, $mSize, $mCheckingSize;
52
53 /**
54 * Constructor
55 * @param $main ApiMain object
56 */
57 public function __construct( $main ) {
58 parent::__construct( $main, 'result' );
59 $this->mIsRawMode = false;
60 $this->mCheckingSize = true;
61 $this->reset();
62 }
63
64 /**
65 * Clear the current result data.
66 */
67 public function reset() {
68 $this->mData = array();
69 $this->mSize = 0;
70 }
71
72 /**
73 * Call this function when special elements such as '_element'
74 * are needed by the formatter, for example in XML printing.
75 */
76 public function setRawMode() {
77 $this->mIsRawMode = true;
78 }
79
80 /**
81 * Returns true whether the formatter requested raw data.
82 * @return bool
83 */
84 public function getIsRawMode() {
85 return $this->mIsRawMode;
86 }
87
88 /**
89 * Get the result's internal data array (read-only)
90 * @return array
91 */
92 public function getData() {
93 return $this->mData;
94 }
95
96 /**
97 * Get the 'real' size of a result item. This means the strlen() of the item,
98 * or the sum of the strlen()s of the elements if the item is an array.
99 * @param $value mixed
100 * @return int
101 */
102 public static function size( $value ) {
103 $s = 0;
104 if ( is_array( $value ) ) {
105 foreach ( $value as $v ) {
106 $s += self::size( $v );
107 }
108 } elseif ( !is_object( $value ) ) {
109 // Objects can't always be cast to string
110 $s = strlen( $value );
111 }
112 return $s;
113 }
114
115 /**
116 * Get the size of the result, i.e. the amount of bytes in it
117 * @return int
118 */
119 public function getSize() {
120 return $this->mSize;
121 }
122
123 /**
124 * Disable size checking in addValue(). Don't use this unless you
125 * REALLY know what you're doing. Values added while size checking
126 * was disabled will not be counted (ever)
127 */
128 public function disableSizeCheck() {
129 $this->mCheckingSize = false;
130 }
131
132 /**
133 * Re-enable size checking in addValue()
134 */
135 public function enableSizeCheck() {
136 $this->mCheckingSize = true;
137 }
138
139 /**
140 * Add an output value to the array by name.
141 * Verifies that value with the same name has not been added before.
142 * @param $arr array to add $value to
143 * @param $name string Index of $arr to add $value at
144 * @param $value mixed
145 * @param $overwrite bool Whether overwriting an existing element is allowed
146 */
147 public static function setElement( &$arr, $name, $value, $overwrite = false ) {
148 if ( $arr === null || $name === null || $value === null || !is_array( $arr ) || is_array( $name ) ) {
149 ApiBase::dieDebug( __METHOD__, 'Bad parameter' );
150 }
151
152 if ( !isset ( $arr[$name] ) || $overwrite ) {
153 $arr[$name] = $value;
154 } elseif ( is_array( $arr[$name] ) && is_array( $value ) ) {
155 $merged = array_intersect_key( $arr[$name], $value );
156 if ( !count( $merged ) ) {
157 $arr[$name] += $value;
158 } else {
159 ApiBase::dieDebug( __METHOD__, "Attempting to merge element $name" );
160 }
161 } else {
162 ApiBase::dieDebug( __METHOD__, "Attempting to add element $name=$value, existing value is {$arr[$name]}" );
163 }
164 }
165
166 /**
167 * Adds a content element to an array.
168 * Use this function instead of hardcoding the '*' element.
169 * @param $arr array to add the content element to
170 * @param $value Mixed
171 * @param $subElemName string when present, content element is created
172 * as a sub item of $arr. Use this parameter to create elements in
173 * format <elem>text</elem> without attributes
174 */
175 public static function setContent( &$arr, $value, $subElemName = null ) {
176 if ( is_array( $value ) ) {
177 ApiBase::dieDebug( __METHOD__, 'Bad parameter' );
178 }
179 if ( is_null( $subElemName ) ) {
180 ApiResult::setElement( $arr, '*', $value );
181 } else {
182 if ( !isset( $arr[$subElemName] ) ) {
183 $arr[$subElemName] = array();
184 }
185 ApiResult::setElement( $arr[$subElemName], '*', $value );
186 }
187 }
188
189 /**
190 * In case the array contains indexed values (in addition to named),
191 * give all indexed values the given tag name. This function MUST be
192 * called on every array that has numerical indexes.
193 * @param $arr array
194 * @param $tag string Tag name
195 */
196 public function setIndexedTagName( &$arr, $tag ) {
197 // In raw mode, add the '_element', otherwise just ignore
198 if ( !$this->getIsRawMode() ) {
199 return;
200 }
201 if ( $arr === null || $tag === null || !is_array( $arr ) || is_array( $tag ) ) {
202 ApiBase::dieDebug( __METHOD__, 'Bad parameter' );
203 }
204 // Do not use setElement() as it is ok to call this more than once
205 $arr['_element'] = $tag;
206 }
207
208 /**
209 * Calls setIndexedTagName() on each sub-array of $arr
210 * @param $arr array
211 * @param $tag string Tag name
212 */
213 public function setIndexedTagName_recursive( &$arr, $tag ) {
214 if ( !is_array( $arr ) ) {
215 return;
216 }
217 foreach ( $arr as &$a ) {
218 if ( !is_array( $a ) ) {
219 continue;
220 }
221 $this->setIndexedTagName( $a, $tag );
222 $this->setIndexedTagName_recursive( $a, $tag );
223 }
224 }
225
226 /**
227 * Calls setIndexedTagName() on an array already in the result.
228 * Don't specify a path to a value that's not in the result, or
229 * you'll get nasty errors.
230 * @param $path array Path to the array, like addValue()'s $path
231 * @param $tag string
232 */
233 public function setIndexedTagName_internal( $path, $tag ) {
234 $data = &$this->mData;
235 foreach ( (array)$path as $p ) {
236 if ( !isset( $data[$p] ) ) {
237 $data[$p] = array();
238 }
239 $data = &$data[$p];
240 }
241 if ( is_null( $data ) ) {
242 return;
243 }
244 $this->setIndexedTagName( $data, $tag );
245 }
246
247 /**
248 * Add value to the output data at the given path.
249 * Path is an indexed array, each element specifying the branch at which to add the new value
250 * Setting $path to array('a','b','c') is equivalent to data['a']['b']['c'] = $value
251 * If $name is empty, the $value is added as a next list element data[] = $value
252 *
253 * @param $path
254 * @param $name string
255 * @param $value mixed
256 * @param $overwrite bool
257 *
258 * @return bool True if $value fits in the result, false if not
259 */
260 public function addValue( $path, $name, $value, $overwrite = false ) {
261 global $wgAPIMaxResultSize;
262
263 $data = &$this->mData;
264 if ( $this->mCheckingSize ) {
265 $newsize = $this->mSize + self::size( $value );
266 if ( $newsize > $wgAPIMaxResultSize ) {
267 $this->setWarning(
268 "This result was truncated because it would otherwise be larger than the " .
269 "limit of {$wgAPIMaxResultSize} bytes" );
270 return false;
271 }
272 $this->mSize = $newsize;
273 }
274
275 if ( !is_null( $path ) ) {
276 if ( is_array( $path ) ) {
277 foreach ( $path as $p ) {
278 if ( !isset( $data[$p] ) ) {
279 $data[$p] = array();
280 }
281 $data = &$data[$p];
282 }
283 } else {
284 if ( !isset( $data[$path] ) ) {
285 $data[$path] = array();
286 }
287 $data = &$data[$path];
288 }
289 }
290
291 if ( !$name ) {
292 $data[] = $value; // Add list element
293 } else {
294 self::setElement( $data, $name, $value, $overwrite ); // Add named element
295 }
296 return true;
297 }
298
299 /**
300 * Add a parsed limit=max to the result.
301 *
302 * @param $moduleName string
303 * @param $limit int
304 */
305 public function setParsedLimit( $moduleName, $limit ) {
306 // Add value, allowing overwriting
307 $this->addValue( 'limits', $moduleName, $limit, true );
308 }
309
310 /**
311 * Unset a value previously added to the result set.
312 * Fails silently if the value isn't found.
313 * For parameters, see addValue()
314 * @param $path array
315 * @param $name string
316 */
317 public function unsetValue( $path, $name ) {
318 $data = &$this->mData;
319 if ( !is_null( $path ) ) {
320 foreach ( (array)$path as $p ) {
321 if ( !isset( $data[$p] ) ) {
322 return;
323 }
324 $data = &$data[$p];
325 }
326 }
327 $this->mSize -= self::size( $data[$name] );
328 unset( $data[$name] );
329 }
330
331 /**
332 * Ensure all values in this result are valid UTF-8.
333 */
334 public function cleanUpUTF8() {
335 array_walk_recursive( $this->mData, array( 'ApiResult', 'cleanUp_helper' ) );
336 }
337
338 /**
339 * Callback function for cleanUpUTF8()
340 *
341 * @param $s string
342 */
343 private static function cleanUp_helper( &$s ) {
344 if ( !is_string( $s ) ) {
345 return;
346 }
347 global $wgContLang;
348 $s = $wgContLang->normalize( $s );
349 }
350
351 /**
352 * Converts a Status object to an array suitable for addValue
353 * @param Status $status
354 * @param string $errorType
355 * @return array
356 */
357 public function convertStatusToArray( $status, $errorType = 'error' ) {
358 if ( $status->isGood() ) {
359 return array();
360 }
361
362 $result = array();
363 foreach ( $status->getErrorsByType( $errorType ) as $error ) {
364 $this->setIndexedTagName( $error['params'], 'param' );
365 $result[] = $error;
366 }
367 $this->setIndexedTagName( $result, $errorType );
368 return $result;
369 }
370
371 public function execute() {
372 ApiBase::dieDebug( __METHOD__, 'execute() is not supported on Result object' );
373 }
374
375 public function getVersion() {
376 return __CLASS__ . ': $Id$';
377 }
378 }