API: Make UTF-8 cleanup actually work; it was broken from the beginning. Apparently...
[lhc/web/wiklou.git] / includes / api / ApiResult.php
1 <?php
2
3 /*
4 * Created on Sep 4, 2006
5 *
6 * API for MediaWiki 1.8+
7 *
8 * Copyright (C) 2006 Yuri Astrakhan <Firstname><Lastname>@gmail.com
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
23 * http://www.gnu.org/copyleft/gpl.html
24 */
25
26 if (!defined('MEDIAWIKI')) {
27 // Eclipse helper - will be ignored in production
28 require_once ('ApiBase.php');
29 }
30
31 /**
32 * This class represents the result of the API operations.
33 * It simply wraps a nested array() structure, adding some functions to simplify array's modifications.
34 * As various modules execute, they add different pieces of information to this result,
35 * structuring it as it will be given to the client.
36 *
37 * Each subarray may either be a dictionary - key-value pairs with unique keys,
38 * or lists, where the items are added using $data[] = $value notation.
39 *
40 * There are two special key values that change how XML output is generated:
41 * '_element' This key sets the tag name for the rest of the elements in the current array.
42 * It is only inserted if the formatter returned true for getNeedsRawData()
43 * '*' This key has special meaning only to the XML formatter, and is outputed as is
44 * for all others. In XML it becomes the content of the current element.
45 *
46 * @ingroup API
47 */
48 class ApiResult extends ApiBase {
49
50 private $mData, $mIsRawMode, $mSize, $mCheckingSize;
51
52 /**
53 * Constructor
54 */
55 public function __construct($main) {
56 parent :: __construct($main, 'result');
57 $this->mIsRawMode = false;
58 $this->mCheckingSize = true;
59 $this->reset();
60 }
61
62 /**
63 * Clear the current result data.
64 */
65 public function reset() {
66 $this->mData = array ();
67 $this->mSize = 0;
68 }
69
70 /**
71 * Call this function when special elements such as '_element'
72 * are needed by the formatter, for example in XML printing.
73 */
74 public function setRawMode() {
75 $this->mIsRawMode = true;
76 }
77
78 /**
79 * Returns true if the result is being created for the formatter that requested raw data.
80 */
81 public function getIsRawMode() {
82 return $this->mIsRawMode;
83 }
84
85 /**
86 * Get the result's internal data array (read-only)
87 */
88 public function getData() {
89 return $this->mData;
90 }
91
92 /**
93 * Get the 'real' size of a result item. This means the strlen() of the item,
94 * or the sum of the strlen()s of the elements if the item is an array.
95 * @param mixed $value
96 * @return int
97 */
98 public static function size($value) {
99 $s = 0;
100 if(is_array($value))
101 foreach($value as $v)
102 $s += self::size($v);
103 else if(!is_object($value))
104 // Objects can't always be cast to string
105 $s = strlen($value);
106 return $s;
107 }
108
109 /**
110 * Get the size of the result, i.e. the amount of bytes in it
111 * @return int
112 */
113 public function getSize() {
114 return $this->mSize;
115 }
116
117 /**
118 * Disable size checking in addValue(). Don't use this unless you
119 * REALLY know what you're doing. Values added while size checking
120 * was disabled will not be counted (ever)
121 */
122 public function disableSizeCheck() {
123 $this->mCheckingSize = false;
124 }
125
126 /**
127 * Re-enable size checking in addValue()
128 */
129 public function enableSizeCheck() {
130 $this->mCheckingSize = true;
131 }
132
133 /**
134 * Add an output value to the array by name.
135 * Verifies that value with the same name has not been added before.
136 */
137 public static function setElement(& $arr, $name, $value) {
138 if ($arr === null || $name === null || $value === null || !is_array($arr) || is_array($name))
139 ApiBase :: dieDebug(__METHOD__, 'Bad parameter');
140
141 if (!isset ($arr[$name])) {
142 $arr[$name] = $value;
143 }
144 elseif (is_array($arr[$name]) && is_array($value)) {
145 $merged = array_intersect_key($arr[$name], $value);
146 if (!count($merged))
147 $arr[$name] += $value;
148 else
149 ApiBase :: dieDebug(__METHOD__, "Attempting to merge element $name");
150 } else
151 ApiBase :: dieDebug(__METHOD__, "Attempting to add element $name=$value, existing value is {$arr[$name]}");
152 }
153
154 /**
155 * Adds the content element to the array.
156 * Use this function instead of hardcoding the '*' element.
157 * @param string $subElemName when present, content element is created as a sub item of the arr.
158 * Use this parameter to create elements in format <elem>text</elem> without attributes
159 */
160 public static function setContent(& $arr, $value, $subElemName = null) {
161 if (is_array($value))
162 ApiBase :: dieDebug(__METHOD__, 'Bad parameter');
163 if (is_null($subElemName)) {
164 ApiResult :: setElement($arr, '*', $value);
165 } else {
166 if (!isset ($arr[$subElemName]))
167 $arr[$subElemName] = array ();
168 ApiResult :: setElement($arr[$subElemName], '*', $value);
169 }
170 }
171
172 /**
173 * In case the array contains indexed values (in addition to named),
174 * all indexed values will have the given tag name.
175 */
176 public function setIndexedTagName(& $arr, $tag) {
177 // In raw mode, add the '_element', otherwise just ignore
178 if (!$this->getIsRawMode())
179 return;
180 if ($arr === null || $tag === null || !is_array($arr) || is_array($tag))
181 ApiBase :: dieDebug(__METHOD__, 'Bad parameter');
182 // Do not use setElement() as it is ok to call this more than once
183 $arr['_element'] = $tag;
184 }
185
186 /**
187 * Calls setIndexedTagName() on $arr and each sub-array
188 */
189 public function setIndexedTagName_recursive(&$arr, $tag)
190 {
191 if(!is_array($arr))
192 return;
193 foreach($arr as &$a)
194 {
195 if(!is_array($a))
196 continue;
197 $this->setIndexedTagName($a, $tag);
198 $this->setIndexedTagName_recursive($a, $tag);
199 }
200 }
201
202 /**
203 * Calls setIndexedTagName() on an array already in the result.
204 * Don't specify a path to a value that's not in the result, or
205 * you'll get nasty errors.
206 * @param array $path Path to the array, like addValue()'s path
207 * @param string $tag
208 */
209 public function setIndexedTagName_internal( $path, $tag ) {
210 $data = & $this->mData;
211 foreach((array)$path as $p)
212 $data = & $data[$p];
213 if(is_null($data))
214 return;
215 $this->setIndexedTagName($data, $tag);
216 }
217
218 /**
219 * Add value to the output data at the given path.
220 * Path is an indexed array, each element specifing the branch at which to add the new value
221 * Setting $path to array('a','b','c') is equivalent to data['a']['b']['c'] = $value
222 * If $name is empty, the $value is added as a next list element data[] = $value
223 * @return bool True if $value fits in the result, false if not
224 */
225 public function addValue($path, $name, $value) {
226 global $wgAPIMaxResultSize;
227 $data = & $this->mData;
228 if( $this->mCheckingSize ) {
229 $newsize = $this->mSize + self::size($value);
230 if($newsize > $wgAPIMaxResultSize)
231 return false;
232 $this->mSize = $newsize;
233 }
234
235 if (!is_null($path)) {
236 if (is_array($path)) {
237 foreach ($path as $p) {
238 if (!isset ($data[$p]))
239 $data[$p] = array ();
240 $data = & $data[$p];
241 }
242 } else {
243 if (!isset ($data[$path]))
244 $data[$path] = array ();
245 $data = & $data[$path];
246 }
247 }
248
249 if (!$name)
250 $data[] = $value; // Add list element
251 else
252 ApiResult :: setElement($data, $name, $value); // Add named element
253 return true;
254 }
255
256 /**
257 * Unset a value previously added to the result set.
258 * Fails silently if the value isn't found.
259 * For parameters, see addValue()
260 */
261 public function unsetValue($path, $name) {
262 $data = & $this->mData;
263 if(!is_null($path))
264 foreach((array)$path as $p) {
265 if(!isset($data[$p]))
266 return;
267 $data = & $data[$p];
268 }
269 $this->mSize -= self::size($data[$name]);
270 unset($data[$name]);
271 }
272
273 /**
274 * Ensure all values in this result are valid UTF-8.
275 */
276 public function cleanUpUTF8()
277 {
278 array_walk_recursive($this->mData, array('ApiResult', 'cleanUp_helper'));
279 }
280
281 private static function cleanUp_helper(&$s)
282 {
283 if(!is_string($s))
284 return;
285 $s = UtfNormal::cleanUp($s);
286 }
287
288 public function execute() {
289 ApiBase :: dieDebug(__METHOD__, 'execute() is not supported on Result object');
290 }
291
292 public function getVersion() {
293 return __CLASS__ . ': $Id$';
294 }
295 }
296
297 /* For compatibility with PHP versions < 5.1.0, define our own array_intersect_key function. */
298 if (!function_exists('array_intersect_key')) {
299 function array_intersect_key($isec, $keys) {
300 $argc = func_num_args();
301
302 if ($argc > 2) {
303 for ($i = 1; $isec && $i < $argc; $i++) {
304 $arr = func_get_arg($i);
305
306 foreach (array_keys($isec) as $key) {
307 if (!isset($arr[$key]))
308 unset($isec[$key]);
309 }
310 }
311
312 return $isec;
313 } else {
314 $res = array();
315 foreach (array_keys($isec) as $key) {
316 if (isset($keys[$key]))
317 $res[$key] = $isec[$key];
318 }
319
320 return $res;
321 }
322 }
323 }