1 <?php
2 
3 /**
4  * DokuWiki StyleSheet creator
5  *
6  * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
7  * @author     Andreas Gohr <andi@splitbrain.org>
8  */
9 
10 use LesserPHP\Lessc;
11 use dokuwiki\StyleUtils;
12 use dokuwiki\Cache\Cache;
13 use dokuwiki\Extension\Event;
14 
15 if (!defined('DOKU_INC')) define('DOKU_INC', __DIR__ . '/../../');
16 if (!defined('NOSESSION')) define('NOSESSION', true); // we do not use a session or authentication here (better caching)
17 if (!defined('DOKU_DISABLE_GZIP_OUTPUT')) define('DOKU_DISABLE_GZIP_OUTPUT', 1); // we gzip ourself here
18 if (!defined('NL')) define('NL', "\n");
19 require_once(DOKU_INC . 'inc/init.php');
20 
21 // Main (don't run when UNIT test)
22 if (!defined('SIMPLE_TEST')) {
23     header('Content-Type: text/css; charset=utf-8');
24     css_out();
25 }
26 
27 
28 // ---------------------- functions ------------------------------
29 
30 /**
31  * Output all needed Styles
32  *
33  * @author Andreas Gohr <andi@splitbrain.org>
34  */
35 function css_out()
36 {
37     global $conf;
38     global $lang;
39     global $config_cascade;
40     global $INPUT;
41 
42     if ($INPUT->str('s') == 'feed') {
43         $mediatypes = ['feed'];
44         $type = 'feed';
45     } else {
46         $mediatypes = ['screen', 'all', 'print', 'speech'];
47         $type = '';
48     }
49 
50     // decide from where to get the template
51     $tpl = trim(preg_replace('/[^\w-]+/', '', $INPUT->str('t')));
52     if (!$tpl) {
53         $tpl = $conf['template'];
54     }
55 
56     // load style.ini
57     $styleUtil = new StyleUtils($tpl, $INPUT->bool('preview'));
58     $styleini = $styleUtil->cssStyleini();
59 
60     // cache influencers
61     $tplinc = tpl_incdir($tpl);
62     $cache_files = getConfigFiles('main');
63     $cache_files[] = $tplinc . 'style.ini';
64     $cache_files[] = DOKU_CONF . "tpl/$tpl/style.ini";
65     $cache_files[] = __FILE__;
66     if ($INPUT->bool('preview')) {
67         $cache_files[] = $conf['cachedir'] . '/preview.ini';
68     }
69 
70     // Array of needed files and their web locations, the latter ones
71     // are needed to fix relative paths in the stylesheets
72     $media_files = [];
73     foreach ($mediatypes as $mediatype) {
74         $files = [];
75 
76         // load core styles
77         $files[DOKU_INC . 'lib/styles/' . $mediatype . '.css'] = DOKU_BASE . 'lib/styles/';
78 
79         // load jQuery-UI theme
80         if ($mediatype == 'screen') {
81             $files[DOKU_INC . 'lib/scripts/jquery/jquery-ui-theme/smoothness.css'] =
82                 DOKU_BASE . 'lib/scripts/jquery/jquery-ui-theme/';
83         }
84         // load plugin styles
85         $files = array_merge($files, css_pluginstyles($mediatype));
86         // load template styles
87         if (isset($styleini['stylesheets'][$mediatype])) {
88             $files = array_merge($files, $styleini['stylesheets'][$mediatype]);
89         }
90         // load user styles
91         if (isset($config_cascade['userstyle'][$mediatype]) && is_array($config_cascade['userstyle'][$mediatype])) {
92             foreach ($config_cascade['userstyle'][$mediatype] as $userstyle) {
93                 $files[$userstyle] = DOKU_BASE;
94             }
95         }
96 
97         // Let plugins decide to either put more styles here or to remove some
98         $media_files[$mediatype] = css_filewrapper($mediatype, $files);
99         $CSSEvt = new Event('CSS_STYLES_INCLUDED', $media_files[$mediatype]);
100 
101         // Make it preventable.
102         if ($CSSEvt->advise_before()) {
103             $cache_files = array_merge($cache_files, array_keys($media_files[$mediatype]['files']));
104         } else {
105             // unset if prevented. Nothing will be printed for this mediatype.
106             unset($media_files[$mediatype]);
107         }
108 
109         // finish event.
110         $CSSEvt->advise_after();
111     }
112 
113     // The generated script depends on some dynamic options
114     $cache = new Cache(
115         'styles' .
116         $_SERVER['HTTP_HOST'] .
117         $_SERVER['SERVER_PORT'] .
118         $INPUT->bool('preview') .
119         DOKU_BASE .
120         $tpl .
121         $type,
122         '.css'
123     );
124     $cache->setEvent('CSS_CACHE_USE');
125 
126     // check cache age & handle conditional request
127     // This may exit if a cache can be used
128     $cache_ok = $cache->useCache(['files' => $cache_files]);
129     http_cached($cache->cache, $cache_ok);
130 
131     // start output buffering
132     ob_start();
133 
134     // Fire CSS_STYLES_INCLUDED for one last time to let the
135     // plugins decide whether to include the DW default styles.
136     // This can be done by preventing the Default.
137     $media_files['DW_DEFAULT'] = css_filewrapper('DW_DEFAULT');
138     Event::createAndTrigger('CSS_STYLES_INCLUDED', $media_files['DW_DEFAULT'], 'css_defaultstyles');
139 
140     // build the stylesheet
141     foreach ($mediatypes as $mediatype) {
142         // Check if there is a wrapper set for this type.
143         if (!isset($media_files[$mediatype])) {
144             continue;
145         }
146 
147         $cssData = $media_files[$mediatype];
148 
149         // Print the styles.
150         echo NL;
151         if ($cssData['encapsulate'] === true) {
152             echo $cssData['encapsulationPrefix'] . ' {';
153         }
154         echo '/* START ' . $cssData['mediatype'] . ' styles */' . NL;
155 
156         // load files
157         foreach ($cssData['files'] as $file => $location) {
158             $display = str_replace(fullpath(DOKU_INC), '', fullpath($file));
159             echo "\n/* XXXXXXXXX $display XXXXXXXXX */\n";
160             echo css_loadfile($file, $location);
161         }
162 
163         echo NL;
164         if ($cssData['encapsulate'] === true) {
165             echo '} /* /@media ';
166         } else {
167             echo '/*';
168         }
169         echo ' END ' . $cssData['mediatype'] . ' styles */' . NL;
170     }
171 
172     // end output buffering and get contents
173     $css = ob_get_contents();
174     ob_end_clean();
175 
176     // strip any source maps
177     stripsourcemaps($css);
178 
179     // apply style replacements
180     $css = css_applystyle($css, $styleini['replacements']);
181 
182     // parse less
183     $css = css_parseless($css);
184 
185     // compress whitespace and comments
186     if ($conf['compress']) {
187         $css = css_compress($css);
188     }
189 
190     // embed small images right into the stylesheet
191     if ($conf['cssdatauri']) {
192         $base = preg_quote(DOKU_BASE, '#');
193         $css = preg_replace_callback('#(url\([ \'"]*)(' . $base . ')(.*?(?:\.(png|gif)))#i', 'css_datauri', $css);
194     }
195 
196     http_cached_finish($cache->cache, $css);
197 }
198 
199 /**
200  * Uses phpless to parse LESS in our CSS
201  *
202  * most of this function is error handling to show a nice useful error when
203  * LESS compilation fails
204  *
205  * @param string $css
206  * @return string
207  */
208 function css_parseless($css)
209 {
210     global $conf;
211 
212     $less = new Lessc();
213     $less->setImportDir([DOKU_INC]);
214     $less->setPreserveComments(!$conf['compress']);
215 
216     if (defined('DOKU_UNITTEST')) {
217         $less->addImportDir(TMP_DIR);
218     }
219 
220     try {
221         return $less->compile($css);
222     } catch (Exception $e) {
223         // get exception message
224         $msg = str_replace(["\n", "\r", "'"], [], $e->getMessage());
225 
226         // try to use line number to find affected file
227         if (preg_match('/line: (\d+)$/', $msg, $m)) {
228             $msg = substr($msg, 0, -1 * strlen($m[0])); //remove useless linenumber
229             $lno = $m[1];
230 
231             // walk upwards to last include
232             $lines = explode("\n", $css);
233             for ($i = $lno - 1; $i >= 0; $i--) {
234                 if (preg_match('/\/(\* XXXXXXXXX )(.*?)( XXXXXXXXX \*)\//', $lines[$i], $m)) {
235                     // we found it, add info to message
236                     $msg .= ' in ' . $m[2] . ' at line ' . ($lno - $i);
237                     break;
238                 }
239             }
240         }
241 
242         // something went wrong
243         $error = 'A fatal error occured during compilation of the CSS files. ' .
244             'If you recently installed a new plugin or template it ' .
245             'might be broken and you should try disabling it again. [' . $msg . ']';
246 
247         echo ".dokuwiki:before {
248             content: '$error';
249             background-color: red;
250             display: block;
251             background-color: #fcc;
252             border-color: #ebb;
253             color: #000;
254             padding: 0.5em;
255         }";
256 
257         exit;
258     }
259 }
260 
261 /**
262  * Does placeholder replacements in the style according to
263  * the ones defined in a templates style.ini file
264  *
265  * This also adds the ini defined placeholders as less variables
266  * (sans the surrounding __ and with a ini_ prefix)
267  *
268  * @param string $css
269  * @param array $replacements array(placeholder => value)
270  * @return string
271  *
272  * @author Andreas Gohr <andi@splitbrain.org>
273  */
274 function css_applystyle($css, $replacements)
275 {
276     // we convert ini replacements to LESS variable names
277     // and build a list of variable: value; pairs
278     $less = '';
279     foreach ((array)$replacements as $key => $value) {
280         $lkey = trim($key, '_');
281         $lkey = '@ini_' . $lkey;
282         $less .= "$lkey: $value;\n";
283 
284         $replacements[$key] = $lkey;
285     }
286 
287     // we now replace all old ini replacements with LESS variables
288     $css = strtr($css, $replacements);
289 
290     // now prepend the list of LESS variables as the very first thing
291     $css = $less . $css;
292     return $css;
293 }
294 
295 /**
296  * Wrapper for the files, content and mediatype for the event CSS_STYLES_INCLUDED
297  *
298  * @param string $mediatype type ofthe current media files/content set
299  * @param array $files set of files that define the current mediatype
300  * @return array
301  *
302  * @author Gerry Weißbach <gerry.w@gammaproduction.de>
303  */
304 function css_filewrapper($mediatype, $files = [])
305 {
306     return [
307         'files' => $files,
308         'mediatype' => $mediatype,
309         'encapsulate' => $mediatype != 'all',
310         'encapsulationPrefix' => '@media ' . $mediatype
311     ];
312 }
313 
314 /**
315  * Prints the @media encapsulated default styles of DokuWiki
316  *
317  * This function is being called by a CSS_STYLES_INCLUDED event
318  * The event can be distinguished by the mediatype which is:
319  *   DW_DEFAULT
320  *
321  * @author Gerry Weißbach <gerry.w@gammaproduction.de>
322  */
323 function css_defaultstyles()
324 {
325     // print the default classes for interwiki links and file downloads
326     echo '@media screen {';
327     css_interwiki();
328     css_filetypes();
329     echo '}';
330 }
331 
332 /**
333  * Prints classes for interwikilinks
334  *
335  * Interwiki links have two classes: 'interwiki' and 'iw_$name>' where
336  * $name is the identifier given in the config. All Interwiki links get
337  * an default style with a default icon. If a special icon is available
338  * for an interwiki URL it is set in it's own class. Both classes can be
339  * overwritten in the template or userstyles.
340  *
341  * @author Andreas Gohr <andi@splitbrain.org>
342  */
343 function css_interwiki()
344 {
345 
346     // default style
347     echo 'a.interwiki {';
348     echo ' background: transparent url(' . DOKU_BASE . 'lib/images/interwiki.svg) 0 0 no-repeat;';
349     echo ' background-size: 1.2em;';
350     echo ' padding: 0 0 0 1.4em;';
351     echo '}';
352 
353     // additional styles when icon available
354     $iwlinks = getInterwiki();
355     foreach (array_keys($iwlinks) as $iw) {
356         $class = preg_replace('/[^_\-a-z0-9]+/i', '_', $iw);
357         foreach (['svg', 'png', 'gif'] as $ext) {
358             $file = 'lib/images/interwiki/' . $iw . '.' . $ext;
359 
360             if (file_exists(DOKU_INC . $file)) {
361                 echo "a.iw_$class {";
362                 echo '  background-image: url(' . DOKU_BASE . $file . ')';
363                 echo '}';
364                 break;
365             }
366         }
367     }
368 }
369 
370 /**
371  * Prints classes for file download links
372  *
373  * @author Andreas Gohr <andi@splitbrain.org>
374  */
375 function css_filetypes()
376 {
377 
378     // default style
379     echo '.mediafile {';
380     echo ' background: transparent url(' . DOKU_BASE . 'lib/images/fileicons/svg/file.svg) 0px 1px no-repeat;';
381     echo ' background-size: 1.2em;';
382     echo ' padding-left: 1.5em;';
383     echo '}';
384 
385     // additional styles when icon available
386     // scan directory for all icons
387     $exts = [];
388     if ($dh = opendir(DOKU_INC . 'lib/images/fileicons/svg')) {
389         while (false !== ($file = readdir($dh))) {
390             if (preg_match('/(.*?)\.svg$/i', $file, $match)) {
391                 $exts[] = strtolower($match[1]);
392             }
393         }
394         closedir($dh);
395     }
396     foreach ($exts as $ext) {
397         $class = preg_replace('/[^_\-a-z0-9]+/', '_', $ext);
398         echo ".mf_$class {";
399         echo '  background-image: url(' . DOKU_BASE . 'lib/images/fileicons/svg/' . $ext . '.svg)';
400         echo '}';
401     }
402 }
403 
404 /**
405  * Loads a given file and fixes relative URLs with the
406  * given location prefix
407  *
408  * @param string $file file system path
409  * @param string $location
410  * @return string
411  */
412 function css_loadfile($file, $location = '')
413 {
414     $css_file = new DokuCssFile($file);
415     return $css_file->load($location);
416 }
417 
418 /**
419  * Helper class to abstract loading of css/less files
420  *
421  * @author Chris Smith <chris@jalakai.co.uk>
422  */
423 class DokuCssFile
424 {
425     protected $filepath;             // file system path to the CSS/Less file
426     protected $location;             // base url location of the CSS/Less file
427     protected $relative_path;
428 
429     public function __construct($file)
430     {
431         $this->filepath = $file;
432     }
433 
434     /**
435      * Load the contents of the css/less file and adjust any relative paths/urls (relative to this file) to be
436      * relative to the dokuwiki root: the web root (DOKU_BASE) for most files; the file system root (DOKU_INC)
437      * for less files.
438      *
439      * @param string $location base url for this file
440      * @return string the CSS/Less contents of the file
441      */
442     public function load($location = '')
443     {
444         if (!file_exists($this->filepath)) return '';
445 
446         $css = io_readFile($this->filepath);
447         if (!$location) return $css;
448 
449         $this->location = $location;
450 
451         $css = preg_replace_callback('#(url\( *)([\'"]?)(.*?)(\2)( *\))#', [$this, 'replacements'], $css);
452         $css = preg_replace_callback('#(@import\s+)([\'"])(.*?)(\2)#', [$this, 'replacements'], $css);
453 
454         return $css;
455     }
456 
457     /**
458      * Get the relative file system path of this file, relative to dokuwiki's root folder, DOKU_INC
459      *
460      * @return string   relative file system path
461      */
462     protected function getRelativePath()
463     {
464 
465         if (is_null($this->relative_path)) {
466             $basedir = [DOKU_INC];
467 
468             // during testing, files may be found relative to a second base dir, TMP_DIR
469             if (defined('DOKU_UNITTEST')) {
470                 $basedir[] = realpath(TMP_DIR);
471             }
472 
473             $basedir = array_map('preg_quote_cb', $basedir);
474             $regex = '/^(' . implode('|', $basedir) . ')/';
475             $this->relative_path = preg_replace($regex, '', dirname($this->filepath));
476         }
477 
478         return $this->relative_path;
479     }
480 
481     /**
482      * preg_replace callback to adjust relative urls from relative to this file to relative
483      * to the appropriate dokuwiki root location as described in the code
484      *
485      * @param array $match see http://php.net/preg_replace_callback
486      * @return string   see http://php.net/preg_replace_callback
487      */
488     public function replacements($match)
489     {
490 
491         if (preg_match('#^(/|data:|https?://)#', $match[3])) { // not a relative url? - no adjustment required
492             return $match[0];
493         } elseif (str_ends_with($match[3], '.less')) { // a less file import? - requires a file system location
494             if ($match[3][0] != '/') {
495                 $match[3] = $this->getRelativePath() . '/' . $match[3];
496             }
497         } else { // everything else requires a url adjustment
498             $match[3] = $this->location . $match[3];
499         }
500 
501         return implode('', array_slice($match, 1));
502     }
503 }
504 
505 /**
506  * Convert local image URLs to data URLs if the filesize is small
507  *
508  * Callback for preg_replace_callback
509  *
510  * @param array $match
511  * @return string
512  */
513 function css_datauri($match)
514 {
515     global $conf;
516 
517     $pre = unslash($match[1]);
518     $base = unslash($match[2]);
519     $url = unslash($match[3]);
520     $ext = unslash($match[4]);
521 
522     $local = DOKU_INC . $url;
523     $size = @filesize($local);
524     if ($size && $size < $conf['cssdatauri']) {
525         $data = base64_encode(file_get_contents($local));
526     }
527     if (!empty($data)) {
528         $url = 'data:image/' . $ext . ';base64,' . $data;
529     } else {
530         $url = $base . $url;
531     }
532     return $pre . $url;
533 }
534 
535 
536 /**
537  * Returns a list of possible Plugin Styles (no existance check here)
538  *
539  * @param string $mediatype
540  * @return array
541  * @author Andreas Gohr <andi@splitbrain.org>
542  *
543  */
544 function css_pluginstyles($mediatype = 'screen')
545 {
546     $list = [];
547     $plugins = plugin_list();
548     foreach ($plugins as $p) {
549         $list[DOKU_PLUGIN . "$p/$mediatype.css"] = DOKU_BASE . "lib/plugins/$p/";
550         $list[DOKU_PLUGIN . "$p/$mediatype.less"] = DOKU_BASE . "lib/plugins/$p/";
551         // alternative for screen.css
552         if ($mediatype == 'screen') {
553             $list[DOKU_PLUGIN . "$p/style.css"] = DOKU_BASE . "lib/plugins/$p/";
554             $list[DOKU_PLUGIN . "$p/style.less"] = DOKU_BASE . "lib/plugins/$p/";
555         }
556     }
557     return $list;
558 }
559 
560 /**
561  * Very simple CSS optimizer
562  *
563  * @param string $css
564  * @return string
565  * @author Andreas Gohr <andi@splitbrain.org>
566  *
567  */
568 function css_compress($css)
569 {
570     // replace quoted strings with placeholder
571     $quote_storage = [];
572 
573     $quote_cb = function ($match) use (&$quote_storage) {
574         $quote_storage[] = $match[0];
575         return '"STR' . (count($quote_storage) - 1) . '"';
576     };
577 
578     $css = preg_replace_callback('/(([\'"]).*?(?<!\\\\)\2)/', $quote_cb, $css);
579 
580     // strip comments through a callback
581     $css = preg_replace_callback('#(/\*)(.*?)(\*/)#s', 'css_comment_cb', $css);
582 
583     // strip (incorrect but common) one line comments
584     $css = preg_replace_callback('/^.*\/\/.*$/m', 'css_onelinecomment_cb', $css);
585 
586     // strip whitespaces
587     $css = preg_replace('![\r\n\t ]+!', ' ', $css);
588     $css = preg_replace('/ ?([;,{}\/]) ?/', '\\1', $css);
589     $css = preg_replace('/ ?: /', ':', $css);
590 
591     // number compression
592     $css = preg_replace(
593         '/([: ])0+(\.\d+?)0*((?:pt|pc|in|mm|cm|em|ex|px)\b|%)(?=[^\{]*[;\}])/',
594         '$1$2$3',
595         $css
596     ); // "0.1em" to ".1em", "1.10em" to "1.1em"
597     $css = preg_replace(
598         '/([: ])\.(0)+((?:pt|pc|in|mm|cm|em|ex|px)\b|%)(?=[^\{]*[;\}])/',
599         '$1$2',
600         $css
601     ); // ".0em" to "0"
602     $css = preg_replace(
603         '/([: ]0)0*(\.0*)?((?:pt|pc|in|mm|cm|em|ex|px)(?=[^\{]*[;\}])\b|%)/',
604         '$1',
605         $css
606     ); // "0.0em" to "0"
607     $css = preg_replace(
608         '/([: ]\d+)(\.0*)((?:pt|pc|in|mm|cm|em|ex|px)(?=[^\{]*[;\}])\b|%)/',
609         '$1$3',
610         $css
611     ); // "1.0em" to "1em"
612     $css = preg_replace(
613         '/([: ])0+(\d+|\d*\.\d+)((?:pt|pc|in|mm|cm|em|ex|px)(?=[^\{]*[;\}])\b|%)/',
614         '$1$2$3',
615         $css
616     ); // "001em" to "1em"
617 
618     // shorten attributes (1em 1em 1em 1em -> 1em)
619     $css = preg_replace(
620         '/(?<![\w\-])((?:margin|padding|border|border-(?:width|radius)):)([\w\.]+)( \2)+(?=[;\}]| !)/',
621         '$1$2',
622         $css
623     ); // "1em 1em 1em 1em" to "1em"
624     $css = preg_replace(
625         '/(?<![\w\-])((?:margin|padding|border|border-(?:width)):)([\w\.]+) ([\w\.]+) \2 \3(?=[;\}]| !)/',
626         '$1$2 $3',
627         $css
628     ); // "1em 2em 1em 2em" to "1em 2em"
629 
630     // shorten colors
631     $css = preg_replace(
632         "/#([0-9a-fA-F]{1})\\1([0-9a-fA-F]{1})\\2([0-9a-fA-F]{1})\\3(?=[^\{]*[;\}])/",
633         "#\\1\\2\\3",
634         $css
635     );
636 
637     // replace back protected strings
638     $quote_back_cb = function ($match) use (&$quote_storage) {
639         return $quote_storage[$match[1]];
640     };
641 
642     $css = preg_replace_callback('/"STR(\d+)"/', $quote_back_cb, $css);
643     $css = trim($css);
644 
645     return $css;
646 }
647 
648 /**
649  * Callback for css_compress()
650  *
651  * Keeps short comments (< 5 chars) to maintain typical browser hacks
652  *
653  * @param array $matches
654  * @return string
655  *
656  * @author Andreas Gohr <andi@splitbrain.org>
657  *
658  */
659 function css_comment_cb($matches)
660 {
661     if (strlen($matches[2]) > 4) return '';
662     return $matches[0];
663 }
664 
665 /**
666  * Callback for css_compress()
667  *
668  * Strips one line comments but makes sure it will not destroy url() constructs with slashes
669  *
670  * @param array $matches
671  * @return string
672  */
673 function css_onelinecomment_cb($matches)
674 {
675     $line = $matches[0];
676 
677     $i = 0;
678     $len = strlen($line);
679 
680     while ($i < $len) {
681         $nextcom = strpos($line, '//', $i);
682         $nexturl = stripos($line, 'url(', $i);
683 
684         if ($nextcom === false) {
685             // no more comments, we're done
686             $i = $len;
687             break;
688         }
689 
690         if ($nexturl === false || $nextcom < $nexturl) {
691             // no url anymore, strip comment and be done
692             $i = $nextcom;
693             break;
694         }
695 
696         // we have an upcoming url
697         $i = strpos($line, ')', $nexturl);
698     }
699 
700     return substr($line, 0, $i);
701 }
702 
703 //Setup VIM: ex: et ts=4 :
704