xref: /dokuwiki/lib/exe/css.php (revision e44b94a4bd0679ff22e14add34b60590fe7077d3)
178a6aeb1SAndreas Gohr<?php
2d4f83172SAndreas Gohr
378a6aeb1SAndreas Gohr/**
478a6aeb1SAndreas Gohr * DokuWiki StyleSheet creator
578a6aeb1SAndreas Gohr *
678a6aeb1SAndreas Gohr * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
778a6aeb1SAndreas Gohr * @author     Andreas Gohr <andi@splitbrain.org>
878a6aeb1SAndreas Gohr */
95a5ec053SGerrit Uitslag
10cc47c50fSsplitbrainuse LesserPHP\Lessc;
11e3c3abf1SAndreas Gohruse dokuwiki\StyleUtils;
120db5771eSMichael Großeuse dokuwiki\Cache\Cache;
13e1d9dcc8SAndreas Gohruse dokuwiki\Extension\Event;
140db5771eSMichael Große
15e1d9dcc8SAndreas Gohrif (!defined('DOKU_INC')) define('DOKU_INC', __DIR__ . '/../../');
161c2d1019SAndreas Gohrif (!defined('NOSESSION')) define('NOSESSION', true); // we do not use a session or authentication here (better caching)
1798bda4fdSAndreas Gohrif (!defined('DOKU_DISABLE_GZIP_OUTPUT')) define('DOKU_DISABLE_GZIP_OUTPUT', 1); // we gzip ourself here
186c47a78cSAnika Henkeif (!defined('NL')) define('NL', "\n");
1978a6aeb1SAndreas Gohrrequire_once(DOKU_INC . 'inc/init.php');
2078a6aeb1SAndreas Gohr
2178a6aeb1SAndreas Gohr// Main (don't run when UNIT test)
2278a6aeb1SAndreas Gohrif (!defined('SIMPLE_TEST')) {
2378a6aeb1SAndreas Gohr    header('Content-Type: text/css; charset=utf-8');
2478a6aeb1SAndreas Gohr    css_out();
2578a6aeb1SAndreas Gohr}
2678a6aeb1SAndreas Gohr
2778a6aeb1SAndreas Gohr
2878a6aeb1SAndreas Gohr// ---------------------- functions ------------------------------
2978a6aeb1SAndreas Gohr
3078a6aeb1SAndreas Gohr/**
3178a6aeb1SAndreas Gohr * Output all needed Styles
3278a6aeb1SAndreas Gohr *
3378a6aeb1SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
3478a6aeb1SAndreas Gohr */
35d868eb89SAndreas Gohrfunction css_out()
36d868eb89SAndreas Gohr{
3778a6aeb1SAndreas Gohr    global $conf;
3878a6aeb1SAndreas Gohr    global $lang;
3909edb711SAndreas Gohr    global $config_cascade;
40bfd0f597STom N Harris    global $INPUT;
4109edb711SAndreas Gohr
42de4634ecSGerry Weißbach    if ($INPUT->str('s') == 'feed') {
43e3c3abf1SAndreas Gohr        $mediatypes = ['feed'];
44de4634ecSGerry Weißbach        $type = 'feed';
45de4634ecSGerry Weißbach    } else {
46e3c3abf1SAndreas Gohr        $mediatypes = ['screen', 'all', 'print', 'speech'];
47de4634ecSGerry Weißbach        $type = '';
48de4634ecSGerry Weißbach    }
49de4634ecSGerry Weißbach
5020a2375aSAndreas Gohr    // decide from where to get the template
5120a2375aSAndreas Gohr    $tpl = trim(preg_replace('/[^\w-]+/', '', $INPUT->str('t')));
525a5ec053SGerrit Uitslag    if (!$tpl) {
535a5ec053SGerrit Uitslag        $tpl = $conf['template'];
545a5ec053SGerrit Uitslag    }
5520a2375aSAndreas Gohr
5614cd40ecSChang Zhao    // load style.ini
57e3c3abf1SAndreas Gohr    $styleUtil = new StyleUtils($tpl, $INPUT->bool('preview'));
584593dbd2SAnna Dabrowska    $styleini = $styleUtil->cssStyleini();
5920a2375aSAndreas Gohr
60afb2c082SAndreas Gohr    // cache influencers
61259571aaSMichal Koutný    $tplinc = tpl_incdir($tpl);
62afb2c082SAndreas Gohr    $cache_files = getConfigFiles('main');
63afb2c082SAndreas Gohr    $cache_files[] = $tplinc . 'style.ini';
64afb2c082SAndreas Gohr    $cache_files[] = DOKU_CONF . "tpl/$tpl/style.ini";
65afb2c082SAndreas Gohr    $cache_files[] = __FILE__;
665a5ec053SGerrit Uitslag    if ($INPUT->bool('preview')) {
675a5ec053SGerrit Uitslag        $cache_files[] = $conf['cachedir'] . '/preview.ini';
685a5ec053SGerrit Uitslag    }
69afb2c082SAndreas Gohr
7078a6aeb1SAndreas Gohr    // Array of needed files and their web locations, the latter ones
7178a6aeb1SAndreas Gohr    // are needed to fix relative paths in the stylesheets
72e3c3abf1SAndreas Gohr    $media_files = [];
7314977bd2SMichael Hamann    foreach ($mediatypes as $mediatype) {
74e3c3abf1SAndreas Gohr        $files = [];
753e32b194SGerry Weißbach
76318cd03eSAnika Henke        // load core styles
77ef36714bSGerry Weißbach        $files[DOKU_INC . 'lib/styles/' . $mediatype . '.css'] = DOKU_BASE . 'lib/styles/';
78af4684acSAndreas Gohr
7943576758SAndreas Gohr        // load jQuery-UI theme
806c47a78cSAnika Henke        if ($mediatype == 'screen') {
8164159a61SAndreas Gohr            $files[DOKU_INC . 'lib/scripts/jquery/jquery-ui-theme/smoothness.css'] =
8264159a61SAndreas Gohr                DOKU_BASE . 'lib/scripts/jquery/jquery-ui-theme/';
836c47a78cSAnika Henke        }
84318cd03eSAnika Henke        // load plugin styles
85ef36714bSGerry Weißbach        $files = array_merge($files, css_pluginstyles($mediatype));
86318cd03eSAnika Henke        // load template styles
87afb2c082SAndreas Gohr        if (isset($styleini['stylesheets'][$mediatype])) {
88ef36714bSGerry Weißbach            $files = array_merge($files, $styleini['stylesheets'][$mediatype]);
8909edb711SAndreas Gohr        }
90318cd03eSAnika Henke        // load user styles
91e3c3abf1SAndreas Gohr        if (isset($config_cascade['userstyle'][$mediatype]) && is_array($config_cascade['userstyle'][$mediatype])) {
927b909d5eSGerrit Uitslag            foreach ($config_cascade['userstyle'][$mediatype] as $userstyle) {
93ef36714bSGerry Weißbach                $files[$userstyle] = DOKU_BASE;
947b909d5eSGerrit Uitslag            }
95318cd03eSAnika Henke        }
9678a6aeb1SAndreas Gohr
97ef36714bSGerry Weißbach        // Let plugins decide to either put more styles here or to remove some
983e32b194SGerry Weißbach        $media_files[$mediatype] = css_filewrapper($mediatype, $files);
99e1d9dcc8SAndreas Gohr        $CSSEvt = new Event('CSS_STYLES_INCLUDED', $media_files[$mediatype]);
100ef36714bSGerry Weißbach
101ef36714bSGerry Weißbach        // Make it preventable.
102ef36714bSGerry Weißbach        if ($CSSEvt->advise_before()) {
103ef36714bSGerry Weißbach            $cache_files = array_merge($cache_files, array_keys($media_files[$mediatype]['files']));
104ef36714bSGerry Weißbach        } else {
105ef36714bSGerry Weißbach            // unset if prevented. Nothing will be printed for this mediatype.
106ef36714bSGerry Weißbach            unset($media_files[$mediatype]);
10714977bd2SMichael Hamann        }
1086619f42eSAdrian Lang
109ef36714bSGerry Weißbach        // finish event.
110ef36714bSGerry Weißbach        $CSSEvt->advise_after();
111ef36714bSGerry Weißbach    }
112ef36714bSGerry Weißbach
113ef36714bSGerry Weißbach    // The generated script depends on some dynamic options
1140db5771eSMichael Große    $cache = new Cache(
11564159a61SAndreas Gohr        'styles' .
11664159a61SAndreas Gohr        $_SERVER['HTTP_HOST'] .
11764159a61SAndreas Gohr        $_SERVER['SERVER_PORT'] .
11864159a61SAndreas Gohr        $INPUT->bool('preview') .
11964159a61SAndreas Gohr        DOKU_BASE .
12064159a61SAndreas Gohr        $tpl .
12164159a61SAndreas Gohr        $type,
12264159a61SAndreas Gohr        '.css'
12364159a61SAndreas Gohr    );
124dc7da772SMichael Große    $cache->setEvent('CSS_CACHE_USE');
125ef36714bSGerry Weißbach
12638f56bffSBen Coburn    // check cache age & handle conditional request
1276619f42eSAdrian Lang    // This may exit if a cache can be used
128e3c3abf1SAndreas Gohr    $cache_ok = $cache->useCache(['files' => $cache_files]);
129e7c68c4dSGerry Weißbach    http_cached($cache->cache, $cache_ok);
13078a6aeb1SAndreas Gohr
1313899c2ecSMichael Hamann    // start output buffering
1323899c2ecSMichael Hamann    ob_start();
1333899c2ecSMichael Hamann
134ef36714bSGerry Weißbach    // Fire CSS_STYLES_INCLUDED for one last time to let the
135ef36714bSGerry Weißbach    // plugins decide whether to include the DW default styles.
136ef36714bSGerry Weißbach    // This can be done by preventing the Default.
137ef36714bSGerry Weißbach    $media_files['DW_DEFAULT'] = css_filewrapper('DW_DEFAULT');
138cbb44eabSAndreas Gohr    Event::createAndTrigger('CSS_STYLES_INCLUDED', $media_files['DW_DEFAULT'], 'css_defaultstyles');
139ef36714bSGerry Weißbach
1406c47a78cSAnika Henke    // build the stylesheet
14114977bd2SMichael Hamann    foreach ($mediatypes as $mediatype) {
142ef36714bSGerry Weißbach        // Check if there is a wrapper set for this type.
143ef36714bSGerry Weißbach        if (!isset($media_files[$mediatype])) {
144ef36714bSGerry Weißbach            continue;
14578a6aeb1SAndreas Gohr        }
14678a6aeb1SAndreas Gohr
147ef36714bSGerry Weißbach        $cssData = $media_files[$mediatype];
148ef36714bSGerry Weißbach
149ef36714bSGerry Weißbach        // Print the styles.
15026dfc232SAndreas Gohr        echo NL;
1515a5ec053SGerrit Uitslag        if ($cssData['encapsulate'] === true) {
15226dfc232SAndreas Gohr            echo $cssData['encapsulationPrefix'] . ' {';
1535a5ec053SGerrit Uitslag        }
15426dfc232SAndreas Gohr        echo '/* START ' . $cssData['mediatype'] . ' styles */' . NL;
155ef36714bSGerry Weißbach
1566c47a78cSAnika Henke        // load files
157ef36714bSGerry Weißbach        foreach ($cssData['files'] as $file => $location) {
15872a66eb7SAndreas Gohr            $display = str_replace(fullpath(DOKU_INC), '', fullpath($file));
15926dfc232SAndreas Gohr            echo "\n/* XXXXXXXXX $display XXXXXXXXX */\n";
16026dfc232SAndreas Gohr            echo css_loadfile($file, $location);
1616c47a78cSAnika Henke        }
162ef36714bSGerry Weißbach
16326dfc232SAndreas Gohr        echo NL;
1645a5ec053SGerrit Uitslag        if ($cssData['encapsulate'] === true) {
16526dfc232SAndreas Gohr            echo '} /* /@media ';
1665a5ec053SGerrit Uitslag        } else {
16726dfc232SAndreas Gohr            echo '/*';
1685a5ec053SGerrit Uitslag        }
16926dfc232SAndreas Gohr        echo ' END ' . $cssData['mediatype'] . ' styles */' . NL;
1706c47a78cSAnika Henke    }
171ef36714bSGerry Weißbach
17278a6aeb1SAndreas Gohr    // end output buffering and get contents
17378a6aeb1SAndreas Gohr    $css = ob_get_contents();
17478a6aeb1SAndreas Gohr    ob_end_clean();
17578a6aeb1SAndreas Gohr
176f8fb2d18SAndreas Gohr    // strip any source maps
177f8fb2d18SAndreas Gohr    stripsourcemaps($css);
178f8fb2d18SAndreas Gohr
1796e69c1baSAndreas Gohr    // apply style replacements
180afb2c082SAndreas Gohr    $css = css_applystyle($css, $styleini['replacements']);
1816e69c1baSAndreas Gohr
18272a66eb7SAndreas Gohr    // parse less
18372a66eb7SAndreas Gohr    $css = css_parseless($css);
184d4a1ece8SAndreas Gohr
18578a6aeb1SAndreas Gohr    // compress whitespace and comments
18678a6aeb1SAndreas Gohr    if ($conf['compress']) {
18778a6aeb1SAndreas Gohr        $css = css_compress($css);
18878a6aeb1SAndreas Gohr    }
18978a6aeb1SAndreas Gohr
190809d3ba5SAndreas Gohr    // embed small images right into the stylesheet
191809d3ba5SAndreas Gohr    if ($conf['cssdatauri']) {
192809d3ba5SAndreas Gohr        $base = preg_quote(DOKU_BASE, '#');
193809d3ba5SAndreas Gohr        $css = preg_replace_callback('#(url\([ \'"]*)(' . $base . ')(.*?(?:\.(png|gif)))#i', 'css_datauri', $css);
194809d3ba5SAndreas Gohr    }
195809d3ba5SAndreas Gohr
1966619f42eSAdrian Lang    http_cached_finish($cache->cache, $css);
19778a6aeb1SAndreas Gohr}
19878a6aeb1SAndreas Gohr
19978a6aeb1SAndreas Gohr/**
20072a66eb7SAndreas Gohr * Uses phpless to parse LESS in our CSS
20172a66eb7SAndreas Gohr *
20272a66eb7SAndreas Gohr * most of this function is error handling to show a nice useful error when
20372a66eb7SAndreas Gohr * LESS compilation fails
20472a66eb7SAndreas Gohr *
205253d4b48SGerrit Uitslag * @param string $css
20672a66eb7SAndreas Gohr * @return string
20772a66eb7SAndreas Gohr */
208d868eb89SAndreas Gohrfunction css_parseless($css)
209d868eb89SAndreas Gohr{
2107d247a3cSGerrit Uitslag    global $conf;
2117d247a3cSGerrit Uitslag
212cc47c50fSsplitbrain    $less = new Lessc();
213e6380ba3SAndreas Gohr    $less->setImportDir([DOKU_INC]);
2147d247a3cSGerrit Uitslag    $less->setPreserveComments(!$conf['compress']);
21530f686ebSChristopher Smith
21630f686ebSChristopher Smith    if (defined('DOKU_UNITTEST')) {
217e6380ba3SAndreas Gohr        $less->addImportDir(TMP_DIR);
21830f686ebSChristopher Smith    }
21930f686ebSChristopher Smith
22072a66eb7SAndreas Gohr    try {
22172a66eb7SAndreas Gohr        return $less->compile($css);
22272a66eb7SAndreas Gohr    } catch (Exception $e) {
22372a66eb7SAndreas Gohr        // get exception message
224e3c3abf1SAndreas Gohr        $msg = str_replace(["\n", "\r", "'"], [], $e->getMessage());
22572a66eb7SAndreas Gohr
22672a66eb7SAndreas Gohr        // try to use line number to find affected file
22772a66eb7SAndreas Gohr        if (preg_match('/line: (\d+)$/', $msg, $m)) {
22872a66eb7SAndreas Gohr            $msg = substr($msg, 0, -1 * strlen($m[0])); //remove useless linenumber
22972a66eb7SAndreas Gohr            $lno = $m[1];
23072a66eb7SAndreas Gohr
23172a66eb7SAndreas Gohr            // walk upwards to last include
23272a66eb7SAndreas Gohr            $lines = explode("\n", $css);
23372a66eb7SAndreas Gohr            for ($i = $lno - 1; $i >= 0; $i--) {
23472a66eb7SAndreas Gohr                if (preg_match('/\/(\* XXXXXXXXX )(.*?)( XXXXXXXXX \*)\//', $lines[$i], $m)) {
23572a66eb7SAndreas Gohr                    // we found it, add info to message
23672a66eb7SAndreas Gohr                    $msg .= ' in ' . $m[2] . ' at line ' . ($lno - $i);
23772a66eb7SAndreas Gohr                    break;
23872a66eb7SAndreas Gohr                }
23972a66eb7SAndreas Gohr            }
24072a66eb7SAndreas Gohr        }
24172a66eb7SAndreas Gohr
24272a66eb7SAndreas Gohr        // something went wrong
24372a66eb7SAndreas Gohr        $error = 'A fatal error occured during compilation of the CSS files. ' .
24472a66eb7SAndreas Gohr            'If you recently installed a new plugin or template it ' .
24572a66eb7SAndreas Gohr            'might be broken and you should try disabling it again. [' . $msg . ']';
24672a66eb7SAndreas Gohr
24772a66eb7SAndreas Gohr        echo ".dokuwiki:before {
24872a66eb7SAndreas Gohr            content: '$error';
24972a66eb7SAndreas Gohr            background-color: red;
25072a66eb7SAndreas Gohr            display: block;
25172a66eb7SAndreas Gohr            background-color: #fcc;
25272a66eb7SAndreas Gohr            border-color: #ebb;
25372a66eb7SAndreas Gohr            color: #000;
25472a66eb7SAndreas Gohr            padding: 0.5em;
25572a66eb7SAndreas Gohr        }";
25672a66eb7SAndreas Gohr
25772a66eb7SAndreas Gohr        exit;
25872a66eb7SAndreas Gohr    }
25972a66eb7SAndreas Gohr}
26072a66eb7SAndreas Gohr
26172a66eb7SAndreas Gohr/**
2626e69c1baSAndreas Gohr * Does placeholder replacements in the style according to
2636e69c1baSAndreas Gohr * the ones defined in a templates style.ini file
2646e69c1baSAndreas Gohr *
265d4a1ece8SAndreas Gohr * This also adds the ini defined placeholders as less variables
266d4a1ece8SAndreas Gohr * (sans the surrounding __ and with a ini_ prefix)
267d4a1ece8SAndreas Gohr *
268253d4b48SGerrit Uitslag * @param string $css
269253d4b48SGerrit Uitslag * @param array $replacements array(placeholder => value)
270253d4b48SGerrit Uitslag * @return string
2715a5ec053SGerrit Uitslag *
2725a5ec053SGerrit Uitslag * @author Andreas Gohr <andi@splitbrain.org>
2736e69c1baSAndreas Gohr */
274d868eb89SAndreas Gohrfunction css_applystyle($css, $replacements)
275d868eb89SAndreas Gohr{
276cbe37079SAndreas Gohr    // we convert ini replacements to LESS variable names
277cbe37079SAndreas Gohr    // and build a list of variable: value; pairs
278d4a1ece8SAndreas Gohr    $less = '';
279afb2c082SAndreas Gohr    foreach ((array)$replacements as $key => $value) {
280cbe37079SAndreas Gohr        $lkey = trim($key, '_');
281cbe37079SAndreas Gohr        $lkey = '@ini_' . $lkey;
282cbe37079SAndreas Gohr        $less .= "$lkey: $value;\n";
283cbe37079SAndreas Gohr
284afb2c082SAndreas Gohr        $replacements[$key] = $lkey;
285d4a1ece8SAndreas Gohr    }
286c51b334eSAndreas Gohr
287cbe37079SAndreas Gohr    // we now replace all old ini replacements with LESS variables
288afb2c082SAndreas Gohr    $css = strtr($css, $replacements);
289cbe37079SAndreas Gohr
290cbe37079SAndreas Gohr    // now prepend the list of LESS variables as the very first thing
291c51b334eSAndreas Gohr    $css = $less . $css;
2926e69c1baSAndreas Gohr    return $css;
2936e69c1baSAndreas Gohr}
2946e69c1baSAndreas Gohr
2956e69c1baSAndreas Gohr/**
296ef36714bSGerry Weißbach * Wrapper for the files, content and mediatype for the event CSS_STYLES_INCLUDED
297ef36714bSGerry Weißbach *
298ef36714bSGerry Weißbach * @param string $mediatype type ofthe current media files/content set
299ef36714bSGerry Weißbach * @param array $files set of files that define the current mediatype
300ef36714bSGerry Weißbach * @return array
3015a5ec053SGerrit Uitslag *
3025a5ec053SGerrit Uitslag * @author Gerry Weißbach <gerry.w@gammaproduction.de>
303ef36714bSGerry Weißbach */
304d868eb89SAndreas Gohrfunction css_filewrapper($mediatype, $files = [])
305d868eb89SAndreas Gohr{
306e3c3abf1SAndreas Gohr    return [
307ef36714bSGerry Weißbach        'files' => $files,
308ef36714bSGerry Weißbach        'mediatype' => $mediatype,
309cf35519cSGerry Weißbach        'encapsulate' => $mediatype != 'all',
310ef36714bSGerry Weißbach        'encapsulationPrefix' => '@media ' . $mediatype
311e3c3abf1SAndreas Gohr    ];
312ef36714bSGerry Weißbach}
313ef36714bSGerry Weißbach
314ef36714bSGerry Weißbach/**
315ef36714bSGerry Weißbach * Prints the @media encapsulated default styles of DokuWiki
316ef36714bSGerry Weißbach *
317ef36714bSGerry Weißbach * This function is being called by a CSS_STYLES_INCLUDED event
318ef36714bSGerry Weißbach * The event can be distinguished by the mediatype which is:
319ef36714bSGerry Weißbach *   DW_DEFAULT
3205a5ec053SGerrit Uitslag *
3215a5ec053SGerrit Uitslag * @author Gerry Weißbach <gerry.w@gammaproduction.de>
322ef36714bSGerry Weißbach */
323d868eb89SAndreas Gohrfunction css_defaultstyles()
324d868eb89SAndreas Gohr{
325ef36714bSGerry Weißbach    // print the default classes for interwiki links and file downloads
32626dfc232SAndreas Gohr    echo '@media screen {';
327ef36714bSGerry Weißbach    css_interwiki();
328ef36714bSGerry Weißbach    css_filetypes();
32926dfc232SAndreas Gohr    echo '}';
330ef36714bSGerry Weißbach}
331ef36714bSGerry Weißbach
332ef36714bSGerry Weißbach/**
3331c2d1019SAndreas Gohr * Prints classes for interwikilinks
3341c2d1019SAndreas Gohr *
3351c2d1019SAndreas Gohr * Interwiki links have two classes: 'interwiki' and 'iw_$name>' where
3361c2d1019SAndreas Gohr * $name is the identifier given in the config. All Interwiki links get
3371c2d1019SAndreas Gohr * an default style with a default icon. If a special icon is available
3381c2d1019SAndreas Gohr * for an interwiki URL it is set in it's own class. Both classes can be
3391c2d1019SAndreas Gohr * overwritten in the template or userstyles.
3401c2d1019SAndreas Gohr *
3411c2d1019SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
3421c2d1019SAndreas Gohr */
343d868eb89SAndreas Gohrfunction css_interwiki()
344d868eb89SAndreas Gohr{
3451c2d1019SAndreas Gohr
3461c2d1019SAndreas Gohr    // default style
3471c2d1019SAndreas Gohr    echo 'a.interwiki {';
348*e44b94a4SAndreas Gohr    echo ' background: transparent url(' . DOKU_BASE . 'lib/images/interwiki.svg) 0 0 no-repeat;';
3491e519eb5SAndreas Gohr    echo ' background-size: 1.2em;';
3501e519eb5SAndreas Gohr    echo ' padding: 0 0 0 1.4em;';
3511c2d1019SAndreas Gohr    echo '}';
3521c2d1019SAndreas Gohr
3531c2d1019SAndreas Gohr    // additional styles when icon available
3541c2d1019SAndreas Gohr    $iwlinks = getInterwiki();
3551c2d1019SAndreas Gohr    foreach (array_keys($iwlinks) as $iw) {
3569d2ddea4SAndreas Gohr        $class = preg_replace('/[^_\-a-z0-9]+/i', '_', $iw);
3571e519eb5SAndreas Gohr        foreach (['svg', 'png', 'gif'] as $ext) {
358*e44b94a4SAndreas Gohr            $file = 'lib/images/interwiki/' . $iw . '.' . $ext;
3591e519eb5SAndreas Gohr
3601e519eb5SAndreas Gohr            if (file_exists(DOKU_INC . $file)) {
3619d2ddea4SAndreas Gohr                echo "a.iw_$class {";
3621e519eb5SAndreas Gohr                echo '  background-image: url(' . DOKU_BASE . $file . ')';
3631c2d1019SAndreas Gohr                echo '}';
3641e519eb5SAndreas Gohr                break;
3651e519eb5SAndreas Gohr            }
3661c2d1019SAndreas Gohr        }
3671c2d1019SAndreas Gohr    }
368d15166e5SAndreas Gohr}
3691c2d1019SAndreas Gohr
370d15166e5SAndreas Gohr/**
371d15166e5SAndreas Gohr * Prints classes for file download links
372d15166e5SAndreas Gohr *
373d15166e5SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
374d15166e5SAndreas Gohr */
375d868eb89SAndreas Gohrfunction css_filetypes()
376d868eb89SAndreas Gohr{
377d15166e5SAndreas Gohr
378d15166e5SAndreas Gohr    // default style
379035e07f1SKate Arzamastseva    echo '.mediafile {';
380*e44b94a4SAndreas Gohr    echo ' background: transparent url(' . DOKU_BASE . 'lib/images/fileicons/svg/file.svg) 0px 1px no-repeat;';
38124115d42SAndreas Gohr    echo ' background-size: 1.2em;';
38224115d42SAndreas Gohr    echo ' padding-left: 1.5em;';
383d15166e5SAndreas Gohr    echo '}';
384d15166e5SAndreas Gohr
385d15166e5SAndreas Gohr    // additional styles when icon available
38627bf7924STom N Harris    // scan directory for all icons
387e3c3abf1SAndreas Gohr    $exts = [];
38824115d42SAndreas Gohr    if ($dh = opendir(DOKU_INC . 'lib/images/fileicons/svg')) {
38927bf7924STom N Harris        while (false !== ($file = readdir($dh))) {
39024115d42SAndreas Gohr            if (preg_match('/(.*?)\.svg$/i', $file, $match)) {
39124115d42SAndreas Gohr                $exts[] = strtolower($match[1]);
392d15166e5SAndreas Gohr            }
3931c2d1019SAndreas Gohr        }
39427bf7924STom N Harris        closedir($dh);
39527bf7924STom N Harris    }
39624115d42SAndreas Gohr    foreach ($exts as $ext) {
39727bf7924STom N Harris        $class = preg_replace('/[^_\-a-z0-9]+/', '_', $ext);
398035e07f1SKate Arzamastseva        echo ".mf_$class {";
399*e44b94a4SAndreas Gohr        echo '  background-image: url(' . DOKU_BASE . 'lib/images/fileicons/svg/' . $ext . '.svg)';
40027bf7924STom N Harris        echo '}';
40127bf7924STom N Harris    }
40227bf7924STom N Harris}
4031c2d1019SAndreas Gohr
4041c2d1019SAndreas Gohr/**
40578a6aeb1SAndreas Gohr * Loads a given file and fixes relative URLs with the
40678a6aeb1SAndreas Gohr * given location prefix
407253d4b48SGerrit Uitslag *
408253d4b48SGerrit Uitslag * @param string $file file system path
409253d4b48SGerrit Uitslag * @param string $location
410253d4b48SGerrit Uitslag * @return string
41178a6aeb1SAndreas Gohr */
412d868eb89SAndreas Gohrfunction css_loadfile($file, $location = '')
413d868eb89SAndreas Gohr{
41412ffbbc3SChristopher Smith    $css_file = new DokuCssFile($file);
41512ffbbc3SChristopher Smith    return $css_file->load($location);
41612ffbbc3SChristopher Smith}
41712ffbbc3SChristopher Smith
4181e2c5948SChristopher Smith/**
4191e2c5948SChristopher Smith * Helper class to abstract loading of css/less files
4201e2c5948SChristopher Smith *
4211e2c5948SChristopher Smith * @author Chris Smith <chris@jalakai.co.uk>
4221e2c5948SChristopher Smith */
4238c7c53b0SAndreas Gohrclass DokuCssFile
4248c7c53b0SAndreas Gohr{
4251e2c5948SChristopher Smith    protected $filepath;             // file system path to the CSS/Less file
4261e2c5948SChristopher Smith    protected $location;             // base url location of the CSS/Less file
427e3c3abf1SAndreas Gohr    protected $relative_path;
42812ffbbc3SChristopher Smith
429d868eb89SAndreas Gohr    public function __construct($file)
430d868eb89SAndreas Gohr    {
43112ffbbc3SChristopher Smith        $this->filepath = $file;
43212ffbbc3SChristopher Smith    }
43312ffbbc3SChristopher Smith
4341e2c5948SChristopher Smith    /**
4351e2c5948SChristopher Smith     * Load the contents of the css/less file and adjust any relative paths/urls (relative to this file) to be
4361e2c5948SChristopher Smith     * relative to the dokuwiki root: the web root (DOKU_BASE) for most files; the file system root (DOKU_INC)
4371e2c5948SChristopher Smith     * for less files.
4381e2c5948SChristopher Smith     *
4391e2c5948SChristopher Smith     * @param string $location base url for this file
4401e2c5948SChristopher Smith     * @return string the CSS/Less contents of the file
4411e2c5948SChristopher Smith     */
442d868eb89SAndreas Gohr    public function load($location = '')
443d868eb89SAndreas Gohr    {
44479e79377SAndreas Gohr        if (!file_exists($this->filepath)) return '';
44512ffbbc3SChristopher Smith
44612ffbbc3SChristopher Smith        $css = io_readFile($this->filepath);
44778a6aeb1SAndreas Gohr        if (!$location) return $css;
44878a6aeb1SAndreas Gohr
44912ffbbc3SChristopher Smith        $this->location = $location;
450de737055SChristopher Smith
451e3c3abf1SAndreas Gohr        $css = preg_replace_callback('#(url\( *)([\'"]?)(.*?)(\2)( *\))#', [$this, 'replacements'], $css);
452e3c3abf1SAndreas Gohr        $css = preg_replace_callback('#(@import\s+)([\'"])(.*?)(\2)#', [$this, 'replacements'], $css);
453809d3ba5SAndreas Gohr
45478a6aeb1SAndreas Gohr        return $css;
45578a6aeb1SAndreas Gohr    }
45678a6aeb1SAndreas Gohr
4571e2c5948SChristopher Smith    /**
4581e2c5948SChristopher Smith     * Get the relative file system path of this file, relative to dokuwiki's root folder, DOKU_INC
4591e2c5948SChristopher Smith     *
4601e2c5948SChristopher Smith     * @return string   relative file system path
4611e2c5948SChristopher Smith     */
462d868eb89SAndreas Gohr    protected function getRelativePath()
463d868eb89SAndreas Gohr    {
46412ffbbc3SChristopher Smith
46512ffbbc3SChristopher Smith        if (is_null($this->relative_path)) {
466e3c3abf1SAndreas Gohr            $basedir = [DOKU_INC];
4671e2c5948SChristopher Smith
4681e2c5948SChristopher Smith            // during testing, files may be found relative to a second base dir, TMP_DIR
46912ffbbc3SChristopher Smith            if (defined('DOKU_UNITTEST')) {
47012ffbbc3SChristopher Smith                $basedir[] = realpath(TMP_DIR);
47112ffbbc3SChristopher Smith            }
47212ffbbc3SChristopher Smith
47373f25ac0SAndreas Gohr            $basedir = array_map('preg_quote_cb', $basedir);
474e3c3abf1SAndreas Gohr            $regex = '/^(' . implode('|', $basedir) . ')/';
47512ffbbc3SChristopher Smith            $this->relative_path = preg_replace($regex, '', dirname($this->filepath));
47612ffbbc3SChristopher Smith        }
47712ffbbc3SChristopher Smith
47812ffbbc3SChristopher Smith        return $this->relative_path;
47912ffbbc3SChristopher Smith    }
48012ffbbc3SChristopher Smith
4811e2c5948SChristopher Smith    /**
4821e2c5948SChristopher Smith     * preg_replace callback to adjust relative urls from relative to this file to relative
4831e2c5948SChristopher Smith     * to the appropriate dokuwiki root location as described in the code
4841e2c5948SChristopher Smith     *
4855a5ec053SGerrit Uitslag     * @param array $match see http://php.net/preg_replace_callback
4861e2c5948SChristopher Smith     * @return string   see http://php.net/preg_replace_callback
4871e2c5948SChristopher Smith     */
488d868eb89SAndreas Gohr    public function replacements($match)
489d868eb89SAndreas Gohr    {
490de737055SChristopher Smith
491e24a74c0SAndreas Gohr        if (preg_match('#^(/|data:|https?://)#', $match[3])) { // not a relative url? - no adjustment required
492de737055SChristopher Smith            return $match[0];
4931b2deed9Sfiwswe        } elseif (str_ends_with($match[3], '.less')) { // a less file import? - requires a file system location
4945312cb0bSSyntaxseed            if ($match[3][0] != '/') {
49512ffbbc3SChristopher Smith                $match[3] = $this->getRelativePath() . '/' . $match[3];
496de737055SChristopher Smith            }
497e24a74c0SAndreas Gohr        } else { // everything else requires a url adjustment
49812ffbbc3SChristopher Smith            $match[3] = $this->location . $match[3];
499de737055SChristopher Smith        }
500de737055SChristopher Smith
501e3c3abf1SAndreas Gohr        return implode('', array_slice($match, 1));
502de737055SChristopher Smith    }
50312ffbbc3SChristopher Smith}
504de737055SChristopher Smith
505809d3ba5SAndreas Gohr/**
5064eb5f931SChristopher Smith * Convert local image URLs to data URLs if the filesize is small
507809d3ba5SAndreas Gohr *
508809d3ba5SAndreas Gohr * Callback for preg_replace_callback
509253d4b48SGerrit Uitslag *
510253d4b48SGerrit Uitslag * @param array $match
511253d4b48SGerrit Uitslag * @return string
512809d3ba5SAndreas Gohr */
513d868eb89SAndreas Gohrfunction css_datauri($match)
514d868eb89SAndreas Gohr{
51528f4004cSAndreas Gohr    global $conf;
51628f4004cSAndreas Gohr
517809d3ba5SAndreas Gohr    $pre = unslash($match[1]);
518809d3ba5SAndreas Gohr    $base = unslash($match[2]);
519809d3ba5SAndreas Gohr    $url = unslash($match[3]);
520809d3ba5SAndreas Gohr    $ext = unslash($match[4]);
521809d3ba5SAndreas Gohr
522809d3ba5SAndreas Gohr    $local = DOKU_INC . $url;
523809d3ba5SAndreas Gohr    $size = @filesize($local);
52428f4004cSAndreas Gohr    if ($size && $size < $conf['cssdatauri']) {
525809d3ba5SAndreas Gohr        $data = base64_encode(file_get_contents($local));
526809d3ba5SAndreas Gohr    }
5278f34cf3dSMichael Große    if (!empty($data)) {
5286a5d6817SAnika Henke        $url = 'data:image/' . $ext . ';base64,' . $data;
529809d3ba5SAndreas Gohr    } else {
530809d3ba5SAndreas Gohr        $url = $base . $url;
531809d3ba5SAndreas Gohr    }
532809d3ba5SAndreas Gohr    return $pre . $url;
533809d3ba5SAndreas Gohr}
534809d3ba5SAndreas Gohr
53515c394afSAndreas Gohr
53678a6aeb1SAndreas Gohr/**
53778a6aeb1SAndreas Gohr * Returns a list of possible Plugin Styles (no existance check here)
53878a6aeb1SAndreas Gohr *
539253d4b48SGerrit Uitslag * @param string $mediatype
540253d4b48SGerrit Uitslag * @return array
5415a5ec053SGerrit Uitslag * @author Andreas Gohr <andi@splitbrain.org>
5425a5ec053SGerrit Uitslag *
54378a6aeb1SAndreas Gohr */
544d868eb89SAndreas Gohrfunction css_pluginstyles($mediatype = 'screen')
545d868eb89SAndreas Gohr{
546e3c3abf1SAndreas Gohr    $list = [];
54778a6aeb1SAndreas Gohr    $plugins = plugin_list();
54878a6aeb1SAndreas Gohr    foreach ($plugins as $p) {
549318cd03eSAnika Henke        $list[DOKU_PLUGIN . "$p/$mediatype.css"] = DOKU_BASE . "lib/plugins/$p/";
550d4a1ece8SAndreas Gohr        $list[DOKU_PLUGIN . "$p/$mediatype.less"] = DOKU_BASE . "lib/plugins/$p/";
551318cd03eSAnika Henke        // alternative for screen.css
552318cd03eSAnika Henke        if ($mediatype == 'screen') {
55378a6aeb1SAndreas Gohr            $list[DOKU_PLUGIN . "$p/style.css"] = DOKU_BASE . "lib/plugins/$p/";
554d4a1ece8SAndreas Gohr            $list[DOKU_PLUGIN . "$p/style.less"] = DOKU_BASE . "lib/plugins/$p/";
55578a6aeb1SAndreas Gohr        }
55678a6aeb1SAndreas Gohr    }
55778a6aeb1SAndreas Gohr    return $list;
55878a6aeb1SAndreas Gohr}
55978a6aeb1SAndreas Gohr
56078a6aeb1SAndreas Gohr/**
56178a6aeb1SAndreas Gohr * Very simple CSS optimizer
56278a6aeb1SAndreas Gohr *
563253d4b48SGerrit Uitslag * @param string $css
564253d4b48SGerrit Uitslag * @return string
5655a5ec053SGerrit Uitslag * @author Andreas Gohr <andi@splitbrain.org>
5665a5ec053SGerrit Uitslag *
56778a6aeb1SAndreas Gohr */
568d868eb89SAndreas Gohrfunction css_compress($css)
569d868eb89SAndreas Gohr{
570ba234b18SPhy    // replace quoted strings with placeholder
571ba234b18SPhy    $quote_storage = [];
572ba234b18SPhy
573ba234b18SPhy    $quote_cb = function ($match) use (&$quote_storage) {
574ba234b18SPhy        $quote_storage[] = $match[0];
5755fdc2ff2SPhy        return '"STR' . (count($quote_storage) - 1) . '"';
576ba234b18SPhy    };
577ba234b18SPhy
5785fdc2ff2SPhy    $css = preg_replace_callback('/(([\'"]).*?(?<!\\\\)\2)/', $quote_cb, $css);
579ba234b18SPhy
580fd7c2db0SAndreas Gohr    // strip comments through a callback
581fd7c2db0SAndreas Gohr    $css = preg_replace_callback('#(/\*)(.*?)(\*/)#s', 'css_comment_cb', $css);
582fd7c2db0SAndreas Gohr
583247c1c5dSAndreas Gohr    // strip (incorrect but common) one line comments
584fe5a50c3SAndreas Gohr    $css = preg_replace_callback('/^.*\/\/.*$/m', 'css_onelinecomment_cb', $css);
585247c1c5dSAndreas Gohr
58678a6aeb1SAndreas Gohr    // strip whitespaces
58778a6aeb1SAndreas Gohr    $css = preg_replace('![\r\n\t ]+!', ' ', $css);
588f5379589SChristopher Smith    $css = preg_replace('/ ?([;,{}\/]) ?/', '\\1', $css);
589f5379589SChristopher Smith    $css = preg_replace('/ ?: /', ':', $css);
59078a6aeb1SAndreas Gohr
591205907a7Sfurun    // number compression
59264159a61SAndreas Gohr    $css = preg_replace(
59364159a61SAndreas Gohr        '/([: ])0+(\.\d+?)0*((?:pt|pc|in|mm|cm|em|ex|px)\b|%)(?=[^\{]*[;\}])/',
59464159a61SAndreas Gohr        '$1$2$3',
59564159a61SAndreas Gohr        $css
59664159a61SAndreas Gohr    ); // "0.1em" to ".1em", "1.10em" to "1.1em"
59764159a61SAndreas Gohr    $css = preg_replace(
59864159a61SAndreas Gohr        '/([: ])\.(0)+((?:pt|pc|in|mm|cm|em|ex|px)\b|%)(?=[^\{]*[;\}])/',
59964159a61SAndreas Gohr        '$1$2',
60064159a61SAndreas Gohr        $css
60164159a61SAndreas Gohr    ); // ".0em" to "0"
60264159a61SAndreas Gohr    $css = preg_replace(
60364159a61SAndreas Gohr        '/([: ]0)0*(\.0*)?((?:pt|pc|in|mm|cm|em|ex|px)(?=[^\{]*[;\}])\b|%)/',
60464159a61SAndreas Gohr        '$1',
60564159a61SAndreas Gohr        $css
60664159a61SAndreas Gohr    ); // "0.0em" to "0"
60764159a61SAndreas Gohr    $css = preg_replace(
60864159a61SAndreas Gohr        '/([: ]\d+)(\.0*)((?:pt|pc|in|mm|cm|em|ex|px)(?=[^\{]*[;\}])\b|%)/',
60964159a61SAndreas Gohr        '$1$3',
61064159a61SAndreas Gohr        $css
61164159a61SAndreas Gohr    ); // "1.0em" to "1em"
61264159a61SAndreas Gohr    $css = preg_replace(
61364159a61SAndreas Gohr        '/([: ])0+(\d+|\d*\.\d+)((?:pt|pc|in|mm|cm|em|ex|px)(?=[^\{]*[;\}])\b|%)/',
61464159a61SAndreas Gohr        '$1$2$3',
61564159a61SAndreas Gohr        $css
61664159a61SAndreas Gohr    ); // "001em" to "1em"
617205907a7Sfurun
618205907a7Sfurun    // shorten attributes (1em 1em 1em 1em -> 1em)
61964159a61SAndreas Gohr    $css = preg_replace(
62064159a61SAndreas Gohr        '/(?<![\w\-])((?:margin|padding|border|border-(?:width|radius)):)([\w\.]+)( \2)+(?=[;\}]| !)/',
62164159a61SAndreas Gohr        '$1$2',
62264159a61SAndreas Gohr        $css
62364159a61SAndreas Gohr    ); // "1em 1em 1em 1em" to "1em"
62464159a61SAndreas Gohr    $css = preg_replace(
62564159a61SAndreas Gohr        '/(?<![\w\-])((?:margin|padding|border|border-(?:width)):)([\w\.]+) ([\w\.]+) \2 \3(?=[;\}]| !)/',
62664159a61SAndreas Gohr        '$1$2 $3',
62764159a61SAndreas Gohr        $css
62864159a61SAndreas Gohr    ); // "1em 2em 1em 2em" to "1em 2em"
629205907a7Sfurun
63078a6aeb1SAndreas Gohr    // shorten colors
63164159a61SAndreas Gohr    $css = preg_replace(
63264159a61SAndreas Gohr        "/#([0-9a-fA-F]{1})\\1([0-9a-fA-F]{1})\\2([0-9a-fA-F]{1})\\3(?=[^\{]*[;\}])/",
63364159a61SAndreas Gohr        "#\\1\\2\\3",
63464159a61SAndreas Gohr        $css
63564159a61SAndreas Gohr    );
63678a6aeb1SAndreas Gohr
637ba234b18SPhy    // replace back protected strings
638ba234b18SPhy    $quote_back_cb = function ($match) use (&$quote_storage) {
639ba234b18SPhy        return $quote_storage[$match[1]];
640ba234b18SPhy    };
641ba234b18SPhy
6425fdc2ff2SPhy    $css = preg_replace_callback('/"STR(\d+)"/', $quote_back_cb, $css);
6432f5645efSPhy    $css = trim($css);
644ba234b18SPhy
64578a6aeb1SAndreas Gohr    return $css;
64678a6aeb1SAndreas Gohr}
64778a6aeb1SAndreas Gohr
648c00aef76SAndreas Gohr/**
649c00aef76SAndreas Gohr * Callback for css_compress()
650c00aef76SAndreas Gohr *
651c00aef76SAndreas Gohr * Keeps short comments (< 5 chars) to maintain typical browser hacks
652c00aef76SAndreas Gohr *
653253d4b48SGerrit Uitslag * @param array $matches
654253d4b48SGerrit Uitslag * @return string
6555a5ec053SGerrit Uitslag *
6565a5ec053SGerrit Uitslag * @author Andreas Gohr <andi@splitbrain.org>
6575a5ec053SGerrit Uitslag *
658c00aef76SAndreas Gohr */
659d868eb89SAndreas Gohrfunction css_comment_cb($matches)
660d868eb89SAndreas Gohr{
661c00aef76SAndreas Gohr    if (strlen($matches[2]) > 4) return '';
662c00aef76SAndreas Gohr    return $matches[0];
663c00aef76SAndreas Gohr}
66478a6aeb1SAndreas Gohr
665fe5a50c3SAndreas Gohr/**
666fe5a50c3SAndreas Gohr * Callback for css_compress()
667fe5a50c3SAndreas Gohr *
668fe5a50c3SAndreas Gohr * Strips one line comments but makes sure it will not destroy url() constructs with slashes
669fe5a50c3SAndreas Gohr *
670253d4b48SGerrit Uitslag * @param array $matches
671fe5a50c3SAndreas Gohr * @return string
672fe5a50c3SAndreas Gohr */
673d868eb89SAndreas Gohrfunction css_onelinecomment_cb($matches)
674d868eb89SAndreas Gohr{
675fe5a50c3SAndreas Gohr    $line = $matches[0];
676fe5a50c3SAndreas Gohr
677fe5a50c3SAndreas Gohr    $i = 0;
678fe5a50c3SAndreas Gohr    $len = strlen($line);
679918a4468SAndreas Gohr
680fe5a50c3SAndreas Gohr    while ($i < $len) {
681fe5a50c3SAndreas Gohr        $nextcom = strpos($line, '//', $i);
682fe5a50c3SAndreas Gohr        $nexturl = stripos($line, 'url(', $i);
683fe5a50c3SAndreas Gohr
684fe5a50c3SAndreas Gohr        if ($nextcom === false) {
685fe5a50c3SAndreas Gohr            // no more comments, we're done
686918a4468SAndreas Gohr            $i = $len;
687fe5a50c3SAndreas Gohr            break;
688fe5a50c3SAndreas Gohr        }
689fe5a50c3SAndreas Gohr
690918a4468SAndreas Gohr        if ($nexturl === false || $nextcom < $nexturl) {
691918a4468SAndreas Gohr            // no url anymore, strip comment and be done
692918a4468SAndreas Gohr            $i = $nextcom;
693918a4468SAndreas Gohr            break;
694918a4468SAndreas Gohr        }
695918a4468SAndreas Gohr
696918a4468SAndreas Gohr        // we have an upcoming url
697918a4468SAndreas Gohr        $i = strpos($line, ')', $nexturl);
698918a4468SAndreas Gohr    }
699918a4468SAndreas Gohr
700918a4468SAndreas Gohr    return substr($line, 0, $i);
701fe5a50c3SAndreas Gohr}
702fe5a50c3SAndreas Gohr
703e3776c06SMichael Hamann//Setup VIM: ex: et ts=4 :
704