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