xref: /PHP-7.4/ext/mbstring/mbstring.c (revision 0cafd53d)
1 /*
2    +----------------------------------------------------------------------+
3    | PHP Version 7                                                        |
4    +----------------------------------------------------------------------+
5    | Copyright (c) The PHP Group                                          |
6    +----------------------------------------------------------------------+
7    | This source file is subject to version 3.01 of the PHP license,      |
8    | that is bundled with this package in the file LICENSE, and is        |
9    | available through the world-wide-web at the following url:           |
10    | http://www.php.net/license/3_01.txt                                  |
11    | If you did not receive a copy of the PHP license and are unable to   |
12    | obtain it through the world-wide-web, please send a note to          |
13    | license@php.net so we can mail you a copy immediately.               |
14    +----------------------------------------------------------------------+
15    | Author: Tsukada Takuya <tsukada@fminn.nagano.nagano.jp>              |
16    |         Rui Hirokawa <hirokawa@php.net>                              |
17    |         Hironori Sato <satoh@jpnnet.com>                             |
18    |         Shigeru Kanemoto <sgk@happysize.co.jp>                       |
19    +----------------------------------------------------------------------+
20  */
21 
22 /* {{{ includes */
23 #ifdef HAVE_CONFIG_H
24 #include "config.h"
25 #endif
26 
27 #include "php.h"
28 #include "php_ini.h"
29 #include "php_variables.h"
30 #include "mbstring.h"
31 #include "ext/standard/php_string.h"
32 #include "ext/standard/php_mail.h"
33 #include "ext/standard/exec.h"
34 #include "ext/standard/url.h"
35 #include "main/php_output.h"
36 #include "ext/standard/info.h"
37 
38 #include "libmbfl/mbfl/mbfl_allocators.h"
39 #include "libmbfl/mbfl/mbfilter_8bit.h"
40 #include "libmbfl/mbfl/mbfilter_pass.h"
41 #include "libmbfl/mbfl/mbfilter_wchar.h"
42 #include "libmbfl/filters/mbfilter_ascii.h"
43 #include "libmbfl/filters/mbfilter_base64.h"
44 #include "libmbfl/filters/mbfilter_qprint.h"
45 #include "libmbfl/filters/mbfilter_ucs4.h"
46 #include "libmbfl/filters/mbfilter_utf8.h"
47 
48 #include "php_variables.h"
49 #include "php_globals.h"
50 #include "rfc1867.h"
51 #include "php_content_types.h"
52 #include "SAPI.h"
53 #include "php_unicode.h"
54 #include "TSRM.h"
55 
56 #include "mb_gpc.h"
57 
58 #if HAVE_MBREGEX
59 # include "php_mbregex.h"
60 # include "php_onig_compat.h"
61 # include <oniguruma.h>
62 # undef UChar
63 #if ONIGURUMA_VERSION_INT < 60800
64 typedef void OnigMatchParam;
65 #define onig_new_match_param() (NULL)
66 #define onig_initialize_match_param(x) (void)(x)
67 #define onig_set_match_stack_limit_size_of_match_param(x, y)
68 #define onig_set_retry_limit_in_match_of_match_param(x, y)
69 #define onig_free_match_param(x)
70 #define onig_search_with_param(reg, str, end, start, range, region, option, mp) \
71 onig_search(reg, str, end, start, range, region, option)
72 #define onig_match_with_param(re, str, end, at, region, option, mp) \
73 onig_match(re, str, end, at, region, option)
74 #endif
75 #else
76 # include "ext/pcre/php_pcre.h"
77 #endif
78 
79 #include "zend_multibyte.h"
80 /* }}} */
81 
82 #if HAVE_MBSTRING
83 
84 /* {{{ prototypes */
85 ZEND_DECLARE_MODULE_GLOBALS(mbstring)
86 
87 static PHP_GINIT_FUNCTION(mbstring);
88 static PHP_GSHUTDOWN_FUNCTION(mbstring);
89 
90 static void php_mb_populate_current_detect_order_list(void);
91 
92 static int php_mb_encoding_translation(void);
93 
94 static void php_mb_gpc_get_detect_order(const zend_encoding ***list, size_t *list_size);
95 
96 static void php_mb_gpc_set_input_encoding(const zend_encoding *encoding);
97 
98 static inline zend_bool php_mb_is_unsupported_no_encoding(enum mbfl_no_encoding no_enc);
99 
100 static inline zend_bool php_mb_is_no_encoding_utf8(enum mbfl_no_encoding no_enc);
101 /* }}} */
102 
103 /* {{{ php_mb_default_identify_list */
104 typedef struct _php_mb_nls_ident_list {
105 	enum mbfl_no_language lang;
106 	const enum mbfl_no_encoding *list;
107 	size_t list_size;
108 } php_mb_nls_ident_list;
109 
110 static const enum mbfl_no_encoding php_mb_default_identify_list_ja[] = {
111 	mbfl_no_encoding_ascii,
112 	mbfl_no_encoding_jis,
113 	mbfl_no_encoding_utf8,
114 	mbfl_no_encoding_euc_jp,
115 	mbfl_no_encoding_sjis
116 };
117 
118 static const enum mbfl_no_encoding php_mb_default_identify_list_cn[] = {
119 	mbfl_no_encoding_ascii,
120 	mbfl_no_encoding_utf8,
121 	mbfl_no_encoding_euc_cn,
122 	mbfl_no_encoding_cp936
123 };
124 
125 static const enum mbfl_no_encoding php_mb_default_identify_list_tw_hk[] = {
126 	mbfl_no_encoding_ascii,
127 	mbfl_no_encoding_utf8,
128 	mbfl_no_encoding_euc_tw,
129 	mbfl_no_encoding_big5
130 };
131 
132 static const enum mbfl_no_encoding php_mb_default_identify_list_kr[] = {
133 	mbfl_no_encoding_ascii,
134 	mbfl_no_encoding_utf8,
135 	mbfl_no_encoding_euc_kr,
136 	mbfl_no_encoding_uhc
137 };
138 
139 static const enum mbfl_no_encoding php_mb_default_identify_list_ru[] = {
140 	mbfl_no_encoding_ascii,
141 	mbfl_no_encoding_utf8,
142 	mbfl_no_encoding_koi8r,
143 	mbfl_no_encoding_cp1251,
144 	mbfl_no_encoding_cp866
145 };
146 
147 static const enum mbfl_no_encoding php_mb_default_identify_list_hy[] = {
148 	mbfl_no_encoding_ascii,
149 	mbfl_no_encoding_utf8,
150 	mbfl_no_encoding_armscii8
151 };
152 
153 static const enum mbfl_no_encoding php_mb_default_identify_list_tr[] = {
154 	mbfl_no_encoding_ascii,
155 	mbfl_no_encoding_utf8,
156 	mbfl_no_encoding_cp1254,
157 	mbfl_no_encoding_8859_9
158 };
159 
160 static const enum mbfl_no_encoding php_mb_default_identify_list_ua[] = {
161 	mbfl_no_encoding_ascii,
162 	mbfl_no_encoding_utf8,
163 	mbfl_no_encoding_koi8u
164 };
165 
166 static const enum mbfl_no_encoding php_mb_default_identify_list_neut[] = {
167 	mbfl_no_encoding_ascii,
168 	mbfl_no_encoding_utf8
169 };
170 
171 
172 static const php_mb_nls_ident_list php_mb_default_identify_list[] = {
173 	{ mbfl_no_language_japanese, php_mb_default_identify_list_ja, sizeof(php_mb_default_identify_list_ja) / sizeof(php_mb_default_identify_list_ja[0]) },
174 	{ mbfl_no_language_korean, php_mb_default_identify_list_kr, sizeof(php_mb_default_identify_list_kr) / sizeof(php_mb_default_identify_list_kr[0]) },
175 	{ mbfl_no_language_traditional_chinese, php_mb_default_identify_list_tw_hk, sizeof(php_mb_default_identify_list_tw_hk) / sizeof(php_mb_default_identify_list_tw_hk[0]) },
176 	{ mbfl_no_language_simplified_chinese, php_mb_default_identify_list_cn, sizeof(php_mb_default_identify_list_cn) / sizeof(php_mb_default_identify_list_cn[0]) },
177 	{ mbfl_no_language_russian, php_mb_default_identify_list_ru, sizeof(php_mb_default_identify_list_ru) / sizeof(php_mb_default_identify_list_ru[0]) },
178 	{ mbfl_no_language_armenian, php_mb_default_identify_list_hy, sizeof(php_mb_default_identify_list_hy) / sizeof(php_mb_default_identify_list_hy[0]) },
179 	{ mbfl_no_language_turkish, php_mb_default_identify_list_tr, sizeof(php_mb_default_identify_list_tr) / sizeof(php_mb_default_identify_list_tr[0]) },
180 	{ mbfl_no_language_ukrainian, php_mb_default_identify_list_ua, sizeof(php_mb_default_identify_list_ua) / sizeof(php_mb_default_identify_list_ua[0]) },
181 	{ mbfl_no_language_neutral, php_mb_default_identify_list_neut, sizeof(php_mb_default_identify_list_neut) / sizeof(php_mb_default_identify_list_neut[0]) }
182 };
183 
184 /* }}} */
185 
186 /* {{{ mb_overload_def mb_ovld[] */
187 static const struct mb_overload_def mb_ovld[] = {
188 	{MB_OVERLOAD_MAIL, "mail", "mb_send_mail", "mb_orig_mail"},
189 	{MB_OVERLOAD_STRING, "strlen", "mb_strlen", "mb_orig_strlen"},
190 	{MB_OVERLOAD_STRING, "strpos", "mb_strpos", "mb_orig_strpos"},
191 	{MB_OVERLOAD_STRING, "strrpos", "mb_strrpos", "mb_orig_strrpos"},
192 	{MB_OVERLOAD_STRING, "stripos", "mb_stripos", "mb_orig_stripos"},
193 	{MB_OVERLOAD_STRING, "strripos", "mb_strripos", "mb_orig_strripos"},
194 	{MB_OVERLOAD_STRING, "strstr", "mb_strstr", "mb_orig_strstr"},
195 	{MB_OVERLOAD_STRING, "strrchr", "mb_strrchr", "mb_orig_strrchr"},
196 	{MB_OVERLOAD_STRING, "stristr", "mb_stristr", "mb_orig_stristr"},
197 	{MB_OVERLOAD_STRING, "substr", "mb_substr", "mb_orig_substr"},
198 	{MB_OVERLOAD_STRING, "strtolower", "mb_strtolower", "mb_orig_strtolower"},
199 	{MB_OVERLOAD_STRING, "strtoupper", "mb_strtoupper", "mb_orig_strtoupper"},
200 	{MB_OVERLOAD_STRING, "substr_count", "mb_substr_count", "mb_orig_substr_count"},
201 	{0, NULL, NULL, NULL}
202 };
203 /* }}} */
204 
205 /* {{{ arginfo */
206 ZEND_BEGIN_ARG_INFO_EX(arginfo_mb_language, 0, 0, 0)
207 	ZEND_ARG_INFO(0, language)
208 ZEND_END_ARG_INFO()
209 
210 ZEND_BEGIN_ARG_INFO_EX(arginfo_mb_internal_encoding, 0, 0, 0)
211 	ZEND_ARG_INFO(0, encoding)
212 ZEND_END_ARG_INFO()
213 
214 ZEND_BEGIN_ARG_INFO_EX(arginfo_mb_http_input, 0, 0, 0)
215 	ZEND_ARG_INFO(0, type)
216 ZEND_END_ARG_INFO()
217 
218 ZEND_BEGIN_ARG_INFO_EX(arginfo_mb_http_output, 0, 0, 0)
219 	ZEND_ARG_INFO(0, encoding)
220 ZEND_END_ARG_INFO()
221 
222 ZEND_BEGIN_ARG_INFO_EX(arginfo_mb_detect_order, 0, 0, 0)
223 	ZEND_ARG_INFO(0, encoding)
224 ZEND_END_ARG_INFO()
225 
226 ZEND_BEGIN_ARG_INFO_EX(arginfo_mb_substitute_character, 0, 0, 0)
227 	ZEND_ARG_INFO(0, substchar)
228 ZEND_END_ARG_INFO()
229 
230 ZEND_BEGIN_ARG_INFO_EX(arginfo_mb_preferred_mime_name, 0, 0, 1)
231 	ZEND_ARG_INFO(0, encoding)
232 ZEND_END_ARG_INFO()
233 
234 ZEND_BEGIN_ARG_INFO_EX(arginfo_mb_parse_str, 0, 0, 1)
235 	ZEND_ARG_INFO(0, encoded_string)
236 	ZEND_ARG_INFO(1, result)
237 ZEND_END_ARG_INFO()
238 
239 ZEND_BEGIN_ARG_INFO_EX(arginfo_mb_output_handler, 0, 0, 2)
240 	ZEND_ARG_INFO(0, contents)
241 	ZEND_ARG_INFO(0, status)
242 ZEND_END_ARG_INFO()
243 
244 ZEND_BEGIN_ARG_INFO_EX(arginfo_mb_str_split, 0, 0, 1)
245 	ZEND_ARG_INFO(0, str)
246 	ZEND_ARG_INFO(0, split_length)
247 	ZEND_ARG_INFO(0, encoding)
248 ZEND_END_ARG_INFO()
249 
250 ZEND_BEGIN_ARG_INFO_EX(arginfo_mb_strlen, 0, 0, 1)
251 	ZEND_ARG_INFO(0, str)
252 	ZEND_ARG_INFO(0, encoding)
253 ZEND_END_ARG_INFO()
254 
255 ZEND_BEGIN_ARG_INFO_EX(arginfo_mb_strpos, 0, 0, 2)
256 	ZEND_ARG_INFO(0, haystack)
257 	ZEND_ARG_INFO(0, needle)
258 	ZEND_ARG_INFO(0, offset)
259 	ZEND_ARG_INFO(0, encoding)
260 ZEND_END_ARG_INFO()
261 
262 ZEND_BEGIN_ARG_INFO_EX(arginfo_mb_strrpos, 0, 0, 2)
263 	ZEND_ARG_INFO(0, haystack)
264 	ZEND_ARG_INFO(0, needle)
265 	ZEND_ARG_INFO(0, offset)
266 	ZEND_ARG_INFO(0, encoding)
267 ZEND_END_ARG_INFO()
268 
269 ZEND_BEGIN_ARG_INFO_EX(arginfo_mb_stripos, 0, 0, 2)
270 	ZEND_ARG_INFO(0, haystack)
271 	ZEND_ARG_INFO(0, needle)
272 	ZEND_ARG_INFO(0, offset)
273 	ZEND_ARG_INFO(0, encoding)
274 ZEND_END_ARG_INFO()
275 
276 ZEND_BEGIN_ARG_INFO_EX(arginfo_mb_strripos, 0, 0, 2)
277 	ZEND_ARG_INFO(0, haystack)
278 	ZEND_ARG_INFO(0, needle)
279 	ZEND_ARG_INFO(0, offset)
280 	ZEND_ARG_INFO(0, encoding)
281 ZEND_END_ARG_INFO()
282 
283 ZEND_BEGIN_ARG_INFO_EX(arginfo_mb_strstr, 0, 0, 2)
284 	ZEND_ARG_INFO(0, haystack)
285 	ZEND_ARG_INFO(0, needle)
286 	ZEND_ARG_INFO(0, part)
287 	ZEND_ARG_INFO(0, encoding)
288 ZEND_END_ARG_INFO()
289 
290 ZEND_BEGIN_ARG_INFO_EX(arginfo_mb_strrchr, 0, 0, 2)
291 	ZEND_ARG_INFO(0, haystack)
292 	ZEND_ARG_INFO(0, needle)
293 	ZEND_ARG_INFO(0, part)
294 	ZEND_ARG_INFO(0, encoding)
295 ZEND_END_ARG_INFO()
296 
297 ZEND_BEGIN_ARG_INFO_EX(arginfo_mb_stristr, 0, 0, 2)
298 	ZEND_ARG_INFO(0, haystack)
299 	ZEND_ARG_INFO(0, needle)
300 	ZEND_ARG_INFO(0, part)
301 	ZEND_ARG_INFO(0, encoding)
302 ZEND_END_ARG_INFO()
303 
304 ZEND_BEGIN_ARG_INFO_EX(arginfo_mb_strrichr, 0, 0, 2)
305 	ZEND_ARG_INFO(0, haystack)
306 	ZEND_ARG_INFO(0, needle)
307 	ZEND_ARG_INFO(0, part)
308 	ZEND_ARG_INFO(0, encoding)
309 ZEND_END_ARG_INFO()
310 
311 ZEND_BEGIN_ARG_INFO_EX(arginfo_mb_substr_count, 0, 0, 2)
312 	ZEND_ARG_INFO(0, haystack)
313 	ZEND_ARG_INFO(0, needle)
314 	ZEND_ARG_INFO(0, encoding)
315 ZEND_END_ARG_INFO()
316 
317 ZEND_BEGIN_ARG_INFO_EX(arginfo_mb_substr, 0, 0, 2)
318 	ZEND_ARG_INFO(0, str)
319 	ZEND_ARG_INFO(0, start)
320 	ZEND_ARG_INFO(0, length)
321 	ZEND_ARG_INFO(0, encoding)
322 ZEND_END_ARG_INFO()
323 
324 ZEND_BEGIN_ARG_INFO_EX(arginfo_mb_strcut, 0, 0, 2)
325 	ZEND_ARG_INFO(0, str)
326 	ZEND_ARG_INFO(0, start)
327 	ZEND_ARG_INFO(0, length)
328 	ZEND_ARG_INFO(0, encoding)
329 ZEND_END_ARG_INFO()
330 
331 ZEND_BEGIN_ARG_INFO_EX(arginfo_mb_strwidth, 0, 0, 1)
332 	ZEND_ARG_INFO(0, str)
333 	ZEND_ARG_INFO(0, encoding)
334 ZEND_END_ARG_INFO()
335 
336 ZEND_BEGIN_ARG_INFO_EX(arginfo_mb_strimwidth, 0, 0, 3)
337 	ZEND_ARG_INFO(0, str)
338 	ZEND_ARG_INFO(0, start)
339 	ZEND_ARG_INFO(0, width)
340 	ZEND_ARG_INFO(0, trimmarker)
341 	ZEND_ARG_INFO(0, encoding)
342 ZEND_END_ARG_INFO()
343 
344 ZEND_BEGIN_ARG_INFO_EX(arginfo_mb_convert_encoding, 0, 0, 2)
345 	ZEND_ARG_INFO(0, str)
346 	ZEND_ARG_INFO(0, to)
347 	ZEND_ARG_INFO(0, from)
348 ZEND_END_ARG_INFO()
349 
350 ZEND_BEGIN_ARG_INFO_EX(arginfo_mb_convert_case, 0, 0, 2)
351 	ZEND_ARG_INFO(0, sourcestring)
352 	ZEND_ARG_INFO(0, mode)
353 	ZEND_ARG_INFO(0, encoding)
354 ZEND_END_ARG_INFO()
355 
356 ZEND_BEGIN_ARG_INFO_EX(arginfo_mb_strtoupper, 0, 0, 1)
357 	ZEND_ARG_INFO(0, sourcestring)
358 	ZEND_ARG_INFO(0, encoding)
359 ZEND_END_ARG_INFO()
360 
361 ZEND_BEGIN_ARG_INFO_EX(arginfo_mb_strtolower, 0, 0, 1)
362 	ZEND_ARG_INFO(0, sourcestring)
363 	ZEND_ARG_INFO(0, encoding)
364 ZEND_END_ARG_INFO()
365 
366 ZEND_BEGIN_ARG_INFO_EX(arginfo_mb_detect_encoding, 0, 0, 1)
367 	ZEND_ARG_INFO(0, str)
368 	ZEND_ARG_INFO(0, encoding_list)
369 	ZEND_ARG_INFO(0, strict)
370 ZEND_END_ARG_INFO()
371 
372 ZEND_BEGIN_ARG_INFO(arginfo_mb_list_encodings, 0)
373 ZEND_END_ARG_INFO()
374 
375 ZEND_BEGIN_ARG_INFO_EX(arginfo_mb_encoding_aliases, 0, 0, 1)
376 	ZEND_ARG_INFO(0, encoding)
377 ZEND_END_ARG_INFO()
378 
379 ZEND_BEGIN_ARG_INFO_EX(arginfo_mb_encode_mimeheader, 0, 0, 1)
380 	ZEND_ARG_INFO(0, str)
381 	ZEND_ARG_INFO(0, charset)
382 	ZEND_ARG_INFO(0, transfer)
383 	ZEND_ARG_INFO(0, linefeed)
384 	ZEND_ARG_INFO(0, indent)
385 ZEND_END_ARG_INFO()
386 
387 ZEND_BEGIN_ARG_INFO_EX(arginfo_mb_decode_mimeheader, 0, 0, 1)
388 	ZEND_ARG_INFO(0, string)
389 ZEND_END_ARG_INFO()
390 
391 ZEND_BEGIN_ARG_INFO_EX(arginfo_mb_convert_kana, 0, 0, 1)
392 	ZEND_ARG_INFO(0, str)
393 	ZEND_ARG_INFO(0, option)
394 	ZEND_ARG_INFO(0, encoding)
395 ZEND_END_ARG_INFO()
396 
397 ZEND_BEGIN_ARG_INFO_EX(arginfo_mb_convert_variables, 0, 0, 3)
398 	ZEND_ARG_INFO(0, to)
399 	ZEND_ARG_INFO(0, from)
400 	ZEND_ARG_VARIADIC_INFO(1, vars)
401 ZEND_END_ARG_INFO()
402 
403 ZEND_BEGIN_ARG_INFO_EX(arginfo_mb_encode_numericentity, 0, 0, 2)
404 	ZEND_ARG_INFO(0, string)
405 	ZEND_ARG_INFO(0, convmap)
406 	ZEND_ARG_INFO(0, encoding)
407 	ZEND_ARG_INFO(0, is_hex)
408 ZEND_END_ARG_INFO()
409 
410 ZEND_BEGIN_ARG_INFO_EX(arginfo_mb_decode_numericentity, 0, 0, 2)
411 	ZEND_ARG_INFO(0, string)
412 	ZEND_ARG_INFO(0, convmap)
413 	ZEND_ARG_INFO(0, encoding)
414 	ZEND_ARG_INFO(0, is_hex)
415 ZEND_END_ARG_INFO()
416 
417 ZEND_BEGIN_ARG_INFO_EX(arginfo_mb_send_mail, 0, 0, 3)
418 	ZEND_ARG_INFO(0, to)
419 	ZEND_ARG_INFO(0, subject)
420 	ZEND_ARG_INFO(0, message)
421 	ZEND_ARG_INFO(0, additional_headers)
422 	ZEND_ARG_INFO(0, additional_parameters)
423 ZEND_END_ARG_INFO()
424 
425 ZEND_BEGIN_ARG_INFO_EX(arginfo_mb_get_info, 0, 0, 0)
426 	ZEND_ARG_INFO(0, type)
427 ZEND_END_ARG_INFO()
428 
429 ZEND_BEGIN_ARG_INFO_EX(arginfo_mb_check_encoding, 0, 0, 0)
430 	ZEND_ARG_INFO(0, var)
431 	ZEND_ARG_INFO(0, encoding)
432 ZEND_END_ARG_INFO()
433 
434 ZEND_BEGIN_ARG_INFO_EX(arginfo_mb_scrub, 0, 0, 1)
435 	ZEND_ARG_INFO(0, str)
436 	ZEND_ARG_INFO(0, encoding)
437 ZEND_END_ARG_INFO()
438 
439 ZEND_BEGIN_ARG_INFO_EX(arginfo_mb_ord, 0, 0, 1)
440 	ZEND_ARG_INFO(0, str)
441 	ZEND_ARG_INFO(0, encoding)
442 ZEND_END_ARG_INFO()
443 
444 ZEND_BEGIN_ARG_INFO_EX(arginfo_mb_chr, 0, 0, 1)
445 	ZEND_ARG_INFO(0, cp)
446 	ZEND_ARG_INFO(0, encoding)
447 ZEND_END_ARG_INFO()
448 
449 #if HAVE_MBREGEX
450 ZEND_BEGIN_ARG_INFO_EX(arginfo_mb_regex_encoding, 0, 0, 0)
451 	ZEND_ARG_INFO(0, encoding)
452 ZEND_END_ARG_INFO()
453 
454 ZEND_BEGIN_ARG_INFO_EX(arginfo_mb_ereg, 0, 0, 2)
455 	ZEND_ARG_INFO(0, pattern)
456 	ZEND_ARG_INFO(0, string)
457 	ZEND_ARG_INFO(1, registers)
458 ZEND_END_ARG_INFO()
459 
460 ZEND_BEGIN_ARG_INFO_EX(arginfo_mb_eregi, 0, 0, 2)
461 	ZEND_ARG_INFO(0, pattern)
462 	ZEND_ARG_INFO(0, string)
463 	ZEND_ARG_INFO(1, registers)
464 ZEND_END_ARG_INFO()
465 
466 ZEND_BEGIN_ARG_INFO_EX(arginfo_mb_ereg_replace, 0, 0, 3)
467 	ZEND_ARG_INFO(0, pattern)
468 	ZEND_ARG_INFO(0, replacement)
469 	ZEND_ARG_INFO(0, string)
470 	ZEND_ARG_INFO(0, option)
471 ZEND_END_ARG_INFO()
472 
473 ZEND_BEGIN_ARG_INFO_EX(arginfo_mb_eregi_replace, 0, 0, 3)
474 	ZEND_ARG_INFO(0, pattern)
475 	ZEND_ARG_INFO(0, replacement)
476 	ZEND_ARG_INFO(0, string)
477 	ZEND_ARG_INFO(0, option)
478 ZEND_END_ARG_INFO()
479 
480 ZEND_BEGIN_ARG_INFO_EX(arginfo_mb_ereg_replace_callback, 0, 0, 3)
481 	ZEND_ARG_INFO(0, pattern)
482 	ZEND_ARG_INFO(0, callback)
483 	ZEND_ARG_INFO(0, string)
484 	ZEND_ARG_INFO(0, option)
485 ZEND_END_ARG_INFO()
486 
487 ZEND_BEGIN_ARG_INFO_EX(arginfo_mb_split, 0, 0, 2)
488 	ZEND_ARG_INFO(0, pattern)
489 	ZEND_ARG_INFO(0, string)
490 	ZEND_ARG_INFO(0, limit)
491 ZEND_END_ARG_INFO()
492 
493 ZEND_BEGIN_ARG_INFO_EX(arginfo_mb_ereg_match, 0, 0, 2)
494 	ZEND_ARG_INFO(0, pattern)
495 	ZEND_ARG_INFO(0, string)
496 	ZEND_ARG_INFO(0, option)
497 ZEND_END_ARG_INFO()
498 
499 ZEND_BEGIN_ARG_INFO_EX(arginfo_mb_ereg_search, 0, 0, 0)
500 	ZEND_ARG_INFO(0, pattern)
501 	ZEND_ARG_INFO(0, option)
502 ZEND_END_ARG_INFO()
503 
504 ZEND_BEGIN_ARG_INFO_EX(arginfo_mb_ereg_search_pos, 0, 0, 0)
505 	ZEND_ARG_INFO(0, pattern)
506 	ZEND_ARG_INFO(0, option)
507 ZEND_END_ARG_INFO()
508 
509 ZEND_BEGIN_ARG_INFO_EX(arginfo_mb_ereg_search_regs, 0, 0, 0)
510 	ZEND_ARG_INFO(0, pattern)
511 	ZEND_ARG_INFO(0, option)
512 ZEND_END_ARG_INFO()
513 
514 ZEND_BEGIN_ARG_INFO_EX(arginfo_mb_ereg_search_init, 0, 0, 1)
515 	ZEND_ARG_INFO(0, string)
516 	ZEND_ARG_INFO(0, pattern)
517 	ZEND_ARG_INFO(0, option)
518 ZEND_END_ARG_INFO()
519 
520 ZEND_BEGIN_ARG_INFO(arginfo_mb_ereg_search_getregs, 0)
521 ZEND_END_ARG_INFO()
522 
523 ZEND_BEGIN_ARG_INFO(arginfo_mb_ereg_search_getpos, 0)
524 ZEND_END_ARG_INFO()
525 
526 ZEND_BEGIN_ARG_INFO_EX(arginfo_mb_ereg_search_setpos, 0, 0, 1)
527 	ZEND_ARG_INFO(0, position)
528 ZEND_END_ARG_INFO()
529 
530 ZEND_BEGIN_ARG_INFO_EX(arginfo_mb_regex_set_options, 0, 0, 0)
531 	ZEND_ARG_INFO(0, options)
532 ZEND_END_ARG_INFO()
533 #endif /* HAVE_MBREGEX */
534 /* }}} */
535 
536 /* {{{ zend_function_entry mbstring_functions[] */
537 static const zend_function_entry mbstring_functions[] = {
538 	PHP_FE(mb_convert_case,			arginfo_mb_convert_case)
539 	PHP_FE(mb_strtoupper,			arginfo_mb_strtoupper)
540 	PHP_FE(mb_strtolower,			arginfo_mb_strtolower)
541 	PHP_FE(mb_language,				arginfo_mb_language)
542 	PHP_FE(mb_internal_encoding,	arginfo_mb_internal_encoding)
543 	PHP_FE(mb_http_input,			arginfo_mb_http_input)
544 	PHP_FE(mb_http_output,			arginfo_mb_http_output)
545 	PHP_FE(mb_detect_order,			arginfo_mb_detect_order)
546 	PHP_FE(mb_substitute_character,	arginfo_mb_substitute_character)
547 	PHP_FE(mb_parse_str,			arginfo_mb_parse_str)
548 	PHP_FE(mb_output_handler,		arginfo_mb_output_handler)
549 	PHP_FE(mb_preferred_mime_name,	arginfo_mb_preferred_mime_name)
550 	PHP_FE(mb_str_split,			arginfo_mb_str_split)
551 	PHP_FE(mb_strlen,				arginfo_mb_strlen)
552 	PHP_FE(mb_strpos,				arginfo_mb_strpos)
553 	PHP_FE(mb_strrpos,				arginfo_mb_strrpos)
554 	PHP_FE(mb_stripos,				arginfo_mb_stripos)
555 	PHP_FE(mb_strripos,				arginfo_mb_strripos)
556 	PHP_FE(mb_strstr,				arginfo_mb_strstr)
557 	PHP_FE(mb_strrchr,				arginfo_mb_strrchr)
558 	PHP_FE(mb_stristr,				arginfo_mb_stristr)
559 	PHP_FE(mb_strrichr,				arginfo_mb_strrichr)
560 	PHP_FE(mb_substr_count,			arginfo_mb_substr_count)
561 	PHP_FE(mb_substr,				arginfo_mb_substr)
562 	PHP_FE(mb_strcut,				arginfo_mb_strcut)
563 	PHP_FE(mb_strwidth,				arginfo_mb_strwidth)
564 	PHP_FE(mb_strimwidth,			arginfo_mb_strimwidth)
565 	PHP_FE(mb_convert_encoding,		arginfo_mb_convert_encoding)
566 	PHP_FE(mb_detect_encoding,		arginfo_mb_detect_encoding)
567 	PHP_FE(mb_list_encodings,		arginfo_mb_list_encodings)
568 	PHP_FE(mb_encoding_aliases,		arginfo_mb_encoding_aliases)
569 	PHP_FE(mb_convert_kana,			arginfo_mb_convert_kana)
570 	PHP_FE(mb_encode_mimeheader,	arginfo_mb_encode_mimeheader)
571 	PHP_FE(mb_decode_mimeheader,	arginfo_mb_decode_mimeheader)
572 	PHP_FE(mb_convert_variables,	arginfo_mb_convert_variables)
573 	PHP_FE(mb_encode_numericentity,	arginfo_mb_encode_numericentity)
574 	PHP_FE(mb_decode_numericentity,	arginfo_mb_decode_numericentity)
575 	PHP_FE(mb_send_mail,			arginfo_mb_send_mail)
576 	PHP_FE(mb_get_info,				arginfo_mb_get_info)
577 	PHP_FE(mb_check_encoding,		arginfo_mb_check_encoding)
578 	PHP_FE(mb_ord,					arginfo_mb_ord)
579 	PHP_FE(mb_chr,					arginfo_mb_chr)
580 	PHP_FE(mb_scrub,				arginfo_mb_scrub)
581 #if HAVE_MBREGEX
582 	PHP_MBREGEX_FUNCTION_ENTRIES
583 #endif
584 	PHP_FE_END
585 };
586 /* }}} */
587 
588 /* {{{ zend_module_entry mbstring_module_entry */
589 zend_module_entry mbstring_module_entry = {
590 	STANDARD_MODULE_HEADER,
591 	"mbstring",
592 	mbstring_functions,
593 	PHP_MINIT(mbstring),
594 	PHP_MSHUTDOWN(mbstring),
595 	PHP_RINIT(mbstring),
596 	PHP_RSHUTDOWN(mbstring),
597 	PHP_MINFO(mbstring),
598 	PHP_MBSTRING_VERSION,
599 	PHP_MODULE_GLOBALS(mbstring),
600 	PHP_GINIT(mbstring),
601 	PHP_GSHUTDOWN(mbstring),
602 	NULL,
603 	STANDARD_MODULE_PROPERTIES_EX
604 };
605 /* }}} */
606 
607 /* {{{ static sapi_post_entry php_post_entries[] */
608 static const sapi_post_entry php_post_entries[] = {
609 	{ DEFAULT_POST_CONTENT_TYPE, sizeof(DEFAULT_POST_CONTENT_TYPE)-1, sapi_read_standard_form_data,	php_std_post_handler },
610 	{ MULTIPART_CONTENT_TYPE,    sizeof(MULTIPART_CONTENT_TYPE)-1,    NULL,                         rfc1867_post_handler },
611 	{ NULL, 0, NULL, NULL }
612 };
613 /* }}} */
614 
615 #ifdef COMPILE_DL_MBSTRING
616 #ifdef ZTS
617 ZEND_TSRMLS_CACHE_DEFINE()
618 #endif
ZEND_GET_MODULE(mbstring)619 ZEND_GET_MODULE(mbstring)
620 #endif
621 
622 /* {{{ allocators */
623 static void *_php_mb_allocators_malloc(size_t sz)
624 {
625 	return emalloc(sz);
626 }
627 
_php_mb_allocators_realloc(void * ptr,size_t sz)628 static void *_php_mb_allocators_realloc(void *ptr, size_t sz)
629 {
630 	return erealloc(ptr, sz);
631 }
632 
_php_mb_allocators_calloc(size_t nelems,size_t szelem)633 static void *_php_mb_allocators_calloc(size_t nelems, size_t szelem)
634 {
635 	return ecalloc(nelems, szelem);
636 }
637 
_php_mb_allocators_free(void * ptr)638 static void _php_mb_allocators_free(void *ptr)
639 {
640 	efree(ptr);
641 }
642 
_php_mb_allocators_pmalloc(size_t sz)643 static void *_php_mb_allocators_pmalloc(size_t sz)
644 {
645 	return pemalloc(sz, 1);
646 }
647 
_php_mb_allocators_prealloc(void * ptr,size_t sz)648 static void *_php_mb_allocators_prealloc(void *ptr, size_t sz)
649 {
650 	return perealloc(ptr, sz, 1);
651 }
652 
_php_mb_allocators_pfree(void * ptr)653 static void _php_mb_allocators_pfree(void *ptr)
654 {
655 	pefree(ptr, 1);
656 }
657 
658 static const mbfl_allocators _php_mb_allocators = {
659 	_php_mb_allocators_malloc,
660 	_php_mb_allocators_realloc,
661 	_php_mb_allocators_calloc,
662 	_php_mb_allocators_free,
663 	_php_mb_allocators_pmalloc,
664 	_php_mb_allocators_prealloc,
665 	_php_mb_allocators_pfree
666 };
667 /* }}} */
668 
669 /* {{{ static sapi_post_entry mbstr_post_entries[] */
670 static const sapi_post_entry mbstr_post_entries[] = {
671 	{ DEFAULT_POST_CONTENT_TYPE, sizeof(DEFAULT_POST_CONTENT_TYPE)-1, sapi_read_standard_form_data, php_mb_post_handler },
672 	{ MULTIPART_CONTENT_TYPE,    sizeof(MULTIPART_CONTENT_TYPE)-1,    NULL,                         rfc1867_post_handler },
673 	{ NULL, 0, NULL, NULL }
674 };
675 /* }}} */
676 
php_mb_get_encoding(zend_string * encoding_name)677 static const mbfl_encoding *php_mb_get_encoding(zend_string *encoding_name) {
678 	if (encoding_name) {
679 		const mbfl_encoding *encoding;
680 		zend_string *last_encoding_name = MBSTRG(last_used_encoding_name);
681 		if (last_encoding_name && (last_encoding_name == encoding_name
682 				|| !strcasecmp(ZSTR_VAL(encoding_name), ZSTR_VAL(last_encoding_name)))) {
683 			return MBSTRG(last_used_encoding);
684 		}
685 
686 		encoding = mbfl_name2encoding(ZSTR_VAL(encoding_name));
687 		if (!encoding) {
688 			php_error_docref(NULL, E_WARNING, "Unknown encoding \"%s\"", ZSTR_VAL(encoding_name));
689 			return NULL;
690 		}
691 
692 		if (last_encoding_name) {
693 			zend_string_release(last_encoding_name);
694 		}
695 		MBSTRG(last_used_encoding_name) = zend_string_copy(encoding_name);
696 		MBSTRG(last_used_encoding) = encoding;
697 		return encoding;
698 	} else {
699 		return MBSTRG(current_internal_encoding);
700 	}
701 }
702 
703 /* {{{ static int php_mb_parse_encoding_list()
704  *  Return FAILURE if input contains any illegal encoding, otherwise SUCCESS.
705  *  Even if any illegal encoding is detected the result may contain a list
706  *  of parsed encodings.
707  */
708 static int
php_mb_parse_encoding_list(const char * value,size_t value_length,const mbfl_encoding *** return_list,size_t * return_size,int persistent)709 php_mb_parse_encoding_list(const char *value, size_t value_length, const mbfl_encoding ***return_list, size_t *return_size, int persistent)
710 {
711 	int bauto, ret = SUCCESS;
712 	size_t n, size;
713 	char *p, *p1, *p2, *endp, *tmpstr;
714 	const mbfl_encoding **entry, **list;
715 
716 	list = NULL;
717 	if (value == NULL || value_length == 0) {
718 		if (return_list) {
719 			*return_list = NULL;
720 		}
721 		if (return_size) {
722 			*return_size = 0;
723 		}
724 		return FAILURE;
725 	} else {
726 		/* copy the value string for work */
727 		if (value[0]=='"' && value[value_length-1]=='"' && value_length>2) {
728 			tmpstr = (char *)estrndup(value+1, value_length-2);
729 			value_length -= 2;
730 		}
731 		else
732 			tmpstr = (char *)estrndup(value, value_length);
733 		/* count the number of listed encoding names */
734 		endp = tmpstr + value_length;
735 		n = 1;
736 		p1 = tmpstr;
737 		while ((p2 = (char*)php_memnstr(p1, ",", 1, endp)) != NULL) {
738 			p1 = p2 + 1;
739 			n++;
740 		}
741 		size = n + MBSTRG(default_detect_order_list_size);
742 		/* make list */
743 		list = (const mbfl_encoding **)pecalloc(size, sizeof(mbfl_encoding*), persistent);
744 		entry = list;
745 		n = 0;
746 		bauto = 0;
747 		p1 = tmpstr;
748 		do {
749 			p2 = p = (char*)php_memnstr(p1, ",", 1, endp);
750 			if (p == NULL) {
751 				p = endp;
752 			}
753 			*p = '\0';
754 			/* trim spaces */
755 			while (p1 < p && (*p1 == ' ' || *p1 == '\t')) {
756 				p1++;
757 			}
758 			p--;
759 			while (p > p1 && (*p == ' ' || *p == '\t')) {
760 				*p = '\0';
761 				p--;
762 			}
763 			/* convert to the encoding number and check encoding */
764 			if (strcasecmp(p1, "auto") == 0) {
765 				if (!bauto) {
766 					const enum mbfl_no_encoding *src = MBSTRG(default_detect_order_list);
767 					const size_t identify_list_size = MBSTRG(default_detect_order_list_size);
768 					size_t i;
769 					bauto = 1;
770 					for (i = 0; i < identify_list_size; i++) {
771 						*entry++ = mbfl_no2encoding(*src++);
772 						n++;
773 					}
774 				}
775 			} else {
776 				const mbfl_encoding *encoding = mbfl_name2encoding(p1);
777 				if (encoding) {
778 					*entry++ = encoding;
779 					n++;
780 				} else {
781 					ret = FAILURE;
782 				}
783 			}
784 			p1 = p2 + 1;
785 		} while (n < size && p2 != NULL);
786 		if (n > 0) {
787 			if (return_list) {
788 				*return_list = list;
789 			} else {
790 				pefree(list, persistent);
791 			}
792 		} else {
793 			pefree(list, persistent);
794 			if (return_list) {
795 				*return_list = NULL;
796 			}
797 			ret = FAILURE;
798 		}
799 		if (return_size) {
800 			*return_size = n;
801 		}
802 		efree(tmpstr);
803 	}
804 
805 	return ret;
806 }
807 /* }}} */
808 
809 /* {{{ static int php_mb_parse_encoding_array()
810  *  Return FAILURE if input contains any illegal encoding, otherwise SUCCESS.
811  *  Even if any illegal encoding is detected the result may contain a list
812  *  of parsed encodings.
813  */
814 static int
php_mb_parse_encoding_array(zval * array,const mbfl_encoding *** return_list,size_t * return_size,int persistent)815 php_mb_parse_encoding_array(zval *array, const mbfl_encoding ***return_list, size_t *return_size, int persistent)
816 {
817 	zval *hash_entry;
818 	HashTable *target_hash;
819 	int i, n, bauto, ret = SUCCESS;
820 	const mbfl_encoding **list, **entry;
821 	size_t size;
822 
823 	list = NULL;
824 	if (Z_TYPE_P(array) == IS_ARRAY) {
825 		target_hash = Z_ARRVAL_P(array);
826 		i = zend_hash_num_elements(target_hash);
827 		size = i + MBSTRG(default_detect_order_list_size);
828 		list = (const mbfl_encoding **)pecalloc(size, sizeof(mbfl_encoding*), persistent);
829 		entry = list;
830 		bauto = 0;
831 		n = 0;
832 		ZEND_HASH_FOREACH_VAL(target_hash, hash_entry) {
833 			zend_string *encoding_str = zval_try_get_string(hash_entry);
834 			if (UNEXPECTED(!encoding_str)) {
835 				ret = FAILURE;
836 				break;
837 			}
838 
839 			if (strcasecmp(ZSTR_VAL(encoding_str), "auto") == 0) {
840 				if (!bauto) {
841 					const enum mbfl_no_encoding *src = MBSTRG(default_detect_order_list);
842 					const size_t identify_list_size = MBSTRG(default_detect_order_list_size);
843 					size_t j;
844 
845 					bauto = 1;
846 					for (j = 0; j < identify_list_size; j++) {
847 						*entry++ = mbfl_no2encoding(*src++);
848 						n++;
849 					}
850 				}
851 			} else {
852 				const mbfl_encoding *encoding = mbfl_name2encoding(ZSTR_VAL(encoding_str));
853 				if (encoding) {
854 					*entry++ = encoding;
855 					n++;
856 				} else {
857 					ret = FAILURE;
858 				}
859 			}
860 			i--;
861 			zend_string_release(encoding_str);
862 		} ZEND_HASH_FOREACH_END();
863 		if (n > 0) {
864 			if (return_list) {
865 				*return_list = list;
866 			} else {
867 				pefree(list, persistent);
868 			}
869 		} else {
870 			pefree(list, persistent);
871 			if (return_list) {
872 				*return_list = NULL;
873 			}
874 			ret = FAILURE;
875 		}
876 		if (return_size) {
877 			*return_size = n;
878 		}
879 	}
880 
881 	return ret;
882 }
883 /* }}} */
884 
885 /* {{{ zend_multibyte interface */
php_mb_zend_encoding_fetcher(const char * encoding_name)886 static const zend_encoding* php_mb_zend_encoding_fetcher(const char *encoding_name)
887 {
888 	return (const zend_encoding*)mbfl_name2encoding(encoding_name);
889 }
890 
php_mb_zend_encoding_name_getter(const zend_encoding * encoding)891 static const char *php_mb_zend_encoding_name_getter(const zend_encoding *encoding)
892 {
893 	return ((const mbfl_encoding *)encoding)->name;
894 }
895 
php_mb_zend_encoding_lexer_compatibility_checker(const zend_encoding * _encoding)896 static int php_mb_zend_encoding_lexer_compatibility_checker(const zend_encoding *_encoding)
897 {
898 	const mbfl_encoding *encoding = (const mbfl_encoding*)_encoding;
899 	if (encoding->flag & MBFL_ENCTYPE_SBCS) {
900 		return 1;
901 	}
902 	if ((encoding->flag & (MBFL_ENCTYPE_MBCS | MBFL_ENCTYPE_GL_UNSAFE)) == MBFL_ENCTYPE_MBCS) {
903 		return 1;
904 	}
905 	return 0;
906 }
907 
php_mb_zend_encoding_detector(const unsigned char * arg_string,size_t arg_length,const zend_encoding ** list,size_t list_size)908 static const zend_encoding *php_mb_zend_encoding_detector(const unsigned char *arg_string, size_t arg_length, const zend_encoding **list, size_t list_size)
909 {
910 	mbfl_string string;
911 
912 	if (!list) {
913 		list = (const zend_encoding **)MBSTRG(current_detect_order_list);
914 		list_size = MBSTRG(current_detect_order_list_size);
915 	}
916 
917 	mbfl_string_init(&string);
918 	string.no_language = MBSTRG(language);
919 	string.val = (unsigned char *)arg_string;
920 	string.len = arg_length;
921 	return (const zend_encoding *) mbfl_identify_encoding(&string, (const mbfl_encoding **)list, list_size, 0);
922 }
923 
php_mb_zend_encoding_converter(unsigned char ** to,size_t * to_length,const unsigned char * from,size_t from_length,const zend_encoding * encoding_to,const zend_encoding * encoding_from)924 static size_t php_mb_zend_encoding_converter(unsigned char **to, size_t *to_length, const unsigned char *from, size_t from_length, const zend_encoding *encoding_to, const zend_encoding *encoding_from)
925 {
926 	mbfl_string string, result;
927 	mbfl_buffer_converter *convd;
928 	int status;
929 	size_t loc;
930 
931 	/* new encoding */
932 	/* initialize string */
933 	string.encoding = (const mbfl_encoding*)encoding_from;
934 	string.no_language = MBSTRG(language);
935 	string.val = (unsigned char*)from;
936 	string.len = from_length;
937 
938 	/* initialize converter */
939 	convd = mbfl_buffer_converter_new((const mbfl_encoding *)encoding_from, (const mbfl_encoding *)encoding_to, string.len);
940 	if (convd == NULL) {
941 		return (size_t) -1;
942 	}
943 
944 	mbfl_buffer_converter_illegal_mode(convd, MBSTRG(current_filter_illegal_mode));
945 	mbfl_buffer_converter_illegal_substchar(convd, MBSTRG(current_filter_illegal_substchar));
946 
947 	/* do it */
948 	status = mbfl_buffer_converter_feed2(convd, &string, &loc);
949 	if (status) {
950 		mbfl_buffer_converter_delete(convd);
951 		return (size_t)-1;
952 	}
953 
954 	mbfl_buffer_converter_flush(convd);
955 	mbfl_string_init(&result);
956 	if (!mbfl_buffer_converter_result(convd, &result)) {
957 		mbfl_buffer_converter_delete(convd);
958 		return (size_t)-1;
959 	}
960 
961 	*to = result.val;
962 	*to_length = result.len;
963 
964 	mbfl_buffer_converter_delete(convd);
965 
966 	return loc;
967 }
968 
php_mb_zend_encoding_list_parser(const char * encoding_list,size_t encoding_list_len,const zend_encoding *** return_list,size_t * return_size,int persistent)969 static int php_mb_zend_encoding_list_parser(const char *encoding_list, size_t encoding_list_len, const zend_encoding ***return_list, size_t *return_size, int persistent)
970 {
971 	return php_mb_parse_encoding_list(encoding_list, encoding_list_len, (const mbfl_encoding ***)return_list, return_size, persistent);
972 }
973 
php_mb_zend_internal_encoding_getter(void)974 static const zend_encoding *php_mb_zend_internal_encoding_getter(void)
975 {
976 	return (const zend_encoding *)MBSTRG(internal_encoding);
977 }
978 
php_mb_zend_internal_encoding_setter(const zend_encoding * encoding)979 static int php_mb_zend_internal_encoding_setter(const zend_encoding *encoding)
980 {
981 	MBSTRG(internal_encoding) = (const mbfl_encoding *)encoding;
982 	return SUCCESS;
983 }
984 
985 static zend_multibyte_functions php_mb_zend_multibyte_functions = {
986 	"mbstring",
987 	php_mb_zend_encoding_fetcher,
988 	php_mb_zend_encoding_name_getter,
989 	php_mb_zend_encoding_lexer_compatibility_checker,
990 	php_mb_zend_encoding_detector,
991 	php_mb_zend_encoding_converter,
992 	php_mb_zend_encoding_list_parser,
993 	php_mb_zend_internal_encoding_getter,
994 	php_mb_zend_internal_encoding_setter
995 };
996 /* }}} */
997 
998 static void *_php_mb_compile_regex(const char *pattern);
999 static int _php_mb_match_regex(void *opaque, const char *str, size_t str_len);
1000 static void _php_mb_free_regex(void *opaque);
1001 
1002 #if HAVE_MBREGEX
1003 /* {{{ _php_mb_compile_regex */
_php_mb_compile_regex(const char * pattern)1004 static void *_php_mb_compile_regex(const char *pattern)
1005 {
1006 	php_mb_regex_t *retval;
1007 	OnigErrorInfo err_info;
1008 	int err_code;
1009 
1010 	if ((err_code = onig_new(&retval,
1011 			(const OnigUChar *)pattern,
1012 			(const OnigUChar *)pattern + strlen(pattern),
1013 			ONIG_OPTION_IGNORECASE | ONIG_OPTION_DONT_CAPTURE_GROUP,
1014 			ONIG_ENCODING_ASCII, &OnigSyntaxPerl, &err_info))) {
1015 		OnigUChar err_str[ONIG_MAX_ERROR_MESSAGE_LEN];
1016 		onig_error_code_to_str(err_str, err_code, err_info);
1017 		php_error_docref(NULL, E_WARNING, "%s: %s", pattern, err_str);
1018 		retval = NULL;
1019 	}
1020 	return retval;
1021 }
1022 /* }}} */
1023 
1024 /* {{{ _php_mb_match_regex */
_php_mb_match_regex(void * opaque,const char * str,size_t str_len)1025 static int _php_mb_match_regex(void *opaque, const char *str, size_t str_len)
1026 {
1027 	OnigMatchParam *mp = onig_new_match_param();
1028 	int err;
1029 	onig_initialize_match_param(mp);
1030 	if (!ZEND_LONG_UINT_OVFL(MBSTRG(regex_stack_limit))) {
1031 		onig_set_match_stack_limit_size_of_match_param(mp, (unsigned int)MBSTRG(regex_stack_limit));
1032 	}
1033 	if (!ZEND_LONG_UINT_OVFL(MBSTRG(regex_retry_limit))) {
1034 		onig_set_retry_limit_in_match_of_match_param(mp, (unsigned int)MBSTRG(regex_retry_limit));
1035 	}
1036 	/* search */
1037 	err = onig_search_with_param((php_mb_regex_t *)opaque, (const OnigUChar *)str,
1038 		(const OnigUChar*)str + str_len, (const OnigUChar *)str,
1039 		(const OnigUChar*)str + str_len, NULL, ONIG_OPTION_NONE, mp);
1040 	onig_free_match_param(mp);
1041 	return err >= 0;
1042 }
1043 /* }}} */
1044 
1045 /* {{{ _php_mb_free_regex */
_php_mb_free_regex(void * opaque)1046 static void _php_mb_free_regex(void *opaque)
1047 {
1048 	onig_free((php_mb_regex_t *)opaque);
1049 }
1050 /* }}} */
1051 #else
1052 /* {{{ _php_mb_compile_regex */
_php_mb_compile_regex(const char * pattern)1053 static void *_php_mb_compile_regex(const char *pattern)
1054 {
1055 	pcre2_code *retval;
1056 	PCRE2_SIZE err_offset;
1057 	int errnum;
1058 
1059 	if (!(retval = pcre2_compile((PCRE2_SPTR)pattern, PCRE2_ZERO_TERMINATED,
1060 			PCRE2_CASELESS, &errnum, &err_offset, php_pcre_cctx()))) {
1061 		PCRE2_UCHAR err_str[128];
1062 		pcre2_get_error_message(errnum, err_str, sizeof(err_str));
1063 		php_error_docref(NULL, E_WARNING, "%s (offset=%zu): %s", pattern, err_offset, err_str);
1064 	}
1065 	return retval;
1066 }
1067 /* }}} */
1068 
1069 /* {{{ _php_mb_match_regex */
_php_mb_match_regex(void * opaque,const char * str,size_t str_len)1070 static int _php_mb_match_regex(void *opaque, const char *str, size_t str_len)
1071 {
1072 	int res;
1073 
1074 	pcre2_match_data *match_data = php_pcre_create_match_data(0, opaque);
1075 	if (NULL == match_data) {
1076 		pcre2_code_free(opaque);
1077 		php_error_docref(NULL, E_WARNING, "Cannot allocate match data");
1078 		return FAILURE;
1079 	}
1080 	res = pcre2_match(opaque, (PCRE2_SPTR)str, str_len, 0, 0, match_data, php_pcre_mctx()) >= 0;
1081 	php_pcre_free_match_data(match_data);
1082 
1083 	return res;
1084 }
1085 /* }}} */
1086 
1087 /* {{{ _php_mb_free_regex */
_php_mb_free_regex(void * opaque)1088 static void _php_mb_free_regex(void *opaque)
1089 {
1090 	pcre2_code_free(opaque);
1091 }
1092 /* }}} */
1093 #endif
1094 
1095 /* {{{ php_mb_nls_get_default_detect_order_list */
php_mb_nls_get_default_detect_order_list(enum mbfl_no_language lang,enum mbfl_no_encoding ** plist,size_t * plist_size)1096 static int php_mb_nls_get_default_detect_order_list(enum mbfl_no_language lang, enum mbfl_no_encoding **plist, size_t *plist_size)
1097 {
1098 	size_t i;
1099 
1100 	*plist = (enum mbfl_no_encoding *) php_mb_default_identify_list_neut;
1101 	*plist_size = sizeof(php_mb_default_identify_list_neut) / sizeof(php_mb_default_identify_list_neut[0]);
1102 
1103 	for (i = 0; i < sizeof(php_mb_default_identify_list) / sizeof(php_mb_default_identify_list[0]); i++) {
1104 		if (php_mb_default_identify_list[i].lang == lang) {
1105 			*plist = (enum mbfl_no_encoding *)php_mb_default_identify_list[i].list;
1106 			*plist_size = php_mb_default_identify_list[i].list_size;
1107 			return 1;
1108 		}
1109 	}
1110 	return 0;
1111 }
1112 /* }}} */
1113 
php_mb_rfc1867_substring_conf(const zend_encoding * encoding,char * start,size_t len,char quote)1114 static char *php_mb_rfc1867_substring_conf(const zend_encoding *encoding, char *start, size_t len, char quote)
1115 {
1116 	char *result = emalloc(len + 2);
1117 	char *resp = result;
1118 	size_t i;
1119 
1120 	for (i = 0; i < len && start[i] != quote; ++i) {
1121 		if (start[i] == '\\' && (start[i + 1] == '\\' || (quote && start[i + 1] == quote))) {
1122 			*resp++ = start[++i];
1123 		} else {
1124 			size_t j = php_mb_mbchar_bytes_ex(start+i, (const mbfl_encoding *)encoding);
1125 
1126 			while (j-- > 0 && i < len) {
1127 				*resp++ = start[i++];
1128 			}
1129 			--i;
1130 		}
1131 	}
1132 
1133 	*resp = '\0';
1134 	return result;
1135 }
1136 
php_mb_rfc1867_getword(const zend_encoding * encoding,char ** line,char stop)1137 static char *php_mb_rfc1867_getword(const zend_encoding *encoding, char **line, char stop) /* {{{ */
1138 {
1139 	char *pos = *line, quote;
1140 	char *res;
1141 
1142 	while (*pos && *pos != stop) {
1143 		if ((quote = *pos) == '"' || quote == '\'') {
1144 			++pos;
1145 			while (*pos && *pos != quote) {
1146 				if (*pos == '\\' && pos[1] && pos[1] == quote) {
1147 					pos += 2;
1148 				} else {
1149 					++pos;
1150 				}
1151 			}
1152 			if (*pos) {
1153 				++pos;
1154 			}
1155 		} else {
1156 			pos += php_mb_mbchar_bytes_ex(pos, (const mbfl_encoding *)encoding);
1157 
1158 		}
1159 	}
1160 	if (*pos == '\0') {
1161 		res = estrdup(*line);
1162 		*line += strlen(*line);
1163 		return res;
1164 	}
1165 
1166 	res = estrndup(*line, pos - *line);
1167 
1168 	while (*pos == stop) {
1169 		pos += php_mb_mbchar_bytes_ex(pos, (const mbfl_encoding *)encoding);
1170 	}
1171 
1172 	*line = pos;
1173 	return res;
1174 }
1175 /* }}} */
1176 
php_mb_rfc1867_getword_conf(const zend_encoding * encoding,char * str)1177 static char *php_mb_rfc1867_getword_conf(const zend_encoding *encoding, char *str) /* {{{ */
1178 {
1179 	while (*str && isspace(*(unsigned char *)str)) {
1180 		++str;
1181 	}
1182 
1183 	if (!*str) {
1184 		return estrdup("");
1185 	}
1186 
1187 	if (*str == '"' || *str == '\'') {
1188 		char quote = *str;
1189 
1190 		str++;
1191 		return php_mb_rfc1867_substring_conf(encoding, str, strlen(str), quote);
1192 	} else {
1193 		char *strend = str;
1194 
1195 		while (*strend && !isspace(*(unsigned char *)strend)) {
1196 			++strend;
1197 		}
1198 		return php_mb_rfc1867_substring_conf(encoding, str, strend - str, 0);
1199 	}
1200 }
1201 /* }}} */
1202 
php_mb_rfc1867_basename(const zend_encoding * encoding,char * filename)1203 static char *php_mb_rfc1867_basename(const zend_encoding *encoding, char *filename) /* {{{ */
1204 {
1205 	char *s, *s2;
1206 	const size_t filename_len = strlen(filename);
1207 
1208 	/* The \ check should technically be needed for win32 systems only where
1209 	 * it is a valid path separator. However, IE in all it's wisdom always sends
1210 	 * the full path of the file on the user's filesystem, which means that unless
1211 	 * the user does basename() they get a bogus file name. Until IE's user base drops
1212 	 * to nill or problem is fixed this code must remain enabled for all systems. */
1213 	s = php_mb_safe_strrchr_ex(filename, '\\', filename_len, (const mbfl_encoding *)encoding);
1214 	s2 = php_mb_safe_strrchr_ex(filename, '/', filename_len, (const mbfl_encoding *)encoding);
1215 
1216 	if (s && s2) {
1217 		if (s > s2) {
1218 			return ++s;
1219 		} else {
1220 			return ++s2;
1221 		}
1222 	} else if (s) {
1223 		return ++s;
1224 	} else if (s2) {
1225 		return ++s2;
1226 	} else {
1227 		return filename;
1228 	}
1229 }
1230 /* }}} */
1231 
1232 /* {{{ php.ini directive handler */
1233 /* {{{ static PHP_INI_MH(OnUpdate_mbstring_language) */
PHP_INI_MH(OnUpdate_mbstring_language)1234 static PHP_INI_MH(OnUpdate_mbstring_language)
1235 {
1236 	enum mbfl_no_language no_language;
1237 
1238 	no_language = mbfl_name2no_language(ZSTR_VAL(new_value));
1239 	if (no_language == mbfl_no_language_invalid) {
1240 		MBSTRG(language) = mbfl_no_language_neutral;
1241 		return FAILURE;
1242 	}
1243 	MBSTRG(language) = no_language;
1244 	php_mb_nls_get_default_detect_order_list(no_language, &MBSTRG(default_detect_order_list), &MBSTRG(default_detect_order_list_size));
1245 	return SUCCESS;
1246 }
1247 /* }}} */
1248 
1249 /* {{{ static PHP_INI_MH(OnUpdate_mbstring_detect_order) */
PHP_INI_MH(OnUpdate_mbstring_detect_order)1250 static PHP_INI_MH(OnUpdate_mbstring_detect_order)
1251 {
1252 	const mbfl_encoding **list;
1253 	size_t size;
1254 
1255 	if (!new_value) {
1256 		if (MBSTRG(detect_order_list)) {
1257 			pefree(MBSTRG(detect_order_list), 1);
1258 		}
1259 		MBSTRG(detect_order_list) = NULL;
1260 		MBSTRG(detect_order_list_size) = 0;
1261 		return SUCCESS;
1262 	}
1263 
1264 	if (FAILURE == php_mb_parse_encoding_list(ZSTR_VAL(new_value), ZSTR_LEN(new_value), &list, &size, 1)) {
1265 		return FAILURE;
1266 	}
1267 
1268 	if (MBSTRG(detect_order_list)) {
1269 		pefree(MBSTRG(detect_order_list), 1);
1270 	}
1271 	MBSTRG(detect_order_list) = list;
1272 	MBSTRG(detect_order_list_size) = size;
1273 	return SUCCESS;
1274 }
1275 /* }}} */
1276 
_php_mb_ini_mbstring_http_input_set(const char * new_value,size_t new_value_length)1277 static int _php_mb_ini_mbstring_http_input_set(const char *new_value, size_t new_value_length) {
1278 	const mbfl_encoding **list;
1279 	size_t size;
1280 	if (FAILURE == php_mb_parse_encoding_list(new_value, new_value_length, &list, &size, 1)) {
1281 		return FAILURE;
1282 	}
1283 	if (MBSTRG(http_input_list)) {
1284 		pefree(MBSTRG(http_input_list), 1);
1285 	}
1286 	MBSTRG(http_input_list) = list;
1287 	MBSTRG(http_input_list_size) = size;
1288 	return SUCCESS;
1289 }
1290 
1291 /* {{{ static PHP_INI_MH(OnUpdate_mbstring_http_input) */
PHP_INI_MH(OnUpdate_mbstring_http_input)1292 static PHP_INI_MH(OnUpdate_mbstring_http_input)
1293 {
1294 	if (stage & (PHP_INI_STAGE_ACTIVATE | PHP_INI_STAGE_RUNTIME)) {
1295 		php_error_docref("ref.mbstring", E_DEPRECATED, "Use of mbstring.http_input is deprecated");
1296 	}
1297 
1298 	if (!new_value || !ZSTR_VAL(new_value)) {
1299 		const char *encoding = php_get_input_encoding();
1300 		MBSTRG(http_input_set) = 0;
1301 		_php_mb_ini_mbstring_http_input_set(encoding, strlen(encoding));
1302 		return SUCCESS;
1303 	}
1304 
1305 	MBSTRG(http_input_set) = 1;
1306 	return _php_mb_ini_mbstring_http_input_set(ZSTR_VAL(new_value), ZSTR_LEN(new_value));
1307 }
1308 /* }}} */
1309 
_php_mb_ini_mbstring_http_output_set(const char * new_value)1310 static int _php_mb_ini_mbstring_http_output_set(const char *new_value) {
1311 	const mbfl_encoding *encoding = mbfl_name2encoding(new_value);
1312 	if (!encoding) {
1313 		return FAILURE;
1314 	}
1315 
1316 	MBSTRG(http_output_encoding) = encoding;
1317 	MBSTRG(current_http_output_encoding) = encoding;
1318 	return SUCCESS;
1319 }
1320 
1321 /* {{{ static PHP_INI_MH(OnUpdate_mbstring_http_output) */
PHP_INI_MH(OnUpdate_mbstring_http_output)1322 static PHP_INI_MH(OnUpdate_mbstring_http_output)
1323 {
1324 	if (stage & (PHP_INI_STAGE_ACTIVATE | PHP_INI_STAGE_RUNTIME)) {
1325 		php_error_docref("ref.mbstring", E_DEPRECATED, "Use of mbstring.http_output is deprecated");
1326 	}
1327 
1328 	if (new_value == NULL || ZSTR_LEN(new_value) == 0) {
1329 		MBSTRG(http_output_set) = 0;
1330 		_php_mb_ini_mbstring_http_output_set(php_get_output_encoding());
1331 		return SUCCESS;
1332 	}
1333 
1334 	MBSTRG(http_output_set) = 1;
1335 	return _php_mb_ini_mbstring_http_output_set(ZSTR_VAL(new_value));
1336 }
1337 /* }}} */
1338 
1339 /* {{{ static _php_mb_ini_mbstring_internal_encoding_set */
_php_mb_ini_mbstring_internal_encoding_set(const char * new_value,size_t new_value_length)1340 static int _php_mb_ini_mbstring_internal_encoding_set(const char *new_value, size_t new_value_length)
1341 {
1342 	const mbfl_encoding *encoding;
1343 
1344 	if (!new_value || !new_value_length || !(encoding = mbfl_name2encoding(new_value))) {
1345 		/* falls back to UTF-8 if an unknown encoding name is given */
1346 		encoding = mbfl_no2encoding(mbfl_no_encoding_utf8);
1347 	}
1348 	MBSTRG(internal_encoding) = encoding;
1349 	MBSTRG(current_internal_encoding) = encoding;
1350 #if HAVE_MBREGEX
1351 	{
1352 		const char *enc_name = new_value;
1353 		if (FAILURE == php_mb_regex_set_default_mbctype(enc_name)) {
1354 			/* falls back to UTF-8 if an unknown encoding name is given */
1355 			enc_name = "UTF-8";
1356 			php_mb_regex_set_default_mbctype(enc_name);
1357 		}
1358 		php_mb_regex_set_mbctype(new_value);
1359 	}
1360 #endif
1361 	return SUCCESS;
1362 }
1363 /* }}} */
1364 
1365 /* {{{ static PHP_INI_MH(OnUpdate_mbstring_internal_encoding) */
PHP_INI_MH(OnUpdate_mbstring_internal_encoding)1366 static PHP_INI_MH(OnUpdate_mbstring_internal_encoding)
1367 {
1368 	if (stage & (PHP_INI_STAGE_ACTIVATE | PHP_INI_STAGE_RUNTIME)) {
1369 		php_error_docref("ref.mbstring", E_DEPRECATED, "Use of mbstring.internal_encoding is deprecated");
1370 	}
1371 
1372 	if (OnUpdateString(entry, new_value, mh_arg1, mh_arg2, mh_arg3, stage) == FAILURE) {
1373 		return FAILURE;
1374 	}
1375 
1376 	if (new_value && ZSTR_LEN(new_value)) {
1377 		MBSTRG(internal_encoding_set) = 1;
1378 		return _php_mb_ini_mbstring_internal_encoding_set(ZSTR_VAL(new_value), ZSTR_LEN(new_value));
1379 	} else {
1380 		const char *encoding = php_get_internal_encoding();
1381 		MBSTRG(internal_encoding_set) = 0;
1382 		return _php_mb_ini_mbstring_internal_encoding_set(encoding, strlen(encoding));
1383 	}
1384 }
1385 /* }}} */
1386 
1387 /* {{{ static PHP_INI_MH(OnUpdate_mbstring_substitute_character) */
PHP_INI_MH(OnUpdate_mbstring_substitute_character)1388 static PHP_INI_MH(OnUpdate_mbstring_substitute_character)
1389 {
1390 	int c;
1391 	char *endptr = NULL;
1392 
1393 	if (new_value != NULL) {
1394 		if (strcasecmp("none", ZSTR_VAL(new_value)) == 0) {
1395 			MBSTRG(filter_illegal_mode) = MBFL_OUTPUTFILTER_ILLEGAL_MODE_NONE;
1396 			MBSTRG(current_filter_illegal_mode) = MBFL_OUTPUTFILTER_ILLEGAL_MODE_NONE;
1397 		} else if (strcasecmp("long", ZSTR_VAL(new_value)) == 0) {
1398 			MBSTRG(filter_illegal_mode) = MBFL_OUTPUTFILTER_ILLEGAL_MODE_LONG;
1399 			MBSTRG(current_filter_illegal_mode) = MBFL_OUTPUTFILTER_ILLEGAL_MODE_LONG;
1400 		} else if (strcasecmp("entity", ZSTR_VAL(new_value)) == 0) {
1401 			MBSTRG(filter_illegal_mode) = MBFL_OUTPUTFILTER_ILLEGAL_MODE_ENTITY;
1402 			MBSTRG(current_filter_illegal_mode) = MBFL_OUTPUTFILTER_ILLEGAL_MODE_ENTITY;
1403 		} else {
1404 			MBSTRG(filter_illegal_mode) = MBFL_OUTPUTFILTER_ILLEGAL_MODE_CHAR;
1405 			MBSTRG(current_filter_illegal_mode) = MBFL_OUTPUTFILTER_ILLEGAL_MODE_CHAR;
1406 			if (ZSTR_LEN(new_value) > 0) {
1407 				c = strtol(ZSTR_VAL(new_value), &endptr, 0);
1408 				if (*endptr == '\0') {
1409 					MBSTRG(filter_illegal_substchar) = c;
1410 					MBSTRG(current_filter_illegal_substchar) = c;
1411 				}
1412 			}
1413 		}
1414 	} else {
1415 		MBSTRG(filter_illegal_mode) = MBFL_OUTPUTFILTER_ILLEGAL_MODE_CHAR;
1416 		MBSTRG(current_filter_illegal_mode) = MBFL_OUTPUTFILTER_ILLEGAL_MODE_CHAR;
1417 		MBSTRG(filter_illegal_substchar) = 0x3f;	/* '?' */
1418 		MBSTRG(current_filter_illegal_substchar) = 0x3f;	/* '?' */
1419 	}
1420 
1421 	return SUCCESS;
1422 }
1423 /* }}} */
1424 
1425 /* {{{ static PHP_INI_MH(OnUpdate_mbstring_encoding_translation) */
PHP_INI_MH(OnUpdate_mbstring_encoding_translation)1426 static PHP_INI_MH(OnUpdate_mbstring_encoding_translation)
1427 {
1428 	if (new_value == NULL) {
1429 		return FAILURE;
1430 	}
1431 
1432 	OnUpdateBool(entry, new_value, mh_arg1, mh_arg2, mh_arg3, stage);
1433 
1434 	if (MBSTRG(encoding_translation)) {
1435 		sapi_unregister_post_entry(php_post_entries);
1436 		sapi_register_post_entries(mbstr_post_entries);
1437 	} else {
1438 		sapi_unregister_post_entry(mbstr_post_entries);
1439 		sapi_register_post_entries(php_post_entries);
1440 	}
1441 
1442 	return SUCCESS;
1443 }
1444 /* }}} */
1445 
1446 /* {{{ static PHP_INI_MH(OnUpdate_mbstring_http_output_conv_mimetypes */
PHP_INI_MH(OnUpdate_mbstring_http_output_conv_mimetypes)1447 static PHP_INI_MH(OnUpdate_mbstring_http_output_conv_mimetypes)
1448 {
1449 	zend_string *tmp;
1450 	void *re = NULL;
1451 
1452 	if (!new_value) {
1453 		new_value = entry->orig_value;
1454 	}
1455 	tmp = php_trim(new_value, NULL, 0, 3);
1456 
1457 	if (ZSTR_LEN(tmp) > 0) {
1458 		if (!(re = _php_mb_compile_regex(ZSTR_VAL(tmp)))) {
1459 			zend_string_release_ex(tmp, 0);
1460 			return FAILURE;
1461 		}
1462 	}
1463 
1464 	if (MBSTRG(http_output_conv_mimetypes)) {
1465 		_php_mb_free_regex(MBSTRG(http_output_conv_mimetypes));
1466 	}
1467 
1468 	MBSTRG(http_output_conv_mimetypes) = re;
1469 
1470 	zend_string_release_ex(tmp, 0);
1471 	return SUCCESS;
1472 }
1473 /* }}} */
1474 /* }}} */
1475 
1476 /* {{{ php.ini directive registration */
1477 PHP_INI_BEGIN()
1478 	PHP_INI_ENTRY("mbstring.language", "neutral", PHP_INI_ALL, OnUpdate_mbstring_language)
1479 	PHP_INI_ENTRY("mbstring.detect_order", NULL, PHP_INI_ALL, OnUpdate_mbstring_detect_order)
1480 	PHP_INI_ENTRY("mbstring.http_input", NULL, PHP_INI_ALL, OnUpdate_mbstring_http_input)
1481 	PHP_INI_ENTRY("mbstring.http_output", NULL, PHP_INI_ALL, OnUpdate_mbstring_http_output)
1482 	STD_PHP_INI_ENTRY("mbstring.internal_encoding", NULL, PHP_INI_ALL, OnUpdate_mbstring_internal_encoding, internal_encoding_name, zend_mbstring_globals, mbstring_globals)
1483 	PHP_INI_ENTRY("mbstring.substitute_character", NULL, PHP_INI_ALL, OnUpdate_mbstring_substitute_character)
1484 	STD_PHP_INI_ENTRY("mbstring.func_overload", "0",
1485 	PHP_INI_SYSTEM, OnUpdateLong, func_overload, zend_mbstring_globals, mbstring_globals)
1486 
1487 	STD_PHP_INI_BOOLEAN("mbstring.encoding_translation", "0",
1488 		PHP_INI_SYSTEM | PHP_INI_PERDIR,
1489 		OnUpdate_mbstring_encoding_translation,
1490 		encoding_translation, zend_mbstring_globals, mbstring_globals)
1491 	PHP_INI_ENTRY("mbstring.http_output_conv_mimetypes",
1492 		"^(text/|application/xhtml\\+xml)",
1493 		PHP_INI_ALL,
1494 		OnUpdate_mbstring_http_output_conv_mimetypes)
1495 
1496 	STD_PHP_INI_BOOLEAN("mbstring.strict_detection", "0",
1497 		PHP_INI_ALL,
1498 		OnUpdateBool,
1499 		strict_detection, zend_mbstring_globals, mbstring_globals)
1500 #if HAVE_MBREGEX
1501 	STD_PHP_INI_ENTRY("mbstring.regex_stack_limit", "100000",PHP_INI_ALL, OnUpdateLong, regex_stack_limit, zend_mbstring_globals, mbstring_globals)
1502 	STD_PHP_INI_ENTRY("mbstring.regex_retry_limit", "1000000",PHP_INI_ALL, OnUpdateLong, regex_retry_limit, zend_mbstring_globals, mbstring_globals)
1503 #endif
PHP_INI_END()1504 PHP_INI_END()
1505 /* }}} */
1506 
1507 static void mbstring_internal_encoding_changed_hook() {
1508 	/* One of the internal_encoding / input_encoding / output_encoding ini settings changed. */
1509 	if (!MBSTRG(internal_encoding_set)) {
1510 		const char *encoding = php_get_internal_encoding();
1511 		_php_mb_ini_mbstring_internal_encoding_set(encoding, strlen(encoding));
1512 	}
1513 
1514 	if (!MBSTRG(http_output_set)) {
1515 		const char *encoding = php_get_output_encoding();
1516 		_php_mb_ini_mbstring_http_output_set(encoding);
1517 	}
1518 
1519 	if (!MBSTRG(http_input_set)) {
1520 		const char *encoding = php_get_input_encoding();
1521 		_php_mb_ini_mbstring_http_input_set(encoding, strlen(encoding));
1522 	}
1523 }
1524 
1525 /* {{{ module global initialize handler */
PHP_GINIT_FUNCTION(mbstring)1526 static PHP_GINIT_FUNCTION(mbstring)
1527 {
1528 #if defined(COMPILE_DL_MBSTRING) && defined(ZTS)
1529 ZEND_TSRMLS_CACHE_UPDATE();
1530 #endif
1531 
1532 	mbstring_globals->language = mbfl_no_language_uni;
1533 	mbstring_globals->internal_encoding = NULL;
1534 	mbstring_globals->current_internal_encoding = mbstring_globals->internal_encoding;
1535 	mbstring_globals->http_output_encoding = &mbfl_encoding_pass;
1536 	mbstring_globals->current_http_output_encoding = &mbfl_encoding_pass;
1537 	mbstring_globals->http_input_identify = NULL;
1538 	mbstring_globals->http_input_identify_get = NULL;
1539 	mbstring_globals->http_input_identify_post = NULL;
1540 	mbstring_globals->http_input_identify_cookie = NULL;
1541 	mbstring_globals->http_input_identify_string = NULL;
1542 	mbstring_globals->http_input_list = NULL;
1543 	mbstring_globals->http_input_list_size = 0;
1544 	mbstring_globals->detect_order_list = NULL;
1545 	mbstring_globals->detect_order_list_size = 0;
1546 	mbstring_globals->current_detect_order_list = NULL;
1547 	mbstring_globals->current_detect_order_list_size = 0;
1548 	mbstring_globals->default_detect_order_list = (enum mbfl_no_encoding *) php_mb_default_identify_list_neut;
1549 	mbstring_globals->default_detect_order_list_size = sizeof(php_mb_default_identify_list_neut) / sizeof(php_mb_default_identify_list_neut[0]);
1550 	mbstring_globals->filter_illegal_mode = MBFL_OUTPUTFILTER_ILLEGAL_MODE_CHAR;
1551 	mbstring_globals->filter_illegal_substchar = 0x3f;	/* '?' */
1552 	mbstring_globals->current_filter_illegal_mode = MBFL_OUTPUTFILTER_ILLEGAL_MODE_CHAR;
1553 	mbstring_globals->current_filter_illegal_substchar = 0x3f;	/* '?' */
1554 	mbstring_globals->illegalchars = 0;
1555 	mbstring_globals->func_overload = 0;
1556 	mbstring_globals->encoding_translation = 0;
1557 	mbstring_globals->strict_detection = 0;
1558 	mbstring_globals->outconv = NULL;
1559 	mbstring_globals->http_output_conv_mimetypes = NULL;
1560 #if HAVE_MBREGEX
1561 	mbstring_globals->mb_regex_globals = php_mb_regex_globals_alloc();
1562 #endif
1563 	mbstring_globals->last_used_encoding_name = NULL;
1564 	mbstring_globals->last_used_encoding = NULL;
1565 	mbstring_globals->internal_encoding_set = 0;
1566 	mbstring_globals->http_output_set = 0;
1567 	mbstring_globals->http_input_set = 0;
1568 }
1569 /* }}} */
1570 
1571 /* {{{ PHP_GSHUTDOWN_FUNCTION */
PHP_GSHUTDOWN_FUNCTION(mbstring)1572 static PHP_GSHUTDOWN_FUNCTION(mbstring)
1573 {
1574 	if (mbstring_globals->http_input_list) {
1575 		free(mbstring_globals->http_input_list);
1576 	}
1577 	if (mbstring_globals->detect_order_list) {
1578 		free(mbstring_globals->detect_order_list);
1579 	}
1580 	if (mbstring_globals->http_output_conv_mimetypes) {
1581 		_php_mb_free_regex(mbstring_globals->http_output_conv_mimetypes);
1582 	}
1583 #if HAVE_MBREGEX
1584 	php_mb_regex_globals_free(mbstring_globals->mb_regex_globals);
1585 #endif
1586 }
1587 /* }}} */
1588 
1589 /* {{{ PHP_MINIT_FUNCTION(mbstring) */
PHP_MINIT_FUNCTION(mbstring)1590 PHP_MINIT_FUNCTION(mbstring)
1591 {
1592 #if defined(COMPILE_DL_MBSTRING) && defined(ZTS)
1593 ZEND_TSRMLS_CACHE_UPDATE();
1594 #endif
1595 	__mbfl_allocators = (mbfl_allocators*)&_php_mb_allocators;
1596 
1597 	REGISTER_INI_ENTRIES();
1598 
1599 	/* We assume that we're the only user of the hook. */
1600 	ZEND_ASSERT(php_internal_encoding_changed == NULL);
1601 	php_internal_encoding_changed = mbstring_internal_encoding_changed_hook;
1602 	mbstring_internal_encoding_changed_hook();
1603 
1604 	/* This is a global handler. Should not be set in a per-request handler. */
1605 	sapi_register_treat_data(mbstr_treat_data);
1606 
1607 	/* Post handlers are stored in the thread-local context. */
1608 	if (MBSTRG(encoding_translation)) {
1609 		sapi_register_post_entries(mbstr_post_entries);
1610 	}
1611 
1612 	REGISTER_LONG_CONSTANT("MB_OVERLOAD_MAIL", MB_OVERLOAD_MAIL, CONST_CS | CONST_PERSISTENT);
1613 	REGISTER_LONG_CONSTANT("MB_OVERLOAD_STRING", MB_OVERLOAD_STRING, CONST_CS | CONST_PERSISTENT);
1614 	REGISTER_LONG_CONSTANT("MB_OVERLOAD_REGEX", MB_OVERLOAD_REGEX, CONST_CS | CONST_PERSISTENT);
1615 
1616 	REGISTER_LONG_CONSTANT("MB_CASE_UPPER", PHP_UNICODE_CASE_UPPER, CONST_CS | CONST_PERSISTENT);
1617 	REGISTER_LONG_CONSTANT("MB_CASE_LOWER", PHP_UNICODE_CASE_LOWER, CONST_CS | CONST_PERSISTENT);
1618 	REGISTER_LONG_CONSTANT("MB_CASE_TITLE", PHP_UNICODE_CASE_TITLE, CONST_CS | CONST_PERSISTENT);
1619 	REGISTER_LONG_CONSTANT("MB_CASE_FOLD", PHP_UNICODE_CASE_FOLD, CONST_CS | CONST_PERSISTENT);
1620 	REGISTER_LONG_CONSTANT("MB_CASE_UPPER_SIMPLE", PHP_UNICODE_CASE_UPPER_SIMPLE, CONST_CS | CONST_PERSISTENT);
1621 	REGISTER_LONG_CONSTANT("MB_CASE_LOWER_SIMPLE", PHP_UNICODE_CASE_LOWER_SIMPLE, CONST_CS | CONST_PERSISTENT);
1622 	REGISTER_LONG_CONSTANT("MB_CASE_TITLE_SIMPLE", PHP_UNICODE_CASE_TITLE_SIMPLE, CONST_CS | CONST_PERSISTENT);
1623 	REGISTER_LONG_CONSTANT("MB_CASE_FOLD_SIMPLE", PHP_UNICODE_CASE_FOLD_SIMPLE, CONST_CS | CONST_PERSISTENT);
1624 
1625 #if HAVE_MBREGEX
1626 	PHP_MINIT(mb_regex) (INIT_FUNC_ARGS_PASSTHRU);
1627 #endif
1628 
1629 	if (FAILURE == zend_multibyte_set_functions(&php_mb_zend_multibyte_functions)) {
1630 		return FAILURE;
1631 	}
1632 
1633 	php_rfc1867_set_multibyte_callbacks(
1634 		php_mb_encoding_translation,
1635 		php_mb_gpc_get_detect_order,
1636 		php_mb_gpc_set_input_encoding,
1637 		php_mb_rfc1867_getword,
1638 		php_mb_rfc1867_getword_conf,
1639 		php_mb_rfc1867_basename);
1640 
1641 	/* override original function (deprecated). */
1642 	if (MBSTRG(func_overload)){
1643 		zend_function *func, *orig;
1644 		const struct mb_overload_def *p;
1645 		zend_string *str;
1646 
1647 		p = &(mb_ovld[0]);
1648 		while (p->type > 0) {
1649 			if ((MBSTRG(func_overload) & p->type) == p->type &&
1650 				!zend_hash_str_exists(CG(function_table), p->save_func, strlen(p->save_func))
1651 			) {
1652 				func = zend_hash_str_find_ptr(CG(function_table), p->ovld_func, strlen(p->ovld_func));
1653 
1654 				if ((orig = zend_hash_str_find_ptr(CG(function_table), p->orig_func, strlen(p->orig_func))) == NULL) {
1655 					php_error_docref("ref.mbstring", E_WARNING, "mbstring couldn't find function %s.", p->orig_func);
1656 					return FAILURE;
1657 				} else {
1658 					ZEND_ASSERT(orig->type == ZEND_INTERNAL_FUNCTION);
1659 					str = zend_string_init_interned(p->save_func, strlen(p->save_func), 1);
1660 					zend_hash_add_mem(CG(function_table), str, orig, sizeof(zend_internal_function));
1661 					zend_string_release_ex(str, 1);
1662 					function_add_ref(orig);
1663 
1664 					str = zend_string_init_interned(p->orig_func, strlen(p->orig_func), 1);
1665 					zend_hash_update_mem(CG(function_table), str, func, sizeof(zend_internal_function));
1666 					zend_string_release_ex(str, 1);
1667 					function_add_ref(func);
1668 				}
1669 			}
1670 			p++;
1671 		}
1672 	}
1673 
1674 	return SUCCESS;
1675 }
1676 /* }}} */
1677 
1678 /* {{{ PHP_MSHUTDOWN_FUNCTION(mbstring) */
PHP_MSHUTDOWN_FUNCTION(mbstring)1679 PHP_MSHUTDOWN_FUNCTION(mbstring)
1680 {
1681 	/*  clear overloaded function. */
1682 	if (MBSTRG(func_overload)){
1683 		const struct mb_overload_def *p;
1684 		zend_function *orig;
1685 
1686 		p = &(mb_ovld[0]);
1687 		while (p->type > 0) {
1688 			if ((MBSTRG(func_overload) & p->type) == p->type &&
1689 				(orig = zend_hash_str_find_ptr(CG(function_table), p->save_func, strlen(p->save_func)))) {
1690 
1691 				zend_hash_str_update_mem(CG(function_table), p->orig_func, strlen(p->orig_func), orig, sizeof(zend_internal_function));
1692 				function_add_ref(orig);
1693 				zend_hash_str_del(CG(function_table), p->save_func, strlen(p->save_func));
1694 			}
1695 			p++;
1696 		}
1697 	}
1698 
1699 	UNREGISTER_INI_ENTRIES();
1700 
1701 	zend_multibyte_restore_functions();
1702 
1703 #if HAVE_MBREGEX
1704 	PHP_MSHUTDOWN(mb_regex) (INIT_FUNC_ARGS_PASSTHRU);
1705 #endif
1706 
1707 	php_internal_encoding_changed = NULL;
1708 
1709 	return SUCCESS;
1710 }
1711 /* }}} */
1712 
1713 /* {{{ PHP_RINIT_FUNCTION(mbstring) */
PHP_RINIT_FUNCTION(mbstring)1714 PHP_RINIT_FUNCTION(mbstring)
1715 {
1716 	MBSTRG(current_internal_encoding) = MBSTRG(internal_encoding);
1717 	MBSTRG(current_http_output_encoding) = MBSTRG(http_output_encoding);
1718 	MBSTRG(current_filter_illegal_mode) = MBSTRG(filter_illegal_mode);
1719 	MBSTRG(current_filter_illegal_substchar) = MBSTRG(filter_illegal_substchar);
1720 
1721 	MBSTRG(illegalchars) = 0;
1722 
1723 	php_mb_populate_current_detect_order_list();
1724 
1725 	/* override original function. */
1726 	if (MBSTRG(func_overload)){
1727 		zend_error(E_DEPRECATED, "The mbstring.func_overload directive is deprecated");
1728 
1729 		CG(compiler_options) |= ZEND_COMPILE_NO_BUILTIN_STRLEN;
1730 	}
1731 #if HAVE_MBREGEX
1732 	PHP_RINIT(mb_regex) (INIT_FUNC_ARGS_PASSTHRU);
1733 #endif
1734 	zend_multibyte_set_internal_encoding((const zend_encoding *)MBSTRG(internal_encoding));
1735 
1736 	return SUCCESS;
1737 }
1738 /* }}} */
1739 
1740 /* {{{ PHP_RSHUTDOWN_FUNCTION(mbstring) */
PHP_RSHUTDOWN_FUNCTION(mbstring)1741 PHP_RSHUTDOWN_FUNCTION(mbstring)
1742 {
1743 	if (MBSTRG(current_detect_order_list) != NULL) {
1744 		efree(MBSTRG(current_detect_order_list));
1745 		MBSTRG(current_detect_order_list) = NULL;
1746 		MBSTRG(current_detect_order_list_size) = 0;
1747 	}
1748 	if (MBSTRG(outconv) != NULL) {
1749 		MBSTRG(illegalchars) += mbfl_buffer_illegalchars(MBSTRG(outconv));
1750 		mbfl_buffer_converter_delete(MBSTRG(outconv));
1751 		MBSTRG(outconv) = NULL;
1752 	}
1753 
1754 	/* clear http input identification. */
1755 	MBSTRG(http_input_identify) = NULL;
1756 	MBSTRG(http_input_identify_post) = NULL;
1757 	MBSTRG(http_input_identify_get) = NULL;
1758 	MBSTRG(http_input_identify_cookie) = NULL;
1759 	MBSTRG(http_input_identify_string) = NULL;
1760 
1761 	if (MBSTRG(last_used_encoding_name)) {
1762 		zend_string_release(MBSTRG(last_used_encoding_name));
1763 		MBSTRG(last_used_encoding_name) = NULL;
1764 	}
1765 
1766 	MBSTRG(internal_encoding_set) = 0;
1767 	MBSTRG(http_output_set) = 0;
1768 	MBSTRG(http_input_set) = 0;
1769 
1770 #if HAVE_MBREGEX
1771 	PHP_RSHUTDOWN(mb_regex) (INIT_FUNC_ARGS_PASSTHRU);
1772 #endif
1773 
1774 	return SUCCESS;
1775 }
1776 /* }}} */
1777 
1778 /* {{{ PHP_MINFO_FUNCTION(mbstring) */
PHP_MINFO_FUNCTION(mbstring)1779 PHP_MINFO_FUNCTION(mbstring)
1780 {
1781 	php_info_print_table_start();
1782 	php_info_print_table_row(2, "Multibyte Support", "enabled");
1783 	php_info_print_table_row(2, "Multibyte string engine", "libmbfl");
1784 	php_info_print_table_row(2, "HTTP input encoding translation", MBSTRG(encoding_translation) ? "enabled": "disabled");
1785 	{
1786 		char tmp[256];
1787 		snprintf(tmp, sizeof(tmp), "%d.%d.%d", MBFL_VERSION_MAJOR, MBFL_VERSION_MINOR, MBFL_VERSION_TEENY);
1788 		php_info_print_table_row(2, "libmbfl version", tmp);
1789 	}
1790 	php_info_print_table_end();
1791 
1792 	php_info_print_table_start();
1793 	php_info_print_table_header(1, "mbstring extension makes use of \"streamable kanji code filter and converter\", which is distributed under the GNU Lesser General Public License version 2.1.");
1794 	php_info_print_table_end();
1795 
1796 #if HAVE_MBREGEX
1797 	PHP_MINFO(mb_regex)(ZEND_MODULE_INFO_FUNC_ARGS_PASSTHRU);
1798 #endif
1799 
1800 	DISPLAY_INI_ENTRIES();
1801 }
1802 /* }}} */
1803 
1804 /* {{{ proto string mb_language([string language])
1805    Sets the current language or Returns the current language as a string */
PHP_FUNCTION(mb_language)1806 PHP_FUNCTION(mb_language)
1807 {
1808 	zend_string *name = NULL;
1809 
1810 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|S", &name) == FAILURE) {
1811 		return;
1812 	}
1813 	if (name == NULL) {
1814 		RETVAL_STRING((char *)mbfl_no_language2name(MBSTRG(language)));
1815 	} else {
1816 		zend_string *ini_name = zend_string_init("mbstring.language", sizeof("mbstring.language") - 1, 0);
1817 		if (FAILURE == zend_alter_ini_entry(ini_name, name, PHP_INI_USER, PHP_INI_STAGE_RUNTIME)) {
1818 			php_error_docref(NULL, E_WARNING, "Unknown language \"%s\"", ZSTR_VAL(name));
1819 			RETVAL_FALSE;
1820 		} else {
1821 			RETVAL_TRUE;
1822 		}
1823 		zend_string_release_ex(ini_name, 0);
1824 	}
1825 }
1826 /* }}} */
1827 
1828 /* {{{ proto string mb_internal_encoding([string encoding])
1829    Sets the current internal encoding or Returns the current internal encoding as a string */
PHP_FUNCTION(mb_internal_encoding)1830 PHP_FUNCTION(mb_internal_encoding)
1831 {
1832 	const char *name = NULL;
1833 	size_t name_len;
1834 	const mbfl_encoding *encoding;
1835 
1836 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|s", &name, &name_len) == FAILURE) {
1837 		return;
1838 	}
1839 	if (name == NULL) {
1840 		name = MBSTRG(current_internal_encoding) ? MBSTRG(current_internal_encoding)->name: NULL;
1841 		if (name != NULL) {
1842 			RETURN_STRING(name);
1843 		} else {
1844 			RETURN_FALSE;
1845 		}
1846 	} else {
1847 		encoding = mbfl_name2encoding(name);
1848 		if (!encoding) {
1849 			php_error_docref(NULL, E_WARNING, "Unknown encoding \"%s\"", name);
1850 			RETURN_FALSE;
1851 		} else {
1852 			MBSTRG(current_internal_encoding) = encoding;
1853 			MBSTRG(internal_encoding_set) = 1;
1854 			RETURN_TRUE;
1855 		}
1856 	}
1857 }
1858 /* }}} */
1859 
1860 /* {{{ proto mixed mb_http_input([string type])
1861    Returns the input encoding */
PHP_FUNCTION(mb_http_input)1862 PHP_FUNCTION(mb_http_input)
1863 {
1864 	char *typ = NULL;
1865 	size_t typ_len;
1866 	int retname;
1867 	char *list, *temp;
1868 	const mbfl_encoding *result = NULL;
1869 
1870 	retname = 1;
1871  	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|s", &typ, &typ_len) == FAILURE) {
1872 		return;
1873  	}
1874  	if (typ == NULL) {
1875  		result = MBSTRG(http_input_identify);
1876  	} else {
1877  		switch (*typ) {
1878 		case 'G':
1879 		case 'g':
1880 			result = MBSTRG(http_input_identify_get);
1881 			break;
1882 		case 'P':
1883 		case 'p':
1884 			result = MBSTRG(http_input_identify_post);
1885 			break;
1886 		case 'C':
1887 		case 'c':
1888 			result = MBSTRG(http_input_identify_cookie);
1889 			break;
1890 		case 'S':
1891 		case 's':
1892 			result = MBSTRG(http_input_identify_string);
1893 			break;
1894 		case 'I':
1895 		case 'i':
1896 			{
1897 				const mbfl_encoding **entry = MBSTRG(http_input_list);
1898 				const size_t n = MBSTRG(http_input_list_size);
1899 				size_t i;
1900 				array_init(return_value);
1901 				for (i = 0; i < n; i++) {
1902 					add_next_index_string(return_value, (*entry)->name);
1903 					entry++;
1904 				}
1905 				retname = 0;
1906 			}
1907 			break;
1908 		case 'L':
1909 		case 'l':
1910 			{
1911 				const mbfl_encoding **entry = MBSTRG(http_input_list);
1912 				const size_t n = MBSTRG(http_input_list_size);
1913 				size_t i;
1914 				list = NULL;
1915 				for (i = 0; i < n; i++) {
1916 					if (list) {
1917 						temp = list;
1918 						spprintf(&list, 0, "%s,%s", temp, (*entry)->name);
1919 						efree(temp);
1920 						if (!list) {
1921 							break;
1922 						}
1923 					} else {
1924 						list = estrdup((*entry)->name);
1925 					}
1926 					entry++;
1927 				}
1928 			}
1929 			if (!list) {
1930 				RETURN_FALSE;
1931 			}
1932 			RETVAL_STRING(list);
1933 			efree(list);
1934 			retname = 0;
1935 			break;
1936 		default:
1937 			result = MBSTRG(http_input_identify);
1938 			break;
1939 		}
1940 	}
1941 
1942 	if (retname) {
1943 		if (result) {
1944 			RETVAL_STRING(result->name);
1945 		} else {
1946 			RETVAL_FALSE;
1947 		}
1948 	}
1949 }
1950 /* }}} */
1951 
1952 /* {{{ proto string mb_http_output([string encoding])
1953    Sets the current output_encoding or returns the current output_encoding as a string */
PHP_FUNCTION(mb_http_output)1954 PHP_FUNCTION(mb_http_output)
1955 {
1956 	const char *name = NULL;
1957 	size_t name_len;
1958 	const mbfl_encoding *encoding;
1959 
1960 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|s", &name, &name_len) == FAILURE) {
1961 		return;
1962 	}
1963 
1964 	if (name == NULL) {
1965 		name = MBSTRG(current_http_output_encoding) ? MBSTRG(current_http_output_encoding)->name: NULL;
1966 		if (name != NULL) {
1967 			RETURN_STRING(name);
1968 		} else {
1969 			RETURN_FALSE;
1970 		}
1971 	} else {
1972 		encoding = mbfl_name2encoding(name);
1973 		if (!encoding) {
1974 			php_error_docref(NULL, E_WARNING, "Unknown encoding \"%s\"", name);
1975 			RETURN_FALSE;
1976 		} else {
1977 			MBSTRG(http_output_set) = 1;
1978 			MBSTRG(current_http_output_encoding) = encoding;
1979 			RETURN_TRUE;
1980 		}
1981 	}
1982 }
1983 /* }}} */
1984 
1985 /* {{{ proto bool|array mb_detect_order([mixed encoding-list])
1986    Sets the current detect_order or Return the current detect_order as a array */
PHP_FUNCTION(mb_detect_order)1987 PHP_FUNCTION(mb_detect_order)
1988 {
1989 	zval *arg1 = NULL;
1990 
1991 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|z", &arg1) == FAILURE) {
1992 		return;
1993 	}
1994 
1995 	if (!arg1) {
1996 		size_t i;
1997 		size_t n = MBSTRG(current_detect_order_list_size);
1998 		const mbfl_encoding **entry = MBSTRG(current_detect_order_list);
1999 		array_init(return_value);
2000 		for (i = 0; i < n; i++) {
2001 			add_next_index_string(return_value, (*entry)->name);
2002 			entry++;
2003 		}
2004 	} else {
2005 		const mbfl_encoding **list = NULL;
2006 		size_t size = 0;
2007 		switch (Z_TYPE_P(arg1)) {
2008 			case IS_ARRAY:
2009 				if (FAILURE == php_mb_parse_encoding_array(arg1, &list, &size, 0)) {
2010 					if (list) {
2011 						efree(list);
2012 					}
2013 					RETURN_FALSE;
2014 				}
2015 				break;
2016 			default:
2017 				if (!try_convert_to_string(arg1)) {
2018 					return;
2019 				}
2020 				if (FAILURE == php_mb_parse_encoding_list(Z_STRVAL_P(arg1), Z_STRLEN_P(arg1), &list, &size, 0)) {
2021 					if (list) {
2022 						efree(list);
2023 					}
2024 					RETURN_FALSE;
2025 				}
2026 				break;
2027 		}
2028 
2029 		if (list == NULL) {
2030 			RETURN_FALSE;
2031 		}
2032 
2033 		if (MBSTRG(current_detect_order_list)) {
2034 			efree(MBSTRG(current_detect_order_list));
2035 		}
2036 		MBSTRG(current_detect_order_list) = list;
2037 		MBSTRG(current_detect_order_list_size) = size;
2038 		RETURN_TRUE;
2039 	}
2040 }
2041 /* }}} */
2042 
php_mb_check_code_point(zend_long cp)2043 static inline int php_mb_check_code_point(zend_long cp)
2044 {
2045 	if (cp <= 0 || cp >= 0x110000) {
2046 		/* Out of Unicode range */
2047 		return 0;
2048 	}
2049 
2050 	if (cp >= 0xd800 && cp <= 0xdfff) {
2051 		/* Surrogate code-point. These are never valid on their own and we only allow a single
2052 		 * substitute character. */
2053 		return 0;
2054 	}
2055 
2056 	/* As the we do not know the target encoding of the conversion operation that is going to
2057 	 * use the substitution character, we cannot check whether the codepoint is actually mapped
2058 	 * in the given encoding at this point. Thus we have to accept everything. */
2059 	return 1;
2060 }
2061 
2062 /* {{{ proto mixed mb_substitute_character([mixed substchar])
2063    Sets the current substitute_character or returns the current substitute_character */
PHP_FUNCTION(mb_substitute_character)2064 PHP_FUNCTION(mb_substitute_character)
2065 {
2066 	zval *arg1 = NULL;
2067 
2068 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|z", &arg1) == FAILURE) {
2069 		return;
2070 	}
2071 
2072 	if (!arg1) {
2073 		if (MBSTRG(current_filter_illegal_mode) == MBFL_OUTPUTFILTER_ILLEGAL_MODE_NONE) {
2074 			RETURN_STRING("none");
2075 		} else if (MBSTRG(current_filter_illegal_mode) == MBFL_OUTPUTFILTER_ILLEGAL_MODE_LONG) {
2076 			RETURN_STRING("long");
2077 		} else if (MBSTRG(current_filter_illegal_mode) == MBFL_OUTPUTFILTER_ILLEGAL_MODE_ENTITY) {
2078 			RETURN_STRING("entity");
2079 		} else {
2080 			RETURN_LONG(MBSTRG(current_filter_illegal_substchar));
2081 		}
2082 	} else {
2083 		RETVAL_TRUE;
2084 
2085 		switch (Z_TYPE_P(arg1)) {
2086 			case IS_STRING:
2087 				if (strncasecmp("none", Z_STRVAL_P(arg1), Z_STRLEN_P(arg1)) == 0) {
2088 					MBSTRG(current_filter_illegal_mode) = MBFL_OUTPUTFILTER_ILLEGAL_MODE_NONE;
2089 				} else if (strncasecmp("long", Z_STRVAL_P(arg1), Z_STRLEN_P(arg1)) == 0) {
2090 					MBSTRG(current_filter_illegal_mode) = MBFL_OUTPUTFILTER_ILLEGAL_MODE_LONG;
2091 				} else if (strncasecmp("entity", Z_STRVAL_P(arg1), Z_STRLEN_P(arg1)) == 0) {
2092 					MBSTRG(current_filter_illegal_mode) = MBFL_OUTPUTFILTER_ILLEGAL_MODE_ENTITY;
2093 				} else {
2094 					convert_to_long_ex(arg1);
2095 
2096 					if (php_mb_check_code_point(Z_LVAL_P(arg1))) {
2097 						MBSTRG(current_filter_illegal_mode) = MBFL_OUTPUTFILTER_ILLEGAL_MODE_CHAR;
2098 						MBSTRG(current_filter_illegal_substchar) = Z_LVAL_P(arg1);
2099 					} else {
2100 						php_error_docref(NULL, E_WARNING, "Unknown character");
2101 						RETURN_FALSE;
2102 					}
2103 				}
2104 				break;
2105 			default:
2106 				convert_to_long_ex(arg1);
2107 				if (php_mb_check_code_point(Z_LVAL_P(arg1))) {
2108 					MBSTRG(current_filter_illegal_mode) = MBFL_OUTPUTFILTER_ILLEGAL_MODE_CHAR;
2109 					MBSTRG(current_filter_illegal_substchar) = Z_LVAL_P(arg1);
2110 				} else {
2111 					php_error_docref(NULL, E_WARNING, "Unknown character");
2112 					RETURN_FALSE;
2113 				}
2114 				break;
2115 		}
2116 	}
2117 }
2118 /* }}} */
2119 
2120 /* {{{ proto string mb_preferred_mime_name(string encoding)
2121    Return the preferred MIME name (charset) as a string */
PHP_FUNCTION(mb_preferred_mime_name)2122 PHP_FUNCTION(mb_preferred_mime_name)
2123 {
2124 	enum mbfl_no_encoding no_encoding;
2125 	char *name = NULL;
2126 	size_t name_len;
2127 
2128 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &name, &name_len) == FAILURE) {
2129 		return;
2130 	} else {
2131 		no_encoding = mbfl_name2no_encoding(name);
2132 		if (no_encoding == mbfl_no_encoding_invalid) {
2133 			php_error_docref(NULL, E_WARNING, "Unknown encoding \"%s\"", name);
2134 			RETVAL_FALSE;
2135 		} else {
2136 			const char *preferred_name = mbfl_no2preferred_mime_name(no_encoding);
2137 			if (preferred_name == NULL || *preferred_name == '\0') {
2138 				php_error_docref(NULL, E_WARNING, "No MIME preferred name corresponding to \"%s\"", name);
2139 				RETVAL_FALSE;
2140 			} else {
2141 				RETVAL_STRING((char *)preferred_name);
2142 			}
2143 		}
2144 	}
2145 }
2146 /* }}} */
2147 
2148 #define IS_SJIS1(c) ((((c)>=0x81 && (c)<=0x9f) || ((c)>=0xe0 && (c)<=0xf5)) ? 1 : 0)
2149 #define IS_SJIS2(c) ((((c)>=0x40 && (c)<=0x7e) || ((c)>=0x80 && (c)<=0xfc)) ? 1 : 0)
2150 
2151 /* {{{ proto bool mb_parse_str(string encoded_string [, array result])
2152    Parses GET/POST/COOKIE data and sets global variables */
PHP_FUNCTION(mb_parse_str)2153 PHP_FUNCTION(mb_parse_str)
2154 {
2155 	zval *track_vars_array = NULL;
2156 	char *encstr = NULL;
2157 	size_t encstr_len;
2158 	php_mb_encoding_handler_info_t info;
2159 	const mbfl_encoding *detected;
2160 
2161 	track_vars_array = NULL;
2162 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|z", &encstr, &encstr_len, &track_vars_array) == FAILURE) {
2163 		return;
2164 	}
2165 
2166 	if (track_vars_array != NULL) {
2167 		track_vars_array = zend_try_array_init(track_vars_array);
2168 		if (!track_vars_array) {
2169 			return;
2170 		}
2171 	}
2172 
2173 	encstr = estrndup(encstr, encstr_len);
2174 
2175 	info.data_type              = PARSE_STRING;
2176 	info.separator              = PG(arg_separator).input;
2177 	info.report_errors          = 1;
2178 	info.to_encoding            = MBSTRG(current_internal_encoding);
2179 	info.to_language            = MBSTRG(language);
2180 	info.from_encodings         = MBSTRG(http_input_list);
2181 	info.num_from_encodings     = MBSTRG(http_input_list_size);
2182 	info.from_language          = MBSTRG(language);
2183 
2184 	if (track_vars_array != NULL) {
2185 		detected = _php_mb_encoding_handler_ex(&info, track_vars_array, encstr);
2186 	} else {
2187 		zval tmp;
2188 		zend_array *symbol_table;
2189 		if (zend_forbid_dynamic_call("mb_parse_str() with a single argument") == FAILURE) {
2190 			efree(encstr);
2191 			return;
2192 		}
2193 
2194 		php_error_docref(NULL, E_DEPRECATED, "Calling mb_parse_str() without the result argument is deprecated");
2195 
2196 		symbol_table = zend_rebuild_symbol_table();
2197 		ZVAL_ARR(&tmp, symbol_table);
2198 		detected = _php_mb_encoding_handler_ex(&info, &tmp, encstr);
2199 	}
2200 
2201 	MBSTRG(http_input_identify) = detected;
2202 
2203 	RETVAL_BOOL(detected);
2204 
2205 	if (encstr != NULL) efree(encstr);
2206 }
2207 /* }}} */
2208 
2209 /* {{{ proto string mb_output_handler(string contents, int status)
2210    Returns string in output buffer converted to the http_output encoding */
PHP_FUNCTION(mb_output_handler)2211 PHP_FUNCTION(mb_output_handler)
2212 {
2213 	char *arg_string;
2214 	size_t arg_string_len;
2215 	zend_long arg_status;
2216 	mbfl_string string, result;
2217 	const char *charset;
2218 	char *p;
2219 	const mbfl_encoding *encoding;
2220 	int last_feed;
2221 	size_t len;
2222 	unsigned char send_text_mimetype = 0;
2223 	char *s, *mimetype = NULL;
2224 
2225 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "sl", &arg_string, &arg_string_len, &arg_status) == FAILURE) {
2226 		return;
2227 	}
2228 
2229 	encoding = MBSTRG(current_http_output_encoding);
2230 
2231  	/* start phase only */
2232  	if ((arg_status & PHP_OUTPUT_HANDLER_START) != 0) {
2233  		/* delete the converter just in case. */
2234  		if (MBSTRG(outconv)) {
2235 			MBSTRG(illegalchars) += mbfl_buffer_illegalchars(MBSTRG(outconv));
2236  			mbfl_buffer_converter_delete(MBSTRG(outconv));
2237  			MBSTRG(outconv) = NULL;
2238   		}
2239 		if (encoding == &mbfl_encoding_pass) {
2240 			RETURN_STRINGL(arg_string, arg_string_len);
2241 		}
2242 
2243 		/* analyze mime type */
2244 		if (SG(sapi_headers).mimetype &&
2245 			_php_mb_match_regex(
2246 				MBSTRG(http_output_conv_mimetypes),
2247 				SG(sapi_headers).mimetype,
2248 				strlen(SG(sapi_headers).mimetype))) {
2249 			if ((s = strchr(SG(sapi_headers).mimetype,';')) == NULL){
2250 				mimetype = estrdup(SG(sapi_headers).mimetype);
2251 			} else {
2252 				mimetype = estrndup(SG(sapi_headers).mimetype,s-SG(sapi_headers).mimetype);
2253 			}
2254 			send_text_mimetype = 1;
2255 		} else if (SG(sapi_headers).send_default_content_type) {
2256 			mimetype = SG(default_mimetype) ? SG(default_mimetype) : SAPI_DEFAULT_MIMETYPE;
2257 		}
2258 
2259  		/* if content-type is not yet set, set it and activate the converter */
2260  		if (SG(sapi_headers).send_default_content_type || send_text_mimetype) {
2261 			charset = encoding->mime_name;
2262 			if (charset) {
2263 				len = spprintf( &p, 0, "Content-Type: %s; charset=%s",  mimetype, charset );
2264 				if (sapi_add_header(p, len, 0) != FAILURE) {
2265 					SG(sapi_headers).send_default_content_type = 0;
2266 				}
2267 			}
2268  			/* activate the converter */
2269  			MBSTRG(outconv) = mbfl_buffer_converter_new(MBSTRG(current_internal_encoding), encoding, 0);
2270 			if (send_text_mimetype){
2271 				efree(mimetype);
2272 			}
2273  		}
2274   	}
2275 
2276  	/* just return if the converter is not activated. */
2277  	if (MBSTRG(outconv) == NULL) {
2278 		RETURN_STRINGL(arg_string, arg_string_len);
2279 	}
2280 
2281  	/* flag */
2282  	last_feed = ((arg_status & PHP_OUTPUT_HANDLER_END) != 0);
2283  	/* mode */
2284  	mbfl_buffer_converter_illegal_mode(MBSTRG(outconv), MBSTRG(current_filter_illegal_mode));
2285  	mbfl_buffer_converter_illegal_substchar(MBSTRG(outconv), MBSTRG(current_filter_illegal_substchar));
2286 
2287  	/* feed the string */
2288  	mbfl_string_init(&string);
2289 	/* these are not needed. convd has encoding info.
2290 	string.no_language = MBSTRG(language);
2291 	string.encoding = MBSTRG(current_internal_encoding);
2292 	*/
2293  	string.val = (unsigned char *)arg_string;
2294  	string.len = arg_string_len;
2295  	mbfl_buffer_converter_feed(MBSTRG(outconv), &string);
2296  	if (last_feed) {
2297  		mbfl_buffer_converter_flush(MBSTRG(outconv));
2298 	}
2299  	/* get the converter output, and return it */
2300  	mbfl_buffer_converter_result(MBSTRG(outconv), &result);
2301 	// TODO: avoid reallocation ???
2302  	RETVAL_STRINGL((char *)result.val, result.len);		/* the string is already strdup()'ed */
2303 	efree(result.val);
2304 
2305  	/* delete the converter if it is the last feed. */
2306  	if (last_feed) {
2307 		MBSTRG(illegalchars) += mbfl_buffer_illegalchars(MBSTRG(outconv));
2308 		mbfl_buffer_converter_delete(MBSTRG(outconv));
2309 		MBSTRG(outconv) = NULL;
2310 	}
2311 }
2312 /* }}} */
2313 
2314 /* {{{ proto array mb_str_split(string str [, int split_length] [, string encoding])
2315  Convert a multibyte string to an array. If split_length is specified,
2316  break the string down into chunks each split_length characters long. */
2317 
2318 /* structure to pass split params to the callback */
2319 struct mbfl_split_params {
2320     zval *return_value; /* php function return value structure pointer */
2321     mbfl_string *result_string; /* string to store result chunk */
2322     size_t mb_chunk_length; /* actual chunk length in chars */
2323     size_t split_length; /* split length in chars */
2324     mbfl_convert_filter *next_filter; /* widechar to encoding converter */
2325 };
2326 
2327 /* callback function to fill split array */
mbfl_split_output(int c,void * data)2328 static int mbfl_split_output(int c, void *data)
2329 {
2330     struct mbfl_split_params *params = (struct mbfl_split_params *)data; /* cast passed data */
2331 
2332     (*params->next_filter->filter_function)(c, params->next_filter); /* decoder filter */
2333 
2334     if(params->split_length == ++params->mb_chunk_length) { /* if current chunk size reached defined chunk size or last char reached */
2335         mbfl_convert_filter_flush(params->next_filter);/* concatenate separate decoded chars to the solid string */
2336         mbfl_memory_device *device = (mbfl_memory_device *)params->next_filter->data; /* chars container */
2337         mbfl_string *chunk = params->result_string;
2338         mbfl_memory_device_result(device, chunk); /* make chunk */
2339         add_next_index_stringl(params->return_value, (const char *)chunk->val, chunk->len); /* add chunk to the array */
2340         efree(chunk->val);
2341         params->mb_chunk_length = 0; /* reset mb_chunk size */
2342     }
2343     return 0;
2344 }
2345 
PHP_FUNCTION(mb_str_split)2346 PHP_FUNCTION(mb_str_split)
2347 {
2348 	zend_string *str, *encoding = NULL;
2349 	size_t mb_len, chunks, chunk_len;
2350 	const char *p, *last; /* pointer for the string cursor and last string char */
2351 	mbfl_string string, result_string;
2352 	const mbfl_encoding *mbfl_encoding;
2353 	zend_long split_length = 1;
2354 
2355 	ZEND_PARSE_PARAMETERS_START(1, 3)
2356 		Z_PARAM_STR(str)
2357 		Z_PARAM_OPTIONAL
2358 		Z_PARAM_LONG(split_length)
2359 		Z_PARAM_STR(encoding)
2360 	ZEND_PARSE_PARAMETERS_END();
2361 
2362 	if (split_length <= 0) {
2363 		php_error_docref(NULL, E_WARNING, "The length of each segment must be greater than zero");
2364 		RETURN_FALSE;
2365 	}
2366 
2367 	/* fill mbfl_string structure */
2368 	string.val = (unsigned char *) ZSTR_VAL(str);
2369 	string.len = ZSTR_LEN(str);
2370 	string.no_language = MBSTRG(language);
2371 	string.encoding = php_mb_get_encoding(encoding);
2372 	if (!string.encoding) {
2373 		RETURN_FALSE;
2374 	}
2375 
2376 	p = ZSTR_VAL(str); /* string cursor pointer */
2377 	last = ZSTR_VAL(str) + ZSTR_LEN(str); /* last string char pointer */
2378 
2379 	mbfl_encoding = string.encoding;
2380 
2381 	/* first scenario: 1,2,4-bytes fixed width encodings (head part) */
2382 	if (mbfl_encoding->flag & MBFL_ENCTYPE_SBCS) { /* 1 byte */
2383 		mb_len = string.len;
2384 		chunk_len = (size_t)split_length; /* chunk length in bytes */
2385 	} else if (mbfl_encoding->flag & (MBFL_ENCTYPE_WCS2BE | MBFL_ENCTYPE_WCS2LE)) { /* 2 bytes */
2386 		mb_len = string.len / 2;
2387 		chunk_len = split_length * 2;
2388 	} else if (mbfl_encoding->flag & (MBFL_ENCTYPE_WCS4BE | MBFL_ENCTYPE_WCS4LE)) { /* 4 bytes */
2389 		mb_len = string.len / 4;
2390 		chunk_len = split_length * 4;
2391 	} else if (mbfl_encoding->mblen_table != NULL) {
2392 		/* second scenario: variable width encodings with length table */
2393 		char unsigned const *mbtab = mbfl_encoding->mblen_table;
2394 
2395 		/* assume that we have 1-bytes characters */
2396 		array_init_size(return_value, (string.len + split_length) / split_length); /* round up */
2397 
2398 		while (p < last) { /* split cycle work until the cursor has reached the last byte */
2399 			char const *chunk_p = p; /* chunk first byte pointer */
2400 			chunk_len = 0; /* chunk length in bytes */
2401 			zend_long char_count;
2402 
2403 			for (char_count = 0; char_count < split_length && p < last; ++char_count) {
2404 				char unsigned const m = mbtab[*(const unsigned char *)p]; /* single character length table */
2405 				chunk_len += m;
2406 				p += m;
2407 			}
2408 			if (p >= last) chunk_len -= p - last; /* check if chunk is in bounds */
2409 			add_next_index_stringl(return_value, chunk_p, chunk_len);
2410 		}
2411 		return;
2412 	} else {
2413 		/* third scenario: other multibyte encodings */
2414 		mbfl_convert_filter *filter, *decoder;
2415 
2416 		/* assume that we have 1-bytes characters */
2417 		array_init_size(return_value, (string.len + split_length) / split_length); /* round up */
2418 
2419 		/* decoder filter to decode wchar to encoding */
2420 		mbfl_memory_device device;
2421 		mbfl_memory_device_init(&device, split_length + 1, 0);
2422 
2423 		decoder = mbfl_convert_filter_new(
2424 				&mbfl_encoding_wchar,
2425 				string.encoding,
2426 				mbfl_memory_device_output,
2427 				NULL,
2428 				&device);
2429 		/* if something wrong with the decoded */
2430 		if (decoder == NULL) {
2431 			RETURN_FALSE;
2432 		}
2433 
2434 		/* wchar filter */
2435 		mbfl_string_init(&result_string); /* mbfl_string to store chunk in the callback */
2436 		struct mbfl_split_params params = { /* init callback function params structure */
2437 			.return_value = return_value,
2438 			.result_string = &result_string,
2439 			.mb_chunk_length = 0,
2440 			.split_length = (size_t)split_length,
2441 			.next_filter = decoder,
2442 		};
2443 
2444 		filter = mbfl_convert_filter_new(
2445 				string.encoding,
2446 				&mbfl_encoding_wchar,
2447 				mbfl_split_output,
2448 				NULL,
2449 				&params);
2450 		/* if something wrong with the filter */
2451 		if (filter == NULL){
2452 			mbfl_convert_filter_delete(decoder); /* this will free allocated memory for the decoded */
2453 			RETURN_FALSE;
2454 		}
2455 
2456 		while (p < last - 1) { /* cycle each byte except last with callback function */
2457 			(*filter->filter_function)(*p++, filter);
2458 		}
2459 		params.mb_chunk_length = split_length - 1; /* force to finish current chunk */
2460 		(*filter->filter_function)(*p++, filter); /*process last char */
2461 
2462 		mbfl_convert_filter_delete(decoder);
2463 		mbfl_convert_filter_delete(filter);
2464 		mbfl_memory_device_clear(&device);
2465 		return;
2466 	}
2467 
2468 	/* first scenario: 1,2,4-bytes fixed width encodings (tail part) */
2469 	chunks = (mb_len + split_length - 1) / split_length; /* (round up idiom) */
2470 	array_init_size(return_value, chunks);
2471 	if (chunks != 0) {
2472 		zend_long i;
2473 
2474 		for (i = 0; i < chunks - 1; p += chunk_len, ++i) {
2475 			add_next_index_stringl(return_value, p, chunk_len);
2476 		}
2477 		add_next_index_stringl(return_value, p, last - p);
2478 	}
2479 }
2480 /* }}} */
2481 
2482 /* {{{ proto int mb_strlen(string str [, string encoding])
2483    Get character numbers of a string */
PHP_FUNCTION(mb_strlen)2484 PHP_FUNCTION(mb_strlen)
2485 {
2486 	size_t n;
2487 	mbfl_string string;
2488 	char *str;
2489 	size_t str_len;
2490 	zend_string *enc_name = NULL;
2491 
2492 	ZEND_PARSE_PARAMETERS_START(1, 2)
2493 		Z_PARAM_STRING(str, str_len)
2494 		Z_PARAM_OPTIONAL
2495 		Z_PARAM_STR(enc_name)
2496 	ZEND_PARSE_PARAMETERS_END();
2497 
2498 	string.val = (unsigned char *) str;
2499 	string.len = str_len;
2500 	string.no_language = MBSTRG(language);
2501 	string.encoding = php_mb_get_encoding(enc_name);
2502 	if (!string.encoding) {
2503 		RETURN_FALSE;
2504 	}
2505 
2506 	n = mbfl_strlen(&string);
2507 	if (!mbfl_is_error(n)) {
2508 		RETVAL_LONG(n);
2509 	} else {
2510 		RETVAL_FALSE;
2511 	}
2512 }
2513 /* }}} */
2514 
2515 /* {{{ proto int mb_strpos(string haystack, string needle [, int offset [, string encoding]])
2516    Find position of first occurrence of a string within another */
PHP_FUNCTION(mb_strpos)2517 PHP_FUNCTION(mb_strpos)
2518 {
2519 	int reverse = 0;
2520 	zend_long offset = 0;
2521 	mbfl_string haystack, needle;
2522 	zend_string *enc_name = NULL;
2523 	size_t n;
2524 
2525 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "ss|lS", (char **)&haystack.val, &haystack.len, (char **)&needle.val, &needle.len, &offset, &enc_name) == FAILURE) {
2526 		return;
2527 	}
2528 
2529 	haystack.no_language = needle.no_language = MBSTRG(language);
2530 	haystack.encoding = needle.encoding = php_mb_get_encoding(enc_name);
2531 	if (!haystack.encoding) {
2532 		RETURN_FALSE;
2533 	}
2534 
2535 	if (offset != 0) {
2536 		size_t slen = mbfl_strlen(&haystack);
2537 		if (offset < 0) {
2538 			offset += slen;
2539 		}
2540 		if (offset < 0 || offset > slen) {
2541 			php_error_docref(NULL, E_WARNING, "Offset not contained in string");
2542 			RETURN_FALSE;
2543 		}
2544 	}
2545 
2546 	if (needle.len == 0) {
2547 		php_error_docref(NULL, E_WARNING, "Empty delimiter");
2548 		RETURN_FALSE;
2549 	}
2550 
2551 	n = mbfl_strpos(&haystack, &needle, offset, reverse);
2552 	if (!mbfl_is_error(n)) {
2553 		RETVAL_LONG(n);
2554 	} else {
2555 		switch (-n) {
2556 		case 1:
2557 			break;
2558 		case 2:
2559 			php_error_docref(NULL, E_WARNING, "Needle has not positive length");
2560 			break;
2561 		case 4:
2562 			php_error_docref(NULL, E_WARNING, "Unknown encoding or conversion error");
2563 			break;
2564 		case 8:
2565 			php_error_docref(NULL, E_NOTICE, "Argument is empty");
2566 			break;
2567 		default:
2568 			php_error_docref(NULL, E_WARNING, "Unknown error in mb_strpos");
2569 			break;
2570 		}
2571 		RETVAL_FALSE;
2572 	}
2573 }
2574 /* }}} */
2575 
2576 /* {{{ proto int mb_strrpos(string haystack, string needle [, int offset [, string encoding]])
2577    Find position of last occurrence of a string within another */
PHP_FUNCTION(mb_strrpos)2578 PHP_FUNCTION(mb_strrpos)
2579 {
2580 	mbfl_string haystack, needle;
2581 	zend_string *enc_name = NULL;
2582 	zval *zoffset = NULL;
2583 	zend_long offset = 0, n;
2584 
2585 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "ss|zS", (char **)&haystack.val, &haystack.len, (char **)&needle.val, &needle.len, &zoffset, &enc_name) == FAILURE) {
2586 		return;
2587 	}
2588 
2589 	if (zoffset) {
2590 		if (Z_TYPE_P(zoffset) == IS_STRING) {
2591 			switch (Z_STRVAL_P(zoffset)[0]) {
2592 				case '0':
2593 				case '1':
2594 				case '2':
2595 				case '3':
2596 				case '4':
2597 				case '5':
2598 				case '6':
2599 				case '7':
2600 				case '8':
2601 				case '9':
2602 				case ' ':
2603 				case '-':
2604 				case '.':
2605 					convert_to_long_ex(zoffset);
2606 					offset = Z_LVAL_P(zoffset);
2607 					break;
2608 				default :
2609 					enc_name = Z_STR_P(zoffset);
2610 					php_error_docref(NULL, E_DEPRECATED,
2611 						"Passing the encoding as third parameter is deprecated. "
2612 						"Use an explicit zero offset");
2613 					break;
2614 			}
2615 		} else {
2616 			convert_to_long_ex(zoffset);
2617 			offset = Z_LVAL_P(zoffset);
2618 		}
2619 	}
2620 
2621 	haystack.no_language = needle.no_language = MBSTRG(language);
2622 	haystack.encoding = needle.encoding = php_mb_get_encoding(enc_name);
2623 	if (!haystack.encoding) {
2624 		RETURN_FALSE;
2625 	}
2626 
2627 	if (offset != 0) {
2628 		size_t haystack_char_len = mbfl_strlen(&haystack);
2629 		if ((offset > 0 && offset > haystack_char_len) ||
2630 			(offset < 0 && -offset > haystack_char_len)) {
2631 			php_error_docref(NULL, E_WARNING, "Offset is greater than the length of haystack string");
2632 			RETURN_FALSE;
2633 		}
2634 	}
2635 
2636 	n = mbfl_strpos(&haystack, &needle, offset, 1);
2637 	if (!mbfl_is_error(n)) {
2638 		RETVAL_LONG(n);
2639 	} else {
2640 		RETVAL_FALSE;
2641 	}
2642 }
2643 /* }}} */
2644 
2645 /* {{{ proto int mb_stripos(string haystack, string needle [, int offset [, string encoding]])
2646    Finds position of first occurrence of a string within another, case insensitive */
PHP_FUNCTION(mb_stripos)2647 PHP_FUNCTION(mb_stripos)
2648 {
2649 	size_t n = (size_t) -1;
2650 	zend_long offset = 0;
2651 	mbfl_string haystack, needle;
2652 	zend_string *from_encoding = NULL;
2653 
2654 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "ss|lS", (char **)&haystack.val, &haystack.len, (char **)&needle.val, &needle.len, &offset, &from_encoding) == FAILURE) {
2655 		return;
2656 	}
2657 
2658 	if (needle.len == 0) {
2659 		php_error_docref(NULL, E_WARNING, "Empty delimiter");
2660 		RETURN_FALSE;
2661 	}
2662 
2663 	n = php_mb_stripos(0, (char *)haystack.val, haystack.len, (char *)needle.val, needle.len, offset, from_encoding);
2664 
2665 	if (!mbfl_is_error(n)) {
2666 		RETVAL_LONG(n);
2667 	} else {
2668 		RETVAL_FALSE;
2669 	}
2670 }
2671 /* }}} */
2672 
2673 /* {{{ proto int mb_strripos(string haystack, string needle [, int offset [, string encoding]])
2674    Finds position of last occurrence of a string within another, case insensitive */
PHP_FUNCTION(mb_strripos)2675 PHP_FUNCTION(mb_strripos)
2676 {
2677 	size_t n = (size_t) -1;
2678 	zend_long offset = 0;
2679 	mbfl_string haystack, needle;
2680 	zend_string *from_encoding = NULL;
2681 
2682 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "ss|lS", (char **)&haystack.val, &haystack.len, (char **)&needle.val, &needle.len, &offset, &from_encoding) == FAILURE) {
2683 		return;
2684 	}
2685 
2686 	n = php_mb_stripos(1, (char *)haystack.val, haystack.len, (char *)needle.val, needle.len, offset, from_encoding);
2687 
2688 	if (!mbfl_is_error(n)) {
2689 		RETVAL_LONG(n);
2690 	} else {
2691 		RETVAL_FALSE;
2692 	}
2693 }
2694 /* }}} */
2695 
2696 /* {{{ proto string mb_strstr(string haystack, string needle[, bool part[, string encoding]])
2697    Finds first occurrence of a string within another */
PHP_FUNCTION(mb_strstr)2698 PHP_FUNCTION(mb_strstr)
2699 {
2700 	size_t n;
2701 	mbfl_string haystack, needle, result, *ret = NULL;
2702 	zend_string *enc_name = NULL;
2703 	zend_bool part = 0;
2704 
2705 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "ss|bS", (char **)&haystack.val, &haystack.len, (char **)&needle.val, &needle.len, &part, &enc_name) == FAILURE) {
2706 		return;
2707 	}
2708 
2709 	haystack.no_language = needle.no_language = MBSTRG(language);
2710 	haystack.encoding = needle.encoding = php_mb_get_encoding(enc_name);
2711 	if (!haystack.encoding) {
2712 		RETURN_FALSE;
2713 	}
2714 
2715 	if (needle.len == 0) {
2716 		php_error_docref(NULL, E_WARNING, "Empty delimiter");
2717 		RETURN_FALSE;
2718 	}
2719 
2720 	n = mbfl_strpos(&haystack, &needle, 0, 0);
2721 	if (!mbfl_is_error(n)) {
2722 		if (part) {
2723 			ret = mbfl_substr(&haystack, &result, 0, n);
2724 			if (ret != NULL) {
2725 				// TODO: avoid reallocation ???
2726 				RETVAL_STRINGL((char *)ret->val, ret->len);
2727 				efree(ret->val);
2728 			} else {
2729 				RETVAL_FALSE;
2730 			}
2731 		} else {
2732 			ret = mbfl_substr(&haystack, &result, n, MBFL_SUBSTR_UNTIL_END);
2733 			if (ret != NULL) {
2734 				// TODO: avoid reallocation ???
2735 				RETVAL_STRINGL((char *)ret->val, ret->len);
2736 				efree(ret->val);
2737 			} else {
2738 				RETVAL_FALSE;
2739 			}
2740 		}
2741 	} else {
2742 		RETVAL_FALSE;
2743 	}
2744 }
2745 /* }}} */
2746 
2747 /* {{{ proto string mb_strrchr(string haystack, string needle[, bool part[, string encoding]])
2748    Finds the last occurrence of a character in a string within another */
PHP_FUNCTION(mb_strrchr)2749 PHP_FUNCTION(mb_strrchr)
2750 {
2751 	size_t n;
2752 	mbfl_string haystack, needle, result, *ret = NULL;
2753 	zend_string *enc_name = NULL;
2754 	zend_bool part = 0;
2755 
2756 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "ss|bS", (char **)&haystack.val, &haystack.len, (char **)&needle.val, &needle.len, &part, &enc_name) == FAILURE) {
2757 		return;
2758 	}
2759 
2760 	haystack.no_language = needle.no_language = MBSTRG(language);
2761 	haystack.encoding = needle.encoding = php_mb_get_encoding(enc_name);
2762 	if (!haystack.encoding) {
2763 		RETURN_FALSE;
2764 	}
2765 
2766 	if (haystack.len == 0) {
2767 		RETURN_FALSE;
2768 	}
2769 	if (needle.len == 0) {
2770 		RETURN_FALSE;
2771 	}
2772 
2773 	n = mbfl_strpos(&haystack, &needle, 0, 1);
2774 	if (!mbfl_is_error(n)) {
2775 		if (part) {
2776 			ret = mbfl_substr(&haystack, &result, 0, n);
2777 			if (ret != NULL) {
2778 				// TODO: avoid reallocation ???
2779 				RETVAL_STRINGL((char *)ret->val, ret->len);
2780 				efree(ret->val);
2781 			} else {
2782 				RETVAL_FALSE;
2783 			}
2784 		} else {
2785 			ret = mbfl_substr(&haystack, &result, n, MBFL_SUBSTR_UNTIL_END);
2786 			if (ret != NULL) {
2787 				// TODO: avoid reallocation ???
2788 				RETVAL_STRINGL((char *)ret->val, ret->len);
2789 				efree(ret->val);
2790 			} else {
2791 				RETVAL_FALSE;
2792 			}
2793 		}
2794 	} else {
2795 		RETVAL_FALSE;
2796 	}
2797 }
2798 /* }}} */
2799 
2800 /* {{{ proto string mb_stristr(string haystack, string needle[, bool part[, string encoding]])
2801    Finds first occurrence of a string within another, case insensitive */
PHP_FUNCTION(mb_stristr)2802 PHP_FUNCTION(mb_stristr)
2803 {
2804 	zend_bool part = 0;
2805 	size_t n;
2806 	mbfl_string haystack, needle, result, *ret = NULL;
2807 	zend_string *from_encoding = NULL;
2808 
2809 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "ss|bS", (char **)&haystack.val, &haystack.len, (char **)&needle.val, &needle.len, &part, &from_encoding) == FAILURE) {
2810 		return;
2811 	}
2812 
2813 	haystack.no_language = needle.no_language = MBSTRG(language);
2814 	haystack.encoding = needle.encoding = php_mb_get_encoding(from_encoding);
2815 	if (!haystack.encoding) {
2816 		RETURN_FALSE;
2817 	}
2818 
2819 	if (!needle.len) {
2820 		php_error_docref(NULL, E_WARNING, "Empty delimiter");
2821 		RETURN_FALSE;
2822 	}
2823 
2824 	n = php_mb_stripos(0, (char *)haystack.val, haystack.len, (char *)needle.val, needle.len, 0, from_encoding);
2825 	if (mbfl_is_error(n)) {
2826 		RETURN_FALSE;
2827 	}
2828 
2829 	if (part) {
2830 		ret = mbfl_substr(&haystack, &result, 0, n);
2831 		if (ret != NULL) {
2832 			// TODO: avoid reallocation ???
2833 			RETVAL_STRINGL((char *)ret->val, ret->len);
2834 			efree(ret->val);
2835 		} else {
2836 			RETVAL_FALSE;
2837 		}
2838 	} else {
2839 		ret = mbfl_substr(&haystack, &result, n, MBFL_SUBSTR_UNTIL_END);
2840 		if (ret != NULL) {
2841 			// TODO: avoid reallocaton ???
2842 			RETVAL_STRINGL((char *)ret->val, ret->len);
2843 			efree(ret->val);
2844 		} else {
2845 			RETVAL_FALSE;
2846 		}
2847 	}
2848 }
2849 /* }}} */
2850 
2851 /* {{{ proto string mb_strrichr(string haystack, string needle[, bool part[, string encoding]])
2852    Finds the last occurrence of a character in a string within another, case insensitive */
PHP_FUNCTION(mb_strrichr)2853 PHP_FUNCTION(mb_strrichr)
2854 {
2855 	zend_bool part = 0;
2856 	size_t n;
2857 	mbfl_string haystack, needle, result, *ret = NULL;
2858 	zend_string *from_encoding = NULL;
2859 
2860 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "ss|bS", (char **)&haystack.val, &haystack.len, (char **)&needle.val, &needle.len, &part, &from_encoding) == FAILURE) {
2861 		return;
2862 	}
2863 
2864 	haystack.no_language = needle.no_language = MBSTRG(language);
2865 	haystack.encoding = needle.encoding = php_mb_get_encoding(from_encoding);
2866 	if (!haystack.encoding) {
2867 		RETURN_FALSE;
2868 	}
2869 
2870 	n = php_mb_stripos(1, (char *)haystack.val, haystack.len, (char *)needle.val, needle.len, 0, from_encoding);
2871 	if (mbfl_is_error(n)) {
2872 		RETURN_FALSE;
2873 	}
2874 
2875 	if (part) {
2876 		ret = mbfl_substr(&haystack, &result, 0, n);
2877 		if (ret != NULL) {
2878 			// TODO: avoid reallocation ???
2879 			RETVAL_STRINGL((char *)ret->val, ret->len);
2880 			efree(ret->val);
2881 		} else {
2882 			RETVAL_FALSE;
2883 		}
2884 	} else {
2885 		ret = mbfl_substr(&haystack, &result, n, MBFL_SUBSTR_UNTIL_END);
2886 		if (ret != NULL) {
2887 			// TODO: avoid reallocation ???
2888 			RETVAL_STRINGL((char *)ret->val, ret->len);
2889 			efree(ret->val);
2890 		} else {
2891 			RETVAL_FALSE;
2892 		}
2893 	}
2894 }
2895 /* }}} */
2896 
2897 /* {{{ proto int mb_substr_count(string haystack, string needle [, string encoding])
2898    Count the number of substring occurrences */
PHP_FUNCTION(mb_substr_count)2899 PHP_FUNCTION(mb_substr_count)
2900 {
2901 	size_t n;
2902 	mbfl_string haystack, needle;
2903 	zend_string *enc_name = NULL;
2904 
2905 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "ss|S", (char **)&haystack.val, &haystack.len, (char **)&needle.val, &needle.len, &enc_name) == FAILURE) {
2906 		return;
2907 	}
2908 
2909 	haystack.no_language = needle.no_language = MBSTRG(language);
2910 	haystack.encoding = needle.encoding = php_mb_get_encoding(enc_name);
2911 	if (!haystack.encoding) {
2912 		RETURN_FALSE;
2913 	}
2914 
2915 	if (needle.len == 0) {
2916 		php_error_docref(NULL, E_WARNING, "Empty substring");
2917 		RETURN_FALSE;
2918 	}
2919 
2920 	n = mbfl_substr_count(&haystack, &needle);
2921 	if (!mbfl_is_error(n)) {
2922 		RETVAL_LONG(n);
2923 	} else {
2924 		RETVAL_FALSE;
2925 	}
2926 }
2927 /* }}} */
2928 
2929 /* {{{ proto string mb_substr(string str, int start [, int length [, string encoding]])
2930    Returns part of a string */
PHP_FUNCTION(mb_substr)2931 PHP_FUNCTION(mb_substr)
2932 {
2933 	char *str;
2934 	zend_string *encoding = NULL;
2935 	zend_long from, len;
2936 	size_t mblen, real_from, real_len;
2937 	size_t str_len;
2938 	zend_bool len_is_null = 1;
2939 	mbfl_string string, result, *ret;
2940 
2941 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "sl|l!S", &str, &str_len, &from, &len, &len_is_null, &encoding) == FAILURE) {
2942 		return;
2943 	}
2944 
2945 	string.no_language = MBSTRG(language);
2946 	string.encoding = php_mb_get_encoding(encoding);
2947 	if (!string.encoding) {
2948 		RETURN_FALSE;
2949 	}
2950 
2951 	string.val = (unsigned char *)str;
2952 	string.len = str_len;
2953 
2954 	/* measures length */
2955 	mblen = 0;
2956 	if (from < 0 || (!len_is_null && len < 0)) {
2957 		mblen = mbfl_strlen(&string);
2958 	}
2959 
2960 	/* if "from" position is negative, count start position from the end
2961 	 * of the string
2962 	 */
2963 	if (from >= 0) {
2964 		real_from = (size_t) from;
2965 	} else if (-from < mblen) {
2966 		real_from = mblen + from;
2967 	} else {
2968 		real_from = 0;
2969 	}
2970 
2971 	/* if "length" position is negative, set it to the length
2972 	 * needed to stop that many chars from the end of the string
2973 	 */
2974 	if (len_is_null) {
2975 		real_len = MBFL_SUBSTR_UNTIL_END;
2976 	} else if (len >= 0) {
2977 		real_len = (size_t) len;
2978 	} else if (real_from < mblen && -len < mblen - real_from) {
2979 		real_len = (mblen - real_from) + len;
2980 	} else {
2981 		real_len = 0;
2982 	}
2983 
2984 	if (((MBSTRG(func_overload) & MB_OVERLOAD_STRING) == MB_OVERLOAD_STRING)
2985 		&& (real_from > mbfl_strlen(&string))) {
2986 		RETURN_FALSE;
2987 	}
2988 
2989 	ret = mbfl_substr(&string, &result, real_from, real_len);
2990 	if (NULL == ret) {
2991 		RETURN_FALSE;
2992 	}
2993 
2994 	// TODO: avoid reallocation ???
2995 	RETVAL_STRINGL((char *)ret->val, ret->len); /* the string is already strdup()'ed */
2996 	efree(ret->val);
2997 }
2998 /* }}} */
2999 
3000 /* {{{ proto string mb_strcut(string str, int start [, int length [, string encoding]])
3001    Returns part of a string */
PHP_FUNCTION(mb_strcut)3002 PHP_FUNCTION(mb_strcut)
3003 {
3004 	zend_string *encoding = NULL;
3005 	zend_long from, len;
3006 	zend_bool len_is_null = 1;
3007 	mbfl_string string, result, *ret;
3008 
3009 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "sl|l!S", (char **)&string.val, &string.len, &from, &len, &len_is_null, &encoding) == FAILURE) {
3010 		return;
3011 	}
3012 
3013 	string.no_language = MBSTRG(language);
3014 	string.encoding = php_mb_get_encoding(encoding);
3015 	if (!string.encoding) {
3016 		RETURN_FALSE;
3017 	}
3018 
3019 	if (len_is_null) {
3020 		len = string.len;
3021 	}
3022 
3023 	/* if "from" position is negative, count start position from the end
3024 	 * of the string
3025 	 */
3026 	if (from < 0) {
3027 		from = string.len + from;
3028 		if (from < 0) {
3029 			from = 0;
3030 		}
3031 	}
3032 
3033 	/* if "length" position is negative, set it to the length
3034 	 * needed to stop that many chars from the end of the string
3035 	 */
3036 	if (len < 0) {
3037 		len = (string.len - from) + len;
3038 		if (len < 0) {
3039 			len = 0;
3040 		}
3041 	}
3042 
3043 	if (from > string.len) {
3044 		RETURN_FALSE;
3045 	}
3046 
3047 	ret = mbfl_strcut(&string, &result, from, len);
3048 	if (ret == NULL) {
3049 		RETURN_FALSE;
3050 	}
3051 
3052 	// TODO: avoid reallocation ???
3053 	RETVAL_STRINGL((char *)ret->val, ret->len); /* the string is already strdup()'ed */
3054 	efree(ret->val);
3055 }
3056 /* }}} */
3057 
3058 /* {{{ proto int mb_strwidth(string str [, string encoding])
3059    Gets terminal width of a string */
PHP_FUNCTION(mb_strwidth)3060 PHP_FUNCTION(mb_strwidth)
3061 {
3062 	size_t n;
3063 	mbfl_string string;
3064 	zend_string *enc_name = NULL;
3065 
3066 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|S", (char **)&string.val, &string.len, &enc_name) == FAILURE) {
3067 		return;
3068 	}
3069 
3070 	string.no_language = MBSTRG(language);
3071 	string.encoding = php_mb_get_encoding(enc_name);
3072 	if (!string.encoding) {
3073 		RETURN_FALSE;
3074 	}
3075 
3076 	n = mbfl_strwidth(&string);
3077 	if (!mbfl_is_error(n)) {
3078 		RETVAL_LONG(n);
3079 	} else {
3080 		RETVAL_FALSE;
3081 	}
3082 }
3083 /* }}} */
3084 
3085 /* {{{ proto string mb_strimwidth(string str, int start, int width [, string trimmarker [, string encoding]])
3086    Trim the string in terminal width */
PHP_FUNCTION(mb_strimwidth)3087 PHP_FUNCTION(mb_strimwidth)
3088 {
3089 	char *str, *trimmarker = NULL;
3090 	zend_string *encoding = NULL;
3091 	zend_long from, width, swidth = 0;
3092 	size_t str_len, trimmarker_len;
3093 	mbfl_string string, result, marker, *ret;
3094 
3095 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "sll|sS", &str, &str_len, &from, &width, &trimmarker, &trimmarker_len, &encoding) == FAILURE) {
3096 		return;
3097 	}
3098 
3099 	string.no_language = marker.no_language = MBSTRG(language);
3100 	string.encoding = marker.encoding = php_mb_get_encoding(encoding);
3101 	if (!string.encoding) {
3102 		RETURN_FALSE;
3103 	}
3104 
3105 	string.val = (unsigned char *)str;
3106 	string.len = str_len;
3107 	marker.val = NULL;
3108 	marker.len = 0;
3109 
3110 	if ((from < 0) || (width < 0)) {
3111 		swidth = mbfl_strwidth(&string);
3112 	}
3113 
3114 	if (from < 0) {
3115 		from += swidth;
3116 	}
3117 
3118 	if (from < 0 || (size_t)from > str_len) {
3119 		php_error_docref(NULL, E_WARNING, "Start position is out of range");
3120 		RETURN_FALSE;
3121 	}
3122 
3123 	if (width < 0) {
3124 		width = swidth + width - from;
3125 	}
3126 
3127 	if (width < 0) {
3128 		php_error_docref(NULL, E_WARNING, "Width is out of range");
3129 		RETURN_FALSE;
3130 	}
3131 
3132 	if (trimmarker) {
3133 		marker.val = (unsigned char *)trimmarker;
3134 		marker.len = trimmarker_len;
3135 	}
3136 
3137 	ret = mbfl_strimwidth(&string, &marker, &result, from, width);
3138 
3139 	if (ret == NULL) {
3140 		RETURN_FALSE;
3141 	}
3142 	// TODO: avoid reallocation ???
3143 	RETVAL_STRINGL((char *)ret->val, ret->len); /* the string is already strdup()'ed */
3144 	efree(ret->val);
3145 }
3146 /* }}} */
3147 
3148 
3149 /* See mbfl_no_encoding definition for list of unsupported encodings */
php_mb_is_unsupported_no_encoding(enum mbfl_no_encoding no_enc)3150 static inline zend_bool php_mb_is_unsupported_no_encoding(enum mbfl_no_encoding no_enc)
3151 {
3152 	return ((no_enc >= mbfl_no_encoding_invalid && no_enc <= mbfl_no_encoding_qprint)
3153 			|| (no_enc >= mbfl_no_encoding_utf7 && no_enc <= mbfl_no_encoding_utf7imap)
3154 			|| (no_enc >= mbfl_no_encoding_jis && no_enc <= mbfl_no_encoding_2022jpms)
3155 			|| (no_enc >= mbfl_no_encoding_cp50220 && no_enc <= mbfl_no_encoding_cp50222));
3156 }
3157 
3158 
3159 /* See mbfl_no_encoding definition for list of UTF-8 encodings */
php_mb_is_no_encoding_utf8(enum mbfl_no_encoding no_enc)3160 static inline zend_bool php_mb_is_no_encoding_utf8(enum mbfl_no_encoding no_enc)
3161 {
3162 	return (no_enc >= mbfl_no_encoding_utf8 && no_enc <= mbfl_no_encoding_utf8_sb);
3163 }
3164 
php_mb_convert_encoding_ex(const char * input,size_t length,const mbfl_encoding * to_encoding,const mbfl_encoding * from_encoding,size_t * output_len)3165 MBSTRING_API char *php_mb_convert_encoding_ex(const char *input, size_t length, const mbfl_encoding *to_encoding, const mbfl_encoding *from_encoding, size_t *output_len)
3166 {
3167 	mbfl_string string, result, *ret;
3168 	mbfl_buffer_converter *convd;
3169 	char *output = NULL;
3170 
3171 	if (output_len) {
3172 		*output_len = 0;
3173 	}
3174 
3175 	/* initialize string */
3176 	string.encoding = from_encoding;
3177 	string.no_language = MBSTRG(language);
3178 	string.val = (unsigned char *)input;
3179 	string.len = length;
3180 
3181 	/* initialize converter */
3182 	convd = mbfl_buffer_converter_new(from_encoding, to_encoding, string.len);
3183 	if (convd == NULL) {
3184 		php_error_docref(NULL, E_WARNING, "Unable to create character encoding converter");
3185 		return NULL;
3186 	}
3187 
3188 	mbfl_buffer_converter_illegal_mode(convd, MBSTRG(current_filter_illegal_mode));
3189 	mbfl_buffer_converter_illegal_substchar(convd, MBSTRG(current_filter_illegal_substchar));
3190 
3191 	/* do it */
3192 	mbfl_string_init(&result);
3193 	ret = mbfl_buffer_converter_feed_result(convd, &string, &result);
3194 	if (ret) {
3195 		if (output_len) {
3196 			*output_len = ret->len;
3197 		}
3198 		output = (char *)ret->val;
3199 	}
3200 
3201 	MBSTRG(illegalchars) += mbfl_buffer_illegalchars(convd);
3202 	mbfl_buffer_converter_delete(convd);
3203 	return output;
3204 }
3205 /* }}} */
3206 
3207 /* {{{ MBSTRING_API char *php_mb_convert_encoding() */
php_mb_convert_encoding(const char * input,size_t length,const char * _to_encoding,const char * _from_encodings,size_t * output_len)3208 MBSTRING_API char *php_mb_convert_encoding(const char *input, size_t length, const char *_to_encoding, const char *_from_encodings, size_t *output_len)
3209 {
3210 	const mbfl_encoding *from_encoding, *to_encoding;
3211 
3212 	if (output_len) {
3213 		*output_len = 0;
3214 	}
3215 	if (!input) {
3216 		return NULL;
3217 	}
3218 	/* new encoding */
3219 	if (_to_encoding && strlen(_to_encoding)) {
3220 		to_encoding = mbfl_name2encoding(_to_encoding);
3221 		if (!to_encoding) {
3222 			php_error_docref(NULL, E_WARNING, "Unknown encoding \"%s\"", _to_encoding);
3223 			return NULL;
3224 		}
3225 	} else {
3226 		to_encoding = MBSTRG(current_internal_encoding);
3227 	}
3228 
3229 	/* pre-conversion encoding */
3230 	from_encoding = MBSTRG(current_internal_encoding);
3231 	if (_from_encodings) {
3232 		const mbfl_encoding **list = NULL;
3233 		size_t size = 0;
3234 		php_mb_parse_encoding_list(_from_encodings, strlen(_from_encodings), &list, &size, 0);
3235 		if (size == 1) {
3236 			from_encoding = *list;
3237 		} else if (size > 1) {
3238 			/* auto detect */
3239 			mbfl_string string;
3240 			mbfl_string_init(&string);
3241 			string.val = (unsigned char *)input;
3242 			string.len = length;
3243 			from_encoding = mbfl_identify_encoding(&string, list, size, MBSTRG(strict_detection));
3244 			if (!from_encoding) {
3245 				php_error_docref(NULL, E_WARNING, "Unable to detect character encoding");
3246 				from_encoding = &mbfl_encoding_pass;
3247 			}
3248 		} else {
3249 			php_error_docref(NULL, E_WARNING, "Illegal character encoding specified");
3250 		}
3251 		if (