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