-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhtml.php
More file actions
295 lines (242 loc) · 8.24 KB
/
Copy pathhtml.php
File metadata and controls
295 lines (242 loc) · 8.24 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
<?php
namespace Puchiko\html;
use DOMDocument;
use DOMNode;
use DOMXPath;
function drawAlert(string $message) {
$escapedMessage = addslashes($message);
$escapedMessage = str_replace(array("\r", "\n"), '', $escapedMessage);
echo " <script type='text/javascript'>
alert('" . $escapedMessage . "');
</script>";
}
/**
* Create a DOMDocument from an HTML fragment.
*
* A temporary wrapper element is added around the fragment to prevent
* DOMDocument from discarding or rearranging the user's original root
* elements when normalizing the HTML. This wrapper is later removed
* before returning the final truncated output.
*
* @param string $html The source HTML
* @return DOMDocument The loaded DOMDocument instance
*/
function createDomFromHtml(string $html): DOMDocument {
$dom = new DOMDocument();
// Suppress libxml warnings during HTML parsing
$prev = libxml_use_internal_errors(true);
$dom->loadHTML(
'<?xml encoding="utf-8" ?><div id="__root_wrapper__">' . $html . '</div>',
LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD
);
// Clear any collected errors and restore previous state
libxml_clear_errors();
libxml_use_internal_errors($prev);
return $dom;
}
/**
* Get the actual root node that contains the HTML fragment.
*
* In this implementation, the traversal root remains <body> because the
* recursive truncation logic already functions correctly starting from
* the body element. The wrapper exists only to keep the fragment stable
* during parsing and is stripped after traversal.
*
* @param DOMDocument $dom
* @return DOMNode
*/
function getDomRoot(DOMDocument $dom): DOMNode {
$body = $dom->getElementsByTagName('body')->item(0);
if ($body !== null) {
return $body;
}
return $dom->documentElement;
}
/**
* Truncate an HTML string to a fixed number of text characters while
* keeping the resulting markup valid. Tags remain balanced, entities
* remain intact, and the DOM is walked recursively from the traversal
* root returned by getDomRoot(). The wrapper introduced in
* createDomFromHtml() is removed before returning the final result.
*
* @param string $html The source HTML to truncate
* @param int $limit Maximum number of text characters allowed
* @return string The truncated, valid HTML
*/
function truncateHtml(string $html, int $limit): string {
$dom = createDomFromHtml($html);
$root = getDomRoot($dom);
$count = 0;
$end = false;
$walker = function(DOMNode $node) use (&$walker, &$count, $limit, &$end) {
if ($end) {
return;
}
// Handle plain text nodes
if ($node->nodeType === XML_TEXT_NODE) {
$len = mb_strlen($node->nodeValue);
// If the limit would be exceeded, truncate this text node
if ($count + $len > $limit) {
$keep = max(0, $limit - $count);
$node->nodeValue = mb_substr($node->nodeValue, 0, $keep);
$end = true;
}
$count += $len;
return;
}
// Recursively walk element child nodes
for ($i = 0; $i < $node->childNodes->length; $i++) {
$child = $node->childNodes->item($i);
$walker($child);
// After truncation, remove any remaining siblings
if ($end) {
while ($node->childNodes->length > $i + 1) {
$node->removeChild($node->lastChild);
}
break;
}
}
};
$walker($root);
// Remove the wrapper and return only its child content
$wrapper = $dom->getElementById('__root_wrapper__');
if ($wrapper !== null) {
// If wrapper has a single child, return only that child's HTML
if ($wrapper->childNodes->length === 1) {
return $dom->saveHTML($wrapper->firstChild);
}
// Otherwise concatenate all children
$out = '';
for ($i = 0; $i < $wrapper->childNodes->length; $i++) {
$out .= $dom->saveHTML($wrapper->childNodes->item($i));
}
return $out;
}
// Fallback: return the traversal root if wrapper is missing
return $dom->saveHTML($root);
}
/**
* Truncate an HTML fragment by limiting the number of <br> line breaks.
* Everything after the allowed number of breaks is removed.
*
* @param string $html The source HTML fragment
* @param int $maxLines Maximum number of <br>-separated lines to keep
* @return string The truncated HTML fragment
*/
function truncateHtmlByLineBreak(string $html, int $maxLines): string {
// Load HTML fragment into DOMDocument
$dom = createDomFromHtml($html);
// Select the actual fragment root
$root = getDomRoot($dom);
// Find all <br> elements under the root, in document order
$xpath = new DOMXPath($dom);
$brNodes = $xpath->query('.//br', $root);
// If there are not more than $maxLines <br> tags, no truncation needed
if ($brNodes === false || $brNodes->length <= $maxLines) {
$wrapper = $dom->getElementById('__root_wrapper__');
if ($wrapper !== null) {
if ($wrapper->childNodes->length === 1) {
return $dom->saveHTML($wrapper->firstChild);
}
$out = '';
for ($i = 0; $i < $wrapper->childNodes->length; $i++) {
$out .= $dom->saveHTML($wrapper->childNodes->item($i));
}
return $out;
}
return $dom->saveHTML($root);
}
// This is the first <br> that should be removed (the (maxLines + 1)-th one)
$limitNode = $brNodes->item($maxLines);
// Recursive pruner: walks the tree and, once it finds $limitNode,
// removes it and everything that comes after it in document order.
$prune = function(DOMNode $node) use (&$prune, $limitNode): bool {
for ($i = 0; $i < $node->childNodes->length; $i++) {
$child = $node->childNodes->item($i);
// If we've reached the limit <br>, remove it and all following siblings
if ($child === $limitNode) {
while ($node->childNodes->length > $i) {
$node->removeChild($node->lastChild);
}
return true;
}
// Recurse into children
if ($child->hasChildNodes()) {
if ($prune($child)) {
// Truncation happened inside this child; remove all siblings after it
while ($node->childNodes->length > $i + 1) {
$node->removeChild($node->lastChild);
}
return true;
}
}
}
// No truncation triggered in this subtree
return false;
};
// Perform the pruning starting from the fragment root
$prune($root);
// Strip the wrapper and return only the fragment content (same pattern as truncateHtml)
$wrapper = $dom->getElementById('__root_wrapper__');
if ($wrapper !== null) {
if ($wrapper->childNodes->length === 1) {
return $dom->saveHTML($wrapper->firstChild);
}
$out = '';
for ($i = 0; $i < $wrapper->childNodes->length; $i++) {
$out .= $dom->saveHTML($wrapper->childNodes->item($i));
}
return $out;
}
return $dom->saveHTML($root);
}
/**
* Count the number of <br> elements in an HTML fragment.
*
* @param string $html The source HTML
* @return int The number of <br> tags found
*/
function countHtmlLineBreaks(string $html): int {
$dom = createDomFromHtml($html);
$root = getDomRoot($dom);
$xpath = new DOMXPath($dom);
$brNodes = $xpath->query('.//br', $root);
if ($brNodes === false) {
return 0;
}
return $brNodes->length;
}
/**
* Close any unclosed HTML tags in a fragment.
*
* Scans for opening and closing tags, tracks which are still open,
* and appends closing tags in reverse order. This acts as a safety
* net after truncation to prevent formatting from leaking.
*
* @param string $html The HTML fragment that may have unclosed tags
* @return string The HTML with all tags properly closed
*/
function closeUnclosedTags(string $html): string {
$voidElements = ['br', 'hr', 'img', 'input', 'meta', 'link', 'area', 'base', 'col', 'embed', 'source', 'track', 'wbr'];
preg_match_all('#<(/?)([a-z][a-z0-9]*)\b[^>]*/?>#i', $html, $matches, PREG_SET_ORDER);
$openTags = [];
foreach ($matches as $match) {
$isClosing = $match[1] === '/';
$tagName = strtolower($match[2]);
if (in_array($tagName, $voidElements, true)) {
continue;
}
if ($isClosing) {
$key = array_search($tagName, array_reverse($openTags, true));
if ($key !== false) {
unset($openTags[$key]);
}
} else {
$openTags[] = $tagName;
}
}
foreach (array_reverse($openTags) as $tag) {
$html .= "</$tag>";
}
return $html;
}