1<?php 2/** 3 * DokuWiki StyleSheet creator 4 * 5 * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) 6 * @author Andreas Gohr <andi@splitbrain.org> 7 */ 8 9if(!defined('DOKU_INC')) define('DOKU_INC',dirname(__FILE__).'/../../'); 10if(!defined('NOSESSION')) define('NOSESSION',true); // we do not use a session or authentication here (better caching) 11if(!defined('DOKU_DISABLE_GZIP_OUTPUT')) define('DOKU_DISABLE_GZIP_OUTPUT',1); // we gzip ourself here 12if(!defined('NL')) define('NL',"\n"); 13require_once(DOKU_INC.'inc/init.php'); 14 15// Main (don't run when UNIT test) 16if(!defined('SIMPLE_TEST')){ 17 header('Content-Type: text/css; charset=utf-8'); 18 css_out(); 19} 20 21 22// ---------------------- functions ------------------------------ 23 24/** 25 * Output all needed Styles 26 * 27 * @author Andreas Gohr <andi@splitbrain.org> 28 */ 29function css_out(){ 30 global $conf; 31 global $lang; 32 global $config_cascade; 33 global $INPUT; 34 35 if ($INPUT->str('s') == 'feed') { 36 $mediatypes = array('feed'); 37 $type = 'feed'; 38 } else { 39 $mediatypes = array('screen', 'all', 'print'); 40 $type = ''; 41 } 42 43 // decide from where to get the template 44 $tpl = trim(preg_replace('/[^\w-]+/','',$INPUT->str('t'))); 45 if(!$tpl) $tpl = $conf['template']; 46 47 // The generated script depends on some dynamic options 48 $cache = new cache('styles'.$_SERVER['HTTP_HOST'].$_SERVER['SERVER_PORT'].DOKU_BASE.$tpl.$type,'.css'); 49 50 // load styl.ini 51 $styleini = css_styleini($tpl); 52 53 // if old 'default' userstyle setting exists, make it 'screen' userstyle for backwards compatibility 54 if (isset($config_cascade['userstyle']['default'])) { 55 $config_cascade['userstyle']['screen'] = $config_cascade['userstyle']['default']; 56 } 57 58 // cache influencers 59 $tplinc = tpl_basedir($tpl); 60 $cache_files = getConfigFiles('main'); 61 $cache_files[] = $tplinc.'style.ini'; 62 $cache_files[] = $tplinc.'style.local.ini'; // @deprecated 63 $cache_files[] = DOKU_CONF."tpl/$tpl/style.ini"; 64 $cache_files[] = __FILE__; 65 66 // Array of needed files and their web locations, the latter ones 67 // are needed to fix relative paths in the stylesheets 68 $files = array(); 69 foreach($mediatypes as $mediatype) { 70 $files[$mediatype] = array(); 71 // load core styles 72 $files[$mediatype][DOKU_INC.'lib/styles/'.$mediatype.'.css'] = DOKU_BASE.'lib/styles/'; 73 // load jQuery-UI theme 74 if ($mediatype == 'screen') { 75 $files[$mediatype][DOKU_INC.'lib/scripts/jquery/jquery-ui-theme/smoothness.css'] = DOKU_BASE.'lib/scripts/jquery/jquery-ui-theme/'; 76 } 77 // load plugin styles 78 $files[$mediatype] = array_merge($files[$mediatype], css_pluginstyles($mediatype)); 79 // load template styles 80 if (isset($styleini['stylesheets'][$mediatype])) { 81 $files[$mediatype] = array_merge($files[$mediatype], $styleini['stylesheets'][$mediatype]); 82 } 83 // load user styles 84 if(isset($config_cascade['userstyle'][$mediatype])){ 85 $files[$mediatype][$config_cascade['userstyle'][$mediatype]] = DOKU_BASE; 86 } 87 88 $cache_files = array_merge($cache_files, array_keys($files[$mediatype])); 89 } 90 91 // check cache age & handle conditional request 92 // This may exit if a cache can be used 93 http_cached($cache->cache, 94 $cache->useCache(array('files' => $cache_files))); 95 96 // start output buffering 97 ob_start(); 98 99 // build the stylesheet 100 foreach ($mediatypes as $mediatype) { 101 102 // print the default classes for interwiki links and file downloads 103 if ($mediatype == 'screen') { 104 print '@media screen {'; 105 css_interwiki(); 106 css_filetypes(); 107 print '}'; 108 } 109 110 // load files 111 $css_content = ''; 112 foreach($files[$mediatype] as $file => $location){ 113 $display = str_replace(fullpath(DOKU_INC), '', fullpath($file)); 114 $css_content .= "\n/* XXXXXXXXX $display XXXXXXXXX */\n"; 115 $css_content .= css_loadfile($file, $location); 116 } 117 switch ($mediatype) { 118 case 'screen': 119 print NL.'@media screen { /* START screen styles */'.NL.$css_content.NL.'} /* /@media END screen styles */'.NL; 120 break; 121 case 'print': 122 print NL.'@media print { /* START print styles */'.NL.$css_content.NL.'} /* /@media END print styles */'.NL; 123 break; 124 case 'all': 125 case 'feed': 126 default: 127 print NL.'/* START rest styles */ '.NL.$css_content.NL.'/* END rest styles */'.NL; 128 break; 129 } 130 } 131 // end output buffering and get contents 132 $css = ob_get_contents(); 133 ob_end_clean(); 134 135 // apply style replacements 136 $css = css_applystyle($css, $styleini['replacements']); 137 138 // parse less 139 $css = css_parseless($css); 140 141 // compress whitespace and comments 142 if($conf['compress']){ 143 $css = css_compress($css); 144 } 145 146 // embed small images right into the stylesheet 147 if($conf['cssdatauri']){ 148 $base = preg_quote(DOKU_BASE,'#'); 149 $css = preg_replace_callback('#(url\([ \'"]*)('.$base.')(.*?(?:\.(png|gif)))#i','css_datauri',$css); 150 } 151 152 http_cached_finish($cache->cache, $css); 153} 154 155/** 156 * Uses phpless to parse LESS in our CSS 157 * 158 * most of this function is error handling to show a nice useful error when 159 * LESS compilation fails 160 * 161 * @param $css 162 * @return string 163 */ 164function css_parseless($css) { 165 $less = new lessc(); 166 try { 167 return $less->compile($css); 168 } catch(Exception $e) { 169 // get exception message 170 $msg = str_replace(array("\n", "\r", "'"), array(), $e->getMessage()); 171 172 // try to use line number to find affected file 173 if(preg_match('/line: (\d+)$/', $msg, $m)){ 174 $msg = substr($msg, 0, -1* strlen($m[0])); //remove useless linenumber 175 $lno = $m[1]; 176 177 // walk upwards to last include 178 $lines = explode("\n", $css); 179 for($i=$lno-1; $i>=0; $i--){ 180 if(preg_match('/\/(\* XXXXXXXXX )(.*?)( XXXXXXXXX \*)\//', $lines[$i], $m)){ 181 // we found it, add info to message 182 $msg .= ' in '.$m[2].' at line '.($lno-$i); 183 break; 184 } 185 } 186 } 187 188 // something went wrong 189 $error = 'A fatal error occured during compilation of the CSS files. '. 190 'If you recently installed a new plugin or template it '. 191 'might be broken and you should try disabling it again. ['.$msg.']'; 192 193 echo ".dokuwiki:before { 194 content: '$error'; 195 background-color: red; 196 display: block; 197 background-color: #fcc; 198 border-color: #ebb; 199 color: #000; 200 padding: 0.5em; 201 }"; 202 203 exit; 204 } 205} 206 207/** 208 * Does placeholder replacements in the style according to 209 * the ones defined in a templates style.ini file 210 * 211 * This also adds the ini defined placeholders as less variables 212 * (sans the surrounding __ and with a ini_ prefix) 213 * 214 * @author Andreas Gohr <andi@splitbrain.org> 215 */ 216function css_applystyle($css, $replacements) { 217 // we convert ini replacements to LESS variable names 218 // and build a list of variable: value; pairs 219 $less = ''; 220 foreach((array) $replacements as $key => $value) { 221 $lkey = trim($key, '_'); 222 $lkey = '@ini_'.$lkey; 223 $less .= "$lkey: $value;\n"; 224 225 $replacements[$key] = $lkey; 226 } 227 228 // we now replace all old ini replacements with LESS variables 229 $css = strtr($css, $replacements); 230 231 // now prepend the list of LESS variables as the very first thing 232 $css = $less.$css; 233 return $css; 234} 235 236/** 237 * Load style ini contents 238 * 239 * Loads and merges style.ini files from template and config and prepares 240 * the stylesheet modes 241 * 242 * @author Andreas Gohr <andi@splitbrain.org> 243 * @param string $tpl the used template 244 * @return array with keys 'stylesheets' and 'replacements' 245 */ 246function css_styleini($tpl) { 247 $stylesheets = array(); // mode, file => base 248 $replacements = array(); // placeholder => value 249 250 // load template's style.ini 251 $incbase = tpl_incdir($tpl); 252 $webbase = tpl_basedir($tpl); 253 $ini = $incbase.'style.ini'; 254 if(file_exists($ini)){ 255 $data = parse_ini_file($ini, true); 256 257 // stylesheets 258 if(is_array($data['stylesheets'])) foreach($data['stylesheets'] as $file => $mode){ 259 $stylesheets[$mode][$incbase.$file] = $webbase; 260 } 261 262 // replacements 263 if(is_array($data['replacements'])){ 264 $replacements = array_merge($replacements, $data['replacements']); 265 } 266 } 267 268 // load template's style.local.ini 269 // @deprecated 2013-08-03 270 $ini = $incbase.'style.local.ini'; 271 if(file_exists($ini)){ 272 $data = parse_ini_file($ini, true); 273 274 // stylesheets 275 if(is_array($data['stylesheets'])) foreach($data['stylesheets'] as $file => $mode){ 276 $stylesheets[$mode][$incbase.$file] = $webbase; 277 } 278 279 // replacements 280 if(is_array($data['replacements'])){ 281 $replacements = array_merge($replacements, $data['replacements']); 282 } 283 } 284 285 // load configs's style.ini 286 $webbase = DOKU_BASE; 287 $ini = DOKU_CONF."tpl/$tpl/style.ini"; 288 $incbase = dirname($ini).'/'; 289 if(file_exists($ini)){ 290 $data = parse_ini_file($ini, true); 291 292 // stylesheets 293 if(is_array($data['stylesheets'])) foreach($data['stylesheets'] as $file => $mode){ 294 $stylesheets[$mode][$incbase.$file] = $webbase; 295 } 296 297 // replacements 298 if(is_array($data['replacements'])){ 299 $replacements = array_merge($replacements, $data['replacements']); 300 } 301 } 302 303 return array( 304 'stylesheets' => $stylesheets, 305 'replacements' => $replacements 306 ); 307} 308 309/** 310 * Prints classes for interwikilinks 311 * 312 * Interwiki links have two classes: 'interwiki' and 'iw_$name>' where 313 * $name is the identifier given in the config. All Interwiki links get 314 * an default style with a default icon. If a special icon is available 315 * for an interwiki URL it is set in it's own class. Both classes can be 316 * overwritten in the template or userstyles. 317 * 318 * @author Andreas Gohr <andi@splitbrain.org> 319 */ 320function css_interwiki(){ 321 322 // default style 323 echo 'a.interwiki {'; 324 echo ' background: transparent url('.DOKU_BASE.'lib/images/interwiki.png) 0px 1px no-repeat;'; 325 echo ' padding: 1px 0px 1px 16px;'; 326 echo '}'; 327 328 // additional styles when icon available 329 $iwlinks = getInterwiki(); 330 foreach(array_keys($iwlinks) as $iw){ 331 $class = preg_replace('/[^_\-a-z0-9]+/i','_',$iw); 332 if(@file_exists(DOKU_INC.'lib/images/interwiki/'.$iw.'.png')){ 333 echo "a.iw_$class {"; 334 echo ' background-image: url('.DOKU_BASE.'lib/images/interwiki/'.$iw.'.png)'; 335 echo '}'; 336 }elseif(@file_exists(DOKU_INC.'lib/images/interwiki/'.$iw.'.gif')){ 337 echo "a.iw_$class {"; 338 echo ' background-image: url('.DOKU_BASE.'lib/images/interwiki/'.$iw.'.gif)'; 339 echo '}'; 340 } 341 } 342} 343 344/** 345 * Prints classes for file download links 346 * 347 * @author Andreas Gohr <andi@splitbrain.org> 348 */ 349function css_filetypes(){ 350 351 // default style 352 echo '.mediafile {'; 353 echo ' background: transparent url('.DOKU_BASE.'lib/images/fileicons/file.png) 0px 1px no-repeat;'; 354 echo ' padding-left: 18px;'; 355 echo ' padding-bottom: 1px;'; 356 echo '}'; 357 358 // additional styles when icon available 359 // scan directory for all icons 360 $exts = array(); 361 if($dh = opendir(DOKU_INC.'lib/images/fileicons')){ 362 while(false !== ($file = readdir($dh))){ 363 if(preg_match('/([_\-a-z0-9]+(?:\.[_\-a-z0-9]+)*?)\.(png|gif)/i',$file,$match)){ 364 $ext = strtolower($match[1]); 365 $type = '.'.strtolower($match[2]); 366 if($ext!='file' && (!isset($exts[$ext]) || $type=='.png')){ 367 $exts[$ext] = $type; 368 } 369 } 370 } 371 closedir($dh); 372 } 373 foreach($exts as $ext=>$type){ 374 $class = preg_replace('/[^_\-a-z0-9]+/','_',$ext); 375 echo ".mf_$class {"; 376 echo ' background-image: url('.DOKU_BASE.'lib/images/fileicons/'.$ext.$type.')'; 377 echo '}'; 378 } 379} 380 381/** 382 * Loads a given file and fixes relative URLs with the 383 * given location prefix 384 */ 385function css_loadfile($file,$location=''){ 386 if(!@file_exists($file)) return ''; 387 $css = io_readFile($file); 388 if(!$location) return $css; 389 390 $css = preg_replace('#(url\([ \'"]*)(?!/|data:|http://|https://| |\'|")#','\\1'.$location,$css); 391 $css = preg_replace('#(@import\s+[\'"])(?!/|data:|http://|https://)#', '\\1'.$location, $css); 392 393 return $css; 394} 395 396/** 397 * Converte local image URLs to data URLs if the filesize is small 398 * 399 * Callback for preg_replace_callback 400 */ 401function css_datauri($match){ 402 global $conf; 403 404 $pre = unslash($match[1]); 405 $base = unslash($match[2]); 406 $url = unslash($match[3]); 407 $ext = unslash($match[4]); 408 409 $local = DOKU_INC.$url; 410 $size = @filesize($local); 411 if($size && $size < $conf['cssdatauri']){ 412 $data = base64_encode(file_get_contents($local)); 413 } 414 if($data){ 415 $url = 'data:image/'.$ext.';base64,'.$data; 416 }else{ 417 $url = $base.$url; 418 } 419 return $pre.$url; 420} 421 422 423/** 424 * Returns a list of possible Plugin Styles (no existance check here) 425 * 426 * @author Andreas Gohr <andi@splitbrain.org> 427 */ 428function css_pluginstyles($mediatype='screen'){ 429 global $lang; 430 $list = array(); 431 $plugins = plugin_list(); 432 foreach ($plugins as $p){ 433 $list[DOKU_PLUGIN."$p/$mediatype.css"] = DOKU_BASE."lib/plugins/$p/"; 434 $list[DOKU_PLUGIN."$p/$mediatype.less"] = DOKU_BASE."lib/plugins/$p/"; 435 // alternative for screen.css 436 if ($mediatype=='screen') { 437 $list[DOKU_PLUGIN."$p/style.css"] = DOKU_BASE."lib/plugins/$p/"; 438 $list[DOKU_PLUGIN."$p/style.less"] = DOKU_BASE."lib/plugins/$p/"; 439 } 440 } 441 return $list; 442} 443 444/** 445 * Very simple CSS optimizer 446 * 447 * @author Andreas Gohr <andi@splitbrain.org> 448 */ 449function css_compress($css){ 450 //strip comments through a callback 451 $css = preg_replace_callback('#(/\*)(.*?)(\*/)#s','css_comment_cb',$css); 452 453 //strip (incorrect but common) one line comments 454 $css = preg_replace('/(?<!:)\/\/.*$/m','',$css); 455 456 // strip whitespaces 457 $css = preg_replace('![\r\n\t ]+!',' ',$css); 458 $css = preg_replace('/ ?([;,{}\/]) ?/','\\1',$css); 459 $css = preg_replace('/ ?: /',':',$css); 460 461 // number compression 462 $css = preg_replace('/([: ])0+(\.\d+?)0*((?:pt|pc|in|mm|cm|em|ex|px)\b|%)(?=[^\{]*[;\}])/', '$1$2$3', $css); // "0.1em" to ".1em", "1.10em" to "1.1em" 463 $css = preg_replace('/([: ])\.(0)+((?:pt|pc|in|mm|cm|em|ex|px)\b|%)(?=[^\{]*[;\}])/', '$1$2', $css); // ".0em" to "0" 464 $css = preg_replace('/([: ]0)0*(\.0*)?((?:pt|pc|in|mm|cm|em|ex|px)(?=[^\{]*[;\}])\b|%)/', '$1', $css); // "0.0em" to "0" 465 $css = preg_replace('/([: ]\d+)(\.0*)((?:pt|pc|in|mm|cm|em|ex|px)(?=[^\{]*[;\}])\b|%)/', '$1$3', $css); // "1.0em" to "1em" 466 $css = preg_replace('/([: ])0+(\d+|\d*\.\d+)((?:pt|pc|in|mm|cm|em|ex|px)(?=[^\{]*[;\}])\b|%)/', '$1$2$3', $css); // "001em" to "1em" 467 468 // shorten attributes (1em 1em 1em 1em -> 1em) 469 $css = preg_replace('/(?<![\w\-])((?:margin|padding|border|border-(?:width|radius)):)([\w\.]+)( \2)+(?=[;\}]| !)/', '$1$2', $css); // "1em 1em 1em 1em" to "1em" 470 $css = preg_replace('/(?<![\w\-])((?:margin|padding|border|border-(?:width)):)([\w\.]+) ([\w\.]+) \2 \3(?=[;\}]| !)/', '$1$2 $3', $css); // "1em 2em 1em 2em" to "1em 2em" 471 472 // shorten colors 473 $css = preg_replace("/#([0-9a-fA-F]{1})\\1([0-9a-fA-F]{1})\\2([0-9a-fA-F]{1})\\3(?=[^\{]*[;\}])/", "#\\1\\2\\3", $css); 474 475 return $css; 476} 477 478/** 479 * Callback for css_compress() 480 * 481 * Keeps short comments (< 5 chars) to maintain typical browser hacks 482 * 483 * @author Andreas Gohr <andi@splitbrain.org> 484 */ 485function css_comment_cb($matches){ 486 if(strlen($matches[2]) > 4) return ''; 487 return $matches[0]; 488} 489 490//Setup VIM: ex: et ts=4 : 491