Charset.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. <?php
  2. namespace PhpXmlRpc\Helper;
  3. use PhpXmlRpc\Exception\ValueErrorException;
  4. use PhpXmlRpc\PhpXmlRpc;
  5. use PhpXmlRpc\Traits\DeprecationLogger;
  6. /**
  7. * @todo implement an interface
  8. */
  9. class Charset
  10. {
  11. use DeprecationLogger;
  12. // tables used for transcoding different charsets into us-ascii xml
  13. protected $xml_iso88591_Entities = array("in" => array(), "out" => array());
  14. //protected $xml_cp1252_Entities = array('in' => array(), out' => array());
  15. protected $charset_supersets = array(
  16. 'US-ASCII' => array('ISO-8859-1', 'ISO-8859-2', 'ISO-8859-3', 'ISO-8859-4',
  17. 'ISO-8859-5', 'ISO-8859-6', 'ISO-8859-7', 'ISO-8859-8',
  18. 'ISO-8859-9', 'ISO-8859-10', 'ISO-8859-11', 'ISO-8859-12',
  19. 'ISO-8859-13', 'ISO-8859-14', 'ISO-8859-15', 'UTF-8',
  20. 'EUC-JP', 'EUC-', 'EUC-KR', 'EUC-CN',),
  21. );
  22. /** @var Charset $instance */
  23. protected static $instance = null;
  24. /**
  25. * This class is singleton for performance reasons.
  26. *
  27. * @return Charset
  28. *
  29. * @todo should we just make $xml_iso88591_Entities a static variable instead ?
  30. */
  31. public static function instance()
  32. {
  33. if (self::$instance === null) {
  34. self::$instance = new static();
  35. }
  36. return self::$instance;
  37. }
  38. /**
  39. * Force usage as singleton.
  40. */
  41. protected function __construct()
  42. {
  43. }
  44. /**
  45. * @param string $tableName
  46. * @return void
  47. * @throws ValueErrorException for unsupported $tableName
  48. *
  49. * @todo add support for cp1252 as well as latin-2 .. latin-10
  50. * Optimization creep: instead of building all those tables on load, keep them ready-made php files
  51. * which are not even included until needed
  52. * @todo should we add to the latin-1 table the characters from cp_1252 range, i.e. 128 to 159 ?
  53. * Those will NOT be present in true ISO-8859-1, but will save the unwary windows user from sending junk
  54. * (though no luck when receiving them...)
  55. * Note also that, apparently, while 'ISO/IEC 8859-1' has no characters defined for bytes 128 to 159,
  56. * IANA ISO-8859-1 does have well-defined 'C1' control codes for those - wikipedia's page on latin-1 says:
  57. * "ISO-8859-1 is the IANA preferred name for this standard when supplemented with the C0 and C1 control codes
  58. * from ISO/IEC 6429." Check what mbstring/iconv do by default with those?
  59. */
  60. protected function buildConversionTable($tableName)
  61. {
  62. switch ($tableName) {
  63. case 'xml_iso88591_Entities':
  64. if (count($this->xml_iso88591_Entities['in'])) {
  65. return;
  66. }
  67. for ($i = 0; $i < 32; $i++) {
  68. $this->xml_iso88591_Entities["in"][] = chr($i);
  69. $this->xml_iso88591_Entities["out"][] = "&#{$i};";
  70. }
  71. /// @todo to be 'print safe', should we encode as well character 127 (DEL) ?
  72. for ($i = 160; $i < 256; $i++) {
  73. $this->xml_iso88591_Entities["in"][] = chr($i);
  74. $this->xml_iso88591_Entities["out"][] = "&#{$i};";
  75. }
  76. break;
  77. /*case 'xml_cp1252_Entities':
  78. if (count($this->xml_cp1252_Entities['in'])) {
  79. return;
  80. }
  81. for ($i = 128; $i < 160; $i++)
  82. {
  83. $this->xml_cp1252_Entities['in'][] = chr($i);
  84. }
  85. $this->xml_cp1252_Entities['out'] = array(
  86. '&#x20AC;', '?', '&#x201A;', '&#x0192;',
  87. '&#x201E;', '&#x2026;', '&#x2020;', '&#x2021;',
  88. '&#x02C6;', '&#x2030;', '&#x0160;', '&#x2039;',
  89. '&#x0152;', '?', '&#x017D;', '?',
  90. '?', '&#x2018;', '&#x2019;', '&#x201C;',
  91. '&#x201D;', '&#x2022;', '&#x2013;', '&#x2014;',
  92. '&#x02DC;', '&#x2122;', '&#x0161;', '&#x203A;',
  93. '&#x0153;', '?', '&#x017E;', '&#x0178;'
  94. );
  95. $this->buildConversionTable('xml_iso88591_Entities');
  96. break;*/
  97. default:
  98. throw new ValueErrorException('Unsupported table: ' . $tableName);
  99. }
  100. }
  101. /**
  102. * Convert a string to the correct XML representation in a target charset.
  103. * This involves:
  104. * - character transformation for all characters which have a different representation in source and dest charsets
  105. * - using 'charset entity' representation for all characters which are outside the 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. *
  112. * Note that when not sending a charset encoding mime type along with http headers, we are bound by RFC 3023 to emit
  113. * strict us-ascii for 'text/xml' payloads (but we should review RFC 7303, which seems to have changed the rules...)
  114. *
  115. * @param string $data
  116. * @param string $srcEncoding
  117. * @param string $destEncoding
  118. * @return string
  119. *
  120. * @todo do a bit of basic benchmarking: strtr vs. str_replace, str_replace vs htmlspecialchars, hand-coded conversion
  121. * vs mbstring when that is enabled
  122. * @todo make use of iconv when it is available and mbstring is not
  123. * @todo support aliases for charset names, eg ASCII, LATIN1, ISO-88591 (see f.e. polyfill-iconv for a list),
  124. * but then take those into account as well in other methods, ie. isValidCharset)
  125. * @todo when converting to ASCII, allow to choose whether to escape the range 0-31,127 (non-print chars) or not
  126. * @todo allow picking different strategies to deal w. invalid chars? eg. source in latin-1 and chars 128-159
  127. * @todo add support for escaping using CDATA sections? (add cdata start and end tokens, replace only ']]>' with ']]]]><![CDATA[>')
  128. */
  129. public function encodeEntities($data, $srcEncoding = '', $destEncoding = '')
  130. {
  131. if ($srcEncoding == '') {
  132. // lame, but we know no better...
  133. $srcEncoding = PhpXmlRpc::$xmlrpc_internalencoding;
  134. }
  135. if ($destEncoding == '') {
  136. $destEncoding = 'US-ASCII';
  137. }
  138. // in case there is transcoding going on, let's upscale to UTF8
  139. /// @todo we should do this as well when $srcEncoding == $destEncoding and the encoding is not supported by
  140. /// htmlspecialchars
  141. if (!in_array($srcEncoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII')) && $srcEncoding != $destEncoding &&
  142. function_exists('mb_convert_encoding')) {
  143. $data = mb_convert_encoding($data, 'UTF-8', str_replace('US-ASCII', 'ASCII', $srcEncoding));
  144. $srcEncoding = 'UTF-8';
  145. }
  146. $conversion = strtoupper($srcEncoding . '_' . $destEncoding);
  147. // list ordered with (expected) most common scenarios first
  148. switch ($conversion) {
  149. case 'UTF-8_UTF-8':
  150. case 'ISO-8859-1_ISO-8859-1':
  151. case 'US-ASCII_UTF-8':
  152. case 'US-ASCII_US-ASCII':
  153. case 'US-ASCII_ISO-8859-1':
  154. //case 'CP1252_CP1252':
  155. $escapedData = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&apos;', '&lt;', '&gt;'), $data);
  156. break;
  157. case 'UTF-8_US-ASCII':
  158. case 'UTF-8_ISO-8859-1':
  159. // NB: this will choke on invalid UTF-8, going most likely beyond EOF
  160. $escapedData = '';
  161. // be kind to users creating string xml-rpc values out of different php types
  162. $data = (string)$data;
  163. $ns = strlen($data);
  164. for ($nn = 0; $nn < $ns; $nn++) {
  165. $ch = $data[$nn];
  166. $ii = ord($ch);
  167. // 7 bits in 1 byte: 0bbbbbbb (127)
  168. if ($ii < 32) {
  169. if ($conversion == 'UTF-8_US-ASCII') {
  170. $escapedData .= sprintf('&#%d;', $ii);
  171. } else {
  172. $escapedData .= $ch;
  173. }
  174. }
  175. else if ($ii < 128) {
  176. /// @todo shall we replace this with a (supposedly) faster str_replace?
  177. /// @todo to be 'print safe', should we encode as well character 127 (DEL) ?
  178. switch ($ii) {
  179. case 34:
  180. $escapedData .= '&quot;';
  181. break;
  182. case 38:
  183. $escapedData .= '&amp;';
  184. break;
  185. case 39:
  186. $escapedData .= '&apos;';
  187. break;
  188. case 60:
  189. $escapedData .= '&lt;';
  190. break;
  191. case 62:
  192. $escapedData .= '&gt;';
  193. break;
  194. default:
  195. $escapedData .= $ch;
  196. } // switch
  197. } // 11 bits in 2 bytes: 110bbbbb 10bbbbbb (2047)
  198. elseif ($ii >> 5 == 6) {
  199. $b1 = ($ii & 31);
  200. $b2 = (ord($data[$nn + 1]) & 63);
  201. $ii = ($b1 * 64) + $b2;
  202. $escapedData .= sprintf('&#%d;', $ii);
  203. $nn += 1;
  204. } // 16 bits in 3 bytes: 1110bbbb 10bbbbbb 10bbbbbb
  205. elseif ($ii >> 4 == 14) {
  206. $b1 = ($ii & 15);
  207. $b2 = (ord($data[$nn + 1]) & 63);
  208. $b3 = (ord($data[$nn + 2]) & 63);
  209. $ii = ((($b1 * 64) + $b2) * 64) + $b3;
  210. $escapedData .= sprintf('&#%d;', $ii);
  211. $nn += 2;
  212. } // 21 bits in 4 bytes: 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
  213. elseif ($ii >> 3 == 30) {
  214. $b1 = ($ii & 7);
  215. $b2 = (ord($data[$nn + 1]) & 63);
  216. $b3 = (ord($data[$nn + 2]) & 63);
  217. $b4 = (ord($data[$nn + 3]) & 63);
  218. $ii = ((((($b1 * 64) + $b2) * 64) + $b3) * 64) + $b4;
  219. $escapedData .= sprintf('&#%d;', $ii);
  220. $nn += 3;
  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. case 'ISO-8859-1_UTF-8':
  230. $escapedData = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&apos;', '&lt;', '&gt;'), $data);
  231. /// @todo if on php >= 8.2, prefer using mbstring or iconv. Also: suppress the warning!
  232. if (function_exists('mb_convert_encoding')) {
  233. $escapedData = mb_convert_encoding($escapedData, 'UTF-8', 'ISO-8859-1');
  234. } else {
  235. $escapedData = utf8_encode($escapedData);
  236. }
  237. break;
  238. case 'ISO-8859-1_US-ASCII':
  239. $this->buildConversionTable('xml_iso88591_Entities');
  240. $escapedData = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&apos;', '&lt;', '&gt;'), $data);
  241. $escapedData = str_replace($this->xml_iso88591_Entities['in'], $this->xml_iso88591_Entities['out'], $escapedData);
  242. break;
  243. /*
  244. case 'CP1252_US-ASCII':
  245. $this->buildConversionTable('xml_cp1252_Entities');
  246. $escapedData = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&apos;', '&lt;', '&gt;'), $data);
  247. $escapedData = str_replace($this->xml_iso88591_Entities']['in'], $this->xml_iso88591_Entities['out'], $escapedData);
  248. $escapedData = str_replace($this->xml_cp1252_Entities['in'], $this->xml_cp1252_Entities['out'], $escapedData);
  249. break;
  250. case 'CP1252_UTF-8':
  251. $this->buildConversionTable('xml_cp1252_Entities');
  252. $escapedData = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&apos;', '&lt;', '&gt;'), $data);
  253. /// @todo we could use real UTF8 chars here instead of xml entities... (note that utf_8 encode all alone will NOT convert them)
  254. $escapedData = str_replace($this->xml_cp1252_Entities['in'], $this->xml_cp1252_Entities['out'], $escapedData);
  255. $escapedData = utf8_encode($escapedData);
  256. break;
  257. case 'CP1252_ISO-8859-1':
  258. $this->buildConversionTable('xml_cp1252_Entities');
  259. $escapedData = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&apos;', '&lt;', '&gt;'), $data);
  260. // 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...
  261. $escapedData = str_replace($this->xml_cp1252_Entities['in'], $this->xml_cp1252_Entities['out'], $escapedData);
  262. break;
  263. */
  264. default:
  265. if (function_exists('mb_convert_encoding')) {
  266. // If reaching where, there are only 2 cases possible: UTF8->XXX or XXX->XXX
  267. // If src is UTF8, we run htmlspecialchars before converting to the target charset, as
  268. // htmlspecialchars has limited charset support, but it groks utf8
  269. if ($srcEncoding === 'UTF-8') {
  270. $data = htmlspecialchars($data, defined('ENT_XML1') ? ENT_XML1 | ENT_QUOTES : ENT_QUOTES, 'UTF-8');
  271. }
  272. if ($srcEncoding !== $destEncoding) {
  273. try {
  274. // php 7.4 and lower: a warning is generated. php 8.0 and up: an Error is thrown. So much for BC...
  275. $data = @mb_convert_encoding($data, str_replace('US-ASCII', 'ASCII', $destEncoding), str_replace('US-ASCII', 'ASCII', $srcEncoding));
  276. } catch (\ValueError $e) {
  277. $data = false;
  278. }
  279. }
  280. if ($data === false) {
  281. $escapedData = '';
  282. $this->getLogger()->error('XML-RPC: ' . __METHOD__ . ": Converting from $srcEncoding to $destEncoding via mbstring: failed...");
  283. } else {
  284. if ($srcEncoding === 'UTF-8') {
  285. $escapedData = $data;
  286. } else {
  287. $escapedData = htmlspecialchars($data, defined('ENT_XML1') ? ENT_XML1 | ENT_QUOTES : ENT_QUOTES, $destEncoding);
  288. }
  289. }
  290. } else {
  291. $escapedData = '';
  292. $this->getLogger()->error('XML-RPC: ' . __METHOD__ . ": Converting from $srcEncoding to $destEncoding: not supported...");
  293. }
  294. }
  295. return $escapedData;
  296. }
  297. /**
  298. * @return string[]
  299. */
  300. public function knownCharsets()
  301. {
  302. $knownCharsets = array('UTF-8', 'ISO-8859-1', 'US-ASCII');
  303. // Add all charsets which mbstring can handle, but remove junk not found in IANA registry at
  304. // http://www.iana.org/assignments/character-sets/character-sets.xhtml
  305. if (function_exists('mb_list_encodings')) {
  306. $knownCharsets = array_unique(array_merge($knownCharsets, array_diff(mb_list_encodings(), array(
  307. 'pass', 'auto', 'wchar', 'BASE64', 'UUENCODE', 'ASCII', 'HTML-ENTITIES', 'Quoted-Printable',
  308. '7bit','8bit', 'byte2be', 'byte2le', 'byte4be', 'byte4le'
  309. ))));
  310. }
  311. return $knownCharsets;
  312. }
  313. // *** BC layer ***
  314. /**
  315. * Checks if a given charset encoding is present in a list of encodings or if it is a valid subset of any encoding
  316. * in the list.
  317. * @deprecated kept around for BC, as it is not in use by the lib
  318. *
  319. * @param string $encoding charset to be tested
  320. * @param string|array $validList comma separated list of valid charsets (or array of charsets)
  321. * @return bool
  322. */
  323. public function isValidCharset($encoding, $validList)
  324. {
  325. $this->logDeprecation('Method ' . __METHOD__ . ' is deprecated');
  326. if (is_string($validList)) {
  327. $validList = explode(',', $validList);
  328. }
  329. if (in_array(strtoupper($encoding), $validList)) {
  330. return true;
  331. } else {
  332. if (array_key_exists($encoding, $this->charset_supersets)) {
  333. foreach ($validList as $allowed) {
  334. if (in_array($allowed, $this->charset_supersets[$encoding])) {
  335. return true;
  336. }
  337. }
  338. }
  339. return false;
  340. }
  341. }
  342. /**
  343. * Used only for backwards compatibility (the .inc shims).
  344. * @deprecated
  345. *
  346. * @param string $charset
  347. * @return array
  348. * @throws ValueErrorException for unknown/unsupported charsets
  349. */
  350. public function getEntities($charset)
  351. {
  352. $this->logDeprecation('Method ' . __METHOD__ . ' is deprecated');
  353. switch ($charset)
  354. {
  355. case 'iso88591':
  356. return $this->xml_iso88591_Entities;
  357. default:
  358. throw new ValueErrorException('Unsupported charset: ' . $charset);
  359. }
  360. }
  361. }