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