-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathclean_html.php
395 lines (313 loc) · 11.5 KB
/
clean_html.php
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
<?php
declare(strict_types = 1);
namespace html2md;
class CleanHTML
{
private $_arrContentDOM = array();
private $_arrRemoveDOM = array();
private $_arrRemoveAttribs = array();
private $_arrRegex = array();
private $html = '';
private $source_url = '';
public function __construct(string $html, string $source_url)
{
$this->html = $html;
$this->source_url = $source_url;
// Initialization
$this->_arrContentDOM = array();
$this->_arrRemoveDOM = array();
$this->_arrRemoveAttribs = array();
$this->_arrRegex = array();
return true;
}
/**
* The regex entry of plugins->options->task->fetch
* contains search&replace expression for the content
* f.i. Search a specific content and replace it by
* a new value
*/
public function setRegex($arr){
$this->_arrRegex = $arr;
}
/**
* List of nodes where the content is placed.
* That list will allow to faster retrieved desired
* content and not pollute content by additional
* elements like comments, navigation, ...
*/
public function setContentDOM($arr)
{
$this->_arrContentDOM = $arr;
}
/**
* List of nodes that can be removed since they are not
* part of the content we want to keep
*/
public function setRemoveDOM($arr)
{
$this->_arrRemoveDOM = $arr;
}
/**
* List of attributes that can be removed from html tags
* once the desired content is isolated they are not part
* of the content we want to keep
*/
public function setRemoveAttributes($arr)
{
$this->_arrRemoveAttribs = $arr;
}
/**
* The HTML string contains the full source code (with head,
* body, footer, ...) and also with a lot of things like
* the navigation page, an aside block and so on.
*
* But the content is perhaps stored in a <article> tag or
* or in a <div class="article"> or ...
*
* The objective of this function is to "target" only the
* desired block and don't keep unneeded ones
*/
private function keepDOMElements(string $selector) : void
{
$dom = new \DOMDocument();
$dom->encoding = 'utf-8';
// Don't worry about spaces
$dom->preserveWhiteSpace = false;
// IMPORTANT !!! Add xml encoding to keep emoji f.i.
@$dom->loadHTML('<?xml encoding="utf-8" ?>'.$this->html);
// We'll search DOM elements
$xpath = new \DOMXPath($dom);
// If we find an element, got it ! We can keep it and
// update the html string to only that part.
foreach ($xpath->query($selector) as $e) {
$this->html = $dom->saveHTML($e);
}
return;
}
/**
* Remove unneeded attributes in HTML tags; remove f.i.
* style, class, title, ... based on $_arrRemoveAttribs
*/
private function removeDOMAttributes(string $attrib) : void
{
$dom = new \DOMDocument;
$dom->encoding = 'utf-8';
// Don't worry about spaces
$dom->preserveWhiteSpace = false;
// IMPORTANT !!! Add xml encoding to keep emoji f.i.
@$dom->loadHTML('<?xml encoding="utf-8" ?>'.$this->html);
$xpath = new \DOMXPath($dom);
// Find elements with a style attribute
$nodes = $xpath->query('//*[@'.$attrib.']');
foreach ($nodes as $node) {
$node->removeAttribute($attrib);
}
$this->html = $dom->saveHTML();
return;
}
/**
* Remove all empty tags (remove <p></p>, <div></div>, ... f.i.)
* @Link https://stackoverflow.com/a/10818570/1065340
*/
private function removeEmptyDOMElement() : void
{
$dom = new \DOMDocument;
$dom->preserveWhiteSpace = false;
$dom->encoding = 'utf-8';
// IMPORTANT !!! Add xml encoding to keep emoji f.i.
@$dom->loadHTML('<?xml encoding="utf-8" ?>'.$this->html);
$xpath = new \DOMXPath($dom);
// Check against the following attributes and if empty
// remove them
$arrRemove = array('div', 'p', 'span');
for($i=0; $i<count($arrRemove); ++$i) {
$list = $xpath->query("//".$arrRemove[$i]);
for($j=0; $j<$list->length; ++$j) {
$node = $list->item($j);
if ( (!$node->hasChildNodes() ) && (trim($node->nodeValue)=='')) {
$node->parentNode->removeChild($node);
}
}
}
$this->html = $dom->saveHTML($dom->documentElement);
return;
}
private function removeDOMElements(string $selector) : void
{
$dom = new \DOMDocument();
$dom->encoding = 'utf-8';
// Don't worry about spaces
$dom->preserveWhiteSpace = false;
// IMPORTANT !!! Add xml encoding to keep emoji f.i.
@$dom->loadHTML('<?xml encoding="utf-8" ?>'.$this->html);
// We'll search DOM elements
$xpath = new \DOMXPath($dom);
// For each elements that we can found; just remove it
foreach ($xpath->query($selector) as $e) {
// Delete this node
$e->parentNode->removeChild($e);
}
$this->html = $dom->saveHTML($dom->documentElement);
return;
}
/**
* Make the src image link absolute
* Convert /image/img.jpg to https://website/image/img.jpg
*
* $rel = relative link to the image (from the img src attribute)
* $base = base URL, URL of the page.
*
* @link https://stackoverflow.com/a/5653947
*/
private function makeImgURLAbsolute(string $rel, string $base) : string
{
if (parse_url($rel, PHP_URL_SCHEME) != '') {
return $rel;
}
if ($rel[0]=='#' || $rel[0]=='?') {
return $base.$rel;
}
extract(parse_url($base));
$path = preg_replace('#/[^/]*$#', '', $path);
if ($rel[0] == '/') {
$path = '';
}
$abs = "$host$path/$rel";
$re = array('#(/\.?/)#', '#/(?!\.\.)[^/]+/\.\./#');
for($n=1; $n>0; $abs=preg_replace($re, '/', $abs, -1, $n)) {
}
return $scheme.'://'.$abs;
}
/**
* Process every img tags, analyze the src attribute and
* make img link absolute
*/
private function updateDOMImages(): void
{
$dom = new \DOMDocument();
$dom->encoding = 'utf-8';
// Don't worry about spaces
$dom->preserveWhiteSpace = false;
// IMPORTANT !!! Add xml encoding to keep emoji f.i.
@$dom->loadHTML('<?xml encoding="utf-8" ?>'.$this->html);
// We'll search DOM elements
$xpath = new \DOMXPath($dom);
// Process every img and specifically his src attribute
$images = $xpath->query('//img/@src');
foreach ($images as $img) {
// Get the src
$src = $img->value;
$src = self::makeImgURLAbsolute($src,$this->source_url);
// Set the img source absolute (with the full http://)
$img->value = $src;
}
$this->html = $dom->saveHTML($dom->documentElement);
}
private function processRegex() : void
{
foreach ($this->_arrRegex as $regex) {
// Retrieve the regex pattern for the search
$search = $regex['search'];
if (isset($regex['replace_by'])) {
$replace = $regex['replace_by'];
if (preg_match_all($search, $this->html, $matches)) {
foreach ($matches as $match) {
$this->html = str_replace($match, $replace, $this->html);
}
}
}
}
return;
}
/**
* h1, h2, ... should be on a new line; can't follow
* other elements and the text should follow the start
* tag (i.e. "<h2>TEXT" and not "<h2> (can be CRLF) text"
*/
private function updateHeadings(): void
{
// Match all headings
$regex = '~<h[1-6]>.*<\/h[1-6]>~im';
$this->html = preg_replace($regex, "\n\n$0",
$this->html);
// No space after the tag (match '<h2> TEXT'
// and replace by '<h2>TEXT')
$regex = '~(<h[1-6^>]+>)(\s*)~im';
$this->html = preg_replace($regex, "$1",
$this->html);
// No space after the text (match '<h2>TEXT </h2>'
// and replace by '<h2>TEXT</h2>')
$regex = '~(<h[1-6^>]+>)(.*)(\s*)(</h[1-6^>]+>)~im';
if (preg_match_all($regex, $this->html, $matches)) {
$j = count($matches);
for ($i=0; $i<$j; $i++) {
// Remove end-of-line and other spaces
if (isset($matches[1][$i])) {
$start_tag = trim($matches[1][$i]);
$content = trim($matches[2][$i]);
$end_tag = $matches[4][$i];
$this->html = str_replace($matches[0][$i],
$start_tag.$content.$end_tag, $this->html);
}
}
}
return;
}
public function doIt() : string
{
// Remove HTML comments
$this->html = preg_replace('/<!--(.*)-->/Uis', '', $this->html);
// Remove inline script
$this->html = preg_replace('#<script(.*?)>(.*?)</script>#is', '', $this->html);
// Target only needed content
if (count($this->_arrContentDOM) > 0) {
foreach ($this->_arrContentDOM as $selector) {
self::keepDOMElements($selector);
}
}
// Remove unneeded content
// Use the $arrRemoveDOM array given during the construction
// of this class. $arrRemoveDOM is feed from the settings.json
// file and more specifically from the node
// plugins->options->task->fetch->remove entry
if (count($this->_arrRemoveDOM) > 0) {
foreach ($this->_arrRemoveDOM as $selector) {
self::removeDOMElements($selector);
}
}
// ------------------------
// From now, it's supposed that $this->html contains
// only the wanted content (no more unwanted nav/span/div/...)
//
// Make the HTML cleaner by removed class, inline style, ids,
// targets (for anchor). Don't remove anything since we need
// to keep src for images, href for anchors, ...
// Remove unneeded attributes (like class, style, id, ...)
if (count($this->_arrRemoveAttribs) > 0) {
foreach ($this->_arrRemoveAttribs as $attrib) {
self::removeDOMAttributes($attrib);
}
}
// Update the img tag, change the "src" attribute
self::updateDOMImages();
// Remove spaces between (not inside!!!) tags.
// so "</div> ( a lot of space and CRLF ) <div>" will become
// "</div><div>"
$this->html = preg_replace('/(\>)\s*(\<)/m', '$1$2', $this->html);
// Remove empty tags (f.i. remove any <p></p>)
self::removeEmptyDOMElement();
// We're almost done.
// Check if there were regex expressions and if so, process
// them
if (count($this->_arrRegex) > 0) {
self::processRegex();
// Perhaps do we have again empty DOM elements
// Remove them in that case
self::removeEmptyDOMElement();
}
// h1, h2, ... should be on a new line; can't follow
// other elements and the title should follow the start tag
self::updateHeadings();
return $this->html;
}
}