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"); 13if(!defined('DEFAULT_FLAVOUR')) define('DEFAULT_FLAVOUR',"style"); 14require_once(DOKU_INC.'inc/init.php'); 15 16// Main (don't run when UNIT test) 17if(!defined('SIMPLE_TEST')){ 18 header('Content-Type: text/css; charset=utf-8'); 19 css_out(); 20} 21 22 23// ---------------------- functions ------------------------------ 24 25/** 26 * Output all needed Styles 27 * 28 * @author Andreas Gohr <andi@splitbrain.org> 29 */ 30function css_out(){ 31 global $conf; 32 global $lang; 33 global $config_cascade; 34 global $INPUT; 35 36 if ($INPUT->str('s') == 'feed') { 37 $mediatypes = array('feed'); 38 } else { 39 $mediatypes = array('screen', 'all', 'print', 'handheld'); 40 } 41 42 // decide from where to get the template 43 $tpl = trim(preg_replace('/[^\w-]+/','',$INPUT->str('t'))); 44 if(!$tpl) $tpl = $conf['template']; 45 46 // decide from where to get the template 47 $flavour = trim(preg_replace('/[^\w-]+/','',$INPUT->str('f'))); 48 if(!$flavour) $flavour = DEFAULT_FLAVOUR; 49 50 // load styl.ini 51 $styleini = css_styleini($tpl, $flavour, $INPUT->bool('preview')); 52 53 // cache influencers 54 $tplinc = tpl_incdir($tpl); 55 $cache_files = getConfigFiles('main'); 56 $cache_files[] = $tplinc.'style.ini'; 57 $cache_files[] = DOKU_CONF."tpl/$tpl/style.ini"; 58 $cache_files[] = DOKU_CONF."tpl/$tpl/ini/".$flavour.".ini"; 59 $cache_files[] = __FILE__; 60 if($INPUT->bool('preview')) $cache_files[] = $conf['cachedir'].'/preview.ini'; 61 62 // Array of needed files and their web locations, the latter ones 63 // are needed to fix relative paths in the stylesheets 64 // We only need to build the list for the requested flavour. 65 $media_files = array(); 66 foreach($mediatypes as $mediatype) { 67 $files = array(); 68 if ( $flavour === DEFAULT_FLAVOUR ) { 69 // load core styles 70 $files[DOKU_INC.'lib/styles/'.$mediatype.'.css'] = DOKU_BASE.'lib/styles/'; 71 72 // load jQuery-UI theme 73 if ($mediatype == 'screen') { 74 $files[DOKU_INC.'lib/scripts/jquery/jquery-ui-theme/smoothness.css'] = DOKU_BASE.'lib/scripts/jquery/jquery-ui-theme/'; 75 } 76 // load plugin styles 77 $files = array_merge($files, css_pluginstyles($mediatype)); 78 // load template styles 79 if (isset($styleini['stylesheets'][$mediatype])) { 80 $files = array_merge($files, $styleini['stylesheets'][$mediatype]); 81 } 82 // load user styles 83 if(!empty($config_cascade['userstyle'][$mediatype])) { 84 foreach($config_cascade['userstyle'][$mediatype] as $userstyle) { 85 $files[$userstyle] = DOKU_BASE; 86 } 87 } 88 } else if (isset($styleini['stylesheets'][$mediatype])) { 89 // only allow the predefined media types 90 $files = $styleini['stylesheets'][$mediatype]; 91 } 92 93 // Let plugins decide to either put more styles here or to remove some 94 $media_files[$mediatype] = css_filewrapper($mediatype, $flavour, $files); 95 $CSSEvt = new Doku_Event('CSS_STYLES_INCLUDED', $media_files[$mediatype]); 96 97 // Make it preventable. 98 if ( $CSSEvt->advise_before() ) { 99 $cache_files = array_merge($cache_files, array_keys($media_files[$mediatype]['files'])); 100 } else { 101 // unset if prevented. Nothing will be printed for this mediatype. 102 unset($media_files[$mediatype]); 103 } 104 105 // finish event. 106 $CSSEvt->advise_after(); 107 } 108 109 // The generated script depends on some dynamic options 110 $cache = new cache('styles'.$_SERVER['HTTP_HOST'].$_SERVER['SERVER_PORT'].DOKU_BASE.$tpl.md5(serialize($cache_files)),'.css'); 111 $cache->_event = 'CSS_CACHE_USE'; 112 113 // check cache age & handle conditional request 114 // This may exit if a cache can be used 115 $cache_ok = $cache->useCache(array('files' => $cache_files)); 116 http_cached($cache->cache, $cache_ok); 117 118 // start output buffering 119 ob_start(); 120 121 if ( $flavour === DEFAULT_FLAVOUR ) { 122 // Fire CSS_STYLES_INCLUDED for one last time to let the 123 // plugins decide whether to include the DW default styles. 124 // This can be done by preventing the Default. 125 $media_files['DW_DEFAULT'] = css_filewrapper('DW_DEFAULT'); 126 trigger_event('CSS_STYLES_INCLUDED', $media_files['DW_DEFAULT'], 'css_defaultstyles'); 127 } 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 * Load style ini contents 280 * 281 * Loads and merges style.ini files from template and config and prepares 282 * the stylesheet modes 283 * 284 * @author Andreas Gohr <andi@splitbrain.org> 285 * 286 * @param string $tpl the used template 287 * @param bool $preview load preview replacements 288 * @return array with keys 'stylesheets' and 'replacements' 289 */ 290function css_styleini($tpl, $flavour=DEFAULT_FLAVOUR, $preview=false) { 291 global $conf; 292 293 $stylesheets = array(); // mode, file => base 294 $replacements = array(); // placeholder => value 295 296 // load template style.ini replacements first 297 // they should be the base for the colors - if not the default flavour 298 $incbase = tpl_incdir($tpl); 299 $webbase = tpl_basedir($tpl); 300 $ini = $incbase.DEFAULT_FLAVOUR.'.ini'; 301 if($flavour != DEFAULT_FLAVOUR && file_exists($ini)) { 302 $data = parse_ini_file($ini, true); 303 // replacements 304 if(is_array($data['replacements'])) { 305 $replacements = array_merge($replacements, css_fixreplacementurls($data['replacements'], $webbase)); 306 } 307 } 308 309 // load template's style.ini 310 $ini = $incbase.$flavour.'.ini'; 311 if(file_exists($ini)){ 312 $data = parse_ini_file($ini, true); 313 314 // stylesheets 315 if(is_array($data['stylesheets'])) foreach($data['stylesheets'] as $file => $mode){ 316 $stylesheets[$mode][$incbase.$file] = $webbase; 317 } 318 // replacements 319 if(isset($data['replacements']) && is_array($data['replacements'])){ 320 $replacements = array_merge($replacements, css_fixreplacementurls($data['replacements'],$webbase)); 321 } 322 } 323 324 // load configs's style.ini 325 $webbase = DOKU_BASE; 326 $ini = DOKU_CONF."tpl/$tpl/style.ini"; 327 $incbase = dirname($ini).'/'; 328 if(file_exists($ini)){ 329 $data = parse_ini_file($ini, true); 330 331 // stylesheets - but only if we are on the default flavour 332 if($flavour === DEFAULT_FLAVOUR && isset($data['stylesheets']) && is_array($data['stylesheets'])) foreach($data['stylesheets'] as $file => $mode){ 333 $stylesheets[$mode][$incbase.$file] = $webbase; 334 } 335 // replacements 336 if(isset($data['replacements']) && is_array($data['replacements'])){ 337 $replacements = array_merge($replacements, css_fixreplacementurls($data['replacements'],$webbase)); 338 } 339 } 340 341 // allow replacement overwrites in preview mode 342 if($preview) { 343 $webbase = DOKU_BASE; 344 $ini = $conf['cachedir'].'/preview.ini'; 345 if(file_exists($ini)) { 346 $data = parse_ini_file($ini, true); 347 // replacements 348 if(is_array($data['replacements'])) { 349 $replacements = array_merge($replacements, css_fixreplacementurls($data['replacements'], $webbase)); 350 } 351 } 352 } 353 354 return array( 355 'stylesheets' => $stylesheets, 356 'replacements' => $replacements 357 ); 358} 359 360/** 361 * Amend paths used in replacement relative urls, refer FS#2879 362 * 363 * @author Chris Smith <chris@jalakai.co.uk> 364 * 365 * @param array $replacements with key-value pairs 366 * @param string $location 367 * @return array 368 */ 369function css_fixreplacementurls($replacements, $location) { 370 foreach($replacements as $key => $value) { 371 $replacements[$key] = preg_replace('#(url\([ \'"]*)(?!/|data:|http://|https://| |\'|")#','\\1'.$location,$value); 372 } 373 return $replacements; 374} 375 376/** 377 * Wrapper for the files, content and mediatype for the event CSS_STYLES_INCLUDED 378 * 379 * @author Gerry Weißbach <gerry.w@gammaproduction.de> 380 * 381 * @param string $mediatype type ofthe current media files/content set 382 * @param array $files set of files that define the current mediatype 383 * @return array 384 */ 385function css_filewrapper($mediatype, $flavour=DEFAULT_FLAVOUR, $files=array()){ 386 return array( 387 'files' => $files, 388 'mediatype' => $mediatype, 389 'flavour' => $flavour, 390 'encapsulate' => in_array($mediatype, array('screen', 'print', 'handheld')), 391 'encapsulationPrefix' => '@media '.$mediatype 392 ); 393} 394 395/** 396 * Prints the @media encapsulated default styles of DokuWiki 397 * 398 * @author Gerry Weißbach <gerry.w@gammaproduction.de> 399 * 400 * This function is being called by a CSS_STYLES_INCLUDED event 401 * The event can be distinguished by the mediatype which is: 402 * DW_DEFAULT 403 */ 404function css_defaultstyles(){ 405 // print the default classes for interwiki links and file downloads 406 print '@media screen {'; 407 css_interwiki(); 408 css_filetypes(); 409 print '}'; 410} 411 412/** 413 * Prints classes for interwikilinks 414 * 415 * Interwiki links have two classes: 'interwiki' and 'iw_$name>' where 416 * $name is the identifier given in the config. All Interwiki links get 417 * an default style with a default icon. If a special icon is available 418 * for an interwiki URL it is set in it's own class. Both classes can be 419 * overwritten in the template or userstyles. 420 * 421 * @author Andreas Gohr <andi@splitbrain.org> 422 */ 423function css_interwiki(){ 424 425 // default style 426 echo 'a.interwiki {'; 427 echo ' background: transparent url('.DOKU_BASE.'lib/images/interwiki.png) 0px 1px no-repeat;'; 428 echo ' padding: 1px 0px 1px 16px;'; 429 echo '}'; 430 431 // additional styles when icon available 432 $iwlinks = getInterwiki(); 433 foreach(array_keys($iwlinks) as $iw){ 434 $class = preg_replace('/[^_\-a-z0-9]+/i','_',$iw); 435 if(file_exists(DOKU_INC.'lib/images/interwiki/'.$iw.'.png')){ 436 echo "a.iw_$class {"; 437 echo ' background-image: url('.DOKU_BASE.'lib/images/interwiki/'.$iw.'.png)'; 438 echo '}'; 439 }elseif(file_exists(DOKU_INC.'lib/images/interwiki/'.$iw.'.gif')){ 440 echo "a.iw_$class {"; 441 echo ' background-image: url('.DOKU_BASE.'lib/images/interwiki/'.$iw.'.gif)'; 442 echo '}'; 443 } 444 } 445} 446 447/** 448 * Prints classes for file download links 449 * 450 * @author Andreas Gohr <andi@splitbrain.org> 451 */ 452function css_filetypes(){ 453 454 // default style 455 echo '.mediafile {'; 456 echo ' background: transparent url('.DOKU_BASE.'lib/images/fileicons/file.png) 0px 1px no-repeat;'; 457 echo ' padding-left: 18px;'; 458 echo ' padding-bottom: 1px;'; 459 echo '}'; 460 461 // additional styles when icon available 462 // scan directory for all icons 463 $exts = array(); 464 if($dh = opendir(DOKU_INC.'lib/images/fileicons')){ 465 while(false !== ($file = readdir($dh))){ 466 if(preg_match('/([_\-a-z0-9]+(?:\.[_\-a-z0-9]+)*?)\.(png|gif)/i',$file,$match)){ 467 $ext = strtolower($match[1]); 468 $type = '.'.strtolower($match[2]); 469 if($ext!='file' && (!isset($exts[$ext]) || $type=='.png')){ 470 $exts[$ext] = $type; 471 } 472 } 473 } 474 closedir($dh); 475 } 476 foreach($exts as $ext=>$type){ 477 $class = preg_replace('/[^_\-a-z0-9]+/','_',$ext); 478 echo ".mf_$class {"; 479 echo ' background-image: url('.DOKU_BASE.'lib/images/fileicons/'.$ext.$type.')'; 480 echo '}'; 481 } 482} 483 484/** 485 * Loads a given file and fixes relative URLs with the 486 * given location prefix 487 * 488 * @param string $file file system path 489 * @param string $location 490 * @return string 491 */ 492function css_loadfile($file,$location=''){ 493 $css_file = new DokuCssFile($file); 494 return $css_file->load($location); 495} 496 497/** 498 * Helper class to abstract loading of css/less files 499 * 500 * @author Chris Smith <chris@jalakai.co.uk> 501 */ 502class DokuCssFile { 503 504 protected $filepath; // file system path to the CSS/Less file 505 protected $location; // base url location of the CSS/Less file 506 protected $relative_path = null; 507 508 public function __construct($file) { 509 $this->filepath = $file; 510 } 511 512 /** 513 * Load the contents of the css/less file and adjust any relative paths/urls (relative to this file) to be 514 * relative to the dokuwiki root: the web root (DOKU_BASE) for most files; the file system root (DOKU_INC) 515 * for less files. 516 * 517 * @param string $location base url for this file 518 * @return string the CSS/Less contents of the file 519 */ 520 public function load($location='') { 521 if (!file_exists($this->filepath)) return ''; 522 523 $css = io_readFile($this->filepath); 524 if (!$location) return $css; 525 526 $this->location = $location; 527 528 $css = preg_replace_callback('#(url\( *)([\'"]?)(.*?)(\2)( *\))#',array($this,'replacements'),$css); 529 $css = preg_replace_callback('#(@import\s+)([\'"])(.*?)(\2)#',array($this,'replacements'),$css); 530 531 return $css; 532 } 533 534 /** 535 * Get the relative file system path of this file, relative to dokuwiki's root folder, DOKU_INC 536 * 537 * @return string relative file system path 538 */ 539 protected function getRelativePath(){ 540 541 if (is_null($this->relative_path)) { 542 $basedir = array(DOKU_INC); 543 544 // during testing, files may be found relative to a second base dir, TMP_DIR 545 if (defined('DOKU_UNITTEST')) { 546 $basedir[] = realpath(TMP_DIR); 547 } 548 549 $basedir = array_map('preg_quote_cb', $basedir); 550 $regex = '/^('.join('|',$basedir).')/'; 551 $this->relative_path = preg_replace($regex, '', dirname($this->filepath)); 552 } 553 554 return $this->relative_path; 555 } 556 557 /** 558 * preg_replace callback to adjust relative urls from relative to this file to relative 559 * to the appropriate dokuwiki root location as described in the code 560 * 561 * @param array see http://php.net/preg_replace_callback 562 * @return string see http://php.net/preg_replace_callback 563 */ 564 public function replacements($match) { 565 566 // not a relative url? - no adjustment required 567 if (preg_match('#^(/|data:|https?://)#',$match[3])) { 568 return $match[0]; 569 } 570 // a less file import? - requires a file system location 571 else if (substr($match[3],-5) == '.less') { 572 if ($match[3]{0} != '/') { 573 $match[3] = $this->getRelativePath() . '/' . $match[3]; 574 } 575 } 576 // everything else requires a url adjustment 577 else { 578 $match[3] = $this->location . $match[3]; 579 } 580 581 return join('',array_slice($match,1)); 582 } 583} 584 585/** 586 * Convert local image URLs to data URLs if the filesize is small 587 * 588 * Callback for preg_replace_callback 589 * 590 * @param array $match 591 * @return string 592 */ 593function css_datauri($match){ 594 global $conf; 595 596 $pre = unslash($match[1]); 597 $base = unslash($match[2]); 598 $url = unslash($match[3]); 599 $ext = unslash($match[4]); 600 601 $local = DOKU_INC.$url; 602 $size = @filesize($local); 603 if($size && $size < $conf['cssdatauri']){ 604 $data = base64_encode(file_get_contents($local)); 605 } 606 if($data){ 607 $url = 'data:image/'.$ext.';base64,'.$data; 608 }else{ 609 $url = $base.$url; 610 } 611 return $pre.$url; 612} 613 614 615/** 616 * Returns a list of possible Plugin Styles (no existance check here) 617 * 618 * @author Andreas Gohr <andi@splitbrain.org> 619 * 620 * @param string $mediatype 621 * @return array 622 */ 623function css_pluginstyles($mediatype='screen'){ 624 $list = array(); 625 $plugins = plugin_list(); 626 foreach ($plugins as $p){ 627 $list[DOKU_PLUGIN."$p/$mediatype.css"] = DOKU_BASE."lib/plugins/$p/"; 628 $list[DOKU_PLUGIN."$p/$mediatype.less"] = DOKU_BASE."lib/plugins/$p/"; 629 // alternative for screen.css 630 if ($mediatype=='screen') { 631 $list[DOKU_PLUGIN."$p/style.css"] = DOKU_BASE."lib/plugins/$p/"; 632 $list[DOKU_PLUGIN."$p/style.less"] = DOKU_BASE."lib/plugins/$p/"; 633 } 634 } 635 return $list; 636} 637 638/** 639 * Very simple CSS optimizer 640 * 641 * @author Andreas Gohr <andi@splitbrain.org> 642 * 643 * @param string $css 644 * @return string 645 */ 646function css_compress($css){ 647 //strip comments through a callback 648 $css = preg_replace_callback('#(/\*)(.*?)(\*/)#s','css_comment_cb',$css); 649 650 //strip (incorrect but common) one line comments 651 $css = preg_replace_callback('/^.*\/\/.*$/m','css_onelinecomment_cb',$css); 652 653 // strip whitespaces 654 $css = preg_replace('![\r\n\t ]+!',' ',$css); 655 $css = preg_replace('/ ?([;,{}\/]) ?/','\\1',$css); 656 $css = preg_replace('/ ?: /',':',$css); 657 658 // number compression 659 $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" 660 $css = preg_replace('/([: ])\.(0)+((?:pt|pc|in|mm|cm|em|ex|px)\b|%)(?=[^\{]*[;\}])/', '$1$2', $css); // ".0em" to "0" 661 $css = preg_replace('/([: ]0)0*(\.0*)?((?:pt|pc|in|mm|cm|em|ex|px)(?=[^\{]*[;\}])\b|%)/', '$1', $css); // "0.0em" to "0" 662 $css = preg_replace('/([: ]\d+)(\.0*)((?:pt|pc|in|mm|cm|em|ex|px)(?=[^\{]*[;\}])\b|%)/', '$1$3', $css); // "1.0em" to "1em" 663 $css = preg_replace('/([: ])0+(\d+|\d*\.\d+)((?:pt|pc|in|mm|cm|em|ex|px)(?=[^\{]*[;\}])\b|%)/', '$1$2$3', $css); // "001em" to "1em" 664 665 // shorten attributes (1em 1em 1em 1em -> 1em) 666 $css = preg_replace('/(?<![\w\-])((?:margin|padding|border|border-(?:width|radius)):)([\w\.]+)( \2)+(?=[;\}]| !)/', '$1$2', $css); // "1em 1em 1em 1em" to "1em" 667 $css = preg_replace('/(?<![\w\-])((?:margin|padding|border|border-(?:width)):)([\w\.]+) ([\w\.]+) \2 \3(?=[;\}]| !)/', '$1$2 $3', $css); // "1em 2em 1em 2em" to "1em 2em" 668 669 // shorten colors 670 $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); 671 672 return $css; 673} 674 675/** 676 * Callback for css_compress() 677 * 678 * Keeps short comments (< 5 chars) to maintain typical browser hacks 679 * 680 * @author Andreas Gohr <andi@splitbrain.org> 681 * 682 * @param array $matches 683 * @return string 684 */ 685function css_comment_cb($matches){ 686 if(strlen($matches[2]) > 4) return ''; 687 return $matches[0]; 688} 689 690/** 691 * Callback for css_compress() 692 * 693 * Strips one line comments but makes sure it will not destroy url() constructs with slashes 694 * 695 * @param array $matches 696 * @return string 697 */ 698function css_onelinecomment_cb($matches) { 699 $line = $matches[0]; 700 701 $i = 0; 702 $len = strlen($line); 703 704 while ($i< $len){ 705 $nextcom = strpos($line, '//', $i); 706 $nexturl = stripos($line, 'url(', $i); 707 708 if($nextcom === false) { 709 // no more comments, we're done 710 $i = $len; 711 break; 712 } 713 714 // keep any quoted string that starts before a comment 715 $nextsqt = strpos($line, "'", $i); 716 $nextdqt = strpos($line, '"', $i); 717 if(min($nextsqt, $nextdqt) < $nextcom) { 718 $skipto = false; 719 if($nextsqt !== false && ($nextdqt === false || $nextsqt < $nextdqt)) { 720 $skipto = strpos($line, "'", $nextsqt+1) +1; 721 } else if ($nextdqt !== false) { 722 $skipto = strpos($line, '"', $nextdqt+1) +1; 723 } 724 725 if($skipto !== false) { 726 $i = $skipto; 727 continue; 728 } 729 } 730 731 if($nexturl === false || $nextcom < $nexturl) { 732 // no url anymore, strip comment and be done 733 $i = $nextcom; 734 break; 735 } 736 737 // we have an upcoming url 738 $i = strpos($line, ')', $nexturl); 739 } 740 741 return substr($line, 0, $i); 742} 743 744//Setup VIM: ex: et ts=4 : 745