Merge "Don't fallback from uk to ru"
[lhc/web/wiklou.git] / includes / api / ApiErrorFormatter.php
1 <?php
2 /**
3 * This file contains the ApiErrorFormatter definition, plus implementations of
4 * specific formatters.
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
20 *
21 * @file
22 */
23
24 /**
25 * Formats errors and warnings for the API, and add them to the associated
26 * ApiResult.
27 * @since 1.25
28 * @ingroup API
29 */
30 class ApiErrorFormatter {
31 /** @var Title Dummy title to silence warnings from MessageCache::parse() */
32 private static $dummyTitle = null;
33
34 /** @var ApiResult */
35 protected $result;
36
37 /** @var Language */
38 protected $lang;
39 protected $useDB = false;
40 protected $format = 'none';
41
42 /**
43 * @param ApiResult $result Into which data will be added
44 * @param Language $lang Used for i18n
45 * @param string $format
46 * - text: Error message as wikitext
47 * - html: Error message as HTML
48 * - raw: Raw message key and parameters, no human-readable text
49 * - none: Code and data only, no human-readable text
50 * @param bool $useDB Whether to use local translations for errors and warnings.
51 */
52 public function __construct( ApiResult $result, Language $lang, $format, $useDB = false ) {
53 $this->result = $result;
54 $this->lang = $lang;
55 $this->useDB = $useDB;
56 $this->format = $format;
57 }
58
59 /**
60 * Fetch a dummy title to set on Messages
61 * @return Title
62 */
63 protected function getDummyTitle() {
64 if ( self::$dummyTitle === null ) {
65 self::$dummyTitle = Title::makeTitle( NS_SPECIAL, 'Badtitle/' . __METHOD__ );
66 }
67 return self::$dummyTitle;
68 }
69
70 /**
71 * Add a warning to the result
72 * @param string $moduleName
73 * @param MessageSpecifier|array|string $msg i18n message for the warning
74 * @param string $code Machine-readable code for the warning. Defaults as
75 * for IApiMessage::getApiCode().
76 * @param array $data Machine-readable data for the warning, if any.
77 * Uses IApiMessage::getApiData() if $msg implements that interface.
78 */
79 public function addWarning( $moduleName, $msg, $code = null, $data = null ) {
80 $msg = ApiMessage::create( $msg, $code, $data )
81 ->inLanguage( $this->lang )
82 ->title( $this->getDummyTitle() )
83 ->useDatabase( $this->useDB );
84 $this->addWarningOrError( 'warning', $moduleName, $msg );
85 }
86
87 /**
88 * Add an error to the result
89 * @param string $moduleName
90 * @param MessageSpecifier|array|string $msg i18n message for the error
91 * @param string $code Machine-readable code for the warning. Defaults as
92 * for IApiMessage::getApiCode().
93 * @param array $data Machine-readable data for the warning, if any.
94 * Uses IApiMessage::getApiData() if $msg implements that interface.
95 */
96 public function addError( $moduleName, $msg, $code = null, $data = null ) {
97 $msg = ApiMessage::create( $msg, $code, $data )
98 ->inLanguage( $this->lang )
99 ->title( $this->getDummyTitle() )
100 ->useDatabase( $this->useDB );
101 $this->addWarningOrError( 'error', $moduleName, $msg );
102 }
103
104 /**
105 * Add warnings and errors from a Status object to the result
106 * @param string $moduleName
107 * @param Status $status
108 * @param string[] $types 'warning' and/or 'error'
109 */
110 public function addMessagesFromStatus(
111 $moduleName, Status $status, $types = [ 'warning', 'error' ]
112 ) {
113 if ( $status->isGood() || !$status->errors ) {
114 return;
115 }
116
117 $types = (array)$types;
118 foreach ( $status->errors as $error ) {
119 if ( !in_array( $error['type'], $types, true ) ) {
120 continue;
121 }
122
123 if ( $error['type'] === 'error' ) {
124 $tag = 'error';
125 } else {
126 // Assume any unknown type is a warning
127 $tag = 'warning';
128 }
129
130 if ( is_array( $error ) && isset( $error['message'] ) ) {
131 // Normal case
132 if ( $error['message'] instanceof Message ) {
133 $msg = ApiMessage::create( $error['message'], null, [] );
134 } else {
135 $args = isset( $error['params'] ) ? $error['params'] : [];
136 array_unshift( $args, $error['message'] );
137 $error += [ 'params' => [] ];
138 $msg = ApiMessage::create( $args, null, [] );
139 }
140 } elseif ( is_array( $error ) ) {
141 // Weird case handled by Message::getErrorMessage
142 $msg = ApiMessage::create( $error, null, [] );
143 } else {
144 // Another weird case handled by Message::getErrorMessage
145 $msg = ApiMessage::create( $error, null, [] );
146 }
147
148 $msg->inLanguage( $this->lang )
149 ->title( $this->getDummyTitle() )
150 ->useDatabase( $this->useDB );
151 $this->addWarningOrError( $tag, $moduleName, $msg );
152 }
153 }
154
155 /**
156 * Format messages from a Status as an array
157 * @param Status $status
158 * @param string $type 'warning' or 'error'
159 * @param string|null $format
160 * @return array
161 */
162 public function arrayFromStatus( Status $status, $type = 'error', $format = null ) {
163 if ( $status->isGood() || !$status->errors ) {
164 return [];
165 }
166
167 $result = new ApiResult( 1e6 );
168 $formatter = new ApiErrorFormatter(
169 $result, $this->lang, $format ?: $this->format, $this->useDB
170 );
171 $formatter->addMessagesFromStatus( 'dummy', $status, [ $type ] );
172 switch ( $type ) {
173 case 'error':
174 return (array)$result->getResultData( [ 'errors', 'dummy' ] );
175 case 'warning':
176 return (array)$result->getResultData( [ 'warnings', 'dummy' ] );
177 }
178 }
179
180 /**
181 * Actually add the warning or error to the result
182 * @param string $tag 'warning' or 'error'
183 * @param string $moduleName
184 * @param ApiMessage|ApiRawMessage $msg
185 */
186 protected function addWarningOrError( $tag, $moduleName, $msg ) {
187 $value = [ 'code' => $msg->getApiCode() ];
188 switch ( $this->format ) {
189 case 'wikitext':
190 $value += [
191 'text' => $msg->text(),
192 ApiResult::META_CONTENT => 'text',
193 ];
194 break;
195
196 case 'html':
197 $value += [
198 'html' => $msg->parse(),
199 ApiResult::META_CONTENT => 'html',
200 ];
201 break;
202
203 case 'raw':
204 $value += [
205 'key' => $msg->getKey(),
206 'params' => $msg->getParams(),
207 ];
208 ApiResult::setIndexedTagName( $value['params'], 'param' );
209 break;
210
211 case 'none':
212 break;
213 }
214 $value += $msg->getApiData();
215
216 $path = [ $tag . 's', $moduleName ];
217 $existing = $this->result->getResultData( $path );
218 if ( $existing === null || !in_array( $value, $existing ) ) {
219 $flags = ApiResult::NO_SIZE_CHECK;
220 if ( $existing === null ) {
221 $flags |= ApiResult::ADD_ON_TOP;
222 }
223 $this->result->addValue( $path, null, $value, $flags );
224 $this->result->addIndexedTagName( $path, $tag );
225 }
226 }
227 }
228
229 /**
230 * Format errors and warnings in the old style, for backwards compatibility.
231 * @since 1.25
232 * @deprecated Only for backwards compatibility, do not use
233 * @ingroup API
234 */
235 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
236 class ApiErrorFormatter_BackCompat extends ApiErrorFormatter {
237 // @codingStandardsIgnoreEnd
238
239 /**
240 * @param ApiResult $result Into which data will be added
241 */
242 public function __construct( ApiResult $result ) {
243 parent::__construct( $result, Language::factory( 'en' ), 'none', false );
244 }
245
246 public function arrayFromStatus( Status $status, $type = 'error', $format = null ) {
247 if ( $status->isGood() || !$status->errors ) {
248 return [];
249 }
250
251 $result = [];
252 foreach ( $status->getErrorsByType( $type ) as $error ) {
253 if ( $error['message'] instanceof Message ) {
254 $error = [
255 'message' => $error['message']->getKey(),
256 'params' => $error['message']->getParams(),
257 ] + $error;
258 }
259 ApiResult::setIndexedTagName( $error['params'], 'param' );
260 $result[] = $error;
261 }
262 ApiResult::setIndexedTagName( $result, $type );
263
264 return $result;
265 }
266
267 protected function addWarningOrError( $tag, $moduleName, $msg ) {
268 $value = $msg->plain();
269
270 if ( $tag === 'error' ) {
271 // In BC mode, only one error
272 $code = $msg->getApiCode();
273 if ( isset( ApiBase::$messageMap[$code] ) ) {
274 // Backwards compatibility
275 $code = ApiBase::$messageMap[$code]['code'];
276 }
277
278 $value = [
279 'code' => $code,
280 'info' => $value,
281 ] + $msg->getApiData();
282 $this->result->addValue( null, 'error', $value,
283 ApiResult::OVERRIDE | ApiResult::ADD_ON_TOP | ApiResult::NO_SIZE_CHECK );
284 } else {
285 // Don't add duplicate warnings
286 $tag .= 's';
287 $path = [ $tag, $moduleName ];
288 $oldWarning = $this->result->getResultData( [ $tag, $moduleName, $tag ] );
289 if ( $oldWarning !== null ) {
290 $warnPos = strpos( $oldWarning, $value );
291 // If $value was found in $oldWarning, check if it starts at 0 or after "\n"
292 if ( $warnPos !== false && ( $warnPos === 0 || $oldWarning[$warnPos - 1] === "\n" ) ) {
293 // Check if $value is followed by "\n" or the end of the $oldWarning
294 $warnPos += strlen( $value );
295 if ( strlen( $oldWarning ) <= $warnPos || $oldWarning[$warnPos] === "\n" ) {
296 return;
297 }
298 }
299 // If there is a warning already, append it to the existing one
300 $value = "$oldWarning\n$value";
301 }
302 $this->result->addContentValue( $path, $tag, $value,
303 ApiResult::OVERRIDE | ApiResult::ADD_ON_TOP | ApiResult::NO_SIZE_CHECK );
304 }
305 }
306 }