/
Class-CSS.php
1785 lines (1559 loc) · 63.5 KB
/
Class-CSS.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Wess (WEdge pre-proceSS) is a pre-parser for CSS files, bringing new possibilities to CSS.
*
* Wedge (http://wedge.org)
* Copyright © 2010 René-Gilles Deberdt, wedge.org
* License: http://wedge.org/license/
*/
/**
* Uses some code and ideas from Shaun Inman's CSS Cacheer library
* http://www.shauninman.com/archive/2008/05/30/check_out_css_cacheer
* Also implements some ideas from Sass (http://sass-lang.com)
*/
class wess
{
/**
* The HSL to RGB and RGB to HSL functions are based on ABC algorithms from the CWI,
* based on 'Fundamentals of Interactive Computer Graphics' (J.D. Foley, 1982.)
*/
protected static function rgb2hex($r, $g, $b)
{
$hex = sprintf('%02x%02x%02x', $r, $g, $b);
if (preg_match('~^([0-9a-f])\1([0-9a-f])\2([0-9a-f])\3?$~i', $hex, $m))
return '#' . $m[1] . $m[2] . $m[3];
return '#' . $hex;
}
// Converts from a RGBA color to a string
protected static function color2string($r, $g, $b, $a)
{
$a = max(0, min(1, $a));
$r = max(0, min(255, round($r)));
$g = max(0, min(255, round($g)));
$b = max(0, min(255, round($b)));
return $a === 1 ? wess::rgb2hex($r, $g, $b) : "rgba($r, $g, $b, $a)";
}
// Converts from hue to RGB
protected static function hue2rgb($m1, $m2, $h)
{
$h < 0 ? $h++ : ($h > 1 ? $h-- : '');
if ($h * 6 < 1)
return $m2 + ($m1 - $m2) * $h * 6;
if ($h * 2 < 1)
return $m1;
if ($h * 3 < 2)
return $m2 + ($m1 - $m2) * (2 / 3 - $h) * 6;
return $m2;
}
/**
* Converts from HSL to RGB
* Algorithm from the CSS3 spec: http://www.w3.org/TR/css3-color/
* $h(ue) is in degrees, $s(aturation) and $l(ightness) are in percents
*/
protected static function hsl2rgb($h, $s, $l, $a)
{
while ($h < 0)
$h += 360;
$h = fmod($h, 360) / 360;
$s = max(0, min(1, $s / 100));
$l = max(0, min(1, $l / 100));
$m1 = $l <= 0.5 ? $l * ($s + 1) : $l + $s - $l * $s;
$m2 = $l * 2 - $m1;
return array(
'r' => wess::hue2rgb($m1, $m2, $h + 1 / 3) * 255,
'g' => wess::hue2rgb($m1, $m2, $h) * 255,
'b' => wess::hue2rgb($m1, $m2, $h - 1 / 3) * 255,
'a' => $a
);
}
/**
* Converts from RGB to HSL
* $r/$g/$b are RGB values (0-255)
*/
protected static function rgb2hsl($r, $g, $b, $a)
{
$r /= 255;
$g /= 255;
$b /= 255;
$max = max($r, $g, $b);
$min = min($r, $g, $b);
$c = $max - $min;
$l = ($max + $min) / 2;
if ($max === $min)
return array('h' => 0, 's' => 0, 'l' => $l * 100, 'a' => $a);
if ($max === $r)
{
$h = ($g - $b) / $c;
while ($h < 0)
$h += 6;
$h = fmod($h, 6);
}
elseif ($max === $g)
$h = (($b - $r) / $c) + 2;
else
$h = (($r - $g) / $c) + 4;
return array(
'h' => $h * 60,
's' => $c / ($l <= 0.5 ? $l + $l : 2 - $l - $l) * 100,
'l' => $l * 100,
'a' => $a
);
}
// Converts from a string to a RGBA or HSLA color
protected static function string2color($data)
{
// We'll only support the standard (non-CSS3) color names. Who uses 'PapayaWhip' anyway?
static $colors = array(
'aqua' => '00ffff', 'black' => '000000', 'blue' => '0000ff',
'fuchsia' => 'ff00ff', 'gray' => '808080', 'green' => '008000',
'grey' => '808080', 'lime' => '00ff00', 'maroon' => '800000',
'navy' => '000080', 'olive' => '808000', 'purple' => '800080',
'red' => 'ff0000', 'silver' => 'c0c0c0', 'teal' => '008080',
'white' => 'ffffff', 'yellow' => 'ffff00'
);
if (!function_exists('to_max'))
{
function to_max($d, $max = 255)
{
return substr($d, -1) === '%' ? (int) substr($d, 0, -1) / 100 * $max : $d;
}
}
// Extract color data
preg_match('~(?:(rgb|hsl)a?\(\h*(\d+%?)\h*,\h*(\d+%?)\h*,\h*(\d+%?)(?:\h*\,\h*(\d*(?:\.\d+)?%?))?\h*\)|#([0-9a-f]{6}|[0-9a-f]{3}))~', $data, $rgb);
$color = $hsl = 0;
if (empty($rgb[0]))
{
$data = explode(',', $data);
$rgb[0] = $data[0];
$data = trim($data[0]);
if (!isset($colors[$data]))
return false;
$color = array(hexdec(substr($colors[$data], 0, 2)), hexdec(substr($colors[$data], 2, 2)), hexdec(substr($colors[$data], -2)), 1);
}
elseif ($rgb[2] !== '' && $rgb[1] === 'rgb')
$color = array(to_max($rgb[2]), to_max($rgb[3]), to_max($rgb[4]), !isset($rgb[5]) || $rgb[5] === '' ? 1 : to_max((float) $rgb[5], 1));
elseif ($rgb[2] !== '')
$hsl = array('h' => to_max($rgb[2], 360), 's' => to_max($rgb[3], 100), 'l' => to_max($rgb[4], 100), 'a' => $rgb[5] === '' ? 1 : to_max((float) $rgb[5], 1));
elseif ($rgb[6] !== '' && isset($rgb[6][3]))
$color = array(hexdec(substr($rgb[6], 0, 2)), hexdec(substr($rgb[6], 2, 2)), hexdec(substr($rgb[6], -2)), 1);
elseif ($rgb[6] !== '')
$color = array(hexdec($rgb[6][0] . $rgb[6][0]), hexdec($rgb[6][1] . $rgb[6][1]), hexdec($rgb[6][2] . $rgb[6][2]), 1);
else
$color = array(255, 255, 255, 1);
return array($rgb[0], $color, $hsl);
}
function process(&$css) {}
}
class wess_mixin extends wess
{
var $default = array();
var $target;
private function def($a)
{
return $this->default[$this->target][(int) $a[1]];
}
function process(&$css)
{
$mix = array();
// Find mixin declarations, capture their tab level and stop at the first empty or unindented line.
if (preg_match_all('~@mixin\h+(?:{([^}]+)}\h*)?([\w.-]+)(?:\(([^()]+)\))?[^\v]*\v+(\h+)([^\v]*\n+)((?:\4\h*[^\v]*\v+)*)~i', $css, $mixins, PREG_SET_ORDER))
{
// We start by building an array of mixins...
foreach ($mixins as $mixin)
{
// Remove the mixin declaration
$css = str_replace($mixin[0], '', $css);
if (!empty($mixin[1]) && !we::is(we::$user['extra_tests'][] = strtolower($mixin[1])))
continue;
// Create our mixin entry...
$mix[$mixin[2]] = rtrim(str_replace("\n" . $mixin[4], "\n", $mixin[5] . $mixin[6]));
// Do we have variables to set?
if (!empty($mixin[3]) && preg_match_all('~(\$[\w-]+)\h*(?:[:=]\h*"?([^",]+))?~', $mixin[3], $variables, PREG_SET_ORDER))
{
foreach ($variables as $i => $var)
{
$mix[$mixin[2]] = str_replace($var[1], '$%' . $i . '%', $mix[$mixin[2]]);
$def[$mixin[2]][$i] = isset($var[2]) ? trim($var[2], '" ') : '';
}
}
}
}
// ...And then we apply them to the CSS file.
// We'll repeat the process as long as there are mixin calls left, allowing for nested mixins.
for ($loop = 0; $loop < 10; $loop++)
{
$repa = array();
$selector_regex = '([abipqsu]|[!+>&#*@:.a-z0-9][^{};,\n"()]+)';
// Search for 'mixin: .otherclass' rules.
if (preg_match_all('~(?<=\n)(\h*)mixin\h*:\h*' . $selector_regex . '\h*(?:\(([^\n]+)\))?~i', $css, $targets, PREG_SET_ORDER))
{
foreach ($targets as $mixin)
{
$rep = '';
$tg = $mixin[2];
if (isset($mix[$tg]))
{
$rep = $mix[$tg];
if (!empty($mixin[3]))
{
$variables = explode(',', $mixin[3]);
$i = 0;
foreach ($variables as $i => $var)
if (!empty($var))
$rep = str_replace('$%' . $i . '%', trim($var, '" '), $rep);
}
// Replace all missing variables with their default value.
if (!empty($def[$tg]))
{
$this->default = $def;
$this->target = $tg;
$rep = preg_replace_callback('~\$%(\d+)%~', array($this, 'def'), $rep);
}
}
// Or is this a simple non-mixin selector we want to mix with? (Child selectors aren't allowed for these.)
elseif (preg_match_all('~(?<=\n)' . preg_quote($tg, '~') . '\h*(?:[a-zA-Z]+\h*)?\v+(\h+)([^\v]*\v+)((?:\1[^\v]*\v+)*)~', $css, $selectors, PREG_SET_ORDER))
foreach ($selectors as $sel)
$rep .= "\n" . rtrim(str_replace("\n" . $sel[1], "\n", $sel[2] . $sel[3]));
$repa[$mixin[0]] = $mixin[1] . str_replace("\n", "\n" . $mixin[1], $rep);
}
}
// ...We should also do '.class mixes .otherclass' here.
if (preg_match_all('~(?<=\n)(\h*)(.*?)\h+mixes\h*' . $selector_regex . '(?:\(([^\n]+)\))?~i', $css, $targets, PREG_SET_ORDER))
{
foreach ($targets as $mixin)
{
$rep = '';
$tg = trim($mixin[3]);
if (isset($mix[$tg]))
{
$rep = $mix[$tg];
if (!empty($mixin[4]))
{
$variables = explode(',', $mixin[4]);
$i = 0;
foreach ($variables as $i => $var)
if (!empty($var))
$rep = str_replace('$%' . $i . '%', trim($var, '" '), $rep);
}
// Replace all missing variables with their default value.
if (!empty($def[$tg]))
{
$this->default = $def;
$this->target = $tg;
$rep = preg_replace_callback('~\$%(\d+)%~', array($this, 'def'), $rep);
}
}
// Or is this a simple non-mixin selector we want to mix with? (Child selectors aren't allowed for these.)
elseif (preg_match_all('~(?<=\n)' . preg_quote($tg, '~') . '\h*(?:[a-zA-Z]+\h*)?\v+(\h+)([^\v]*\v+)((?:\1[^\v]*\v+)*)~', $css, $selectors, PREG_SET_ORDER))
foreach ($selectors as $sel)
$rep .= "\n" . rtrim(str_replace("\n" . $sel[1], "\n", $sel[2] . $sel[3]));
$newline = "\n" . $mixin[1] . (isset($mixin[1][0]) ? $mixin[1][0] : "\t");
$repa[$mixin[0]] = $mixin[1] . $mixin[2] . $newline . str_replace("\n", $newline, $rep);
}
}
if (!empty($repa))
{
// Sort the array by key length, to avoid conflicts.
$keys = array_map('strlen', array_keys($repa));
array_multisort($keys, SORT_DESC, $repa);
$css = str_replace(array_keys($repa), array_values($repa), $css);
}
else
break;
}
}
}
/**
* Find '@dynamic my_function', then execute dynamic_my_function() to replace them.
* You may add parameters to the function call: @dynamic my_function(string, number)
* Just don't use quotes around the parameters, they're all returned as trimmed strings.
* Obviously, don't use a comma or spaces as a parameter either. Why would you do that anyway?
*/
class wess_dynamic extends wess
{
function process(&$css)
{
static $done = array();
if (preg_match_all('~@dynamic\h+([a-z0-9_]+)(?:\h+\([^)]*\))?~i', $css, $functions, PREG_SET_ORDER))
{
foreach ($functions as $func)
{
$callback = 'dynamic_' . $func[1];
if (is_callable($callback))
{
if (isset($done[$func[0]]))
continue;
$data = isset($func[2]) ? call_user_func_array($callback, array_map('trim', explode(',', $func[2]))) : $callback();
$css = preg_replace('~' . preg_quote($func[0], '~') . '~i', $data, $css);
$done[$func[0]] = true;
}
}
}
}
}
// Dynamic CSS constants.
class wess_var extends wess
{
// Sort arrays by their content length. The trim() is 10 times slower but needed. It's still super-fast.
private static function lensort($a, $b)
{
return strlen(trim($a)) < strlen(trim($b));
}
private static function develop_var($k, $limit = 0)
{
global $css_vars;
if (strpos($css_vars[$k], '$') !== false)
foreach ($css_vars as $key => $val)
$css_vars[$k] = str_replace($key, $val, $css_vars[$k]);
if (strpos($css_vars[$k], '$') !== false && $limit < 8)
wess_var::develop_var($k, ++$limit);
}
function process(&$css)
{
global $css_vars, $alphamix;
// Reuse CSS variables from Wedge.
$css_vars = isset($css_vars) ? $css_vars : array();
/*
Double quotes are only required for empty strings.
Authors can specify conditions for the variable to be set,
depending on the browser, rtl, guest or member, i.e. anything
that can be queried with we::is(). Like this:
$variable = "rgba(2,4,6,.5)";
$variable {ie6,ie7,ie8} = rgb(1,2,3);
The only reason we're not accepting ":" in declarations is that
we want to be able to do this: (Check the last line carefully)
(common.css) $left = @is (rtl, right, left)
(anything.css) .class
border-$left: 1px solid $border-col
*/
if (preg_match_all('~^\h*(\$[\w-]+)\h*(?:{([^}]+)}\h*)?=\h*("?)(.*)\\3;?\s*$~m', $css, $matches))
{
// Sort the matches by key length, to avoid conflicts as much as possible.
$decs = $matches[0];
usort($decs, 'wess_var::lensort');
// Erase all traces of variable definitions.
$css = str_replace($decs, '', $css);
unset($decs);
// Build CSS vars, taking into account {tests} and self-references.
foreach ($matches[0] as $i => $dec)
if (empty($matches[2][$i]) || we::is(we::$user['extra_tests'][] = strtolower($matches[2][$i])))
$css_vars[$matches[1][$i]] = preg_replace('~' . preg_quote($matches[1][$i], '~') . '\b~', isset($css_vars[$matches[1][$i]]) ? $css_vars[$matches[1][$i]] : '', rtrim($matches[4][$i], '; '));
// Same as above, but for the actual variables.
$keys = array_map('strlen', array_keys($css_vars));
array_multisort($keys, SORT_DESC, $css_vars);
foreach ($css_vars as $key => $val)
wess_var::develop_var($key);
// We need to keep this one for later...
if (isset($css_vars['$alphamix']))
$alphamix = trim($css_vars['$alphamix'], '"');
}
// Replace @ifnull($var1, $var2) with $var1, or $var2 if $var1 doesn't exist.
while (preg_match_all('~@ifnull\h*\((\$[\w-]+)\s*,\s*+(?!@ifnull)\s*([^)]+)\s*\)~i', $css, $matches))
foreach ($matches[1] as $i => $var)
$css = str_replace($matches[0][$i], isset($css_vars[$var]) ? $var : $matches[2][$i], $css);
// Replace away!
if (!empty($css_vars))
$css = str_replace(array_keys($css_vars), array_values($css_vars), $css);
}
}
/**
* Conditionals, @if and @is (inline if).
* If you test for a browser condition, you may place your test anywhere in the code.
* If you test for a variable value, you can't declare mixins inside your test, because
* the test will only be run after mixins are already transformed.
*/
class wess_if extends wess
{
var $test_vars;
public function __construct($test_vars = false)
{
$this->test_vars = $test_vars;
}
function process(&$css)
{
// @is (condition[, if_true[, if_false]])
// This function will return if_true if true, or if_false if false. It will return literal 'true' and 'false' if no true/false are set (for use in variables.)
// !! Note: this has got to be one of my most amusing regexes... But still, it doesn't always
// correctly handle brackets. Add quotes around them if you run into any, err, problems. Lazy me.
$skipped = 0;
$strex = '\s*+("(?:[^"@]|@(?!is\h*\())*"|\'(?:[^\'@]|@(?!is\h*\())*\'|(?:[^\'",@]|@(?!is\h*\())(?:[^,@]|@(?!is\h*\())*)\s*+';
while (preg_match_all('~@is\h*\(' . $strex . '(?:,' . $strex . '(?:,' . str_replace(',', ')', $strex) . ')?)?\)~i', $css, $matches) > $skipped)
{
foreach ($matches[1] as $i => $match)
{
// First, remove quotes that might be around our test...
if ($match[0] == '\'' || $match[0] == '"')
$match = substr($match, 1, -1);
// If we're executing this before mixins, don't bother doing variables.
if (!$this->test_vars && strpos($match, '$') !== false)
{
$css = preg_replace('~@is\h+\(\h+' . preg_quote($match, '~') . '~', '@is (' . preg_replace('~(?<!")(\$\w+)\b~', '"$1"', $match), $css);
$skipped++;
continue;
}
// Are we doing a true/false test..?
if (empty($matches[2][$i]) && empty($matches[3][$i]))
{
$matches[2][$i] = 'true';
$matches[3][$i] = 'false';
}
if (we::is(we::$user['extra_tests'][] = $match))
{
if ($matches[2][$i][0] == '\'' || $matches[2][$i][0] == '"')
$matches[2][$i] = substr($matches[2][$i], 1, -1);
$css = str_replace($matches[0][$i], $matches[2][$i], $css);
}
else
{
if (!isset($matches[3][$i]))
$matches[3][$i] = '';
if ($matches[3][$i] !== '' && ($matches[3][$i][0] == '\'' || $matches[3][$i][0] == '"'))
$matches[3][$i] = substr($matches[3][$i], 1, -1);
$css = str_replace($matches[0][$i], $matches[3][$i], $css);
}
}
}
// @if / @else / @endif
// This one is cleaner, but more demanding in terms of structure. @endif is required,
// and all three commands need to be on the same tab level. Respect this or crash Wess.
// You can nest commands inside @if and @else as well.
// If PHP crashes, maybe it has too high a regex recursion limit, especially in Windows. Try uncommenting this:
// ini_set('pcre.recursion_limit', '524');
$skipped = 0;
while (preg_match_all('~(?<=\n)(\h*)@if\h+([^\n]*)(\n(?>[^@]|@(?!if\h))*?)\n\1@endif~i', $css, $matches, PREG_SET_ORDER) > $skipped)
{
foreach ($matches as $m)
{
$match = $m[2];
$parts = explode($m[1] . '@else', $m[3]);
if (!isset($parts[1])) // no @else?
$parts[1] = '';
$remove_tabs = preg_match('~\h+~', $m[3], $tabs) ? strlen($tabs[0]) - strlen($m[1]) : 0;
foreach ($parts as &$part)
$part = preg_replace('~\n\h{' . $remove_tabs . '}~', "\n", $part);
$i = -1;
$num = count($parts);
while (++$i < $num)
{
if (strtolower(substr($parts[$i], 0, 2)) == 'if' || strtolower(substr($parts[$i], 0, 3)) == ' if') // An @elseif, maybe?
{
$match = preg_match('~^if\h*([^\n]*)~', $parts[$i], $newif) ? trim($newif[1]) : 'true';
$parts[$i] = substr($parts[$i], strlen($newif[0]));
}
// If we're executing this before mixins, don't bother doing variables.
if (!$this->test_vars && strpos($match, '$') !== false)
{
$css = preg_replace('~@if\h+' . preg_quote($match, '~') . '~', '@if ' . preg_replace('~(?<!")(\$\w+)\b~', '"$1"', $match), $css);
$skipped++;
continue 2;
}
// And finally, the actual battery of tests.
if ($match !== '' && we::is(we::$user['extra_tests'][] = $match))
break;
$match = 'true';
}
$css = str_replace($m[0], $i < $num ? $parts[$i] : '', $css);
}
}
}
}
/**
* Apply color functions to the CSS file.
*/
class wess_color extends wess
{
var $arg, $parg;
// Transforms "gradient: rgba(1,2,3,.5)" into background-color, or the equivalent IE filter.
// Transforms "gradient: color1, color2, [angle]" into linear-gradient([angle], color1, color2), or the equivalent IE filter. Default angle is 180deg (top to bottom).
// The angle parameter is optional. You can either use a direction (to left...), or the angle of the destination (0deg = from bottom to top)
protected static function gradient_background($input)
{
$bg1 = $input[2];
$bg2 = empty($input[3]) ? $bg1 : $input[3];
$dir = empty($input[4]) ? '180deg' : $input[4];
// IE 6, 7 and 8 will need a filter to apply the transparency effect, except for IE9. Also, IE8 can do without hasLayout.
if (we::is('ie8down') || (we::is('ie9') && $bg1 != $bg2))
{
if (preg_match('~^#[0-9a-f]{3}$~i', $bg1))
$bg1 = '#' . $bg1[1] . $bg1[1] . $bg1[2] . $bg1[2] . $bg1[3] . $bg1[3];
if (preg_match('~^#[0-9a-f]{3}$~i', $bg2))
$bg2 = '#' . $bg2[1] . $bg2[1] . $bg2[2] . $bg2[2] . $bg2[3] . $bg2[3];
return $input[1] . 'background: none' . $input[1] . (we::is('ie6,ie7') ? 'zoom: 1' . $input[1] : '') .
'filter:progid:DXImageTransform.Microsoft.Gradient(startColorStr=' . $bg1 . ',endColorStr=' . $bg2 . ($dir == 'left' ? ',GradientType=1' : '') . ')';
}
// Better than nothing...
if (we::is('ie') && we::$browser['version'] < 10)
return $input[1] . 'background-color: ' . $bg1;
return $input[1] . 'background: ' . sprintf(we::is('safari') && we::$browser['version'] < 5.1 ?
'-webkit-gradient(linear, 0%% 0%%, ' . ($dir == 'left' ? '100%% 0%%' : '0%% 100%%') . ', from(%1$s), to(%2$s))' :
'linear-gradient(' . ($dir == '180deg' ? '' : $dir . ', ') . '%1$s, %2$s)',
$bg1,
$bg2
);
}
private function op($origin, $index = 0, $reverse = false)
{
$arg = $this->arg[$index];
$parg = isset($this->parg[$index]) ? $this->parg[$index] : null;
if ((isset($parg) && ($parg[0] === '+' || $parg[0] === '-')) || ($arg && ($arg[0] === '+' || $arg[0] === '-')))
return $origin + (isset($parg) ? $origin * $parg : $arg) * ($reverse ? -1 : 1);
return isset($parg) ? $parg : $arg;
}
// Now, go with the actual color parsing.
function process(&$css)
{
$nodupes = array();
// No need for a recursive regex, as we shouldn't have more than one level of nested brackets...
while (preg_match_all('~(strength|brightness|luma|saturation|hue|complement|average|alpha|channels)\(((?:(?:rgb|hsl)a?\([^()]+\)|[^()])+)\)~i', $css, $matches))
{
foreach ($matches[0] as $i => $dec)
{
if (isset($nodupes[$dec]))
continue;
$nodupes[$dec] = true;
$code = strtolower($matches[1][$i]);
$m = strtolower(trim($matches[2][$i]));
if (empty($m))
continue;
$rgb = wess::string2color($m);
if ($rgb === false)
{
// Unfortunately, the alpha() function can clash with the equivalent IE filter...
if ($code === 'alpha' && strpos($m, 'opacity') !== false)
$css = str_replace($dec, 'alpha_ms_wedge' . substr($dec, 5), $css);
// Syntax error? We just replace with red. Otherwise we'll end up in an infinite loop.
else
$css = str_replace($dec, 'red', $css);
continue;
}
$nc = 0;
$color = $rgb[1];
$hsl = $rgb[2];
$arg = array_map('trim', explode(',', substr($m, strlen($rgb[0]))));
$parg = array();
while ($arg && $arg[0] === '')
array_shift($arg);
$arg[0] = isset($arg[0]) ? $arg[0] : 5;
if ($code === 'channels' && !isset($arg[0], $arg[1], $arg[2], $arg[3]))
for ($i = 1; $i < 4; $i++)
$arg[$i] = isset($arg[$i]) ? $arg[$i] : '+0';
foreach ($arg as $i => $a)
$parg[$i] = substr($a, -1) === '%' ? ((float) substr($a, 0, -1)) / 100 : null;
$hsl = $hsl ? $hsl : wess::rgb2hsl($color[0], $color[1], $color[2], $color[3]);
/*
This is where we run our color functions...
- 'brightness' is an alias to 'luma'.
- 'strength' is a version of 'luma' that makes bright colors brighter, and dark colors darker.
- 'luma', 'saturation', 'alpha' and 'channels' change their behavior based on the value:
Use '+' or '-' signs to indicate a change relative to the old value.
+50% on a value of .3 will transform it to .45
-.15 on a value of .3 will transform it to .15
No sign means the new value will replace the old one.
.3 on a value of .424242 will transform it to .3
30% on a value of .424242 will transform it to .3
*/
$this->arg = $arg;
$this->parg = $parg;
if ($code === 'average' && !empty($rgb[0]))
{
// Extract the second color from our list. Technically, we COULD
// have an infinite number of colors... Is it any useful, though?
$rgb2 = wess::string2color(ltrim(substr($m, strlen($rgb[0])), ', '));
$color2 = $rgb2[1];
$hsl2 = $rgb2[2] ? $rgb2[2] : wess::rgb2hsl($rgb2[1][0], $rgb2[1][1], $rgb2[1][2], $rgb2[1][3]);
$hsl['h'] = ($hsl['h'] + $hsl2['h']) / 2;
$hsl['s'] = ($hsl['s'] + $hsl2['s']) / 2;
$hsl['l'] = ($hsl['l'] + $hsl2['l']) / 2;
$hsl['a'] = ($hsl['a'] + $hsl2['a']) / 2;
}
// Change alpha (transparency) level.
elseif ($code === 'alpha')
$hsl['a'] = $this->op($hsl['a']);
// Change color luma, i.e. lightness, i.e. overall brightness. 'Luma' sounded better.
elseif ($code === 'luma' || $code === 'brightness' || $code == 'strength')
$hsl['l'] = $this->op($hsl['l'], 0, $code === 'strength' && $hsl['l'] < 0.5);
// Change color saturation (if up, gets color further away from grayscale)
elseif ($code === 'saturation')
$hsl['s'] = $this->op($hsl['s']);
// Change color hue (moves it over the virtual color wheel by X degrees or X%)
elseif ($code === 'hue')
$hsl['h'] += $parg[0] ? $parg[0] * 360 : $arg[0];
// Get color's complement (retrieves the color at the opposite end of the color wheel)
elseif ($code === 'complement')
$hsl['h'] += 180;
// Change color's channels individually (red, green, blue and alpha components)
elseif ($code === 'channels')
{
if ($color === 0)
$color = wess::hsl2rgb($hsl['h'], $hsl['s'], $hsl['l'], $hsl['a']);
$nc = array(
'r' => $this->op($color[0], 0),
'g' => $this->op($color[1], 1),
'b' => $this->op($color[2], 2),
'a' => $this->op($color[3], 3)
);
}
else
{
// Do modders want to add their own color processor? Send them all the data they might need.
// If they want even more, send them the author. Careful though, he's French. He bites.
$hook = call_hook('css_color', array(&$nc, &$hsl, &$color, &$arg, &$parg, &$dec));
// Attention modders: at the end of your hook function, set $nc or $hsl,
// and then *return true* to tell Wedge you were here. Oh, and Brooks too.
if (empty($hook))
continue;
}
$nc = $nc ? $nc : wess::hsl2rgb($hsl['h'], $hsl['s'], $hsl['l'], $hsl['a']);
$css = str_replace($dec, wess::color2string($nc['r'], $nc['g'], $nc['b'], $nc['a']), $css);
}
}
$colval = '((?:rgb|hsl)a?\([^()]+\)|[^()\n,]+)';
$css = preg_replace_callback('~(\n\h*)gradient\h*:\h*' . $colval . '(?:\s*,\s*' . $colval . ')?(?:\s*,\s*(-?\w+(?: \w+)?)?)?~i', 'wess_color::gradient_background', $css);
$css = str_replace('alpha_ms_wedge', 'alpha', $css);
}
}
// Miscellaneous helper functions...
class wess_func extends wess
{
function process(&$css)
{
if (!preg_match_all('~\b(width|height)\(([^)]+)\)~i', $css, $matches))
return;
$done = array();
foreach ($matches[2] as $i => $file)
{
if (isset($done[$file]))
continue;
$done[$file] = true;
// Get dimensions from file. Try to turn it into absolute path if a URL was given.
list ($width, $height) = @getimagesize(str_replace(ROOT, ROOT_DIR, $file));
$css = str_replace(array('width(' . $file . ')', 'height(' . $file . ')'), array($width, $height), $css);
}
}
}
class wess_nesting extends wess
{
var $rules, $props;
// Sort the bases array by the first argument's length.
private static function lensort($a, $b)
{
return strlen($b[0]) - strlen($a[0]);
}
function process(&$css)
{
/******************************************************************************
Process nested selectors
******************************************************************************/
// Transform the CSS into a tree
$tree = str_replace('"', '#wedge-quote#', trim($css));
// Normal CSS syntax, if found, should be preserved.
$regular_css = array();
if (strpos($css, '{') !== false && strpos($css, '}') !== false)
$tree = preg_replace_callback(
'~(?<=^|[\s};])([!+>&#*@:.a-z0-9](?:[^{\n]|(?=,)\n)*?)\s*({(?>[^{}]+|(?1))*})~i',
function ($m) use (&$regular_css) {
$regular_css[] = $m[0];
return '.wedge_css_placeholder';
},
$tree
);
// Turn our simplified syntax into regular CSS.
// You must conform to the rules. It is my sworn duty to see that you do conform.
// If you're having problems indenting your code, just put it between brackets and use regular CSS.
$tree = preg_replace('~\v\h+(?=\v)~', '', $tree); // Delete blank lines
$atree = preg_split('~\v+~', $tree);
$tree = $ex_string = '';
$levels = array(0);
foreach (array_map('ltrim', $atree) as $n => $line)
{
$l = strlen($atree[$n]) - strlen($line);
// Determine the previous level.
$level = end($levels);
// Do we have an extends/unextend line followed by a line on the same level or above it?
// If yes, this means we just extended a selector and should close it immediately.
if ($level >= $l && strhas($ex_string, array(' extends ', ' unextends ')))
$tree .= " {\n}\n";
// Same level, and no continuation of a selector? We're probably in a list of properties.
elseif ($level == $l && $ex_string && substr($ex_string, -1) !== ',')
$tree .= strpos($ex_string, 'placeholder') !== false ? "\n" : ";\n";
// Higher level than before? This is a child, obviously.
elseif ($level < $l && $ex_string)
{
$tree .= " {\n";
$levels[] = $l;
}
while ($level > $l)
{
array_pop($levels);
$level = end($levels);
$tree .= "\n" . str_repeat("\t", $level) . "}\n";
}
$tree .= str_repeat("\t", $l) . $line;
$ex_string = $line;
}
unset($atree);
// Did we finish the file with an extends or unextends...? Immediately open it and close it.
if (strhas($ex_string, array(' extends ', ' unextends ')))
$tree .= " {\n}\n";
for ($i = count($levels); $i > 1; $i--)
$tree .= '}';
// Okay, now we can restore normal CSS.
if (!empty($regular_css))
$tree = preg_replace_callback(
'~\.wedge_css_placeholder~',
function ($m) use ($regular_css) {
static $i = 0;
return $regular_css[$i++];
},
$tree
);
/*
'@replace' command: replaces any string with another. Just put @replace on a line, and add
two indented lines: search string on the first, replacement string on the second. For instance:
@replace
rule: search
rule: replace
*/
// !! @todo: rewrite this at the end of the parser so that we can specify target selectors after the @replace keyword.
preg_match_all('~\n\h*@replace\h*{\n\h*([^\n]+);\n\h*([^\n]*)\n?}~i', $tree, $replacements, PREG_SET_ORDER);
if (!empty($replacements))
foreach ($replacements as $replace)
$tree = str_replace($replace[1], $replace[2], $tree);
$tree = preg_replace('~\n\h*@replace\h*{[^}]*}~i', "\n", $tree);
/*
And a few more pre-parsing actions...
A couple of reminders on @import:
(1) avoid using them in CSS files. REALLY. Use <css> in custom.xml, or add_css_file(), or add_css().
(2) @import won't work if used inside a suffixed file, because @import is only parsed when
found at the start of a physical file (or within <style> tags in the main HTML.)
*/
$tree = preg_replace('~^(@(?:import|charset)\h+[^{}\n]*);?$~mi', '<rule selector="$1"></rule>', $tree); // Transform single-line @rules into selectors
$tree = preg_replace('~^([!+>&#*@:.a-z0-9][^{};]*?\h*reset);~mi', '<rule selector="$1"></rule>', $tree); // Transform single-line resets into selectors
$tree = preg_replace_callback('~\burl\([^)]+\)~', function ($a) { return str_replace(':', '#wedge-colon#', $a[0]); }, $tree); // Protect colons (:) inside URLs
$tree = preg_replace('~([a-z, -]+)\h*:(?!//)\h*([^;}{\n]+?);*\h*(?=[\n}])~i', '<property name="$1" value="$2">', $tree); // Transform properties
$tree = preg_replace('~<property name="[^"]+" value="\h+">~', '', $tree); // Remove properties with empty content (e.g. background: $bg where $bg is later unset)
$tree = preg_replace('~(?<=^|[\s};])([!+>&#*@:.a-z0-9](?:[^{\n]|(?=,)\n)*?)\s*{~i', '<rule selector="$1">', $tree); // Transform selectors. Strings starting with a digit are only allowed because of keyframes.
$tree = preg_replace(array('~ {2,}~'), array(' '), $tree); // Remove extra spaces
$tree = str_replace(array('}', "\n"), array('</rule>', "\n\t"), $tree); // Close rules and indent everything one tab
// Parse the XML into a crawlable DOM
$this->pierce($tree);
/******************************************************************************
Rebuild parsed CSS
******************************************************************************/
$css = $standard_nest = '';
$bases = $virtuals = $used_virtuals = $removals = $selector_removals = $unextends = array();
$selector_regex = '((?<![a-z])[abipqsu]|[!+>&#*@:.a-z0-9][^{};,\n"]+)';
// 'reset' keyword: remove earlier occurrences of a selector.
// e.g.: ".class reset" -> removes all previous ".class" definitions
foreach ($this->rules as $n => &$node)
{
if (!isset($node['selector']))
exit('Malformed CSS file!');
if (strpos($node['selector'], ' reset') !== false)
{
preg_match_all('~' . $selector_regex . '\h+reset\b~i', $node['selector'], $matches, PREG_SET_ORDER);
foreach ($matches as $m)
{
// Start by rebuilding a full selector. For efficiency reasons, and because I'm too lazy to rework this,
// Wedge will only parse single parents, and will reject comma-separated classes and parents using
// keywords such as 'extends'. If you come up with an implementation to support them, feel free to share!
$selector = $m[1];
$current_node = $node;
while ($current_node['parent'] > 0)
{
$current_node = $this->rules[$current_node['parent']];
$selector = $current_node['selector'] . ' ' . $selector;
}
$quoted = preg_quote($selector, '~');
$full_test = '~(?:^|\s|,)' . $quoted . '(?:,|\s|$)~m';
// Run through all earlier rules and delete anything related to this.
foreach ($this->rules as $n2 => &$node2)
{
if ($n === $n2)
break;
// Remove our reset selector from the current selector.
if (strpos($node2['selector'], $selector) !== false && preg_match($full_test, $node2['selector']))
{
$node2['selector'] = trim(preg_replace('~(?:^|,)[^,]*' . $quoted . '[^,]*(?:,|$)~m', ',', $node2['selector']), "\x00..\x20,");
$node2['selector'] = str_replace(',,', ',', $node2['selector']);
if (empty($node2['selector']))
$this->unset_recursive($n2);
}
}
}
$node['selector'] = preg_replace('~\breset\b~i', '', $node['selector']);
if (trim($node['selector'] == ''))
{
unset($this->rules[$n]);
continue;
}
}
}
// 'virtual' keyword: remove rule if nothing extends on it.
// Please note that Wess will only accept one virtual selector at a time.
foreach ($this->rules as $n => &$node)
{
if (strpos($node['selector'], ' virtual') !== false)
{
if (preg_match('~' . $selector_regex . '\h+virtual\b~i', $node['selector'], $matches))
{
$node['selector'] = str_replace($matches[0], $matches[1], $node['selector']);
$virtuals[$matches[1]] = $n;
}
}
}
$is_ie6 = we::is('ie6');
// Replace ".class extends .original_class, .class2 extends .other_class" with ".class, .class2"
foreach ($this->rules as $n => &$node)
{
/*
'@remove' command: remove properties as specified. To remove all "background: #fff" rules from .class and h1
and associated selectors (anything that inherits .class or h1, or is inherited by it), use this:
@remove .class, h1
background: #fff
Of course you may also use just one selector, or provide no selectors; Wess will target all selectors in the entire file.
You may also replace #fff with a wildcard (*), in which case this rule will be removed, whatever its value.
*/
if (strpos($node['selector'], '@remove') === 0)
{
$sels = preg_match('~@remove\h+(?:from\h+)?([^\n]+)~', $node['selector'], $sels) ? array_map('trim', explode(',', trim(str_replace('#wedge-quote#', '"', $sels[1]), "\x00..\x20\""))) : array();
foreach ($node['props'] as $remove)
{
if (empty($sels))
$removals[$remove['name'] . ':' . $remove['value']] = true;
else
foreach ($sels as $selector)
$selector_removals[$selector][$remove['name'] . ':' . $remove['value']] = true;
}
unset($this->rules[$n]);
continue;
}
// 'unextends' keyword: reset specified inheritance.
// e.g.: ".class unextends .orig "-> cancels any earlier ".class extends .orig"
if (strpos($node['selector'], ' unextends') !== false)
{
preg_match_all('~' . $selector_regex . '\h+unextends\b~i', $node['selector'], $matches, PREG_SET_ORDER);
foreach ($matches as $m)
$unextends[$m[1]] = $n;
$node['selector'] = preg_replace('~\bunextends\b~i', '', $node['selector']);
if (trim($node['selector'] == ''))
{
unset($this->rules[$n]);
continue;
}
}
// 'extends' keyword: selector inheritance.
// e.g.: ".class extends .orig" -> turns all ".orig" definitions into ".orig, .class"
if (strpos($node['selector'], 'extends') !== false)
{
// A quick hack to turn direct selectors into normal selectors when in IE6. This is because it ignores direct selectors, as well as
// any selectors declared alongside them. If you still want these selectors to inherit something, do it manually in an '@if ie6' block!
if ($is_ie6 && strpos($node['selector'], '>') !== false)
$node['selector'] = '.ie6';
$node['selector'] = str_replace('#wedge-quote#', '"', $node['selector']);
preg_match_all('~' . $selector_regex . '\h+extends\h+("[^\n{"]+"|[^\n,{"]+)~i', $node['selector'], $matches, PREG_SET_ORDER);
foreach ($matches as $m)
{
$save_selector = $node['selector'];
$node['selector'] = $m[1];
$path = implode(',', $this->parse_ancestors($node));
// In case we extend directly from a parent's property, make sure to keep only the first parent (reset) if we have several.
if (strpos($m[2], '&') !== false)
$m[2] = str_replace('&', reset(($this->parse_ancestors($this->rules[$node['parent']]))), $m[2]);
// And if we have multiple inheritance, add each selector to the base list.
$targets = array_map('trim', explode(',', trim($m[2], '"')));
foreach ($targets as $target)
$bases[] = array(
$target, // Add to this class in the tree...
preg_quote($target),
$path, // ...The current selector
$n,
);
$node['selector'] = str_replace($m[0], $m[1], $save_selector);
}