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