aboutsummaryrefslogtreecommitdiffstats
path: root/library/markdownify/parsehtml/parsehtml.php
blob: 1a8ecacda89efc17ee1afbb8afbde6fb3472c3d7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
<?php
/**
 * parseHTML is a HTML parser which works with PHP 4 and above.
 * It tries to handle invalid HTML to some degree.
 *
 * @version 1.0 beta
 * @author Milian Wolff (mail@milianw.de, http://milianw.de)
 * @license LGPL, see LICENSE_LGPL.txt and the summary below
 * @copyright (C) 2007  Milian Wolff
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */
class parseHTML {
  /**
   * tags which are always empty (<br /> etc.)
   *
   * @var array<string>
   */
  var $emptyTags = array(
    'br',
    'hr',
    'input',
    'img',
    'area',
    'link',
    'meta',
    'param',
  );
  /**
   * tags with preformatted text
   * whitespaces wont be touched in them
   *
   * @var array<string>
   */
  var $preformattedTags = array(
    'script',
    'style',
    'pre',
    'code',
  );
  /**
   * supress HTML tags inside preformatted tags (see above)
   *
   * @var bool
   */
  var $noTagsInCode = false;
  /**
   * html to be parsed
   *
   * @var string
   */
  var $html = '';
  /**
   * node type:
   *
   * - tag (see isStartTag)
   * - text (includes cdata)
   * - comment
   * - doctype
   * - pi (processing instruction)
   *
   * @var string
   */
  var $nodeType = '';
  /**
   * current node content, i.e. either a
   * simple string (text node), or something like
   * <tag attrib="value"...>
   *
   * @var string
   */
  var $node = '';
  /**
   * wether current node is an opening tag (<a>) or not (</a>)
   * set to NULL if current node is not a tag
   * NOTE: empty tags (<br />) set this to true as well!
   *
   * @var bool | null
   */
  var $isStartTag = null;
  /**
   * wether current node is an empty tag (<br />) or not (<a></a>)
   *
   * @var bool | null
   */
  var $isEmptyTag = null;
  /**
   * tag name
   *
   * @var string | null
   */
  var $tagName = '';
  /**
   * attributes of current tag
   *
   * @var array (attribName=>value) | null
   */
  var $tagAttributes = null;
  /**
   * wether the current tag is a block element
   *
   * @var bool | null
   */
  var $isBlockElement = null;

  /**
   * keep whitespace
   *
   * @var int
   */
  var $keepWhitespace = 0;
  /**
   * list of open tags
   * count this to get current depth
   *
   * @var array
   */
  var $openTags = array();
  /**
   * list of block elements
   *
   * @var array
   * TODO: what shall we do with <del> and <ins> ?!
   */
  var $blockElements = array (
    # tag name => <bool> is block
    # block elements
    'address' => true,
    'blockquote' => true,
    'center' => true,
    'del' => true,
    'dir' => true,
    'div' => true,
    'dl' => true,
    'fieldset' => true,
    'form' => true,
    'h1' => true,
    'h2' => true,
    'h3' => true,
    'h4' => true,
    'h5' => true,
    'h6' => true,
    'hr' => true,
    'ins' => true,
    'isindex' => true,
    'menu' => true,
    'noframes' => true,
    'noscript' => true,
    'ol' => true,
    'p' => true,
    'pre' => true,
    'table' => true,
    'ul' => true,
    # set table elements and list items to block as well
    'thead' => true,
    'tbody' => true,
    'tfoot' => true,
    'td' => true,
    'tr' => true,
    'th' => true,
    'li' => true,
    'dd' => true,
    'dt' => true,
    # header items and html / body as well
    'html' => true,
    'body' => true,
    'head' => true,
    'meta' => true,
    'link' => true,
    'style' => true,
    'title' => true,
    # unfancy media tags, when indented should be rendered as block
    'map' => true,
    'object' => true,
    'param' => true,
    'embed' => true,
    'area' => true,
    # inline elements
    'a' => false,
    'abbr' => false,
    'acronym' => false,
    'applet' => false,
    'b' => false,
    'basefont' => false,
    'bdo' => false,
    'big' => false,
    'br' => false,
    'button' => false,
    'cite' => false,
    'code' => false,
    'del' => false,
    'dfn' => false,
    'em' => false,
    'font' => false,
    'i' => false,
    'img' => false,
    'ins' => false,
    'input' => false,
    'iframe' => false,
    'kbd' => false,
    'label' => false,
    'q' => false,
    'samp' => false,
    'script' => false,
    'select' => false,
    'small' => false,
    'span' => false,
    'strong' => false,
    'sub' => false,
    'sup' => false,
    'textarea' => false,
    'tt' => false,
    'var' => false,
  );
  /**
   * get next node, set $this->html prior!
   *
   * @param void
   * @return bool
   */
  function nextNode() {
    if (empty($this->html)) {
      # we are done with parsing the html string
      return false;
    }
    static $skipWhitespace = true;
    if ($this->isStartTag && !$this->isEmptyTag) {
      array_push($this->openTags, $this->tagName);
      if (in_array($this->tagName, $this->preformattedTags)) {
        # dont truncate whitespaces for <code> or <pre> contents
        $this->keepWhitespace++;
      }
    }

    if ($this->html[0] == '<') {
      $token = substr($this->html, 0, 9);
      if (substr($token, 0, 2) == '<?') {
        # xml prolog or other pi's
        /** TODO **/
        #trigger_error('this might need some work', E_USER_NOTICE);
        $pos = strpos($this->html, '>');
        $this->setNode('pi', $pos + 1);
        return true;
      }
      if (substr($token, 0, 4) == '<!--') {
        # comment
        $pos = strpos($this->html, '-->');
        if ($pos === false) {
          # could not find a closing -->, use next gt instead
          # this is firefox' behaviour
          $pos = strpos($this->html, '>') + 1;
        } else {
          $pos += 3;
        }
        $this->setNode('comment', $pos);

        $skipWhitespace = true;
        return true;
      }
      if ($token == '<!DOCTYPE') {
        # doctype
        $this->setNode('doctype', strpos($this->html, '>')+1);

        $skipWhitespace = true;
        return true;
      }
      if ($token == '<![CDATA[') {
        # cdata, use text node

        # remove leading <![CDATA[
        $this->html = substr($this->html, 9);

        $this->setNode('text', strpos($this->html, ']]>')+3);

        # remove trailing ]]> and trim
        $this->node = substr($this->node, 0, -3);
        $this->handleWhitespaces();

        $skipWhitespace = true;
        return true;
      }
      if ($this->parseTag()) {
        # seems to be a tag
        # handle whitespaces
        if ($this->isBlockElement) {
          $skipWhitespace = true;
        } else {
          $skipWhitespace = false;
        }
        return true;
      }
    }
    if ($this->keepWhitespace) {
      $skipWhitespace = false;
    }
    # when we get here it seems to be a text node
    $pos = strpos($this->html, '<');
    if ($pos === false) {
      $pos = strlen($this->html);
    }
    $this->setNode('text', $pos);
    $this->handleWhitespaces();
    if ($skipWhitespace && $this->node == ' ') {
      return $this->nextNode();
    }
    $skipWhitespace = false;
    return true;
  }
  /**
   * parse tag, set tag name and attributes, see if it's a closing tag and so forth...
   *
   * @param void
   * @return bool
   */
  function parseTag() {
    static $a_ord, $z_ord, $special_ords;
    if (!isset($a_ord)) {
      $a_ord = ord('a');
      $z_ord = ord('z');
      $special_ords = array(
        ord(':'), // for xml:lang
        ord('-'), // for http-equiv
      );
    }

    $tagName = '';

    $pos = 1;
    $isStartTag = $this->html[$pos] != '/';
    if (!$isStartTag) {
      $pos++;
    }
    # get tagName
    while (isset($this->html[$pos])) {
      $pos_ord = ord(strtolower($this->html[$pos]));
      if (($pos_ord >= $a_ord && $pos_ord <= $z_ord) || (!empty($tagName) && is_numeric($this->html[$pos]))) {
        $tagName .= $this->html[$pos];
        $pos++;
      } else {
        $pos--;
        break;
      }
    }

    $tagName = strtolower($tagName);
    if (empty($tagName) || !isset($this->blockElements[$tagName])) {
      # something went wrong => invalid tag
      $this->invalidTag();
      return false;
    }
    if ($this->noTagsInCode && end($this->openTags) == 'code' && !($tagName == 'code' && !$isStartTag)) {
      # we supress all HTML tags inside code tags
      $this->invalidTag();
      return false;
    }

    # get tag attributes
    /** TODO: in html 4 attributes do not need to be quoted **/
    $isEmptyTag = false;
    $attributes = array();
    $currAttrib = '';
    while (isset($this->html[$pos+1])) {
      $pos++;
      # close tag
      if ($this->html[$pos] == '>' || $this->html[$pos].$this->html[$pos+1] == '/>') {
        if ($this->html[$pos] == '/') {
          $isEmptyTag = true;
          $pos++;
        }
        break;
      }

      $pos_ord = ord(strtolower($this->html[$pos]));
      if ( ($pos_ord >= $a_ord && $pos_ord <= $z_ord) || in_array($pos_ord, $special_ords)) {
        # attribute name
        $currAttrib .= $this->html[$pos];
      } elseif (in_array($this->html[$pos], array(' ', "\t", "\n"))) {
        # drop whitespace
      } elseif (in_array($this->html[$pos].$this->html[$pos+1], array('="', "='"))) {
        # get attribute value
        $pos++;
        $await = $this->html[$pos]; # single or double quote
        $pos++;
        $value = '';
        while (isset($this->html[$pos]) && $this->html[$pos] != $await) {
          $value .= $this->html[$pos];
          $pos++;
        }
        $attributes[$currAttrib] = $value;
        $currAttrib = '';
      } else {
        $this->invalidTag();
        return false;
      }
    }
    if ($this->html[$pos] != '>') {
      $this->invalidTag();
      return false;
    }

    if (!empty($currAttrib)) {
      # html 4 allows something like <option selected> instead of <option selected="selected">
      $attributes[$currAttrib] = $currAttrib;
    }
    if (!$isStartTag) {
      if (!empty($attributes) || $tagName != end($this->openTags)) {
        # end tags must not contain any attributes
        # or maybe we did not expect a different tag to be closed
        $this->invalidTag();
        return false;
      }
      array_pop($this->openTags);
      if (in_array($tagName, $this->preformattedTags)) {
        $this->keepWhitespace--;
      }
    }
    $pos++;
    $this->node = substr($this->html, 0, $pos);
    $this->html = substr($this->html, $pos);
    $this->tagName = $tagName;
    $this->tagAttributes = $attributes;
    $this->isStartTag = $isStartTag;
    $this->isEmptyTag = $isEmptyTag || in_array($tagName, $this->emptyTags);
    if ($this->isEmptyTag) {
      # might be not well formed
      $this->node = preg_replace('# */? *>$#', ' />', $this->node);
    }
    $this->nodeType = 'tag';
    $this->isBlockElement = $this->blockElements[$tagName];
    return true;
  }
  /**
   * handle invalid tags
   *
   * @param void
   * @return void
   */
  function invalidTag() {
    $this->html = substr_replace($this->html, '&lt;', 0, 1);
  }
  /**
   * update all vars and make $this->html shorter
   *
   * @param string $type see description for $this->nodeType
   * @param int $pos to which position shall we cut?
   * @return void
   */
  function setNode($type, $pos) {
    if ($this->nodeType == 'tag') {
      # set tag specific vars to null
      # $type == tag should not be called here
      # see this::parseTag() for more
      $this->tagName = null;
      $this->tagAttributes = null;
      $this->isStartTag = null;
      $this->isEmptyTag = null;
      $this->isBlockElement = null;

    }
    $this->nodeType = $type;
    $this->node = substr($this->html, 0, $pos);
    $this->html = substr($this->html, $pos);
  }
  /**
   * check if $this->html begins with $str
   *
   * @param string $str
   * @return bool
   */
  function match($str) {
    return substr($this->html, 0, strlen($str)) == $str;
  }
  /**
   * truncate whitespaces
   *
   * @param void
   * @return void
   */
  function handleWhitespaces() {
    if ($this->keepWhitespace) {
      # <pre> or <code> before...
      return;
    }
    # truncate multiple whitespaces to a single one
    $this->node = preg_replace('#\s+#s', ' ', $this->node);
  }
  /**
   * normalize self::node
   *
   * @param void
   * @return void
   */
  function normalizeNode() {
    $this->node = '<';
    if (!$this->isStartTag) {
      $this->node .= '/'.$this->tagName.'>';
      return;
    }
    $this->node .= $this->tagName;
    foreach ($this->tagAttributes as $name => $value) {
      $this->node .= ' '.$name.'="'.str_replace('"', '&quot;', $value).'"';
    }
    if ($this->isEmptyTag) {
      $this->node .= ' /';
    }
    $this->node .= '>';
  }
}

/**
 * indent a HTML string properly
 *
 * @param string $html
 * @param string $indent optional
 * @return string
 */
function indentHTML($html, $indent = "  ", $noTagsInCode = false) {
  $parser = new parseHTML;
  $parser->noTagsInCode = $noTagsInCode;
  $parser->html = $html;
  $html = '';
  $last = true; # last tag was block elem
  $indent_a = array();
  while($parser->nextNode()) {
    if ($parser->nodeType == 'tag') {
      $parser->normalizeNode();
    }
    if ($parser->nodeType == 'tag' && $parser->isBlockElement) {
      $isPreOrCode = in_array($parser->tagName, array('code', 'pre'));
      if (!$parser->keepWhitespace && !$last && !$isPreOrCode) {
        $html = rtrim($html)."\n";
      }
      if ($parser->isStartTag) {
        $html .= implode($indent_a);
        if (!$parser->isEmptyTag) {
          array_push($indent_a, $indent);
        }
      } else {
        array_pop($indent_a);
        if (!$isPreOrCode) {
          $html .= implode($indent_a);
        }
      }
      $html .= $parser->node;
      if (!$parser->keepWhitespace && !($isPreOrCode && $parser->isStartTag)) {
        $html .= "\n";
      }
      $last = true;
    } else {
      if ($parser->nodeType == 'tag' && $parser->tagName == 'br') {
        $html .= $parser->node."\n";
        $last = true;
        continue;
      } elseif ($last && !$parser->keepWhitespace) {
        $html .= implode($indent_a);
        $parser->node = ltrim($parser->node);
      }
      $html .= $parser->node;

      if (in_array($parser->nodeType, array('comment', 'pi', 'doctype'))) {
        $html .= "\n";
      } else {
        $last = false;
      }
    }
  }
  return $html;
}
/*
# testcase / example
error_reporting(E_ALL);

$html = '<p>Simple block on one line:</p>

<div>foo</div>

<p>And nested without indentation:</p>

<div>
<div>
<div>
foo
</div>
<div style=">"/>
</div>
<div>bar</div>
</div>

<p>And with attributes:</p>

<div>
    <div id="foo">
    </div>
</div>

<p>This was broken in 1.0.2b7:</p>

<div class="inlinepage">
<div class="toggleableend">
foo
</div>
</div>';
#$html = '<a href="asdfasdf"       title=\'asdf\' foo="bar">asdf</a>';
echo indentHTML($html);
die();
*/