WIP introduce namespaces; move all global functions and variables to classes
[plcapi.git] / src / Helper / Charset.php
1 <?php
2
3 namespace PhpXmlRpc\Helper;
4
5 use PhpXmlRpc\PhpXmlRpc;
6
7 class Charset
8 {
9
10     // tables used for transcoding different charsets into us-ascii xml
11     protected $xml_iso88591_Entities = array("in" => array(), "out" => array());
12
13     /// @todo add to iso table the characters from cp_1252 range, i.e. 128 to 159?
14     /// These will NOT be present in true ISO-8859-1, but will save the unwary
15     /// windows user from sending junk (though no luck when receiving them...)
16     /*
17     protected $xml_cp1252_Entities = array('in' => array(), out' => array(
18         '&#x20AC;', '?',        '&#x201A;', '&#x0192;',
19         '&#x201E;', '&#x2026;', '&#x2020;', '&#x2021;',
20         '&#x02C6;', '&#x2030;', '&#x0160;', '&#x2039;',
21         '&#x0152;', '?',        '&#x017D;', '?',
22         '?',        '&#x2018;', '&#x2019;', '&#x201C;',
23         '&#x201D;', '&#x2022;', '&#x2013;', '&#x2014;',
24         '&#x02DC;', '&#x2122;', '&#x0161;', '&#x203A;',
25         '&#x0153;', '?',        '&#x017E;', '&#x0178;'
26     ));
27     */
28
29     protected $charset_supersets = array(
30         'US-ASCII' => array ('ISO-8859-1', 'ISO-8859-2', 'ISO-8859-3', 'ISO-8859-4',
31             'ISO-8859-5', 'ISO-8859-6', 'ISO-8859-7', 'ISO-8859-8',
32             'ISO-8859-9', 'ISO-8859-10', 'ISO-8859-11', 'ISO-8859-12',
33             'ISO-8859-13', 'ISO-8859-14', 'ISO-8859-15', 'UTF-8',
34             'EUC-JP', 'EUC-', 'EUC-KR', 'EUC-CN')
35     );
36
37     protected static $instance = null;
38
39     /**
40      * This class is singleton for performance reasons
41      * @return Charset
42      */
43     public static function instance()
44     {
45         if(self::$instance === null)
46         {
47             self::$instance = new self();
48         }
49
50         return self::$instance;
51     }
52
53     private function __construct()
54     {
55         for($i = 0; $i < 32; $i++) {
56             $this->xml_iso88591_Entities["in"][] = chr($i);
57             $this->xml_iso88591_Entities["out"][] = "&#{$i};";
58         }
59
60         for($i = 160; $i < 256; $i++) {
61             $this->xml_iso88591_Entities["in"][] = chr($i);
62             $this->xml_iso88591_Entities["out"][] = "&#{$i};";
63         }
64
65         /*for ($i = 128; $i < 160; $i++)
66         {
67             $this->xml_cp1252_Entities['in'][] = chr($i);
68         }*/
69
70     }
71
72     /**
73      * Convert a string to the correct XML representation in a target charset
74      * To help correct communication of non-ascii chars inside strings, regardless
75      * of the charset used when sending requests, parsing them, sending responses
76      * and parsing responses, an option is to convert all non-ascii chars present in the message
77      * into their equivalent 'charset entity'. Charset entities enumerated this way
78      * are independent of the charset encoding used to transmit them, and all XML
79      * parsers are bound to understand them.
80      * Note that in the std case we are not sending a charset encoding mime type
81      * along with http headers, so we are bound by RFC 3023 to emit strict us-ascii.
82      *
83      * @todo do a bit of basic benchmarking (strtr vs. str_replace)
84      * @todo make usage of iconv() or recode_string() or mb_string() where available
85      *
86      * @param string $data
87      * @param string $src_encoding
88      * @param string $dest_encoding
89      * @return string
90      */
91     public function encode_entities($data, $src_encoding='', $dest_encoding='')
92     {
93         if ($src_encoding == '')
94         {
95             // lame, but we know no better...
96             $src_encoding = PhpXmlRpc::$xmlrpc_internalencoding;
97         }
98
99         switch(strtoupper($src_encoding.'_'.$dest_encoding))
100         {
101             case 'ISO-8859-1_':
102             case 'ISO-8859-1_US-ASCII':
103                 $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&apos;', '&lt;', '&gt;'), $data);
104                 $escaped_data = str_replace($this->xml_iso88591_Entities['in'], $this->xml_iso88591_Entities['out'], $escaped_data);
105                 break;
106             case 'ISO-8859-1_UTF-8':
107                 $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&apos;', '&lt;', '&gt;'), $data);
108                 $escaped_data = utf8_encode($escaped_data);
109                 break;
110             case 'ISO-8859-1_ISO-8859-1':
111             case 'US-ASCII_US-ASCII':
112             case 'US-ASCII_UTF-8':
113             case 'US-ASCII_':
114             case 'US-ASCII_ISO-8859-1':
115             case 'UTF-8_UTF-8':
116                 //case 'CP1252_CP1252':
117                 $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&apos;', '&lt;', '&gt;'), $data);
118                 break;
119             case 'UTF-8_':
120             case 'UTF-8_US-ASCII':
121             case 'UTF-8_ISO-8859-1':
122                 // NB: this will choke on invalid UTF-8, going most likely beyond EOF
123                 $escaped_data = '';
124                 // be kind to users creating string xmlrpcvals out of different php types
125                 $data = (string) $data;
126                 $ns = strlen ($data);
127                 for ($nn = 0; $nn < $ns; $nn++)
128                 {
129                     $ch = $data[$nn];
130                     $ii = ord($ch);
131                     //1 7 0bbbbbbb (127)
132                     if ($ii < 128)
133                     {
134                         /// @todo shall we replace this with a (supposedly) faster str_replace?
135                         switch($ii){
136                             case 34:
137                                 $escaped_data .= '&quot;';
138                                 break;
139                             case 38:
140                                 $escaped_data .= '&amp;';
141                                 break;
142                             case 39:
143                                 $escaped_data .= '&apos;';
144                                 break;
145                             case 60:
146                                 $escaped_data .= '&lt;';
147                                 break;
148                             case 62:
149                                 $escaped_data .= '&gt;';
150                                 break;
151                             default:
152                                 $escaped_data .= $ch;
153                         } // switch
154                     }
155                     //2 11 110bbbbb 10bbbbbb (2047)
156                     else if ($ii>>5 == 6)
157                     {
158                         $b1 = ($ii & 31);
159                         $ii = ord($data[$nn+1]);
160                         $b2 = ($ii & 63);
161                         $ii = ($b1 * 64) + $b2;
162                         $ent = sprintf ('&#%d;', $ii);
163                         $escaped_data .= $ent;
164                         $nn += 1;
165                     }
166                     //3 16 1110bbbb 10bbbbbb 10bbbbbb
167                     else if ($ii>>4 == 14)
168                     {
169                         $b1 = ($ii & 15);
170                         $ii = ord($data[$nn+1]);
171                         $b2 = ($ii & 63);
172                         $ii = ord($data[$nn+2]);
173                         $b3 = ($ii & 63);
174                         $ii = ((($b1 * 64) + $b2) * 64) + $b3;
175                         $ent = sprintf ('&#%d;', $ii);
176                         $escaped_data .= $ent;
177                         $nn += 2;
178                     }
179                     //4 21 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
180                     else if ($ii>>3 == 30)
181                     {
182                         $b1 = ($ii & 7);
183                         $ii = ord($data[$nn+1]);
184                         $b2 = ($ii & 63);
185                         $ii = ord($data[$nn+2]);
186                         $b3 = ($ii & 63);
187                         $ii = ord($data[$nn+3]);
188                         $b4 = ($ii & 63);
189                         $ii = ((((($b1 * 64) + $b2) * 64) + $b3) * 64) + $b4;
190                         $ent = sprintf ('&#%d;', $ii);
191                         $escaped_data .= $ent;
192                         $nn += 3;
193                     }
194                 }
195                 break;
196             /*
197             case 'CP1252_':
198             case 'CP1252_US-ASCII':
199                 $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&apos;', '&lt;', '&gt;'), $data);
200                 $escaped_data = str_replace($this->xml_iso88591_Entities']['in'], $this->xml_iso88591_Entities['out'], $escaped_data);
201                 $escaped_data = str_replace($this->xml_cp1252_Entities['in'], $this->xml_cp1252_Entities['out'], $escaped_data);
202                 break;
203             case 'CP1252_UTF-8':
204                 $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&apos;', '&lt;', '&gt;'), $data);
205                 /// @todo we could use real UTF8 chars here instead of xml entities... (note that utf_8 encode all allone will NOT convert them)
206                 $escaped_data = str_replace($this->xml_cp1252_Entities['in'], $this->xml_cp1252_Entities['out'], $escaped_data);
207                 $escaped_data = utf8_encode($escaped_data);
208                 break;
209             case 'CP1252_ISO-8859-1':
210                 $escaped_data = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&apos;', '&lt;', '&gt;'), $data);
211                 // we might as well replace all funky chars with a '?' here, but we are kind and leave it to the receiving application layer to decide what to do with these weird entities...
212                 $escaped_data = str_replace($this->xml_cp1252_Entities['in'], $this->xml_cp1252_Entities['out'], $escaped_data);
213                 break;
214             */
215             default:
216                 $escaped_data = '';
217                 error_log("Converting from $src_encoding to $dest_encoding: not supported...");
218         }
219         return $escaped_data;
220     }
221
222     /**
223      * Checks if a given charset encoding is present in a list of encodings or
224      * if it is a valid subset of any encoding in the list
225      * @param string $encoding charset to be tested
226      * @param string|array $validList comma separated list of valid charsets (or array of charsets)
227      * @return bool
228      */
229     public function is_valid_charset($encoding, $validList)
230     {
231
232         if (is_string($validList))
233             $validList = explode(',', $validList);
234         if (@in_array(strtoupper($encoding), $validList))
235             return true;
236         else
237         {
238             if (array_key_exists($encoding, $this->charset_supersets))
239                 foreach ($validList as $allowed)
240                     if (in_array($allowed, $this->charset_supersets[$encoding]))
241                         return true;
242             return false;
243         }
244     }
245
246 }