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