wfMsgForContentNoTrans() was removed
[mediawiki.git] / includes / api / ApiErrorFormatter.php
blob37cb19d3148bfac2ac7fbb6684e62e9087833860
1 <?php
2 /**
3 * This file contains the ApiErrorFormatter definition, plus implementations of
4 * specific formatters.
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.
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.
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
21 * @file
24 /**
25 * Formats errors and warnings for the API, and add them to the associated
26 * ApiResult.
27 * @since 1.25
28 * @ingroup API
30 class ApiErrorFormatter {
31 /** @var Title Dummy title to silence warnings from MessageCache::parse() */
32 private static $dummyTitle = null;
34 /** @var ApiResult */
35 protected $result;
37 /** @var Language */
38 protected $lang;
39 protected $useDB = false;
40 protected $format = 'none';
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.
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;
59 /**
60 * Fetch a dummy title to set on Messages
61 * @return Title
63 protected function getDummyTitle() {
64 if ( self::$dummyTitle === null ) {
65 self::$dummyTitle = Title::makeTitle( NS_SPECIAL, 'Badtitle/' . __METHOD__ );
67 return self::$dummyTitle;
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.
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 );
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.
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 );
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'
110 public function addMessagesFromStatus(
111 $moduleName, Status $status, $types = array( 'warning', 'error' )
113 if ( $status->isGood() || !$status->errors ) {
114 return;
117 $types = (array)$types;
118 foreach ( $status->errors as $error ) {
119 if ( !in_array( $error['type'], $types, true ) ) {
120 continue;
123 if ( $error['type'] === 'error' ) {
124 $tag = 'error';
125 } else {
126 // Assume any unknown type is a warning
127 $tag = 'warning';
130 if ( is_array( $error ) && isset( $error['message'] ) ) {
131 // Normal case
132 if ( $error['message'] instanceof Message ) {
133 $msg = ApiMessage::create( $error['message'], null, array() );
134 } else {
135 $args = isset( $error['params'] ) ? $error['params'] : array();
136 array_unshift( $args, $error['message'] );
137 $error += array( 'params' => array() );
138 $msg = ApiMessage::create( $args, null, array() );
140 } elseif ( is_array( $error ) ) {
141 // Weird case handled by Message::getErrorMessage
142 $msg = ApiMessage::create( $error, null, array() );
143 } else {
144 // Another weird case handled by Message::getErrorMessage
145 $msg = ApiMessage::create( $error, null, array() );
148 $msg->inLanguage( $this->lang )
149 ->title( $this->getDummyTitle() )
150 ->useDatabase( $this->useDB );
151 $this->addWarningOrError( $tag, $moduleName, $msg );
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
162 public function arrayFromStatus( Status $status, $type = 'error', $format = null ) {
163 if ( $status->isGood() || !$status->errors ) {
164 return array();
167 $result = new ApiResult( 1e6 );
168 $formatter = new ApiErrorFormatter(
169 $result, $this->lang, $format ?: $this->format, $this->useDB
171 $formatter->addMessagesFromStatus( 'dummy', $status, array( $type ) );
172 switch ( $type ) {
173 case 'error':
174 return (array)$result->getResultData( array( 'errors', 'dummy' ) );
175 case 'warning':
176 return (array)$result->getResultData( array( 'warnings', 'dummy' ) );
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
186 protected function addWarningOrError( $tag, $moduleName, $msg ) {
187 $value = array( 'code' => $msg->getApiCode() );
188 switch ( $this->format ) {
189 case 'wikitext':
190 $value += array(
191 'text' => $msg->text(),
192 ApiResult::META_CONTENT => 'text',
194 break;
196 case 'html':
197 $value += array(
198 'html' => $msg->parse(),
199 ApiResult::META_CONTENT => 'html',
201 break;
203 case 'raw':
204 $value += array(
205 'message' => $msg->getKey(),
206 'params' => $msg->getParams(),
208 ApiResult::setIndexedTagName( $value['params'], 'param' );
209 break;
211 case 'none':
212 break;
214 $value += $msg->getApiData();
216 $path = array( $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;
223 $this->result->addValue( $path, null, $value, $flags );
224 $this->result->addIndexedTagName( $path, $tag );
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
235 // @codingStandardsIgnoreStart Squiz.Classes.ValidClassName.NotCamelCaps
236 class ApiErrorFormatter_BackCompat extends ApiErrorFormatter {
237 // @codingStandardsIgnoreEnd
240 * @param ApiResult $result Into which data will be added
242 public function __construct( ApiResult $result ) {
243 parent::__construct( $result, Language::factory( 'en' ), 'none', false );
246 public function arrayFromStatus( Status $status, $type = 'error', $format = null ) {
247 if ( $status->isGood() || !$status->errors ) {
248 return array();
251 $result = array();
252 foreach ( $status->getErrorsByType( $type ) as $error ) {
253 if ( $error['message'] instanceof Message ) {
254 $error = array(
255 'message' => $error['message']->getKey(),
256 'params' => $error['message']->getParams(),
257 ) + $error;
259 ApiResult::setIndexedTagName( $error['params'], 'param' );
260 $result[] = $error;
262 ApiResult::setIndexedTagName( $result, $type );
264 return $result;
267 protected function addWarningOrError( $tag, $moduleName, $msg ) {
268 $value = $msg->plain();
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'];
278 $value = array(
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 = array( $tag, $moduleName );
288 $oldWarning = $this->result->getResultData( array( $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;
299 // If there is a warning already, append it to the existing one
300 $value = "$oldWarning\n$value";
302 $this->result->addContentValue( $path, $tag, $value,
303 ApiResult::OVERRIDE | ApiResult::ADD_ON_TOP | ApiResult::NO_SIZE_CHECK );