html.c 45 KB

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