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