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