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