xref: /dokuwiki/inc/Utf8/Unicode.php (revision 26dfc2323f8f70cb69aac4c8c51bf7997809f2ca)
1<?php
2
3namespace dokuwiki\Utf8;
4
5/**
6 * Convert between UTF-8 and a list of Unicode Code Points
7 */
8class Unicode
9{
10
11    /**
12     * Takes an UTF-8 string and returns an array of ints representing the
13     * Unicode characters. Astral planes are supported ie. the ints in the
14     * output can be > 0xFFFF. Occurrances of the BOM are ignored. Surrogates
15     * are not allowed.
16     *
17     * If $strict is set to true the function returns false if the input
18     * string isn't a valid UTF-8 octet sequence and raises a PHP error at
19     * level E_USER_WARNING
20     *
21     * Note: this function has been modified slightly in this library to
22     * trigger errors on encountering bad bytes
23     *
24     * @author <hsivonen@iki.fi>
25     * @author Harry Fuecks <hfuecks@gmail.com>
26     * @see    unicode_to_utf8
27     * @link   http://hsivonen.iki.fi/php-utf8/
28     * @link   http://sourceforge.net/projects/phputf8/
29     * @todo break into less complex chunks
30     * @todo use exceptions instead of user errors
31     *
32     * @param  string $str UTF-8 encoded string
33     * @param  boolean $strict Check for invalid sequences?
34     * @return mixed array of unicode code points or false if UTF-8 invalid
35     */
36    public static function fromUtf8($str, $strict = false)
37    {
38        $mState = 0;     // cached expected number of octets after the current octet
39        // until the beginning of the next UTF8 character sequence
40        $mUcs4 = 0;     // cached Unicode character
41        $mBytes = 1;     // cached expected number of octets in the current sequence
42
43        $out = [];
44
45        $len = strlen($str);
46
47        for ($i = 0; $i < $len; $i++) {
48            $in = ord($str[$i]);
49
50            if ($mState === 0) {
51                // When mState is zero we expect either a US-ASCII character or a
52                // multi-octet sequence.
53                if (0 === (0x80 & $in)) {
54                    // US-ASCII, pass straight through.
55                    $out[] = $in;
56                    $mBytes = 1;
57                } elseif (0xC0 === (0xE0 & $in)) {
58                    // First octet of 2 octet sequence
59                    $mUcs4 = $in;
60                    $mUcs4 = ($mUcs4 & 0x1F) << 6;
61                    $mState = 1;
62                    $mBytes = 2;
63                } elseif (0xE0 === (0xF0 & $in)) {
64                    // First octet of 3 octet sequence
65                    $mUcs4 = $in;
66                    $mUcs4 = ($mUcs4 & 0x0F) << 12;
67                    $mState = 2;
68                    $mBytes = 3;
69                } elseif (0xF0 === (0xF8 & $in)) {
70                    // First octet of 4 octet sequence
71                    $mUcs4 = $in;
72                    $mUcs4 = ($mUcs4 & 0x07) << 18;
73                    $mState = 3;
74                    $mBytes = 4;
75                } elseif (0xF8 === (0xFC & $in)) {
76                    /* First octet of 5 octet sequence.
77                     *
78                     * This is illegal because the encoded codepoint must be either
79                     * (a) not the shortest form or
80                     * (b) outside the Unicode range of 0-0x10FFFF.
81                     * Rather than trying to resynchronize, we will carry on until the end
82                     * of the sequence and let the later error handling code catch it.
83                     */
84                    $mUcs4 = $in;
85                    $mUcs4 = ($mUcs4 & 0x03) << 24;
86                    $mState = 4;
87                    $mBytes = 5;
88                } elseif (0xFC === (0xFE & $in)) {
89                    // First octet of 6 octet sequence, see comments for 5 octet sequence.
90                    $mUcs4 = $in;
91                    $mUcs4 = ($mUcs4 & 1) << 30;
92                    $mState = 5;
93                    $mBytes = 6;
94                } elseif ($strict) {
95                    /* Current octet is neither in the US-ASCII range nor a legal first
96                     * octet of a multi-octet sequence.
97                     */
98                    trigger_error(
99                        'utf8_to_unicode: Illegal sequence identifier ' .
100                        'in UTF-8 at byte ' . $i,
101                        E_USER_WARNING
102                    );
103                    return false;
104                }
105            } elseif (0x80 === (0xC0 & $in)) {
106                // When mState is non-zero, we expect a continuation of the multi-octet
107                // sequence
108                // Legal continuation.
109                $shift = ($mState - 1) * 6;
110                $tmp = $in;
111                $tmp = ($tmp & 0x0000003F) << $shift;
112                $mUcs4 |= $tmp;
113                /**
114                 * End of the multi-octet sequence. mUcs4 now contains the final
115                 * Unicode codepoint to be output
116                 */
117                if (0 === --$mState) {
118                    /*
119                     * Check for illegal sequences and codepoints.
120                     */
121                    // From Unicode 3.1, non-shortest form is illegal
122                    if (
123                        ((2 === $mBytes) && ($mUcs4 < 0x0080)) ||
124                        ((3 === $mBytes) && ($mUcs4 < 0x0800)) ||
125                        ((4 === $mBytes) && ($mUcs4 < 0x10000)) ||
126                        (4 < $mBytes) ||
127                        // From Unicode 3.2, surrogate characters are illegal
128                        (($mUcs4 & 0xFFFFF800) === 0xD800) ||
129                        // Codepoints outside the Unicode range are illegal
130                        ($mUcs4 > 0x10FFFF)
131                    ) {
132                        if ($strict) {
133                            trigger_error(
134                                'utf8_to_unicode: Illegal sequence or codepoint ' .
135                                'in UTF-8 at byte ' . $i,
136                                E_USER_WARNING
137                            );
138
139                            return false;
140                        }
141                    }
142
143                    if (0xFEFF !== $mUcs4) {
144                        // BOM is legal but we don't want to output it
145                        $out[] = $mUcs4;
146                    }
147
148                    //initialize UTF8 cache
149                    $mState = 0;
150                    $mUcs4 = 0;
151                    $mBytes = 1;
152                }
153            } elseif ($strict) {
154                /**
155                 *((0xC0 & (*in) != 0x80) && (mState != 0))
156                 * Incomplete multi-octet sequence.
157                 */
158                trigger_error(
159                    'utf8_to_unicode: Incomplete multi-octet ' .
160                    '   sequence in UTF-8 at byte ' . $i,
161                    E_USER_WARNING
162                );
163
164                return false;
165            }
166        }
167        return $out;
168    }
169
170    /**
171     * Takes an array of ints representing the Unicode characters and returns
172     * a UTF-8 string. Astral planes are supported ie. the ints in the
173     * input can be > 0xFFFF. Occurrances of the BOM are ignored. Surrogates
174     * are not allowed.
175     *
176     * If $strict is set to true the function returns false if the input
177     * array contains ints that represent surrogates or are outside the
178     * Unicode range and raises a PHP error at level E_USER_WARNING
179     *
180     * Note: this function has been modified slightly in this library to use
181     * output buffering to concatenate the UTF-8 string (faster) as well as
182     * reference the array by it's keys
183     *
184     * @param  array $arr of unicode code points representing a string
185     * @param  boolean $strict Check for invalid sequences?
186     * @return string|false UTF-8 string or false if array contains invalid code points
187     *
188     * @author <hsivonen@iki.fi>
189     * @author Harry Fuecks <hfuecks@gmail.com>
190     * @see    utf8_to_unicode
191     * @link   http://hsivonen.iki.fi/php-utf8/
192     * @link   http://sourceforge.net/projects/phputf8/
193     * @todo use exceptions instead of user errors
194     */
195    public static function toUtf8($arr, $strict = false)
196    {
197        if (!is_array($arr)) return '';
198        ob_start();
199
200        foreach (array_keys($arr) as $k) {
201            if (($arr[$k] >= 0) && ($arr[$k] <= 0x007f)) {
202                # ASCII range (including control chars)
203                echo chr($arr[$k]);
204            } elseif ($arr[$k] <= 0x07ff) {
205                # 2 byte sequence
206                echo chr(0xc0 | ($arr[$k] >> 6));
207                echo chr(0x80 | ($arr[$k] & 0x003f));
208            } elseif ($arr[$k] == 0xFEFF) {
209                # Byte order mark (skip)
210                // nop -- zap the BOM
211            } elseif ($arr[$k] >= 0xD800 && $arr[$k] <= 0xDFFF) {
212                # Test for illegal surrogates
213                // found a surrogate
214                if ($strict) {
215                    trigger_error(
216                        'unicode_to_utf8: Illegal surrogate ' .
217                        'at index: ' . $k . ', value: ' . $arr[$k],
218                        E_USER_WARNING
219                    );
220                    return false;
221                }
222            } elseif ($arr[$k] <= 0xffff) {
223                # 3 byte sequence
224                echo chr(0xe0 | ($arr[$k] >> 12));
225                echo chr(0x80 | (($arr[$k] >> 6) & 0x003f));
226                echo chr(0x80 | ($arr[$k] & 0x003f));
227            } elseif ($arr[$k] <= 0x10ffff) {
228                # 4 byte sequence
229                echo chr(0xf0 | ($arr[$k] >> 18));
230                echo chr(0x80 | (($arr[$k] >> 12) & 0x3f));
231                echo chr(0x80 | (($arr[$k] >> 6) & 0x3f));
232                echo chr(0x80 | ($arr[$k] & 0x3f));
233            } elseif ($strict) {
234                trigger_error(
235                    'unicode_to_utf8: Codepoint out of Unicode range ' .
236                    'at index: ' . $k . ', value: ' . $arr[$k],
237                    E_USER_WARNING
238                );
239
240                // out of range
241                return false;
242            }
243        }
244
245        return ob_get_clean();
246    }
247}
248