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