Merge "Add attributes parameter to ShowSearchHitTitle"
[lhc/web/wiklou.git] / includes / api / ApiMessage.php
1 <?php
2 /**
3 * Defines an interface for messages with additional machine-readable data for
4 * use by the API, and provides concrete implementations of that interface.
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 * Interface for messages with machine-readable data for use by the API
26 *
27 * The idea is that it's a Message that has some extra data for the API to use when interpreting it
28 * as an error (or, in the future, as a warning). Internals of MediaWiki often use messages (or
29 * message keys, or Status objects containing messages) to pass information about errors to the user
30 * (see e.g. Title::getUserPermissionsErrors()) and the API has to make do with that.
31 *
32 * @since 1.25
33 * @note This interface exists to work around PHP's inheritance, so ApiMessage
34 * can extend Message and ApiRawMessage can extend RawMessage while still
35 * allowing an instanceof check for a Message object including this
36 * functionality. If for some reason you feel the need to implement this
37 * interface on some other class, that class must also implement all the
38 * public methods the Message class provides (not just those from
39 * MessageSpecifier, which as written is fairly useless).
40 * @ingroup API
41 */
42 interface IApiMessage extends MessageSpecifier {
43 /**
44 * Returns a machine-readable code for use by the API
45 *
46 * If no code was specifically set, the message key is used as the code
47 * after removing "apiwarn-" or "apierror-" prefixes and applying
48 * backwards-compatibility mappings.
49 *
50 * @return string
51 */
52 public function getApiCode();
53
54 /**
55 * Returns additional machine-readable data about the error condition
56 * @return array
57 */
58 public function getApiData();
59
60 /**
61 * Sets the machine-readable code for use by the API
62 * @param string|null $code If null, uses the default (see self::getApiCode())
63 * @param array|null $data If non-null, passed to self::setApiData()
64 */
65 public function setApiCode( $code, array $data = null );
66
67 /**
68 * Sets additional machine-readable data about the error condition
69 * @param array $data
70 */
71 public function setApiData( array $data );
72 }
73
74 /**
75 * Trait to implement the IApiMessage interface for Message subclasses
76 * @since 1.27
77 * @ingroup API
78 */
79 trait ApiMessageTrait {
80
81 /**
82 * Compatibility code mappings for various MW messages.
83 * @todo Ideally anything relying on this should be changed to use ApiMessage.
84 */
85 protected static $messageMap = [
86 'actionthrottledtext' => 'ratelimited',
87 'autoblockedtext' => 'autoblocked',
88 'badaccess-group0' => 'permissiondenied',
89 'badaccess-groups' => 'permissiondenied',
90 'badipaddress' => 'invalidip',
91 'blankpage' => 'emptypage',
92 'blockedtext' => 'blocked',
93 'cannotdelete' => 'cantdelete',
94 'cannotundelete' => 'cantundelete',
95 'cantmove-titleprotected' => 'protectedtitle',
96 'cantrollback' => 'onlyauthor',
97 'confirmedittext' => 'confirmemail',
98 'content-not-allowed-here' => 'contentnotallowedhere',
99 'deleteprotected' => 'cantedit',
100 'delete-toobig' => 'bigdelete',
101 'edit-conflict' => 'editconflict',
102 'imagenocrossnamespace' => 'nonfilenamespace',
103 'imagetypemismatch' => 'filetypemismatch',
104 'importbadinterwiki' => 'badinterwiki',
105 'importcantopen' => 'cantopenfile',
106 'import-noarticle' => 'badinterwiki',
107 'importnofile' => 'nofile',
108 'importuploaderrorpartial' => 'partialupload',
109 'importuploaderrorsize' => 'filetoobig',
110 'importuploaderrortemp' => 'notempdir',
111 'ipb_already_blocked' => 'alreadyblocked',
112 'ipb_blocked_as_range' => 'blockedasrange',
113 'ipb_cant_unblock' => 'cantunblock',
114 'ipb_expiry_invalid' => 'invalidexpiry',
115 'ip_range_invalid' => 'invalidrange',
116 'mailnologin' => 'cantsend',
117 'markedaspatrollederror-noautopatrol' => 'noautopatrol',
118 'movenologintext' => 'cantmove-anon',
119 'movenotallowed' => 'cantmove',
120 'movenotallowedfile' => 'cantmovefile',
121 'namespaceprotected' => 'protectednamespace',
122 'nocreate-loggedin' => 'cantcreate',
123 'nocreatetext' => 'cantcreate-anon',
124 'noname' => 'invaliduser',
125 'nosuchusershort' => 'nosuchuser',
126 'notanarticle' => 'missingtitle',
127 'nouserspecified' => 'invaliduser',
128 'ns-specialprotected' => 'unsupportednamespace',
129 'protect-cantedit' => 'cantedit',
130 'protectedinterface' => 'protectednamespace-interface',
131 'protectedpagetext' => 'protectedpage',
132 'range_block_disabled' => 'rangedisabled',
133 'rcpatroldisabled' => 'patroldisabled',
134 'readonlytext' => 'readonly',
135 'sessionfailure' => 'badtoken',
136 'systemblockedtext' => 'blocked',
137 'titleprotected' => 'protectedtitle',
138 'undo-failure' => 'undofailure',
139 'userrights-nodatabase' => 'nosuchdatabase',
140 'userrights-no-interwiki' => 'nointerwikiuserrights',
141 ];
142
143 protected $apiCode = null;
144 protected $apiData = [];
145
146 public function getApiCode() {
147 if ( $this->apiCode === null ) {
148 $key = $this->getKey();
149 if ( isset( self::$messageMap[$key] ) ) {
150 $this->apiCode = self::$messageMap[$key];
151 } elseif ( $key === 'apierror-missingparam' ) {
152 /// @todo: Kill this case along with ApiBase::$messageMap
153 $this->apiCode = 'no' . $this->getParams()[0];
154 } elseif ( substr( $key, 0, 8 ) === 'apiwarn-' ) {
155 $this->apiCode = substr( $key, 8 );
156 } elseif ( substr( $key, 0, 9 ) === 'apierror-' ) {
157 $this->apiCode = substr( $key, 9 );
158 } else {
159 $this->apiCode = $key;
160 }
161 }
162 return $this->apiCode;
163 }
164
165 public function setApiCode( $code, array $data = null ) {
166 if ( $code !== null && !( is_string( $code ) && $code !== '' ) ) {
167 throw new InvalidArgumentException( "Invalid code \"$code\"" );
168 }
169
170 $this->apiCode = $code;
171 if ( $data !== null ) {
172 $this->setApiData( $data );
173 }
174 }
175
176 public function getApiData() {
177 return $this->apiData;
178 }
179
180 public function setApiData( array $data ) {
181 $this->apiData = $data;
182 }
183
184 public function serialize() {
185 return serialize( [
186 'parent' => parent::serialize(),
187 'apiCode' => $this->apiCode,
188 'apiData' => $this->apiData,
189 ] );
190 }
191
192 public function unserialize( $serialized ) {
193 $data = unserialize( $serialized );
194 parent::unserialize( $data['parent'] );
195 $this->apiCode = $data['apiCode'];
196 $this->apiData = $data['apiData'];
197 }
198 }
199
200 /**
201 * Extension of Message implementing IApiMessage
202 * @since 1.25
203 * @ingroup API
204 */
205 class ApiMessage extends Message implements IApiMessage {
206 use ApiMessageTrait;
207
208 /**
209 * Create an IApiMessage for the message
210 *
211 * This returns $msg if it's an IApiMessage, calls 'new ApiRawMessage' if
212 * $msg is a RawMessage, or calls 'new ApiMessage' in all other cases.
213 *
214 * @param Message|RawMessage|array|string $msg
215 * @param string|null $code
216 * @param array|null $data
217 * @return IApiMessage
218 */
219 public static function create( $msg, $code = null, array $data = null ) {
220 if ( is_array( $msg ) ) {
221 // From StatusValue
222 if ( isset( $msg['message'] ) ) {
223 if ( isset( $msg['params'] ) ) {
224 $msg = array_merge( [ $msg['message'] ], $msg['params'] );
225 } else {
226 $msg = [ $msg['message'] ];
227 }
228 }
229
230 // Weirdness that comes in sometimes, including the above
231 if ( $msg[0] instanceof MessageSpecifier ) {
232 $msg = $msg[0];
233 }
234 }
235
236 if ( $msg instanceof IApiMessage ) {
237 return $msg;
238 } elseif ( $msg instanceof RawMessage ) {
239 return new ApiRawMessage( $msg, $code, $data );
240 } else {
241 return new ApiMessage( $msg, $code, $data );
242 }
243 }
244
245 /**
246 * @param Message|string|array $msg
247 * - Message: is cloned
248 * - array: first element is $key, rest are $params to Message::__construct
249 * - string: passed to Message::__construct
250 * @param string|null $code
251 * @param array|null $data
252 */
253 public function __construct( $msg, $code = null, array $data = null ) {
254 if ( $msg instanceof Message ) {
255 foreach ( get_class_vars( get_class( $this ) ) as $key => $value ) {
256 if ( isset( $msg->$key ) ) {
257 $this->$key = $msg->$key;
258 }
259 }
260 } elseif ( is_array( $msg ) ) {
261 $key = array_shift( $msg );
262 parent::__construct( $key, $msg );
263 } else {
264 parent::__construct( $msg );
265 }
266 $this->setApiCode( $code, $data );
267 }
268 }
269
270 /**
271 * Extension of RawMessage implementing IApiMessage
272 * @since 1.25
273 * @ingroup API
274 */
275 class ApiRawMessage extends RawMessage implements IApiMessage {
276 use ApiMessageTrait;
277
278 /**
279 * @param RawMessage|string|array $msg
280 * - RawMessage: is cloned
281 * - array: first element is $key, rest are $params to RawMessage::__construct
282 * - string: passed to RawMessage::__construct
283 * @param string|null $code
284 * @param array|null $data
285 */
286 public function __construct( $msg, $code = null, array $data = null ) {
287 if ( $msg instanceof RawMessage ) {
288 foreach ( get_class_vars( get_class( $this ) ) as $key => $value ) {
289 if ( isset( $msg->$key ) ) {
290 $this->$key = $msg->$key;
291 }
292 }
293 } elseif ( is_array( $msg ) ) {
294 $key = array_shift( $msg );
295 parent::__construct( $key, $msg );
296 } else {
297 parent::__construct( $msg );
298 }
299 $this->setApiCode( $code, $data );
300 }
301 }