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