html.c 48 KB

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