ILIAS  Release_4_4_x_branch Revision 61816
 All Data Structures Namespaces Files Functions Variables Groups Pages
Encoder.php
Go to the documentation of this file.
1 <?php
2 
8 {
9 
13  private function __construct() {
14  trigger_error('Cannot instantiate encoder, call methods statically', E_USER_ERROR);
15  }
16 
20  public static function muteErrorHandler() {}
21 
25  public static function unsafeIconv($in, $out, $text) {
26  set_error_handler(array('HTMLPurifier_Encoder', 'muteErrorHandler'));
27  $r = iconv($in, $out, $text);
28  restore_error_handler();
29  return $r;
30  }
31 
35  public static function iconv($in, $out, $text, $max_chunk_size = 8000) {
37  if ($code == self::ICONV_OK) {
38  return self::unsafeIconv($in, $out, $text);
39  } elseif ($code == self::ICONV_TRUNCATES) {
40  // we can only work around this if the input character set
41  // is utf-8
42  if ($in == 'utf-8') {
43  if ($max_chunk_size < 4) {
44  trigger_error('max_chunk_size is too small', E_USER_WARNING);
45  return false;
46  }
47  // split into 8000 byte chunks, but be careful to handle
48  // multibyte boundaries properly
49  if (($c = strlen($text)) <= $max_chunk_size) {
50  return self::unsafeIconv($in, $out, $text);
51  }
52  $r = '';
53  $i = 0;
54  while (true) {
55  if ($i + $max_chunk_size >= $c) {
56  $r .= self::unsafeIconv($in, $out, substr($text, $i));
57  break;
58  }
59  // wibble the boundary
60  if (0x80 != (0xC0 & ord($text[$i + $max_chunk_size]))) {
61  $chunk_size = $max_chunk_size;
62  } elseif (0x80 != (0xC0 & ord($text[$i + $max_chunk_size - 1]))) {
63  $chunk_size = $max_chunk_size - 1;
64  } elseif (0x80 != (0xC0 & ord($text[$i + $max_chunk_size - 2]))) {
65  $chunk_size = $max_chunk_size - 2;
66  } elseif (0x80 != (0xC0 & ord($text[$i + $max_chunk_size - 3]))) {
67  $chunk_size = $max_chunk_size - 3;
68  } else {
69  return false; // rather confusing UTF-8...
70  }
71  $chunk = substr($text, $i, $chunk_size); // substr doesn't mind overlong lengths
72  $r .= self::unsafeIconv($in, $out, $chunk);
73  $i += $chunk_size;
74  }
75  return $r;
76  } else {
77  return false;
78  }
79  } else {
80  return false;
81  }
82  }
83 
109  public static function cleanUTF8($str, $force_php = false) {
110 
111  // UTF-8 validity is checked since PHP 4.3.5
112  // This is an optimization: if the string is already valid UTF-8, no
113  // need to do PHP stuff. 99% of the time, this will be the case.
114  // The regexp matches the XML char production, as well as well as excluding
115  // non-SGML codepoints U+007F to U+009F
116  if (preg_match('/^[\x{9}\x{A}\x{D}\x{20}-\x{7E}\x{A0}-\x{D7FF}\x{E000}-\x{FFFD}\x{10000}-\x{10FFFF}]*$/Du', $str)) {
117  return $str;
118  }
119 
120  $mState = 0; // cached expected number of octets after the current octet
121  // until the beginning of the next UTF8 character sequence
122  $mUcs4 = 0; // cached Unicode character
123  $mBytes = 1; // cached expected number of octets in the current sequence
124 
125  // original code involved an $out that was an array of Unicode
126  // codepoints. Instead of having to convert back into UTF-8, we've
127  // decided to directly append valid UTF-8 characters onto a string
128  // $out once they're done. $char accumulates raw bytes, while $mUcs4
129  // turns into the Unicode code point, so there's some redundancy.
130 
131  $out = '';
132  $char = '';
133 
134  $len = strlen($str);
135  for($i = 0; $i < $len; $i++) {
136  $in = ord($str{$i});
137  $char .= $str[$i]; // append byte to char
138  if (0 == $mState) {
139  // When mState is zero we expect either a US-ASCII character
140  // or a multi-octet sequence.
141  if (0 == (0x80 & ($in))) {
142  // US-ASCII, pass straight through.
143  if (($in <= 31 || $in == 127) &&
144  !($in == 9 || $in == 13 || $in == 10) // save \r\t\n
145  ) {
146  // control characters, remove
147  } else {
148  $out .= $char;
149  }
150  // reset
151  $char = '';
152  $mBytes = 1;
153  } elseif (0xC0 == (0xE0 & ($in))) {
154  // First octet of 2 octet sequence
155  $mUcs4 = ($in);
156  $mUcs4 = ($mUcs4 & 0x1F) << 6;
157  $mState = 1;
158  $mBytes = 2;
159  } elseif (0xE0 == (0xF0 & ($in))) {
160  // First octet of 3 octet sequence
161  $mUcs4 = ($in);
162  $mUcs4 = ($mUcs4 & 0x0F) << 12;
163  $mState = 2;
164  $mBytes = 3;
165  } elseif (0xF0 == (0xF8 & ($in))) {
166  // First octet of 4 octet sequence
167  $mUcs4 = ($in);
168  $mUcs4 = ($mUcs4 & 0x07) << 18;
169  $mState = 3;
170  $mBytes = 4;
171  } elseif (0xF8 == (0xFC & ($in))) {
172  // First octet of 5 octet sequence.
173  //
174  // This is illegal because the encoded codepoint must be
175  // either:
176  // (a) not the shortest form or
177  // (b) outside the Unicode range of 0-0x10FFFF.
178  // Rather than trying to resynchronize, we will carry on
179  // until the end of the sequence and let the later error
180  // handling code catch it.
181  $mUcs4 = ($in);
182  $mUcs4 = ($mUcs4 & 0x03) << 24;
183  $mState = 4;
184  $mBytes = 5;
185  } elseif (0xFC == (0xFE & ($in))) {
186  // First octet of 6 octet sequence, see comments for 5
187  // octet sequence.
188  $mUcs4 = ($in);
189  $mUcs4 = ($mUcs4 & 1) << 30;
190  $mState = 5;
191  $mBytes = 6;
192  } else {
193  // Current octet is neither in the US-ASCII range nor a
194  // legal first octet of a multi-octet sequence.
195  $mState = 0;
196  $mUcs4 = 0;
197  $mBytes = 1;
198  $char = '';
199  }
200  } else {
201  // When mState is non-zero, we expect a continuation of the
202  // multi-octet sequence
203  if (0x80 == (0xC0 & ($in))) {
204  // Legal continuation.
205  $shift = ($mState - 1) * 6;
206  $tmp = $in;
207  $tmp = ($tmp & 0x0000003F) << $shift;
208  $mUcs4 |= $tmp;
209 
210  if (0 == --$mState) {
211  // End of the multi-octet sequence. mUcs4 now contains
212  // the final Unicode codepoint to be output
213 
214  // Check for illegal sequences and codepoints.
215 
216  // From Unicode 3.1, non-shortest form is illegal
217  if (((2 == $mBytes) && ($mUcs4 < 0x0080)) ||
218  ((3 == $mBytes) && ($mUcs4 < 0x0800)) ||
219  ((4 == $mBytes) && ($mUcs4 < 0x10000)) ||
220  (4 < $mBytes) ||
221  // From Unicode 3.2, surrogate characters = illegal
222  (($mUcs4 & 0xFFFFF800) == 0xD800) ||
223  // Codepoints outside the Unicode range are illegal
224  ($mUcs4 > 0x10FFFF)
225  ) {
226 
227  } elseif (0xFEFF != $mUcs4 && // omit BOM
228  // check for valid Char unicode codepoints
229  (
230  0x9 == $mUcs4 ||
231  0xA == $mUcs4 ||
232  0xD == $mUcs4 ||
233  (0x20 <= $mUcs4 && 0x7E >= $mUcs4) ||
234  // 7F-9F is not strictly prohibited by XML,
235  // but it is non-SGML, and thus we don't allow it
236  (0xA0 <= $mUcs4 && 0xD7FF >= $mUcs4) ||
237  (0x10000 <= $mUcs4 && 0x10FFFF >= $mUcs4)
238  )
239  ) {
240  $out .= $char;
241  }
242  // initialize UTF8 cache (reset)
243  $mState = 0;
244  $mUcs4 = 0;
245  $mBytes = 1;
246  $char = '';
247  }
248  } else {
249  // ((0xC0 & (*in) != 0x80) && (mState != 0))
250  // Incomplete multi-octet sequence.
251  // used to result in complete fail, but we'll reset
252  $mState = 0;
253  $mUcs4 = 0;
254  $mBytes = 1;
255  $char ='';
256  }
257  }
258  }
259  return $out;
260  }
261 
275  // +----------+----------+----------+----------+
276  // | 33222222 | 22221111 | 111111 | |
277  // | 10987654 | 32109876 | 54321098 | 76543210 | bit
278  // +----------+----------+----------+----------+
279  // | | | | 0xxxxxxx | 1 byte 0x00000000..0x0000007F
280  // | | | 110yyyyy | 10xxxxxx | 2 byte 0x00000080..0x000007FF
281  // | | 1110zzzz | 10yyyyyy | 10xxxxxx | 3 byte 0x00000800..0x0000FFFF
282  // | 11110www | 10wwzzzz | 10yyyyyy | 10xxxxxx | 4 byte 0x00010000..0x0010FFFF
283  // +----------+----------+----------+----------+
284  // | 00000000 | 00011111 | 11111111 | 11111111 | Theoretical upper limit of legal scalars: 2097151 (0x001FFFFF)
285  // | 00000000 | 00010000 | 11111111 | 11111111 | Defined upper limit of legal scalar codes
286  // +----------+----------+----------+----------+
287 
288  public static function unichr($code) {
289  if($code > 1114111 or $code < 0 or
290  ($code >= 55296 and $code <= 57343) ) {
291  // bits are set outside the "valid" range as defined
292  // by UNICODE 4.1.0
293  return '';
294  }
295 
296  $x = $y = $z = $w = 0;
297  if ($code < 128) {
298  // regular ASCII character
299  $x = $code;
300  } else {
301  // set up bits for UTF-8
302  $x = ($code & 63) | 128;
303  if ($code < 2048) {
304  $y = (($code & 2047) >> 6) | 192;
305  } else {
306  $y = (($code & 4032) >> 6) | 128;
307  if($code < 65536) {
308  $z = (($code >> 12) & 15) | 224;
309  } else {
310  $z = (($code >> 12) & 63) | 128;
311  $w = (($code >> 18) & 7) | 240;
312  }
313  }
314  }
315  // set up the actual character
316  $ret = '';
317  if($w) $ret .= chr($w);
318  if($z) $ret .= chr($z);
319  if($y) $ret .= chr($y);
320  $ret .= chr($x);
321 
322  return $ret;
323  }
324 
325  public static function iconvAvailable() {
326  static $iconv = null;
327  if ($iconv === null) {
328  $iconv = function_exists('iconv') && self::testIconvTruncateBug() != self::ICONV_UNUSABLE;
329  }
330  return $iconv;
331  }
332 
336  public static function convertToUTF8($str, $config, $context) {
337  $encoding = $config->get('Core.Encoding');
338  if ($encoding === 'utf-8') return $str;
339  static $iconv = null;
340  if ($iconv === null) $iconv = self::iconvAvailable();
341  if ($iconv && !$config->get('Test.ForceNoIconv')) {
342  // unaffected by bugs, since UTF-8 support all characters
343  $str = self::unsafeIconv($encoding, 'utf-8//IGNORE', $str);
344  if ($str === false) {
345  // $encoding is not a valid encoding
346  trigger_error('Invalid encoding ' . $encoding, E_USER_ERROR);
347  return '';
348  }
349  // If the string is bjorked by Shift_JIS or a similar encoding
350  // that doesn't support all of ASCII, convert the naughty
351  // characters to their true byte-wise ASCII/UTF-8 equivalents.
352  $str = strtr($str, self::testEncodingSupportsASCII($encoding));
353  return $str;
354  } elseif ($encoding === 'iso-8859-1') {
355  $str = utf8_encode($str);
356  return $str;
357  }
359  if ($bug == self::ICONV_OK) {
360  trigger_error('Encoding not supported, please install iconv', E_USER_ERROR);
361  } else {
362  trigger_error('You have a buggy version of iconv, see https://bugs.php.net/bug.php?id=48147 and http://sourceware.org/bugzilla/show_bug.cgi?id=13541', E_USER_ERROR);
363  }
364  }
365 
371  public static function convertFromUTF8($str, $config, $context) {
372  $encoding = $config->get('Core.Encoding');
373  if ($escape = $config->get('Core.EscapeNonASCIICharacters')) {
375  }
376  if ($encoding === 'utf-8') return $str;
377  static $iconv = null;
378  if ($iconv === null) $iconv = self::iconvAvailable();
379  if ($iconv && !$config->get('Test.ForceNoIconv')) {
380  // Undo our previous fix in convertToUTF8, otherwise iconv will barf
381  $ascii_fix = self::testEncodingSupportsASCII($encoding);
382  if (!$escape && !empty($ascii_fix)) {
383  $clear_fix = array();
384  foreach ($ascii_fix as $utf8 => $native) $clear_fix[$utf8] = '';
385  $str = strtr($str, $clear_fix);
386  }
387  $str = strtr($str, array_flip($ascii_fix));
388  // Normal stuff
389  $str = self::iconv('utf-8', $encoding . '//IGNORE', $str);
390  return $str;
391  } elseif ($encoding === 'iso-8859-1') {
392  $str = utf8_decode($str);
393  return $str;
394  }
395  trigger_error('Encoding not supported', E_USER_ERROR);
396  // You might be tempted to assume that the ASCII representation
397  // might be OK, however, this is *not* universally true over all
398  // encodings. So we take the conservative route here, rather
399  // than forcibly turn on %Core.EscapeNonASCIICharacters
400  }
401 
418  public static function convertToASCIIDumbLossless($str) {
419  $bytesleft = 0;
420  $result = '';
421  $working = 0;
422  $len = strlen($str);
423  for( $i = 0; $i < $len; $i++ ) {
424  $bytevalue = ord( $str[$i] );
425  if( $bytevalue <= 0x7F ) { //0xxx xxxx
426  $result .= chr( $bytevalue );
427  $bytesleft = 0;
428  } elseif( $bytevalue <= 0xBF ) { //10xx xxxx
429  $working = $working << 6;
430  $working += ($bytevalue & 0x3F);
431  $bytesleft--;
432  if( $bytesleft <= 0 ) {
433  $result .= "&#" . $working . ";";
434  }
435  } elseif( $bytevalue <= 0xDF ) { //110x xxxx
436  $working = $bytevalue & 0x1F;
437  $bytesleft = 1;
438  } elseif( $bytevalue <= 0xEF ) { //1110 xxxx
439  $working = $bytevalue & 0x0F;
440  $bytesleft = 2;
441  } else { //1111 0xxx
442  $working = $bytevalue & 0x07;
443  $bytesleft = 3;
444  }
445  }
446  return $result;
447  }
448 
450  const ICONV_OK = 0;
451 
454  const ICONV_TRUNCATES = 1;
455 
458  const ICONV_UNUSABLE = 2;
459 
474  public static function testIconvTruncateBug() {
475  static $code = null;
476  if ($code === null) {
477  // better not use iconv, otherwise infinite loop!
478  $r = self::unsafeIconv('utf-8', 'ascii//IGNORE', "\xCE\xB1" . str_repeat('a', 9000));
479  if ($r === false) {
480  $code = self::ICONV_UNUSABLE;
481  } elseif (($c = strlen($r)) < 9000) {
482  $code = self::ICONV_TRUNCATES;
483  } elseif ($c > 9000) {
484  trigger_error('Your copy of iconv is extremely buggy. Please notify HTML Purifier maintainers: include your iconv version as per phpversion()', E_USER_ERROR);
485  } else {
486  $code = self::ICONV_OK;
487  }
488  }
489  return $code;
490  }
491 
503  public static function testEncodingSupportsASCII($encoding, $bypass = false) {
504  // All calls to iconv here are unsafe, proof by case analysis:
505  // If ICONV_OK, no difference.
506  // If ICONV_TRUNCATE, all calls involve one character inputs,
507  // so bug is not triggered.
508  // If ICONV_UNUSABLE, this call is irrelevant
509  static $encodings = array();
510  if (!$bypass) {
511  if (isset($encodings[$encoding])) return $encodings[$encoding];
512  $lenc = strtolower($encoding);
513  switch ($lenc) {
514  case 'shift_jis':
515  return array("\xC2\xA5" => '\\', "\xE2\x80\xBE" => '~');
516  case 'johab':
517  return array("\xE2\x82\xA9" => '\\');
518  }
519  if (strpos($lenc, 'iso-8859-') === 0) return array();
520  }
521  $ret = array();
522  if (self::unsafeIconv('UTF-8', $encoding, 'a') === false) return false;
523  for ($i = 0x20; $i <= 0x7E; $i++) { // all printable ASCII chars
524  $c = chr($i); // UTF-8 char
525  $r = self::unsafeIconv('UTF-8', "$encoding//IGNORE", $c); // initial conversion
526  if (
527  $r === '' ||
528  // This line is needed for iconv implementations that do not
529  // omit characters that do not exist in the target character set
530  ($r === $c && self::unsafeIconv($encoding, 'UTF-8//IGNORE', $r) !== $c)
531  ) {
532  // Reverse engineer: what's the UTF-8 equiv of this byte
533  // sequence? This assumes that there's no variable width
534  // encoding that doesn't support ASCII.
535  $ret[self::unsafeIconv($encoding, 'UTF-8//IGNORE', $c)] = $c;
536  }
537  }
538  $encodings[$encoding] = $ret;
539  return $ret;
540  }
541 
542 
543 }
544 
545 // vim: et sw=4 sts=4