Coverage Report

Created: 2022-02-19 20:31

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