HTMLPurifier 4.4.0
|
00001 <?php 00002 00011 class HTMLPurifier_PercentEncoder 00012 { 00013 00017 protected $preserve = array(); 00018 00022 public function __construct($preserve = false) { 00023 // unreserved letters, ought to const-ify 00024 for ($i = 48; $i <= 57; $i++) $this->preserve[$i] = true; // digits 00025 for ($i = 65; $i <= 90; $i++) $this->preserve[$i] = true; // upper-case 00026 for ($i = 97; $i <= 122; $i++) $this->preserve[$i] = true; // lower-case 00027 $this->preserve[45] = true; // Dash - 00028 $this->preserve[46] = true; // Period . 00029 $this->preserve[95] = true; // Underscore _ 00030 $this->preserve[126]= true; // Tilde ~ 00031 00032 // extra letters not to escape 00033 if ($preserve !== false) { 00034 for ($i = 0, $c = strlen($preserve); $i < $c; $i++) { 00035 $this->preserve[ord($preserve[$i])] = true; 00036 } 00037 } 00038 } 00039 00050 public function encode($string) { 00051 $ret = ''; 00052 for ($i = 0, $c = strlen($string); $i < $c; $i++) { 00053 if ($string[$i] !== '%' && !isset($this->preserve[$int = ord($string[$i])]) ) { 00054 $ret .= '%' . sprintf('%02X', $int); 00055 } else { 00056 $ret .= $string[$i]; 00057 } 00058 } 00059 return $ret; 00060 } 00061 00069 public function normalize($string) { 00070 if ($string == '') return ''; 00071 $parts = explode('%', $string); 00072 $ret = array_shift($parts); 00073 foreach ($parts as $part) { 00074 $length = strlen($part); 00075 if ($length < 2) { 00076 $ret .= '%25' . $part; 00077 continue; 00078 } 00079 $encoding = substr($part, 0, 2); 00080 $text = substr($part, 2); 00081 if (!ctype_xdigit($encoding)) { 00082 $ret .= '%25' . $part; 00083 continue; 00084 } 00085 $int = hexdec($encoding); 00086 if (isset($this->preserve[$int])) { 00087 $ret .= chr($int) . $text; 00088 continue; 00089 } 00090 $encoding = strtoupper($encoding); 00091 $ret .= '%' . $encoding . $text; 00092 } 00093 return $ret; 00094 } 00095 00096 } 00097 00098 // vim: et sw=4 sts=4