-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhtmlparser.class.php
More file actions
625 lines (548 loc) · 15.2 KB
/
htmlparser.class.php
File metadata and controls
625 lines (548 loc) · 15.2 KB
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
619
620
621
622
623
624
625
<?php
/**
* HTMLParser class
*
* This parser is normally used to prepare a website template for mailing. All external resources (stylesheets etc) and links are made to internal ones.
*
* @version 0.5
* @author Christian Weber <christian@cw-internetdienste.de>
* @link http://www.cw-internetdienste.de
*
* freely distributable under the MIT Licence
*
*/
class htmlparser {
/**
* regex
*
* Regular expression used to validate urls
*
* (default value: '@\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))@')
*
* @var string
* @access private
*/
private $regex = '@\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))@';
/**
* encoding
*
* Default html encoding used
*
* (default value: 'UTF-8')
*
* @var string
* @access private
*/
private $encoding = 'UTF-8';
/**
* url
*
* The root url used to rewrite existing resources
*
* (default value: '')
*
* @var string
* @access private
*/
private $url = '';
/**
* plain
*
* Stores the plain text version
*
* (default value: '')
*
* @var string
* @access private
*/
private $plain = '';
/**
* finalhtml
*
* Stores the final html code
*
* (default value: '')
*
* @var string
* @access private
*/
private $finalhtml = '';
/**
* htmlfile
*
* Stores the users given source code or file
*
* (default value: '')
*
* @var string
* @access private
*/
private $htmlfile = '';
/**
* node
*
* Stores the node object
*
* (default value: null)
*
* @var mixed
* @access private
*/
private $node = null;
/**
* document
*
* Stores the document paht of the node object
*
* (default value: null)
*
* @var mixed
* @access private
*/
private $document = null;
/**
* nodes
*
* Stores everything beginning at the html tag of the dom object
*
* (default value: null)
*
* @var mixed
* @access private
*/
private $nodes = null;
/**
* source
*
* Toggles whether $htmlfile is a source file or direct source input
*
* (default value: false)
*
* @var bool
* @access private
*/
private $source = false;
/**
* tidy
*
* Toggles tidy usage
*
* (default value: false)
*
* @var bool
* @access private
*/
private $tidy = false;
/**
* html
*
* (default value: array())
*
* @var array
* @access protected
*/
protected $html = array();
/**
* selectors
*
* (default value: array())
*
* @var array
* @access protected
*/
protected $selectors = array();
/**
* styles
*
* (default value: array())
*
* @var array
* @access protected
*/
protected $styles = array();
public function __construct($htmlfile,$url,$source=false,$encoding='UTF-8') {
// if there is no html or valid url given, kill this object
if(!isset($htmlfile) || empty($htmlfile) || trim($htmlfile) == '' || !isset($url) || empty($url) || trim($url) == '' || !$this->validateURL($url) || !is_bool($source)) { return false; }
if(substr($url,-1) !== '/') { $url .= '/'; }
$this->url = $url;
// check if html is source or file
if($source!=false) {
$this->source = true;
}
// check if tidy exists
if(function_exists('tidy_repair_string')) {
$this->tidy = true;
}
// set html file encoding
$this->encoding = $encoding;
// set html file
$this->htmlfile = $htmlfile;
// load the html file
$this->loadHTML();
}
public function get_plain() {
return $this->plain;
}
public function get_html() {
return $this->finalhtml;
}
/**
* validateURL function.
*
* @access private
* @param mixed $url
* @return int
*/
private function validateURL($url) {
if(function_exists('filter_var')) {
return filter_var($url, FILTER_VALIDATE_URL);
} else {
return preg_match($this->regex,$url);
}
}
/**
* loadHTML function.
*
* @access private
*/
private function loadHTML() {
// needed to make html5 tags work in domdocument
libxml_use_internal_errors(true);
// create new dom object
$this->node = new DOMDocument();
// set base tidy configuration
$config = array(
'char-encoding' => $this->encoding,
'output-encoding' => $this->encoding,
'output-xhtml' => true
);
$html = '';
if($this->source === true) {
// tidy up html string
$html = ($this->tidy===true) ? tidy_repair_string($this->htmlfile,$config,$this->encoding):$this->htmlfile;
// load source
$this->node->loadHTML($html);
} else {
// load source
$this->node->loadHTMLFile($this->htmlfile);
}
//preserve whitespace
$this->node->preserveWhiteSpace = true;
// get dom tree
$this->nodes = $this->node->getElementsByTagName('html');
// set document root node
$this->document = $this->node->documentElement;
// create a clean array of the domtree
$this->html = $this->createDomTree($this->nodes);
// clean up markup
$this->cleanHTML();
// save final html
$this->finalhtml = ($this->tidy===true) ? tidy_repair_string($this->node->saveHTML(),$config,$this->encoding):$this->node->saveHTML();
// update tidy configuration
$config['clean'] = true;
$config['show-body-only'] = true;
// save plain text
$this->plain = ($this->tidy===true) ? tidy_repair_string($this->plain,$config,$this->encoding):$this->plain;
libxml_clear_errors();
}
/**
* createDomTree function.
*
* Recursively generates a clean array of nested source dom tree
*
* @access private
* @param DOMNodeList $nodes
* @return array $data
*/
private function createDomTree(DOMNodeList $nodes) {
// node array
$data = array();
// process each node
foreach($nodes as $key => $node) {
// get childs of current node
$childs = $node->childNodes;
// check if node has child nodes
if(!is_null($childs) && count($childs) > 0) {
// add node name and fetch recursively sub-nodes
$d = array(
'element' => $node->nodeName,
'children' => $this->createDomTree($childs)
);
// check if its a css file. if true, load and parse the file
if($node->nodeName === 'link' || $node->nodeName === 'style') {
$this->parseCSS($node);
}
// add plain text version
$this->addPlain($node);
// apply inline css and remove invalid or no more needed attributes
$this->checkNodeStyle($node);
} else {
// has value?
if($node->nodeValue != '') {
// save values
$d = array(
'element' => $node->nodeName,
'value' => $this->checkData($node->nodeName,$node->nodeValue)
);
// check if its a css file. if true, load and parse the file
if($node->nodeName === 'link' || $node->nodeName === 'style') {
$this->parseCSS($node);
}
// apply inline css and remove invalid or no more needed attributes
$this->checkNodeStyle($node,1);
}
}
// check if node has attributes
if($node->hasAttributes()) {
// fetch attributes
$d['attributes'] = $this->getAttributes($node);
}
if($node->nodeName != 'link' && $node->nodeName != 'script' && $node->nodeName != 'style') {
$data[] = $d;
}
}
return $data;
}
/**
* checkNodeStyle function.
*
* @access private
* @param object $node
* @param int $type (default: 0)
*/
private function checkNodeStyle($node,$type=0) {
if(get_class($node) != 'DOMElement') { return false; }
if($type) { $node = $node->parentNode; }
// check what type is needed
if($node->hasAttribute('class')) {
// class selection
// process the selectors
$this->processClassSelectors($node);
} elseif($node->hasAttribute('id')) {
// id selection
// process the selectors
$this->processIDSelectors($node);
} else {
// tag selection
// process teh selectors
$this->processTagSelectors($node);
}
}
/**
* processClassSelectors function.
*
* @access private
* @param DOMElement $node
*/
private function processClassSelectors(DOMElement $node) {
if(!$node) { return false; }
foreach($this->selectors as $key => $item) {
// check if selector is a valid class selector
if(strpos($item,'.') !== false) {
// seperate tag and class
// explode because class could be foo.bar and not just .bar
$class = explode('.',$item);
if((count($class) == 2 && !empty($class[0]) && $node->nodeName == $class[0] && $node->getAttribute('class') == $class[1]) || ((count($class) != 2 || empty($class[0])) && $node->getAttribute('class') == $class[1])) {
// remove class attribute
$node->removeAttribute('class');
// set inline css
($node->hasAttribute('style')) ? $node->setAttribute('style',$node->getAttribute('style').$this->styles[$key]):$node->setAttribute('style',$this->styles[$key]);
}
}
}
}
/**
* processIDSelectors function.
*
* @access private
* @param DOMElement $node
*/
private function processIDSelectors(DOMElement $node) {
if(!$node) { return false; }
foreach($this->selectors as $key => $item) {
// check if selector is a valid id selector
if(strpos($item,'#') !== false) {
// seperate tag and id
// explode because id could be foo#bar and not just #bar
$id = explode('#',$item);
if((count($id) == 2 && !empty($id[0]) && $node->nodeName == $id[0] && $node->getAttribute('id') == $class[1]) || ((count($id) != 2 || empty($id[0])) && $node->getAttribute('id') == $id[1])) {
// remove class attribute
$node->removeAttribute('id');
// set inline css
($node->hasAttribute('style')) ? $node->setAttribute('style',$node->getAttribute('style').$this->styles[$key]):$node->setAttribute('style',$this->styles[$key]);
}
}
}
}
/**
* processTagSelectors function.
*
* @access private
* @param DOMElement $node
*/
private function processTagSelectors(DOMElement $node) {
if(!$node) { return false; }
foreach($this->selectors as $key => $item) {
if($node->nodeName == $item) {
// remove class attribute
// set inline css
($node->hasAttribute('style')) ? $node->setAttribute('style',$node->getAttribute('style').$this->styles[$key]):$node->setAttribute('style',$this->styles[$key]);
}
}
}
/**
* checkData function.
*
* @access private
* @param string $type
* @param string $val
* @return string $val
*/
private function checkData($type,$val) {
if(!isset($type) || empty($type) || trim($type) === '' || !isset($val)) { return false; }
// check if data needs to be changed
// TODO: check if url is already absolute
switch($type) {
case 'src': if(substr($val,0,1) == '/') { $val = substr($val,1); }
$val = $this->encodeImage($this->url.$val); // relative to absolute path + base64 encode
break;
case 'href': if(substr($val,0,1) == '/') { $val = substr($val,1); }
$val = $this->url.$val; // relative to absolute path
break;
case '#text': $val = htmlentities($val); // convert characters to correct entities
break;
}
return $val;
}
private function encodeImage($src) {
// TODO: check for allowed image extension to exlude videos
$data = file_get_contents($src);
$mime = getimagesize($src);
return 'data:'.$mime['mime'].';base64,'.base64_encode($data);
}
/**
* addPlain function.
*
* @access private
* @param DOMElement $node
*/
private function addPlain(DOMElement $node) {
$text = '';
// check type of node
switch($node->nodeName) {
case 'h1':
case 'h2':
case 'h3':
case 'h4':
case 'h5':
case 'h6': $text .= ''.strtoupper($node->nodeValue).PHP_EOL;
for($i=0;$i<strlen($node->nodeValue);$i++) {
$text.= '-';
}
$text .= PHP_EOL;
break;
case '#text':
case 'p': $text .= $node->nodeValue.' '.PHP_EOL;
break;
case 'br': $text .= PHP_EOL;
break;
case 'tr':
case 'hr': $text .= '-----------------------------------------------------'.PHP_EOL;
break;
}
// add to plain text version
if(!empty($text) && trim($text) != '') { $this->plain .= $text; }
}
/**
* cleanHTML function.
*
* Removes all unallowed data from source as style, script and link tags
*
* @access private
*/
private function cleanHTML() {
// clean all unallowed tags
$styles = $this->node->getElementsByTagName('style');
$scripts = $this->node->getElementsByTagName('script');
$stylesheets = $this->node->getElementsByTagName('link');
// delete style tags
foreach($styles as $node) {
$node->parentNode->removeChild($node);
}
// delete script tags
foreach($scripts as $node) {
$node->parentNode->removeChild($node);
}
// delete link tags
foreach($stylesheets as $node) {
$node->parentNode->removeChild($node);
}
}
/**
* getAttributes function.
*
* Rewrites the attributes of a node and checks them. Also prepares them for the $html array
*
* @access private
* @param DOMElement $node
* @return array $attributes
*/
private function getAttributes(DOMElement $node) {
// attribuets array
$attributes = array();
$_attr = $node->attributes;
foreach($_attr as $attr) {
$val = $this->checkData($attr->nodeName,$attr->nodeValue);
$attributes[] = array(
'name' => $attr->nodeName,
'value' => $val
);
$node->setAttribute($attr->nodeName,$val);
}
return $attributes;
}
/**
* parseCSS function.
*
* Checks whether a node is a stylesheet or style tag. If true tokenizes the styles and adds css to internal variables
*
* @access private
* @param DOMElement $node
* @return int
*/
private function parseCSS(DOMElement $node) {
// if node is no style tag or stylesheet return
if(!$node->hasAttribute('href') && !$node->nodeName == 'style') { return false; }
// load the file or style tag value
$style = ($node->nodeName=='style') ? explode('<br />',nl2br($node->nodeValue)):file($this->checkData('href',$node->getAttribute('href')));
$css = '';
if(!is_array($style)) { return false; }
// read style and strip whitespaces
foreach($style as $line) {
if(substr($line,0,1) !== '@') {
$css .= trim($line);
}
}
// remove brackets via tokenizer
$token = strtok($css,'{}');
$tokenized = array();
// process tokenized elments
while($token !== false) {
$tokenized[] = $token;
$token = strtok('{}');
}
// check amount of elements
$size = count($tokenized);
// process elements
for($i=0;$i<$size;$i+=2) {
// can be multiple selectors for the same style, split them
$selectors = explode(',',$tokenized[$i]);
// assign selectors and their styles
foreach($selectors as $selector) {
$this->selectors[] = trim($selector);
$this->styles[] = trim($tokenized[$i+1]);
}
}
}
}
?>