HTMLPurifier 4.4.0
/home/ezyang/Dev/htmlpurifier/library/HTMLPurifier/Encoder.php
Go to the documentation of this file.
00001 <?php
00002 
00007 class HTMLPurifier_Encoder
00008 {
00009 
00013     private function __construct() {
00014         trigger_error('Cannot instantiate encoder, call methods statically', E_USER_ERROR);
00015     }
00016 
00020     public static function muteErrorHandler() {}
00021 
00025     public static function unsafeIconv($in, $out, $text) {
00026         set_error_handler(array('HTMLPurifier_Encoder', 'muteErrorHandler'));
00027         $r = iconv($in, $out, $text);
00028         restore_error_handler();
00029         return $r;
00030     }
00031 
00035     public static function iconv($in, $out, $text, $max_chunk_size = 8000) {
00036         $code = self::testIconvTruncateBug();
00037         if ($code == self::ICONV_OK) {
00038             return self::unsafeIconv($in, $out, $text);
00039         } elseif ($code == self::ICONV_TRUNCATES) {
00040             // we can only work around this if the input character set
00041             // is utf-8
00042             if ($in == 'utf-8') {
00043                 if ($max_chunk_size < 4) {
00044                     trigger_error('max_chunk_size is too small', E_USER_WARNING);
00045                     return false;
00046                 }
00047                 // split into 8000 byte chunks, but be careful to handle
00048                 // multibyte boundaries properly
00049                 if (($c = strlen($text)) <= $max_chunk_size) {
00050                     return self::unsafeIconv($in, $out, $text);
00051                 }
00052                 $r = '';
00053                 $i = 0;
00054                 while (true) {
00055                     if ($i + $max_chunk_size >= $c) {
00056                         $r .= self::unsafeIconv($in, $out, substr($text, $i));
00057                         break;
00058                     }
00059                     // wibble the boundary
00060                     if (0x80 != (0xC0 & ord($text[$i + $max_chunk_size]))) {
00061                         $chunk_size = $max_chunk_size;
00062                     } elseif (0x80 != (0xC0 & ord($text[$i + $max_chunk_size - 1]))) {
00063                         $chunk_size = $max_chunk_size - 1;
00064                     } elseif (0x80 != (0xC0 & ord($text[$i + $max_chunk_size - 2]))) {
00065                         $chunk_size = $max_chunk_size - 2;
00066                     } elseif (0x80 != (0xC0 & ord($text[$i + $max_chunk_size - 3]))) {
00067                         $chunk_size = $max_chunk_size - 3;
00068                     } else {
00069                         return false; // rather confusing UTF-8...
00070                     }
00071                     $chunk = substr($text, $i, $chunk_size); // substr doesn't mind overlong lengths
00072                     $r .= self::unsafeIconv($in, $out, $chunk);
00073                     $i += $chunk_size;
00074                 }
00075                 return $r;
00076             } else {
00077                 return false;
00078             }
00079         } else {
00080             return false;
00081         }
00082     }
00083 
00109     public static function cleanUTF8($str, $force_php = false) {
00110 
00111         // UTF-8 validity is checked since PHP 4.3.5
00112         // This is an optimization: if the string is already valid UTF-8, no
00113         // need to do PHP stuff. 99% of the time, this will be the case.
00114         // The regexp matches the XML char production, as well as well as excluding
00115         // non-SGML codepoints U+007F to U+009F
00116         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)) {
00117             return $str;
00118         }
00119 
00120         $mState = 0; // cached expected number of octets after the current octet
00121                      // until the beginning of the next UTF8 character sequence
00122         $mUcs4  = 0; // cached Unicode character
00123         $mBytes = 1; // cached expected number of octets in the current sequence
00124 
00125         // original code involved an $out that was an array of Unicode
00126         // codepoints.  Instead of having to convert back into UTF-8, we've
00127         // decided to directly append valid UTF-8 characters onto a string
00128         // $out once they're done.  $char accumulates raw bytes, while $mUcs4
00129         // turns into the Unicode code point, so there's some redundancy.
00130 
00131         $out = '';
00132         $char = '';
00133 
00134         $len = strlen($str);
00135         for($i = 0; $i < $len; $i++) {
00136             $in = ord($str{$i});
00137             $char .= $str[$i]; // append byte to char
00138             if (0 == $mState) {
00139                 // When mState is zero we expect either a US-ASCII character
00140                 // or a multi-octet sequence.
00141                 if (0 == (0x80 & ($in))) {
00142                     // US-ASCII, pass straight through.
00143                     if (($in <= 31 || $in == 127) &&
00144                         !($in == 9 || $in == 13 || $in == 10) // save \r\t\n
00145                     ) {
00146                         // control characters, remove
00147                     } else {
00148                         $out .= $char;
00149                     }
00150                     // reset
00151                     $char = '';
00152                     $mBytes = 1;
00153                 } elseif (0xC0 == (0xE0 & ($in))) {
00154                     // First octet of 2 octet sequence
00155                     $mUcs4 = ($in);
00156                     $mUcs4 = ($mUcs4 & 0x1F) << 6;
00157                     $mState = 1;
00158                     $mBytes = 2;
00159                 } elseif (0xE0 == (0xF0 & ($in))) {
00160                     // First octet of 3 octet sequence
00161                     $mUcs4 = ($in);
00162                     $mUcs4 = ($mUcs4 & 0x0F) << 12;
00163                     $mState = 2;
00164                     $mBytes = 3;
00165                 } elseif (0xF0 == (0xF8 & ($in))) {
00166                     // First octet of 4 octet sequence
00167                     $mUcs4 = ($in);
00168                     $mUcs4 = ($mUcs4 & 0x07) << 18;
00169                     $mState = 3;
00170                     $mBytes = 4;
00171                 } elseif (0xF8 == (0xFC & ($in))) {
00172                     // First octet of 5 octet sequence.
00173                     //
00174                     // This is illegal because the encoded codepoint must be
00175                     // either:
00176                     // (a) not the shortest form or
00177                     // (b) outside the Unicode range of 0-0x10FFFF.
00178                     // Rather than trying to resynchronize, we will carry on
00179                     // until the end of the sequence and let the later error
00180                     // handling code catch it.
00181                     $mUcs4 = ($in);
00182                     $mUcs4 = ($mUcs4 & 0x03) << 24;
00183                     $mState = 4;
00184                     $mBytes = 5;
00185                 } elseif (0xFC == (0xFE & ($in))) {
00186                     // First octet of 6 octet sequence, see comments for 5
00187                     // octet sequence.
00188                     $mUcs4 = ($in);
00189                     $mUcs4 = ($mUcs4 & 1) << 30;
00190                     $mState = 5;
00191                     $mBytes = 6;
00192                 } else {
00193                     // Current octet is neither in the US-ASCII range nor a
00194                     // legal first octet of a multi-octet sequence.
00195                     $mState = 0;
00196                     $mUcs4  = 0;
00197                     $mBytes = 1;
00198                     $char = '';
00199                 }
00200             } else {
00201                 // When mState is non-zero, we expect a continuation of the
00202                 // multi-octet sequence
00203                 if (0x80 == (0xC0 & ($in))) {
00204                     // Legal continuation.
00205                     $shift = ($mState - 1) * 6;
00206                     $tmp = $in;
00207                     $tmp = ($tmp & 0x0000003F) << $shift;
00208                     $mUcs4 |= $tmp;
00209 
00210                     if (0 == --$mState) {
00211                         // End of the multi-octet sequence. mUcs4 now contains
00212                         // the final Unicode codepoint to be output
00213 
00214                         // Check for illegal sequences and codepoints.
00215 
00216                         // From Unicode 3.1, non-shortest form is illegal
00217                         if (((2 == $mBytes) && ($mUcs4 < 0x0080)) ||
00218                             ((3 == $mBytes) && ($mUcs4 < 0x0800)) ||
00219                             ((4 == $mBytes) && ($mUcs4 < 0x10000)) ||
00220                             (4 < $mBytes) ||
00221                             // From Unicode 3.2, surrogate characters = illegal
00222                             (($mUcs4 & 0xFFFFF800) == 0xD800) ||
00223                             // Codepoints outside the Unicode range are illegal
00224                             ($mUcs4 > 0x10FFFF)
00225                         ) {
00226 
00227                         } elseif (0xFEFF != $mUcs4 && // omit BOM
00228                             // check for valid Char unicode codepoints
00229                             (
00230                                 0x9 == $mUcs4 ||
00231                                 0xA == $mUcs4 ||
00232                                 0xD == $mUcs4 ||
00233                                 (0x20 <= $mUcs4 && 0x7E >= $mUcs4) ||
00234                                 // 7F-9F is not strictly prohibited by XML,
00235                                 // but it is non-SGML, and thus we don't allow it
00236                                 (0xA0 <= $mUcs4 && 0xD7FF >= $mUcs4) ||
00237                                 (0x10000 <= $mUcs4 && 0x10FFFF >= $mUcs4)
00238                             )
00239                         ) {
00240                             $out .= $char;
00241                         }
00242                         // initialize UTF8 cache (reset)
00243                         $mState = 0;
00244                         $mUcs4  = 0;
00245                         $mBytes = 1;
00246                         $char = '';
00247                     }
00248                 } else {
00249                     // ((0xC0 & (*in) != 0x80) && (mState != 0))
00250                     // Incomplete multi-octet sequence.
00251                     // used to result in complete fail, but we'll reset
00252                     $mState = 0;
00253                     $mUcs4  = 0;
00254                     $mBytes = 1;
00255                     $char ='';
00256                 }
00257             }
00258         }
00259         return $out;
00260     }
00261 
00275     // +----------+----------+----------+----------+
00276     // | 33222222 | 22221111 | 111111   |          |
00277     // | 10987654 | 32109876 | 54321098 | 76543210 | bit
00278     // +----------+----------+----------+----------+
00279     // |          |          |          | 0xxxxxxx | 1 byte 0x00000000..0x0000007F
00280     // |          |          | 110yyyyy | 10xxxxxx | 2 byte 0x00000080..0x000007FF
00281     // |          | 1110zzzz | 10yyyyyy | 10xxxxxx | 3 byte 0x00000800..0x0000FFFF
00282     // | 11110www | 10wwzzzz | 10yyyyyy | 10xxxxxx | 4 byte 0x00010000..0x0010FFFF
00283     // +----------+----------+----------+----------+
00284     // | 00000000 | 00011111 | 11111111 | 11111111 | Theoretical upper limit of legal scalars: 2097151 (0x001FFFFF)
00285     // | 00000000 | 00010000 | 11111111 | 11111111 | Defined upper limit of legal scalar codes
00286     // +----------+----------+----------+----------+
00287 
00288     public static function unichr($code) {
00289         if($code > 1114111 or $code < 0 or
00290           ($code >= 55296 and $code <= 57343) ) {
00291             // bits are set outside the "valid" range as defined
00292             // by UNICODE 4.1.0
00293             return '';
00294         }
00295 
00296         $x = $y = $z = $w = 0;
00297         if ($code < 128) {
00298             // regular ASCII character
00299             $x = $code;
00300         } else {
00301             // set up bits for UTF-8
00302             $x = ($code & 63) | 128;
00303             if ($code < 2048) {
00304                 $y = (($code & 2047) >> 6) | 192;
00305             } else {
00306                 $y = (($code & 4032) >> 6) | 128;
00307                 if($code < 65536) {
00308                     $z = (($code >> 12) & 15) | 224;
00309                 } else {
00310                     $z = (($code >> 12) & 63) | 128;
00311                     $w = (($code >> 18) & 7)  | 240;
00312                 }
00313             }
00314         }
00315         // set up the actual character
00316         $ret = '';
00317         if($w) $ret .= chr($w);
00318         if($z) $ret .= chr($z);
00319         if($y) $ret .= chr($y);
00320         $ret .= chr($x);
00321 
00322         return $ret;
00323     }
00324 
00325     public static function iconvAvailable() {
00326         static $iconv = null;
00327         if ($iconv === null) {
00328             $iconv = function_exists('iconv') && self::testIconvTruncateBug() != self::ICONV_UNUSABLE;
00329         }
00330         return $iconv;
00331     }
00332 
00336     public static function convertToUTF8($str, $config, $context) {
00337         $encoding = $config->get('Core.Encoding');
00338         if ($encoding === 'utf-8') return $str;
00339         static $iconv = null;
00340         if ($iconv === null) $iconv = self::iconvAvailable();
00341         if ($iconv && !$config->get('Test.ForceNoIconv')) {
00342             // unaffected by bugs, since UTF-8 support all characters
00343             $str = self::unsafeIconv($encoding, 'utf-8//IGNORE', $str);
00344             if ($str === false) {
00345                 // $encoding is not a valid encoding
00346                 trigger_error('Invalid encoding ' . $encoding, E_USER_ERROR);
00347                 return '';
00348             }
00349             // If the string is bjorked by Shift_JIS or a similar encoding
00350             // that doesn't support all of ASCII, convert the naughty
00351             // characters to their true byte-wise ASCII/UTF-8 equivalents.
00352             $str = strtr($str, self::testEncodingSupportsASCII($encoding));
00353             return $str;
00354         } elseif ($encoding === 'iso-8859-1') {
00355             $str = utf8_encode($str);
00356             return $str;
00357         }
00358         trigger_error('Encoding not supported, please install iconv', E_USER_ERROR);
00359     }
00360 
00366     public static function convertFromUTF8($str, $config, $context) {
00367         $encoding = $config->get('Core.Encoding');
00368         if ($escape = $config->get('Core.EscapeNonASCIICharacters')) {
00369             $str = self::convertToASCIIDumbLossless($str);
00370         }
00371         if ($encoding === 'utf-8') return $str;
00372         static $iconv = null;
00373         if ($iconv === null) $iconv = self::iconvAvailable();
00374         if ($iconv && !$config->get('Test.ForceNoIconv')) {
00375             // Undo our previous fix in convertToUTF8, otherwise iconv will barf
00376             $ascii_fix = self::testEncodingSupportsASCII($encoding);
00377             if (!$escape && !empty($ascii_fix)) {
00378                 $clear_fix = array();
00379                 foreach ($ascii_fix as $utf8 => $native) $clear_fix[$utf8] = '';
00380                 $str = strtr($str, $clear_fix);
00381             }
00382             $str = strtr($str, array_flip($ascii_fix));
00383             // Normal stuff
00384             $str = self::iconv('utf-8', $encoding . '//IGNORE', $str);
00385             return $str;
00386         } elseif ($encoding === 'iso-8859-1') {
00387             $str = utf8_decode($str);
00388             return $str;
00389         }
00390         trigger_error('Encoding not supported', E_USER_ERROR);
00391         // You might be tempted to assume that the ASCII representation
00392         // might be OK, however, this is *not* universally true over all
00393         // encodings.  So we take the conservative route here, rather
00394         // than forcibly turn on %Core.EscapeNonASCIICharacters
00395     }
00396 
00413     public static function convertToASCIIDumbLossless($str) {
00414         $bytesleft = 0;
00415         $result = '';
00416         $working = 0;
00417         $len = strlen($str);
00418         for( $i = 0; $i < $len; $i++ ) {
00419             $bytevalue = ord( $str[$i] );
00420             if( $bytevalue <= 0x7F ) { //0xxx xxxx
00421                 $result .= chr( $bytevalue );
00422                 $bytesleft = 0;
00423             } elseif( $bytevalue <= 0xBF ) { //10xx xxxx
00424                 $working = $working << 6;
00425                 $working += ($bytevalue & 0x3F);
00426                 $bytesleft--;
00427                 if( $bytesleft <= 0 ) {
00428                     $result .= "&#" . $working . ";";
00429                 }
00430             } elseif( $bytevalue <= 0xDF ) { //110x xxxx
00431                 $working = $bytevalue & 0x1F;
00432                 $bytesleft = 1;
00433             } elseif( $bytevalue <= 0xEF ) { //1110 xxxx
00434                 $working = $bytevalue & 0x0F;
00435                 $bytesleft = 2;
00436             } else { //1111 0xxx
00437                 $working = $bytevalue & 0x07;
00438                 $bytesleft = 3;
00439             }
00440         }
00441         return $result;
00442     }
00443 
00445     const ICONV_OK = 0;
00446 
00449     const ICONV_TRUNCATES = 1;
00450 
00453     const ICONV_UNUSABLE = 2;
00454 
00469     public static function testIconvTruncateBug() {
00470         static $code = null;
00471         if ($code === null) {
00472             // better not use iconv, otherwise infinite loop!
00473             $r = self::unsafeIconv('utf-8', 'ascii//IGNORE', "\xCE\xB1" . str_repeat('a', 9000));
00474             if ($r === false) {
00475                 $code = self::ICONV_UNUSABLE;
00476             } elseif (($c = strlen($r)) < 9000) {
00477                 $code = self::ICONV_TRUNCATES;
00478             } elseif ($c > 9000) {
00479                 trigger_error('Your copy of iconv is extremely buggy. Please notify HTML Purifier maintainers: include your iconv version as per phpversion()', E_USER_ERROR);
00480             } else {
00481                 $code = self::ICONV_OK;
00482             }
00483         }
00484         return $code;
00485     }
00486 
00498     public static function testEncodingSupportsASCII($encoding, $bypass = false) {
00499         // All calls to iconv here are unsafe, proof by case analysis:
00500         // If ICONV_OK, no difference.
00501         // If ICONV_TRUNCATE, all calls involve one character inputs,
00502         // so bug is not triggered.
00503         // If ICONV_UNUSABLE, this call is irrelevant
00504         static $encodings = array();
00505         if (!$bypass) {
00506             if (isset($encodings[$encoding])) return $encodings[$encoding];
00507             $lenc = strtolower($encoding);
00508             switch ($lenc) {
00509                 case 'shift_jis':
00510                     return array("\xC2\xA5" => '\\', "\xE2\x80\xBE" => '~');
00511                 case 'johab':
00512                     return array("\xE2\x82\xA9" => '\\');
00513             }
00514             if (strpos($lenc, 'iso-8859-') === 0) return array();
00515         }
00516         $ret = array();
00517         if (self::unsafeIconv('UTF-8', $encoding, 'a') === false) return false;
00518         for ($i = 0x20; $i <= 0x7E; $i++) { // all printable ASCII chars
00519             $c = chr($i); // UTF-8 char
00520             $r = self::unsafeIconv('UTF-8', "$encoding//IGNORE", $c); // initial conversion
00521             if (
00522                 $r === '' ||
00523                 // This line is needed for iconv implementations that do not
00524                 // omit characters that do not exist in the target character set
00525                 ($r === $c && self::unsafeIconv($encoding, 'UTF-8//IGNORE', $r) !== $c)
00526             ) {
00527                 // Reverse engineer: what's the UTF-8 equiv of this byte
00528                 // sequence? This assumes that there's no variable width
00529                 // encoding that doesn't support ASCII.
00530                 $ret[self::unsafeIconv($encoding, 'UTF-8//IGNORE', $c)] = $c;
00531             }
00532         }
00533         $encodings[$encoding] = $ret;
00534         return $ret;
00535     }
00536 
00537 
00538 }
00539 
00540 // vim: et sw=4 sts=4