1 /*
2    +----------------------------------------------------------------------+
3    | PHP Version 5                                                        |
4    +----------------------------------------------------------------------+
5    | This source file is subject to version 3.01 of the PHP license,      |
6    | that is bundled with this package in the file LICENSE, and is        |
7    | available through the world-wide-web at the following url:           |
8    | http://www.php.net/license/3_01.txt                                  |
9    | If you did not receive a copy of the PHP license and are unable to   |
10    | obtain it through the world-wide-web, please send a note to          |
11    | license@php.net so we can mail you a copy immediately.               |
12    +----------------------------------------------------------------------+
13    | Authors: Stanislav Malyshev <stas@zend.com>                          |
14    +----------------------------------------------------------------------+
15  */
16 
17 #ifdef HAVE_CONFIG_H
18 #include "config.h"
19 #endif
20 
21 #include "../intl_cppshims.h"
22 
23 #include <limits.h>
24 #include <unicode/msgfmt.h>
25 #include <unicode/chariter.h>
26 #include <unicode/ustdio.h>
27 #include <unicode/timezone.h>
28 #include <unicode/datefmt.h>
29 #include <unicode/calendar.h>
30 
31 #include <vector>
32 
33 #include "../intl_convertcpp.h"
34 #include "../common/common_date.h"
35 
36 extern "C" {
37 #include "php_intl.h"
38 #include "msgformat_class.h"
39 #include "msgformat_format.h"
40 #include "msgformat_helpers.h"
41 #include "intl_convert.h"
42 #define USE_TIMEZONE_POINTER
43 #include "../timezone/timezone_class.h"
44 }
45 
46 #if U_ICU_VERSION_MAJOR_NUM * 10 + U_ICU_VERSION_MINOR_NUM >= 48
47 #define HAS_MESSAGE_PATTERN 1
48 #endif
49 
50 U_NAMESPACE_BEGIN
51 /**
52  * This class isolates our access to private internal methods of
53  * MessageFormat.  It is never instantiated; it exists only for C++
54  * access management.
55  */
56 class MessageFormatAdapter {
57 public:
58     static const Formattable::Type* getArgTypeList(const MessageFormat& m,
59                                                    int32_t& count);
60 #ifdef HAS_MESSAGE_PATTERN
61     static const MessagePattern getMessagePattern(MessageFormat* m);
62 #endif
63 };
64 
65 const Formattable::Type*
getArgTypeList(const MessageFormat & m,int32_t & count)66 MessageFormatAdapter::getArgTypeList(const MessageFormat& m,
67                                      int32_t& count) {
68     return m.getArgTypeList(count);
69 }
70 
71 #ifdef HAS_MESSAGE_PATTERN
72 const MessagePattern
getMessagePattern(MessageFormat * m)73 MessageFormatAdapter::getMessagePattern(MessageFormat* m) {
74     return m->msgPattern;
75 }
76 #endif
77 U_NAMESPACE_END
78 
umsg_format_arg_count(UMessageFormat * fmt)79 U_CFUNC int32_t umsg_format_arg_count(UMessageFormat *fmt)
80 {
81 	int32_t fmt_count = 0;
82 	MessageFormatAdapter::getArgTypeList(*(const MessageFormat*)fmt, fmt_count);
83 	return fmt_count;
84 }
85 
umsg_get_numeric_types(MessageFormatter_object * mfo,intl_error & err TSRMLS_DC)86 static HashTable *umsg_get_numeric_types(MessageFormatter_object *mfo,
87 										 intl_error& err TSRMLS_DC)
88 {
89 	HashTable *ret;
90 	int32_t parts_count;
91 
92 	if (U_FAILURE(err.code)) {
93 		return NULL;
94 	}
95 
96 	if (mfo->mf_data.arg_types) {
97 		/* already cached */
98 		return mfo->mf_data.arg_types;
99 	}
100 
101 	const Formattable::Type *types = MessageFormatAdapter::getArgTypeList(
102 		*(MessageFormat*)mfo->mf_data.umsgf, parts_count);
103 
104 	/* Hash table will store Formattable::Type objects directly,
105 	 * so no need for destructor */
106 	ALLOC_HASHTABLE(ret);
107 	zend_hash_init(ret, parts_count, NULL, NULL, 0);
108 
109 	for (int i = 0; i < parts_count; i++) {
110 		const Formattable::Type t = types[i];
111 		if (zend_hash_index_update(ret, (ulong)i, (void*)&t, sizeof(t), NULL)
112 				== FAILURE) {
113 			intl_errors_set(&err, U_MEMORY_ALLOCATION_ERROR,
114 				"Write to argument types hash table failed", 0 TSRMLS_CC);
115 			break;
116 		}
117 	}
118 
119 	if (U_FAILURE(err.code)) {
120 		zend_hash_destroy(ret);
121 		efree(ret);
122 
123 		return NULL;
124 	}
125 
126 	mfo->mf_data.arg_types = ret;
127 
128 	return ret;
129 }
130 
131 #ifdef HAS_MESSAGE_PATTERN
umsg_parse_format(MessageFormatter_object * mfo,const MessagePattern & mp,intl_error & err TSRMLS_DC)132 static HashTable *umsg_parse_format(MessageFormatter_object *mfo,
133 									const MessagePattern& mp,
134 									intl_error& err TSRMLS_DC)
135 {
136 	HashTable *ret;
137 	int32_t parts_count;
138 
139 	if (U_FAILURE(err.code)) {
140 		return NULL;
141 	}
142 
143 	if (!((MessageFormat *)mfo->mf_data.umsgf)->usesNamedArguments()) {
144 		return umsg_get_numeric_types(mfo, err TSRMLS_CC);
145 	}
146 
147 	if (mfo->mf_data.arg_types) {
148 		/* already cached */
149 		return mfo->mf_data.arg_types;
150 	}
151 
152 	/* Hash table will store Formattable::Type objects directly,
153 	 * so no need for destructor */
154 	ALLOC_HASHTABLE(ret);
155 	zend_hash_init(ret, 32, NULL, NULL, 0);
156 
157 	parts_count = mp.countParts();
158 
159 	// See MessageFormat::cacheExplicitFormats()
160 	/*
161 	 * Looking through the pattern, go to each arg_start part type.
162 	 * The arg-typeof that tells us the argument type (simple, complicated)
163 	 * then the next part is either the arg_name or arg number
164 	 * and then if it's simple after that there could be a part-type=arg-type
165 	 * while substring will tell us number, spellout, etc.
166 	 * If the next thing isn't an arg-type then assume string.
167 	*/
168 	/* The last two "parts" can at most be ARG_LIMIT and MSG_LIMIT
169 	 * which we need not examine. */
170 	for (int32_t i = 0; i < parts_count - 2 && U_SUCCESS(err.code); i++) {
171 		MessagePattern::Part p = mp.getPart(i);
172 
173 		if (p.getType() != UMSGPAT_PART_TYPE_ARG_START) {
174 			continue;
175 		}
176 
177 		MessagePattern::Part name_part = mp.getPart(++i); /* Getting name, advancing i */
178 		Formattable::Type type,
179 						  *storedType;
180 
181 		if (name_part.getType() == UMSGPAT_PART_TYPE_ARG_NAME) {
182 			UnicodeString argName = mp.getSubstring(name_part);
183 			if (zend_hash_find(ret, (char*)argName.getBuffer(), argName.length(),
184 					(void**)&storedType) == FAILURE) {
185 				/* not found already; create new entry in HT */
186 				Formattable::Type bogusType = Formattable::kObject;
187 				if (zend_hash_update(ret, (char*)argName.getBuffer(), argName.length(),
188 						(void*)&bogusType, sizeof(bogusType), (void**)&storedType) == FAILURE) {
189 					intl_errors_set(&err, U_MEMORY_ALLOCATION_ERROR,
190 						"Write to argument types hash table failed", 0 TSRMLS_CC);
191 					continue;
192 				}
193 			}
194 		} else if (name_part.getType() == UMSGPAT_PART_TYPE_ARG_NUMBER) {
195 			int32_t argNumber = name_part.getValue();
196 			if (argNumber < 0) {
197 				intl_errors_set(&err, U_INVALID_FORMAT_ERROR,
198 					"Found part with negative number", 0 TSRMLS_CC);
199 				continue;
200 			}
201 			if (zend_hash_index_find(ret, (ulong)argNumber, (void**)&storedType)
202 					== FAILURE) {
203 				/* not found already; create new entry in HT */
204 				Formattable::Type bogusType = Formattable::kObject;
205 				if (zend_hash_index_update(ret, (ulong)argNumber, (void*)&bogusType,
206 						sizeof(bogusType), (void**)&storedType) == FAILURE) {
207 					intl_errors_set(&err, U_MEMORY_ALLOCATION_ERROR,
208 						"Write to argument types hash table failed", 0 TSRMLS_CC);
209 					continue;
210 				}
211 			}
212 		} else {
213 			intl_errors_set(&err, U_INVALID_FORMAT_ERROR, "Invalid part type encountered", 0 TSRMLS_CC);
214 			continue;
215 		}
216 
217 		UMessagePatternArgType argType = p.getArgType();
218 		/* No type specified, treat it as a string */
219 		if (argType == UMSGPAT_ARG_TYPE_NONE) {
220 			type = Formattable::kString;
221 		} else { /* Some type was specified, might be simple or complicated */
222 			if (argType == UMSGPAT_ARG_TYPE_SIMPLE) {
223 				/* For a SIMPLE arg, after the name part, there should be
224 				 * an ARG_TYPE part whose string value tells us what to do */
225 				MessagePattern::Part type_part = mp.getPart(++i); /* Getting type, advancing i */
226 				if (type_part.getType() == UMSGPAT_PART_TYPE_ARG_TYPE) {
227 					UnicodeString typeString = mp.getSubstring(type_part);
228 					/* This is all based on the rules in the docs for MessageFormat
229 					 * @see http://icu-project.org/apiref/icu4c/classMessageFormat.html */
230 					if (typeString == "number") {
231 						MessagePattern::Part style_part = mp.getPart(i + 1); /* Not advancing i */
232 						if (style_part.getType() == UMSGPAT_PART_TYPE_ARG_STYLE) {
233 							UnicodeString styleString = mp.getSubstring(style_part);
234 							if (styleString == "integer") {
235 								type = Formattable::kInt64;
236 							} else if (styleString == "currency") {
237 								type = Formattable::kDouble;
238 							} else if (styleString == "percent") {
239 								type = Formattable::kDouble;
240 							} else { /* some style invalid/unknown to us */
241 								type = Formattable::kDouble;
242 							}
243 						} else { // if missing style, part, make it a double
244 							type = Formattable::kDouble;
245 						}
246 					} else if ((typeString == "date") || (typeString == "time")) {
247 						type = Formattable::kDate;
248 					} else if ((typeString == "spellout") || (typeString == "ordinal")
249 							|| (typeString == "duration")) {
250 						type = Formattable::kDouble;
251 					}
252 				} else {
253 					/* If there's no UMSGPAT_PART_TYPE_ARG_TYPE right after a
254 					 * UMSGPAT_ARG_TYPE_SIMPLE argument, then the pattern
255 					 * is broken. */
256 					intl_errors_set(&err, U_PARSE_ERROR,
257 						"Expected UMSGPAT_PART_TYPE_ARG_TYPE part following "
258 						"UMSGPAT_ARG_TYPE_SIMPLE part", 0 TSRMLS_CC);
259 					continue;
260 				}
261 			} else if (argType == UMSGPAT_ARG_TYPE_PLURAL) {
262 				type = Formattable::kDouble;
263 			} else if (argType == UMSGPAT_ARG_TYPE_CHOICE) {
264 				type = Formattable::kDouble;
265 			} else if (argType == UMSGPAT_ARG_TYPE_SELECT) {
266 				type = Formattable::kString;
267 #if U_ICU_VERSION_MAJOR_NUM >= 50
268 			} else if (argType == UMSGPAT_ARG_TYPE_SELECTORDINAL) {
269 				type = Formattable::kDouble;
270 #endif
271 			} else {
272 				type = Formattable::kString;
273 			}
274 		} /* was type specified? */
275 
276 		/* We found a different type for the same arg! */
277 		if (*storedType != Formattable::kObject && *storedType != type) {
278 			intl_errors_set(&err, U_ARGUMENT_TYPE_MISMATCH,
279 				"Inconsistent types declared for an argument", 0 TSRMLS_CC);
280 			continue;
281 		}
282 
283 		*storedType = type;
284 	} /* visiting each part */
285 
286 	if (U_FAILURE(err.code)) {
287 		zend_hash_destroy(ret);
288 		efree(ret);
289 
290 		return NULL;
291 	}
292 
293 	mfo->mf_data.arg_types = ret;
294 
295 	return ret;
296 }
297 #endif
298 
umsg_get_types(MessageFormatter_object * mfo,intl_error & err TSRMLS_DC)299 static HashTable *umsg_get_types(MessageFormatter_object *mfo,
300 								 intl_error& err TSRMLS_DC)
301 {
302 	MessageFormat *mf = (MessageFormat *)mfo->mf_data.umsgf;
303 
304 #ifdef HAS_MESSAGE_PATTERN
305 	const MessagePattern mp = MessageFormatAdapter::getMessagePattern(mf);
306 
307 	return umsg_parse_format(mfo, mp, err TSRMLS_CC);
308 #else
309 	if (mf->usesNamedArguments()) {
310 			intl_errors_set(&err, U_UNSUPPORTED_ERROR,
311 				"This extension supports named arguments only on ICU 4.8+",
312 				0 TSRMLS_CC);
313 		return NULL;
314 	}
315 	return umsg_get_numeric_types(mfo, err TSRMLS_CC);
316 #endif
317 }
318 
umsg_set_timezone(MessageFormatter_object * mfo,intl_error & err TSRMLS_DC)319 static void umsg_set_timezone(MessageFormatter_object *mfo,
320 							  intl_error& err TSRMLS_DC)
321 {
322 	MessageFormat *mf = (MessageFormat *)mfo->mf_data.umsgf;
323 	TimeZone	  *used_tz = NULL;
324 	const Format  **formats;
325 	int32_t		  count;
326 
327 	/* Unfortanely, this cannot change the time zone for arguments that
328 	 * appear inside complex formats because ::getFormats() returns NULL
329 	 * for all uncached formats, which is the case for complex formats
330 	 * unless they were set via one of the ::setFormat() methods */
331 
332 	if (mfo->mf_data.tz_set) {
333 		return; /* already done */
334 	}
335 
336 	formats = mf->getFormats(count);
337 
338 	if (formats == NULL) {
339 		intl_errors_set(&err, U_MEMORY_ALLOCATION_ERROR,
340 			"Out of memory retrieving subformats", 0 TSRMLS_CC);
341 	}
342 
343 	for (int i = 0; U_SUCCESS(err.code) && i < count; i++) {
344 		DateFormat* df = dynamic_cast<DateFormat*>(
345 			const_cast<Format *>(formats[i]));
346 		if (df == NULL) {
347 			continue;
348 		}
349 
350 		if (used_tz == NULL) {
351 			zval nullzv = zval_used_for_init,
352 				 *zvptr = &nullzv;
353 			used_tz = timezone_process_timezone_argument(&zvptr, &err,
354 				"msgfmt_format" TSRMLS_CC);
355 			if (used_tz == NULL) {
356 				continue;
357 			}
358 		}
359 
360 		df->setTimeZone(*used_tz);
361 	}
362 
363 	if (U_SUCCESS(err.code)) {
364 		mfo->mf_data.tz_set = 1;
365 	}
366 }
367 
umsg_format_helper(MessageFormatter_object * mfo,HashTable * args,UChar ** formatted,int * formatted_len TSRMLS_DC)368 U_CFUNC void umsg_format_helper(MessageFormatter_object *mfo,
369 								HashTable *args,
370 								UChar **formatted,
371 								int *formatted_len TSRMLS_DC)
372 {
373 	int arg_count = zend_hash_num_elements(args);
374 	std::vector<Formattable> fargs;
375 	std::vector<UnicodeString> farg_names;
376 	MessageFormat *mf = (MessageFormat *)mfo->mf_data.umsgf;
377 	HashTable *types;
378 	intl_error& err = INTL_DATA_ERROR(mfo);
379 
380 	if (U_FAILURE(err.code)) {
381 		return;
382 	}
383 
384 	types = umsg_get_types(mfo, err TSRMLS_CC);
385 
386 	umsg_set_timezone(mfo, err TSRMLS_CC);
387 
388 	fargs.resize(arg_count);
389 	farg_names.resize(arg_count);
390 
391 	int				argNum = 0;
392 	HashPosition	pos;
393 	zval			**elem;
394 
395 	// Key related variables
396 	int				key_type;
397 	char			*str_index;
398 	uint			str_len;
399 	ulong			num_index;
400 
401 	for (zend_hash_internal_pointer_reset_ex(args, &pos);
402 		U_SUCCESS(err.code) &&
403 			(key_type = zend_hash_get_current_key_ex(
404 					args, &str_index, &str_len, &num_index, 0, &pos),
405 				zend_hash_get_current_data_ex(args, (void **)&elem, &pos)
406 			) == SUCCESS;
407 		zend_hash_move_forward_ex(args, &pos), argNum++)
408 	{
409 		Formattable& formattable = fargs[argNum];
410 		UnicodeString& key = farg_names[argNum];
411 		Formattable::Type argType = Formattable::kObject, //unknown
412 						  *storedArgType = NULL;
413 
414 		/* Process key and retrieve type */
415 		if (key_type == HASH_KEY_IS_LONG) {
416 			/* includes case where index < 0 because it's exposed as unsigned */
417 			if (num_index > (ulong)INT32_MAX) {
418 				intl_errors_set(&err, U_ILLEGAL_ARGUMENT_ERROR,
419 					"Found negative or too large array key", 0 TSRMLS_CC);
420 				continue;
421 			}
422 
423 		   UChar temp[16];
424 		   int32_t len = u_sprintf(temp, "%u", (uint32_t)num_index);
425 		   key.append(temp, len);
426 
427 		   zend_hash_index_find(types, (ulong)num_index, (void**)&storedArgType);
428 		} else { //string; assumed to be in UTF-8
429 			intl_stringFromChar(key, str_index, str_len-1, &err.code);
430 
431 			if (U_FAILURE(err.code)) {
432 				char *message;
433 				spprintf(&message, 0,
434 					"Invalid UTF-8 data in argument key: '%s'", str_index);
435 				intl_errors_set(&err, err.code,	message, 1 TSRMLS_CC);
436 				efree(message);
437 				continue;
438 			}
439 
440 			zend_hash_find(types, (char*)key.getBuffer(), key.length(),
441 				(void**)&storedArgType);
442 		}
443 
444 		if (storedArgType != NULL) {
445 			argType = *storedArgType;
446 		}
447 
448 		/* Convert zval to formattable according to message format type
449 		 * or (as a fallback) the zval type */
450 		if (argType != Formattable::kObject) {
451 			switch (argType) {
452 			case Formattable::kString:
453 				{
454 	string_arg:
455 					/* This implicitly converts objects
456 					 * Note that our vectors will leak if object conversion fails
457 					 * and PHP ends up with a fatal error and calls longjmp
458 					 * as a result of that.
459 					 */
460 					convert_to_string_ex(elem);
461 
462 					UnicodeString *text = new UnicodeString();
463 					intl_stringFromChar(*text,
464 						Z_STRVAL_PP(elem), Z_STRLEN_PP(elem), &err.code);
465 
466 					if (U_FAILURE(err.code)) {
467 						char *message;
468 						spprintf(&message, 0, "Invalid UTF-8 data in string argument: "
469 							"'%s'", Z_STRVAL_PP(elem));
470 						intl_errors_set(&err, err.code, message, 1 TSRMLS_CC);
471 						efree(message);
472 						delete text;
473 						continue;
474 					}
475 					formattable.adoptString(text);
476 					break;
477 				}
478 			case Formattable::kDouble:
479 				{
480 					double d;
481 					if (Z_TYPE_PP(elem) == IS_DOUBLE) {
482 						d = Z_DVAL_PP(elem);
483 					} else if (Z_TYPE_PP(elem) == IS_LONG) {
484 						d = (double)Z_LVAL_PP(elem);
485 					} else {
486 						SEPARATE_ZVAL_IF_NOT_REF(elem);
487 						convert_scalar_to_number(*elem TSRMLS_CC);
488 						d = (Z_TYPE_PP(elem) == IS_DOUBLE)
489 							? Z_DVAL_PP(elem)
490 							: (double)Z_LVAL_PP(elem);
491 					}
492 					formattable.setDouble(d);
493 					break;
494 				}
495 			case Formattable::kLong:
496 				{
497 					int32_t tInt32 = 0;
498 retry_klong:
499 					if (Z_TYPE_PP(elem) == IS_DOUBLE) {
500 						if (Z_DVAL_PP(elem) > (double)INT32_MAX ||
501 								Z_DVAL_PP(elem) < (double)INT32_MIN) {
502 							intl_errors_set(&err, U_ILLEGAL_ARGUMENT_ERROR,
503 								"Found PHP float with absolute value too large for "
504 								"32 bit integer argument", 0 TSRMLS_CC);
505 						} else {
506 							tInt32 = (int32_t)Z_DVAL_PP(elem);
507 						}
508 					} else if (Z_TYPE_PP(elem) == IS_LONG) {
509 						if (Z_LVAL_PP(elem) > INT32_MAX ||
510 								Z_LVAL_PP(elem) < INT32_MIN) {
511 							intl_errors_set(&err, U_ILLEGAL_ARGUMENT_ERROR,
512 								"Found PHP integer with absolute value too large "
513 								"for 32 bit integer argument", 0 TSRMLS_CC);
514 						} else {
515 							tInt32 = (int32_t)Z_LVAL_PP(elem);
516 						}
517 					} else {
518 						SEPARATE_ZVAL_IF_NOT_REF(elem);
519 						convert_scalar_to_number(*elem TSRMLS_CC);
520 						goto retry_klong;
521 					}
522 					formattable.setLong(tInt32);
523 					break;
524 				}
525 			case Formattable::kInt64:
526 				{
527 					int64_t tInt64 = 0;
528 retry_kint64:
529 					if (Z_TYPE_PP(elem) == IS_DOUBLE) {
530 						if (Z_DVAL_PP(elem) > (double)U_INT64_MAX ||
531 								Z_DVAL_PP(elem) < (double)U_INT64_MIN) {
532 							intl_errors_set(&err, U_ILLEGAL_ARGUMENT_ERROR,
533 								"Found PHP float with absolute value too large for "
534 								"64 bit integer argument", 0 TSRMLS_CC);
535 						} else {
536 							tInt64 = (int64_t)Z_DVAL_PP(elem);
537 						}
538 					} else if (Z_TYPE_PP(elem) == IS_LONG) {
539 						/* assume long is not wider than 64 bits */
540 						tInt64 = (int64_t)Z_LVAL_PP(elem);
541 					} else {
542 						SEPARATE_ZVAL_IF_NOT_REF(elem);
543 						convert_scalar_to_number(*elem TSRMLS_CC);
544 						goto retry_kint64;
545 					}
546 					formattable.setInt64(tInt64);
547 					break;
548 				}
549 			case Formattable::kDate:
550 				{
551 					double dd = intl_zval_to_millis(*elem, &err, "msgfmt_format" TSRMLS_CC);
552 					if (U_FAILURE(err.code)) {
553 						char *message, *key_char;
554 						int key_len;
555 						UErrorCode status = UErrorCode();
556 						if (intl_charFromString(key, &key_char, &key_len,
557 								&status) == SUCCESS) {
558 							spprintf(&message, 0, "The argument for key '%s' "
559 								"cannot be used as a date or time", key_char);
560 							intl_errors_set(&err, err.code, message, 1 TSRMLS_CC);
561 							efree(key_char);
562 							efree(message);
563 						}
564 						continue;
565 					}
566 					formattable.setDate(dd);
567 					break;
568 				}
569 			default:
570 				intl_errors_set(&err, U_ILLEGAL_ARGUMENT_ERROR,
571 					"Found unsupported argument type", 0 TSRMLS_CC);
572 				break;
573 			}
574 		} else {
575 			/* We couldn't find any information about the argument in the pattern, this
576 			 * means it's an extra argument. So convert it to a number if it's a number or
577 			 * bool or null and to a string if it's anything else except arrays . */
578 			switch (Z_TYPE_PP(elem)) {
579 			case IS_DOUBLE:
580 				formattable.setDouble(Z_DVAL_PP(elem));
581 				break;
582 			case IS_BOOL:
583 				convert_to_long_ex(elem);
584 				/* Intentional fallthrough */
585 			case IS_LONG:
586 				formattable.setInt64((int64_t)Z_LVAL_PP(elem));
587 				break;
588 			case IS_NULL:
589 				formattable.setInt64((int64_t)0);
590 				break;
591 			case IS_STRING:
592 			case IS_OBJECT:
593 				goto string_arg;
594 			default:
595 				{
596 					char *message, *key_char;
597 					int key_len;
598 					UErrorCode status = UErrorCode();
599 					if (intl_charFromString(key, &key_char, &key_len,
600 							&status) == SUCCESS) {
601 						spprintf(&message, 0, "No strategy to convert the "
602 							"value given for the argument with key '%s' "
603 							"is available", key_char);
604 						intl_errors_set(&err,
605 							U_ILLEGAL_ARGUMENT_ERROR, message, 1 TSRMLS_CC);
606 						efree(key_char);
607 						efree(message);
608 					}
609 				}
610 			}
611 		}
612 	} // visiting each argument
613 
614 	if (U_FAILURE(err.code)) {
615 		return;
616 	}
617 
618 	UnicodeString resultStr;
619 	FieldPosition fieldPosition(0);
620 
621 	/* format the message */
622 	mf->format(farg_names.empty() ? NULL : &farg_names[0],
623 		fargs.empty() ? NULL : &fargs[0], arg_count, resultStr, err.code);
624 
625 	if (U_FAILURE(err.code)) {
626 		intl_errors_set(&err, err.code,
627 			"Call to ICU MessageFormat::format() has failed", 0 TSRMLS_CC);
628 		return;
629 	}
630 
631 	*formatted_len = resultStr.length();
632 	*formatted = eumalloc(*formatted_len+1);
633 	resultStr.extract(*formatted, *formatted_len+1, err.code);
634 	if (U_FAILURE(err.code)) {
635 		intl_errors_set(&err, err.code,
636 			"Error copying format() result", 0 TSRMLS_CC);
637 		return;
638 	}
639 }
640 
641 #define cleanup_zvals() for(int j=i;j>=0;j--) { zval_ptr_dtor((*args)+i); }
642 
umsg_parse_helper(UMessageFormat * fmt,int * count,zval *** args,UChar * source,int source_len,UErrorCode * status)643 U_CFUNC void umsg_parse_helper(UMessageFormat *fmt, int *count, zval ***args, UChar *source, int source_len, UErrorCode *status)
644 {
645     UnicodeString srcString(source, source_len);
646     Formattable *fargs = ((const MessageFormat*)fmt)->parse(srcString, *count, *status);
647 
648 	if(U_FAILURE(*status)) {
649 		return;
650 	}
651 
652 	*args = (zval **)safe_emalloc(*count, sizeof(zval *), 0);
653 
654     // assign formattables to varargs
655     for(int32_t i = 0; i < *count; i++) {
656 	    int64_t aInt64;
657 		double aDate;
658 		UnicodeString temp;
659 		char *stmp;
660 		int stmp_len;
661 
662 		ALLOC_INIT_ZVAL((*args)[i]);
663 
664 		switch(fargs[i].getType()) {
665         case Formattable::kDate:
666 			aDate = ((double)fargs[i].getDate())/U_MILLIS_PER_SECOND;
667 			ZVAL_DOUBLE((*args)[i], aDate);
668             break;
669 
670         case Formattable::kDouble:
671 			ZVAL_DOUBLE((*args)[i], (double)fargs[i].getDouble());
672             break;
673 
674         case Formattable::kLong:
675 			ZVAL_LONG((*args)[i], fargs[i].getLong());
676             break;
677 
678         case Formattable::kInt64:
679             aInt64 = fargs[i].getInt64();
680 			if(aInt64 > LONG_MAX || aInt64 < -LONG_MAX) {
681 				ZVAL_DOUBLE((*args)[i], (double)aInt64);
682 			} else {
683 				ZVAL_LONG((*args)[i], (long)aInt64);
684 			}
685             break;
686 
687         case Formattable::kString:
688             fargs[i].getString(temp);
689 			intl_convert_utf16_to_utf8(&stmp, &stmp_len, temp.getBuffer(), temp.length(), status);
690 			if(U_FAILURE(*status)) {
691 				cleanup_zvals();
692 				return;
693 			}
694 			ZVAL_STRINGL((*args)[i], stmp, stmp_len, 0);
695             break;
696 
697         case Formattable::kObject:
698         case Formattable::kArray:
699             *status = U_ILLEGAL_ARGUMENT_ERROR;
700 			cleanup_zvals();
701             break;
702         }
703     }
704 	delete[] fargs;
705 }
706 
707 /*
708  * Local variables:
709  * tab-width: 4
710  * c-basic-offset: 4
711  * End:
712  * vim600: noet sw=4 ts=4 fdm=marker
713  * vim<600: noet sw=4 ts=4
714  */
715