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 // decide from where to get the template 36 $tpl = trim(preg_replace('/[^\w-]+/','',$INPUT->str('t'))); 37 if(!$tpl) $tpl = $conf['template']; 38 39 // load styl.ini 40 $styleini = css_styleini($tpl); 41 42 // find mediatypes 43 if ($INPUT->str('s') == 'feed') { 44 $mediatypes = array('feed'); 45 $type = 'feed'; 46 } else { 47 $mediatypes = array_unique(array_merge(array('screen', 'all', 'print'), array_keys($styleini['stylesheets']))); 48 $type = ''; 49 } 50 51 // The generated script depends on some dynamic options 52 $cache = new cache('styles'.$_SERVER['HTTP_HOST'].$_SERVER['SERVER_PORT'].DOKU_BASE.$tpl.$type,'.css'); 53 54 // if old 'default' userstyle setting exists, make it 'screen' userstyle for backwards compatibility 55 if (isset($config_cascade['userstyle']['default'])) { 56 $config_cascade['userstyle']['screen'] = $config_cascade['userstyle']['default']; 57 } 58 59 // cache influencers 60 $tplinc = tpl_incdir($tpl); 61 $cache_files = getConfigFiles('main'); 62 $cache_files[] = $tplinc.'style.ini'; 63 $cache_files[] = $tplinc.'style.local.ini'; // @deprecated 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 75 // load jQuery-UI theme 76 if ($mediatype == 'screen') { 77 $files[$mediatype][DOKU_INC.'lib/scripts/jquery/jquery-ui-theme/smoothness.css'] = DOKU_BASE.'lib/scripts/jquery/jquery-ui-theme/'; 78 } 79 // load plugin styles 80 $files[$mediatype] = array_merge($files[$mediatype], css_pluginstyles($mediatype)); 81 // load template styles 82 if (isset($styleini['stylesheets'][$mediatype])) { 83 $files[$mediatype] = array_merge($files[$mediatype], $styleini['stylesheets'][$mediatype]); 84 } 85 // load user styles 86 if(isset($config_cascade['userstyle'][$mediatype])){ 87 $files[$mediatype][$config_cascade['userstyle'][$mediatype]] = DOKU_BASE; 88 } 89 90 $cache_files = array_merge($cache_files, array_keys($files[$mediatype])); 91 } 92 93 // check cache age & handle conditional request 94 // This may exit if a cache can be used 95 http_cached($cache->cache, 96 $cache->useCache(array('files' => $cache_files))); 97 98 // start output buffering 99 ob_start(); 100 101 // build the stylesheet 102 foreach ($mediatypes as $mediatype) { 103 104 // print the default classes for interwiki links and file downloads 105 if ($mediatype == 'screen') { 106 print '@media screen {'; 107 css_interwiki(); 108 css_filetypes(); 109 print '}'; 110 } 111 112 // load files 113 $css_content = ''; 114 foreach($files[$mediatype] as $file => $location){ 115 $display = str_replace(fullpath(DOKU_INC), '', fullpath($file)); 116 $css_content .= "\n/* XXXXXXXXX $display XXXXXXXXX */\n"; 117 $css_content .= css_loadfile($file, $location); 118 } 119 switch ($mediatype) { 120 case 'screen': 121 print NL.'@media screen { /* START screen styles */'.NL.$css_content.NL.'} /* /@media END screen styles */'.NL; 122 break; 123 case 'print': 124 print NL.'@media print { /* START print styles */'.NL.$css_content.NL.'} /* /@media END print styles */'.NL; 125 break; 126 case 'all': 127 case 'feed': 128 default: 129 print NL.'/* START rest styles */ '.NL.$css_content.NL.'/* END rest styles */'.NL; 130 break; 131 } 132 } 133 // end output buffering and get contents 134 $css = ob_get_contents(); 135 ob_end_clean(); 136 137 // strip any source maps 138 stripsourcemaps($css); 139 140 // apply style replacements 141 $css = css_applystyle($css, $styleini['replacements']); 142 143 // parse less 144 $css = css_parseless($css); 145 146 // compress whitespace and comments 147 if($conf['compress']){ 148 $css = css_compress($css); 149 } 150 151 // embed small images right into the stylesheet 152 if($conf['cssdatauri']){ 153 $base = preg_quote(DOKU_BASE,'#'); 154 $css = preg_replace_callback('#(url\([ \'"]*)('.$base.')(.*?(?:\.(png|gif)))#i','css_datauri',$css); 155 } 156 157 http_cached_finish($cache->cache, $css); 158} 159 160/** 161 * Uses phpless to parse LESS in our CSS 162 * 163 * most of this function is error handling to show a nice useful error when 164 * LESS compilation fails 165 * 166 * @param $css 167 * @return string 168 */ 169function css_parseless($css) { 170 $less = new lessc(); 171 $less->importDir[] = DOKU_INC; 172 173 if (defined('DOKU_UNITTEST')){ 174 $less->importDir[] = TMP_DIR; 175 } 176 177 try { 178 return $less->compile($css); 179 } catch(Exception $e) { 180 // get exception message 181 $msg = str_replace(array("\n", "\r", "'"), array(), $e->getMessage()); 182 183 // try to use line number to find affected file 184 if(preg_match('/line: (\d+)$/', $msg, $m)){ 185 $msg = substr($msg, 0, -1* strlen($m[0])); //remove useless linenumber 186 $lno = $m[1]; 187 188 // walk upwards to last include 189 $lines = explode("\n", $css); 190 for($i=$lno-1; $i>=0; $i--){ 191 if(preg_match('/\/(\* XXXXXXXXX )(.*?)( XXXXXXXXX \*)\//', $lines[$i], $m)){ 192 // we found it, add info to message 193 $msg .= ' in '.$m[2].' at line '.($lno-$i); 194 break; 195 } 196 } 197 } 198 199 // something went wrong 200 $error = 'A fatal error occured during compilation of the CSS files. '. 201 'If you recently installed a new plugin or template it '. 202 'might be broken and you should try disabling it again. ['.$msg.']'; 203 204 echo ".dokuwiki:before { 205 content: '$error'; 206 background-color: red; 207 display: block; 208 background-color: #fcc; 209 border-color: #ebb; 210 color: #000; 211 padding: 0.5em; 212 }"; 213 214 exit; 215 } 216} 217 218/** 219 * Does placeholder replacements in the style according to 220 * the ones defined in a templates style.ini file 221 * 222 * This also adds the ini defined placeholders as less variables 223 * (sans the surrounding __ and with a ini_ prefix) 224 * 225 * @author Andreas Gohr <andi@splitbrain.org> 226 */ 227function css_applystyle($css, $replacements) { 228 // we convert ini replacements to LESS variable names 229 // and build a list of variable: value; pairs 230 $less = ''; 231 foreach((array) $replacements as $key => $value) { 232 $lkey = trim($key, '_'); 233 $lkey = '@ini_'.$lkey; 234 $less .= "$lkey: $value;\n"; 235 236 $replacements[$key] = $lkey; 237 } 238 239 // we now replace all old ini replacements with LESS variables 240 $css = strtr($css, $replacements); 241 242 // now prepend the list of LESS variables as the very first thing 243 $css = $less.$css; 244 return $css; 245} 246 247/** 248 * Load style ini contents 249 * 250 * Loads and merges style.ini files from template and config and prepares 251 * the stylesheet modes 252 * 253 * @author Andreas Gohr <andi@splitbrain.org> 254 * @param string $tpl the used template 255 * @return array with keys 'stylesheets' and 'replacements' 256 */ 257function css_styleini($tpl) { 258 $stylesheets = array(); // mode, file => base 259 $replacements = array(); // placeholder => value 260 261 // load template's style.ini 262 $incbase = tpl_incdir($tpl); 263 $webbase = tpl_basedir($tpl); 264 $ini = $incbase.'style.ini'; 265 if(file_exists($ini)){ 266 $data = parse_ini_file($ini, true); 267 268 // stylesheets 269 if(is_array($data['stylesheets'])) foreach($data['stylesheets'] as $file => $mode){ 270 $stylesheets[$mode][$incbase.$file] = $webbase; 271 } 272 273 // replacements 274 if(is_array($data['replacements'])){ 275 $replacements = array_merge($replacements, css_fixreplacementurls($data['replacements'],$webbase)); 276 } 277 } 278 279 // load template's style.local.ini 280 // @deprecated 2013-08-03 281 $ini = $incbase.'style.local.ini'; 282 if(file_exists($ini)){ 283 $data = parse_ini_file($ini, true); 284 285 // stylesheets 286 if(is_array($data['stylesheets'])) foreach($data['stylesheets'] as $file => $mode){ 287 $stylesheets[$mode][$incbase.$file] = $webbase; 288 } 289 290 // replacements 291 if(is_array($data['replacements'])){ 292 $replacements = array_merge($replacements, css_fixreplacementurls($data['replacements'],$webbase)); 293 } 294 } 295 296 // load configs's style.ini 297 $webbase = DOKU_BASE; 298 $ini = DOKU_CONF."tpl/$tpl/style.ini"; 299 $incbase = dirname($ini).'/'; 300 if(file_exists($ini)){ 301 $data = parse_ini_file($ini, true); 302 303 // stylesheets 304 if(is_array($data['stylesheets'])) foreach($data['stylesheets'] as $file => $mode){ 305 $stylesheets[$mode][$incbase.$file] = $webbase; 306 } 307 308 // replacements 309 if(is_array($data['replacements'])){ 310 $replacements = array_merge($replacements, css_fixreplacementurls($data['replacements'],$webbase)); 311 } 312 } 313 314 return array( 315 'stylesheets' => $stylesheets, 316 'replacements' => $replacements 317 ); 318} 319 320/** 321 * Amend paths used in replacement relative urls, refer FS#2879 322 * 323 * @author Chris Smith <chris@jalakai.co.uk> 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 413/** 414 * Helper class to abstract loading of css/less files 415 * 416 * @author Chris Smith <chris@jalakai.co.uk> 417 */ 418class DokuCssFile { 419 420 protected $filepath; // file system path to the CSS/Less file 421 protected $location; // base url location of the CSS/Less file 422 private $relative_path = null; 423 424 public function __construct($file) { 425 $this->filepath = $file; 426 } 427 428 /** 429 * Load the contents of the css/less file and adjust any relative paths/urls (relative to this file) to be 430 * relative to the dokuwiki root: the web root (DOKU_BASE) for most files; the file system root (DOKU_INC) 431 * for less files. 432 * 433 * @param string $location base url for this file 434 * @return string the CSS/Less contents of the file 435 */ 436 public function load($location='') { 437 if (!@file_exists($this->filepath)) return ''; 438 439 $css = io_readFile($this->filepath); 440 if (!$location) return $css; 441 442 $this->location = $location; 443 444 $css = preg_replace_callback('#(url\( *)([\'"]?)(.*?)(\2)( *\))#',array($this,'replacements'),$css); 445 $css = preg_replace_callback('#(@import\s+)([\'"])(.*?)(\2)#',array($this,'replacements'),$css); 446 447 return $css; 448 } 449 450 /** 451 * Get the relative file system path of this file, relative to dokuwiki's root folder, DOKU_INC 452 * 453 * @return string relative file system path 454 */ 455 private function getRelativePath(){ 456 457 if (is_null($this->relative_path)) { 458 $basedir = array(DOKU_INC); 459 460 // during testing, files may be found relative to a second base dir, TMP_DIR 461 if (defined('DOKU_UNITTEST')) { 462 $basedir[] = realpath(TMP_DIR); 463 } 464 465 $basedir = array_map('preg_quote_cb', $basedir); 466 $regex = '/^('.join('|',$basedir).')/'; 467 $this->relative_path = preg_replace($regex, '', dirname($this->filepath)); 468 } 469 470 return $this->relative_path; 471 } 472 473 /** 474 * preg_replace callback to adjust relative urls from relative to this file to relative 475 * to the appropriate dokuwiki root location as described in the code 476 * 477 * @param array see http://php.net/preg_replace_callback 478 * @return string see http://php.net/preg_replace_callback 479 */ 480 public function replacements($match) { 481 482 // not a relative url? - no adjustment required 483 if (preg_match('#^(/|data:|https?://)#',$match[3])) { 484 return $match[0]; 485 } 486 // a less file import? - requires a file system location 487 else if (substr($match[3],-5) == '.less') { 488 if ($match[3]{0} != '/') { 489 $match[3] = $this->getRelativePath() . '/' . $match[3]; 490 } 491 } 492 // everything else requires a url adjustment 493 else { 494 $match[3] = $this->location . $match[3]; 495 } 496 497 return join('',array_slice($match,1)); 498 } 499} 500 501/** 502 * Convert local image URLs to data URLs if the filesize is small 503 * 504 * Callback for preg_replace_callback 505 */ 506function css_datauri($match){ 507 global $conf; 508 509 $pre = unslash($match[1]); 510 $base = unslash($match[2]); 511 $url = unslash($match[3]); 512 $ext = unslash($match[4]); 513 514 $local = DOKU_INC.$url; 515 $size = @filesize($local); 516 if($size && $size < $conf['cssdatauri']){ 517 $data = base64_encode(file_get_contents($local)); 518 } 519 if($data){ 520 $url = 'data:image/'.$ext.';base64,'.$data; 521 }else{ 522 $url = $base.$url; 523 } 524 return $pre.$url; 525} 526 527 528/** 529 * Returns a list of possible Plugin Styles (no existance check here) 530 * 531 * @author Andreas Gohr <andi@splitbrain.org> 532 */ 533function css_pluginstyles($mediatype='screen'){ 534 global $lang; 535 $list = array(); 536 $plugins = plugin_list(); 537 foreach ($plugins as $p){ 538 $list[DOKU_PLUGIN."$p/$mediatype.css"] = DOKU_BASE."lib/plugins/$p/"; 539 $list[DOKU_PLUGIN."$p/$mediatype.less"] = DOKU_BASE."lib/plugins/$p/"; 540 // alternative for screen.css 541 if ($mediatype=='screen') { 542 $list[DOKU_PLUGIN."$p/style.css"] = DOKU_BASE."lib/plugins/$p/"; 543 $list[DOKU_PLUGIN."$p/style.less"] = DOKU_BASE."lib/plugins/$p/"; 544 } 545 } 546 return $list; 547} 548 549/** 550 * Very simple CSS optimizer 551 * 552 * @author Andreas Gohr <andi@splitbrain.org> 553 */ 554function css_compress($css){ 555 //strip comments through a callback 556 $css = preg_replace_callback('#(/\*)(.*?)(\*/)#s','css_comment_cb',$css); 557 558 //strip (incorrect but common) one line comments 559 $css = preg_replace_callback('/^.*\/\/.*$/m','css_onelinecomment_cb',$css); 560 561 // strip whitespaces 562 $css = preg_replace('![\r\n\t ]+!',' ',$css); 563 $css = preg_replace('/ ?([;,{}\/]) ?/','\\1',$css); 564 $css = preg_replace('/ ?: /',':',$css); 565 566 // number compression 567 $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" 568 $css = preg_replace('/([: ])\.(0)+((?:pt|pc|in|mm|cm|em|ex|px)\b|%)(?=[^\{]*[;\}])/', '$1$2', $css); // ".0em" to "0" 569 $css = preg_replace('/([: ]0)0*(\.0*)?((?:pt|pc|in|mm|cm|em|ex|px)(?=[^\{]*[;\}])\b|%)/', '$1', $css); // "0.0em" to "0" 570 $css = preg_replace('/([: ]\d+)(\.0*)((?:pt|pc|in|mm|cm|em|ex|px)(?=[^\{]*[;\}])\b|%)/', '$1$3', $css); // "1.0em" to "1em" 571 $css = preg_replace('/([: ])0+(\d+|\d*\.\d+)((?:pt|pc|in|mm|cm|em|ex|px)(?=[^\{]*[;\}])\b|%)/', '$1$2$3', $css); // "001em" to "1em" 572 573 // shorten attributes (1em 1em 1em 1em -> 1em) 574 $css = preg_replace('/(?<![\w\-])((?:margin|padding|border|border-(?:width|radius)):)([\w\.]+)( \2)+(?=[;\}]| !)/', '$1$2', $css); // "1em 1em 1em 1em" to "1em" 575 $css = preg_replace('/(?<![\w\-])((?:margin|padding|border|border-(?:width)):)([\w\.]+) ([\w\.]+) \2 \3(?=[;\}]| !)/', '$1$2 $3', $css); // "1em 2em 1em 2em" to "1em 2em" 576 577 // shorten colors 578 $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); 579 580 return $css; 581} 582 583/** 584 * Callback for css_compress() 585 * 586 * Keeps short comments (< 5 chars) to maintain typical browser hacks 587 * 588 * @author Andreas Gohr <andi@splitbrain.org> 589 */ 590function css_comment_cb($matches){ 591 if(strlen($matches[2]) > 4) return ''; 592 return $matches[0]; 593} 594 595/** 596 * Callback for css_compress() 597 * 598 * Strips one line comments but makes sure it will not destroy url() constructs with slashes 599 * 600 * @param $matches 601 * @return string 602 */ 603function css_onelinecomment_cb($matches) { 604 $line = $matches[0]; 605 606 $i = 0; 607 $len = strlen($line); 608 609 while ($i< $len){ 610 $nextcom = strpos($line, '//', $i); 611 $nexturl = stripos($line, 'url(', $i); 612 613 if($nextcom === false) { 614 // no more comments, we're done 615 $i = $len; 616 break; 617 } 618 619 // keep any quoted string that starts before a comment 620 $nextsqt = strpos($line, "'", $i); 621 $nextdqt = strpos($line, '"', $i); 622 if(min($nextsqt, $nextdqt) < $nextcom) { 623 $skipto = false; 624 if($nextsqt !== false && ($nextdqt === false || $nextsqt < $nextdqt)) { 625 $skipto = strpos($line, "'", $nextsqt+1) +1; 626 } else if ($nextdqt !== false) { 627 $skipto = strpos($line, '"', $nextdqt+1) +1; 628 } 629 630 if($skipto !== false) { 631 $i = $skipto; 632 continue; 633 } 634 } 635 636 if($nexturl === false || $nextcom < $nexturl) { 637 // no url anymore, strip comment and be done 638 $i = $nextcom; 639 break; 640 } 641 642 // we have an upcoming url 643 $i = strpos($line, ')', $nexturl); 644 } 645 646 return substr($line, 0, $i); 647} 648 649//Setup VIM: ex: et ts=4 : 650