PageRenderTime 55ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 1ms

/ext/standard/html.c

http://github.com/php/php-src
C | 1593 lines | 1231 code | 141 blank | 221 comment | 414 complexity | 9a97ad8e71977e24c8b9f178a4af0144 MD5 | raw file
Possible License(s): BSD-2-Clause, BSD-3-Clause, MPL-2.0-no-copyleft-exception, LGPL-2.1
  1. /*
  2. +----------------------------------------------------------------------+
  3. | Copyright (c) The PHP Group |
  4. +----------------------------------------------------------------------+
  5. | This source file is subject to version 3.01 of the PHP license, |
  6. | that is bundled with this package in the file LICENSE, and is |
  7. | available through the world-wide-web at the following url: |
  8. | http://www.php.net/license/3_01.txt |
  9. | If you did not receive a copy of the PHP license and are unable to |
  10. | obtain it through the world-wide-web, please send a note to |
  11. | license@php.net so we can mail you a copy immediately. |
  12. +----------------------------------------------------------------------+
  13. | Authors: Rasmus Lerdorf <rasmus@php.net> |
  14. | Jaakko Hyvätti <jaakko.hyvatti@iki.fi> |
  15. | Wez Furlong <wez@thebrainroom.com> |
  16. | Gustavo Lopes <cataphract@php.net> |
  17. +----------------------------------------------------------------------+
  18. */
  19. /*
  20. * HTML entity resources:
  21. *
  22. * http://www.unicode.org/Public/MAPPINGS/OBSOLETE/UNI2SGML.TXT
  23. *
  24. * XHTML 1.0 DTD
  25. * http://www.w3.org/TR/2002/REC-xhtml1-20020801/dtds.html#h-A2
  26. *
  27. * From HTML 4.01 strict DTD:
  28. * http://www.w3.org/TR/html4/HTMLlat1.ent
  29. * http://www.w3.org/TR/html4/HTMLsymbol.ent
  30. * http://www.w3.org/TR/html4/HTMLspecial.ent
  31. *
  32. * HTML 5:
  33. * http://dev.w3.org/html5/spec/Overview.html#named-character-references
  34. */
  35. #include "php.h"
  36. #ifdef PHP_WIN32
  37. #include "config.w32.h"
  38. #else
  39. #include <php_config.h>
  40. #endif
  41. #include "php_standard.h"
  42. #include "php_string.h"
  43. #include "SAPI.h"
  44. #include <locale.h>
  45. #if HAVE_LANGINFO_H
  46. #include <langinfo.h>
  47. #endif
  48. #include <zend_hash.h>
  49. #include "html_tables.h"
  50. /* Macro for disabling flag of translation of non-basic entities where this isn't supported.
  51. * Not appropriate for html_entity_decode/htmlspecialchars_decode */
  52. #define LIMIT_ALL(all, doctype, charset) do { \
  53. (all) = (all) && !CHARSET_PARTIAL_SUPPORT((charset)) && ((doctype) != ENT_HTML_DOC_XML1); \
  54. } while (0)
  55. #define MB_FAILURE(pos, advance) do { \
  56. *cursor = pos + (advance); \
  57. *status = FAILURE; \
  58. return 0; \
  59. } while (0)
  60. #define CHECK_LEN(pos, chars_need) ((str_len - (pos)) >= (chars_need))
  61. /* valid as single byte character or leading byte */
  62. #define utf8_lead(c) ((c) < 0x80 || ((c) >= 0xC2 && (c) <= 0xF4))
  63. /* whether it's actually valid depends on other stuff;
  64. * this macro cannot check for non-shortest forms, surrogates or
  65. * code points above 0x10FFFF */
  66. #define utf8_trail(c) ((c) >= 0x80 && (c) <= 0xBF)
  67. #define gb2312_lead(c) ((c) != 0x8E && (c) != 0x8F && (c) != 0xA0 && (c) != 0xFF)
  68. #define gb2312_trail(c) ((c) >= 0xA1 && (c) <= 0xFE)
  69. #define sjis_lead(c) ((c) != 0x80 && (c) != 0xA0 && (c) < 0xFD)
  70. #define sjis_trail(c) ((c) >= 0x40 && (c) != 0x7F && (c) < 0xFD)
  71. /* {{{ get_default_charset
  72. */
  73. static char *get_default_charset(void) {
  74. if (PG(internal_encoding) && PG(internal_encoding)[0]) {
  75. return PG(internal_encoding);
  76. } else if (SG(default_charset) && SG(default_charset)[0] ) {
  77. return SG(default_charset);
  78. }
  79. return NULL;
  80. }
  81. /* }}} */
  82. /* {{{ get_next_char
  83. */
  84. static inline unsigned int get_next_char(
  85. enum entity_charset charset,
  86. const unsigned char *str,
  87. size_t str_len,
  88. size_t *cursor,
  89. int *status)
  90. {
  91. size_t pos = *cursor;
  92. unsigned int this_char = 0;
  93. *status = SUCCESS;
  94. assert(pos <= str_len);
  95. if (!CHECK_LEN(pos, 1))
  96. MB_FAILURE(pos, 1);
  97. switch (charset) {
  98. case cs_utf_8:
  99. {
  100. /* We'll follow strategy 2. from section 3.6.1 of UTR #36:
  101. * "In a reported illegal byte sequence, do not include any
  102. * non-initial byte that encodes a valid character or is a leading
  103. * byte for a valid sequence." */
  104. unsigned char c;
  105. c = str[pos];
  106. if (c < 0x80) {
  107. this_char = c;
  108. pos++;
  109. } else if (c < 0xc2) {
  110. MB_FAILURE(pos, 1);
  111. } else if (c < 0xe0) {
  112. if (!CHECK_LEN(pos, 2))
  113. MB_FAILURE(pos, 1);
  114. if (!utf8_trail(str[pos + 1])) {
  115. MB_FAILURE(pos, utf8_lead(str[pos + 1]) ? 1 : 2);
  116. }
  117. this_char = ((c & 0x1f) << 6) | (str[pos + 1] & 0x3f);
  118. if (this_char < 0x80) { /* non-shortest form */
  119. MB_FAILURE(pos, 2);
  120. }
  121. pos += 2;
  122. } else if (c < 0xf0) {
  123. size_t avail = str_len - pos;
  124. if (avail < 3 ||
  125. !utf8_trail(str[pos + 1]) || !utf8_trail(str[pos + 2])) {
  126. if (avail < 2 || utf8_lead(str[pos + 1]))
  127. MB_FAILURE(pos, 1);
  128. else if (avail < 3 || utf8_lead(str[pos + 2]))
  129. MB_FAILURE(pos, 2);
  130. else
  131. MB_FAILURE(pos, 3);
  132. }
  133. this_char = ((c & 0x0f) << 12) | ((str[pos + 1] & 0x3f) << 6) | (str[pos + 2] & 0x3f);
  134. if (this_char < 0x800) { /* non-shortest form */
  135. MB_FAILURE(pos, 3);
  136. } else if (this_char >= 0xd800 && this_char <= 0xdfff) { /* surrogate */
  137. MB_FAILURE(pos, 3);
  138. }
  139. pos += 3;
  140. } else if (c < 0xf5) {
  141. size_t avail = str_len - pos;
  142. if (avail < 4 ||
  143. !utf8_trail(str[pos + 1]) || !utf8_trail(str[pos + 2]) ||
  144. !utf8_trail(str[pos + 3])) {
  145. if (avail < 2 || utf8_lead(str[pos + 1]))
  146. MB_FAILURE(pos, 1);
  147. else if (avail < 3 || utf8_lead(str[pos + 2]))
  148. MB_FAILURE(pos, 2);
  149. else if (avail < 4 || utf8_lead(str[pos + 3]))
  150. MB_FAILURE(pos, 3);
  151. else
  152. MB_FAILURE(pos, 4);
  153. }
  154. this_char = ((c & 0x07) << 18) | ((str[pos + 1] & 0x3f) << 12) | ((str[pos + 2] & 0x3f) << 6) | (str[pos + 3] & 0x3f);
  155. if (this_char < 0x10000 || this_char > 0x10FFFF) { /* non-shortest form or outside range */
  156. MB_FAILURE(pos, 4);
  157. }
  158. pos += 4;
  159. } else {
  160. MB_FAILURE(pos, 1);
  161. }
  162. }
  163. break;
  164. case cs_big5:
  165. /* reference http://demo.icu-project.org/icu-bin/convexp?conv=big5 */
  166. {
  167. unsigned char c = str[pos];
  168. if (c >= 0x81 && c <= 0xFE) {
  169. unsigned char next;
  170. if (!CHECK_LEN(pos, 2))
  171. MB_FAILURE(pos, 1);
  172. next = str[pos + 1];
  173. if ((next >= 0x40 && next <= 0x7E) ||
  174. (next >= 0xA1 && next <= 0xFE)) {
  175. this_char = (c << 8) | next;
  176. } else {
  177. MB_FAILURE(pos, 1);
  178. }
  179. pos += 2;
  180. } else {
  181. this_char = c;
  182. pos += 1;
  183. }
  184. }
  185. break;
  186. case cs_big5hkscs:
  187. {
  188. unsigned char c = str[pos];
  189. if (c >= 0x81 && c <= 0xFE) {
  190. unsigned char next;
  191. if (!CHECK_LEN(pos, 2))
  192. MB_FAILURE(pos, 1);
  193. next = str[pos + 1];
  194. if ((next >= 0x40 && next <= 0x7E) ||
  195. (next >= 0xA1 && next <= 0xFE)) {
  196. this_char = (c << 8) | next;
  197. } else if (next != 0x80 && next != 0xFF) {
  198. MB_FAILURE(pos, 1);
  199. } else {
  200. MB_FAILURE(pos, 2);
  201. }
  202. pos += 2;
  203. } else {
  204. this_char = c;
  205. pos += 1;
  206. }
  207. }
  208. break;
  209. case cs_gb2312: /* EUC-CN */
  210. {
  211. unsigned char c = str[pos];
  212. if (c >= 0xA1 && c <= 0xFE) {
  213. unsigned char next;
  214. if (!CHECK_LEN(pos, 2))
  215. MB_FAILURE(pos, 1);
  216. next = str[pos + 1];
  217. if (gb2312_trail(next)) {
  218. this_char = (c << 8) | next;
  219. } else if (gb2312_lead(next)) {
  220. MB_FAILURE(pos, 1);
  221. } else {
  222. MB_FAILURE(pos, 2);
  223. }
  224. pos += 2;
  225. } else if (gb2312_lead(c)) {
  226. this_char = c;
  227. pos += 1;
  228. } else {
  229. MB_FAILURE(pos, 1);
  230. }
  231. }
  232. break;
  233. case cs_sjis:
  234. {
  235. unsigned char c = str[pos];
  236. if ((c >= 0x81 && c <= 0x9F) || (c >= 0xE0 && c <= 0xFC)) {
  237. unsigned char next;
  238. if (!CHECK_LEN(pos, 2))
  239. MB_FAILURE(pos, 1);
  240. next = str[pos + 1];
  241. if (sjis_trail(next)) {
  242. this_char = (c << 8) | next;
  243. } else if (sjis_lead(next)) {
  244. MB_FAILURE(pos, 1);
  245. } else {
  246. MB_FAILURE(pos, 2);
  247. }
  248. pos += 2;
  249. } else if (c < 0x80 || (c >= 0xA1 && c <= 0xDF)) {
  250. this_char = c;
  251. pos += 1;
  252. } else {
  253. MB_FAILURE(pos, 1);
  254. }
  255. }
  256. break;
  257. case cs_eucjp:
  258. {
  259. unsigned char c = str[pos];
  260. if (c >= 0xA1 && c <= 0xFE) {
  261. unsigned next;
  262. if (!CHECK_LEN(pos, 2))
  263. MB_FAILURE(pos, 1);
  264. next = str[pos + 1];
  265. if (next >= 0xA1 && next <= 0xFE) {
  266. /* this a jis kanji char */
  267. this_char = (c << 8) | next;
  268. } else {
  269. MB_FAILURE(pos, (next != 0xA0 && next != 0xFF) ? 1 : 2);
  270. }
  271. pos += 2;
  272. } else if (c == 0x8E) {
  273. unsigned next;
  274. if (!CHECK_LEN(pos, 2))
  275. MB_FAILURE(pos, 1);
  276. next = str[pos + 1];
  277. if (next >= 0xA1 && next <= 0xDF) {
  278. /* JIS X 0201 kana */
  279. this_char = (c << 8) | next;
  280. } else {
  281. MB_FAILURE(pos, (next != 0xA0 && next != 0xFF) ? 1 : 2);
  282. }
  283. pos += 2;
  284. } else if (c == 0x8F) {
  285. size_t avail = str_len - pos;
  286. if (avail < 3 || !(str[pos + 1] >= 0xA1 && str[pos + 1] <= 0xFE) ||
  287. !(str[pos + 2] >= 0xA1 && str[pos + 2] <= 0xFE)) {
  288. if (avail < 2 || (str[pos + 1] != 0xA0 && str[pos + 1] != 0xFF))
  289. MB_FAILURE(pos, 1);
  290. else if (avail < 3 || (str[pos + 2] != 0xA0 && str[pos + 2] != 0xFF))
  291. MB_FAILURE(pos, 2);
  292. else
  293. MB_FAILURE(pos, 3);
  294. } else {
  295. /* JIS X 0212 hojo-kanji */
  296. this_char = (c << 16) | (str[pos + 1] << 8) | str[pos + 2];
  297. }
  298. pos += 3;
  299. } else if (c != 0xA0 && c != 0xFF) {
  300. /* character encoded in 1 code unit */
  301. this_char = c;
  302. pos += 1;
  303. } else {
  304. MB_FAILURE(pos, 1);
  305. }
  306. }
  307. break;
  308. default:
  309. /* single-byte charsets */
  310. this_char = str[pos++];
  311. break;
  312. }
  313. *cursor = pos;
  314. return this_char;
  315. }
  316. /* }}} */
  317. /* {{{ php_next_utf8_char
  318. * Public interface for get_next_char used with UTF-8 */
  319. PHPAPI unsigned int php_next_utf8_char(
  320. const unsigned char *str,
  321. size_t str_len,
  322. size_t *cursor,
  323. int *status)
  324. {
  325. return get_next_char(cs_utf_8, str, str_len, cursor, status);
  326. }
  327. /* }}} */
  328. /* {{{ entity_charset determine_charset
  329. * Returns the charset identifier based on an explicitly provided charset,
  330. * the internal_encoding and default_charset ini settings, or UTF-8 by default. */
  331. static enum entity_charset determine_charset(char *charset_hint, zend_bool quiet)
  332. {
  333. if (!charset_hint || !*charset_hint) {
  334. charset_hint = get_default_charset();
  335. }
  336. if (charset_hint && *charset_hint) {
  337. size_t len = strlen(charset_hint);
  338. /* now walk the charset map and look for the codeset */
  339. for (size_t i = 0; i < sizeof(charset_map)/sizeof(charset_map[0]); i++) {
  340. if (len == charset_map[i].codeset_len &&
  341. zend_binary_strcasecmp(charset_hint, len, charset_map[i].codeset, len) == 0) {
  342. return charset_map[i].charset;
  343. }
  344. }
  345. if (!quiet) {
  346. php_error_docref(NULL, E_WARNING, "Charset `%s' not supported, assuming utf-8",
  347. charset_hint);
  348. }
  349. }
  350. return cs_utf_8;
  351. }
  352. /* }}} */
  353. /* {{{ php_utf32_utf8 */
  354. static inline size_t php_utf32_utf8(unsigned char *buf, unsigned k)
  355. {
  356. size_t retval = 0;
  357. /* assert(0x0 <= k <= 0x10FFFF); */
  358. if (k < 0x80) {
  359. buf[0] = k;
  360. retval = 1;
  361. } else if (k < 0x800) {
  362. buf[0] = 0xc0 | (k >> 6);
  363. buf[1] = 0x80 | (k & 0x3f);
  364. retval = 2;
  365. } else if (k < 0x10000) {
  366. buf[0] = 0xe0 | (k >> 12);
  367. buf[1] = 0x80 | ((k >> 6) & 0x3f);
  368. buf[2] = 0x80 | (k & 0x3f);
  369. retval = 3;
  370. } else {
  371. buf[0] = 0xf0 | (k >> 18);
  372. buf[1] = 0x80 | ((k >> 12) & 0x3f);
  373. buf[2] = 0x80 | ((k >> 6) & 0x3f);
  374. buf[3] = 0x80 | (k & 0x3f);
  375. retval = 4;
  376. }
  377. /* UTF-8 has been restricted to max 4 bytes since RFC 3629 */
  378. return retval;
  379. }
  380. /* }}} */
  381. /* {{{ unimap_bsearc_cmp
  382. * Binary search of unicode code points in unicode <--> charset mapping.
  383. * Returns the code point in the target charset (whose mapping table was given) or 0 if
  384. * the unicode code point is not in the table.
  385. */
  386. static inline unsigned char unimap_bsearch(const uni_to_enc *table, unsigned code_key_a, size_t num)
  387. {
  388. const uni_to_enc *l = table,
  389. *h = &table[num-1],
  390. *m;
  391. unsigned short code_key;
  392. /* we have no mappings outside the BMP */
  393. if (code_key_a > 0xFFFFU)
  394. return 0;
  395. code_key = (unsigned short) code_key_a;
  396. while (l <= h) {
  397. m = l + (h - l) / 2;
  398. if (code_key < m->un_code_point)
  399. h = m - 1;
  400. else if (code_key > m->un_code_point)
  401. l = m + 1;
  402. else
  403. return m->cs_code;
  404. }
  405. return 0;
  406. }
  407. /* }}} */
  408. /* {{{ map_from_unicode */
  409. static inline int map_from_unicode(unsigned code, enum entity_charset charset, unsigned *res)
  410. {
  411. unsigned char found;
  412. const uni_to_enc *table;
  413. size_t table_size;
  414. switch (charset) {
  415. case cs_8859_1:
  416. /* identity mapping of code points to unicode */
  417. if (code > 0xFF) {
  418. return FAILURE;
  419. }
  420. *res = code;
  421. break;
  422. case cs_8859_5:
  423. if (code <= 0xA0 || code == 0xAD /* soft hyphen */) {
  424. *res = code;
  425. } else if (code == 0x2116) {
  426. *res = 0xF0; /* numero sign */
  427. } else if (code == 0xA7) {
  428. *res = 0xFD; /* section sign */
  429. } else if (code >= 0x0401 && code <= 0x044F) {
  430. if (code == 0x040D || code == 0x0450 || code == 0x045D)
  431. return FAILURE;
  432. *res = code - 0x360;
  433. } else {
  434. return FAILURE;
  435. }
  436. break;
  437. case cs_8859_15:
  438. if (code < 0xA4 || (code > 0xBE && code <= 0xFF)) {
  439. *res = code;
  440. } else { /* between A4 and 0xBE */
  441. found = unimap_bsearch(unimap_iso885915,
  442. code, sizeof(unimap_iso885915) / sizeof(*unimap_iso885915));
  443. if (found)
  444. *res = found;
  445. else
  446. return FAILURE;
  447. }
  448. break;
  449. case cs_cp1252:
  450. if (code <= 0x7F || (code >= 0xA0 && code <= 0xFF)) {
  451. *res = code;
  452. } else {
  453. found = unimap_bsearch(unimap_win1252,
  454. code, sizeof(unimap_win1252) / sizeof(*unimap_win1252));
  455. if (found)
  456. *res = found;
  457. else
  458. return FAILURE;
  459. }
  460. break;
  461. case cs_macroman:
  462. if (code == 0x7F)
  463. return FAILURE;
  464. table = unimap_macroman;
  465. table_size = sizeof(unimap_macroman) / sizeof(*unimap_macroman);
  466. goto table_over_7F;
  467. case cs_cp1251:
  468. table = unimap_win1251;
  469. table_size = sizeof(unimap_win1251) / sizeof(*unimap_win1251);
  470. goto table_over_7F;
  471. case cs_koi8r:
  472. table = unimap_koi8r;
  473. table_size = sizeof(unimap_koi8r) / sizeof(*unimap_koi8r);
  474. goto table_over_7F;
  475. case cs_cp866:
  476. table = unimap_cp866;
  477. table_size = sizeof(unimap_cp866) / sizeof(*unimap_cp866);
  478. table_over_7F:
  479. if (code <= 0x7F) {
  480. *res = code;
  481. } else {
  482. found = unimap_bsearch(table, code, table_size);
  483. if (found)
  484. *res = found;
  485. else
  486. return FAILURE;
  487. }
  488. break;
  489. /* from here on, only map the possible characters in the ASCII range.
  490. * to improve support here, it's a matter of building the unicode mappings.
  491. * See <http://www.unicode.org/Public/6.0.0/ucd/Unihan.zip> */
  492. case cs_sjis:
  493. case cs_eucjp:
  494. /* we interpret 0x5C as the Yen symbol. This is not universal.
  495. * See <http://www.w3.org/Submission/japanese-xml/#ambiguity_of_yen> */
  496. if (code >= 0x20 && code <= 0x7D) {
  497. if (code == 0x5C)
  498. return FAILURE;
  499. *res = code;
  500. } else {
  501. return FAILURE;
  502. }
  503. break;
  504. case cs_big5:
  505. case cs_big5hkscs:
  506. case cs_gb2312:
  507. if (code >= 0x20 && code <= 0x7D) {
  508. *res = code;
  509. } else {
  510. return FAILURE;
  511. }
  512. break;
  513. default:
  514. return FAILURE;
  515. }
  516. return SUCCESS;
  517. }
  518. /* }}} */
  519. /* {{{ */
  520. static inline void map_to_unicode(unsigned code, const enc_to_uni *table, unsigned *res)
  521. {
  522. /* only single byte encodings are currently supported; assumed code <= 0xFF */
  523. *res = table->inner[ENT_ENC_TO_UNI_STAGE1(code)]->uni_cp[ENT_ENC_TO_UNI_STAGE2(code)];
  524. }
  525. /* }}} */
  526. /* {{{ unicode_cp_is_allowed */
  527. static inline int unicode_cp_is_allowed(unsigned uni_cp, int document_type)
  528. {
  529. /* XML 1.0 HTML 4.01 HTML 5
  530. * 0x09..0x0A 0x09..0x0A 0x09..0x0A
  531. * 0x0D 0x0D 0x0C..0x0D
  532. * 0x0020..0xD7FF 0x20..0x7E 0x20..0x7E
  533. * 0x00A0..0xD7FF 0x00A0..0xD7FF
  534. * 0xE000..0xFFFD 0xE000..0x10FFFF 0xE000..0xFDCF
  535. * 0x010000..0x10FFFF 0xFDF0..0x10FFFF (*)
  536. *
  537. * (*) exclude code points where ((code & 0xFFFF) >= 0xFFFE)
  538. *
  539. * References:
  540. * XML 1.0: <http://www.w3.org/TR/REC-xml/#charsets>
  541. * HTML 4.01: <http://www.w3.org/TR/1999/PR-html40-19990824/sgml/sgmldecl.html>
  542. * HTML 5: <http://dev.w3.org/html5/spec/Overview.html#preprocessing-the-input-stream>
  543. *
  544. * Not sure this is the relevant part for HTML 5, though. I opted to
  545. * disallow the characters that would result in a parse error when
  546. * preprocessing of the input stream. See also section 8.1.3.
  547. *
  548. * It's unclear if XHTML 1.0 allows C1 characters. I'll opt to apply to
  549. * XHTML 1.0 the same rules as for XML 1.0.
  550. * See <http://cmsmcq.com/2007/C1.xml>.
  551. */
  552. switch (document_type) {
  553. case ENT_HTML_DOC_HTML401:
  554. return (uni_cp >= 0x20 && uni_cp <= 0x7E) ||
  555. (uni_cp == 0x0A || uni_cp == 0x09 || uni_cp == 0x0D) ||
  556. (uni_cp >= 0xA0 && uni_cp <= 0xD7FF) ||
  557. (uni_cp >= 0xE000 && uni_cp <= 0x10FFFF);
  558. case ENT_HTML_DOC_HTML5:
  559. return (uni_cp >= 0x20 && uni_cp <= 0x7E) ||
  560. (uni_cp >= 0x09 && uni_cp <= 0x0D && uni_cp != 0x0B) || /* form feed U+0C allowed */
  561. (uni_cp >= 0xA0 && uni_cp <= 0xD7FF) ||
  562. (uni_cp >= 0xE000 && uni_cp <= 0x10FFFF &&
  563. ((uni_cp & 0xFFFF) < 0xFFFE) && /* last two of each plane (nonchars) disallowed */
  564. (uni_cp < 0xFDD0 || uni_cp > 0xFDEF)); /* U+FDD0-U+FDEF (nonchars) disallowed */
  565. case ENT_HTML_DOC_XHTML:
  566. case ENT_HTML_DOC_XML1:
  567. return (uni_cp >= 0x20 && uni_cp <= 0xD7FF) ||
  568. (uni_cp == 0x0A || uni_cp == 0x09 || uni_cp == 0x0D) ||
  569. (uni_cp >= 0xE000 && uni_cp <= 0x10FFFF && uni_cp != 0xFFFE && uni_cp != 0xFFFF);
  570. default:
  571. return 1;
  572. }
  573. }
  574. /* }}} */
  575. /* {{{ unicode_cp_is_allowed */
  576. static inline int numeric_entity_is_allowed(unsigned uni_cp, int document_type)
  577. {
  578. /* less restrictive than unicode_cp_is_allowed */
  579. switch (document_type) {
  580. case ENT_HTML_DOC_HTML401:
  581. /* all non-SGML characters (those marked with UNUSED in DESCSET) should be
  582. * representable with numeric entities */
  583. return uni_cp <= 0x10FFFF;
  584. case ENT_HTML_DOC_HTML5:
  585. /* 8.1.4. The numeric character reference forms described above are allowed to
  586. * reference any Unicode code point other than U+0000, U+000D, permanently
  587. * undefined Unicode characters (noncharacters), and control characters other
  588. * than space characters (U+0009, U+000A, U+000C and U+000D) */
  589. /* seems to allow surrogate characters, then */
  590. return (uni_cp >= 0x20 && uni_cp <= 0x7E) ||
  591. (uni_cp >= 0x09 && uni_cp <= 0x0C && uni_cp != 0x0B) || /* form feed U+0C allowed, but not U+0D */
  592. (uni_cp >= 0xA0 && uni_cp <= 0x10FFFF &&
  593. ((uni_cp & 0xFFFF) < 0xFFFE) && /* last two of each plane (nonchars) disallowed */
  594. (uni_cp < 0xFDD0 || uni_cp > 0xFDEF)); /* U+FDD0-U+FDEF (nonchars) disallowed */
  595. case ENT_HTML_DOC_XHTML:
  596. case ENT_HTML_DOC_XML1:
  597. /* OTOH, XML 1.0 requires "character references to match the production for Char
  598. * See <http://www.w3.org/TR/REC-xml/#NT-CharRef> */
  599. return unicode_cp_is_allowed(uni_cp, document_type);
  600. default:
  601. return 1;
  602. }
  603. }
  604. /* }}} */
  605. /* {{{ process_numeric_entity
  606. * Auxiliary function to traverse_for_entities.
  607. * On input, *buf should point to the first character after # and on output, it's the last
  608. * byte read, no matter if there was success or insuccess.
  609. */
  610. static inline int process_numeric_entity(const char **buf, unsigned *code_point)
  611. {
  612. zend_long code_l;
  613. int hexadecimal = (**buf == 'x' || **buf == 'X'); /* TODO: XML apparently disallows "X" */
  614. char *endptr;
  615. if (hexadecimal && (**buf != '\0'))
  616. (*buf)++;
  617. /* strtol allows whitespace and other stuff in the beginning
  618. * we're not interested */
  619. if ((hexadecimal && !isxdigit(**buf)) ||
  620. (!hexadecimal && !isdigit(**buf))) {
  621. return FAILURE;
  622. }
  623. code_l = ZEND_STRTOL(*buf, &endptr, hexadecimal ? 16 : 10);
  624. /* we're guaranteed there were valid digits, so *endptr > buf */
  625. *buf = endptr;
  626. if (**buf != ';')
  627. return FAILURE;
  628. /* many more are invalid, but that depends on whether it's HTML
  629. * (and which version) or XML. */
  630. if (code_l > Z_L(0x10FFFF))
  631. return FAILURE;
  632. if (code_point != NULL)
  633. *code_point = (unsigned)code_l;
  634. return SUCCESS;
  635. }
  636. /* }}} */
  637. /* {{{ process_named_entity */
  638. static inline int process_named_entity_html(const char **buf, const char **start, size_t *length)
  639. {
  640. *start = *buf;
  641. /* "&" is represented by a 0x26 in all supported encodings. That means
  642. * the byte after represents a character or is the leading byte of an
  643. * sequence of 8-bit code units. If in the ranges below, it represents
  644. * necessarily a alpha character because none of the supported encodings
  645. * has an overlap with ASCII in the leading byte (only on the second one) */
  646. while ((**buf >= 'a' && **buf <= 'z') ||
  647. (**buf >= 'A' && **buf <= 'Z') ||
  648. (**buf >= '0' && **buf <= '9')) {
  649. (*buf)++;
  650. }
  651. if (**buf != ';')
  652. return FAILURE;
  653. /* cast to size_t OK as the quantity is always non-negative */
  654. *length = *buf - *start;
  655. if (*length == 0)
  656. return FAILURE;
  657. return SUCCESS;
  658. }
  659. /* }}} */
  660. /* {{{ resolve_named_entity_html */
  661. static inline int resolve_named_entity_html(const char *start, size_t length, const entity_ht *ht, unsigned *uni_cp1, unsigned *uni_cp2)
  662. {
  663. const entity_cp_map *s;
  664. zend_ulong hash = zend_inline_hash_func(start, length);
  665. s = ht->buckets[hash % ht->num_elems];
  666. while (s->entity) {
  667. if (s->entity_len == length) {
  668. if (memcmp(start, s->entity, length) == 0) {
  669. *uni_cp1 = s->codepoint1;
  670. *uni_cp2 = s->codepoint2;
  671. return SUCCESS;
  672. }
  673. }
  674. s++;
  675. }
  676. return FAILURE;
  677. }
  678. /* }}} */
  679. static inline size_t write_octet_sequence(unsigned char *buf, enum entity_charset charset, unsigned code) {
  680. /* code is not necessarily a unicode code point */
  681. switch (charset) {
  682. case cs_utf_8:
  683. return php_utf32_utf8(buf, code);
  684. case cs_8859_1:
  685. case cs_cp1252:
  686. case cs_8859_15:
  687. case cs_koi8r:
  688. case cs_cp1251:
  689. case cs_8859_5:
  690. case cs_cp866:
  691. case cs_macroman:
  692. /* single byte stuff */
  693. *buf = code;
  694. return 1;
  695. case cs_big5:
  696. case cs_big5hkscs:
  697. case cs_sjis:
  698. case cs_gb2312:
  699. /* we don't have complete unicode mappings for these yet in entity_decode,
  700. * and we opt to pass through the octet sequences for these in htmlentities
  701. * instead of converting to an int and then converting back. */
  702. #if 0
  703. return php_mb2_int_to_char(buf, code);
  704. #else
  705. #if ZEND_DEBUG
  706. assert(code <= 0xFFU);
  707. #endif
  708. *buf = code;
  709. return 1;
  710. #endif
  711. case cs_eucjp:
  712. #if 0 /* idem */
  713. return php_mb2_int_to_char(buf, code);
  714. #else
  715. #if ZEND_DEBUG
  716. assert(code <= 0xFFU);
  717. #endif
  718. *buf = code;
  719. return 1;
  720. #endif
  721. default:
  722. assert(0);
  723. return 0;
  724. }
  725. }
  726. /* {{{ traverse_for_entities
  727. * Auxiliary function to php_unescape_html_entities().
  728. * - The argument "all" determines if all numeric entities are decode or only those
  729. * that correspond to quotes (depending on quote_style).
  730. */
  731. /* maximum expansion (factor 1.2) for HTML 5 with &nGt; and &nLt; */
  732. /* +2 is 1 because of rest (probably unnecessary), 1 because of terminating 0 */
  733. #define TRAVERSE_FOR_ENTITIES_EXPAND_SIZE(oldlen) ((oldlen) + (oldlen) / 5 + 2)
  734. static void traverse_for_entities(
  735. const char *old,
  736. size_t oldlen,
  737. zend_string *ret, /* should have allocated TRAVERSE_FOR_ENTITIES_EXPAND_SIZE(olden) */
  738. int all,
  739. int flags,
  740. const entity_ht *inv_map,
  741. enum entity_charset charset)
  742. {
  743. const char *p,
  744. *lim;
  745. char *q;
  746. int doctype = flags & ENT_HTML_DOC_TYPE_MASK;
  747. lim = old + oldlen; /* terminator address */
  748. assert(*lim == '\0');
  749. for (p = old, q = ZSTR_VAL(ret); p < lim;) {
  750. unsigned code, code2 = 0;
  751. const char *next = NULL; /* when set, next > p, otherwise possible inf loop */
  752. /* Shift JIS, Big5 and HKSCS use multi-byte encodings where an
  753. * ASCII range byte can be part of a multi-byte sequence.
  754. * However, they start at 0x40, therefore if we find a 0x26 byte,
  755. * we're sure it represents the '&' character. */
  756. /* assumes there are no single-char entities */
  757. if (p[0] != '&' || (p + 3 >= lim)) {
  758. *(q++) = *(p++);
  759. continue;
  760. }
  761. /* now p[3] is surely valid and is no terminator */
  762. /* numerical entity */
  763. if (p[1] == '#') {
  764. next = &p[2];
  765. if (process_numeric_entity(&next, &code) == FAILURE)
  766. goto invalid_code;
  767. /* If we're in htmlspecialchars_decode, we're only decoding entities
  768. * that represent &, <, >, " and '. Is this one of them? */
  769. if (!all && (code > 63U ||
  770. stage3_table_be_apos_00000[code].data.ent.entity == NULL))
  771. goto invalid_code;
  772. /* are we allowed to decode this entity in this document type?
  773. * HTML 5 is the only that has a character that cannot be used in
  774. * a numeric entity but is allowed literally (U+000D). The
  775. * unoptimized version would be ... || !numeric_entity_is_allowed(code) */
  776. if (!unicode_cp_is_allowed(code, doctype) ||
  777. (doctype == ENT_HTML_DOC_HTML5 && code == 0x0D))
  778. goto invalid_code;
  779. } else {
  780. const char *start;
  781. size_t ent_len;
  782. next = &p[1];
  783. start = next;
  784. if (process_named_entity_html(&next, &start, &ent_len) == FAILURE)
  785. goto invalid_code;
  786. if (resolve_named_entity_html(start, ent_len, inv_map, &code, &code2) == FAILURE) {
  787. if (doctype == ENT_HTML_DOC_XHTML && ent_len == 4 && start[0] == 'a'
  788. && start[1] == 'p' && start[2] == 'o' && start[3] == 's') {
  789. /* uses html4 inv_map, which doesn't include apos;. This is a
  790. * hack to support it */
  791. code = (unsigned) '\'';
  792. } else {
  793. goto invalid_code;
  794. }
  795. }
  796. }
  797. assert(*next == ';');
  798. if (((code == '\'' && !(flags & ENT_HTML_QUOTE_SINGLE)) ||
  799. (code == '"' && !(flags & ENT_HTML_QUOTE_DOUBLE)))
  800. /* && code2 == '\0' always true for current maps */)
  801. goto invalid_code;
  802. /* UTF-8 doesn't need mapping (ISO-8859-1 doesn't either, but
  803. * the call is needed to ensure the codepoint <= U+00FF) */
  804. if (charset != cs_utf_8) {
  805. /* replace unicode code point */
  806. if (map_from_unicode(code, charset, &code) == FAILURE || code2 != 0)
  807. goto invalid_code; /* not representable in target charset */
  808. }
  809. q += write_octet_sequence((unsigned char*)q, charset, code);
  810. if (code2) {
  811. q += write_octet_sequence((unsigned char*)q, charset, code2);
  812. }
  813. /* jump over the valid entity; may go beyond size of buffer; np */
  814. p = next + 1;
  815. continue;
  816. invalid_code:
  817. for (; p < next; p++) {
  818. *(q++) = *p;
  819. }
  820. }
  821. *q = '\0';
  822. ZSTR_LEN(ret) = (size_t)(q - ZSTR_VAL(ret));
  823. }
  824. /* }}} */
  825. /* {{{ unescape_inverse_map */
  826. static const entity_ht *unescape_inverse_map(int all, int flags)
  827. {
  828. int document_type = flags & ENT_HTML_DOC_TYPE_MASK;
  829. if (all) {
  830. switch (document_type) {
  831. case ENT_HTML_DOC_HTML401:
  832. case ENT_HTML_DOC_XHTML: /* but watch out for &apos;...*/
  833. return &ent_ht_html4;
  834. case ENT_HTML_DOC_HTML5:
  835. return &ent_ht_html5;
  836. default:
  837. return &ent_ht_be_apos;
  838. }
  839. } else {
  840. switch (document_type) {
  841. case ENT_HTML_DOC_HTML401:
  842. return &ent_ht_be_noapos;
  843. default:
  844. return &ent_ht_be_apos;
  845. }
  846. }
  847. }
  848. /* }}} */
  849. /* {{{ determine_entity_table
  850. * Entity table to use. Note that entity tables are defined in terms of
  851. * unicode code points */
  852. static entity_table_opt determine_entity_table(int all, int doctype)
  853. {
  854. entity_table_opt retval = {0};
  855. assert(!(doctype == ENT_HTML_DOC_XML1 && all));
  856. if (all) {
  857. retval.ms_table = (doctype == ENT_HTML_DOC_HTML5) ?
  858. entity_ms_table_html5 : entity_ms_table_html4;
  859. } else {
  860. retval.table = (doctype == ENT_HTML_DOC_HTML401) ?
  861. stage3_table_be_noapos_00000 : stage3_table_be_apos_00000;
  862. }
  863. return retval;
  864. }
  865. /* }}} */
  866. /* {{{ php_unescape_html_entities
  867. * The parameter "all" should be true to decode all possible entities, false to decode
  868. * only the basic ones, i.e., those in basic_entities_ex + the numeric entities
  869. * that correspond to quotes.
  870. */
  871. PHPAPI zend_string *php_unescape_html_entities(zend_string *str, int all, int flags, char *hint_charset)
  872. {
  873. zend_string *ret;
  874. enum entity_charset charset;
  875. const entity_ht *inverse_map;
  876. size_t new_size;
  877. if (!memchr(ZSTR_VAL(str), '&', ZSTR_LEN(str))) {
  878. return zend_string_copy(str);
  879. }
  880. if (all) {
  881. charset = determine_charset(hint_charset, /* quiet */ 0);
  882. } else {
  883. charset = cs_8859_1; /* charset shouldn't matter, use ISO-8859-1 for performance */
  884. }
  885. /* don't use LIMIT_ALL! */
  886. new_size = TRAVERSE_FOR_ENTITIES_EXPAND_SIZE(ZSTR_LEN(str));
  887. if (ZSTR_LEN(str) > new_size) {
  888. /* overflow, refuse to do anything */
  889. return zend_string_copy(str);
  890. }
  891. ret = zend_string_alloc(new_size, 0);
  892. inverse_map = unescape_inverse_map(all, flags);
  893. /* replace numeric entities */
  894. traverse_for_entities(ZSTR_VAL(str), ZSTR_LEN(str), ret, all, flags, inverse_map, charset);
  895. return ret;
  896. }
  897. /* }}} */
  898. PHPAPI zend_string *php_escape_html_entities(const unsigned char *old, size_t oldlen, int all, int flags, char *hint_charset)
  899. {
  900. return php_escape_html_entities_ex(old, oldlen, all, flags, hint_charset, 1, /* quiet */ 0);
  901. }
  902. /* {{{ find_entity_for_char */
  903. static inline void find_entity_for_char(
  904. unsigned int k,
  905. enum entity_charset charset,
  906. const entity_stage1_row *table,
  907. const unsigned char **entity,
  908. size_t *entity_len,
  909. const unsigned char *old,
  910. size_t oldlen,
  911. size_t *cursor)
  912. {
  913. unsigned stage1_idx = ENT_STAGE1_INDEX(k);
  914. const entity_stage3_row *c;
  915. if (stage1_idx > 0x1D) {
  916. *entity = NULL;
  917. *entity_len = 0;
  918. return;
  919. }
  920. c = &table[stage1_idx][ENT_STAGE2_INDEX(k)][ENT_STAGE3_INDEX(k)];
  921. if (!c->ambiguous) {
  922. *entity = (const unsigned char *)c->data.ent.entity;
  923. *entity_len = c->data.ent.entity_len;
  924. } else {
  925. /* peek at next char */
  926. size_t cursor_before = *cursor;
  927. int status = SUCCESS;
  928. unsigned next_char;
  929. if (!(*cursor < oldlen))
  930. goto no_suitable_2nd;
  931. next_char = get_next_char(charset, old, oldlen, cursor, &status);
  932. if (status == FAILURE)
  933. goto no_suitable_2nd;
  934. {
  935. const entity_multicodepoint_row *s, *e;
  936. s = &c->data.multicodepoint_table[1];
  937. e = s - 1 + c->data.multicodepoint_table[0].leading_entry.size;
  938. /* we could do a binary search but it's not worth it since we have
  939. * at most two entries... */
  940. for ( ; s <= e; s++) {
  941. if (s->normal_entry.second_cp == next_char) {
  942. *entity = (const unsigned char *) s->normal_entry.entity;
  943. *entity_len = s->normal_entry.entity_len;
  944. return;
  945. }
  946. }
  947. }
  948. no_suitable_2nd:
  949. *cursor = cursor_before;
  950. *entity = (const unsigned char *)
  951. c->data.multicodepoint_table[0].leading_entry.default_entity;
  952. *entity_len = c->data.multicodepoint_table[0].leading_entry.default_entity_len;
  953. }
  954. }
  955. /* }}} */
  956. /* {{{ find_entity_for_char_basic */
  957. static inline void find_entity_for_char_basic(
  958. unsigned int k,
  959. const entity_stage3_row *table,
  960. const unsigned char **entity,
  961. size_t *entity_len)
  962. {
  963. if (k >= 64U) {
  964. *entity = NULL;
  965. *entity_len = 0;
  966. return;
  967. }
  968. *entity = (const unsigned char *) table[k].data.ent.entity;
  969. *entity_len = table[k].data.ent.entity_len;
  970. }
  971. /* }}} */
  972. /* {{{ php_escape_html_entities
  973. */
  974. PHPAPI zend_string *php_escape_html_entities_ex(const unsigned char *old, size_t oldlen, int all, int flags, char *hint_charset, zend_bool double_encode, zend_bool quiet)
  975. {
  976. size_t cursor, maxlen, len;
  977. zend_string *replaced;
  978. enum entity_charset charset = determine_charset(hint_charset, quiet);
  979. int doctype = flags & ENT_HTML_DOC_TYPE_MASK;
  980. entity_table_opt entity_table;
  981. const enc_to_uni *to_uni_table = NULL;
  982. const entity_ht *inv_map = NULL; /* used for !double_encode */
  983. /* only used if flags includes ENT_HTML_IGNORE_ERRORS or ENT_HTML_SUBSTITUTE_DISALLOWED_CHARS */
  984. const unsigned char *replacement = NULL;
  985. size_t replacement_len = 0;
  986. if (all) { /* replace with all named entities */
  987. if (!quiet && CHARSET_PARTIAL_SUPPORT(charset)) {
  988. php_error_docref(NULL, E_NOTICE, "Only basic entities "
  989. "substitution is supported for multi-byte encodings other than UTF-8; "
  990. "functionality is equivalent to htmlspecialchars");
  991. }
  992. LIMIT_ALL(all, doctype, charset);
  993. }
  994. entity_table = determine_entity_table(all, doctype);
  995. if (all && !CHARSET_UNICODE_COMPAT(charset)) {
  996. to_uni_table = enc_to_uni_index[charset];
  997. }
  998. if (!double_encode) {
  999. /* first arg is 1 because we want to identify valid named entities
  1000. * even if we are only encoding the basic ones */
  1001. inv_map = unescape_inverse_map(1, flags);
  1002. }
  1003. if (flags & (ENT_HTML_SUBSTITUTE_ERRORS | ENT_HTML_SUBSTITUTE_DISALLOWED_CHARS)) {
  1004. if (charset == cs_utf_8) {
  1005. replacement = (const unsigned char*)"\xEF\xBF\xBD";
  1006. replacement_len = sizeof("\xEF\xBF\xBD") - 1;
  1007. } else {
  1008. replacement = (const unsigned char*)"&#xFFFD;";
  1009. replacement_len = sizeof("&#xFFFD;") - 1;
  1010. }
  1011. }
  1012. /* initial estimate */
  1013. if (oldlen < 64) {
  1014. maxlen = 128;
  1015. } else {
  1016. maxlen = zend_safe_addmult(oldlen, 2, 0, "html_entities");
  1017. }
  1018. replaced = zend_string_alloc(maxlen, 0);
  1019. len = 0;
  1020. cursor = 0;
  1021. while (cursor < oldlen) {
  1022. const unsigned char *mbsequence = NULL;
  1023. size_t mbseqlen = 0,
  1024. cursor_before = cursor;
  1025. int status = SUCCESS;
  1026. unsigned int this_char = get_next_char(charset, old, oldlen, &cursor, &status);
  1027. /* guarantee we have at least 40 bytes to write.
  1028. * In HTML5, entities may take up to 33 bytes */
  1029. if (len > maxlen - 40) { /* maxlen can never be smaller than 128 */
  1030. replaced = zend_string_safe_realloc(replaced, maxlen, 1, 128, 0);
  1031. maxlen += 128;
  1032. }
  1033. if (status == FAILURE) {
  1034. /* invalid MB sequence */
  1035. if (flags & ENT_HTML_IGNORE_ERRORS) {
  1036. continue;
  1037. } else if (flags & ENT_HTML_SUBSTITUTE_ERRORS) {
  1038. memcpy(&ZSTR_VAL(replaced)[len], replacement, replacement_len);
  1039. len += replacement_len;
  1040. continue;
  1041. } else {
  1042. zend_string_efree(replaced);
  1043. return ZSTR_EMPTY_ALLOC();
  1044. }
  1045. } else { /* SUCCESS */
  1046. mbsequence = &old[cursor_before];
  1047. mbseqlen = cursor - cursor_before;
  1048. }
  1049. if (this_char != '&') { /* no entity on this position */
  1050. const unsigned char *rep = NULL;
  1051. size_t rep_len = 0;
  1052. if (((this_char == '\'' && !(flags & ENT_HTML_QUOTE_SINGLE)) ||
  1053. (this_char == '"' && !(flags & ENT_HTML_QUOTE_DOUBLE))))
  1054. goto pass_char_through;
  1055. if (all) { /* false that CHARSET_PARTIAL_SUPPORT(charset) */
  1056. if (to_uni_table != NULL) {
  1057. /* !CHARSET_UNICODE_COMPAT therefore not UTF-8; since UTF-8
  1058. * is the only multibyte encoding with !CHARSET_PARTIAL_SUPPORT,
  1059. * we're using a single byte encoding */
  1060. map_to_unicode(this_char, to_uni_table, &this_char);
  1061. if (this_char == 0xFFFF) /* no mapping; pass through */
  1062. goto pass_char_through;
  1063. }
  1064. /* the cursor may advance */
  1065. find_entity_for_char(this_char, charset, entity_table.ms_table, &rep,
  1066. &rep_len, old, oldlen, &cursor);
  1067. } else {
  1068. find_entity_for_char_basic(this_char, entity_table.table, &rep, &rep_len);
  1069. }
  1070. if (rep != NULL) {
  1071. ZSTR_VAL(replaced)[len++] = '&';
  1072. memcpy(&ZSTR_VAL(replaced)[len], rep, rep_len);
  1073. len += rep_len;
  1074. ZSTR_VAL(replaced)[len++] = ';';
  1075. } else {
  1076. /* we did not find an entity for this char.
  1077. * check for its validity, if its valid pass it unchanged */
  1078. if (flags & ENT_HTML_SUBSTITUTE_DISALLOWED_CHARS) {
  1079. if (CHARSET_UNICODE_COMPAT(charset)) {
  1080. if (!unicode_cp_is_allowed(this_char, doctype)) {
  1081. mbsequence = replacement;
  1082. mbseqlen = replacement_len;
  1083. }
  1084. } else if (to_uni_table) {
  1085. if (!all) /* otherwise we already did this */
  1086. map_to_unicode(this_char, to_uni_table, &this_char);
  1087. if (!unicode_cp_is_allowed(this_char, doctype)) {
  1088. mbsequence = replacement;
  1089. mbseqlen = replacement_len;
  1090. }
  1091. } else {
  1092. /* not a unicode code point, unless, coincidentally, it's in
  1093. * the 0x20..0x7D range (except 0x5C in sjis). We know nothing
  1094. * about other code points, because we have no tables. Since
  1095. * Unicode code points in that range are not disallowed in any
  1096. * document type, we could do nothing. However, conversion
  1097. * tables frequently map 0x00-0x1F to the respective C0 code
  1098. * points. Let's play it safe and admit that's the case */
  1099. if (this_char <= 0x7D &&
  1100. !unicode_cp_is_allowed(this_char, doctype)) {
  1101. mbsequence = replacement;
  1102. mbseqlen = replacement_len;
  1103. }
  1104. }
  1105. }
  1106. pass_char_through:
  1107. if (mbseqlen > 1) {
  1108. memcpy(ZSTR_VAL(replaced) + len, mbsequence, mbseqlen);
  1109. len += mbseqlen;
  1110. } else {
  1111. ZSTR_VAL(replaced)[len++] = mbsequence[0];
  1112. }
  1113. }
  1114. } else { /* this_char == '&' */
  1115. if (double_encode) {
  1116. encode_amp:
  1117. memcpy(&ZSTR_VAL(replaced)[len], "&amp;", sizeof("&amp;") - 1);
  1118. len += sizeof("&amp;") - 1;
  1119. } else { /* no double encode */
  1120. /* check if entity is valid */
  1121. size_t ent_len; /* not counting & or ; */
  1122. /* peek at next char */
  1123. if (old[cursor] == '#') { /* numeric entity */
  1124. unsigned code_point;
  1125. int valid;
  1126. char *pos = (char*)&old[cursor+1];
  1127. valid = process_numeric_entity((const char **)&pos, &code_point);
  1128. if (valid == FAILURE)
  1129. goto encode_amp;
  1130. if (flags & ENT_HTML_SUBSTITUTE_DISALLOWED_CHARS) {
  1131. if (!numeric_entity_is_allowed(code_point, doctype))
  1132. goto encode_amp;
  1133. }
  1134. ent_len = pos - (char*)&old[cursor];
  1135. } else { /* named entity */
  1136. /* check for vality of named entity */
  1137. const char *start = (const char *) &old[cursor],
  1138. *next = start;
  1139. unsigned dummy1, dummy2;
  1140. if (process_named_entity_html(&next, &start, &ent_len) == FAILURE)
  1141. goto encode_amp;
  1142. if (resolve_named_entity_html(start, ent_len, inv_map, &dummy1, &dummy2) == FAILURE) {
  1143. if (!(doctype == ENT_HTML_DOC_XHTML && ent_len == 4 && start[0] == 'a'
  1144. && start[1] == 'p' && start[2] == 'o' && start[3] == 's')) {
  1145. /* uses html4 inv_map, which doesn't include apos;. This is a
  1146. * hack to support it */
  1147. goto encode_amp;
  1148. }
  1149. }
  1150. }
  1151. /* checks passed; copy entity to result */
  1152. /* entity size is unbounded, we may need more memory */
  1153. /* at this point maxlen - len >= 40 */
  1154. if (maxlen - len < ent_len + 2 /* & and ; */) {
  1155. /* ent_len < oldlen, which is certainly <= SIZE_MAX/2 */
  1156. replaced = zend_string_safe_realloc(replaced, maxlen, 1, ent_len + 128, 0);
  1157. maxlen += ent_len + 128;
  1158. }
  1159. ZSTR_VAL(replaced)[len++] = '&';
  1160. memcpy(&ZSTR_VAL(replaced)[len], &old[cursor], ent_len);
  1161. len += ent_len;
  1162. ZSTR_VAL(replaced)[len++] = ';';
  1163. cursor += ent_len + 1;
  1164. }
  1165. }
  1166. }
  1167. ZSTR_VAL(replaced)[len] = '\0';
  1168. ZSTR_LEN(replaced) = len;
  1169. return replaced;
  1170. }
  1171. /* }}} */
  1172. /* {{{ php_html_entities
  1173. */
  1174. static void php_html_entities(INTERNAL_FUNCTION_PARAMETERS, int all)
  1175. {
  1176. zend_string *str, *hint_charset = NULL;
  1177. zend_long flags = ENT_COMPAT;
  1178. zend_string *replaced;
  1179. zend_bool double_encode = 1;
  1180. ZEND_PARSE_PARAMETERS_START(1, 4)
  1181. Z_PARAM_STR(str)
  1182. Z_PARAM_OPTIONAL
  1183. Z_PARAM_LONG(flags)
  1184. Z_PARAM_STR_EX(hint_charset, 1, 0)
  1185. Z_PARAM_BOOL(double_encode);
  1186. ZEND_PARSE_PARAMETERS_END();
  1187. replaced = php_escape_html_entities_ex(
  1188. (unsigned char*)ZSTR_VAL(str), ZSTR_LEN(str), all, (int) flags,
  1189. hint_charset ? ZSTR_VAL(hint_charset) : NULL, double_encode, /* quiet */ 0);
  1190. RETVAL_STR(replaced);
  1191. }
  1192. /* }}} */
  1193. #define HTML_SPECIALCHARS 0
  1194. #define HTML_ENTITIES 1
  1195. /* {{{ register_html_constants
  1196. */
  1197. void register_html_constants(INIT_FUNC_ARGS)
  1198. {
  1199. REGISTER_LONG_CONSTANT("HTML_SPECIALCHARS", HTML_SPECIALCHARS, CONST_PERSISTENT|CONST_CS);
  1200. REGISTER_LONG_CONSTANT("HTML_ENTITIES", HTML_ENTITIES, CONST_PERSISTENT|CONST_CS);
  1201. REGISTER_LONG_CONSTANT("ENT_COMPAT", ENT_COMPAT, CONST_PERSISTENT|CONST_CS);
  1202. REGISTER_LONG_CONSTANT("ENT_QUOTES", ENT_QUOTES, CONST_PERSISTENT|CONST_CS);
  1203. REGISTER_LONG_CONSTANT("ENT_NOQUOTES", ENT_NOQUOTES, CONST_PERSISTENT|CONST_CS);
  1204. REGISTER_LONG_CONSTANT("ENT_IGNORE", ENT_IGNORE, CONST_PERSISTENT|CONST_CS);
  1205. REGISTER_LONG_CONSTANT("ENT_SUBSTITUTE", ENT_SUBSTITUTE, CONST_PERSISTENT|CONST_CS);
  1206. REGISTER_LONG_CONSTANT("ENT_DISALLOWED", ENT_DISALLOWED, CONST_PERSISTENT|CONST_CS);
  1207. REGISTER_LONG_CONSTANT("ENT_HTML401", ENT_HTML401, CONST_PERSISTENT|CONST_CS);
  1208. REGISTER_LONG_CONSTANT("ENT_XML1", ENT_XML1, CONST_PERSISTENT|CONST_CS);
  1209. REGISTER_LONG_CONSTANT("ENT_XHTML", ENT_XHTML, CONST_PERSISTENT|CONST_CS);
  1210. REGISTER_LONG_CONSTANT("ENT_HTML5", ENT_HTML5, CONST_PERSISTENT|CONST_CS);
  1211. }
  1212. /* }}} */
  1213. /* {{{ proto string htmlspecialchars(string string [, int quote_style[, string encoding[, bool double_encode]]])
  1214. Convert special characters to HTML entities */
  1215. PHP_FUNCTION(htmlspecialchars)
  1216. {
  1217. php_html_entities(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
  1218. }
  1219. /* }}} */
  1220. /* {{{ proto string htmlspecialchars_decode(string string [, int quote_style])
  1221. Convert special HTML entities back to characters */
  1222. PHP_FUNCTION(htmlspecialchars_decode)
  1223. {
  1224. zend_string *str;
  1225. zend_long quote_style = ENT_COMPAT;
  1226. zend_string *replaced;
  1227. ZEND_PARSE_PARAMETERS_START(1, 2)
  1228. Z_PARAM_STR(str)
  1229. Z_PARAM_OPTIONAL
  1230. Z_PARAM_LONG(quote_style)
  1231. ZEND_PARSE_PARAMETERS_END();
  1232. replaced = php_unescape_html_entities(str, 0 /*!all*/, (int)quote_style, NULL);
  1233. if (replaced) {
  1234. RETURN_STR(replaced);
  1235. }
  1236. RETURN_FALSE;
  1237. }
  1238. /* }}} */
  1239. /* {{{ proto string html_entity_decode(string string [, int quote_style][, string encoding])
  1240. Convert all HTML entities to their applicable characters */
  1241. PHP_FUNCTION(html_entity_decode)
  1242. {
  1243. zend_string *str, *hint_charset = NULL;
  1244. zend_long quote_style = ENT_COMPAT;
  1245. zend_string *replaced;
  1246. ZEND_PARSE_PARAMETERS_START(1, 3)
  1247. Z_PARAM_STR(str)
  1248. Z_PARAM_OPTIONAL
  1249. Z_PARAM_LONG(quote_style)
  1250. Z_PARAM_STR(hint_charset)
  1251. ZEND_PARSE_PARAMETERS_END();
  1252. replaced = php_unescape_html_entities(
  1253. str, 1 /*all*/, (int)quote_style, hint_charset ? ZSTR_VAL(hint_charset) : NULL);
  1254. if (replaced) {
  1255. RETURN_STR(replaced);
  1256. }
  1257. RETURN_FALSE;
  1258. }
  1259. /* }}} */
  1260. /* {{{ proto string htmlentities(string string [, int quote_style[, string encoding[, bool double_encode]]])
  1261. Convert all applicable characters to HTML entities */
  1262. PHP_FUNCTION(htmlentities)
  1263. {
  1264. php_html_entities(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
  1265. }
  1266. /* }}} */
  1267. /* {{{ write_s3row_data */
  1268. static inline void write_s3row_data(
  1269. const entity_stage3_row *r,
  1270. unsigned orig_cp,
  1271. enum entity_charset charset,
  1272. zval *arr)
  1273. {
  1274. char key[9] = ""; /* two unicode code points in UTF-8 */
  1275. char entity[LONGEST_ENTITY_LENGTH + 2] = {'&'};
  1276. size_t written_k1;
  1277. written_k1 = write_octet_sequence((unsigned char*)key, charset, orig_cp);
  1278. if (!r->ambiguous) {
  1279. size_t l = r->data.ent.entity_len;
  1280. memcpy(&entity[1], r->data.ent.entity, l);
  1281. entity[l + 1] = ';';
  1282. add_assoc_stringl_ex(arr, key, written_k1, entity, l + 2);
  1283. } else {
  1284. unsigned i,
  1285. num_entries;
  1286. const entity_multicodepoint_row *mcpr = r->data.multicodepoint_table;
  1287. if (mcpr[0].leading_entry.default_entity != NULL) {
  1288. size_t l = mcpr[0].leading_entry.default_entity_len;
  1289. memcpy(&entity[1], mcpr[0].leading_entry.default_entity, l);
  1290. entity[l + 1] = ';';
  1291. add_assoc_stringl_ex(arr, key, written_k1, entity, l + 2);
  1292. }
  1293. num_entries = mcpr[0].leading_entry.size;
  1294. for (i = 1; i <= num_entries; i++) {
  1295. size_t l,
  1296. written_k2;
  1297. unsigned uni_cp,
  1298. spe_cp;
  1299. uni_cp = mcpr[i].normal_entry.second_cp;
  1300. l = mcpr[i].normal_entry.entity_len;
  1301. if (!CHARSET_UNICODE_COMPAT(charset)) {
  1302. if (map_from_unicode(uni_cp, charset, &spe_cp) == FAILURE)
  1303. continue; /* non representable in this charset */
  1304. } else {
  1305. spe_cp = uni_cp;
  1306. }
  1307. written_k2 = write_octet_sequence((unsigned char*)&key[written_k1], charset, spe_cp);
  1308. memcpy(&entity[1], mcpr[i].normal_entry.entity, l);
  1309. entity[l + 1] = ';';
  1310. add_assoc_stringl_ex(arr, key, written_k1 + written_k2, entity, l + 2);
  1311. }
  1312. }
  1313. }
  1314. /* }}} */
  1315. /* {{{ proto array get_html_translation_table([int table [, int flags [, string encoding]]])
  1316. Returns the internal translation table used by htmlspecialchars and htmlentities */
  1317. PHP_FUNCTION(get_html_translation_table)
  1318. {
  1319. zend_long all = HTML_SPECIALCHARS,
  1320. flags = ENT_COMPAT;
  1321. int doctype;
  1322. entity_table_opt entity_table;
  1323. const enc_to_uni *to_uni_table = NULL;
  1324. char *charset_hint = NULL;
  1325. size_t charset_hint_len;
  1326. enum entity_charset charset;
  1327. /* in this function we have to jump through some loops because we're
  1328. * getting the translated table from data structures that are optimized for
  1329. * random access, not traversal */
  1330. ZEND_PARSE_PARAMETERS_START(0, 3)
  1331. Z_PARAM_OPTIONAL
  1332. Z_PARAM_LONG(all)
  1333. Z_PARAM_LONG(flags)
  1334. Z_PARAM_STRING(charset_hint, charset_hint_len)
  1335. ZEND_PARSE_PARAMETERS_END();
  1336. charset = determine_charset(charset_hint, /* quiet */ 0);
  1337. doctype = flags & ENT_HTML_DOC_TYPE_MASK;
  1338. LIMIT_ALL(all, doctype, charset);
  1339. array_init(return_value);
  1340. entity_table = determine_entity_table((int)all, doctype);
  1341. if (all && !CHARSET_UNICODE_COMPAT(charset)) {
  1342. to_uni_table = enc_to_uni_index[charset];
  1343. }
  1344. if (all) { /* HTML_ENTITIES (actually, any non-zero value for 1st param) */
  1345. const entity_stage1_row *ms_table = entity_table.ms_table;
  1346. if (CHARSET_UNICODE_COMPAT(charset)) {
  1347. unsigned i, j, k,
  1348. max_i, max_j, max_k;
  1349. /* no mapping to unicode required */
  1350. if (CHARSET_SINGLE_BYTE(charset)) { /* ISO-8859-1 */
  1351. max_i = 1; max_j = 4; max_k = 64;
  1352. } else {
  1353. max_i = 0x1E; max_j = 64; max_k = 64;
  1354. }
  1355. for (i = 0; i < max_i; i++) {
  1356. if (ms_table[i] == empty_stage2_table)
  1357. continue;
  1358. for (j = 0; j < max_j; j++) {
  1359. if (ms_table[i][j] == empty_stage3_table)
  1360. continue;
  1361. for (k = 0; k < max_k; k++) {
  1362. const entity_stage3_row *r = &ms_table[i][j][k];
  1363. unsigned code;
  1364. if (r->data.ent.entity == NULL)
  1365. continue;
  1366. code = ENT_CODE_POINT_FROM_STAGES(i, j, k);
  1367. if (((code == '\'' && !(flags & ENT_HTML_QUOTE_SINGLE)) ||
  1368. (code == '"' && !(flags & ENT_HTML_QUOTE_DOUBLE))))
  1369. continue;
  1370. write_s3row_data(r, code, charset, return_value);
  1371. }
  1372. }
  1373. }
  1374. } else {
  1375. /* we have to iterate through the set of code points for this
  1376. * encoding and map them to unicode code points */
  1377. unsigned i;
  1378. for (i = 0; i <= 0xFF; i++) {
  1379. const entity_stage3_row *r;
  1380. unsigned uni_cp;
  1381. /* can be done before mapping, they're invariant */
  1382. if (((i == '\'' && !(flags & ENT_HTML_QUOTE_SINGLE)) ||
  1383. (i == '"' && !(flags & ENT_HTML_QUOTE_DOUBLE))))
  1384. continue;
  1385. map_to_unicode(i, to_uni_table, &uni_cp);
  1386. r = &ms_table[ENT_STAGE1_INDEX(uni_cp)][ENT_STAGE2_INDEX(uni_cp)][ENT_STAGE3_INDEX(uni_cp)];
  1387. if (r->data.ent.entity == NULL)
  1388. continue;
  1389. write_s3row_data(r, i, charset, return_value);
  1390. }
  1391. }
  1392. } else {
  1393. /* we could use sizeof(stage3_table_be_apos_00000) as well */
  1394. unsigned j,
  1395. numelems = sizeof(stage3_table_be_noapos_00000) /
  1396. sizeof(*stage3_table_be_noapos_00000);
  1397. for (j = 0; j < numelems; j++) {
  1398. const entity_stage3_row *r = &entity_table.table[j];
  1399. if (r->data.ent.entity == NULL)
  1400. continue;
  1401. if (((j == '\'' && !(flags & ENT_HTML_QUOTE_SINGLE)) ||
  1402. (j == '"' && !(flags & ENT_HTML_QUOTE_DOUBLE))))
  1403. continue;
  1404. /* charset is indifferent, used cs_8859_1 for efficiency */
  1405. write_s3row_data(r, j, cs_8859_1, return_value);
  1406. }
  1407. }
  1408. }
  1409. /* }}} */