You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

525 lines
17 KiB

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