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