3 namespace PhpXmlRpc\Helper;
5 use PhpXmlRpc\PhpXmlRpc;
8 * @todo implement an interface
12 // tables used for transcoding different charsets into us-ascii xml
13 protected $xml_iso88591_Entities = array("in" => array(), "out" => array());
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?
23 //protected $xml_cp1252_Entities = array('in' => array(), out' => array());
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',),
33 /** @var Charset $instance */
34 protected static $instance = null;
37 * This class is singleton for performance reasons.
38 * @todo should we just make $xml_iso88591_Entities a static variable instead ?
42 public static function instance()
44 if (self::$instance === null) {
45 self::$instance = new static();
48 return self::$instance;
52 * Force usage as singleton
54 protected function __construct()
59 * @param string $tableName
60 * @throws \Exception for unsupported $tableName
62 protected function buildConversionTable($tableName)
65 case 'xml_iso88591_Entities':
66 if (count($this->xml_iso88591_Entities['in'])) {
69 for ($i = 0; $i < 32; $i++) {
70 $this->xml_iso88591_Entities["in"][] = chr($i);
71 $this->xml_iso88591_Entities["out"][] = "&#{$i};";
74 for ($i = 160; $i < 256; $i++) {
75 $this->xml_iso88591_Entities["in"][] = chr($i);
76 $this->xml_iso88591_Entities["out"][] = "&#{$i};";
79 /*case 'xml_cp1252_Entities':
80 if (count($this->xml_cp1252_Entities['in'])) {
83 for ($i = 128; $i < 160; $i++)
85 $this->xml_cp1252_Entities['in'][] = chr($i);
87 $this->xml_cp1252_Entities['out'] = array(
88 '€', '?', '‚', 'ƒ',
89 '„', '…', '†', '‡',
90 'ˆ', '‰', 'Š', '‹',
91 'Œ', '?', 'Ž', '?',
92 '?', '‘', '’', '“',
93 '”', '•', '–', '—',
94 '˜', '™', 'š', '›',
95 'œ', '?', 'ž', 'Ÿ'
97 $this->buildConversionTable('xml_iso88591_Entities');
100 throw new \Exception('Unsupported table: ' . $tableName);
105 * Convert a string to the correct XML representation in a target charset.
107 * - character transformation for all characters which have a different representation in source and dest charsets
108 * - using 'charset entity' representation for all characters which are outside of the target charset
110 * To help correct communication of non-ascii chars inside strings, regardless of the charset used when sending
111 * requests, parsing them, sending responses and parsing responses, an option is to convert all non-ascii chars
112 * present in the message into their equivalent 'charset entity'. Charset entities enumerated this way are
113 * independent of the charset encoding used to transmit them, and all XML parsers are bound to understand them.
115 * Note that when not sending a charset encoding mime type along with http headers, we are bound by RFC 3023 to emit
116 * strict us-ascii for 'text/xml' payloads (but we should review RFC 7303, which seems to have changed the rules...)
118 * @todo do a bit of basic benchmarking (strtr vs. str_replace)
119 * @todo make usage of iconv() or mb_string() where available
120 * @todo support aliases for charset names, eg ASCII, LATIN1, ISO-88591 (see f.e. polyfill-iconv for a list)
122 * @param string $data
123 * @param string $srcEncoding
124 * @param string $destEncoding
128 public function encodeEntities($data, $srcEncoding = '', $destEncoding = '')
130 if ($srcEncoding == '') {
131 // lame, but we know no better...
132 $srcEncoding = PhpXmlRpc::$xmlrpc_internalencoding;
135 $conversion = strtoupper($srcEncoding . '_' . $destEncoding);
136 switch ($conversion) {
138 case 'ISO-8859-1_US-ASCII':
139 $this->buildConversionTable('xml_iso88591_Entities');
140 $escapedData = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $data);
141 $escapedData = str_replace($this->xml_iso88591_Entities['in'], $this->xml_iso88591_Entities['out'], $escapedData);
144 case 'ISO-8859-1_UTF-8':
145 $escapedData = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $data);
146 $escapedData = utf8_encode($escapedData);
149 case 'ISO-8859-1_ISO-8859-1':
150 case 'US-ASCII_US-ASCII':
151 case 'US-ASCII_UTF-8':
153 case 'US-ASCII_ISO-8859-1':
155 //case 'CP1252_CP1252':
156 $escapedData = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $data);
160 case 'UTF-8_US-ASCII':
161 case 'UTF-8_ISO-8859-1':
162 // NB: this will choke on invalid UTF-8, going most likely beyond EOF
164 // be kind to users creating string xmlrpc values out of different php types
165 $data = (string)$data;
167 for ($nn = 0; $nn < $ns; $nn++) {
170 // 7 bits: 0bbbbbbb (127)
172 /// @todo shall we replace this with a (supposedly) faster str_replace?
175 $escapedData .= '"';
178 $escapedData .= '&';
181 $escapedData .= ''';
184 $escapedData .= '<';
187 $escapedData .= '>';
192 } // 11 bits: 110bbbbb 10bbbbbb (2047)
193 elseif ($ii >> 5 == 6) {
195 $ii = ord($data[$nn + 1]);
197 $ii = ($b1 * 64) + $b2;
198 $ent = sprintf('&#%d;', $ii);
199 $escapedData .= $ent;
201 } // 16 bits: 1110bbbb 10bbbbbb 10bbbbbb
202 elseif ($ii >> 4 == 14) {
204 $ii = ord($data[$nn + 1]);
206 $ii = ord($data[$nn + 2]);
208 $ii = ((($b1 * 64) + $b2) * 64) + $b3;
209 $ent = sprintf('&#%d;', $ii);
210 $escapedData .= $ent;
212 } // 21 bits: 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
213 elseif ($ii >> 3 == 30) {
215 $ii = ord($data[$nn + 1]);
217 $ii = ord($data[$nn + 2]);
219 $ii = ord($data[$nn + 3]);
221 $ii = ((((($b1 * 64) + $b2) * 64) + $b3) * 64) + $b4;
222 $ent = sprintf('&#%d;', $ii);
223 $escapedData .= $ent;
228 // when converting to latin-1, do not be so eager with using entities for characters 160-255
229 if ($conversion == 'UTF-8_ISO-8859-1') {
230 $this->buildConversionTable('xml_iso88591_Entities');
231 $escapedData = str_replace(array_slice($this->xml_iso88591_Entities['out'], 32), array_slice($this->xml_iso88591_Entities['in'], 32), $escapedData);
237 case 'CP1252_US-ASCII':
238 $this->buildConversionTable('xml_cp1252_Entities');
239 $escapedData = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $data);
240 $escapedData = str_replace($this->xml_iso88591_Entities']['in'], $this->xml_iso88591_Entities['out'], $escapedData);
241 $escapedData = str_replace($this->xml_cp1252_Entities['in'], $this->xml_cp1252_Entities['out'], $escapedData);
244 $this->buildConversionTable('xml_cp1252_Entities');
245 $escapedData = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $data);
246 /// @todo we could use real UTF8 chars here instead of xml entities... (note that utf_8 encode all alone will NOT convert them)
247 $escapedData = str_replace($this->xml_cp1252_Entities['in'], $this->xml_cp1252_Entities['out'], $escapedData);
248 $escapedData = utf8_encode($escapedData);
250 case 'CP1252_ISO-8859-1':
251 $this->buildConversionTable('xml_cp1252_Entities');
252 $escapedData = str_replace(array('&', '"', "'", '<', '>'), array('&', '"', ''', '<', '>'), $data);
253 // 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...
254 $escapedData = str_replace($this->xml_cp1252_Entities['in'], $this->xml_cp1252_Entities['out'], $escapedData);
260 Logger::instance()->errorLog('XML-RPC: ' . __METHOD__ . ": Converting from $srcEncoding to $destEncoding: not supported...");
267 * Checks if a given charset encoding is present in a list of encodings or if it is a valid subset of any encoding
270 * @param string $encoding charset to be tested
271 * @param string|array $validList comma separated list of valid charsets (or array of charsets)
275 public function isValidCharset($encoding, $validList)
277 if (is_string($validList)) {
278 $validList = explode(',', $validList);
280 if (@in_array(strtoupper($encoding), $validList)) {
283 if (array_key_exists($encoding, $this->charset_supersets)) {
284 foreach ($validList as $allowed) {
285 if (in_array($allowed, $this->charset_supersets[$encoding])) {
296 * Used only for backwards compatibility
299 * @param string $charset
303 * @throws \Exception for unknown/unsupported charsets
305 public function getEntities($charset)
307 //trigger_error('Method ' . __METHOD__ . ' is deprecated', E_USER_DEPRECATED);
312 return $this->xml_iso88591_Entities;
314 throw new \Exception('Unsupported charset: ' . $charset);