Merge "Whitelist the <wbr> element."
[mediawiki.git] / includes / api / ApiResult.php
blob39c114b822ab872a5d2cc851e2742ef82af5075b
1 <?php
2 /**
5 * Created on Sep 4, 2006
7 * Copyright © 2006 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
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.
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.
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
24 * @file
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.
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.
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.
42 * @ingroup API
44 class ApiResult extends ApiBase {
46 /**
47 * override existing value in addValue() and setElement()
48 * @since 1.21
50 const OVERRIDE = 1;
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
57 const ADD_ON_TOP = 2;
59 private $mData, $mIsRawMode, $mSize, $mCheckingSize;
61 /**
62 * Constructor
63 * @param $main ApiMain object
65 public function __construct( $main ) {
66 parent::__construct( $main, 'result' );
67 $this->mIsRawMode = false;
68 $this->mCheckingSize = true;
69 $this->reset();
72 /**
73 * Clear the current result data.
75 public function reset() {
76 $this->mData = array();
77 $this->mSize = 0;
80 /**
81 * Call this function when special elements such as '_element'
82 * are needed by the formatter, for example in XML printing.
84 public function setRawMode() {
85 $this->mIsRawMode = true;
88 /**
89 * Returns true whether the formatter requested raw data.
90 * @return bool
92 public function getIsRawMode() {
93 return $this->mIsRawMode;
96 /**
97 * Get the result's internal data array (read-only)
98 * @return array
100 public function getData() {
101 return $this->mData;
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
110 public static function size( $value ) {
111 $s = 0;
112 if ( is_array( $value ) ) {
113 foreach ( $value as $v ) {
114 $s += self::size( $v );
116 } elseif ( !is_object( $value ) ) {
117 // Objects can't always be cast to string
118 $s = strlen( $value );
120 return $s;
124 * Get the size of the result, i.e. the amount of bytes in it
125 * @return int
127 public function getSize() {
128 return $this->mSize;
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)
136 public function disableSizeCheck() {
137 $this->mCheckingSize = false;
141 * Re-enable size checking in addValue()
143 public function enableSizeCheck() {
144 $this->mCheckingSize = true;
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 array $arr to add $value to
151 * @param string $name Index of $arr to add $value at
152 * @param $value mixed
153 * @param int $flags 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.
157 * @since 1.21 int $flags replaced boolean $override
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' );
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;
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" );
178 } else {
179 ApiBase::dieDebug( __METHOD__, "Attempting to add element $name=$value, existing value is {$arr[$name]}" );
184 * Adds a content element to an array.
185 * Use this function instead of hardcoding the '*' element.
186 * @param array $arr to add the content element to
187 * @param $value Mixed
188 * @param string $subElemName 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.
192 public static function setContent( &$arr, $value, $subElemName = null ) {
193 if ( is_array( $value ) ) {
194 ApiBase::dieDebug( __METHOD__, 'Bad parameter' );
196 if ( is_null( $subElemName ) ) {
197 ApiResult::setElement( $arr, '*', $value );
198 } else {
199 if ( !isset( $arr[$subElemName] ) ) {
200 $arr[$subElemName] = array();
202 ApiResult::setElement( $arr[$subElemName], '*', $value );
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 string $tag Tag name
213 public function setIndexedTagName( &$arr, $tag ) {
214 // In raw mode, add the '_element', otherwise just ignore
215 if ( !$this->getIsRawMode() ) {
216 return;
218 if ( $arr === null || $tag === null || !is_array( $arr ) || is_array( $tag ) ) {
219 ApiBase::dieDebug( __METHOD__, 'Bad parameter' );
221 // Do not use setElement() as it is ok to call this more than once
222 $arr['_element'] = $tag;
226 * Calls setIndexedTagName() on each sub-array of $arr
227 * @param $arr array
228 * @param string $tag Tag name
230 public function setIndexedTagName_recursive( &$arr, $tag ) {
231 if ( !is_array( $arr ) ) {
232 return;
234 foreach ( $arr as &$a ) {
235 if ( !is_array( $a ) ) {
236 continue;
238 $this->setIndexedTagName( $a, $tag );
239 $this->setIndexedTagName_recursive( $a, $tag );
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 array $path Path to the array, like addValue()'s $path
248 * @param $tag string
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();
256 $data = &$data[$p];
258 if ( is_null( $data ) ) {
259 return;
261 $this->setIndexedTagName( $data, $tag );
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.
271 * @param $path array|string|null
272 * @param $name string
273 * @param $value mixed
274 * @param int $flags 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
279 * @since 1.21 int $flags replaced boolean $override
281 public function addValue( $path, $name, $value, $flags = 0 ) {
282 global $wgAPIMaxResultSize;
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;
293 $this->mSize = $newsize;
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();
307 $data = &$data[$p];
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;
321 } else {
322 // Add named element
323 self::setElement( $data, $name, $value, $flags );
325 return true;
329 * Add a parsed limit=max to the result.
331 * @param $moduleName string
332 * @param $limit int
334 public function setParsedLimit( $moduleName, $limit ) {
335 // Add value, allowing overwriting
336 $this->addValue( 'limits', $moduleName, $limit, ApiResult::OVERRIDE );
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
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;
353 $data = &$data[$p];
356 $this->mSize -= self::size( $data[$name] );
357 unset( $data[$name] );
361 * Ensure all values in this result are valid UTF-8.
363 public function cleanUpUTF8() {
364 array_walk_recursive( $this->mData, array( 'ApiResult', 'cleanUp_helper' ) );
368 * Callback function for cleanUpUTF8()
370 * @param $s string
372 private static function cleanUp_helper( &$s ) {
373 if ( !is_string( $s ) ) {
374 return;
376 global $wgContLang;
377 $s = $wgContLang->normalize( $s );
381 * Converts a Status object to an array suitable for addValue
382 * @param Status $status
383 * @param string $errorType
384 * @return array
386 public function convertStatusToArray( $status, $errorType = 'error' ) {
387 if ( $status->isGood() ) {
388 return array();
391 $result = array();
392 foreach ( $status->getErrorsByType( $errorType ) as $error ) {
393 $this->setIndexedTagName( $error['params'], 'param' );
394 $result[] = $error;
396 $this->setIndexedTagName( $result, $errorType );
397 return $result;
400 public function execute() {
401 ApiBase::dieDebug( __METHOD__, 'execute() is not supported on Result object' );