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 try { 177 return $less->compile($css); 178 } catch(Exception $e) { 179 // get exception message 180 $msg = str_replace(array("\n", "\r", "'"), array(), $e->getMessage()); 181 182 // try to use line number to find affected file 183 if(preg_match('/line: (\d+)$/', $msg, $m)){ 184 $msg = substr($msg, 0, -1* strlen($m[0])); //remove useless linenumber 185 $lno = $m[1]; 186 187 // walk upwards to last include 188 $lines = explode("\n", $css); 189 for($i=$lno-1; $i>=0; $i--){ 190 if(preg_match('/\/(\* XXXXXXXXX )(.*?)( XXXXXXXXX \*)\//', $lines[$i], $m)){ 191 // we found it, add info to message 192 $msg .= ' in '.$m[2].' at line '.($lno-$i); 193 break; 194 } 195 } 196 } 197 198 // something went wrong 199 $error = 'A fatal error occured during compilation of the CSS files. '. 200 'If you recently installed a new plugin or template it '. 201 'might be broken and you should try disabling it again. ['.$msg.']'; 202 203 echo ".dokuwiki:before { 204 content: '$error'; 205 background-color: red; 206 display: block; 207 background-color: #fcc; 208 border-color: #ebb; 209 color: #000; 210 padding: 0.5em; 211 }"; 212 213 exit; 214 } 215} 216 217/** 218 * Does placeholder replacements in the style according to 219 * the ones defined in a templates style.ini file 220 * 221 * This also adds the ini defined placeholders as less variables 222 * (sans the surrounding __ and with a ini_ prefix) 223 * 224 * @author Andreas Gohr <andi@splitbrain.org> 225 */ 226function css_applystyle($css, $replacements) { 227 // we convert ini replacements to LESS variable names 228 // and build a list of variable: value; pairs 229 $less = ''; 230 foreach((array) $replacements as $key => $value) { 231 $lkey = trim($key, '_'); 232 $lkey = '@ini_'.$lkey; 233 $less .= "$lkey: $value;\n"; 234 235 $replacements[$key] = $lkey; 236 } 237 238 // we now replace all old ini replacements with LESS variables 239 $css = strtr($css, $replacements); 240 241 // now prepend the list of LESS variables as the very first thing 242 $css = $less.$css; 243 return $css; 244} 245 246/** 247 * Load style ini contents 248 * 249 * Loads and merges style.ini files from template and config and prepares 250 * the stylesheet modes 251 * 252 * @author Andreas Gohr <andi@splitbrain.org> 253 * @param string $tpl the used template 254 * @return array with keys 'stylesheets' and 'replacements' 255 */ 256function css_styleini($tpl) { 257 $stylesheets = array(); // mode, file => base 258 $replacements = array(); // placeholder => value 259 260 // load template's style.ini 261 $incbase = tpl_incdir($tpl); 262 $webbase = tpl_basedir($tpl); 263 $ini = $incbase.'style.ini'; 264 if(file_exists($ini)){ 265 $data = parse_ini_file($ini, true); 266 267 // stylesheets 268 if(is_array($data['stylesheets'])) foreach($data['stylesheets'] as $file => $mode){ 269 $stylesheets[$mode][$incbase.$file] = $webbase; 270 } 271 272 // replacements 273 if(is_array($data['replacements'])){ 274 $replacements = array_merge($replacements, $data['replacements']); 275 } 276 } 277 278 // load template's style.local.ini 279 // @deprecated 2013-08-03 280 $ini = $incbase.'style.local.ini'; 281 if(file_exists($ini)){ 282 $data = parse_ini_file($ini, true); 283 284 // stylesheets 285 if(is_array($data['stylesheets'])) foreach($data['stylesheets'] as $file => $mode){ 286 $stylesheets[$mode][$incbase.$file] = $webbase; 287 } 288 289 // replacements 290 if(is_array($data['replacements'])){ 291 $replacements = array_merge($replacements, $data['replacements']); 292 } 293 } 294 295 // load configs's style.ini 296 $webbase = DOKU_BASE; 297 $ini = DOKU_CONF."tpl/$tpl/style.ini"; 298 $incbase = dirname($ini).'/'; 299 if(file_exists($ini)){ 300 $data = parse_ini_file($ini, true); 301 302 // stylesheets 303 if(is_array($data['stylesheets'])) foreach($data['stylesheets'] as $file => $mode){ 304 $stylesheets[$mode][$incbase.$file] = $webbase; 305 } 306 307 // replacements 308 if(is_array($data['replacements'])){ 309 $replacements = array_merge($replacements, $data['replacements']); 310 } 311 } 312 313 return array( 314 'stylesheets' => $stylesheets, 315 'replacements' => $replacements 316 ); 317} 318 319/** 320 * Prints classes for interwikilinks 321 * 322 * Interwiki links have two classes: 'interwiki' and 'iw_$name>' where 323 * $name is the identifier given in the config. All Interwiki links get 324 * an default style with a default icon. If a special icon is available 325 * for an interwiki URL it is set in it's own class. Both classes can be 326 * overwritten in the template or userstyles. 327 * 328 * @author Andreas Gohr <andi@splitbrain.org> 329 */ 330function css_interwiki(){ 331 332 // default style 333 echo 'a.interwiki {'; 334 echo ' background: transparent url('.DOKU_BASE.'lib/images/interwiki.png) 0px 1px no-repeat;'; 335 echo ' padding: 1px 0px 1px 16px;'; 336 echo '}'; 337 338 // additional styles when icon available 339 $iwlinks = getInterwiki(); 340 foreach(array_keys($iwlinks) as $iw){ 341 $class = preg_replace('/[^_\-a-z0-9]+/i','_',$iw); 342 if(@file_exists(DOKU_INC.'lib/images/interwiki/'.$iw.'.png')){ 343 echo "a.iw_$class {"; 344 echo ' background-image: url('.DOKU_BASE.'lib/images/interwiki/'.$iw.'.png)'; 345 echo '}'; 346 }elseif(@file_exists(DOKU_INC.'lib/images/interwiki/'.$iw.'.gif')){ 347 echo "a.iw_$class {"; 348 echo ' background-image: url('.DOKU_BASE.'lib/images/interwiki/'.$iw.'.gif)'; 349 echo '}'; 350 } 351 } 352} 353 354/** 355 * Prints classes for file download links 356 * 357 * @author Andreas Gohr <andi@splitbrain.org> 358 */ 359function css_filetypes(){ 360 361 // default style 362 echo '.mediafile {'; 363 echo ' background: transparent url('.DOKU_BASE.'lib/images/fileicons/file.png) 0px 1px no-repeat;'; 364 echo ' padding-left: 18px;'; 365 echo ' padding-bottom: 1px;'; 366 echo '}'; 367 368 // additional styles when icon available 369 // scan directory for all icons 370 $exts = array(); 371 if($dh = opendir(DOKU_INC.'lib/images/fileicons')){ 372 while(false !== ($file = readdir($dh))){ 373 if(preg_match('/([_\-a-z0-9]+(?:\.[_\-a-z0-9]+)*?)\.(png|gif)/i',$file,$match)){ 374 $ext = strtolower($match[1]); 375 $type = '.'.strtolower($match[2]); 376 if($ext!='file' && (!isset($exts[$ext]) || $type=='.png')){ 377 $exts[$ext] = $type; 378 } 379 } 380 } 381 closedir($dh); 382 } 383 foreach($exts as $ext=>$type){ 384 $class = preg_replace('/[^_\-a-z0-9]+/','_',$ext); 385 echo ".mf_$class {"; 386 echo ' background-image: url('.DOKU_BASE.'lib/images/fileicons/'.$ext.$type.')'; 387 echo '}'; 388 } 389} 390 391/** 392 * Loads a given file and fixes relative URLs with the 393 * given location prefix 394 */ 395function css_loadfile($file,$location=''){ 396 if(!@file_exists($file)) return ''; 397 $css = io_readFile($file); 398 if(!$location) return $css; 399 400 $css = preg_replace('#(url\([ \'"]*)(?!/|data:|http://|https://| |\'|")#','\\1'.$location,$css); 401 $css = preg_replace('#(@import\s+[\'"])(?!/|data:|http://|https://)#', '\\1'.$location, $css); 402 403 return $css; 404} 405 406/** 407 * Converte local image URLs to data URLs if the filesize is small 408 * 409 * Callback for preg_replace_callback 410 */ 411function css_datauri($match){ 412 global $conf; 413 414 $pre = unslash($match[1]); 415 $base = unslash($match[2]); 416 $url = unslash($match[3]); 417 $ext = unslash($match[4]); 418 419 $local = DOKU_INC.$url; 420 $size = @filesize($local); 421 if($size && $size < $conf['cssdatauri']){ 422 $data = base64_encode(file_get_contents($local)); 423 } 424 if($data){ 425 $url = '\'data:image/'.$ext.';base64,'.$data.'\''; 426 }else{ 427 $url = $base.$url; 428 } 429 return $pre.$url; 430} 431 432 433/** 434 * Returns a list of possible Plugin Styles (no existance check here) 435 * 436 * @author Andreas Gohr <andi@splitbrain.org> 437 */ 438function css_pluginstyles($mediatype='screen'){ 439 global $lang; 440 $list = array(); 441 $plugins = plugin_list(); 442 foreach ($plugins as $p){ 443 $list[DOKU_PLUGIN."$p/$mediatype.css"] = DOKU_BASE."lib/plugins/$p/"; 444 $list[DOKU_PLUGIN."$p/$mediatype.less"] = DOKU_BASE."lib/plugins/$p/"; 445 // alternative for screen.css 446 if ($mediatype=='screen') { 447 $list[DOKU_PLUGIN."$p/style.css"] = DOKU_BASE."lib/plugins/$p/"; 448 $list[DOKU_PLUGIN."$p/style.less"] = DOKU_BASE."lib/plugins/$p/"; 449 } 450 // @deprecated 2012-04-09: rtl will cease to be a mode of its own, 451 // please use "[dir=rtl]" in any css file in all, screen or print mode instead 452 if($lang['direction'] == 'rtl'){ 453 $list[DOKU_PLUGIN."$p/rtl.css"] = DOKU_BASE."lib/plugins/$p/"; 454 } 455 } 456 return $list; 457} 458 459/** 460 * Very simple CSS optimizer 461 * 462 * @author Andreas Gohr <andi@splitbrain.org> 463 */ 464function css_compress($css){ 465 //strip comments through a callback 466 $css = preg_replace_callback('#(/\*)(.*?)(\*/)#s','css_comment_cb',$css); 467 468 //strip (incorrect but common) one line comments 469 $css = preg_replace('/(?<!:)\/\/.*$/m','',$css); 470 471 // strip whitespaces 472 $css = preg_replace('![\r\n\t ]+!',' ',$css); 473 $css = preg_replace('/ ?([;,{}\/]) ?/','\\1',$css); 474 $css = preg_replace('/ ?: /',':',$css); 475 476 // number compression 477 $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" 478 $css = preg_replace('/([: ])\.(0)+((?:pt|pc|in|mm|cm|em|ex|px)\b|%)(?=[^\{]*[;\}])/', '$1$2', $css); // ".0em" to "0" 479 $css = preg_replace('/([: ]0)0*(\.0*)?((?:pt|pc|in|mm|cm|em|ex|px)(?=[^\{]*[;\}])\b|%)/', '$1', $css); // "0.0em" to "0" 480 $css = preg_replace('/([: ]\d+)(\.0*)((?:pt|pc|in|mm|cm|em|ex|px)(?=[^\{]*[;\}])\b|%)/', '$1$3', $css); // "1.0em" to "1em" 481 $css = preg_replace('/([: ])0+(\d+|\d*\.\d+)((?:pt|pc|in|mm|cm|em|ex|px)(?=[^\{]*[;\}])\b|%)/', '$1$2$3', $css); // "001em" to "1em" 482 483 // shorten attributes (1em 1em 1em 1em -> 1em) 484 $css = preg_replace('/(?<![\w\-])((?:margin|padding|border|border-(?:width|radius)):)([\w\.]+)( \2)+(?=[;\}]| !)/', '$1$2', $css); // "1em 1em 1em 1em" to "1em" 485 $css = preg_replace('/(?<![\w\-])((?:margin|padding|border|border-(?:width)):)([\w\.]+) ([\w\.]+) \2 \3(?=[;\}]| !)/', '$1$2 $3', $css); // "1em 2em 1em 2em" to "1em 2em" 486 487 // shorten colors 488 $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); 489 490 return $css; 491} 492 493/** 494 * Callback for css_compress() 495 * 496 * Keeps short comments (< 5 chars) to maintain typical browser hacks 497 * 498 * @author Andreas Gohr <andi@splitbrain.org> 499 */ 500function css_comment_cb($matches){ 501 if(strlen($matches[2]) > 4) return ''; 502 return $matches[0]; 503} 504 505//Setup VIM: ex: et ts=4 : 506