Completed
Push — master ( 37c80b...8da425 )
by Tim
15:43
created
Classes/Service/CleanHtmlService.php 2 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -520,7 +520,7 @@
 block discarded – undo
520 520
     /**
521 521
      * Include configured header comment in HTML content block
522 522
      *
523
-     * @param $html
523
+     * @param string $html
524 524
      */
525 525
     public function includeHeaderComment(&$html)
526 526
     {
Please login to merge, or discard this patch.
Indentation   +512 added lines, -512 removed lines patch added patch discarded remove patch
@@ -17,516 +17,516 @@
 block discarded – undo
17 17
 class CleanHtmlService implements SingletonInterface
18 18
 {
19 19
 
20
-    /**
21
-     * Enable Debug comment in footer
22
-     *
23
-     * @var boolean
24
-     */
25
-    protected $debugComment = false;
26
-
27
-    /**
28
-     * Format Type
29
-     *
30
-     * @var integer
31
-     */
32
-    protected $formatType = 0;
33
-
34
-    /**
35
-     * Tab character
36
-     *
37
-     * @var string
38
-     */
39
-    protected $tab = "\t";
40
-
41
-    /**
42
-     * Newline character
43
-     *
44
-     * @var string
45
-     */
46
-    protected $newline = "\n";
47
-
48
-    /**
49
-     * Configured extra header comment
50
-     *
51
-     * @var string
52
-     */
53
-    protected $headerComment = '';
54
-
55
-    /**
56
-     * Empty space char
57
-     * @var string
58
-     */
59
-    protected $emptySpaceChar = ' ';
60
-
61
-    /**
62
-     * Set variables based on given config
63
-     *
64
-     * @param array $config
65
-     *
66
-     * @return void
67
-     */
68
-    public function setVariables(array $config)
69
-    {
70
-        // Set newline based on OS
71
-        if (Environment::isWindows()) {
72
-            $this->newline = "\r\n";
73
-        } else {
74
-            $this->newline = "\n";
75
-        }
76
-
77
-        if (!empty($config)) {
78
-            if ($config['formatHtml'] && is_numeric($config['formatHtml'])) {
79
-                $this->formatType = (int)$config['formatHtml'];
80
-            }
81
-
82
-            if ($config['formatHtml.']['tabSize'] && is_numeric($config['formatHtml.']['tabSize'])) {
83
-                $this->tab = str_pad('', $config['formatHtml.']['tabSize'], ' ');
84
-            }
85
-
86
-            if (isset($config['formatHtml.']['debugComment'])) {
87
-                $this->debugComment = (bool)$config['formatHtml.']['debugComment'];
88
-            }
89
-
90
-            if (isset($config['headerComment'])) {
91
-                $this->headerComment = $config['headerComment'];
92
-            }
93
-
94
-            if (isset($config['dropEmptySpaceChar']) && (bool)$config['dropEmptySpaceChar']) {
95
-                $this->emptySpaceChar = '';
96
-            }
97
-        }
98
-    }
99
-
100
-    /**
101
-     * Clean given HTML with formatter
102
-     *
103
-     * @param string $html
104
-     * @param array $config
105
-     *
106
-     * @return string
107
-     */
108
-    public function clean($html, $config = [])
109
-    {
110
-        if (!empty($config)) {
111
-            if ((bool)$config['enabled'] === false) {
112
-                return $html;
113
-            }
114
-
115
-            $this->setVariables($config);
116
-        }
117
-
118
-        $manipulations = [];
119
-
120
-        if (isset($config['removeGenerator']) && (bool)$config['removeGenerator']) {
121
-            $manipulations['removeGenerator'] = GeneralUtility::makeInstance(RemoveGenerator::class);
122
-        }
123
-
124
-        if (isset($config['removeComments']) && (bool)$config['removeComments']) {
125
-            $manipulations['removeComments'] = GeneralUtility::makeInstance(RemoveComments::class);
126
-        }
127
-
128
-        if (isset($config['removeBlurScript']) && (bool)$config['removeBlurScript']) {
129
-            $manipulations['removeBlurScript'] = GeneralUtility::makeInstance(RemoveBlurScript::class);
130
-        }
131
-
132
-        if (!empty($this->headerComment)) {
133
-            $this->includeHeaderComment($html);
134
-        }
135
-
136
-        foreach ($manipulations as $key => $manipulation) {
137
-            /** @var ManipulationInterface $manipulation */
138
-            $configuration = isset($config[$key . '.']) && is_array($config[$key . '.']) ? $config[$key . '.'] : [];
139
-            $html = $manipulation->manipulate($html, $configuration);
140
-        }
141
-
142
-        if ($this->formatType > 0) {
143
-            $html = $this->formatHtml($html);
144
-        }
145
-
146
-        return $html;
147
-    }
148
-
149
-    /**
150
-     * Formats the (X)HTML code:
151
-     *  - taps according to the hirarchy of the tags
152
-     *  - removes empty spaces between tags
153
-     *  - removes linebreaks within tags (spares where necessary: pre, textarea, comments, ..)
154
-     *  choose from five options:
155
-     *    0 => off
156
-     *    1 => no line break at all  (code in one line)
157
-     *    2 => minimalistic line breaks (structure defining box-elements)
158
-     *    3 => aesthetic line breaks (important box-elements)
159
-     *    4 => logic line breaks (all box-elements)
160
-     *    5 => max line breaks (all elements)
161
-     *
162
-     * @param string $html
163
-     *
164
-     * @return string
165
-     */
166
-    protected function formatHtml($html)
167
-    {
168
-        // Save original formated comments, pre, textarea, styles and java-scripts & replace them with markers
169
-        preg_match_all(
170
-            '/(?s)((<!--.*?-->)|(<[ \n\r]*pre[^>]*>.*?<[ \n\r]*\/pre[^>]*>)|(<[ \n\r]*textarea[^>]*>.*?<[ \n\r]*\/textarea[^>]*>)|(<[ \n\r]*style[^>]*>.*?<[ \n\r]*\/style[^>]*>)|(<[ \n\r]*script[^>]*>.*?<[ \n\r]*\/script[^>]*>))/im',
171
-            $html,
172
-            $matches
173
-        );
174
-        $noFormat = $matches[0]; // do not format these block elements
175
-        for ($i = 0; $i < count($noFormat); $i++) {
176
-            $html = str_replace($noFormat[$i], "\n<!-- ELEMENT $i -->", $html);
177
-        }
178
-
179
-        // define box elements for formatting
180
-        $trueBoxElements = 'address|blockquote|center|dir|div|dl|fieldset|form|h1|h2|h3|h4|h5|h6|hr|isindex|menu|noframes|noscript|ol|p|pre|table|ul|article|aside|details|figcaption|figure|footer|header|hgroup|menu|nav|section';
181
-        $functionalBoxElements = 'dd|dt|frameset|li|tbody|td|tfoot|th|thead|tr|colgroup';
182
-        $usableBoxElements = 'applet|button|del|iframe|ins|map|object|script';
183
-        $imagineBoxElements = 'html|body|head|meta|title|link|script|base|!--';
184
-        $allBoxLikeElements = '(?>' . $trueBoxElements . '|' . $functionalBoxElements . '|' . $usableBoxElements . '|' . $imagineBoxElements . ')';
185
-        $esteticBoxLikeElements = '(?>html|head|body|meta name|title|div|table|h1|h2|h3|h4|h5|h6|p|form|pre|center|!--)';
186
-        $structureBoxLikeElements = '(?>html|head|body|div|!--)';
187
-
188
-        // split html into it's elements
189
-        $htmlArrayTemp = preg_split(
190
-            '/(<(?:[^<>]+(?:"[^"]*"|\'[^\']*\')?)+>)/',
191
-            $html,
192
-            -1,
193
-            PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY
194
-        );
195
-        // remove empty lines
196
-        $htmlArray = [''];
197
-        $z = 1;
198
-        for ($x = 0; $x < count($htmlArrayTemp); $x++) {
199
-            $t = trim($htmlArrayTemp[$x]);
200
-            if ($t !== '') {
201
-                $htmlArray[$z] = $htmlArrayTemp[$x];
202
-                $z++;
203
-            } else {
204
-                $htmlArray[$z] = $this->emptySpaceChar;
205
-                $z++;
206
-            }
207
-        }
208
-
209
-        // rebuild html
210
-        $html = '';
211
-        $tabs = 0;
212
-        for ($x = 0; $x < count($htmlArray); $x++) {
213
-            // check if the element should stand in a new line
214
-            $newline = false;
215
-            if (substr($htmlArray[$x - 1], 0, 5) == '<?xml') {
216
-                $newline = true;
217
-            } elseif ($this->formatType == 2 && ( // minimalistic line break
218
-                    # this element has a line break before itself
219
-                    preg_match(
220
-                        '/<' . $structureBoxLikeElements . '(.*)>/Usi',
221
-                        $htmlArray[$x]
222
-                    ) || preg_match(
223
-                        '/<' . $structureBoxLikeElements . '(.*) \/>/Usi',
224
-                        $htmlArray[$x]
225
-                    ) || # one element before is a element that has a line break after
226
-                    preg_match(
227
-                        '/<\/' . $structureBoxLikeElements . '(.*)>/Usi',
228
-                        $htmlArray[$x - 1]
229
-                    ) || substr(
230
-                        $htmlArray[$x - 1],
231
-                        0,
232
-                        4
233
-                    ) == '<!--' || preg_match('/<' . $structureBoxLikeElements . '(.*) \/>/Usi', $htmlArray[$x - 1]))
234
-            ) {
235
-                $newline = true;
236
-            } elseif ($this->formatType == 3 && ( // aestetic line break
237
-                    # this element has a line break before itself
238
-                    preg_match(
239
-                        '/<' . $esteticBoxLikeElements . '(.*)>/Usi',
240
-                        $htmlArray[$x]
241
-                    ) || preg_match(
242
-                        '/<' . $esteticBoxLikeElements . '(.*) \/>/Usi',
243
-                        $htmlArray[$x]
244
-                    ) || # one element before is a element that has a line break after
245
-                    preg_match('/<\/' . $esteticBoxLikeElements . '(.*)>/Usi', $htmlArray[$x - 1]) || substr(
246
-                        $htmlArray[$x - 1],
247
-                        0,
248
-                        4
249
-                    ) == '<!--' || preg_match('/<' . $esteticBoxLikeElements . '(.*) \/>/Usi', $htmlArray[$x - 1]))
250
-            ) {
251
-                $newline = true;
252
-            } elseif ($this->formatType >= 4 && ( // logical line break
253
-                    # this element has a line break before itself
254
-                    preg_match(
255
-                        '/<' . $allBoxLikeElements . '(.*)>/Usi',
256
-                        $htmlArray[$x]
257
-                    ) || preg_match(
258
-                        '/<' . $allBoxLikeElements . '(.*) \/>/Usi',
259
-                        $htmlArray[$x]
260
-                    ) || # one element before is a element that has a line break after
261
-                    preg_match('/<\/' . $allBoxLikeElements . '(.*)>/Usi', $htmlArray[$x - 1]) || substr(
262
-                        $htmlArray[$x - 1],
263
-                        0,
264
-                        4
265
-                    ) == '<!--' || preg_match('/<' . $allBoxLikeElements . '(.*) \/>/Usi', $htmlArray[$x - 1]))
266
-            ) {
267
-                $newline = true;
268
-            }
269
-
270
-            // count down a tab
271
-            if (substr($htmlArray[$x], 0, 2) == '</') {
272
-                $tabs--;
273
-            }
274
-
275
-            // add tabs and line breaks in front of the current tag
276
-            if ($newline) {
277
-                $html .= $this->newline;
278
-                for ($y = 0; $y < $tabs; $y++) {
279
-                    $html .= $this->tab;
280
-                }
281
-            }
282
-
283
-            // remove white spaces and line breaks and add current tag to the html-string
284
-            if (substr($htmlArray[$x - 1], 0, 4) == '<pre' // remove white space after line ending in PRE / TEXTAREA / comment
285
-                || substr($htmlArray[$x - 1], 0, 9) == '<textarea' || substr($htmlArray[$x - 1], 0, 4) == '<!--'
286
-            ) {
287
-                $html .= $this->rTrimLines($htmlArray[$x]);
288
-            } elseif (substr($htmlArray[$x], 0, 9) == '<![CDATA[' // remove multiple white space in CDATA / XML
289
-                || substr($htmlArray[$x], 0, 5) == '<?xml'
290
-            ) {
291
-                $html .= $this->killWhiteSpace($htmlArray[$x]);
292
-            } else { // remove all line breaks
293
-                $html .= $this->killLineBreaks($htmlArray[$x]);
294
-            }
295
-
296
-            // count up a tab
297
-            if (substr($htmlArray[$x], 0, 1) == '<' && substr($htmlArray[$x], 1, 1) != '/') {
298
-                if (substr($htmlArray[$x], 1, 1) != ' ' && substr($htmlArray[$x], 1, 3) != 'img' && substr(
299
-                        $htmlArray[$x],
300
-                        1,
301
-                        2
302
-                    ) != 'br' && substr($htmlArray[$x], 1, 2) != 'hr' && substr(
303
-                        $htmlArray[$x],
304
-                        1,
305
-                        5
306
-                    ) != 'input' && substr($htmlArray[$x], 1, 4) != 'link' && substr(
307
-                        $htmlArray[$x],
308
-                        1,
309
-                        4
310
-                    ) != 'meta' && substr($htmlArray[$x], 1, 4) != 'col ' && substr(
311
-                        $htmlArray[$x],
312
-                        1,
313
-                        5
314
-                    ) != 'frame' && substr($htmlArray[$x], 1, 7) != 'isindex' && substr(
315
-                        $htmlArray[$x],
316
-                        1,
317
-                        5
318
-                    ) != 'param' && substr($htmlArray[$x], 1, 4) != 'area' && substr(
319
-                        $htmlArray[$x],
320
-                        1,
321
-                        4
322
-                    ) != 'base' && substr($htmlArray[$x], 0, 2) != '<!' && substr($htmlArray[$x], 0, 5) != '<?xml'
323
-                ) {
324
-                    $tabs++;
325
-                }
326
-            }
327
-        }
328
-
329
-        // Remove empty lines
330
-        if ($this->formatType > 1) {
331
-            $this->removeEmptyLines($html);
332
-        }
333
-
334
-        // Restore saved comments, styles and java-scripts
335
-        for ($i = 0; $i < count($noFormat); $i++) {
336
-            $noFormat[$i] = $this->rTrimLines($noFormat[$i]); // remove white space after line ending
337
-            $html = str_replace("<!-- ELEMENT $i -->", $noFormat[$i], $html);
338
-        }
339
-
340
-        // include debug comment at the end
341
-        if ($tabs != 0 && $this->debugComment === true) {
342
-            $html .= '<!--' . $tabs . " open elements found-->\r\n";
343
-        }
344
-
345
-        return $html;
346
-    }
347
-
348
-    /**
349
-     * Remove ALL line breaks and multiple white space
350
-     *
351
-     * @param string $html
352
-     *
353
-     * @return string
354
-     */
355
-    protected function killLineBreaks($html)
356
-    {
357
-        $html = $this->convNlOs($html);
358
-        $html = str_replace($this->newline, "", $html);
359
-        $html = preg_replace('/\s\s+/u', ' ', $html);
360
-        return $html;
361
-    }
362
-
363
-    /**
364
-     * Remove multiple white space, keeps line breaks
365
-     *
366
-     * @param string $html
367
-     *
368
-     * @return string
369
-     */
370
-    protected function killWhiteSpace($html)
371
-    {
372
-        $html = $this->convNlOs($html);
373
-        $temp = explode($this->newline, $html);
374
-        for ($i = 0; $i < count($temp); $i++) {
375
-            if (!trim($temp[$i])) {
376
-                unset($temp[$i]);
377
-            } else {
378
-                $temp[$i] = trim($temp[$i]);
379
-                $temp[$i] = preg_replace('/\s\s+/', ' ', $temp[$i]);
380
-            }
381
-        }
382
-        $html = implode($this->newline, $temp);
383
-        return $html;
384
-    }
385
-
386
-    /**
387
-     * Remove white space at the end of lines, keeps other white space and line breaks
388
-     *
389
-     * @param string $html
390
-     *
391
-     * @return string
392
-     */
393
-    protected function rTrimLines($html)
394
-    {
395
-        $html = $this->convNlOs($html);
396
-        $temp = explode($this->newline, $html);
397
-        for ($i = 0; $i < count($temp); $i++) {
398
-            $temp[$i] = rtrim($temp[$i]);
399
-        }
400
-        $html = implode($this->newline, $temp);
401
-        return $html;
402
-    }
403
-
404
-    /**
405
-     * Convert newlines according to the current OS
406
-     *
407
-     * @param string $html
408
-     *
409
-     * @return string
410
-     */
411
-    protected function convNlOs($html)
412
-    {
413
-        $html = preg_replace("(\r\n|\n|\r)", $this->newline, $html);
414
-        return $html;
415
-    }
416
-
417
-    /**
418
-     * Remove tabs and empty spaces before and after lines, transforms linebreaks system conform
419
-     *
420
-     * @param string $html Html-Code
421
-     *
422
-     * @return void
423
-     */
424
-    protected function trimLines(&$html)
425
-    {
426
-        $html = str_replace("\t", "", $html);
427
-        // convert newlines according to the current OS
428
-        if (Environment::isWindows()) {
429
-            $html = str_replace("\n", "\r\n", $html);
430
-        } else {
431
-            $html = str_replace("\r\n", "\n", $html);
432
-        }
433
-        $temp = explode($this->newline, $html);
434
-        $temp = array_map('trim', $temp);
435
-        $html = implode($this->newline, $temp);
436
-        unset($temp);
437
-    }
438
-
439
-    /**
440
-     * Remove empty lines
441
-     *
442
-     * @param string $html
443
-     *
444
-     * @return void
445
-     */
446
-    protected function removeEmptyLines(&$html)
447
-    {
448
-        $temp = explode($this->newline, $html);
449
-        $result = [];
450
-        for ($i = 0; $i < count($temp); ++$i) {
451
-            if ("" == trim($temp[$i])) {
452
-                continue;
453
-            }
454
-            $result[] = $temp[$i];
455
-        }
456
-        $html = implode($this->newline, $result);
457
-    }
458
-
459
-    /**
460
-     * Remove new lines where unnecessary
461
-     * spares line breaks within: pre, textarea, ...
462
-     *
463
-     * @param string $html
464
-     *
465
-     * @return void
466
-     */
467
-    protected function removeNewLines(&$html)
468
-    {
469
-        $splitArray = [
470
-            'textarea',
471
-            'pre'
472
-        ]; // eventuell auch: span, script, style
473
-        $peaces = preg_split('#(<(' . implode('|', $splitArray) . ').*>.*</\2>)#Uis', $html, -1, PREG_SPLIT_DELIM_CAPTURE);
474
-        $html = "";
475
-        for ($i = 0; $i < count($peaces); $i++) {
476
-            if (($i + 1) % 3 == 0) {
477
-                continue;
478
-            }
479
-            $html .= (($i - 1) % 3 != 0) ? $this->killLineBreaks($peaces[$i]) : $peaces[$i];
480
-        }
481
-    }
482
-
483
-    /**
484
-     * Remove obsolete link schema
485
-     *
486
-     * @param string $html
487
-     *
488
-     * @return void
489
-     */
490
-    protected function removeLinkSchema(&$html)
491
-    {
492
-        $html = preg_replace("/<link rel=\"?schema.dc\"?.+?>/is", "", $html);
493
-    }
494
-
495
-    /**
496
-     * Remove empty alt tags
497
-     *
498
-     * @param string $html
499
-     *
500
-     * @return void
501
-     */
502
-    protected function removeEmptyAltAtr(&$html)
503
-    {
504
-        $html = str_replace("alt=\"\"", "", $html);
505
-    }
506
-
507
-    /**
508
-     * Remove broken links in <a> tags
509
-     *
510
-     * @param string $html
511
-     *
512
-     * @return void
513
-     */
514
-    protected function removeRealUrlBrokenRootLink(&$html)
515
-    {
516
-        $html = str_replace('href=".html"', 'href=""', $html);
517
-    }
518
-
519
-    /**
520
-     * Include configured header comment in HTML content block
521
-     *
522
-     * @param $html
523
-     */
524
-    public function includeHeaderComment(&$html)
525
-    {
526
-        if (!empty($this->headerComment)) {
527
-            $html = preg_replace_callback('/<meta http-equiv(.*)>/Usi', function ($matches) {
528
-                return trim($matches[0] . $this->newline . $this->tab . $this->tab . '<!-- ' . $this->headerComment . '-->');
529
-            }, $html, 1);
530
-        }
531
-    }
20
+	/**
21
+	 * Enable Debug comment in footer
22
+	 *
23
+	 * @var boolean
24
+	 */
25
+	protected $debugComment = false;
26
+
27
+	/**
28
+	 * Format Type
29
+	 *
30
+	 * @var integer
31
+	 */
32
+	protected $formatType = 0;
33
+
34
+	/**
35
+	 * Tab character
36
+	 *
37
+	 * @var string
38
+	 */
39
+	protected $tab = "\t";
40
+
41
+	/**
42
+	 * Newline character
43
+	 *
44
+	 * @var string
45
+	 */
46
+	protected $newline = "\n";
47
+
48
+	/**
49
+	 * Configured extra header comment
50
+	 *
51
+	 * @var string
52
+	 */
53
+	protected $headerComment = '';
54
+
55
+	/**
56
+	 * Empty space char
57
+	 * @var string
58
+	 */
59
+	protected $emptySpaceChar = ' ';
60
+
61
+	/**
62
+	 * Set variables based on given config
63
+	 *
64
+	 * @param array $config
65
+	 *
66
+	 * @return void
67
+	 */
68
+	public function setVariables(array $config)
69
+	{
70
+		// Set newline based on OS
71
+		if (Environment::isWindows()) {
72
+			$this->newline = "\r\n";
73
+		} else {
74
+			$this->newline = "\n";
75
+		}
76
+
77
+		if (!empty($config)) {
78
+			if ($config['formatHtml'] && is_numeric($config['formatHtml'])) {
79
+				$this->formatType = (int)$config['formatHtml'];
80
+			}
81
+
82
+			if ($config['formatHtml.']['tabSize'] && is_numeric($config['formatHtml.']['tabSize'])) {
83
+				$this->tab = str_pad('', $config['formatHtml.']['tabSize'], ' ');
84
+			}
85
+
86
+			if (isset($config['formatHtml.']['debugComment'])) {
87
+				$this->debugComment = (bool)$config['formatHtml.']['debugComment'];
88
+			}
89
+
90
+			if (isset($config['headerComment'])) {
91
+				$this->headerComment = $config['headerComment'];
92
+			}
93
+
94
+			if (isset($config['dropEmptySpaceChar']) && (bool)$config['dropEmptySpaceChar']) {
95
+				$this->emptySpaceChar = '';
96
+			}
97
+		}
98
+	}
99
+
100
+	/**
101
+	 * Clean given HTML with formatter
102
+	 *
103
+	 * @param string $html
104
+	 * @param array $config
105
+	 *
106
+	 * @return string
107
+	 */
108
+	public function clean($html, $config = [])
109
+	{
110
+		if (!empty($config)) {
111
+			if ((bool)$config['enabled'] === false) {
112
+				return $html;
113
+			}
114
+
115
+			$this->setVariables($config);
116
+		}
117
+
118
+		$manipulations = [];
119
+
120
+		if (isset($config['removeGenerator']) && (bool)$config['removeGenerator']) {
121
+			$manipulations['removeGenerator'] = GeneralUtility::makeInstance(RemoveGenerator::class);
122
+		}
123
+
124
+		if (isset($config['removeComments']) && (bool)$config['removeComments']) {
125
+			$manipulations['removeComments'] = GeneralUtility::makeInstance(RemoveComments::class);
126
+		}
127
+
128
+		if (isset($config['removeBlurScript']) && (bool)$config['removeBlurScript']) {
129
+			$manipulations['removeBlurScript'] = GeneralUtility::makeInstance(RemoveBlurScript::class);
130
+		}
131
+
132
+		if (!empty($this->headerComment)) {
133
+			$this->includeHeaderComment($html);
134
+		}
135
+
136
+		foreach ($manipulations as $key => $manipulation) {
137
+			/** @var ManipulationInterface $manipulation */
138
+			$configuration = isset($config[$key . '.']) && is_array($config[$key . '.']) ? $config[$key . '.'] : [];
139
+			$html = $manipulation->manipulate($html, $configuration);
140
+		}
141
+
142
+		if ($this->formatType > 0) {
143
+			$html = $this->formatHtml($html);
144
+		}
145
+
146
+		return $html;
147
+	}
148
+
149
+	/**
150
+	 * Formats the (X)HTML code:
151
+	 *  - taps according to the hirarchy of the tags
152
+	 *  - removes empty spaces between tags
153
+	 *  - removes linebreaks within tags (spares where necessary: pre, textarea, comments, ..)
154
+	 *  choose from five options:
155
+	 *    0 => off
156
+	 *    1 => no line break at all  (code in one line)
157
+	 *    2 => minimalistic line breaks (structure defining box-elements)
158
+	 *    3 => aesthetic line breaks (important box-elements)
159
+	 *    4 => logic line breaks (all box-elements)
160
+	 *    5 => max line breaks (all elements)
161
+	 *
162
+	 * @param string $html
163
+	 *
164
+	 * @return string
165
+	 */
166
+	protected function formatHtml($html)
167
+	{
168
+		// Save original formated comments, pre, textarea, styles and java-scripts & replace them with markers
169
+		preg_match_all(
170
+			'/(?s)((<!--.*?-->)|(<[ \n\r]*pre[^>]*>.*?<[ \n\r]*\/pre[^>]*>)|(<[ \n\r]*textarea[^>]*>.*?<[ \n\r]*\/textarea[^>]*>)|(<[ \n\r]*style[^>]*>.*?<[ \n\r]*\/style[^>]*>)|(<[ \n\r]*script[^>]*>.*?<[ \n\r]*\/script[^>]*>))/im',
171
+			$html,
172
+			$matches
173
+		);
174
+		$noFormat = $matches[0]; // do not format these block elements
175
+		for ($i = 0; $i < count($noFormat); $i++) {
176
+			$html = str_replace($noFormat[$i], "\n<!-- ELEMENT $i -->", $html);
177
+		}
178
+
179
+		// define box elements for formatting
180
+		$trueBoxElements = 'address|blockquote|center|dir|div|dl|fieldset|form|h1|h2|h3|h4|h5|h6|hr|isindex|menu|noframes|noscript|ol|p|pre|table|ul|article|aside|details|figcaption|figure|footer|header|hgroup|menu|nav|section';
181
+		$functionalBoxElements = 'dd|dt|frameset|li|tbody|td|tfoot|th|thead|tr|colgroup';
182
+		$usableBoxElements = 'applet|button|del|iframe|ins|map|object|script';
183
+		$imagineBoxElements = 'html|body|head|meta|title|link|script|base|!--';
184
+		$allBoxLikeElements = '(?>' . $trueBoxElements . '|' . $functionalBoxElements . '|' . $usableBoxElements . '|' . $imagineBoxElements . ')';
185
+		$esteticBoxLikeElements = '(?>html|head|body|meta name|title|div|table|h1|h2|h3|h4|h5|h6|p|form|pre|center|!--)';
186
+		$structureBoxLikeElements = '(?>html|head|body|div|!--)';
187
+
188
+		// split html into it's elements
189
+		$htmlArrayTemp = preg_split(
190
+			'/(<(?:[^<>]+(?:"[^"]*"|\'[^\']*\')?)+>)/',
191
+			$html,
192
+			-1,
193
+			PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY
194
+		);
195
+		// remove empty lines
196
+		$htmlArray = [''];
197
+		$z = 1;
198
+		for ($x = 0; $x < count($htmlArrayTemp); $x++) {
199
+			$t = trim($htmlArrayTemp[$x]);
200
+			if ($t !== '') {
201
+				$htmlArray[$z] = $htmlArrayTemp[$x];
202
+				$z++;
203
+			} else {
204
+				$htmlArray[$z] = $this->emptySpaceChar;
205
+				$z++;
206
+			}
207
+		}
208
+
209
+		// rebuild html
210
+		$html = '';
211
+		$tabs = 0;
212
+		for ($x = 0; $x < count($htmlArray); $x++) {
213
+			// check if the element should stand in a new line
214
+			$newline = false;
215
+			if (substr($htmlArray[$x - 1], 0, 5) == '<?xml') {
216
+				$newline = true;
217
+			} elseif ($this->formatType == 2 && ( // minimalistic line break
218
+					# this element has a line break before itself
219
+					preg_match(
220
+						'/<' . $structureBoxLikeElements . '(.*)>/Usi',
221
+						$htmlArray[$x]
222
+					) || preg_match(
223
+						'/<' . $structureBoxLikeElements . '(.*) \/>/Usi',
224
+						$htmlArray[$x]
225
+					) || # one element before is a element that has a line break after
226
+					preg_match(
227
+						'/<\/' . $structureBoxLikeElements . '(.*)>/Usi',
228
+						$htmlArray[$x - 1]
229
+					) || substr(
230
+						$htmlArray[$x - 1],
231
+						0,
232
+						4
233
+					) == '<!--' || preg_match('/<' . $structureBoxLikeElements . '(.*) \/>/Usi', $htmlArray[$x - 1]))
234
+			) {
235
+				$newline = true;
236
+			} elseif ($this->formatType == 3 && ( // aestetic line break
237
+					# this element has a line break before itself
238
+					preg_match(
239
+						'/<' . $esteticBoxLikeElements . '(.*)>/Usi',
240
+						$htmlArray[$x]
241
+					) || preg_match(
242
+						'/<' . $esteticBoxLikeElements . '(.*) \/>/Usi',
243
+						$htmlArray[$x]
244
+					) || # one element before is a element that has a line break after
245
+					preg_match('/<\/' . $esteticBoxLikeElements . '(.*)>/Usi', $htmlArray[$x - 1]) || substr(
246
+						$htmlArray[$x - 1],
247
+						0,
248
+						4
249
+					) == '<!--' || preg_match('/<' . $esteticBoxLikeElements . '(.*) \/>/Usi', $htmlArray[$x - 1]))
250
+			) {
251
+				$newline = true;
252
+			} elseif ($this->formatType >= 4 && ( // logical line break
253
+					# this element has a line break before itself
254
+					preg_match(
255
+						'/<' . $allBoxLikeElements . '(.*)>/Usi',
256
+						$htmlArray[$x]
257
+					) || preg_match(
258
+						'/<' . $allBoxLikeElements . '(.*) \/>/Usi',
259
+						$htmlArray[$x]
260
+					) || # one element before is a element that has a line break after
261
+					preg_match('/<\/' . $allBoxLikeElements . '(.*)>/Usi', $htmlArray[$x - 1]) || substr(
262
+						$htmlArray[$x - 1],
263
+						0,
264
+						4
265
+					) == '<!--' || preg_match('/<' . $allBoxLikeElements . '(.*) \/>/Usi', $htmlArray[$x - 1]))
266
+			) {
267
+				$newline = true;
268
+			}
269
+
270
+			// count down a tab
271
+			if (substr($htmlArray[$x], 0, 2) == '</') {
272
+				$tabs--;
273
+			}
274
+
275
+			// add tabs and line breaks in front of the current tag
276
+			if ($newline) {
277
+				$html .= $this->newline;
278
+				for ($y = 0; $y < $tabs; $y++) {
279
+					$html .= $this->tab;
280
+				}
281
+			}
282
+
283
+			// remove white spaces and line breaks and add current tag to the html-string
284
+			if (substr($htmlArray[$x - 1], 0, 4) == '<pre' // remove white space after line ending in PRE / TEXTAREA / comment
285
+				|| substr($htmlArray[$x - 1], 0, 9) == '<textarea' || substr($htmlArray[$x - 1], 0, 4) == '<!--'
286
+			) {
287
+				$html .= $this->rTrimLines($htmlArray[$x]);
288
+			} elseif (substr($htmlArray[$x], 0, 9) == '<![CDATA[' // remove multiple white space in CDATA / XML
289
+				|| substr($htmlArray[$x], 0, 5) == '<?xml'
290
+			) {
291
+				$html .= $this->killWhiteSpace($htmlArray[$x]);
292
+			} else { // remove all line breaks
293
+				$html .= $this->killLineBreaks($htmlArray[$x]);
294
+			}
295
+
296
+			// count up a tab
297
+			if (substr($htmlArray[$x], 0, 1) == '<' && substr($htmlArray[$x], 1, 1) != '/') {
298
+				if (substr($htmlArray[$x], 1, 1) != ' ' && substr($htmlArray[$x], 1, 3) != 'img' && substr(
299
+						$htmlArray[$x],
300
+						1,
301
+						2
302
+					) != 'br' && substr($htmlArray[$x], 1, 2) != 'hr' && substr(
303
+						$htmlArray[$x],
304
+						1,
305
+						5
306
+					) != 'input' && substr($htmlArray[$x], 1, 4) != 'link' && substr(
307
+						$htmlArray[$x],
308
+						1,
309
+						4
310
+					) != 'meta' && substr($htmlArray[$x], 1, 4) != 'col ' && substr(
311
+						$htmlArray[$x],
312
+						1,
313
+						5
314
+					) != 'frame' && substr($htmlArray[$x], 1, 7) != 'isindex' && substr(
315
+						$htmlArray[$x],
316
+						1,
317
+						5
318
+					) != 'param' && substr($htmlArray[$x], 1, 4) != 'area' && substr(
319
+						$htmlArray[$x],
320
+						1,
321
+						4
322
+					) != 'base' && substr($htmlArray[$x], 0, 2) != '<!' && substr($htmlArray[$x], 0, 5) != '<?xml'
323
+				) {
324
+					$tabs++;
325
+				}
326
+			}
327
+		}
328
+
329
+		// Remove empty lines
330
+		if ($this->formatType > 1) {
331
+			$this->removeEmptyLines($html);
332
+		}
333
+
334
+		// Restore saved comments, styles and java-scripts
335
+		for ($i = 0; $i < count($noFormat); $i++) {
336
+			$noFormat[$i] = $this->rTrimLines($noFormat[$i]); // remove white space after line ending
337
+			$html = str_replace("<!-- ELEMENT $i -->", $noFormat[$i], $html);
338
+		}
339
+
340
+		// include debug comment at the end
341
+		if ($tabs != 0 && $this->debugComment === true) {
342
+			$html .= '<!--' . $tabs . " open elements found-->\r\n";
343
+		}
344
+
345
+		return $html;
346
+	}
347
+
348
+	/**
349
+	 * Remove ALL line breaks and multiple white space
350
+	 *
351
+	 * @param string $html
352
+	 *
353
+	 * @return string
354
+	 */
355
+	protected function killLineBreaks($html)
356
+	{
357
+		$html = $this->convNlOs($html);
358
+		$html = str_replace($this->newline, "", $html);
359
+		$html = preg_replace('/\s\s+/u', ' ', $html);
360
+		return $html;
361
+	}
362
+
363
+	/**
364
+	 * Remove multiple white space, keeps line breaks
365
+	 *
366
+	 * @param string $html
367
+	 *
368
+	 * @return string
369
+	 */
370
+	protected function killWhiteSpace($html)
371
+	{
372
+		$html = $this->convNlOs($html);
373
+		$temp = explode($this->newline, $html);
374
+		for ($i = 0; $i < count($temp); $i++) {
375
+			if (!trim($temp[$i])) {
376
+				unset($temp[$i]);
377
+			} else {
378
+				$temp[$i] = trim($temp[$i]);
379
+				$temp[$i] = preg_replace('/\s\s+/', ' ', $temp[$i]);
380
+			}
381
+		}
382
+		$html = implode($this->newline, $temp);
383
+		return $html;
384
+	}
385
+
386
+	/**
387
+	 * Remove white space at the end of lines, keeps other white space and line breaks
388
+	 *
389
+	 * @param string $html
390
+	 *
391
+	 * @return string
392
+	 */
393
+	protected function rTrimLines($html)
394
+	{
395
+		$html = $this->convNlOs($html);
396
+		$temp = explode($this->newline, $html);
397
+		for ($i = 0; $i < count($temp); $i++) {
398
+			$temp[$i] = rtrim($temp[$i]);
399
+		}
400
+		$html = implode($this->newline, $temp);
401
+		return $html;
402
+	}
403
+
404
+	/**
405
+	 * Convert newlines according to the current OS
406
+	 *
407
+	 * @param string $html
408
+	 *
409
+	 * @return string
410
+	 */
411
+	protected function convNlOs($html)
412
+	{
413
+		$html = preg_replace("(\r\n|\n|\r)", $this->newline, $html);
414
+		return $html;
415
+	}
416
+
417
+	/**
418
+	 * Remove tabs and empty spaces before and after lines, transforms linebreaks system conform
419
+	 *
420
+	 * @param string $html Html-Code
421
+	 *
422
+	 * @return void
423
+	 */
424
+	protected function trimLines(&$html)
425
+	{
426
+		$html = str_replace("\t", "", $html);
427
+		// convert newlines according to the current OS
428
+		if (Environment::isWindows()) {
429
+			$html = str_replace("\n", "\r\n", $html);
430
+		} else {
431
+			$html = str_replace("\r\n", "\n", $html);
432
+		}
433
+		$temp = explode($this->newline, $html);
434
+		$temp = array_map('trim', $temp);
435
+		$html = implode($this->newline, $temp);
436
+		unset($temp);
437
+	}
438
+
439
+	/**
440
+	 * Remove empty lines
441
+	 *
442
+	 * @param string $html
443
+	 *
444
+	 * @return void
445
+	 */
446
+	protected function removeEmptyLines(&$html)
447
+	{
448
+		$temp = explode($this->newline, $html);
449
+		$result = [];
450
+		for ($i = 0; $i < count($temp); ++$i) {
451
+			if ("" == trim($temp[$i])) {
452
+				continue;
453
+			}
454
+			$result[] = $temp[$i];
455
+		}
456
+		$html = implode($this->newline, $result);
457
+	}
458
+
459
+	/**
460
+	 * Remove new lines where unnecessary
461
+	 * spares line breaks within: pre, textarea, ...
462
+	 *
463
+	 * @param string $html
464
+	 *
465
+	 * @return void
466
+	 */
467
+	protected function removeNewLines(&$html)
468
+	{
469
+		$splitArray = [
470
+			'textarea',
471
+			'pre'
472
+		]; // eventuell auch: span, script, style
473
+		$peaces = preg_split('#(<(' . implode('|', $splitArray) . ').*>.*</\2>)#Uis', $html, -1, PREG_SPLIT_DELIM_CAPTURE);
474
+		$html = "";
475
+		for ($i = 0; $i < count($peaces); $i++) {
476
+			if (($i + 1) % 3 == 0) {
477
+				continue;
478
+			}
479
+			$html .= (($i - 1) % 3 != 0) ? $this->killLineBreaks($peaces[$i]) : $peaces[$i];
480
+		}
481
+	}
482
+
483
+	/**
484
+	 * Remove obsolete link schema
485
+	 *
486
+	 * @param string $html
487
+	 *
488
+	 * @return void
489
+	 */
490
+	protected function removeLinkSchema(&$html)
491
+	{
492
+		$html = preg_replace("/<link rel=\"?schema.dc\"?.+?>/is", "", $html);
493
+	}
494
+
495
+	/**
496
+	 * Remove empty alt tags
497
+	 *
498
+	 * @param string $html
499
+	 *
500
+	 * @return void
501
+	 */
502
+	protected function removeEmptyAltAtr(&$html)
503
+	{
504
+		$html = str_replace("alt=\"\"", "", $html);
505
+	}
506
+
507
+	/**
508
+	 * Remove broken links in <a> tags
509
+	 *
510
+	 * @param string $html
511
+	 *
512
+	 * @return void
513
+	 */
514
+	protected function removeRealUrlBrokenRootLink(&$html)
515
+	{
516
+		$html = str_replace('href=".html"', 'href=""', $html);
517
+	}
518
+
519
+	/**
520
+	 * Include configured header comment in HTML content block
521
+	 *
522
+	 * @param $html
523
+	 */
524
+	public function includeHeaderComment(&$html)
525
+	{
526
+		if (!empty($this->headerComment)) {
527
+			$html = preg_replace_callback('/<meta http-equiv(.*)>/Usi', function ($matches) {
528
+				return trim($matches[0] . $this->newline . $this->tab . $this->tab . '<!-- ' . $this->headerComment . '-->');
529
+			}, $html, 1);
530
+		}
531
+	}
532 532
 }
Please login to merge, or discard this patch.
Classes/Middleware/CleanHtmlMiddleware.php 1 patch
Indentation   +39 added lines, -39 removed lines patch added patch discarded remove patch
@@ -17,43 +17,43 @@
 block discarded – undo
17 17
  */
18 18
 class CleanHtmlMiddleware implements MiddlewareInterface
19 19
 {
20
-    /**
21
-     * @var CleanHtmlService
22
-     */
23
-    protected $cleanHtmlService = null;
24
-
25
-    public function __construct()
26
-    {
27
-        $this->cleanHtmlService = GeneralUtility::makeInstance(CleanHtmlService::class);
28
-    }
29
-
30
-    /**
31
-     * Clean the HTML output
32
-     *
33
-     * @param ServerRequestInterface $request
34
-     * @param RequestHandlerInterface $handler
35
-     * @return ResponseInterface
36
-     */
37
-    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
38
-    {
39
-        $response = $handler->handle($request);
40
-
41
-        if (
42
-            !($response instanceof NullResponse)
43
-            && $GLOBALS['TSFE'] instanceof TypoScriptFrontendController
44
-            && $GLOBALS['TSFE']->isOutputting()) {
45
-
46
-            $processedHtml = $this->cleanHtmlService->clean(
47
-                $response->getBody()->__toString(),
48
-                $GLOBALS['TSFE']->config['config']['sourceopt.']
49
-            );
50
-
51
-            // Replace old body with $processedHtml
52
-            $responseBody = new Stream('php://temp', 'rw');
53
-            $responseBody->write($processedHtml);
54
-            $response = $response->withBody($responseBody);
55
-        }
56
-
57
-        return $response;
58
-    }
20
+	/**
21
+	 * @var CleanHtmlService
22
+	 */
23
+	protected $cleanHtmlService = null;
24
+
25
+	public function __construct()
26
+	{
27
+		$this->cleanHtmlService = GeneralUtility::makeInstance(CleanHtmlService::class);
28
+	}
29
+
30
+	/**
31
+	 * Clean the HTML output
32
+	 *
33
+	 * @param ServerRequestInterface $request
34
+	 * @param RequestHandlerInterface $handler
35
+	 * @return ResponseInterface
36
+	 */
37
+	public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
38
+	{
39
+		$response = $handler->handle($request);
40
+
41
+		if (
42
+			!($response instanceof NullResponse)
43
+			&& $GLOBALS['TSFE'] instanceof TypoScriptFrontendController
44
+			&& $GLOBALS['TSFE']->isOutputting()) {
45
+
46
+			$processedHtml = $this->cleanHtmlService->clean(
47
+				$response->getBody()->__toString(),
48
+				$GLOBALS['TSFE']->config['config']['sourceopt.']
49
+			);
50
+
51
+			// Replace old body with $processedHtml
52
+			$responseBody = new Stream('php://temp', 'rw');
53
+			$responseBody->write($processedHtml);
54
+			$response = $response->withBody($responseBody);
55
+		}
56
+
57
+		return $response;
58
+	}
59 59
 }
Please login to merge, or discard this patch.