3 * DokuWiki StyleSheet creator
5 * @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
6 * @author Andreas Gohr <andi@splitbrain.org>
8 use dokuwiki\StyleUtils
;
9 use dokuwiki\Cache\Cache
;
10 use dokuwiki\Extension\Event
;
12 if(!defined('DOKU_INC')) define('DOKU_INC', __DIR__
.'/../../');
13 if(!defined('NOSESSION')) define('NOSESSION',true); // we do not use a session or authentication here (better caching)
14 if(!defined('DOKU_DISABLE_GZIP_OUTPUT')) define('DOKU_DISABLE_GZIP_OUTPUT',1); // we gzip ourself here
15 if(!defined('NL')) define('NL',"\n");
16 require_once(DOKU_INC
.'inc/init.php');
18 // Main (don't run when UNIT test)
19 if(!defined('SIMPLE_TEST')){
20 header('Content-Type: text/css; charset=utf-8');
25 // ---------------------- functions ------------------------------
28 * Output all needed Styles
30 * @author Andreas Gohr <andi@splitbrain.org>
35 global $config_cascade;
38 if ($INPUT->str('s') == 'feed') {
39 $mediatypes = ['feed'];
42 $mediatypes = ['screen', 'all', 'print', 'speech'];
46 // decide from where to get the template
47 $tpl = trim(preg_replace('/[^\w-]+/','',$INPUT->str('t')));
48 if(!$tpl) $tpl = $conf['template'];
51 $styleUtil = new StyleUtils($tpl, $INPUT->bool('preview'));
52 $styleini = $styleUtil->cssStyleini();
55 $tplinc = tpl_incdir($tpl);
56 $cache_files = getConfigFiles('main');
57 $cache_files[] = $tplinc.'style.ini';
58 $cache_files[] = DOKU_CONF
."tpl/$tpl/style.ini";
59 $cache_files[] = __FILE__
;
60 if($INPUT->bool('preview')) $cache_files[] = $conf['cachedir'].'/preview.ini';
62 // Array of needed files and their web locations, the latter ones
63 // are needed to fix relative paths in the stylesheets
65 foreach($mediatypes as $mediatype) {
69 $files[DOKU_INC
.'lib/styles/'.$mediatype.'.css'] = DOKU_BASE
.'lib/styles/';
71 // load jQuery-UI theme
72 if ($mediatype == 'screen') {
73 $files[DOKU_INC
.'lib/scripts/jquery/jquery-ui-theme/smoothness.css'] =
74 DOKU_BASE
.'lib/scripts/jquery/jquery-ui-theme/';
77 $files = array_merge($files, css_pluginstyles($mediatype));
78 // load template styles
79 if (isset($styleini['stylesheets'][$mediatype])) {
80 $files = array_merge($files, $styleini['stylesheets'][$mediatype]);
83 if(isset($config_cascade['userstyle'][$mediatype]) && is_array($config_cascade['userstyle'][$mediatype])) {
84 foreach($config_cascade['userstyle'][$mediatype] as $userstyle) {
85 $files[$userstyle] = DOKU_BASE
;
89 // Let plugins decide to either put more styles here or to remove some
90 $media_files[$mediatype] = css_filewrapper($mediatype, $files);
91 $CSSEvt = new Event('CSS_STYLES_INCLUDED', $media_files[$mediatype]);
93 // Make it preventable.
94 if ( $CSSEvt->advise_before() ) {
95 $cache_files = array_merge($cache_files, array_keys($media_files[$mediatype]['files']));
97 // unset if prevented. Nothing will be printed for this mediatype.
98 unset($media_files[$mediatype]);
102 $CSSEvt->advise_after();
105 // The generated script depends on some dynamic options
108 $_SERVER['HTTP_HOST'] .
109 $_SERVER['SERVER_PORT'] .
110 $INPUT->bool('preview') .
116 $cache->setEvent('CSS_CACHE_USE');
118 // check cache age & handle conditional request
119 // This may exit if a cache can be used
120 $cache_ok = $cache->useCache(['files' => $cache_files]);
121 http_cached($cache->cache
, $cache_ok);
123 // start output buffering
126 // Fire CSS_STYLES_INCLUDED for one last time to let the
127 // plugins decide whether to include the DW default styles.
128 // This can be done by preventing the Default.
129 $media_files['DW_DEFAULT'] = css_filewrapper('DW_DEFAULT');
130 Event
::createAndTrigger('CSS_STYLES_INCLUDED', $media_files['DW_DEFAULT'], 'css_defaultstyles');
132 // build the stylesheet
133 foreach ($mediatypes as $mediatype) {
135 // Check if there is a wrapper set for this type.
136 if ( !isset($media_files[$mediatype]) ) {
140 $cssData = $media_files[$mediatype];
144 if ( $cssData['encapsulate'] === true ) print $cssData['encapsulationPrefix'] . ' {';
145 print '/* START '.$cssData['mediatype'].' styles */'.NL
;
148 foreach($cssData['files'] as $file => $location){
149 $display = str_replace(fullpath(DOKU_INC
), '', fullpath($file));
150 print "\n/* XXXXXXXXX $display XXXXXXXXX */\n";
151 print css_loadfile($file, $location);
155 if ( $cssData['encapsulate'] === true ) print '} /* /@media ';
157 print ' END '.$cssData['mediatype'].' styles */'.NL
;
160 // end output buffering and get contents
161 $css = ob_get_contents();
164 // strip any source maps
165 stripsourcemaps($css);
167 // apply style replacements
168 $css = css_applystyle($css, $styleini['replacements']);
171 $css = css_parseless($css);
173 // compress whitespace and comments
174 if($conf['compress']){
175 $css = css_compress($css);
178 // embed small images right into the stylesheet
179 if($conf['cssdatauri']){
180 $base = preg_quote(DOKU_BASE
,'#');
181 $css = preg_replace_callback('#(url\([ \'"]*)('.$base.')(.*?(?:\.(png|gif)))#i','css_datauri',$css);
184 http_cached_finish($cache->cache
, $css);
188 * Uses phpless to parse LESS in our CSS
190 * most of this function is error handling to show a nice useful error when
191 * LESS compilation fails
196 function css_parseless($css) {
200 $less->importDir
= [DOKU_INC
];
201 $less->setPreserveComments(!$conf['compress']);
203 if (defined('DOKU_UNITTEST')){
204 $less->importDir
[] = TMP_DIR
;
208 return $less->compile($css);
209 } catch(Exception
$e) {
210 // get exception message
211 $msg = str_replace(["\n", "\r", "'"], [], $e->getMessage());
213 // try to use line number to find affected file
214 if(preg_match('/line: (\d+)$/', $msg, $m)){
215 $msg = substr($msg, 0, -1* strlen($m[0])); //remove useless linenumber
218 // walk upwards to last include
219 $lines = explode("\n", $css);
220 for($i=$lno-1; $i>=0; $i--){
221 if(preg_match('/\/(\* XXXXXXXXX )(.*?)( XXXXXXXXX \*)\//', $lines[$i], $m)){
222 // we found it, add info to message
223 $msg .= ' in '.$m[2].' at line '.($lno-$i);
229 // something went wrong
230 $error = 'A fatal error occured during compilation of the CSS files. '.
231 'If you recently installed a new plugin or template it '.
232 'might be broken and you should try disabling it again. ['.$msg.']';
234 echo ".dokuwiki:before {
236 background-color: red;
238 background-color: #fcc;
249 * Does placeholder replacements in the style according to
250 * the ones defined in a templates style.ini file
252 * This also adds the ini defined placeholders as less variables
253 * (sans the surrounding __ and with a ini_ prefix)
255 * @author Andreas Gohr <andi@splitbrain.org>
258 * @param array $replacements array(placeholder => value)
261 function css_applystyle($css, $replacements) {
262 // we convert ini replacements to LESS variable names
263 // and build a list of variable: value; pairs
265 foreach((array) $replacements as $key => $value) {
266 $lkey = trim($key, '_');
267 $lkey = '@ini_'.$lkey;
268 $less .= "$lkey: $value;\n";
270 $replacements[$key] = $lkey;
273 // we now replace all old ini replacements with LESS variables
274 $css = strtr($css, $replacements);
276 // now prepend the list of LESS variables as the very first thing
282 * Wrapper for the files, content and mediatype for the event CSS_STYLES_INCLUDED
284 * @author Gerry Weißbach <gerry.w@gammaproduction.de>
286 * @param string $mediatype type ofthe current media files/content set
287 * @param array $files set of files that define the current mediatype
290 function css_filewrapper($mediatype, $files=[]){
293 'mediatype' => $mediatype,
294 'encapsulate' => $mediatype != 'all',
295 'encapsulationPrefix' => '@media '.$mediatype
300 * Prints the @media encapsulated default styles of DokuWiki
302 * @author Gerry Weißbach <gerry.w@gammaproduction.de>
304 * This function is being called by a CSS_STYLES_INCLUDED event
305 * The event can be distinguished by the mediatype which is:
308 function css_defaultstyles(){
309 // print the default classes for interwiki links and file downloads
310 print '@media screen {';
317 * Prints classes for interwikilinks
319 * Interwiki links have two classes: 'interwiki' and 'iw_$name>' where
320 * $name is the identifier given in the config. All Interwiki links get
321 * an default style with a default icon. If a special icon is available
322 * for an interwiki URL it is set in it's own class. Both classes can be
323 * overwritten in the template or userstyles.
325 * @author Andreas Gohr <andi@splitbrain.org>
327 function css_interwiki(){
330 echo 'a.interwiki {';
331 echo ' background: transparent url('.DOKU_BASE
.'lib/images/interwiki.svg) 0 0 no-repeat;';
332 echo ' background-size: 1.2em;';
333 echo ' padding: 0 0 0 1.4em;';
336 // additional styles when icon available
337 $iwlinks = getInterwiki();
338 foreach (array_keys($iwlinks) as $iw) {
339 $class = preg_replace('/[^_\-a-z0-9]+/i', '_', $iw);
340 foreach (['svg', 'png', 'gif'] as $ext) {
341 $file = 'lib/images/interwiki/' . $iw . '.' . $ext;
343 if (file_exists(DOKU_INC
. $file)) {
344 echo "a.iw_$class {";
345 echo ' background-image: url(' . DOKU_BASE
. $file . ')';
354 * Prints classes for file download links
356 * @author Andreas Gohr <andi@splitbrain.org>
358 function css_filetypes(){
362 echo ' background: transparent url('.DOKU_BASE
.'lib/images/fileicons/svg/file.svg) 0px 1px no-repeat;';
363 echo ' background-size: 1.2em;';
364 echo ' padding-left: 1.5em;';
367 // additional styles when icon available
368 // scan directory for all icons
370 if($dh = opendir(DOKU_INC
.'lib/images/fileicons/svg')){
371 while(false !== ($file = readdir($dh))){
372 if(preg_match('/(.*?)\.svg$/i',$file, $match)){
373 $exts[] = strtolower($match[1]);
378 foreach($exts as $ext){
379 $class = preg_replace('/[^_\-a-z0-9]+/','_',$ext);
381 echo ' background-image: url('.DOKU_BASE
.'lib/images/fileicons/svg/'.$ext.'.svg)';
387 * Loads a given file and fixes relative URLs with the
388 * given location prefix
390 * @param string $file file system path
391 * @param string $location
394 function css_loadfile($file,$location=''){
395 $css_file = new DokuCssFile($file);
396 return $css_file->load($location);
400 * Helper class to abstract loading of css/less files
402 * @author Chris Smith <chris@jalakai.co.uk>
406 protected $filepath; // file system path to the CSS/Less file
407 protected $location; // base url location of the CSS/Less file
408 protected $relative_path;
410 public function __construct($file) {
411 $this->filepath
= $file;
415 * Load the contents of the css/less file and adjust any relative paths/urls (relative to this file) to be
416 * relative to the dokuwiki root: the web root (DOKU_BASE) for most files; the file system root (DOKU_INC)
419 * @param string $location base url for this file
420 * @return string the CSS/Less contents of the file
422 public function load($location='') {
423 if (!file_exists($this->filepath
)) return '';
425 $css = io_readFile($this->filepath
);
426 if (!$location) return $css;
428 $this->location
= $location;
430 $css = preg_replace_callback('#(url\( *)([\'"]?)(.*?)(\2)( *\))#',[$this, 'replacements'],$css);
431 $css = preg_replace_callback('#(@import\s+)([\'"])(.*?)(\2)#',[$this, 'replacements'],$css);
437 * Get the relative file system path of this file, relative to dokuwiki's root folder, DOKU_INC
439 * @return string relative file system path
441 protected function getRelativePath(){
443 if (is_null($this->relative_path
)) {
444 $basedir = [DOKU_INC
];
446 // during testing, files may be found relative to a second base dir, TMP_DIR
447 if (defined('DOKU_UNITTEST')) {
448 $basedir[] = realpath(TMP_DIR
);
451 $basedir = array_map('preg_quote_cb', $basedir);
452 $regex = '/^('.implode('|',$basedir).')/';
453 $this->relative_path
= preg_replace($regex, '', dirname($this->filepath
));
456 return $this->relative_path
;
460 * preg_replace callback to adjust relative urls from relative to this file to relative
461 * to the appropriate dokuwiki root location as described in the code
463 * @param array see http://php.net/preg_replace_callback
464 * @return string see http://php.net/preg_replace_callback
466 public function replacements($match) {
468 if (preg_match('#^(/|data:|https?://)#', $match[3])) { // not a relative url? - no adjustment required
470 } elseif (substr($match[3], -5) == '.less') { // a less file import? - requires a file system location
471 if ($match[3][0] != '/') {
472 $match[3] = $this->getRelativePath() . '/' . $match[3];
474 } else { // everything else requires a url adjustment
475 $match[3] = $this->location
. $match[3];
478 return implode('',array_slice($match,1));
483 * Convert local image URLs to data URLs if the filesize is small
485 * Callback for preg_replace_callback
487 * @param array $match
490 function css_datauri($match){
493 $pre = unslash($match[1]);
494 $base = unslash($match[2]);
495 $url = unslash($match[3]);
496 $ext = unslash($match[4]);
498 $local = DOKU_INC
.$url;
499 $size = @filesize
($local);
500 if($size && $size < $conf['cssdatauri']){
501 $data = base64_encode(file_get_contents($local));
504 $url = 'data:image/'.$ext.';base64,'.$data;
513 * Returns a list of possible Plugin Styles (no existance check here)
515 * @author Andreas Gohr <andi@splitbrain.org>
517 * @param string $mediatype
520 function css_pluginstyles($mediatype='screen'){
522 $plugins = plugin_list();
523 foreach ($plugins as $p){
524 $list[DOKU_PLUGIN
."$p/$mediatype.css"] = DOKU_BASE
."lib/plugins/$p/";
525 $list[DOKU_PLUGIN
."$p/$mediatype.less"] = DOKU_BASE
."lib/plugins/$p/";
526 // alternative for screen.css
527 if ($mediatype=='screen') {
528 $list[DOKU_PLUGIN
."$p/style.css"] = DOKU_BASE
."lib/plugins/$p/";
529 $list[DOKU_PLUGIN
."$p/style.less"] = DOKU_BASE
."lib/plugins/$p/";
536 * Very simple CSS optimizer
538 * @author Andreas Gohr <andi@splitbrain.org>
543 function css_compress($css){
544 // replace quoted strings with placeholder
547 $quote_cb = function ($match) use (&$quote_storage) {
548 $quote_storage[] = $match[0];
549 return '"STR'.(count($quote_storage)-1).'"';
552 $css = preg_replace_callback('/(([\'"]).*?(?<!\\\\)\2)/', $quote_cb, $css);
554 // strip comments through a callback
555 $css = preg_replace_callback('#(/\*)(.*?)(\*/)#s','css_comment_cb',$css);
557 // strip (incorrect but common) one line comments
558 $css = preg_replace_callback('/^.*\/\/.*$/m','css_onelinecomment_cb',$css);
561 $css = preg_replace('![\r\n\t ]+!',' ',$css);
562 $css = preg_replace('/ ?([;,{}\/]) ?/','\\1',$css);
563 $css = preg_replace('/ ?: /',':',$css);
565 // number compression
567 '/([: ])0+(\.\d+?)0*((?:pt|pc|in|mm|cm|em|ex|px)\b|%)(?=[^\{]*[;\}])/',
570 ); // "0.1em" to ".1em", "1.10em" to "1.1em"
572 '/([: ])\.(0)+((?:pt|pc|in|mm|cm|em|ex|px)\b|%)(?=[^\{]*[;\}])/',
577 '/([: ]0)0*(\.0*)?((?:pt|pc|in|mm|cm|em|ex|px)(?=[^\{]*[;\}])\b|%)/',
582 '/([: ]\d+)(\.0*)((?:pt|pc|in|mm|cm|em|ex|px)(?=[^\{]*[;\}])\b|%)/',
585 ); // "1.0em" to "1em"
587 '/([: ])0+(\d+|\d*\.\d+)((?:pt|pc|in|mm|cm|em|ex|px)(?=[^\{]*[;\}])\b|%)/',
590 ); // "001em" to "1em"
592 // shorten attributes (1em 1em 1em 1em -> 1em)
594 '/(?<![\w\-])((?:margin|padding|border|border-(?:width|radius)):)([\w\.]+)( \2)+(?=[;\}]| !)/',
597 ); // "1em 1em 1em 1em" to "1em"
599 '/(?<![\w\-])((?:margin|padding|border|border-(?:width)):)([\w\.]+) ([\w\.]+) \2 \3(?=[;\}]| !)/',
602 ); // "1em 2em 1em 2em" to "1em 2em"
606 "/#([0-9a-fA-F]{1})\\1([0-9a-fA-F]{1})\\2([0-9a-fA-F]{1})\\3(?=[^\{]*[;\}])/",
611 // replace back protected strings
612 $quote_back_cb = function ($match) use (&$quote_storage) {
613 return $quote_storage[$match[1]];
616 $css = preg_replace_callback('/"STR(\d+)"/', $quote_back_cb, $css);
623 * Callback for css_compress()
625 * Keeps short comments (< 5 chars) to maintain typical browser hacks
627 * @author Andreas Gohr <andi@splitbrain.org>
629 * @param array $matches
632 function css_comment_cb($matches){
633 if(strlen($matches[2]) > 4) return '';
638 * Callback for css_compress()
640 * Strips one line comments but makes sure it will not destroy url() constructs with slashes
642 * @param array $matches
645 function css_onelinecomment_cb($matches) {
649 $len = strlen($line);
652 $nextcom = strpos($line, '//', $i);
653 $nexturl = stripos($line, 'url(', $i);
655 if($nextcom === false) {
656 // no more comments, we're done
661 if($nexturl === false ||
$nextcom < $nexturl) {
662 // no url anymore, strip comment and be done
667 // we have an upcoming url
668 $i = strpos($line, ')', $nexturl);
671 return substr($line, 0, $i);
674 //Setup VIM: ex: et ts=4 :