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',realpath(dirname(__FILE__).'/../../../../').'/'); 10require_once(DOKU_INC.'inc/init.php'); 11 12// ---------------------- functions ------------------------------ 13 14/** 15 * Output all needed Styles 16 * 17 * @author Andreas Gohr <andi@splitbrain.org> 18 */ 19function css_ckg_out($path, $tpl = "") 20{ 21 global $conf; 22 global $lang; 23 global $config_cascade; 24 global $INPUT; 25 $copy = $INPUT->str('ckg_save_ss',FALSE); 26 chdir($path); 27 28 $mediatypes = array('screen', 'all'); 29 $type = ''; 30 31 if(!$tpl) { 32 $tpl = $conf['template']; 33 34 if($copy) { 35 $copy_path = DOKU_PLUGIN . 'ckgedit/ckeditor/css/_style.css'; 36 msg($copy_path,1); 37 } 38 } 39 40 // load styl.ini 41 $styleini = css_ckg_styleini($tpl); 42 43 // if old 'default' userstyle setting exists, make it 'screen' userstyle for backwards compatibility 44 if (isset($config_cascade['userstyle']['default'])) { 45 $config_cascade['userstyle']['screen'] = $config_cascade['userstyle']['default']; 46 } 47 48 // Array of needed files and their web locations, the latter ones 49 // are needed to fix relative paths in the stylesheets 50 $files = array(); 51 foreach($mediatypes as $mediatype) { 52 $files[$mediatype] = array(); 53 // load core styles 54 $files[$mediatype][DOKU_INC.'lib/styles/'.$mediatype.'.css'] = DOKU_BASE.'lib/styles/'; 55 56 // load template styles 57 if (isset($styleini['stylesheets'][$mediatype])) { 58 $files[$mediatype] = array_merge($files[$mediatype], $styleini['stylesheets'][$mediatype]); 59 } 60 // load user styles 61 if(!empty($config_cascade['userstyle'][$mediatype])) { 62 foreach($config_cascade['userstyle'][$mediatype] as $userstyle) { 63 $files[$mediatype][$userstyle] = DOKU_BASE; 64 } 65 } 66 } 67 68 $css=""; 69 70 // build the stylesheet 71 foreach ($mediatypes as $mediatype) { 72 73 // print the default classes for interwiki links and file downloads 74 if ($mediatype == 'screen') { 75 $css .= '@media screen {'; 76 css_ckg_interwiki($css); 77 css_ckg_filetypes($css); 78 $css .= '}'; 79 } 80 81 $xcl = 'plugins|popup|fileuploader|toc|search|recent|diff|edit|form|admin|manager|media|modal'; 82 83 // load files 84 $css_ckg_content = ''; 85 foreach($files[$mediatype] as $file => $location) { 86 if(preg_match('#' .$xcl . '#',$file) ) { 87 continue; 88 } 89 $display = str_replace(fullpath(DOKU_INC), '', fullpath($file)); 90 $css_ckg_content .= "\n/* XXXXXXXXX $display XXXXXXXXX */\n"; 91 $css_ckg_content .= css_ckg_loadfile($file, $location); 92 } 93 switch ($mediatype) { 94 case 'screen': 95 $css .= NL.'@media screen { /* START screen styles */'.NL.$css_ckg_content.NL.'} /* /@media END screen styles */'.NL; 96 break; 97 case 'all': 98 default: 99 $css .= NL.'/* START rest styles */ '.NL.$css_ckg_content.NL.'/* END rest styles */'.NL; 100 break; 101 } 102 } 103 104 // apply style replacements 105 $css = css_ckg_applystyle($css, $styleini['replacements']); 106 // parse less 107 $css = css_ckg_parseless($css); 108 109 // embed small images right into the stylesheet 110 if($conf['cssdatauri']){ 111 $base = preg_quote(DOKU_BASE,'#'); 112 $css = preg_replace_callback('#(url\([ \'"]*)('.$base.')(.*?(?:\.(png|gif)))#i','css_ckg_datauri',$css); 113 } 114 115 $css = preg_replace("/(\#?|\.?|div\.)dokuwiki\.?/", '', $css); 116 117 $css = "@import 'additional.css';\n/* template: $tpl */\n@media screen {\n.$tpl{color:#ccc;}\n}\n" . $css; 118 $css .= ' 119 span.multi_p_open { 120 display: block; 121 } 122 body,html { 123 background-color: #fff; 124 background-image:none; 125 } 126 blockquote { 127 padding-left: .5em; 128 margin-left: 1.5em; 129 } 130' . "\n"; 131 132 if( io_saveFile($path . 'Styles/_style.css' ,$css)) { 133 if(isset($copy_path)) { ; 134 $retv = io_saveFile($copy_path,$css); 135 if(!$retv) msg("failed: " . $copy_path); 136 } 137 return 0; 138 } 139 else { 140 return 1; 141 } 142} 143 144/** 145 * Uses phpless to parse LESS in our CSS 146 * 147 * most of this function is error handling to show a nice useful error when 148 * LESS compilation fails 149 * 150 * @param $css 151 * @return string 152 */ 153function css_ckg_parseless($css) { 154 $less = new lessc(); 155 $less->importDir[] = DOKU_INC; 156 157 try { 158 return $less->compile($css); 159 } catch(Exception $e) { 160 // get exception message 161 $msg = str_replace(array("\n", "\r", "'"), array(), $e->getMessage()); 162 163 // try to use line number to find affected file 164 if(preg_match('/line: (\d+)$/', $msg, $m)){ 165 $msg = substr($msg, 0, -1* strlen($m[0])); //remove useless linenumber 166 $lno = $m[1]; 167 168 // walk upwards to last include 169 $lines = explode("\n", $css); 170 for($i=$lno-1; $i>=0; $i--){ 171 if(preg_match('/\/(\* XXXXXXXXX )(.*?)( XXXXXXXXX \*)\//', $lines[$i], $m)){ 172 // we found it, add info to message 173 $msg .= ' in '.$m[2].' at line '.($lno-$i); 174 break; 175 } 176 } 177 } 178 179 // something went wrong 180 $error = 'A fatal error occured during compilation of the CSS files. '. 181 'If you recently installed a new plugin or template it '. 182 'might be broken and you should try disabling it again. ['.$msg.']'; 183 184 msg($error); 185 186 exit; 187 } 188} 189 190/** 191 * Does placeholder replacements in the style according to 192 * the ones defined in a templates style.ini file 193 * 194 * This also adds the ini defined placeholders as less variables 195 * (sans the surrounding __ and with a ini_ prefix) 196 * 197 * @author Andreas Gohr <andi@splitbrain.org> 198 */ 199function css_ckg_applystyle($css, $replacements) { 200 // we convert ini replacements to LESS variable names 201 // and build a list of variable: value; pairs 202 $less = ''; 203 foreach((array) $replacements as $key => $value) { 204 $lkey = trim($key, '_'); 205 $lkey = '@ini_'.$lkey; 206 $less .= "$lkey: $value;\n"; 207 208 $replacements[$key] = $lkey; 209 } 210 211 // we now replace all old ini replacements with LESS variables 212 $css = strtr($css, $replacements); 213 214 // now prepend the list of LESS variables as the very first thing 215 $css = $less.$css; 216 return $css; 217} 218 219/** 220 * Load style ini contents 221 * 222 * Loads and merges style.ini files from template and config and prepares 223 * the stylesheet modes 224 * 225 * @author Andreas Gohr <andi@splitbrain.org> 226 * @param string $tpl the used template 227 * @return array with keys 'stylesheets' and 'replacements' 228 */ 229function css_ckg_styleini($tpl) { 230 $stylesheets = array(); // mode, file => base 231 $replacements = array(); // placeholder => value 232 233 // load template's style.ini 234 $incbase = tpl_incdir($tpl); 235 $webbase = tpl_basedir($tpl); 236 $ini = $incbase.'style.ini'; 237 if(file_exists($ini)){ 238 $data = parse_ini_file($ini, true); 239 240 // stylesheets 241 if(is_array($data['stylesheets'])) foreach($data['stylesheets'] as $file => $mode){ 242 $stylesheets[$mode][$incbase.$file] = $webbase; 243 } 244 245 // replacements 246 if(is_array($data['replacements'])){ 247 $replacements = array_merge($replacements, css_ckg_fixreplacementurls($data['replacements'],$webbase)); 248 } 249 } 250 251 // load configs's style.ini 252 $webbase = DOKU_BASE; 253 $ini = DOKU_CONF."tpl/$tpl/style.ini"; 254 $incbase = dirname($ini).'/'; 255 if(file_exists($ini)){ 256 $data = parse_ini_file($ini, true); 257 258 // stylesheets 259 if(isset($data['stylesheets']) && is_array($data['stylesheets'])) foreach($data['stylesheets'] as $file => $mode){ 260 $stylesheets[$mode][$incbase.$file] = $webbase; 261 } 262 263 // replacements 264 if(isset($data['replacements']) && is_array($data['replacements'])){ 265 $replacements = array_merge($replacements, css_ckg_fixreplacementurls($data['replacements'],$webbase)); 266 } 267 } 268 269 return array( 270 'stylesheets' => $stylesheets, 271 'replacements' => $replacements 272 ); 273} 274 275/** 276 * Amend paths used in replacement relative urls, refer FS#2879 277 * 278 * @author Chris Smith <chris@jalakai.co.uk> 279 */ 280function css_ckg_fixreplacementurls($replacements, $location) { 281 foreach($replacements as $key => $value) { 282 $replacements[$key] = preg_replace('#(url\([ \'"]*)(?!/|data:|http://|https://| |\'|")#','\\1'.$location,$value); 283 } 284 return $replacements; 285} 286 287/** 288 * Prints classes for interwikilinks 289 * 290 * Interwiki links have two classes: 'interwiki' and 'iw_$name>' where 291 * $name is the identifier given in the config. All Interwiki links get 292 * an default style with a default icon. If a special icon is available 293 * for an interwiki URL it is set in it's own class. Both classes can be 294 * overwritten in the template or userstyles. 295 * 296 * @author Andreas Gohr <andi@splitbrain.org> 297 */ 298function css_ckg_interwiki(&$css){ 299 300 // default style 301 $css .= 'a.interwiki {'; 302 $css .= ' background: transparent url('.DOKU_BASE.'lib/images/interwiki.png) 0px 1px no-repeat;'; 303 $css .= ' padding: 1px 0px 1px 16px;'; 304 $css .= '}'; 305 306 // additional styles when icon available 307 $iwlinks = getInterwiki(); 308 foreach(array_keys($iwlinks) as $iw){ 309 $class = preg_replace('/[^_\-a-z0-9]+/i','_',$iw); 310 if(@file_exists(DOKU_INC.'lib/images/interwiki/'.$iw.'.png')){ 311 $css .= "a.iw_$class {"; 312 $css .= ' background-image: url('.DOKU_BASE.'lib/images/interwiki/'.$iw.'.png)'; 313 $css .= '}'; 314 }elseif(@file_exists(DOKU_INC.'lib/images/interwiki/'.$iw.'.gif')){ 315 $css .= "a.iw_$class {"; 316 $css .= ' background-image: url('.DOKU_BASE.'lib/images/interwiki/'.$iw.'.gif)'; 317 $css .= '}'; 318 } 319 } 320} 321 322/** 323 * Prints classes for file download links 324 * 325 * @author Andreas Gohr <andi@splitbrain.org> 326 */ 327function css_ckg_filetypes(&$css){ 328 329 // default style 330 $css .= '.mediafile {'; 331 $css .= ' background: transparent url('.DOKU_BASE.'lib/images/fileicons/file.png) 0px 1px no-repeat;'; 332 $css .= ' padding-left: 18px;'; 333 $css .= ' padding-bottom: 1px;'; 334 $css .= '}'; 335 336 // additional styles when icon available 337 // scan directory for all icons 338 $exts = array(); 339 if($dh = opendir(DOKU_INC.'lib/images/fileicons')){ 340 while(false !== ($file = readdir($dh))){ 341 if(preg_match('/([_\-a-z0-9]+(?:\.[_\-a-z0-9]+)*?)\.(png|gif)/i',$file,$match)){ 342 $ext = strtolower($match[1]); 343 $type = '.'.strtolower($match[2]); 344 if($ext!='file' && (!isset($exts[$ext]) || $type=='.png')){ 345 $exts[$ext] = $type; 346 } 347 } 348 } 349 closedir($dh); 350 } 351 foreach($exts as $ext=>$type){ 352 $class = preg_replace('/[^_\-a-z0-9]+/','_',$ext); 353 $css .= ".mf_$class {"; 354 $css .= ' background-image: url('.DOKU_BASE.'lib/images/fileicons/'.$ext.$type.')'; 355 $css .= '}'; 356 } 357} 358 359/** 360 * Loads a given file and fixes relative URLs with the 361 * given location prefix 362 */ 363function css_ckg_loadfile($file,$location=''){ 364 $css_ckg_file = new DokuCssFile($file); 365 return $css_ckg_file->load($location); 366} 367 368/** 369 * Helper class to abstract loading of css/less files 370 * 371 * @author Chris Smith <chris@jalakai.co.uk> 372 */ 373class DokuCssFile { 374 375 protected $filepath; // file system path to the CSS/Less file 376 protected $location; // base url location of the CSS/Less file 377 private $relative_path = null; 378 379 public function __construct($file) { 380 $this->filepath = $file; 381 } 382 383 /** 384 * Load the contents of the css/less file and adjust any relative paths/urls (relative to this file) to be 385 * relative to the dokuwiki root: the web root (DOKU_BASE) for most files; the file system root (DOKU_INC) 386 * for less files. 387 * 388 * @param string $location base url for this file 389 * @return string the CSS/Less contents of the file 390 */ 391 public function load($location='') { 392 if (!file_exists($this->filepath)) return ''; 393 394 $css = io_readFile($this->filepath); 395 if (!$location) return $css; 396 397 $this->location = $location; 398 399 $css = preg_replace_callback('#(url\( *)([\'"]?)(.*?)(\2)( *\))#',array($this,'replacements'),$css); 400 $css = preg_replace_callback('#(@import\s+)([\'"])(.*?)(\2)#',array($this,'replacements'),$css); 401 402 return $css; 403 } 404 405 /** 406 * Get the relative file system path of this file, relative to dokuwiki's root folder, DOKU_INC 407 * 408 * @return string relative file system path 409 */ 410 private function getRelativePath(){ 411 412 if (is_null($this->relative_path)) { 413 $basedir = array(DOKU_INC); 414 415 $basedir = array_map('preg_quote_cb', $basedir); 416 $regex = '/^('.join('|',$basedir).')/'; 417 $this->relative_path = preg_replace($regex, '', dirname($this->filepath)); 418 } 419 420 return $this->relative_path; 421 } 422 423 /** 424 * preg_replace callback to adjust relative urls from relative to this file to relative 425 * to the appropriate dokuwiki root location as described in the code 426 * 427 * @param array see http://php.net/preg_replace_callback 428 * @return string see http://php.net/preg_replace_callback 429 */ 430 public function replacements($match) { 431 432 // not a relative url? - no adjustment required 433 if (preg_match('#^(/|data:|https?://)#',$match[3])) { 434 return $match[0]; 435 } 436 // a less file import? - requires a file system location 437 else if (substr($match[3],-5) == '.less') { 438 if ($match[3][0] != '/') { 439 $match[3] = $this->getRelativePath() . '/' . $match[3]; 440 } 441 } 442 // everything else requires a url adjustment 443 else { 444 $match[3] = $this->location . $match[3]; 445 } 446 447 return join('',array_slice($match,1)); 448 } 449} 450 451/** 452 * Convert local image URLs to data URLs if the filesize is small 453 * 454 * Callback for preg_replace_callback 455 */ 456function css_ckg_datauri($match){ 457 global $conf; 458 459 $pre = unslash($match[1]); 460 $base = unslash($match[2]); 461 $url = unslash($match[3]); 462 $ext = unslash($match[4]); 463 464 $local = DOKU_INC.$url; 465 $size = @filesize($local); 466 if($size && $size < $conf['cssdatauri']){ 467 $data = base64_encode(file_get_contents($local)); 468 } 469 if($data){ 470 $url = 'data:image/'.$ext.';base64,'.$data; 471 }else{ 472 $url = $base.$url; 473 } 474 return $pre.$url; 475} 476 477 478 479/** 480 * Very simple CSS optimizer 481 * 482 * @author Andreas Gohr <andi@splitbrain.org> 483 */ 484function css_ckg_compress($css){ 485 //strip comments through a callback 486 $css = preg_replace_callback('#(/\*)(.*?)(\*/)#s','css_ckg_comment_cb',$css); 487 488 //strip (incorrect but common) one line comments 489 $css = preg_replace('/(?<!:)\/\/.*$/m','',$css); 490 491 // strip whitespaces 492 $css = preg_replace('![\r\n\t ]+!',' ',$css); 493 $css = preg_replace('/ ?([;,{}\/]) ?/','\\1',$css); 494 $css = preg_replace('/ ?: /',':',$css); 495 496 // number compression 497 $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" 498 $css = preg_replace('/([: ])\.(0)+((?:pt|pc|in|mm|cm|em|ex|px)\b|%)(?=[^\{]*[;\}])/', '$1$2', $css); // ".0em" to "0" 499 $css = preg_replace('/([: ]0)0*(\.0*)?((?:pt|pc|in|mm|cm|em|ex|px)(?=[^\{]*[;\}])\b|%)/', '$1', $css); // "0.0em" to "0" 500 $css = preg_replace('/([: ]\d+)(\.0*)((?:pt|pc|in|mm|cm|em|ex|px)(?=[^\{]*[;\}])\b|%)/', '$1$3', $css); // "1.0em" to "1em" 501 $css = preg_replace('/([: ])0+(\d+|\d*\.\d+)((?:pt|pc|in|mm|cm|em|ex|px)(?=[^\{]*[;\}])\b|%)/', '$1$2$3', $css); // "001em" to "1em" 502 503 // shorten attributes (1em 1em 1em 1em -> 1em) 504 $css = preg_replace('/(?<![\w\-])((?:margin|padding|border|border-(?:width|radius)):)([\w\.]+)( \2)+(?=[;\}]| !)/', '$1$2', $css); // "1em 1em 1em 1em" to "1em" 505 $css = preg_replace('/(?<![\w\-])((?:margin|padding|border|border-(?:width)):)([\w\.]+) ([\w\.]+) \2 \3(?=[;\}]| !)/', '$1$2 $3', $css); // "1em 2em 1em 2em" to "1em 2em" 506 507 // shorten colors 508 $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); 509 510 return $css; 511} 512 513/** 514 * Callback for css_ckg_compress() 515 * 516 * Keeps short comments (< 5 chars) to maintain typical browser hacks 517 * 518 * @author Andreas Gohr <andi@splitbrain.org> 519 */ 520function css_ckg_comment_cb($matches){ 521 if(strlen($matches[2]) > 4) return ''; 522 return $matches[0]; 523} 524 525