| @@ -191,7 +191,7 @@ | ||
| 191 | 191 | '/(<(?:[^<>]+(?:"[^"]*"|\'[^\']*\')?)+>)/', | 
| 192 | 192 | $html, | 
| 193 | 193 | -1, | 
| 194 | - \PREG_SPLIT_DELIM_CAPTURE | \PREG_SPLIT_NO_EMPTY | |
| 194 | + \PREG_SPLIT_DELIM_CAPTURE|\PREG_SPLIT_NO_EMPTY | |
| 195 | 195 | ); | 
| 196 | 196 | |
| 197 | 197 |          if (false === $htmlArrayTemp) { | 
| @@ -17,392 +17,392 @@ | ||
| 17 | 17 | */ | 
| 18 | 18 | class CleanHtmlService implements SingletonInterface | 
| 19 | 19 |  { | 
| 20 | - /** | |
| 21 | - * Enable Debug comment in footer. | |
| 22 | - * | |
| 23 | - * @var bool | |
| 24 | - */ | |
| 25 | - protected $debugComment = false; | |
| 26 | - | |
| 27 | - /** | |
| 28 | - * Format Type. | |
| 29 | - * | |
| 30 | - * @var int | |
| 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 | - * | |
| 58 | - * @var string | |
| 59 | - */ | |
| 60 | - protected $emptySpaceChar = ' '; | |
| 61 | - | |
| 62 | - /** | |
| 63 | - * Set variables based on given config. | |
| 64 | - */ | |
| 65 | - public function setVariables(array $config): void | |
| 66 | -    { | |
| 67 | -        if (isset($config['headerComment']) && !empty($config['headerComment'])) { | |
| 68 | - $this->headerComment = $config['headerComment']; | |
| 69 | - } | |
| 70 | - | |
| 71 | -        if (isset($config['formatHtml']) && is_numeric($config['formatHtml'])) { | |
| 72 | - $this->formatType = (int) $config['formatHtml']; | |
| 73 | - } | |
| 74 | - | |
| 75 | -        if (isset($config['formatHtml.']['tabSize']) && is_numeric($config['formatHtml.']['tabSize'])) { | |
| 76 | -            $this->tab = str_pad('', (int) $config['formatHtml.']['tabSize'], ' '); | |
| 77 | - } | |
| 78 | - | |
| 79 | -        if (isset($config['formatHtml.']['debugComment'])) { | |
| 80 | - $this->debugComment = (bool) $config['formatHtml.']['debugComment']; | |
| 81 | - } | |
| 82 | - | |
| 83 | -        if (isset($config['dropEmptySpaceChar']) && (bool) $config['dropEmptySpaceChar']) { | |
| 84 | - $this->emptySpaceChar = ''; | |
| 85 | - } | |
| 86 | - } | |
| 87 | - | |
| 88 | - /** | |
| 89 | - * Clean given HTML with formatter. | |
| 90 | - * | |
| 91 | - * @return string | |
| 92 | - */ | |
| 93 | - public function clean(string $html, array $config = []) | |
| 94 | -    { | |
| 95 | -        if (!empty($config)) { | |
| 96 | - $this->setVariables($config); | |
| 97 | - } | |
| 98 | - | |
| 99 | - // convert line-breaks to UNIX | |
| 100 | - $this->convNlOs($html); | |
| 101 | - | |
| 102 | - $manipulations = []; | |
| 103 | - | |
| 104 | -        if (isset($config['removeGenerator']) && (bool) $config['removeGenerator']) { | |
| 105 | - $manipulations['removeGenerator'] = GeneralUtility::makeInstance(RemoveGenerator::class); | |
| 106 | - } | |
| 107 | - | |
| 108 | -        if (isset($config['removeComments']) && (bool) $config['removeComments']) { | |
| 109 | - $manipulations['removeComments'] = GeneralUtility::makeInstance(RemoveComments::class); | |
| 110 | - } | |
| 111 | - | |
| 112 | -        if (!empty($this->headerComment)) { | |
| 113 | - $this->includeHeaderComment($html); | |
| 114 | - } | |
| 115 | - | |
| 116 | -        foreach ($manipulations as $key => $manipulation) { | |
| 117 | - /** @var ManipulationInterface $manipulation */ | |
| 118 | - $configuration = isset($config[$key.'.']) && \is_array($config[$key.'.']) ? $config[$key.'.'] : []; | |
| 119 | - $html = $manipulation->manipulate($html, $configuration); | |
| 120 | - } | |
| 121 | - | |
| 122 | - // cleanup HTML5 self-closing elements | |
| 123 | - if (!isset($GLOBALS['TSFE']->config['config']['doctype']) | |
| 124 | -            || 'x' !== substr($GLOBALS['TSFE']->config['config']['doctype'], 0, 1)) { | |
| 125 | - $html = preg_replace( | |
| 126 | - '/<((?:area|base|br|col|embed|hr|img|input|link|meta|param|source|track|wbr)\s[^>\\\\]+?)\s?\/>/', | |
| 127 | - '<$1>', | |
| 128 | - $html | |
| 129 | - ); | |
| 130 | - } | |
| 131 | - | |
| 132 | -        if ($this->formatType > 0) { | |
| 133 | - $html = $this->formatHtml($html); | |
| 134 | - } | |
| 135 | - | |
| 136 | - // remove white space after line ending | |
| 137 | - $this->rTrimLines($html); | |
| 138 | - | |
| 139 | - // recover line-breaks | |
| 140 | -        if (Environment::isWindows()) { | |
| 141 | - $html = str_replace($this->newline, "\r\n", $html); | |
| 142 | - } | |
| 143 | - | |
| 144 | - return (string) $html; | |
| 145 | - } | |
| 146 | - | |
| 147 | - /** | |
| 148 | - * Formats the (X)HTML code: | |
| 149 | - * - taps according to the hirarchy of the tags | |
| 150 | - * - removes empty spaces between tags | |
| 151 | - * - removes linebreaks within tags (spares where necessary: pre, textarea, comments, ..) | |
| 152 | - * choose from five options: | |
| 153 | - * 0 => off | |
| 154 | - * 1 => no line break at all (code in one line) | |
| 155 | - * 2 => minimalistic line breaks (structure defining box-elements) | |
| 156 | - * 3 => aesthetic line breaks (important box-elements) | |
| 157 | - * 4 => logic line breaks (all box-elements) | |
| 158 | - * 5 => max line breaks (all elements). | |
| 159 | - */ | |
| 160 | - protected function formatHtml(string $html): string | |
| 161 | -    { | |
| 162 | - // Save original formated pre, textarea, comments, styles and scripts & replace them with markers | |
| 163 | - preg_match_all( | |
| 164 | - '/(?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', | |
| 165 | - $html, | |
| 166 | - $matches | |
| 167 | - ); | |
| 168 | - $noFormat = $matches[0]; // do not format these block elements | |
| 169 | -        for ($i = 0; $i < \count($noFormat); ++$i) { | |
| 170 | -            $html = str_replace($noFormat[$i], "\n<!-- ELEMENT {$i} -->", $html); | |
| 171 | - } | |
| 172 | - | |
| 173 | - // define box elements for formatting | |
| 174 | - $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'; | |
| 175 | - $functionalBoxElements = 'dd|dt|frameset|li|tbody|td|tfoot|th|thead|tr|colgroup'; | |
| 176 | - $usableBoxElements = 'applet|button|del|iframe|ins|map|object|script'; | |
| 177 | - $imagineBoxElements = 'html|body|head|meta|title|link|script|base|!--'; | |
| 178 | - $allBoxLikeElements = '(?>'.$trueBoxElements.'|'.$functionalBoxElements.'|'.$usableBoxElements.'|'.$imagineBoxElements.')'; | |
| 179 | - $esteticBoxLikeElements = '(?>html|head|body|meta name|title|div|table|h1|h2|h3|h4|h5|h6|p|form|pre|center|!--)'; | |
| 180 | - $structureBoxLikeElements = '(?>html|head|body|div|!--)'; | |
| 181 | - | |
| 182 | - // split html into it's elements | |
| 183 | - $htmlArrayTemp = preg_split( | |
| 184 | - '/(<(?:[^<>]+(?:"[^"]*"|\'[^\']*\')?)+>)/', | |
| 185 | - $html, | |
| 186 | - -1, | |
| 187 | - \PREG_SPLIT_DELIM_CAPTURE | \PREG_SPLIT_NO_EMPTY | |
| 188 | - ); | |
| 189 | - | |
| 190 | -        if (false === $htmlArrayTemp) { | |
| 191 | - // Restore saved comments, styles and scripts | |
| 192 | -            for ($i = 0; $i < \count($noFormat); ++$i) { | |
| 193 | -                $html = str_replace("<!-- ELEMENT {$i} -->", $noFormat[$i], $html); | |
| 194 | - } | |
| 195 | - | |
| 196 | - return $html; | |
| 197 | - } | |
| 198 | - // remove empty lines | |
| 199 | - $htmlArray = ['']; | |
| 200 | - $index = 1; | |
| 201 | -        for ($x = 0; $x < \count($htmlArrayTemp); ++$x) { | |
| 202 | - $text = trim($htmlArrayTemp[$x]); | |
| 203 | - $htmlArray[$index] = '' !== $text ? $htmlArrayTemp[$x] : $this->emptySpaceChar; | |
| 204 | - ++$index; | |
| 205 | - } | |
| 206 | - | |
| 207 | - // rebuild html | |
| 208 | - $html = ''; | |
| 209 | - $tabs = 0; | |
| 210 | -        for ($x = 0; $x < \count($htmlArray); ++$x) { | |
| 211 | - $htmlArrayBefore = $htmlArray[$x - 1] ?? ''; | |
| 212 | - $htmlArrayCurrent = $htmlArray[$x] ?? ''; | |
| 213 | - | |
| 214 | - // check if the element should stand in a new line | |
| 215 | - $newline = false; | |
| 216 | -            if ('<?xml' == substr($htmlArrayBefore, 0, 5)) { | |
| 217 | - $newline = true; | |
| 218 | - } elseif (2 == $this->formatType && ( // minimalistic line break | |
| 219 | - // this element has a line break before itself | |
| 220 | - preg_match( | |
| 221 | - '/<'.$structureBoxLikeElements.'(.*)>/Usi', | |
| 222 | - $htmlArrayCurrent | |
| 223 | - ) || preg_match( | |
| 224 | - '/<'.$structureBoxLikeElements.'(.*) \/>/Usi', | |
| 225 | - $htmlArrayCurrent | |
| 226 | - ) // one element before is a element that has a line break after | |
| 227 | - || preg_match( | |
| 228 | - '/<\/'.$structureBoxLikeElements.'(.*)>/Usi', | |
| 229 | - $htmlArrayBefore | |
| 230 | - ) || '<!--' == substr( | |
| 231 | - $htmlArrayBefore, | |
| 232 | - 0, | |
| 233 | - 4 | |
| 234 | -                ) || preg_match('/<'.$structureBoxLikeElements.'(.*) \/>/Usi', $htmlArrayBefore)) | |
| 235 | -            ) { | |
| 236 | - $newline = true; | |
| 237 | - } elseif (3 == $this->formatType && ( // aestetic line break | |
| 238 | - // this element has a line break before itself | |
| 239 | - preg_match( | |
| 240 | - '/<'.$esteticBoxLikeElements.'(.*)>/Usi', | |
| 241 | - $htmlArrayCurrent | |
| 242 | - ) || preg_match( | |
| 243 | - '/<'.$esteticBoxLikeElements.'(.*) \/>/Usi', | |
| 244 | - $htmlArrayCurrent | |
| 245 | - ) // one element before is a element that has a line break after | |
| 246 | -                || preg_match('/<\/'.$esteticBoxLikeElements.'(.*)>/Usi', $htmlArrayBefore) || '<!--' == substr( | |
| 247 | - $htmlArrayBefore, | |
| 248 | - 0, | |
| 249 | - 4 | |
| 250 | -                ) || preg_match('/<'.$esteticBoxLikeElements.'(.*) \/>/Usi', $htmlArrayBefore)) | |
| 251 | -            ) { | |
| 252 | - $newline = true; | |
| 253 | - } elseif ($this->formatType >= 4 && ( // logical line break | |
| 254 | - // this element has a line break before itself | |
| 255 | - preg_match( | |
| 256 | - '/<'.$allBoxLikeElements.'(.*)>/Usi', | |
| 257 | - $htmlArrayCurrent | |
| 258 | - ) || preg_match( | |
| 259 | - '/<'.$allBoxLikeElements.'(.*) \/>/Usi', | |
| 260 | - $htmlArrayCurrent | |
| 261 | - ) // one element before is a element that has a line break after | |
| 262 | -                || preg_match('/<\/'.$allBoxLikeElements.'(.*)>/Usi', $htmlArrayBefore) || '<!--' == substr( | |
| 263 | - $htmlArrayBefore, | |
| 264 | - 0, | |
| 265 | - 4 | |
| 266 | -                ) || preg_match('/<'.$allBoxLikeElements.'(.*) \/>/Usi', $htmlArrayBefore)) | |
| 267 | -            ) { | |
| 268 | - $newline = true; | |
| 269 | - } | |
| 270 | - | |
| 271 | - // count down a tab | |
| 272 | -            if ('</' == substr($htmlArrayCurrent, 0, 2)) { | |
| 273 | - --$tabs; | |
| 274 | - } | |
| 275 | - | |
| 276 | - // add tabs and line breaks in front of the current tag | |
| 277 | -            if ($newline) { | |
| 278 | - $html .= $this->newline; | |
| 279 | -                for ($y = 0; $y < $tabs; ++$y) { | |
| 280 | - $html .= $this->tab; | |
| 281 | - } | |
| 282 | - } | |
| 283 | - | |
| 284 | - // remove white spaces and line breaks and add current tag to the html-string | |
| 285 | -            if ('<![CDATA[' == substr($htmlArrayCurrent, 0, 9) // remove multiple white space in CDATA / XML | |
| 286 | - || '<?xml' == substr($htmlArrayCurrent, 0, 5) | |
| 287 | -            ) { | |
| 288 | - $html .= $this->killWhiteSpace($htmlArrayCurrent); | |
| 289 | -            } else { // remove all line breaks | |
| 290 | - $html .= $this->killLineBreaks($htmlArrayCurrent); | |
| 291 | - } | |
| 292 | - | |
| 293 | - // count up a tab | |
| 294 | -            if ('<' == substr($htmlArrayCurrent, 0, 1) && '/' != substr($htmlArrayCurrent, 1, 1)) { | |
| 295 | -                if (' ' !== substr($htmlArrayCurrent, 1, 1) | |
| 296 | - && 'img' !== substr($htmlArrayCurrent, 1, 3) | |
| 297 | - && 'source' !== substr($htmlArrayCurrent, 1, 6) | |
| 298 | - && 'br' !== substr($htmlArrayCurrent, 1, 2) | |
| 299 | - && 'hr' !== substr($htmlArrayCurrent, 1, 2) | |
| 300 | - && 'input' !== substr($htmlArrayCurrent, 1, 5) | |
| 301 | - && 'link' !== substr($htmlArrayCurrent, 1, 4) | |
| 302 | - && 'meta' !== substr($htmlArrayCurrent, 1, 4) | |
| 303 | - && 'col ' !== substr($htmlArrayCurrent, 1, 4) | |
| 304 | - && 'frame' !== substr($htmlArrayCurrent, 1, 5) | |
| 305 | - && 'isindex' !== substr($htmlArrayCurrent, 1, 7) | |
| 306 | - && 'param' !== substr($htmlArrayCurrent, 1, 5) | |
| 307 | - && 'area' !== substr($htmlArrayCurrent, 1, 4) | |
| 308 | - && 'base' !== substr($htmlArrayCurrent, 1, 4) | |
| 309 | - && '<!' !== substr($htmlArrayCurrent, 0, 2) | |
| 310 | - && '<?xml' !== substr($htmlArrayCurrent, 0, 5) | |
| 311 | -                ) { | |
| 312 | - ++$tabs; | |
| 313 | - } | |
| 314 | - } | |
| 315 | - } | |
| 316 | - | |
| 317 | - // Remove empty lines | |
| 318 | -        if ($this->formatType > 1) { | |
| 319 | - $this->removeEmptyLines($html); | |
| 320 | - } | |
| 321 | - | |
| 322 | - // Restore saved comments, styles and scripts | |
| 323 | -        for ($i = 0; $i < \count($noFormat); ++$i) { | |
| 324 | -            $html = str_replace("<!-- ELEMENT {$i} -->", $noFormat[$i], $html); | |
| 325 | - } | |
| 326 | - | |
| 327 | - // include debug comment at the end | |
| 328 | -        if (0 != $tabs && true === $this->debugComment) { | |
| 329 | -            $html .= "<!-- {$tabs} open elements found -->"; | |
| 330 | - } | |
| 331 | - | |
| 332 | - return $html; | |
| 333 | - } | |
| 334 | - | |
| 335 | - /** | |
| 336 | - * Remove ALL line breaks and multiple white space. | |
| 337 | - * | |
| 338 | - * @param string $html | |
| 339 | - * | |
| 340 | - * @return string | |
| 341 | - */ | |
| 342 | - protected function killLineBreaks($html) | |
| 343 | -    { | |
| 344 | - $html = str_replace($this->newline, '', $html); | |
| 345 | - | |
| 346 | -        return preg_replace('/\s\s+/u', ' ', $html); | |
| 347 | -        // ? return preg_replace('/\n|\s+(\s)/u', '$1', $html); | |
| 348 | - } | |
| 349 | - | |
| 350 | - /** | |
| 351 | - * Remove multiple white space, keeps line breaks. | |
| 352 | - */ | |
| 353 | - protected function killWhiteSpace(string $html): string | |
| 354 | -    { | |
| 355 | - $temp = explode($this->newline, $html); | |
| 356 | -        for ($i = 0; $i < \count($temp); ++$i) { | |
| 357 | -            if (!trim($temp[$i])) { | |
| 358 | - unset($temp[$i]); | |
| 359 | - continue; | |
| 360 | - } | |
| 361 | - | |
| 362 | - $temp[$i] = trim($temp[$i]); | |
| 363 | -            $temp[$i] = preg_replace('/\s\s+/', ' ', $temp[$i]); | |
| 364 | - } | |
| 365 | - | |
| 366 | - return implode($this->newline, $temp); | |
| 367 | - } | |
| 368 | - | |
| 369 | - /** | |
| 370 | - * Remove white space at the end of lines, keeps other white space and line breaks. | |
| 371 | - */ | |
| 372 | - protected function rTrimLines(string &$html): void | |
| 373 | -    { | |
| 374 | -        $html = preg_replace('/\s+$/m', '', $html); | |
| 375 | - } | |
| 376 | - | |
| 377 | - /** | |
| 378 | - * Convert newlines according to the current OS. | |
| 379 | - */ | |
| 380 | - protected function convNlOs(string &$html): void | |
| 381 | -    { | |
| 382 | -        $html = preg_replace("(\r\n|\r)", $this->newline, $html); | |
| 383 | - } | |
| 384 | - | |
| 385 | - /** | |
| 386 | - * Remove empty lines. | |
| 387 | - */ | |
| 388 | - protected function removeEmptyLines(string &$html): void | |
| 389 | -    { | |
| 390 | - $temp = explode($this->newline, $html); | |
| 391 | - $result = []; | |
| 392 | -        for ($i = 0; $i < \count($temp); ++$i) { | |
| 393 | -            if ('' == trim($temp[$i])) { | |
| 394 | - continue; | |
| 395 | - } | |
| 396 | - $result[] = $temp[$i]; | |
| 397 | - } | |
| 398 | - $html = implode($this->newline, $result); | |
| 399 | - } | |
| 400 | - | |
| 401 | - /** | |
| 402 | - * Include configured header comment in HTML content block. | |
| 403 | - */ | |
| 404 | - public function includeHeaderComment(string &$html): void | |
| 405 | -    { | |
| 406 | -        $html = preg_replace('/^(-->)$/m', "\n\t".$this->headerComment."\n$1", $html); | |
| 407 | - } | |
| 20 | + /** | |
| 21 | + * Enable Debug comment in footer. | |
| 22 | + * | |
| 23 | + * @var bool | |
| 24 | + */ | |
| 25 | + protected $debugComment = false; | |
| 26 | + | |
| 27 | + /** | |
| 28 | + * Format Type. | |
| 29 | + * | |
| 30 | + * @var int | |
| 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 | + * | |
| 58 | + * @var string | |
| 59 | + */ | |
| 60 | + protected $emptySpaceChar = ' '; | |
| 61 | + | |
| 62 | + /** | |
| 63 | + * Set variables based on given config. | |
| 64 | + */ | |
| 65 | + public function setVariables(array $config): void | |
| 66 | +	{ | |
| 67 | +		if (isset($config['headerComment']) && !empty($config['headerComment'])) { | |
| 68 | + $this->headerComment = $config['headerComment']; | |
| 69 | + } | |
| 70 | + | |
| 71 | +		if (isset($config['formatHtml']) && is_numeric($config['formatHtml'])) { | |
| 72 | + $this->formatType = (int) $config['formatHtml']; | |
| 73 | + } | |
| 74 | + | |
| 75 | +		if (isset($config['formatHtml.']['tabSize']) && is_numeric($config['formatHtml.']['tabSize'])) { | |
| 76 | +			$this->tab = str_pad('', (int) $config['formatHtml.']['tabSize'], ' '); | |
| 77 | + } | |
| 78 | + | |
| 79 | +		if (isset($config['formatHtml.']['debugComment'])) { | |
| 80 | + $this->debugComment = (bool) $config['formatHtml.']['debugComment']; | |
| 81 | + } | |
| 82 | + | |
| 83 | +		if (isset($config['dropEmptySpaceChar']) && (bool) $config['dropEmptySpaceChar']) { | |
| 84 | + $this->emptySpaceChar = ''; | |
| 85 | + } | |
| 86 | + } | |
| 87 | + | |
| 88 | + /** | |
| 89 | + * Clean given HTML with formatter. | |
| 90 | + * | |
| 91 | + * @return string | |
| 92 | + */ | |
| 93 | + public function clean(string $html, array $config = []) | |
| 94 | +	{ | |
| 95 | +		if (!empty($config)) { | |
| 96 | + $this->setVariables($config); | |
| 97 | + } | |
| 98 | + | |
| 99 | + // convert line-breaks to UNIX | |
| 100 | + $this->convNlOs($html); | |
| 101 | + | |
| 102 | + $manipulations = []; | |
| 103 | + | |
| 104 | +		if (isset($config['removeGenerator']) && (bool) $config['removeGenerator']) { | |
| 105 | + $manipulations['removeGenerator'] = GeneralUtility::makeInstance(RemoveGenerator::class); | |
| 106 | + } | |
| 107 | + | |
| 108 | +		if (isset($config['removeComments']) && (bool) $config['removeComments']) { | |
| 109 | + $manipulations['removeComments'] = GeneralUtility::makeInstance(RemoveComments::class); | |
| 110 | + } | |
| 111 | + | |
| 112 | +		if (!empty($this->headerComment)) { | |
| 113 | + $this->includeHeaderComment($html); | |
| 114 | + } | |
| 115 | + | |
| 116 | +		foreach ($manipulations as $key => $manipulation) { | |
| 117 | + /** @var ManipulationInterface $manipulation */ | |
| 118 | + $configuration = isset($config[$key.'.']) && \is_array($config[$key.'.']) ? $config[$key.'.'] : []; | |
| 119 | + $html = $manipulation->manipulate($html, $configuration); | |
| 120 | + } | |
| 121 | + | |
| 122 | + // cleanup HTML5 self-closing elements | |
| 123 | + if (!isset($GLOBALS['TSFE']->config['config']['doctype']) | |
| 124 | +			|| 'x' !== substr($GLOBALS['TSFE']->config['config']['doctype'], 0, 1)) { | |
| 125 | + $html = preg_replace( | |
| 126 | + '/<((?:area|base|br|col|embed|hr|img|input|link|meta|param|source|track|wbr)\s[^>\\\\]+?)\s?\/>/', | |
| 127 | + '<$1>', | |
| 128 | + $html | |
| 129 | + ); | |
| 130 | + } | |
| 131 | + | |
| 132 | +		if ($this->formatType > 0) { | |
| 133 | + $html = $this->formatHtml($html); | |
| 134 | + } | |
| 135 | + | |
| 136 | + // remove white space after line ending | |
| 137 | + $this->rTrimLines($html); | |
| 138 | + | |
| 139 | + // recover line-breaks | |
| 140 | +		if (Environment::isWindows()) { | |
| 141 | + $html = str_replace($this->newline, "\r\n", $html); | |
| 142 | + } | |
| 143 | + | |
| 144 | + return (string) $html; | |
| 145 | + } | |
| 146 | + | |
| 147 | + /** | |
| 148 | + * Formats the (X)HTML code: | |
| 149 | + * - taps according to the hirarchy of the tags | |
| 150 | + * - removes empty spaces between tags | |
| 151 | + * - removes linebreaks within tags (spares where necessary: pre, textarea, comments, ..) | |
| 152 | + * choose from five options: | |
| 153 | + * 0 => off | |
| 154 | + * 1 => no line break at all (code in one line) | |
| 155 | + * 2 => minimalistic line breaks (structure defining box-elements) | |
| 156 | + * 3 => aesthetic line breaks (important box-elements) | |
| 157 | + * 4 => logic line breaks (all box-elements) | |
| 158 | + * 5 => max line breaks (all elements). | |
| 159 | + */ | |
| 160 | + protected function formatHtml(string $html): string | |
| 161 | +	{ | |
| 162 | + // Save original formated pre, textarea, comments, styles and scripts & replace them with markers | |
| 163 | + preg_match_all( | |
| 164 | + '/(?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', | |
| 165 | + $html, | |
| 166 | + $matches | |
| 167 | + ); | |
| 168 | + $noFormat = $matches[0]; // do not format these block elements | |
| 169 | +		for ($i = 0; $i < \count($noFormat); ++$i) { | |
| 170 | +			$html = str_replace($noFormat[$i], "\n<!-- ELEMENT {$i} -->", $html); | |
| 171 | + } | |
| 172 | + | |
| 173 | + // define box elements for formatting | |
| 174 | + $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'; | |
| 175 | + $functionalBoxElements = 'dd|dt|frameset|li|tbody|td|tfoot|th|thead|tr|colgroup'; | |
| 176 | + $usableBoxElements = 'applet|button|del|iframe|ins|map|object|script'; | |
| 177 | + $imagineBoxElements = 'html|body|head|meta|title|link|script|base|!--'; | |
| 178 | + $allBoxLikeElements = '(?>'.$trueBoxElements.'|'.$functionalBoxElements.'|'.$usableBoxElements.'|'.$imagineBoxElements.')'; | |
| 179 | + $esteticBoxLikeElements = '(?>html|head|body|meta name|title|div|table|h1|h2|h3|h4|h5|h6|p|form|pre|center|!--)'; | |
| 180 | + $structureBoxLikeElements = '(?>html|head|body|div|!--)'; | |
| 181 | + | |
| 182 | + // split html into it's elements | |
| 183 | + $htmlArrayTemp = preg_split( | |
| 184 | + '/(<(?:[^<>]+(?:"[^"]*"|\'[^\']*\')?)+>)/', | |
| 185 | + $html, | |
| 186 | + -1, | |
| 187 | + \PREG_SPLIT_DELIM_CAPTURE | \PREG_SPLIT_NO_EMPTY | |
| 188 | + ); | |
| 189 | + | |
| 190 | +		if (false === $htmlArrayTemp) { | |
| 191 | + // Restore saved comments, styles and scripts | |
| 192 | +			for ($i = 0; $i < \count($noFormat); ++$i) { | |
| 193 | +				$html = str_replace("<!-- ELEMENT {$i} -->", $noFormat[$i], $html); | |
| 194 | + } | |
| 195 | + | |
| 196 | + return $html; | |
| 197 | + } | |
| 198 | + // remove empty lines | |
| 199 | + $htmlArray = ['']; | |
| 200 | + $index = 1; | |
| 201 | +		for ($x = 0; $x < \count($htmlArrayTemp); ++$x) { | |
| 202 | + $text = trim($htmlArrayTemp[$x]); | |
| 203 | + $htmlArray[$index] = '' !== $text ? $htmlArrayTemp[$x] : $this->emptySpaceChar; | |
| 204 | + ++$index; | |
| 205 | + } | |
| 206 | + | |
| 207 | + // rebuild html | |
| 208 | + $html = ''; | |
| 209 | + $tabs = 0; | |
| 210 | +		for ($x = 0; $x < \count($htmlArray); ++$x) { | |
| 211 | + $htmlArrayBefore = $htmlArray[$x - 1] ?? ''; | |
| 212 | + $htmlArrayCurrent = $htmlArray[$x] ?? ''; | |
| 213 | + | |
| 214 | + // check if the element should stand in a new line | |
| 215 | + $newline = false; | |
| 216 | +			if ('<?xml' == substr($htmlArrayBefore, 0, 5)) { | |
| 217 | + $newline = true; | |
| 218 | + } elseif (2 == $this->formatType && ( // minimalistic line break | |
| 219 | + // this element has a line break before itself | |
| 220 | + preg_match( | |
| 221 | + '/<'.$structureBoxLikeElements.'(.*)>/Usi', | |
| 222 | + $htmlArrayCurrent | |
| 223 | + ) || preg_match( | |
| 224 | + '/<'.$structureBoxLikeElements.'(.*) \/>/Usi', | |
| 225 | + $htmlArrayCurrent | |
| 226 | + ) // one element before is a element that has a line break after | |
| 227 | + || preg_match( | |
| 228 | + '/<\/'.$structureBoxLikeElements.'(.*)>/Usi', | |
| 229 | + $htmlArrayBefore | |
| 230 | + ) || '<!--' == substr( | |
| 231 | + $htmlArrayBefore, | |
| 232 | + 0, | |
| 233 | + 4 | |
| 234 | +				) || preg_match('/<'.$structureBoxLikeElements.'(.*) \/>/Usi', $htmlArrayBefore)) | |
| 235 | +			) { | |
| 236 | + $newline = true; | |
| 237 | + } elseif (3 == $this->formatType && ( // aestetic line break | |
| 238 | + // this element has a line break before itself | |
| 239 | + preg_match( | |
| 240 | + '/<'.$esteticBoxLikeElements.'(.*)>/Usi', | |
| 241 | + $htmlArrayCurrent | |
| 242 | + ) || preg_match( | |
| 243 | + '/<'.$esteticBoxLikeElements.'(.*) \/>/Usi', | |
| 244 | + $htmlArrayCurrent | |
| 245 | + ) // one element before is a element that has a line break after | |
| 246 | +				|| preg_match('/<\/'.$esteticBoxLikeElements.'(.*)>/Usi', $htmlArrayBefore) || '<!--' == substr( | |
| 247 | + $htmlArrayBefore, | |
| 248 | + 0, | |
| 249 | + 4 | |
| 250 | +				) || preg_match('/<'.$esteticBoxLikeElements.'(.*) \/>/Usi', $htmlArrayBefore)) | |
| 251 | +			) { | |
| 252 | + $newline = true; | |
| 253 | + } elseif ($this->formatType >= 4 && ( // logical line break | |
| 254 | + // this element has a line break before itself | |
| 255 | + preg_match( | |
| 256 | + '/<'.$allBoxLikeElements.'(.*)>/Usi', | |
| 257 | + $htmlArrayCurrent | |
| 258 | + ) || preg_match( | |
| 259 | + '/<'.$allBoxLikeElements.'(.*) \/>/Usi', | |
| 260 | + $htmlArrayCurrent | |
| 261 | + ) // one element before is a element that has a line break after | |
| 262 | +				|| preg_match('/<\/'.$allBoxLikeElements.'(.*)>/Usi', $htmlArrayBefore) || '<!--' == substr( | |
| 263 | + $htmlArrayBefore, | |
| 264 | + 0, | |
| 265 | + 4 | |
| 266 | +				) || preg_match('/<'.$allBoxLikeElements.'(.*) \/>/Usi', $htmlArrayBefore)) | |
| 267 | +			) { | |
| 268 | + $newline = true; | |
| 269 | + } | |
| 270 | + | |
| 271 | + // count down a tab | |
| 272 | +			if ('</' == substr($htmlArrayCurrent, 0, 2)) { | |
| 273 | + --$tabs; | |
| 274 | + } | |
| 275 | + | |
| 276 | + // add tabs and line breaks in front of the current tag | |
| 277 | +			if ($newline) { | |
| 278 | + $html .= $this->newline; | |
| 279 | +				for ($y = 0; $y < $tabs; ++$y) { | |
| 280 | + $html .= $this->tab; | |
| 281 | + } | |
| 282 | + } | |
| 283 | + | |
| 284 | + // remove white spaces and line breaks and add current tag to the html-string | |
| 285 | +			if ('<![CDATA[' == substr($htmlArrayCurrent, 0, 9) // remove multiple white space in CDATA / XML | |
| 286 | + || '<?xml' == substr($htmlArrayCurrent, 0, 5) | |
| 287 | +			) { | |
| 288 | + $html .= $this->killWhiteSpace($htmlArrayCurrent); | |
| 289 | +			} else { // remove all line breaks | |
| 290 | + $html .= $this->killLineBreaks($htmlArrayCurrent); | |
| 291 | + } | |
| 292 | + | |
| 293 | + // count up a tab | |
| 294 | +			if ('<' == substr($htmlArrayCurrent, 0, 1) && '/' != substr($htmlArrayCurrent, 1, 1)) { | |
| 295 | +				if (' ' !== substr($htmlArrayCurrent, 1, 1) | |
| 296 | + && 'img' !== substr($htmlArrayCurrent, 1, 3) | |
| 297 | + && 'source' !== substr($htmlArrayCurrent, 1, 6) | |
| 298 | + && 'br' !== substr($htmlArrayCurrent, 1, 2) | |
| 299 | + && 'hr' !== substr($htmlArrayCurrent, 1, 2) | |
| 300 | + && 'input' !== substr($htmlArrayCurrent, 1, 5) | |
| 301 | + && 'link' !== substr($htmlArrayCurrent, 1, 4) | |
| 302 | + && 'meta' !== substr($htmlArrayCurrent, 1, 4) | |
| 303 | + && 'col ' !== substr($htmlArrayCurrent, 1, 4) | |
| 304 | + && 'frame' !== substr($htmlArrayCurrent, 1, 5) | |
| 305 | + && 'isindex' !== substr($htmlArrayCurrent, 1, 7) | |
| 306 | + && 'param' !== substr($htmlArrayCurrent, 1, 5) | |
| 307 | + && 'area' !== substr($htmlArrayCurrent, 1, 4) | |
| 308 | + && 'base' !== substr($htmlArrayCurrent, 1, 4) | |
| 309 | + && '<!' !== substr($htmlArrayCurrent, 0, 2) | |
| 310 | + && '<?xml' !== substr($htmlArrayCurrent, 0, 5) | |
| 311 | +				) { | |
| 312 | + ++$tabs; | |
| 313 | + } | |
| 314 | + } | |
| 315 | + } | |
| 316 | + | |
| 317 | + // Remove empty lines | |
| 318 | +		if ($this->formatType > 1) { | |
| 319 | + $this->removeEmptyLines($html); | |
| 320 | + } | |
| 321 | + | |
| 322 | + // Restore saved comments, styles and scripts | |
| 323 | +		for ($i = 0; $i < \count($noFormat); ++$i) { | |
| 324 | +			$html = str_replace("<!-- ELEMENT {$i} -->", $noFormat[$i], $html); | |
| 325 | + } | |
| 326 | + | |
| 327 | + // include debug comment at the end | |
| 328 | +		if (0 != $tabs && true === $this->debugComment) { | |
| 329 | +			$html .= "<!-- {$tabs} open elements found -->"; | |
| 330 | + } | |
| 331 | + | |
| 332 | + return $html; | |
| 333 | + } | |
| 334 | + | |
| 335 | + /** | |
| 336 | + * Remove ALL line breaks and multiple white space. | |
| 337 | + * | |
| 338 | + * @param string $html | |
| 339 | + * | |
| 340 | + * @return string | |
| 341 | + */ | |
| 342 | + protected function killLineBreaks($html) | |
| 343 | +	{ | |
| 344 | + $html = str_replace($this->newline, '', $html); | |
| 345 | + | |
| 346 | +		return preg_replace('/\s\s+/u', ' ', $html); | |
| 347 | +		// ? return preg_replace('/\n|\s+(\s)/u', '$1', $html); | |
| 348 | + } | |
| 349 | + | |
| 350 | + /** | |
| 351 | + * Remove multiple white space, keeps line breaks. | |
| 352 | + */ | |
| 353 | + protected function killWhiteSpace(string $html): string | |
| 354 | +	{ | |
| 355 | + $temp = explode($this->newline, $html); | |
| 356 | +		for ($i = 0; $i < \count($temp); ++$i) { | |
| 357 | +			if (!trim($temp[$i])) { | |
| 358 | + unset($temp[$i]); | |
| 359 | + continue; | |
| 360 | + } | |
| 361 | + | |
| 362 | + $temp[$i] = trim($temp[$i]); | |
| 363 | +			$temp[$i] = preg_replace('/\s\s+/', ' ', $temp[$i]); | |
| 364 | + } | |
| 365 | + | |
| 366 | + return implode($this->newline, $temp); | |
| 367 | + } | |
| 368 | + | |
| 369 | + /** | |
| 370 | + * Remove white space at the end of lines, keeps other white space and line breaks. | |
| 371 | + */ | |
| 372 | + protected function rTrimLines(string &$html): void | |
| 373 | +	{ | |
| 374 | +		$html = preg_replace('/\s+$/m', '', $html); | |
| 375 | + } | |
| 376 | + | |
| 377 | + /** | |
| 378 | + * Convert newlines according to the current OS. | |
| 379 | + */ | |
| 380 | + protected function convNlOs(string &$html): void | |
| 381 | +	{ | |
| 382 | +		$html = preg_replace("(\r\n|\r)", $this->newline, $html); | |
| 383 | + } | |
| 384 | + | |
| 385 | + /** | |
| 386 | + * Remove empty lines. | |
| 387 | + */ | |
| 388 | + protected function removeEmptyLines(string &$html): void | |
| 389 | +	{ | |
| 390 | + $temp = explode($this->newline, $html); | |
| 391 | + $result = []; | |
| 392 | +		for ($i = 0; $i < \count($temp); ++$i) { | |
| 393 | +			if ('' == trim($temp[$i])) { | |
| 394 | + continue; | |
| 395 | + } | |
| 396 | + $result[] = $temp[$i]; | |
| 397 | + } | |
| 398 | + $html = implode($this->newline, $result); | |
| 399 | + } | |
| 400 | + | |
| 401 | + /** | |
| 402 | + * Include configured header comment in HTML content block. | |
| 403 | + */ | |
| 404 | + public function includeHeaderComment(string &$html): void | |
| 405 | +	{ | |
| 406 | +		$html = preg_replace('/^(-->)$/m', "\n\t".$this->headerComment."\n$1", $html); | |
| 407 | + } | |
| 408 | 408 | } | 
| @@ -89,7 +89,7 @@ discard block | ||
| 89 | 89 | } | 
| 90 | 90 | |
| 91 | 91 | // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#attributes | 
| 92 | -        $dom['body'] = preg_replace_callback('/<img(?<pre>[^>]*)src="(?:https?:)?(?:\/\/[^\/]+?)?(?<src>\/[^"]+\.svg)"(?<post>[^>]*?)[\s\/]*>(?!\s*<\/picture>)/s', function (array $match): string { // ^[/] | |
| 92 | +        $dom['body'] = preg_replace_callback('/<img(?<pre>[^>]*)src="(?:https?:)?(?:\/\/[^\/]+?)?(?<src>\/[^"]+\.svg)"(?<post>[^>]*?)[\s\/]*>(?!\s*<\/picture>)/s', function(array $match): string { // ^[/] | |
| 93 | 93 |              if (!isset($this->svgFileArr[$match['src']])) { // check usage | 
| 94 | 94 | return $match[0]; | 
| 95 | 95 | } | 
| @@ -99,7 +99,7 @@ discard block | ||
| 99 | 99 | }, $dom['body']); | 
| 100 | 100 | |
| 101 | 101 | // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/object#attributes | 
| 102 | -        $dom['body'] = preg_replace_callback('/<object(?<pre>[^>]*)data="(?<data>\/[^"]+\.svg)"(?<post>[^>]*?)[\s\/]*>(?:<\/object>)/s', function (array $match): string { // ^[/] | |
| 102 | +        $dom['body'] = preg_replace_callback('/<object(?<pre>[^>]*)data="(?<data>\/[^"]+\.svg)"(?<post>[^>]*?)[\s\/]*>(?:<\/object>)/s', function(array $match): string { // ^[/] | |
| 103 | 103 |              if (!isset($this->svgFileArr[$match['data']])) { // check usage | 
| 104 | 104 | return $match[0]; | 
| 105 | 105 | } | 
| @@ -152,7 +152,7 @@ discard block | ||
| 152 | 152 | // }, $svg); | 
| 153 | 153 | |
| 154 | 154 | // https://developer.mozilla.org/en-US/docs/Web/SVG/Element/svg#attributes | 
| 155 | -        $svg = preg_replace_callback('/([^>]*)\s*(?=>)/s', function (array $match) use (&$attr): string { | |
| 155 | +        $svg = preg_replace_callback('/([^>]*)\s*(?=>)/s', function(array $match) use (&$attr): string { | |
| 156 | 156 |              if (false === preg_match_all('/(?!\s)(?<attr>[\w\-]+)="\s*(?<value>[^"]+)\s*"/', $match[1], $matches)) { | 
| 157 | 157 | return $match[0]; | 
| 158 | 158 | } | 
| @@ -206,7 +206,7 @@ discard block | ||
| 206 | 206 | |
| 207 | 207 | $svg = preg_replace_callback( | 
| 208 | 208 | '/<use(?<pre>.*?)(?:xlink:)?href="(?<href>\/.+?\.svg)(?:#[^"]*?)?"(?<post>.*?)[\s\/]*>(?:<\/use>)?/s', | 
| 209 | -            function (array $match): string { | |
| 209 | +            function(array $match): string { | |
| 210 | 210 |                  if (!isset($this->svgFileArr[$match['href']])) { // check usage | 
| 211 | 211 | return $match[0]; | 
| 212 | 212 | } | 
| @@ -13,244 +13,244 @@ | ||
| 13 | 13 | */ | 
| 14 | 14 | class SvgStoreService implements \TYPO3\CMS\Core\SingletonInterface | 
| 15 | 15 |  { | 
| 16 | - /** | |
| 17 | - * SVG-Sprite relativ storage directory. | |
| 18 | - * | |
| 19 | - * @var string | |
| 20 | - */ | |
| 21 | - protected $outputDir = '/typo3temp/assets/svg/'; | |
| 22 | - | |
| 23 | - /** | |
| 24 | - * TYPO3 absolute path to public web. | |
| 25 | - * | |
| 26 | - * @var string | |
| 27 | - */ | |
| 28 | - protected $sitePath = ''; | |
| 29 | - | |
| 30 | - /** | |
| 31 | - * Final TYPO3 Frontend-Cache object. | |
| 32 | - * | |
| 33 | - * @var \TYPO3\CMS\Core\Cache\Frontend\VariableFrontend | |
| 34 | - */ | |
| 35 | - protected $svgCache; | |
| 36 | - | |
| 37 | - /** | |
| 38 | - * Cached SVG-Sprite relativ file path. | |
| 39 | - * | |
| 40 | - * @var string | |
| 41 | - */ | |
| 42 | - protected $spritePath = ''; | |
| 43 | - | |
| 44 | - /** | |
| 45 | - * Cached used SVG files (incl. defs). | |
| 46 | - * | |
| 47 | - * @var array | |
| 48 | - */ | |
| 49 | - protected $svgFileArr = []; | |
| 50 | - | |
| 51 | - /** | |
| 52 | - * Final SVG-Sprite Vectors. | |
| 53 | - * | |
| 54 | - * @var array | |
| 55 | - */ | |
| 56 | - protected $svgs = []; | |
| 57 | - | |
| 58 | - /** | |
| 59 | - * Final SVG-Sprite Styles. | |
| 60 | - * | |
| 61 | - * @var array | |
| 62 | - */ | |
| 63 | - protected $styl = []; // ToFix ; https://stackoverflow.com/questions/39583880/external-svg-fails-to-apply-internal-css | |
| 64 | - | |
| 65 | - /** | |
| 66 | - * Final SVG-Sprite Objects. | |
| 67 | - * | |
| 68 | - * @var array | |
| 69 | - */ | |
| 70 | - protected $defs = []; // ToFix ; https://bugs.chromium.org/p/chromium/issues/detail?id=751733#c14 | |
| 71 | - | |
| 72 | - public function __construct() | |
| 73 | -    { | |
| 74 | - $this->sitePath = \TYPO3\CMS\Core\Core\Environment::getPublicPath(); // [^/]$ | |
| 75 | -        $this->svgCache = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Cache\CacheManager::class)->getCache('svgstore'); | |
| 76 | - | |
| 77 | -        $this->spritePath = $this->svgCache->get('spritePath') ?: ''; | |
| 78 | -        $this->svgFileArr = $this->svgCache->get('svgFileArr') ?: []; | |
| 79 | - | |
| 80 | -        if (empty($this->spritePath) && !$this->populateCache()) { | |
| 81 | -            throw new \Exception('could not write file: '.$this->sitePath.$this->spritePath); | |
| 82 | - } | |
| 83 | - | |
| 84 | -        if (!file_exists($this->sitePath.$this->spritePath)) { | |
| 85 | -            throw new \Exception('file does not exists: '.$this->sitePath.$this->spritePath); | |
| 86 | - } | |
| 87 | - } | |
| 88 | - | |
| 89 | - public function process(string $html): string | |
| 90 | -    { | |
| 91 | -        if ($GLOBALS['TSFE']->config['config']['disableAllHeaderCode'] ?? false) { | |
| 92 | - $dom = ['head' => '', 'body' => $html]; | |
| 93 | -        } elseif (!preg_match('/(?<head>.+?<\/head>)(?<body>.+)/s', $html, $dom)) { | |
| 94 | - return $html; | |
| 95 | - } | |
| 96 | - | |
| 97 | - // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#attributes | |
| 98 | -        $dom['body'] = preg_replace_callback('/<img(?<pre>[^>]*)src="(?:https?:)?(?:\/\/[^\/]+?)?(?<src>\/[^"]+\.svg)"(?<post>[^>]*?)[\s\/]*>(?!\s*<\/picture>)/s', function (array $match): string { // ^[/] | |
| 99 | -            if (!isset($this->svgFileArr[$match['src']])) { // check usage | |
| 100 | - return $match[0]; | |
| 101 | - } | |
| 102 | -            $attr = preg_replace('/\s(?:alt|ismap|loading|title|sizes|srcset|usemap|crossorigin|decoding|fetchpriority|referrerpolicy)="[^"]*"/', '', $match['pre'].$match['post']); // cleanup | |
| 103 | - | |
| 104 | -            return sprintf('<svg %s %s><use href="%s#%s"/></svg>', $this->svgFileArr[$match['src']]['attr'], trim($attr), $this->spritePath, $this->convertFilePath($match['src'])); | |
| 105 | - }, $dom['body']); | |
| 106 | - | |
| 107 | - // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/object#attributes | |
| 108 | -        $dom['body'] = preg_replace_callback('/<object(?<pre>[^>]*)data="(?<data>\/[^"]+\.svg)"(?<post>[^>]*?)[\s\/]*>(?:<\/object>)/s', function (array $match): string { // ^[/] | |
| 109 | -            if (!isset($this->svgFileArr[$match['data']])) { // check usage | |
| 110 | - return $match[0]; | |
| 111 | - } | |
| 112 | -            $attr = preg_replace('/\s(?:form|name|type|usemap)="[^"]*"/', '', $match['pre'].$match['post']); // cleanup | |
| 113 | - | |
| 114 | -            return sprintf('<svg %s %s><use href="%s#%s"/></svg>', $this->svgFileArr[$match['data']]['attr'], trim($attr), $this->spritePath, $this->convertFilePath($match['data'])); | |
| 115 | - }, $dom['body']); | |
| 116 | - | |
| 117 | - return $dom['head'].$dom['body']; | |
| 118 | - } | |
| 119 | - | |
| 120 | - private function convertFilePath(string $path): string | |
| 121 | -    { | |
| 122 | -        return preg_replace('/.svg$|[^\w\-]/', '', str_replace('/', '-', ltrim($path, '/'))); // ^[^/] | |
| 123 | - } | |
| 124 | - | |
| 125 | - private function addFileToSpriteArr(string $hash, string $path, array $attr = []): ?array | |
| 126 | -    { | |
| 127 | -        if (!file_exists($this->sitePath.$path)) { | |
| 128 | - return null; | |
| 129 | - } | |
| 130 | - | |
| 131 | - $svg = file_get_contents($this->sitePath.$path); | |
| 132 | - | |
| 133 | -        if (preg_match('/(?:;base64|i:a?i?pgf)/', $svg)) { // noop! | |
| 134 | - return null; | |
| 135 | - } | |
| 136 | - | |
| 137 | -        if (preg_match('/<(?:style|defs)|url\(/', $svg)) { | |
| 138 | - return null; // check links @ __construct | |
| 139 | - } | |
| 140 | - | |
| 141 | - // https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/xlink:href | |
| 142 | -        $svg = preg_replace('/^.*?<svg|\s*(<\/svg>)(?!.*\1).*$|xlink:|\s(?:(?:version|xmlns)|(?:[a-z\-]+\:[a-z\-]+))="[^"]*"/s', '', $svg); // cleanup | |
| 143 | - | |
| 144 | -        // $svg = preg_replace('/(?<=(?:id|class)=")/', $hash.'__', $svg); // extend  IDs | |
| 145 | -        // $svg = preg_replace('/(?<=href="|url\()#/', $hash.'__', $svg); // recover IDs | |
| 146 | - | |
| 147 | -        // $svg = preg_replace_callback('/<style[^>]*>(?<styl>.+?)<\/style>|<defs[^>]*>(?<defs>.+?)<\/defs>/s', function(array $match) use($hash): string { | |
| 148 | - // | |
| 149 | - // if(isset($match['styl'])) | |
| 150 | -        //    { | |
| 151 | -        //        $this->styl[] = preg_replace('/\s*(\.|#){1}(.+?)\s*\{/', '$1'.$hash.'__$2{', $match['styl']); // patch CSS # https://mathiasbynens.be/notes/css-escapes | |
| 152 | - // } | |
| 153 | - // if(isset($match['defs'])) | |
| 154 | -        //    { | |
| 155 | - // $this->defs[] = trim($match['defs']); | |
| 156 | - // } | |
| 157 | - // return ''; | |
| 158 | - // }, $svg); | |
| 159 | - | |
| 160 | - // https://developer.mozilla.org/en-US/docs/Web/SVG/Element/svg#attributes | |
| 161 | -        $svg = preg_replace_callback('/([^>]*)\s*(?=>)/s', function (array $match) use (&$attr): string { | |
| 162 | -            if (false === preg_match_all('/(?!\s)(?<attr>[\w\-]+)="\s*(?<value>[^"]+)\s*"/', $match[1], $matches)) { | |
| 163 | - return $match[0]; | |
| 164 | - } | |
| 165 | -            foreach ($matches['attr'] as $index => $attribute) { | |
| 166 | -                switch ($attribute) { | |
| 167 | - case 'id': | |
| 168 | - case 'width': | |
| 169 | - case 'height': | |
| 170 | - unset($matches[0][$index]); | |
| 171 | - break; | |
| 172 | - | |
| 173 | - case 'viewBox': | |
| 174 | -                        if (false !== preg_match('/\S+\s\S+\s\+?(?<width>[\d\.]+)\s\+?(?<height>[\d\.]+)/', $matches['value'][$index], $match)) { | |
| 175 | -                            $attr[] = sprintf('%s="0 0 %s %s"', $attribute, $match['width'], $match['height']); // save! | |
| 176 | - } | |
| 177 | - } | |
| 178 | - } | |
| 179 | - | |
| 180 | -            return implode(' ', $matches[0]); | |
| 181 | - }, $svg, 1); | |
| 182 | - | |
| 183 | -        if (empty($attr)) { | |
| 184 | - return null; | |
| 185 | - } | |
| 186 | - | |
| 187 | -        $this->svgs[] = sprintf('id="%s" %s', $this->convertFilePath($path), $svg); // prepend ID | |
| 188 | - | |
| 189 | -        return ['attr' => implode(' ', $attr), 'hash' => $hash]; | |
| 190 | - } | |
| 191 | - | |
| 192 | - private function populateCache(): bool | |
| 193 | -    { | |
| 194 | - $storageArr = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Resource\StorageRepository::class)->findAll(); | |
| 195 | -        foreach ($storageArr as $storage) { | |
| 196 | -            if ('relative' == $storage->getConfiguration()['pathType']) { | |
| 197 | - $storageArr[$storage->getUid()] = rtrim($storage->getConfiguration()['basePath'], '/'); // [^/]$ | |
| 198 | - } | |
| 199 | - } | |
| 200 | - unset($storageArr[0]); // keep! | |
| 201 | - | |
| 202 | - $fileArr = GeneralUtility::makeInstance(\HTML\Sourceopt\Resource\SvgFileRepository::class)->findAllByStorageUids(array_keys($storageArr)); | |
| 203 | -        foreach ($fileArr as $file) { | |
| 204 | - $file['path'] = '/'.$storageArr[$file['storage']].$file['identifier']; // ^[/] | |
| 205 | - $file['defs'] = $this->addFileToSpriteArr($file['sha1'], $file['path']); | |
| 206 | - | |
| 207 | -            if (null !== $file['defs']) { | |
| 208 | - $this->svgFileArr[$file['path']] = $file['defs']; | |
| 209 | - } | |
| 210 | - } | |
| 211 | - unset($storageArr, $storage, $fileArr, $file); // save MEM | |
| 212 | - | |
| 213 | - $svg = preg_replace_callback( | |
| 214 | - '/<use(?<pre>.*?)(?:xlink:)?href="(?<href>\/.+?\.svg)(?:#[^"]*?)?"(?<post>.*?)[\s\/]*>(?:<\/use>)?/s', | |
| 215 | -            function (array $match): string { | |
| 216 | -                if (!isset($this->svgFileArr[$match['href']])) { // check usage | |
| 217 | - return $match[0]; | |
| 218 | - } | |
| 219 | - | |
| 220 | -                return sprintf('<use%s href="#%s"/>', $match['pre'].$match['post'], $this->convertFilePath($match['href'])); | |
| 221 | - }, | |
| 222 | - '<svg xmlns="http://www.w3.org/2000/svg">' | |
| 223 | -            // ."\n<style>\n".implode("\n", $this->styl)."\n</style>" | |
| 224 | -            // ."\n<defs>\n".implode("\n", $this->defs)."\n</defs>" | |
| 225 | -            ."\n<symbol ".implode("</symbol>\n<symbol ", $this->svgs)."</symbol>\n" | |
| 226 | - .'</svg>' | |
| 227 | - ); | |
| 228 | - | |
| 229 | - // unset($this->styl); // save MEM | |
| 230 | - // unset($this->defs); // save MEM | |
| 231 | - unset($this->svgs); // save MEM | |
| 232 | - | |
| 233 | -        if ($GLOBALS['TSFE']->config['config']['sourceopt.']['formatHtml'] ?? false) { | |
| 234 | -            $svg = preg_replace('/(?<=>)\s+(?=<)/', '', $svg); // remove emptiness | |
| 235 | -            $svg = preg_replace('/[\t\v]/', ' ', $svg); // prepare shrinkage | |
| 236 | -            $svg = preg_replace('/\s{2,}/', ' ', $svg); // shrink whitespace | |
| 237 | - } | |
| 238 | - | |
| 239 | -        $svg = preg_replace('/<([a-z]+)\s*(\/|>\s*<\/\1)>\s*|\s+(?=\/>)/i', '', $svg); // remove emtpy TAGs & shorten endings | |
| 240 | -        $svg = preg_replace('/<((circle|ellipse|line|path|polygon|polyline|rect|stop|use)\s[^>]+?)\s*>\s*<\/\2>/', '<$1/>', $svg); // shorten/minify TAG syntax | |
| 241 | - | |
| 242 | -        if (!is_dir($this->sitePath.$this->outputDir)) { | |
| 243 | - GeneralUtility::mkdir_deep($this->sitePath.$this->outputDir); | |
| 244 | - } | |
| 245 | - | |
| 246 | -        $this->spritePath = $this->outputDir.hash('sha1', serialize($this->svgFileArr)).'.svg'; | |
| 247 | -        if (false === file_put_contents($this->sitePath.$this->spritePath, $svg)) { | |
| 248 | - return false; | |
| 249 | - } | |
| 250 | - | |
| 251 | -        $this->svgCache->set('spritePath', $this->spritePath); | |
| 252 | -        $this->svgCache->set('svgFileArr', $this->svgFileArr); | |
| 253 | - | |
| 254 | - return true; | |
| 255 | - } | |
| 16 | + /** | |
| 17 | + * SVG-Sprite relativ storage directory. | |
| 18 | + * | |
| 19 | + * @var string | |
| 20 | + */ | |
| 21 | + protected $outputDir = '/typo3temp/assets/svg/'; | |
| 22 | + | |
| 23 | + /** | |
| 24 | + * TYPO3 absolute path to public web. | |
| 25 | + * | |
| 26 | + * @var string | |
| 27 | + */ | |
| 28 | + protected $sitePath = ''; | |
| 29 | + | |
| 30 | + /** | |
| 31 | + * Final TYPO3 Frontend-Cache object. | |
| 32 | + * | |
| 33 | + * @var \TYPO3\CMS\Core\Cache\Frontend\VariableFrontend | |
| 34 | + */ | |
| 35 | + protected $svgCache; | |
| 36 | + | |
| 37 | + /** | |
| 38 | + * Cached SVG-Sprite relativ file path. | |
| 39 | + * | |
| 40 | + * @var string | |
| 41 | + */ | |
| 42 | + protected $spritePath = ''; | |
| 43 | + | |
| 44 | + /** | |
| 45 | + * Cached used SVG files (incl. defs). | |
| 46 | + * | |
| 47 | + * @var array | |
| 48 | + */ | |
| 49 | + protected $svgFileArr = []; | |
| 50 | + | |
| 51 | + /** | |
| 52 | + * Final SVG-Sprite Vectors. | |
| 53 | + * | |
| 54 | + * @var array | |
| 55 | + */ | |
| 56 | + protected $svgs = []; | |
| 57 | + | |
| 58 | + /** | |
| 59 | + * Final SVG-Sprite Styles. | |
| 60 | + * | |
| 61 | + * @var array | |
| 62 | + */ | |
| 63 | + protected $styl = []; // ToFix ; https://stackoverflow.com/questions/39583880/external-svg-fails-to-apply-internal-css | |
| 64 | + | |
| 65 | + /** | |
| 66 | + * Final SVG-Sprite Objects. | |
| 67 | + * | |
| 68 | + * @var array | |
| 69 | + */ | |
| 70 | + protected $defs = []; // ToFix ; https://bugs.chromium.org/p/chromium/issues/detail?id=751733#c14 | |
| 71 | + | |
| 72 | + public function __construct() | |
| 73 | +	{ | |
| 74 | + $this->sitePath = \TYPO3\CMS\Core\Core\Environment::getPublicPath(); // [^/]$ | |
| 75 | +		$this->svgCache = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Cache\CacheManager::class)->getCache('svgstore'); | |
| 76 | + | |
| 77 | +		$this->spritePath = $this->svgCache->get('spritePath') ?: ''; | |
| 78 | +		$this->svgFileArr = $this->svgCache->get('svgFileArr') ?: []; | |
| 79 | + | |
| 80 | +		if (empty($this->spritePath) && !$this->populateCache()) { | |
| 81 | +			throw new \Exception('could not write file: '.$this->sitePath.$this->spritePath); | |
| 82 | + } | |
| 83 | + | |
| 84 | +		if (!file_exists($this->sitePath.$this->spritePath)) { | |
| 85 | +			throw new \Exception('file does not exists: '.$this->sitePath.$this->spritePath); | |
| 86 | + } | |
| 87 | + } | |
| 88 | + | |
| 89 | + public function process(string $html): string | |
| 90 | +	{ | |
| 91 | +		if ($GLOBALS['TSFE']->config['config']['disableAllHeaderCode'] ?? false) { | |
| 92 | + $dom = ['head' => '', 'body' => $html]; | |
| 93 | +		} elseif (!preg_match('/(?<head>.+?<\/head>)(?<body>.+)/s', $html, $dom)) { | |
| 94 | + return $html; | |
| 95 | + } | |
| 96 | + | |
| 97 | + // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#attributes | |
| 98 | +		$dom['body'] = preg_replace_callback('/<img(?<pre>[^>]*)src="(?:https?:)?(?:\/\/[^\/]+?)?(?<src>\/[^"]+\.svg)"(?<post>[^>]*?)[\s\/]*>(?!\s*<\/picture>)/s', function (array $match): string { // ^[/] | |
| 99 | +			if (!isset($this->svgFileArr[$match['src']])) { // check usage | |
| 100 | + return $match[0]; | |
| 101 | + } | |
| 102 | +			$attr = preg_replace('/\s(?:alt|ismap|loading|title|sizes|srcset|usemap|crossorigin|decoding|fetchpriority|referrerpolicy)="[^"]*"/', '', $match['pre'].$match['post']); // cleanup | |
| 103 | + | |
| 104 | +			return sprintf('<svg %s %s><use href="%s#%s"/></svg>', $this->svgFileArr[$match['src']]['attr'], trim($attr), $this->spritePath, $this->convertFilePath($match['src'])); | |
| 105 | + }, $dom['body']); | |
| 106 | + | |
| 107 | + // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/object#attributes | |
| 108 | +		$dom['body'] = preg_replace_callback('/<object(?<pre>[^>]*)data="(?<data>\/[^"]+\.svg)"(?<post>[^>]*?)[\s\/]*>(?:<\/object>)/s', function (array $match): string { // ^[/] | |
| 109 | +			if (!isset($this->svgFileArr[$match['data']])) { // check usage | |
| 110 | + return $match[0]; | |
| 111 | + } | |
| 112 | +			$attr = preg_replace('/\s(?:form|name|type|usemap)="[^"]*"/', '', $match['pre'].$match['post']); // cleanup | |
| 113 | + | |
| 114 | +			return sprintf('<svg %s %s><use href="%s#%s"/></svg>', $this->svgFileArr[$match['data']]['attr'], trim($attr), $this->spritePath, $this->convertFilePath($match['data'])); | |
| 115 | + }, $dom['body']); | |
| 116 | + | |
| 117 | + return $dom['head'].$dom['body']; | |
| 118 | + } | |
| 119 | + | |
| 120 | + private function convertFilePath(string $path): string | |
| 121 | +	{ | |
| 122 | +		return preg_replace('/.svg$|[^\w\-]/', '', str_replace('/', '-', ltrim($path, '/'))); // ^[^/] | |
| 123 | + } | |
| 124 | + | |
| 125 | + private function addFileToSpriteArr(string $hash, string $path, array $attr = []): ?array | |
| 126 | +	{ | |
| 127 | +		if (!file_exists($this->sitePath.$path)) { | |
| 128 | + return null; | |
| 129 | + } | |
| 130 | + | |
| 131 | + $svg = file_get_contents($this->sitePath.$path); | |
| 132 | + | |
| 133 | +		if (preg_match('/(?:;base64|i:a?i?pgf)/', $svg)) { // noop! | |
| 134 | + return null; | |
| 135 | + } | |
| 136 | + | |
| 137 | +		if (preg_match('/<(?:style|defs)|url\(/', $svg)) { | |
| 138 | + return null; // check links @ __construct | |
| 139 | + } | |
| 140 | + | |
| 141 | + // https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/xlink:href | |
| 142 | +		$svg = preg_replace('/^.*?<svg|\s*(<\/svg>)(?!.*\1).*$|xlink:|\s(?:(?:version|xmlns)|(?:[a-z\-]+\:[a-z\-]+))="[^"]*"/s', '', $svg); // cleanup | |
| 143 | + | |
| 144 | +		// $svg = preg_replace('/(?<=(?:id|class)=")/', $hash.'__', $svg); // extend  IDs | |
| 145 | +		// $svg = preg_replace('/(?<=href="|url\()#/', $hash.'__', $svg); // recover IDs | |
| 146 | + | |
| 147 | +		// $svg = preg_replace_callback('/<style[^>]*>(?<styl>.+?)<\/style>|<defs[^>]*>(?<defs>.+?)<\/defs>/s', function(array $match) use($hash): string { | |
| 148 | + // | |
| 149 | + // if(isset($match['styl'])) | |
| 150 | +		//    { | |
| 151 | +		//        $this->styl[] = preg_replace('/\s*(\.|#){1}(.+?)\s*\{/', '$1'.$hash.'__$2{', $match['styl']); // patch CSS # https://mathiasbynens.be/notes/css-escapes | |
| 152 | + // } | |
| 153 | + // if(isset($match['defs'])) | |
| 154 | +		//    { | |
| 155 | + // $this->defs[] = trim($match['defs']); | |
| 156 | + // } | |
| 157 | + // return ''; | |
| 158 | + // }, $svg); | |
| 159 | + | |
| 160 | + // https://developer.mozilla.org/en-US/docs/Web/SVG/Element/svg#attributes | |
| 161 | +		$svg = preg_replace_callback('/([^>]*)\s*(?=>)/s', function (array $match) use (&$attr): string { | |
| 162 | +			if (false === preg_match_all('/(?!\s)(?<attr>[\w\-]+)="\s*(?<value>[^"]+)\s*"/', $match[1], $matches)) { | |
| 163 | + return $match[0]; | |
| 164 | + } | |
| 165 | +			foreach ($matches['attr'] as $index => $attribute) { | |
| 166 | +				switch ($attribute) { | |
| 167 | + case 'id': | |
| 168 | + case 'width': | |
| 169 | + case 'height': | |
| 170 | + unset($matches[0][$index]); | |
| 171 | + break; | |
| 172 | + | |
| 173 | + case 'viewBox': | |
| 174 | +						if (false !== preg_match('/\S+\s\S+\s\+?(?<width>[\d\.]+)\s\+?(?<height>[\d\.]+)/', $matches['value'][$index], $match)) { | |
| 175 | +							$attr[] = sprintf('%s="0 0 %s %s"', $attribute, $match['width'], $match['height']); // save! | |
| 176 | + } | |
| 177 | + } | |
| 178 | + } | |
| 179 | + | |
| 180 | +			return implode(' ', $matches[0]); | |
| 181 | + }, $svg, 1); | |
| 182 | + | |
| 183 | +		if (empty($attr)) { | |
| 184 | + return null; | |
| 185 | + } | |
| 186 | + | |
| 187 | +		$this->svgs[] = sprintf('id="%s" %s', $this->convertFilePath($path), $svg); // prepend ID | |
| 188 | + | |
| 189 | +		return ['attr' => implode(' ', $attr), 'hash' => $hash]; | |
| 190 | + } | |
| 191 | + | |
| 192 | + private function populateCache(): bool | |
| 193 | +	{ | |
| 194 | + $storageArr = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Resource\StorageRepository::class)->findAll(); | |
| 195 | +		foreach ($storageArr as $storage) { | |
| 196 | +			if ('relative' == $storage->getConfiguration()['pathType']) { | |
| 197 | + $storageArr[$storage->getUid()] = rtrim($storage->getConfiguration()['basePath'], '/'); // [^/]$ | |
| 198 | + } | |
| 199 | + } | |
| 200 | + unset($storageArr[0]); // keep! | |
| 201 | + | |
| 202 | + $fileArr = GeneralUtility::makeInstance(\HTML\Sourceopt\Resource\SvgFileRepository::class)->findAllByStorageUids(array_keys($storageArr)); | |
| 203 | +		foreach ($fileArr as $file) { | |
| 204 | + $file['path'] = '/'.$storageArr[$file['storage']].$file['identifier']; // ^[/] | |
| 205 | + $file['defs'] = $this->addFileToSpriteArr($file['sha1'], $file['path']); | |
| 206 | + | |
| 207 | +			if (null !== $file['defs']) { | |
| 208 | + $this->svgFileArr[$file['path']] = $file['defs']; | |
| 209 | + } | |
| 210 | + } | |
| 211 | + unset($storageArr, $storage, $fileArr, $file); // save MEM | |
| 212 | + | |
| 213 | + $svg = preg_replace_callback( | |
| 214 | + '/<use(?<pre>.*?)(?:xlink:)?href="(?<href>\/.+?\.svg)(?:#[^"]*?)?"(?<post>.*?)[\s\/]*>(?:<\/use>)?/s', | |
| 215 | +			function (array $match): string { | |
| 216 | +				if (!isset($this->svgFileArr[$match['href']])) { // check usage | |
| 217 | + return $match[0]; | |
| 218 | + } | |
| 219 | + | |
| 220 | +				return sprintf('<use%s href="#%s"/>', $match['pre'].$match['post'], $this->convertFilePath($match['href'])); | |
| 221 | + }, | |
| 222 | + '<svg xmlns="http://www.w3.org/2000/svg">' | |
| 223 | +			// ."\n<style>\n".implode("\n", $this->styl)."\n</style>" | |
| 224 | +			// ."\n<defs>\n".implode("\n", $this->defs)."\n</defs>" | |
| 225 | +			."\n<symbol ".implode("</symbol>\n<symbol ", $this->svgs)."</symbol>\n" | |
| 226 | + .'</svg>' | |
| 227 | + ); | |
| 228 | + | |
| 229 | + // unset($this->styl); // save MEM | |
| 230 | + // unset($this->defs); // save MEM | |
| 231 | + unset($this->svgs); // save MEM | |
| 232 | + | |
| 233 | +		if ($GLOBALS['TSFE']->config['config']['sourceopt.']['formatHtml'] ?? false) { | |
| 234 | +			$svg = preg_replace('/(?<=>)\s+(?=<)/', '', $svg); // remove emptiness | |
| 235 | +			$svg = preg_replace('/[\t\v]/', ' ', $svg); // prepare shrinkage | |
| 236 | +			$svg = preg_replace('/\s{2,}/', ' ', $svg); // shrink whitespace | |
| 237 | + } | |
| 238 | + | |
| 239 | +		$svg = preg_replace('/<([a-z]+)\s*(\/|>\s*<\/\1)>\s*|\s+(?=\/>)/i', '', $svg); // remove emtpy TAGs & shorten endings | |
| 240 | +		$svg = preg_replace('/<((circle|ellipse|line|path|polygon|polyline|rect|stop|use)\s[^>]+?)\s*>\s*<\/\2>/', '<$1/>', $svg); // shorten/minify TAG syntax | |
| 241 | + | |
| 242 | +		if (!is_dir($this->sitePath.$this->outputDir)) { | |
| 243 | + GeneralUtility::mkdir_deep($this->sitePath.$this->outputDir); | |
| 244 | + } | |
| 245 | + | |
| 246 | +		$this->spritePath = $this->outputDir.hash('sha1', serialize($this->svgFileArr)).'.svg'; | |
| 247 | +		if (false === file_put_contents($this->sitePath.$this->spritePath, $svg)) { | |
| 248 | + return false; | |
| 249 | + } | |
| 250 | + | |
| 251 | +		$this->svgCache->set('spritePath', $this->spritePath); | |
| 252 | +		$this->svgCache->set('svgFileArr', $this->svgFileArr); | |
| 253 | + | |
| 254 | + return true; | |
| 255 | + } | |
| 256 | 256 | } | 
| @@ -13,43 +13,43 @@ | ||
| 13 | 13 | */ | 
| 14 | 14 | class SvgFileRepository extends \TYPO3\CMS\Core\Resource\FileRepository | 
| 15 | 15 |  { | 
| 16 | - /** | |
| 17 | - * Retrieves all used SVGs within given storage-array. | |
| 18 | - */ | |
| 19 | - public function findAllByStorageUids(array $storageUids): array | |
| 20 | -    { | |
| 21 | - return | |
| 22 | - ($queryBuilder = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Database\ConnectionPool::class)->getQueryBuilderForTable($this->table)) | |
| 23 | -                ->select('sys_file.storage', 'sys_file.identifier', 'sys_file.sha1') | |
| 24 | - ->from($this->table) | |
| 25 | - ->innerJoin( | |
| 26 | - 'sys_file', | |
| 27 | - 'sys_file_reference', | |
| 28 | - 'sys_file_reference', | |
| 29 | - $queryBuilder->expr()->eq( | |
| 30 | - 'sys_file_reference.uid_local', | |
| 31 | -                        $queryBuilder->quoteIdentifier('sys_file.uid') | |
| 32 | - ) | |
| 33 | - ) | |
| 34 | - ->where( | |
| 35 | - $queryBuilder->expr()->in( | |
| 36 | - 'sys_file.storage', | |
| 37 | - $queryBuilder->createNamedParameter($storageUids, \Doctrine\DBAL\Connection::PARAM_INT_ARRAY) | |
| 38 | - ), | |
| 39 | - $queryBuilder->expr()->lt( | |
| 40 | - 'sys_file.size', | |
| 41 | - $queryBuilder->createNamedParameter((int) $GLOBALS['TSFE']->config['config']['svgstore.']['fileSize'] ?? null, \PDO::PARAM_INT) | |
| 42 | - ), | |
| 43 | - $queryBuilder->expr()->eq( | |
| 44 | - 'sys_file.mime_type', | |
| 45 | -                        $queryBuilder->createNamedParameter('image/svg+xml', \PDO::PARAM_STR) | |
| 46 | - ) | |
| 47 | - ) | |
| 48 | -                ->groupBy('sys_file.uid', 'sys_file.storage', 'sys_file.identifier', 'sys_file.sha1') | |
| 49 | -                ->orderBy('sys_file.storage') | |
| 50 | -                ->addOrderBy('sys_file.identifier') | |
| 51 | - ->execute() | |
| 52 | - ->fetchAll() // TODO; use stdClass | |
| 53 | - ; | |
| 54 | - } | |
| 16 | + /** | |
| 17 | + * Retrieves all used SVGs within given storage-array. | |
| 18 | + */ | |
| 19 | + public function findAllByStorageUids(array $storageUids): array | |
| 20 | +	{ | |
| 21 | + return | |
| 22 | + ($queryBuilder = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Database\ConnectionPool::class)->getQueryBuilderForTable($this->table)) | |
| 23 | +				->select('sys_file.storage', 'sys_file.identifier', 'sys_file.sha1') | |
| 24 | + ->from($this->table) | |
| 25 | + ->innerJoin( | |
| 26 | + 'sys_file', | |
| 27 | + 'sys_file_reference', | |
| 28 | + 'sys_file_reference', | |
| 29 | + $queryBuilder->expr()->eq( | |
| 30 | + 'sys_file_reference.uid_local', | |
| 31 | +						$queryBuilder->quoteIdentifier('sys_file.uid') | |
| 32 | + ) | |
| 33 | + ) | |
| 34 | + ->where( | |
| 35 | + $queryBuilder->expr()->in( | |
| 36 | + 'sys_file.storage', | |
| 37 | + $queryBuilder->createNamedParameter($storageUids, \Doctrine\DBAL\Connection::PARAM_INT_ARRAY) | |
| 38 | + ), | |
| 39 | + $queryBuilder->expr()->lt( | |
| 40 | + 'sys_file.size', | |
| 41 | + $queryBuilder->createNamedParameter((int) $GLOBALS['TSFE']->config['config']['svgstore.']['fileSize'] ?? null, \PDO::PARAM_INT) | |
| 42 | + ), | |
| 43 | + $queryBuilder->expr()->eq( | |
| 44 | + 'sys_file.mime_type', | |
| 45 | +						$queryBuilder->createNamedParameter('image/svg+xml', \PDO::PARAM_STR) | |
| 46 | + ) | |
| 47 | + ) | |
| 48 | +				->groupBy('sys_file.uid', 'sys_file.storage', 'sys_file.identifier', 'sys_file.sha1') | |
| 49 | +				->orderBy('sys_file.storage') | |
| 50 | +				->addOrderBy('sys_file.identifier') | |
| 51 | + ->execute() | |
| 52 | + ->fetchAll() // TODO; use stdClass | |
| 53 | + ; | |
| 54 | + } | |
| 55 | 55 | } | 
| @@ -14,16 +14,16 @@ | ||
| 14 | 14 | */ | 
| 15 | 15 | class RemoveGenerator implements ManipulationInterface | 
| 16 | 16 |  { | 
| 17 | - /** | |
| 18 | - * @param string $html The original HTML | |
| 19 | - * @param array $configuration Configuration | |
| 20 | - * | |
| 21 | - * @return string the manipulated HTML | |
| 22 | - */ | |
| 23 | - public function manipulate(string $html, array $configuration = []): string | |
| 24 | -    { | |
| 25 | - $regex = '<meta name=["\']?generator["\']? [^>]+>'; | |
| 17 | + /** | |
| 18 | + * @param string $html The original HTML | |
| 19 | + * @param array $configuration Configuration | |
| 20 | + * | |
| 21 | + * @return string the manipulated HTML | |
| 22 | + */ | |
| 23 | + public function manipulate(string $html, array $configuration = []): string | |
| 24 | +	{ | |
| 25 | + $regex = '<meta name=["\']?generator["\']? [^>]+>'; | |
| 26 | 26 | |
| 27 | -        return preg_replace('/'.$regex.'/is', '', $html); | |
| 28 | - } | |
| 27 | +		return preg_replace('/'.$regex.'/is', '', $html); | |
| 28 | + } | |
| 29 | 29 | } | 
| @@ -14,11 +14,11 @@ | ||
| 14 | 14 | */ | 
| 15 | 15 | interface ManipulationInterface | 
| 16 | 16 |  { | 
| 17 | - /** | |
| 18 | - * @param string $html The original HTML | |
| 19 | - * @param array $configuration Configuration | |
| 20 | - * | |
| 21 | - * @return string the manipulated HTML | |
| 22 | - */ | |
| 23 | - public function manipulate(string $html, array $configuration = []): string; | |
| 17 | + /** | |
| 18 | + * @param string $html The original HTML | |
| 19 | + * @param array $configuration Configuration | |
| 20 | + * | |
| 21 | + * @return string the manipulated HTML | |
| 22 | + */ | |
| 23 | + public function manipulate(string $html, array $configuration = []): string; | |
| 24 | 24 | } | 
| @@ -14,67 +14,67 @@ | ||
| 14 | 14 | */ | 
| 15 | 15 | class RemoveComments implements ManipulationInterface | 
| 16 | 16 |  { | 
| 17 | - /** | |
| 18 | - * Patterns for white-listing comments inside content. | |
| 19 | - * | |
| 20 | - * @var array | |
| 21 | - */ | |
| 22 | - protected $whiteListCommentsPatterns = []; | |
| 17 | + /** | |
| 18 | + * Patterns for white-listing comments inside content. | |
| 19 | + * | |
| 20 | + * @var array | |
| 21 | + */ | |
| 22 | + protected $whiteListCommentsPatterns = []; | |
| 23 | 23 | |
| 24 | - /** | |
| 25 | - * @param string $html The original HTML | |
| 26 | - * @param array $configuration Configuration | |
| 27 | - * | |
| 28 | - * @return string the manipulated HTML | |
| 29 | - */ | |
| 30 | - public function manipulate(string $html, array $configuration = []): string | |
| 31 | -    { | |
| 32 | -        if (isset($configuration['keep.'])) { | |
| 33 | - $this->whiteListCommentsPatterns = $configuration['keep.']; | |
| 34 | - } | |
| 24 | + /** | |
| 25 | + * @param string $html The original HTML | |
| 26 | + * @param array $configuration Configuration | |
| 27 | + * | |
| 28 | + * @return string the manipulated HTML | |
| 29 | + */ | |
| 30 | + public function manipulate(string $html, array $configuration = []): string | |
| 31 | +	{ | |
| 32 | +		if (isset($configuration['keep.'])) { | |
| 33 | + $this->whiteListCommentsPatterns = $configuration['keep.']; | |
| 34 | + } | |
| 35 | 35 | |
| 36 | - // match all comments, styles and scripts | |
| 37 | - $matches = []; | |
| 38 | - preg_match_all( | |
| 39 | - '/(?s)((<!--.*?-->)|(<[ \n\r]*style[^>]*>.*?<[ \n\r]*\/style[^>]*>)|(<[ \n\r]*script[^>]*>.*?<[ \n\r]*\/script[^>]*>))/im', | |
| 40 | - $html, | |
| 41 | - $matches | |
| 42 | - ); | |
| 43 | -        foreach ($matches[0] as $tag) { | |
| 44 | -            if (false === $this->keepComment($tag)) { | |
| 45 | - $html = str_replace($tag, '', $html); | |
| 46 | - } | |
| 47 | - } | |
| 36 | + // match all comments, styles and scripts | |
| 37 | + $matches = []; | |
| 38 | + preg_match_all( | |
| 39 | + '/(?s)((<!--.*?-->)|(<[ \n\r]*style[^>]*>.*?<[ \n\r]*\/style[^>]*>)|(<[ \n\r]*script[^>]*>.*?<[ \n\r]*\/script[^>]*>))/im', | |
| 40 | + $html, | |
| 41 | + $matches | |
| 42 | + ); | |
| 43 | +		foreach ($matches[0] as $tag) { | |
| 44 | +			if (false === $this->keepComment($tag)) { | |
| 45 | + $html = str_replace($tag, '', $html); | |
| 46 | + } | |
| 47 | + } | |
| 48 | 48 | |
| 49 | - return $html; | |
| 50 | - } | |
| 49 | + return $html; | |
| 50 | + } | |
| 51 | 51 | |
| 52 | - /** | |
| 53 | - * Check if a comment is defined to be kept in a pattern whiteListOfComments. | |
| 54 | - * | |
| 55 | - * @param string $commentHtml | |
| 56 | - * | |
| 57 | - * @return bool | |
| 58 | - */ | |
| 59 | - protected function keepComment($commentHtml) | |
| 60 | -    { | |
| 61 | - // if not even a comment, skip this | |
| 62 | -        if (!preg_match('/^\<\!\-\-(.*?)\-\-\>$/usi', $commentHtml)) { | |
| 63 | - return true; | |
| 64 | - } | |
| 52 | + /** | |
| 53 | + * Check if a comment is defined to be kept in a pattern whiteListOfComments. | |
| 54 | + * | |
| 55 | + * @param string $commentHtml | |
| 56 | + * | |
| 57 | + * @return bool | |
| 58 | + */ | |
| 59 | + protected function keepComment($commentHtml) | |
| 60 | +	{ | |
| 61 | + // if not even a comment, skip this | |
| 62 | +		if (!preg_match('/^\<\!\-\-(.*?)\-\-\>$/usi', $commentHtml)) { | |
| 63 | + return true; | |
| 64 | + } | |
| 65 | 65 | |
| 66 | - // if not defined in white list | |
| 67 | -        if (!empty($this->whiteListCommentsPatterns)) { | |
| 68 | -            $commentHtml = str_replace('<!--', '', $commentHtml); | |
| 69 | -            $commentHtml = str_replace('-->', '', $commentHtml); | |
| 70 | - $commentHtml = trim($commentHtml); | |
| 71 | -            foreach ($this->whiteListCommentsPatterns as $pattern) { | |
| 72 | -                if (!empty($pattern) && preg_match($pattern, $commentHtml)) { | |
| 73 | - return true; | |
| 74 | - } | |
| 75 | - } | |
| 76 | - } | |
| 66 | + // if not defined in white list | |
| 67 | +		if (!empty($this->whiteListCommentsPatterns)) { | |
| 68 | +			$commentHtml = str_replace('<!--', '', $commentHtml); | |
| 69 | +			$commentHtml = str_replace('-->', '', $commentHtml); | |
| 70 | + $commentHtml = trim($commentHtml); | |
| 71 | +			foreach ($this->whiteListCommentsPatterns as $pattern) { | |
| 72 | +				if (!empty($pattern) && preg_match($pattern, $commentHtml)) { | |
| 73 | + return true; | |
| 74 | + } | |
| 75 | + } | |
| 76 | + } | |
| 77 | 77 | |
| 78 | - return false; | |
| 79 | - } | |
| 78 | + return false; | |
| 79 | + } | |
| 80 | 80 | } | 
| @@ -18,28 +18,28 @@ | ||
| 18 | 18 | */ | 
| 19 | 19 | class SvgStoreMiddleware implements MiddlewareInterface | 
| 20 | 20 |  { | 
| 21 | - /** | |
| 22 | - * Search/Extract/Merge SVGs @ HTML output. | |
| 23 | - */ | |
| 24 | - public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface | |
| 25 | -    { | |
| 26 | - $response = $handler->handle($request); | |
| 21 | + /** | |
| 22 | + * Search/Extract/Merge SVGs @ HTML output. | |
| 23 | + */ | |
| 24 | + public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface | |
| 25 | +	{ | |
| 26 | + $response = $handler->handle($request); | |
| 27 | 27 | |
| 28 | - if (!($response instanceof NullResponse) | |
| 29 | - && $GLOBALS['TSFE'] instanceof TypoScriptFrontendController | |
| 30 | - && ($GLOBALS['TSFE']->config['config']['svgstore.']['enabled'] ?? false) | |
| 31 | -        && 'text/html' == substr($response->getHeaderLine('Content-Type'), 0, 9) | |
| 32 | - && !empty($response->getBody()) | |
| 33 | -        ) { | |
| 34 | - $processedHtml = GeneralUtility::makeInstance(\HTML\Sourceopt\Service\SvgStoreService::class) | |
| 35 | - ->process((string) $response->getBody()) | |
| 36 | - ; | |
| 28 | + if (!($response instanceof NullResponse) | |
| 29 | + && $GLOBALS['TSFE'] instanceof TypoScriptFrontendController | |
| 30 | + && ($GLOBALS['TSFE']->config['config']['svgstore.']['enabled'] ?? false) | |
| 31 | +		&& 'text/html' == substr($response->getHeaderLine('Content-Type'), 0, 9) | |
| 32 | + && !empty($response->getBody()) | |
| 33 | +		) { | |
| 34 | + $processedHtml = GeneralUtility::makeInstance(\HTML\Sourceopt\Service\SvgStoreService::class) | |
| 35 | + ->process((string) $response->getBody()) | |
| 36 | + ; | |
| 37 | 37 | |
| 38 | -            $responseBody = new Stream('php://temp', 'rw'); | |
| 39 | - $responseBody->write($processedHtml); | |
| 40 | - $response = $response->withBody($responseBody); | |
| 41 | - } | |
| 38 | +			$responseBody = new Stream('php://temp', 'rw'); | |
| 39 | + $responseBody->write($processedHtml); | |
| 40 | + $response = $response->withBody($responseBody); | |
| 41 | + } | |
| 42 | 42 | |
| 43 | - return $response; | |
| 44 | - } | |
| 43 | + return $response; | |
| 44 | + } | |
| 45 | 45 | } | 
| @@ -18,32 +18,32 @@ | ||
| 18 | 18 | */ | 
| 19 | 19 | class CleanHtmlMiddleware implements MiddlewareInterface | 
| 20 | 20 |  { | 
| 21 | - /** | |
| 22 | - * Clean the HTML output. | |
| 23 | - */ | |
| 24 | - public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface | |
| 25 | -    { | |
| 26 | - $response = $handler->handle($request); | |
| 21 | + /** | |
| 22 | + * Clean the HTML output. | |
| 23 | + */ | |
| 24 | + public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface | |
| 25 | +	{ | |
| 26 | + $response = $handler->handle($request); | |
| 27 | 27 | |
| 28 | - if (!($response instanceof NullResponse) | |
| 29 | - && $GLOBALS['TSFE'] instanceof TypoScriptFrontendController | |
| 30 | - && ($GLOBALS['TSFE']->config['config']['sourceopt.']['enabled'] ?? false) | |
| 31 | -        && 'text/html' == substr($response->getHeaderLine('Content-Type'), 0, 9) | |
| 32 | - && !empty($response->getBody()) | |
| 33 | -        ) { | |
| 34 | - $processedHtml = GeneralUtility::makeInstance(\HTML\Sourceopt\Service\CleanHtmlService::class) | |
| 35 | - ->clean( | |
| 36 | - (string) $response->getBody(), | |
| 37 | - (array) $GLOBALS['TSFE']->config['config']['sourceopt.'] | |
| 38 | - ) | |
| 39 | - ; | |
| 28 | + if (!($response instanceof NullResponse) | |
| 29 | + && $GLOBALS['TSFE'] instanceof TypoScriptFrontendController | |
| 30 | + && ($GLOBALS['TSFE']->config['config']['sourceopt.']['enabled'] ?? false) | |
| 31 | +		&& 'text/html' == substr($response->getHeaderLine('Content-Type'), 0, 9) | |
| 32 | + && !empty($response->getBody()) | |
| 33 | +		) { | |
| 34 | + $processedHtml = GeneralUtility::makeInstance(\HTML\Sourceopt\Service\CleanHtmlService::class) | |
| 35 | + ->clean( | |
| 36 | + (string) $response->getBody(), | |
| 37 | + (array) $GLOBALS['TSFE']->config['config']['sourceopt.'] | |
| 38 | + ) | |
| 39 | + ; | |
| 40 | 40 | |
| 41 | - // Replace old body with $processedHtml | |
| 42 | -            $responseBody = new Stream('php://temp', 'rw'); | |
| 43 | - $responseBody->write($processedHtml); | |
| 44 | - $response = $response->withBody($responseBody); | |
| 45 | - } | |
| 41 | + // Replace old body with $processedHtml | |
| 42 | +			$responseBody = new Stream('php://temp', 'rw'); | |
| 43 | + $responseBody->write($processedHtml); | |
| 44 | + $response = $response->withBody($responseBody); | |
| 45 | + } | |
| 46 | 46 | |
| 47 | - return $response; | |
| 48 | - } | |
| 47 | + return $response; | |
| 48 | + } | |
| 49 | 49 | } | 
| @@ -19,29 +19,29 @@ | ||
| 19 | 19 | */ | 
| 20 | 20 | class RegExRepMiddleware implements MiddlewareInterface | 
| 21 | 21 |  { | 
| 22 | - /** | |
| 23 | - * RegEx search & replace @ HTML output. | |
| 24 | - */ | |
| 25 | - public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface | |
| 26 | -    { | |
| 27 | - $response = $handler->handle($request); | |
| 22 | + /** | |
| 23 | + * RegEx search & replace @ HTML output. | |
| 24 | + */ | |
| 25 | + public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface | |
| 26 | +	{ | |
| 27 | + $response = $handler->handle($request); | |
| 28 | 28 | |
| 29 | - if (!($response instanceof NullResponse) | |
| 30 | - && $GLOBALS['TSFE'] instanceof TypoScriptFrontendController | |
| 31 | - && $GLOBALS['TSFE']->cObj instanceof ContentObjectRenderer | |
| 32 | - && isset($GLOBALS['TSFE']->config['config']['replacer.']) | |
| 33 | -        && 'text/html' == substr($response->getHeaderLine('Content-Type'), 0, 9) | |
| 34 | - && !empty($response->getBody()) | |
| 35 | -        ) { | |
| 36 | - $processedHtml = GeneralUtility::makeInstance(\HTML\Sourceopt\Service\RegExRepService::class) | |
| 37 | - ->process((string) $response->getBody()) | |
| 38 | - ; | |
| 29 | + if (!($response instanceof NullResponse) | |
| 30 | + && $GLOBALS['TSFE'] instanceof TypoScriptFrontendController | |
| 31 | + && $GLOBALS['TSFE']->cObj instanceof ContentObjectRenderer | |
| 32 | + && isset($GLOBALS['TSFE']->config['config']['replacer.']) | |
| 33 | +		&& 'text/html' == substr($response->getHeaderLine('Content-Type'), 0, 9) | |
| 34 | + && !empty($response->getBody()) | |
| 35 | +		) { | |
| 36 | + $processedHtml = GeneralUtility::makeInstance(\HTML\Sourceopt\Service\RegExRepService::class) | |
| 37 | + ->process((string) $response->getBody()) | |
| 38 | + ; | |
| 39 | 39 | |
| 40 | -            $responseBody = new Stream('php://temp', 'rw'); | |
| 41 | - $responseBody->write($processedHtml); | |
| 42 | - $response = $response->withBody($responseBody); | |
| 43 | - } | |
| 40 | +			$responseBody = new Stream('php://temp', 'rw'); | |
| 41 | + $responseBody->write($processedHtml); | |
| 42 | + $response = $response->withBody($responseBody); | |
| 43 | + } | |
| 44 | 44 | |
| 45 | - return $response; | |
| 46 | - } | |
| 45 | + return $response; | |
| 46 | + } | |
| 47 | 47 | } |