Coverage Report

Created: 2025-09-27 06:26

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