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 // compress whitespace and comments 152 if($conf['compress']){ 153 $css = css_compress($css); 154 } 155 156 // embed small images right into the stylesheet 157 if($conf['cssdatauri']){ 158 $base = preg_quote(DOKU_BASE,'#'); 159 $css = preg_replace_callback('#(url\([ \'"]*)('.$base.')(.*?(?:\.(png|gif)))#i','css_datauri',$css); 160 } 161 162 http_cached_finish($cache->cache, $css); 163} 164 165/** 166 * Uses phpless to parse LESS in our CSS 167 * 168 * most of this function is error handling to show a nice useful error when 169 * LESS compilation fails 170 * 171 * @param $css 172 * @return string 173 */ 174function css_parseless($css) { 175 $less = new lessc(); 176 $less->importDir[] = DOKU_INC; 177 178 if (defined('DOKU_UNITTEST')){ 179 $less->importDir[] = TMP_DIR; 180 } 181 182 try { 183 return $less->compile($css); 184 } catch(Exception $e) { 185 // get exception message 186 $msg = str_replace(array("\n", "\r", "'"), array(), $e->getMessage()); 187 188 // try to use line number to find affected file 189 if(preg_match('/line: (\d+)$/', $msg, $m)){ 190 $msg = substr($msg, 0, -1* strlen($m[0])); //remove useless linenumber 191 $lno = $m[1]; 192 193 // walk upwards to last include 194 $lines = explode("\n", $css); 195 for($i=$lno-1; $i>=0; $i--){ 196 if(preg_match('/\/(\* XXXXXXXXX )(.*?)( XXXXXXXXX \*)\//', $lines[$i], $m)){ 197 // we found it, add info to message 198 $msg .= ' in '.$m[2].' at line '.($lno-$i); 199 break; 200 } 201 } 202 } 203 204 // something went wrong 205 $error = 'A fatal error occured during compilation of the CSS files. '. 206 'If you recently installed a new plugin or template it '. 207 'might be broken and you should try disabling it again. ['.$msg.']'; 208 209 echo ".dokuwiki:before { 210 content: '$error'; 211 background-color: red; 212 display: block; 213 background-color: #fcc; 214 border-color: #ebb; 215 color: #000; 216 padding: 0.5em; 217 }"; 218 219 exit; 220 } 221} 222 223/** 224 * Does placeholder replacements in the style according to 225 * the ones defined in a templates style.ini file 226 * 227 * This also adds the ini defined placeholders as less variables 228 * (sans the surrounding __ and with a ini_ prefix) 229 * 230 * @author Andreas Gohr <andi@splitbrain.org> 231 */ 232function css_applystyle($css, $replacements) { 233 // we convert ini replacements to LESS variable names 234 // and build a list of variable: value; pairs 235 $less = ''; 236 foreach((array) $replacements as $key => $value) { 237 $lkey = trim($key, '_'); 238 $lkey = '@ini_'.$lkey; 239 $less .= "$lkey: $value;\n"; 240 241 $replacements[$key] = $lkey; 242 } 243 244 // we now replace all old ini replacements with LESS variables 245 $css = strtr($css, $replacements); 246 247 // now prepend the list of LESS variables as the very first thing 248 $css = $less.$css; 249 return $css; 250} 251 252/** 253 * Load style ini contents 254 * 255 * Loads and merges style.ini files from template and config and prepares 256 * the stylesheet modes 257 * 258 * @author Andreas Gohr <andi@splitbrain.org> 259 * @param string $tpl the used template 260 * @return array with keys 'stylesheets' and 'replacements' 261 */ 262function css_styleini($tpl) { 263 $stylesheets = array(); // mode, file => base 264 $replacements = array(); // placeholder => value 265 266 // load template's style.ini 267 $incbase = tpl_incdir($tpl); 268 $webbase = tpl_basedir($tpl); 269 $ini = $incbase.'style.ini'; 270 if(file_exists($ini)){ 271 $data = parse_ini_file($ini, true); 272 273 // stylesheets 274 if(is_array($data['stylesheets'])) foreach($data['stylesheets'] as $file => $mode){ 275 $stylesheets[$mode][$incbase.$file] = $webbase; 276 } 277 278 // replacements 279 if(is_array($data['replacements'])){ 280 $replacements = array_merge($replacements, css_fixreplacementurls($data['replacements'],$webbase)); 281 } 282 } 283 284 // load template's style.local.ini 285 // @deprecated 2013-08-03 286 $ini = $incbase.'style.local.ini'; 287 if(file_exists($ini)){ 288 $data = parse_ini_file($ini, true); 289 290 // stylesheets 291 if(is_array($data['stylesheets'])) foreach($data['stylesheets'] as $file => $mode){ 292 $stylesheets[$mode][$incbase.$file] = $webbase; 293 } 294 295 // replacements 296 if(is_array($data['replacements'])){ 297 $replacements = array_merge($replacements, css_fixreplacementurls($data['replacements'],$webbase)); 298 } 299 } 300 301 // load configs's style.ini 302 $webbase = DOKU_BASE; 303 $ini = DOKU_CONF."tpl/$tpl/style.ini"; 304 $incbase = dirname($ini).'/'; 305 if(file_exists($ini)){ 306 $data = parse_ini_file($ini, true); 307 308 // stylesheets 309 if(is_array($data['stylesheets'])) foreach($data['stylesheets'] as $file => $mode){ 310 $stylesheets[$mode][$incbase.$file] = $webbase; 311 } 312 313 // replacements 314 if(is_array($data['replacements'])){ 315 $replacements = array_merge($replacements, css_fixreplacementurls($data['replacements'],$webbase)); 316 } 317 } 318 319 return array( 320 'stylesheets' => $stylesheets, 321 'replacements' => $replacements 322 ); 323} 324 325function css_fixreplacementurls($replacements, $location) { 326 foreach($replacements as $key => $value) { 327 $replacements[$key] = preg_replace('#(url\([ \'"]*)(?!/|data:|http://|https://| |\'|")#','\\1'.$location,$value); 328 } 329 return $replacements; 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 */ 343function css_interwiki(){ 344 345 // default style 346 echo 'a.interwiki {'; 347 echo ' background: transparent url('.DOKU_BASE.'lib/images/interwiki.png) 0px 1px no-repeat;'; 348 echo ' padding: 1px 0px 1px 16px;'; 349 echo '}'; 350 351 // additional styles when icon available 352 $iwlinks = getInterwiki(); 353 foreach(array_keys($iwlinks) as $iw){ 354 $class = preg_replace('/[^_\-a-z0-9]+/i','_',$iw); 355 if(@file_exists(DOKU_INC.'lib/images/interwiki/'.$iw.'.png')){ 356 echo "a.iw_$class {"; 357 echo ' background-image: url('.DOKU_BASE.'lib/images/interwiki/'.$iw.'.png)'; 358 echo '}'; 359 }elseif(@file_exists(DOKU_INC.'lib/images/interwiki/'.$iw.'.gif')){ 360 echo "a.iw_$class {"; 361 echo ' background-image: url('.DOKU_BASE.'lib/images/interwiki/'.$iw.'.gif)'; 362 echo '}'; 363 } 364 } 365} 366 367/** 368 * Prints classes for file download links 369 * 370 * @author Andreas Gohr <andi@splitbrain.org> 371 */ 372function css_filetypes(){ 373 374 // default style 375 echo '.mediafile {'; 376 echo ' background: transparent url('.DOKU_BASE.'lib/images/fileicons/file.png) 0px 1px no-repeat;'; 377 echo ' padding-left: 18px;'; 378 echo ' padding-bottom: 1px;'; 379 echo '}'; 380 381 // additional styles when icon available 382 // scan directory for all icons 383 $exts = array(); 384 if($dh = opendir(DOKU_INC.'lib/images/fileicons')){ 385 while(false !== ($file = readdir($dh))){ 386 if(preg_match('/([_\-a-z0-9]+(?:\.[_\-a-z0-9]+)*?)\.(png|gif)/i',$file,$match)){ 387 $ext = strtolower($match[1]); 388 $type = '.'.strtolower($match[2]); 389 if($ext!='file' && (!isset($exts[$ext]) || $type=='.png')){ 390 $exts[$ext] = $type; 391 } 392 } 393 } 394 closedir($dh); 395 } 396 foreach($exts as $ext=>$type){ 397 $class = preg_replace('/[^_\-a-z0-9]+/','_',$ext); 398 echo ".mf_$class {"; 399 echo ' background-image: url('.DOKU_BASE.'lib/images/fileicons/'.$ext.$type.')'; 400 echo '}'; 401 } 402} 403 404/** 405 * Loads a given file and fixes relative URLs with the 406 * given location prefix 407 */ 408function css_loadfile($file,$location=''){ 409 $css_file = new DokuCssFile($file); 410 return $css_file->load($location); 411} 412 413class DokuCssFile { 414 415 protected $filepath; 416 protected $location; 417 private $relative_path = null; 418 419 public function __construct($file) { 420 $this->filepath = $file; 421 } 422 423 public function load($location='') { 424 if (!@file_exists($this->filepath)) return ''; 425 426 $css = io_readFile($this->filepath); 427 if (!$location) return $css; 428 429 $this->location = $location; 430 431 $css = preg_replace_callback('#(url\( *)([\'"]?)(.*?)(\2)( *\))#',array($this,'replacements'),$css); 432 $css = preg_replace_callback('#(@import\s+)([\'"])(.*?)(\2)#',array($this,'replacements'),$css); 433 434 return $css; 435 } 436 437 private function getRelativePath(){ 438 439 if (is_null($this->relative_path)) { 440 $basedir = array(DOKU_INC); 441 if (defined('DOKU_UNITTEST')) { 442 $basedir[] = realpath(TMP_DIR); 443 } 444 $regex = '#^('.join('|',$basedir).')#'; 445 446 $this->relative_path = preg_replace($regex, '', dirname($this->filepath)); 447 } 448 449 return $this->relative_path; 450 } 451 452 public function replacements($match) { 453 454 if (preg_match('#^(/|data:|https?://)#',$match[3])) { 455 return $match[0]; 456 } 457 else if (substr($match[3],-5) == '.less') { 458 if ($match[3]{0} != '/') { 459 $match[3] = $this->getRelativePath() . '/' . $match[3]; 460 } 461 } 462 else { 463 $match[3] = $this->location . $match[3]; 464 } 465 466 return join('',array_slice($match,1)); 467 } 468} 469 470/** 471 * Convert local image URLs to data URLs if the filesize is small 472 * 473 * Callback for preg_replace_callback 474 */ 475function css_datauri($match){ 476 global $conf; 477 478 $pre = unslash($match[1]); 479 $base = unslash($match[2]); 480 $url = unslash($match[3]); 481 $ext = unslash($match[4]); 482 483 $local = DOKU_INC.$url; 484 $size = @filesize($local); 485 if($size && $size < $conf['cssdatauri']){ 486 $data = base64_encode(file_get_contents($local)); 487 } 488 if($data){ 489 $url = 'data:image/'.$ext.';base64,'.$data; 490 }else{ 491 $url = $base.$url; 492 } 493 return $pre.$url; 494} 495 496 497/** 498 * Returns a list of possible Plugin Styles (no existance check here) 499 * 500 * @author Andreas Gohr <andi@splitbrain.org> 501 */ 502function css_pluginstyles($mediatype='screen'){ 503 global $lang; 504 $list = array(); 505 $plugins = plugin_list(); 506 foreach ($plugins as $p){ 507 $list[DOKU_PLUGIN."$p/$mediatype.css"] = DOKU_BASE."lib/plugins/$p/"; 508 $list[DOKU_PLUGIN."$p/$mediatype.less"] = DOKU_BASE."lib/plugins/$p/"; 509 // alternative for screen.css 510 if ($mediatype=='screen') { 511 $list[DOKU_PLUGIN."$p/style.css"] = DOKU_BASE."lib/plugins/$p/"; 512 $list[DOKU_PLUGIN."$p/style.less"] = DOKU_BASE."lib/plugins/$p/"; 513 } 514 // @deprecated 2012-04-09: rtl will cease to be a mode of its own, 515 // please use "[dir=rtl]" in any css file in all, screen or print mode instead 516 if($lang['direction'] == 'rtl'){ 517 $list[DOKU_PLUGIN."$p/rtl.css"] = DOKU_BASE."lib/plugins/$p/"; 518 } 519 } 520 return $list; 521} 522 523/** 524 * Very simple CSS optimizer 525 * 526 * @author Andreas Gohr <andi@splitbrain.org> 527 */ 528function css_compress($css){ 529 //strip comments through a callback 530 $css = preg_replace_callback('#(/\*)(.*?)(\*/)#s','css_comment_cb',$css); 531 532 //strip (incorrect but common) one line comments 533 $css = preg_replace('/(?<!:)\/\/.*$/m','',$css); 534 535 // strip whitespaces 536 $css = preg_replace('![\r\n\t ]+!',' ',$css); 537 $css = preg_replace('/ ?([;,{}\/]) ?/','\\1',$css); 538 $css = preg_replace('/ ?: /',':',$css); 539 540 // number compression 541 $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" 542 $css = preg_replace('/([: ])\.(0)+((?:pt|pc|in|mm|cm|em|ex|px)\b|%)(?=[^\{]*[;\}])/', '$1$2', $css); // ".0em" to "0" 543 $css = preg_replace('/([: ]0)0*(\.0*)?((?:pt|pc|in|mm|cm|em|ex|px)(?=[^\{]*[;\}])\b|%)/', '$1', $css); // "0.0em" to "0" 544 $css = preg_replace('/([: ]\d+)(\.0*)((?:pt|pc|in|mm|cm|em|ex|px)(?=[^\{]*[;\}])\b|%)/', '$1$3', $css); // "1.0em" to "1em" 545 $css = preg_replace('/([: ])0+(\d+|\d*\.\d+)((?:pt|pc|in|mm|cm|em|ex|px)(?=[^\{]*[;\}])\b|%)/', '$1$2$3', $css); // "001em" to "1em" 546 547 // shorten attributes (1em 1em 1em 1em -> 1em) 548 $css = preg_replace('/(?<![\w\-])((?:margin|padding|border|border-(?:width|radius)):)([\w\.]+)( \2)+(?=[;\}]| !)/', '$1$2', $css); // "1em 1em 1em 1em" to "1em" 549 $css = preg_replace('/(?<![\w\-])((?:margin|padding|border|border-(?:width)):)([\w\.]+) ([\w\.]+) \2 \3(?=[;\}]| !)/', '$1$2 $3', $css); // "1em 2em 1em 2em" to "1em 2em" 550 551 // shorten colors 552 $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); 553 554 return $css; 555} 556 557/** 558 * Callback for css_compress() 559 * 560 * Keeps short comments (< 5 chars) to maintain typical browser hacks 561 * 562 * @author Andreas Gohr <andi@splitbrain.org> 563 */ 564function css_comment_cb($matches){ 565 if(strlen($matches[2]) > 4) return ''; 566 return $matches[0]; 567} 568 569//Setup VIM: ex: et ts=4 : 570