1 |
2
|
Manuela
|
<?php
|
2 |
|
|
/**
|
3 |
|
|
* OutputFilter 'CssToHead'
|
4 |
|
|
* @copyright Manuela v.d.Decken <manuela@isteam.de>
|
5 |
|
|
* @author Manuela v.d.Decken <manuela@isteam.de>
|
6 |
|
|
* @version 161223.3
|
7 |
|
|
* @param string $content
|
8 |
|
|
* @return string
|
9 |
|
|
* @description step1) moves all css definitions from <body> to bottom of the <head> section
|
10 |
|
|
* step2) do not move definitions which are already in <head>
|
11 |
|
|
* step3) delete all css from <body>
|
12 |
|
|
*/
|
13 |
|
|
function doFilterCssToHead($sContent) {
|
14 |
|
|
$aFilterSettings = getOutputFilterSettings();
|
15 |
|
|
$key = \preg_replace('=^.*?filter([^\.\/\\\\]+)(\.[^\.]+)?$=is', '\1', __FILE__);
|
16 |
|
|
if ($aFilterSettings[$key]) {}
|
17 |
|
|
$aMatches = [];
|
18 |
|
|
$sPattern = '/^(.*<head[^>]*>)(.*)(<\/head>.*<body[^>]*>)(.*)(<\/body>.*)$/siU';
|
19 |
|
|
// 1 = .*<head..>
|
20 |
|
|
// 2 = content of head
|
21 |
|
|
// 3 = </head> * <body..>
|
22 |
|
|
// 4 = content of body
|
23 |
|
|
// 5 = </body>... end of document
|
24 |
|
|
if (\preg_match($sPattern, $sContent, $aDocumentParts)) {
|
25 |
|
|
unset($aDocumentParts[0]);
|
26 |
|
|
$sPattern = '/(\<link[^>]*?"(text\/css|stylesheet)"[^>]*?\/?\>)|'
|
27 |
|
|
. '(\<style[^>]*?"text\/css"[^>]*?\>.*?\<\/style\>)|'
|
28 |
|
|
. '(\<style[^>]*?\>.*?\<\/style\>)/si';
|
29 |
|
|
// search for pattern inside the <body>
|
30 |
|
|
if (\preg_match_all($sPattern, $aDocumentParts[4], $aMatches)) {
|
31 |
|
|
// remove duplicates from the matches and save result
|
32 |
|
|
$aBodyMatches = $aMatches = \array_unique($aMatches[0]);
|
33 |
|
|
// set elements to 'false' which already are in <head>
|
34 |
|
|
\array_walk(
|
35 |
|
|
$aMatches,
|
36 |
|
|
function(&$value, $key) use (&$aDocumentParts) {
|
37 |
|
|
if (\preg_match('/'.preg_quote($value, '/').'/siu', $aDocumentParts[2])) {
|
38 |
|
|
$value = false;
|
39 |
|
|
}
|
40 |
|
|
}
|
41 |
|
|
);
|
42 |
|
|
// remove 'false' matches
|
43 |
|
|
$aMatches = \array_filter($aMatches);
|
44 |
|
|
if(\sizeof($aMatches) > 0) {
|
45 |
|
|
// now attach all matches found in <body> to the <head>
|
46 |
|
|
$aDocumentParts[2] .= "\n".\implode("\n", $aMatches)."\n";
|
47 |
|
|
// remove the matches from <body>
|
48 |
|
|
$aDocumentParts[4] = \str_replace($aBodyMatches, '', $aDocumentParts[4]);
|
49 |
|
|
}
|
50 |
|
|
//at least rebuild the document
|
51 |
|
|
$sContent = \implode("\n", $aDocumentParts);
|
52 |
|
|
}
|
53 |
|
|
} else {
|
54 |
|
|
throw new \Exception('malformed document created');
|
55 |
|
|
}
|
56 |
|
|
|
57 |
|
|
return $sContent;
|
58 |
|
|
}
|