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