Merge commit 'catalyst/MOODLE_19_STABLE' into mdl19-linuxchix
[moodle-linuxchix.git] / theme / chameleon / ui / ChameleonCSS.class.php
blob28c0bda06c4549dd3cd6b1d5dd0e08364be93fbc
1 <?php
3 class ChameleonCSS {
4 var $error;
5 var $base;
7 var $perm;
8 var $temp;
10 function ChameleonCSS($base, $perm, $temp) {
11 $this->base = $base;
12 $this->perm = $perm;
13 $this->temp = $temp;
16 function update($file, $content = '') {
17 if (!is_writable($this->base . $this->$file)) {
18 $this->error = $this->$file . ' is not writeable, the file permissions are currently ' . $this->getfilepermissions($this->$file);
19 return false;
22 if (!$fp = fopen($this->base . $this->$file, 'w')) {
23 $this->error = 'couldn\'t open file';
24 return false;
26 fwrite($fp, stripslashes($content));
27 fclose($fp);
28 return true;
31 function getfilepermissions($file) {
32 return substr(sprintf('%o', fileperms($this->base . $file)), -4);
35 function read() {
36 $permcss = file_get_contents($this->base . $this->perm);
37 $tempcss = file_get_contents($this->base . $this->temp);
39 if ($permcss === false || $tempcss === false) {
40 $this->error = 'Couldn\'t read file';
41 return false;
44 $permcss = trim($permcss);
45 $tempcss = trim($tempcss);
47 if ($tempcss == '') {
48 return $permcss;
50 return $this->_merge($permcss, $tempcss);
56 function _merge($permcss, $tempcss) {
57 $csssrcs = array($this->_toobj($permcss), $this->_toobj($tempcss));
59 $merged = array();
61 for ($i = 0; $i < 2; ++$i) {
62 foreach ($csssrcs[$i] as $sel => $rule) {
63 $newsel = false;
64 if (!isset($merged[$sel])) {
65 $merged[$sel] = array();
66 $newsel = true;
68 foreach ($rule as $prop => $value) {
69 $merged[$sel][$prop] = $value;
71 if ($i > 0 && !$newsel) {
72 foreach ($merged[$sel] as $prop => $value) {
73 if (!isset($csssrcs[$i][$sel][$prop])) {
74 unset($merged[$sel][$prop]);
79 if ($i > 0) {
80 foreach ($merged as $sel => $value) {
81 if (!isset($csssrcs[$i][$sel])) {
82 unset($merged[$sel]);
88 return $this->_tostr($merged);
94 function _toobj($cssstr) {
95 $cssobj = array();
96 $end = strpos($cssstr, '}');
97 while ($end !== false) {
98 $currule = substr($cssstr, 0, $end);
99 $parts = explode('{', $currule);
100 $selector = trim($parts[0]);
101 $rules = trim($parts[1]);
102 $rulesarr = explode(';', $rules);
104 $num = count($rulesarr);
105 for ($i = 0; $i < $num; ++$i) {
106 if (strpos($rulesarr[$i], ':') === false) {
107 break;
109 $rule = explode(':', $rulesarr[$i]);
110 $prop = trim($rule[0]);
111 $value = trim($rule[1]);
113 if (!isset($cssobj[$selector])) {
114 $cssobj[$selector] = array();
116 $cssobj[$selector][$prop] = $value;
118 $cssstr = substr($cssstr, $end + 1);
119 $end = strpos($cssstr, '}');
121 return $cssobj;
125 function _tostr($cssobj) {
126 $cssstr = '';
127 foreach ($cssobj as $sel => $rule) {
128 $cssstr .= "$sel {\n";
129 foreach ($rule as $prop => $value) {
130 $cssstr .= " $prop: $value;\n";
132 $cssstr .= "}\n";
134 return $cssstr;