1/*
2   +----------------------------------------------------------------------+
3   | PHP Version 5                                                        |
4   +----------------------------------------------------------------------+
5   | This source file is subject to version 3.01 of the PHP license,      |
6   | that is bundled with this package in the file LICENSE, and is        |
7   | available through the world-wide-web at the following url:           |
8   | http://www.php.net/license/3_01.txt                                  |
9   | If you did not receive a copy of the PHP license and are unable to   |
10   | obtain it through the world-wide-web, please send a note to          |
11   | license@php.net so we can mail you a copy immediately.               |
12   +----------------------------------------------------------------------+
13   | Author: Ed Batutis <ed@batutis.com>                                  |
14   +----------------------------------------------------------------------+
15 */
16
17/* {{{ includes */
18#ifdef HAVE_CONFIG_H
19#include "config.h"
20#endif
21
22#include <php.h>
23#include "grapheme.h"
24#include "grapheme_util.h"
25
26#include <unicode/utypes.h>
27#include <unicode/ucol.h>
28#include <unicode/ustring.h>
29#include <unicode/ubrk.h>
30
31#include "ext/standard/php_string.h"
32
33/* }}} */
34
35#define GRAPHEME_EXTRACT_TYPE_COUNT     0
36#define GRAPHEME_EXTRACT_TYPE_MAXBYTES  1
37#define GRAPHEME_EXTRACT_TYPE_MAXCHARS  2
38#define GRAPHEME_EXTRACT_TYPE_MIN   GRAPHEME_EXTRACT_TYPE_COUNT
39#define GRAPHEME_EXTRACT_TYPE_MAX   GRAPHEME_EXTRACT_TYPE_MAXCHARS
40
41
42/* {{{ grapheme_register_constants
43 * Register API constants
44 */
45void grapheme_register_constants( INIT_FUNC_ARGS )
46{
47    REGISTER_LONG_CONSTANT("GRAPHEME_EXTR_COUNT", GRAPHEME_EXTRACT_TYPE_COUNT, CONST_CS | CONST_PERSISTENT);
48    REGISTER_LONG_CONSTANT("GRAPHEME_EXTR_MAXBYTES", GRAPHEME_EXTRACT_TYPE_MAXBYTES, CONST_CS | CONST_PERSISTENT);
49    REGISTER_LONG_CONSTANT("GRAPHEME_EXTR_MAXCHARS", GRAPHEME_EXTRACT_TYPE_MAXCHARS, CONST_CS | CONST_PERSISTENT);
50}
51/* }}} */
52
53/* {{{ proto size_t grapheme_strlen(string str)
54   Get number of graphemes in a string */
55PHP_FUNCTION(grapheme_strlen)
56{
57    unsigned char* string;
58    size_t string_len;
59    UChar* ustring = NULL;
60    int ustring_len = 0;
61    int ret_len;
62    UErrorCode status;
63
64    if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", (char **)&string, &string_len) == FAILURE) {
65
66        intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,
67             "grapheme_strlen: unable to parse input param", 0 );
68
69        RETURN_FALSE;
70    }
71
72    ret_len = grapheme_ascii_check(string, string_len);
73
74    if ( ret_len >= 0 )
75        RETURN_LONG(ret_len);
76
77    /* convert the string to UTF-16. */
78    status = U_ZERO_ERROR;
79    intl_convert_utf8_to_utf16(&ustring, &ustring_len, (char*) string, string_len, &status );
80
81    if ( U_FAILURE( status ) ) {
82        /* Set global error code. */
83        intl_error_set_code( NULL, status );
84
85        /* Set error messages. */
86        intl_error_set_custom_msg( NULL, "Error converting input string to UTF-16", 0 );
87        if (ustring) {
88            efree( ustring );
89        }
90        RETURN_NULL();
91    }
92
93    ret_len = grapheme_split_string(ustring, ustring_len, NULL, 0 );
94
95    if (ustring) {
96        efree( ustring );
97    }
98
99    if (ret_len >= 0) {
100        RETVAL_LONG(ret_len);
101    } else {
102        RETVAL_FALSE;
103    }
104}
105/* }}} */
106
107/* {{{ proto int grapheme_strpos(string haystack, string needle [, int offset ])
108   Find position of first occurrence of a string within another */
109PHP_FUNCTION(grapheme_strpos)
110{
111    unsigned char *haystack, *needle;
112    size_t haystack_len, needle_len;
113    unsigned char *found;
114    zend_long loffset = 0;
115    int32_t offset = 0;
116    int ret_pos;
117
118    if (zend_parse_parameters(ZEND_NUM_ARGS(), "ss|l", (char **)&haystack, &haystack_len, (char **)&needle, &needle_len, &loffset) == FAILURE) {
119
120        intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,
121             "grapheme_strpos: unable to parse input param", 0 );
122
123        RETURN_FALSE;
124    }
125
126    if ( OUTSIDE_STRING(loffset, haystack_len) ) {
127
128        intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "grapheme_strpos: Offset not contained in string", 1 );
129
130        RETURN_FALSE;
131    }
132
133    /* we checked that it will fit: */
134    offset = (int32_t) loffset;
135
136    /* the offset is 'grapheme count offset' so it still might be invalid - we'll check it later */
137
138    if (needle_len == 0) {
139
140        intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "grapheme_strpos: Empty delimiter", 1 );
141
142        RETURN_FALSE;
143    }
144
145
146    /* quick check to see if the string might be there
147     * I realize that 'offset' is 'grapheme count offset' but will work in spite of that
148    */
149    found = (unsigned char *)php_memnstr((char *)haystack + offset, (char *)needle, needle_len, (char *)haystack + haystack_len);
150
151    /* if it isn't there the we are done */
152    if (!found) {
153        RETURN_FALSE;
154    }
155
156    /* if it is there, and if the haystack is ascii, we are all done */
157    if ( grapheme_ascii_check(haystack, haystack_len) >= 0 ) {
158
159        RETURN_LONG(found - haystack);
160    }
161
162    /* do utf16 part of the strpos */
163    ret_pos = grapheme_strpos_utf16(haystack, haystack_len, needle, needle_len, offset, NULL, 0 /* fIgnoreCase */, 0 /* last */ );
164
165    if ( ret_pos >= 0 ) {
166        RETURN_LONG(ret_pos);
167    } else {
168        RETURN_FALSE;
169    }
170
171}
172/* }}} */
173
174/* {{{ proto int grapheme_stripos(string haystack, string needle [, int offset ])
175   Find position of first occurrence of a string within another, ignoring case differences */
176PHP_FUNCTION(grapheme_stripos)
177{
178    unsigned char *haystack, *needle, *haystack_dup, *needle_dup;
179    size_t haystack_len, needle_len;
180    unsigned char *found;
181    zend_long loffset = 0;
182    int32_t offset = 0;
183    int ret_pos;
184    int is_ascii;
185
186    if (zend_parse_parameters(ZEND_NUM_ARGS(), "ss|l", (char **)&haystack, &haystack_len, (char **)&needle, &needle_len, &loffset) == FAILURE) {
187
188        intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,
189             "grapheme_stripos: unable to parse input param", 0 );
190
191        RETURN_FALSE;
192    }
193
194    if ( OUTSIDE_STRING(loffset, haystack_len) ) {
195
196        intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "grapheme_stripos: Offset not contained in string", 1 );
197
198        RETURN_FALSE;
199    }
200
201    /* we checked that it will fit: */
202    offset = (int32_t) loffset;
203
204    /* the offset is 'grapheme count offset' so it still might be invalid - we'll check it later */
205
206    if (needle_len == 0) {
207
208        intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "grapheme_stripos: Empty delimiter", 1 );
209
210        RETURN_FALSE;
211    }
212
213
214    is_ascii = ( grapheme_ascii_check(haystack, haystack_len) >= 0 );
215
216    if ( is_ascii ) {
217        needle_dup = (unsigned char *)estrndup((char *)needle, needle_len);
218        php_strtolower((char *)needle_dup, needle_len);
219        haystack_dup = (unsigned char *)estrndup((char *)haystack, haystack_len);
220        php_strtolower((char *)haystack_dup, haystack_len);
221
222        found = (unsigned char*) php_memnstr((char *)haystack_dup + offset, (char *)needle_dup, needle_len, (char *)haystack_dup + haystack_len);
223
224        efree(haystack_dup);
225        efree(needle_dup);
226
227        if (found) {
228            RETURN_LONG(found - haystack_dup);
229        }
230
231        /* if needle was ascii too, we are all done, otherwise we need to try using Unicode to see what we get */
232        if ( grapheme_ascii_check(needle, needle_len) >= 0 ) {
233            RETURN_FALSE;
234        }
235    }
236
237    /* do utf16 part of the strpos */
238    ret_pos = grapheme_strpos_utf16(haystack, haystack_len, needle, needle_len, offset, NULL, 1 /* fIgnoreCase */, 0 /*last */ );
239
240    if ( ret_pos >= 0 ) {
241        RETURN_LONG(ret_pos);
242    } else {
243        RETURN_FALSE;
244    }
245
246}
247/* }}} */
248
249/* {{{ proto int grapheme_strrpos(string haystack, string needle [, int offset])
250   Find position of last occurrence of a string within another */
251PHP_FUNCTION(grapheme_strrpos)
252{
253    unsigned char *haystack, *needle;
254    size_t haystack_len, needle_len;
255    zend_long loffset = 0;
256    int32_t offset = 0;
257    int32_t ret_pos;
258    int is_ascii;
259
260    if (zend_parse_parameters(ZEND_NUM_ARGS(), "ss|l", (char **)&haystack, &haystack_len, (char **)&needle, &needle_len, &loffset) == FAILURE) {
261
262        intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,
263             "grapheme_strrpos: unable to parse input param", 0 );
264
265        RETURN_FALSE;
266    }
267
268    if ( OUTSIDE_STRING(loffset, haystack_len) ) {
269
270        intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "grapheme_strpos: Offset not contained in string", 1 );
271
272        RETURN_FALSE;
273    }
274
275    /* we checked that it will fit: */
276    offset = (int32_t) loffset;
277
278    /* the offset is 'grapheme count offset' so it still might be invalid - we'll check it later */
279
280    if (needle_len == 0) {
281
282        intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "grapheme_strpos: Empty delimiter", 1 );
283
284        RETURN_FALSE;
285    }
286
287    is_ascii = grapheme_ascii_check(haystack, haystack_len) >= 0;
288
289    if ( is_ascii ) {
290
291        ret_pos = grapheme_strrpos_ascii(haystack, haystack_len, needle, needle_len, offset);
292
293
294        if ( ret_pos >= 0 ) {
295            RETURN_LONG(ret_pos);
296        }
297
298        /* if the needle was ascii too, we are done */
299
300        if (  grapheme_ascii_check(needle, needle_len) >= 0 ) {
301            RETURN_FALSE;
302        }
303
304        /* else we need to continue via utf16 */
305    }
306
307    ret_pos = grapheme_strpos_utf16(haystack, haystack_len, needle, needle_len, offset, NULL, 0 /* f_ignore_case */, 1/* last */);
308
309    if ( ret_pos >= 0 ) {
310        RETURN_LONG(ret_pos);
311    } else {
312        RETURN_FALSE;
313    }
314
315
316}
317/* }}} */
318
319/* {{{ proto int grapheme_strripos(string haystack, string needle [, int offset])
320   Find position of last occurrence of a string within another, ignoring case */
321PHP_FUNCTION(grapheme_strripos)
322{
323    unsigned char *haystack, *needle;
324    size_t haystack_len, needle_len;
325    zend_long loffset = 0;
326    int32_t offset = 0;
327    int32_t ret_pos;
328    int is_ascii;
329
330    if (zend_parse_parameters(ZEND_NUM_ARGS(), "ss|l", (char **)&haystack, &haystack_len, (char **)&needle, &needle_len, &loffset) == FAILURE) {
331
332        intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,
333             "grapheme_strrpos: unable to parse input param", 0 );
334
335        RETURN_FALSE;
336    }
337
338    if ( OUTSIDE_STRING(loffset, haystack_len) ) {
339
340        intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "grapheme_strpos: Offset not contained in string", 1 );
341
342        RETURN_FALSE;
343    }
344
345    /* we checked that it will fit: */
346    offset = (int32_t) loffset;
347
348    /* the offset is 'grapheme count offset' so it still might be invalid - we'll check it later */
349
350    if (needle_len == 0) {
351
352        intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "grapheme_strpos: Empty delimiter", 1 );
353
354        RETURN_FALSE;
355    }
356
357    is_ascii = grapheme_ascii_check(haystack, haystack_len) >= 0;
358
359    if ( is_ascii ) {
360        unsigned char *needle_dup, *haystack_dup;
361
362        needle_dup = (unsigned char *)estrndup((char *)needle, needle_len);
363        php_strtolower((char *)needle_dup, needle_len);
364        haystack_dup = (unsigned char *)estrndup((char *)haystack, haystack_len);
365        php_strtolower((char *)haystack_dup, haystack_len);
366
367        ret_pos = grapheme_strrpos_ascii(haystack_dup, haystack_len, needle_dup, needle_len, offset);
368
369        efree(haystack_dup);
370        efree(needle_dup);
371
372        if ( ret_pos >= 0 ) {
373            RETURN_LONG(ret_pos);
374        }
375
376        /* if the needle was ascii too, we are done */
377
378        if (  grapheme_ascii_check(needle, needle_len) >= 0 ) {
379            RETURN_FALSE;
380        }
381
382        /* else we need to continue via utf16 */
383    }
384
385    ret_pos = grapheme_strpos_utf16(haystack, haystack_len, needle, needle_len, offset, NULL,  1 /* f_ignore_case */, 1 /*last */);
386
387    if ( ret_pos >= 0 ) {
388        RETURN_LONG(ret_pos);
389    } else {
390        RETURN_FALSE;
391    }
392
393
394}
395/* }}} */
396
397/* {{{ proto string grapheme_substr(string str, int start [, int length])
398   Returns part of a string */
399PHP_FUNCTION(grapheme_substr)
400{
401    unsigned char *str, *sub_str;
402    UChar *ustr;
403    size_t str_len;
404    int32_t ustr_len;
405    int32_t sub_str_len;
406    zend_long lstart = 0, length = 0;
407    int32_t start = 0;
408    int iter_val;
409    UErrorCode status;
410    unsigned char u_break_iterator_buffer[U_BRK_SAFECLONE_BUFFERSIZE];
411    UBreakIterator* bi = NULL;
412    int sub_str_start_pos, sub_str_end_pos;
413    int32_t (*iter_func)(UBreakIterator *);
414
415    if (zend_parse_parameters(ZEND_NUM_ARGS(), "sl|l", (char **)&str, &str_len, &lstart, &length) == FAILURE) {
416
417        intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,
418             "grapheme_substr: unable to parse input param", 0 );
419
420        RETURN_FALSE;
421    }
422
423    if ( OUTSIDE_STRING(lstart, str_len) ) {
424
425        intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "grapheme_substr: start not contained in string", 1 );
426
427        RETURN_FALSE;
428    }
429
430    /* we checked that it will fit: */
431    start = (int32_t) lstart;
432
433    /* the offset is 'grapheme count offset' so it still might be invalid - we'll check it later */
434
435    if ( grapheme_ascii_check(str, str_len) >= 0 ) {
436        grapheme_substr_ascii((char *)str, str_len, start, length, ZEND_NUM_ARGS(), (char **) &sub_str, &sub_str_len);
437
438        if ( NULL == sub_str ) {
439            intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "grapheme_substr: invalid parameters", 1 );
440            RETURN_FALSE;
441        }
442
443        RETURN_STRINGL(((char *)sub_str), sub_str_len);
444    }
445
446    ustr = NULL;
447    ustr_len = 0;
448    status = U_ZERO_ERROR;
449    intl_convert_utf8_to_utf16(&ustr, &ustr_len, (char *)str, str_len, &status);
450
451    if ( U_FAILURE( status ) ) {
452        /* Set global error code. */
453        intl_error_set_code( NULL, status );
454
455        /* Set error messages. */
456        intl_error_set_custom_msg( NULL, "Error converting input string to UTF-16", 0 );
457        if (ustr) {
458            efree( ustr );
459        }
460        RETURN_FALSE;
461    }
462
463    bi = grapheme_get_break_iterator((void*)u_break_iterator_buffer, &status );
464
465    if( U_FAILURE(status) ) {
466        RETURN_FALSE;
467    }
468
469    ubrk_setText(bi, ustr, ustr_len,    &status);
470
471    if ( start < 0 ) {
472        iter_func = ubrk_previous;
473        ubrk_last(bi);
474        iter_val = 1;
475    }
476    else {
477        iter_func = ubrk_next;
478        iter_val = -1;
479    }
480
481    sub_str_start_pos = 0;
482
483    while ( start ) {
484        sub_str_start_pos = iter_func(bi);
485
486        if ( UBRK_DONE == sub_str_start_pos ) {
487            break;
488        }
489
490        start += iter_val;
491    }
492
493    if ( 0 != start || sub_str_start_pos >= ustr_len ) {
494
495        intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "grapheme_substr: start not contained in string", 1 );
496
497        if (ustr) {
498            efree(ustr);
499        }
500        ubrk_close(bi);
501        RETURN_FALSE;
502    }
503
504    if (ZEND_NUM_ARGS() <= 2) {
505
506        /* no length supplied, return the rest of the string */
507
508        sub_str = NULL;
509        sub_str_len = 0;
510        status = U_ZERO_ERROR;
511        intl_convert_utf16_to_utf8((char **)&sub_str, &sub_str_len, ustr + sub_str_start_pos, ustr_len - sub_str_start_pos, &status);
512
513        if (ustr) {
514            efree( ustr );
515        }
516        ubrk_close( bi );
517
518        if ( U_FAILURE( status ) ) {
519            /* Set global error code. */
520            intl_error_set_code( NULL, status );
521
522            /* Set error messages. */
523            intl_error_set_custom_msg( NULL, "Error converting output string to UTF-8", 0 );
524
525            if (sub_str) {
526                efree( sub_str );
527            }
528
529            RETURN_FALSE;
530        }
531
532        /* return the allocated string, not a duplicate */
533        RETVAL_STRINGL(((char *)sub_str), sub_str_len);
534        //???
535        efree(sub_str);
536        return;
537    }
538
539    if(length == 0) {
540        /* empty length - we've validated start, we can return "" now */
541        if (ustr) {
542            efree(ustr);
543        }
544        ubrk_close(bi);
545        RETURN_EMPTY_STRING();
546    }
547
548    /* find the end point of the string to return */
549
550    if ( length < 0 ) {
551        iter_func = ubrk_previous;
552        ubrk_last(bi);
553        iter_val = 1;
554    }
555    else {
556        iter_func = ubrk_next;
557        iter_val = -1;
558    }
559
560    sub_str_end_pos = 0;
561
562    while ( length ) {
563        sub_str_end_pos = iter_func(bi);
564
565        if ( UBRK_DONE == sub_str_end_pos ) {
566            break;
567        }
568
569        length += iter_val;
570    }
571
572    ubrk_close(bi);
573
574    if ( UBRK_DONE == sub_str_end_pos) {
575        if(length < 0) {
576            intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "grapheme_substr: length not contained in string", 1 );
577
578            efree(ustr);
579            RETURN_FALSE;
580        } else {
581            sub_str_end_pos = ustr_len;
582        }
583    }
584
585    if(sub_str_start_pos > sub_str_end_pos) {
586        intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "grapheme_substr: length is beyond start", 1 );
587
588        efree(ustr);
589        RETURN_FALSE;
590    }
591
592    sub_str = NULL;
593    status = U_ZERO_ERROR;
594    intl_convert_utf16_to_utf8((char **)&sub_str, &sub_str_len, ustr + sub_str_start_pos, ( sub_str_end_pos - sub_str_start_pos ), &status);
595
596    efree( ustr );
597
598    if ( U_FAILURE( status ) ) {
599        /* Set global error code. */
600        intl_error_set_code( NULL, status );
601
602        /* Set error messages. */
603        intl_error_set_custom_msg( NULL, "Error converting output string to UTF-8", 0 );
604
605        if ( NULL != sub_str )
606            efree( sub_str );
607
608        RETURN_FALSE;
609    }
610
611     /* return the allocated string, not a duplicate */
612    RETVAL_STRINGL(((char *)sub_str), sub_str_len);
613    //????
614    efree(sub_str);
615
616}
617/* }}} */
618
619/* {{{  strstr_common_handler */
620static void strstr_common_handler(INTERNAL_FUNCTION_PARAMETERS, int f_ignore_case)
621{
622    unsigned char *haystack, *needle, *found;
623    size_t haystack_len, needle_len;
624    int ret_pos, uchar_pos;
625    zend_bool part = 0;
626
627    if (zend_parse_parameters(ZEND_NUM_ARGS(), "ss|b", (char **)&haystack, &haystack_len, (char **)&needle, &needle_len, &part) == FAILURE) {
628
629        intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,
630             "grapheme_strstr: unable to parse input param", 0 );
631
632        RETURN_FALSE;
633    }
634
635    if (needle_len == 0) {
636
637        intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "grapheme_strpos: Empty delimiter", 1 );
638
639        RETURN_FALSE;
640    }
641
642
643    if ( !f_ignore_case ) {
644
645        /* ASCII optimization: quick check to see if the string might be there
646         * I realize that 'offset' is 'grapheme count offset' but will work in spite of that
647        */
648        found = (unsigned char *)php_memnstr((char *)haystack, (char *)needle, needle_len, (char *)haystack + haystack_len);
649
650        /* if it isn't there the we are done */
651        if ( !found ) {
652            RETURN_FALSE;
653        }
654
655        /* if it is there, and if the haystack is ascii, we are all done */
656        if ( grapheme_ascii_check(haystack, haystack_len) >= 0 ) {
657            size_t found_offset = found - haystack;
658
659            if (part) {
660                RETURN_STRINGL(((char *)haystack) , found_offset);
661            } else {
662                RETURN_STRINGL(((char *)found), haystack_len - found_offset);
663            }
664        }
665
666    }
667
668    /* need to work in utf16 */
669    ret_pos = grapheme_strpos_utf16(haystack, haystack_len, needle, needle_len, 0, &uchar_pos, f_ignore_case, 0 /*last */ );
670
671    if ( ret_pos < 0 ) {
672        RETURN_FALSE;
673    }
674
675    /* uchar_pos is the 'nth' Unicode character position of the needle */
676
677    ret_pos = 0;
678    U8_FWD_N(haystack, ret_pos, haystack_len, uchar_pos);
679
680    if (part) {
681        RETURN_STRINGL(((char *)haystack), ret_pos);
682    }
683    else {
684        RETURN_STRINGL(((char *)haystack) + ret_pos, haystack_len - ret_pos);
685    }
686
687}
688/* }}} */
689
690/* {{{ proto string grapheme_strstr(string haystack, string needle[, bool part])
691   Finds first occurrence of a string within another */
692PHP_FUNCTION(grapheme_strstr)
693{
694    strstr_common_handler(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0 /* f_ignore_case */);
695}
696/* }}} */
697
698/* {{{ proto string grapheme_stristr(string haystack, string needle[, bool part])
699   Finds first occurrence of a string within another */
700PHP_FUNCTION(grapheme_stristr)
701{
702    strstr_common_handler(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1 /* f_ignore_case */);
703}
704/* }}} */
705
706/* {{{ grapheme_extract_charcount_iter - grapheme iterator for grapheme_extract MAXCHARS */
707static inline int32_t
708grapheme_extract_charcount_iter(UBreakIterator *bi, int32_t csize, unsigned char *pstr, int32_t str_len)
709{
710    int pos = 0, prev_pos = 0;
711    int ret_pos = 0, prev_ret_pos = 0;
712
713    while ( 1 ) {
714        pos = ubrk_next(bi);
715
716        if ( UBRK_DONE == pos ) {
717            break;
718        }
719
720        /* if we are beyond our limit, then the loop is done */
721        if ( pos > csize ) {
722            break;
723        }
724
725        /* update our pointer in the original UTF-8 buffer by as many characters
726           as ubrk_next iterated over */
727
728        prev_ret_pos = ret_pos;
729        U8_FWD_N(pstr, ret_pos, str_len, pos - prev_pos);
730
731        if ( prev_ret_pos == ret_pos ) {
732            /* something wrong - malformed utf8? */
733            break;
734        }
735
736        prev_pos = pos;
737    }
738
739    return ret_pos;
740}
741/* }}} */
742
743/* {{{ grapheme_extract_bytecount_iter - grapheme iterator for grapheme_extract MAXBYTES */
744static inline int32_t
745grapheme_extract_bytecount_iter(UBreakIterator *bi, int32_t bsize, unsigned char *pstr, int32_t str_len)
746{
747    int pos = 0, prev_pos = 0;
748    int ret_pos = 0, prev_ret_pos = 0;
749
750    while ( 1 ) {
751        pos = ubrk_next(bi);
752
753        if ( UBRK_DONE == pos ) {
754            break;
755        }
756
757        prev_ret_pos = ret_pos;
758        U8_FWD_N(pstr, ret_pos, str_len, pos - prev_pos);
759
760        if ( ret_pos > bsize ) {
761            ret_pos = prev_ret_pos;
762            break;
763        }
764
765        if ( prev_ret_pos == ret_pos ) {
766            /* something wrong - malformed utf8? */
767            break;
768        }
769
770        prev_pos = pos;
771    }
772
773    return ret_pos;
774}
775/* }}} */
776
777/* {{{ grapheme_extract_count_iter - grapheme iterator for grapheme_extract COUNT */
778static inline int32_t
779grapheme_extract_count_iter(UBreakIterator *bi, int32_t size, unsigned char *pstr, int32_t str_len)
780{
781    int pos = 0, next_pos = 0;
782    int ret_pos = 0;
783
784    while ( size ) {
785        next_pos = ubrk_next(bi);
786
787        if ( UBRK_DONE == next_pos ) {
788            break;
789        }
790        pos = next_pos;
791        size--;
792    }
793
794    /* pos is one past the last UChar - and represent the number of code units to
795        advance in the utf-8 buffer
796    */
797
798    U8_FWD_N(pstr, ret_pos, str_len, pos);
799
800    return ret_pos;
801}
802/* }}} */
803
804/* {{{ grapheme extract iter function pointer array */
805typedef int32_t (*grapheme_extract_iter)(UBreakIterator * /*bi*/, int32_t /*size*/, unsigned char * /*pstr*/, int32_t /*str_len*/);
806
807static grapheme_extract_iter grapheme_extract_iters[] = {
808    &grapheme_extract_count_iter,
809    &grapheme_extract_bytecount_iter,
810    &grapheme_extract_charcount_iter,
811};
812/* }}} */
813
814/* {{{ proto string grapheme_extract(string str, int size[, int extract_type[, int start[, int next]]])
815    Function to extract a sequence of default grapheme clusters */
816PHP_FUNCTION(grapheme_extract)
817{
818    unsigned char *str, *pstr;
819    UChar *ustr;
820    size_t str_len;
821    int32_t ustr_len;
822    zend_long size; /* maximum number of grapheme clusters, bytes, or characters (based on extract_type) to return */
823    zend_long lstart = 0; /* starting position in str in bytes */
824    int32_t start = 0;
825    zend_long extract_type = GRAPHEME_EXTRACT_TYPE_COUNT;
826    UErrorCode status;
827    unsigned char u_break_iterator_buffer[U_BRK_SAFECLONE_BUFFERSIZE];
828    UBreakIterator* bi = NULL;
829    int ret_pos;
830    zval *next = NULL; /* return offset of next part of the string */
831
832    if (zend_parse_parameters(ZEND_NUM_ARGS(), "sl|llz", (char **)&str, &str_len, &size, &extract_type, &lstart, &next) == FAILURE) {
833
834        intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,
835             "grapheme_extract: unable to parse input param", 0 );
836
837        RETURN_FALSE;
838    }
839
840    if ( NULL != next ) {
841        if ( !Z_ISREF_P(next) ) {
842            intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,
843                 "grapheme_extract: 'next' was not passed by reference", 0 );
844
845            RETURN_FALSE;
846        }
847        else {
848            ZVAL_DEREF(next);
849            /* initialize next */
850            SEPARATE_ZVAL(next);
851            zval_dtor(next);
852            ZVAL_LONG(next, lstart);
853        }
854    }
855
856    if ( extract_type < GRAPHEME_EXTRACT_TYPE_MIN || extract_type > GRAPHEME_EXTRACT_TYPE_MAX ) {
857
858        intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,
859             "grapheme_extract: unknown extract type param", 0 );
860
861        RETURN_FALSE;
862    }
863
864    if ( lstart > INT32_MAX || lstart < 0 || lstart >= str_len ) {
865        intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "grapheme_extract: start not contained in string", 0 );
866        RETURN_FALSE;
867    }
868
869    if ( size > INT32_MAX || size < 0) {
870        intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR, "grapheme_extract: size is invalid", 0 );
871        RETURN_FALSE;
872    }
873    if (size == 0) {
874        RETURN_EMPTY_STRING();
875    }
876
877    /* we checked that it will fit: */
878    start = (int32_t) lstart;
879
880    pstr = str + start;
881
882    /* just in case pstr points in the middle of a character, move forward to the start of the next char */
883    if ( !UTF8_IS_SINGLE(*pstr) && !U8_IS_LEAD(*pstr) ) {
884        unsigned char *str_end = str + str_len;
885
886        while ( !UTF8_IS_SINGLE(*pstr) && !U8_IS_LEAD(*pstr) ) {
887            pstr++;
888            if ( pstr >= str_end ) {
889                intl_error_set( NULL, U_ILLEGAL_ARGUMENT_ERROR,
890                                "grapheme_extract: invalid input string", 0 );
891
892                RETURN_FALSE;
893            }
894        }
895    }
896
897    str_len -= (pstr - str);
898
899    /* if the string is all ASCII up to size+1 - or str_len whichever is first - then we are done.
900        (size + 1 because the size-th character might be the beginning of a grapheme cluster)
901     */
902
903    if ( -1 != grapheme_ascii_check(pstr, size + 1 < str_len ? size + 1 : str_len ) ) {
904        zend_long nsize = ( size < str_len ? size : str_len );
905        if ( NULL != next ) {
906            ZVAL_LONG(next, start+nsize);
907        }
908        RETURN_STRINGL(((char *)pstr), nsize);
909    }
910
911    /* convert the strings to UTF-16. */
912    ustr = NULL;
913    ustr_len = 0;
914    status = U_ZERO_ERROR;
915    intl_convert_utf8_to_utf16(&ustr, &ustr_len, (char *)pstr, str_len, &status );
916
917    if ( U_FAILURE( status ) ) {
918        /* Set global error code. */
919        intl_error_set_code( NULL, status );
920
921        /* Set error messages. */
922        intl_error_set_custom_msg( NULL, "Error converting input string to UTF-16", 0 );
923
924        if ( NULL != ustr )
925            efree( ustr );
926
927        RETURN_FALSE;
928    }
929
930    bi = NULL;
931    status = U_ZERO_ERROR;
932    bi = grapheme_get_break_iterator(u_break_iterator_buffer, &status );
933
934    ubrk_setText(bi, ustr, ustr_len, &status);
935
936    /* if the caller put us in the middle of a grapheme, we can't detect it in all cases since we
937        can't back up. So, we will not do anything. */
938
939    /* now we need to find the end of the chunk the user wants us to return */
940
941    ret_pos = (*grapheme_extract_iters[extract_type])(bi, size, pstr, str_len);
942
943    if (ustr) {
944        efree(ustr);
945    }
946    ubrk_close(bi);
947
948    if ( NULL != next ) {
949        ZVAL_LONG(next, start+ret_pos);
950    }
951
952    RETURN_STRINGL(((char *)pstr), ret_pos);
953}
954
955/* }}} */
956
957/*
958 * Local variables:
959 * tab-width: 4
960 * c-basic-offset: 4
961 * End:
962 * vim600: fdm=marker
963 * vim: noet sw=4 ts=4
964 */
965
966