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