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