dolibarr 23.0.3
lessc.class.php
1<?php
2/*
3 * lessphp v0.8.0
4 * http://leafo.net/lessphp
5 *
6 * LESS CSS compiler, adapted from http://lesscss.org
7 *
8 * Copyright 2013, Leaf Corcoran <leafot@gmail.com>
9 * Copyright (C) 2024 Frédéric France <frederic.france@free.fr>
10 * Licensed under MIT or GPLv3, see LICENSE
11 */
12
13// phpcs:disable
40class Lessc
41{
42 public static $VERSION = "v0.8.0";
43
44 public static $TRUE = array("keyword", "true");
45 public static $FALSE = array("keyword", "false");
46
47 protected $libFunctions = array();
48 protected $registeredVars = array();
49 protected $preserveComments = false;
50
51 public $vPrefix = '@'; // prefix of abstract properties
52 public $mPrefix = '$'; // prefix of abstract blocks
53 public $parentSelector = '&';
54
55 public $importDisabled = false;
56 public $importDir = '';
57
58 public $scope;
59 public $formatter;
60 public $formatterName;
61 public $parser;
62 public $_parseFile;
63 public $env;
64 public $count;
65
66 protected $numberPrecision = null;
67
68 protected $allParsedFiles = array();
69
70 // set to the parser that generated the current line when compiling
71 // so we know how to create error messages
72 protected $sourceParser = null;
73 protected $sourceLoc = null;
74
75 protected static $nextImportId = 0; // uniquely identify imports
76
77 // attempts to find the path of an import url, returns null for css files
78 protected function findImport($url)
79 {
80 foreach ((array) $this->importDir as $dir) {
81 $full = $dir.(substr($dir, -1) != '/' ? '/' : '').$url;
82 if ($this->fileExists($file = $full.'.less') || $this->fileExists($file = $full)) {
83 return $file;
84 }
85 }
86
87 return null;
88 }
89
96 protected function fileExists($name)
97 {
98 return is_file($name);
99 }
100
101 public static function compressList($items, $delim)
102 {
103 if (!isset($items[1]) && isset($items[0])) {
104 return $items[0];
105 } else {
106 return array('list', $delim, $items);
107 }
108 }
109
110 public static function preg_quote($what)
111 {
112 return preg_quote($what, '/');
113 }
114
115 protected function tryImport($importPath, $parentBlock, $out)
116 {
117 if ($importPath[0] == "function" && $importPath[1] == "url") {
118 $importPath = $this->flattenList($importPath[2]);
119 }
120
121 $str = $this->coerceString($importPath);
122 if ($str === null) {
123 return false;
124 }
125
126 $url = $this->compileValue($this->lib_e($str));
127
128 // don't import if it ends in css
129 if (substr_compare($url, '.css', -4, 4) === 0) {
130 return false;
131 }
132
133 $realPath = $this->findImport($url);
134
135 if ($realPath === null) {
136 return false;
137 }
138
139 if ($this->importDisabled) {
140 return array(false, "/* import disabled */");
141 }
142
143 if (isset($this->allParsedFiles[realpath($realPath)])) {
144 return array(false, null);
145 }
146
147 $this->addParsedFile($realPath);
148 $parser = $this->makeParser($realPath);
149 $root = $parser->parse(file_get_contents($realPath));
150
151 // set the parents of all the block props
152 foreach ($root->props as $prop) {
153 if ($prop[0] == "block") {
154 $prop[1]->parent = $parentBlock;
155 }
156 }
157
158 // copy mixins into scope, set their parents
159 // bring blocks from import into current block
160 // TODO: need to mark the source parser these came from this file
161 foreach ($root->children as $childName => $child) {
162 if (isset($parentBlock->children[$childName])) {
163 $parentBlock->children[$childName] = array_merge(
164 $parentBlock->children[$childName],
165 $child
166 );
167 } else {
168 $parentBlock->children[$childName] = $child;
169 }
170 }
171
172 $pi = pathinfo($realPath);
173 $dir = $pi["dirname"];
174
175 list($top, $bottom) = $this->sortProps($root->props, true);
176 $this->compileImportedProps($top, $parentBlock, $out, $parser, $dir);
177
178 return array(true, $bottom, $parser, $dir);
179 }
180
181 protected function compileImportedProps($props, $block, $out, $sourceParser, $importDir)
182 {
183 $oldSourceParser = $this->sourceParser;
184
185 $oldImport = $this->importDir;
186
187 // TODO: this is because the importDir api is stupid
188 $this->importDir = (array) $this->importDir;
189 array_unshift($this->importDir, $importDir);
190
191 foreach ($props as $prop) {
192 $this->compileProp($prop, $block, $out);
193 }
194
195 $this->importDir = $oldImport;
196 $this->sourceParser = $oldSourceParser;
197 }
198
220 protected function compileBlock($block)
221 {
222 switch ($block->type) {
223 case "root":
224 $this->compileRoot($block);
225 break;
226 case null:
227 $this->compileCSSBlock($block);
228 break;
229 case "media":
230 $this->compileMedia($block);
231 break;
232 case "directive":
233 $name = "@".$block->name;
234 if (!empty($block->value)) {
235 $name .= " ".$this->compileValue($this->reduce($block->value));
236 }
237
238 $this->compileNestedBlock($block, array($name));
239 break;
240 default:
241 $this->throwError("unknown block type: $block->type\n");
242 }
243 }
244
245 protected function compileCSSBlock($block)
246 {
247 $env = $this->pushEnv();
248
249 $selectors = $this->compileSelectors($block->tags);
250 $env->selectors = $this->multiplySelectors($selectors);
251 $out = $this->makeOutputBlock(null, $env->selectors);
252
253 $this->scope->children[] = $out;
254 $this->compileProps($block, $out);
255
256 $block->scope = $env; // mixins carry scope with them!
257 $this->popEnv();
258 }
259
260 protected function compileMedia($media)
261 {
262 $env = $this->pushEnv($media);
263 $parentScope = $this->mediaParent($this->scope);
264
265 $query = $this->compileMediaQuery($this->multiplyMedia($env));
266
267 $this->scope = $this->makeOutputBlock($media->type, array($query));
268 $parentScope->children[] = $this->scope;
269
270 $this->compileProps($media, $this->scope);
271
272 if (count($this->scope->lines) > 0) {
273 $orphanSelelectors = $this->findClosestSelectors();
274 if (!is_null($orphanSelelectors)) {
275 $orphan = $this->makeOutputBlock(null, $orphanSelelectors);
276 $orphan->lines = $this->scope->lines;
277 array_unshift($this->scope->children, $orphan);
278 $this->scope->lines = array();
279 }
280 }
281
282 $this->scope = $this->scope->parent;
283 $this->popEnv();
284 }
285
286 protected function mediaParent($scope)
287 {
288 while (!empty($scope->parent)) {
289 if (!empty($scope->type) && $scope->type != "media") {
290 break;
291 }
292 $scope = $scope->parent;
293 }
294
295 return $scope;
296 }
297
298 protected function compileNestedBlock($block, $selectors)
299 {
300 $this->pushEnv($block);
301 $this->scope = $this->makeOutputBlock($block->type, $selectors);
302 $this->scope->parent->children[] = $this->scope;
303
304 $this->compileProps($block, $this->scope);
305
306 $this->scope = $this->scope->parent;
307 $this->popEnv();
308 }
309
310 protected function compileRoot($root)
311 {
312 $this->pushEnv();
313 $this->scope = $this->makeOutputBlock($root->type);
314 $this->compileProps($root, $this->scope);
315 $this->popEnv();
316 }
317
318 protected function compileProps($block, $out)
319 {
320 foreach ($this->sortProps($block->props) as $prop) {
321 $this->compileProp($prop, $block, $out);
322 }
323 $out->lines = $this->deduplicate($out->lines);
324 }
325
331 protected function deduplicate($lines)
332 {
333 $unique = array();
334 $comments = array();
335
336 foreach ($lines as $line) {
337 if (strpos($line, '/*') === 0) {
338 $comments[] = $line;
339 continue;
340 }
341 if (!in_array($line, $unique)) {
342 $unique[] = $line;
343 }
344 array_splice($unique, array_search($line, $unique), 0, $comments);
345 $comments = array();
346 }
347 return array_merge($unique, $comments);
348 }
349
350 protected function sortProps($props, $split = false)
351 {
352 $vars = array();
353 $imports = array();
354 $other = array();
355 $stack = array();
356
357 foreach ($props as $prop) {
358 switch ($prop[0]) {
359 case "comment":
360 $stack[] = $prop;
361 break;
362 case "assign":
363 $stack[] = $prop;
364 if (isset($prop[1][0]) && $prop[1][0] == $this->vPrefix) {
365 $vars = array_merge($vars, $stack);
366 } else {
367 $other = array_merge($other, $stack);
368 }
369 $stack = array();
370 break;
371 case "import":
372 $id = self::$nextImportId++;
373 $prop[] = $id;
374 $stack[] = $prop;
375 $imports = array_merge($imports, $stack);
376 $other[] = array("import_mixin", $id);
377 $stack = array();
378 break;
379 default:
380 $stack[] = $prop;
381 $other = array_merge($other, $stack);
382 $stack = array();
383 break;
384 }
385 }
386 $other = array_merge($other, $stack);
387
388 if ($split) {
389 return array(array_merge($imports, $vars), $other);
390 } else {
391 return array_merge($imports, $vars, $other);
392 }
393 }
394
395 protected function compileMediaQuery($queries)
396 {
397 $compiledQueries = array();
398 foreach ($queries as $query) {
399 $parts = array();
400 foreach ($query as $q) {
401 switch ($q[0]) {
402 case "mediaType":
403 $parts[] = implode(" ", array_slice($q, 1));
404 break;
405 case "mediaExp":
406 if (isset($q[2])) {
407 $parts[] = "($q[1]: ".
408 $this->compileValue($this->reduce($q[2])).")";
409 } else {
410 $parts[] = "($q[1])";
411 }
412 break;
413 case "variable":
414 $parts[] = $this->compileValue($this->reduce($q));
415 break;
416 }
417 }
418
419 if (count($parts) > 0) {
420 $compiledQueries[] = implode(" and ", $parts);
421 }
422 }
423
424 $out = "@media";
425 if (!empty($parts)) {
426 $out .= " ".
427 implode($this->formatter->selectorSeparator, $compiledQueries);
428 }
429 return $out;
430 }
431
432 protected function multiplyMedia($env, $childQueries = null)
433 {
434 if (is_null($env) ||
435 !empty($env->block->type) && $env->block->type != "media"
436 ) {
437 return $childQueries;
438 }
439
440 // plain old block, skip
441 if (empty($env->block->type)) {
442 return $this->multiplyMedia($env->parent, $childQueries);
443 }
444
445 $out = array();
446 $queries = $env->block->queries;
447 if (is_null($childQueries)) {
448 $out = $queries;
449 } else {
450 foreach ($queries as $parent) {
451 foreach ($childQueries as $child) {
452 $out[] = array_merge($parent, $child);
453 }
454 }
455 }
456
457 return $this->multiplyMedia($env->parent, $out);
458 }
459
460 protected function expandParentSelectors(&$tag, $replace)
461 {
462 $parts = explode("$&$", $tag);
463 $count = 0;
464 foreach ($parts as &$part) {
465 $c = 0;
466 $part = str_replace($this->parentSelector, $replace, $part, $c);
467 $count += $c;
468 }
469 $tag = implode($this->parentSelector, $parts);
470 return $count;
471 }
472
473 protected function findClosestSelectors()
474 {
475 $env = $this->env;
476 $selectors = null;
477 while ($env !== null) {
478 if (isset($env->selectors)) {
479 $selectors = $env->selectors;
480 break;
481 }
482 $env = $env->parent;
483 }
484
485 return $selectors;
486 }
487
488
489 // multiply $selectors against the nearest selectors in env
490 protected function multiplySelectors($selectors)
491 {
492 // find parent selectors
493
494 $parentSelectors = $this->findClosestSelectors();
495 if (is_null($parentSelectors)) {
496 // kill parent reference in top level selector
497 foreach ($selectors as &$s) {
498 $this->expandParentSelectors($s, "");
499 }
500
501 return $selectors;
502 }
503
504 $out = array();
505 foreach ($parentSelectors as $parent) {
506 foreach ($selectors as $child) {
507 $count = $this->expandParentSelectors($child, $parent);
508
509 // don't prepend the parent tag if & was used
510 if ($count > 0) {
511 $out[] = trim($child);
512 } else {
513 $out[] = trim($parent.' '.$child);
514 }
515 }
516 }
517
518 return $out;
519 }
520
521 // reduces selector expressions
522 protected function compileSelectors($selectors)
523 {
524 $out = array();
525
526 foreach ($selectors as $s) {
527 if (is_array($s)) {
528 list(, $value) = $s;
529 $out[] = trim($this->compileValue($this->reduce($value)));
530 } else {
531 $out[] = $s;
532 }
533 }
534
535 return $out;
536 }
537
538 protected function eq($left, $right)
539 {
540 return $left == $right;
541 }
542
543 protected function patternMatch($block, $orderedArgs, $keywordArgs)
544 {
545 // match the guards if it has them
546 // any one of the groups must have all its guards pass for a match
547 if (!empty($block->guards)) {
548 $groupPassed = false;
549 foreach ($block->guards as $guardGroup) {
550 foreach ($guardGroup as $guard) {
551 $this->pushEnv();
552 $this->zipSetArgs($block->args, $orderedArgs, $keywordArgs);
553
554 $negate = false;
555 if ($guard[0] == "negate") {
556 $guard = $guard[1];
557 $negate = true;
558 }
559
560 $passed = $this->reduce($guard) == self::$TRUE;
561 if ($negate) {
562 $passed = !$passed;
563 }
564
565 $this->popEnv();
566
567 if ($passed) {
568 $groupPassed = true;
569 } else {
570 $groupPassed = false;
571 break;
572 }
573 }
574
575 if ($groupPassed) {
576 break;
577 }
578 }
579
580 if (!$groupPassed) {
581 return false;
582 }
583 }
584
585 if (empty($block->args)) {
586 return $block->isVararg || empty($orderedArgs) && empty($keywordArgs);
587 }
588
589 $remainingArgs = $block->args;
590 if ($keywordArgs) {
591 $remainingArgs = array();
592 foreach ($block->args as $arg) {
593 if ($arg[0] == "arg" && isset($keywordArgs[$arg[1]])) {
594 continue;
595 }
596
597 $remainingArgs[] = $arg;
598 }
599 }
600
601 $i = -1; // no args
602 // try to match by arity or by argument literal
603 foreach ($remainingArgs as $i => $arg) {
604 switch ($arg[0]) {
605 case "lit":
606 if (empty($orderedArgs[$i]) || !$this->eq($arg[1], $orderedArgs[$i])) {
607 return false;
608 }
609 break;
610 case "arg":
611 // no arg and no default value
612 if (!isset($orderedArgs[$i]) && !isset($arg[2])) {
613 return false;
614 }
615 break;
616 case "rest":
617 $i--; // rest can be empty
618 break 2;
619 }
620 }
621
622 if ($block->isVararg) {
623 return true; // not having enough is handled above
624 } else {
625 $numMatched = $i + 1;
626 // greater than because default values always match
627 return $numMatched >= count($orderedArgs);
628 }
629 }
630
631 protected function patternMatchAll($blocks, $orderedArgs, $keywordArgs, $skip = array())
632 {
633 $matches = null;
634 foreach ($blocks as $block) {
635 // skip seen blocks that don't have arguments
636 if (isset($skip[$block->id]) && !isset($block->args)) {
637 continue;
638 }
639
640 if ($this->patternMatch($block, $orderedArgs, $keywordArgs)) {
641 $matches[] = $block;
642 }
643 }
644
645 return $matches;
646 }
647
648 // attempt to find blocks matched by path and args
649 protected function findBlocks($searchIn, $path, $orderedArgs, $keywordArgs, $seen = array())
650 {
651 if ($searchIn == null) {
652 return null;
653 }
654 if (isset($seen[$searchIn->id])) {
655 return null;
656 }
657 $seen[$searchIn->id] = true;
658
659 $name = $path[0];
660
661 if (isset($searchIn->children[$name])) {
662 $blocks = $searchIn->children[$name];
663 if (count($path) == 1) {
664 $matches = $this->patternMatchAll($blocks, $orderedArgs, $keywordArgs, $seen);
665 if (!empty($matches)) {
666 // This will return all blocks that match in the closest
667 // scope that has any matching block, like lessjs
668 return $matches;
669 }
670 } else {
671 $matches = array();
672 foreach ($blocks as $subBlock) {
673 $subMatches = $this->findBlocks(
674 $subBlock,
675 array_slice($path, 1),
676 $orderedArgs,
677 $keywordArgs,
678 $seen
679 );
680
681 if (!is_null($subMatches)) {
682 foreach ($subMatches as $sm) {
683 $matches[] = $sm;
684 }
685 }
686 }
687
688 return count($matches) > 0 ? $matches : null;
689 }
690 }
691 if ($searchIn->parent === $searchIn) {
692 return null;
693 }
694 return $this->findBlocks($searchIn->parent, $path, $orderedArgs, $keywordArgs, $seen);
695 }
696
697 // sets all argument names in $args to either the default value
698 // or the one passed in through $values
699 protected function zipSetArgs($args, $orderedValues, $keywordValues)
700 {
701 $assignedValues = array();
702
703 $i = 0;
704 foreach ($args as $a) {
705 if ($a[0] == "arg") {
706 if (isset($keywordValues[$a[1]])) {
707 // has keyword arg
708 $value = $keywordValues[$a[1]];
709 } elseif (isset($orderedValues[$i])) {
710 // has ordered arg
711 $value = $orderedValues[$i];
712 $i++;
713 } elseif (isset($a[2])) {
714 // has default value
715 $value = $a[2];
716 } else {
717 $value = null; // :(
718 $this->throwError("Failed to assign arg ".$a[1]); // This ends function by throwing an exception
719 }
720
721 $value = $this->reduce($value);
722 $this->set($a[1], $value);
723 $assignedValues[] = $value;
724 } else {
725 // a lit
726 $i++;
727 }
728 }
729
730 // check for a rest
731 $last = end($args);
732 if ($last && $last[0] == "rest") {
733 $rest = array_slice($orderedValues, count($args) - 1);
734 $this->set($last[1], $this->reduce(array("list", " ", $rest)));
735 }
736
737 // wow is this the only true use of PHP's + operator for arrays?
738 $this->env->arguments = $assignedValues + $orderedValues;
739 }
740
741 // compile a prop and update $lines or $blocks appropriately
742 protected function compileProp($prop, $block, $out)
743 {
744 // set error position context
745 $this->sourceLoc = isset($prop[-1]) ? $prop[-1] : -1;
746
747 switch ($prop[0]) {
748 case 'assign':
749 list(, $name, $value) = $prop;
750 if ($name[0] == $this->vPrefix) {
751 $this->set($name, $value);
752 } else {
753 $out->lines[] = $this->formatter->property(
754 $name,
755 $this->compileValue($this->reduce($value))
756 );
757 }
758 break;
759 case 'block':
760 list(, $child) = $prop;
761 $this->compileBlock($child);
762 break;
763 case 'mixin':
764 list(, $path, $args, $suffix) = $prop;
765
766 $orderedArgs = array();
767 $keywordArgs = array();
768 foreach ((array) $args as $arg) {
769 //$argval = null;
770 switch ($arg[0]) {
771 case "arg":
772 if (!isset($arg[2])) {
773 $orderedArgs[] = $this->reduce(array("variable", $arg[1]));
774 } else {
775 $keywordArgs[$arg[1]] = $this->reduce($arg[2]);
776 }
777 break;
778
779 case "lit":
780 $orderedArgs[] = $this->reduce($arg[1]);
781 break;
782 default:
783 $this->throwError("Unknown arg type: ".$arg[0]);
784 }
785 }
786
787 $mixins = $this->findBlocks($block, $path, $orderedArgs, $keywordArgs);
788
789 if ($mixins === null) {
790 $this->throwError("{$prop[1][0]} is undefined");
791 }
792
793 foreach ($mixins as $mixin) {
794 if ($mixin === $block && !$orderedArgs) {
795 continue;
796 }
797
798 $haveScope = false;
799 if (isset($mixin->parent->scope)) {
800 $haveScope = true;
801 $mixinParentEnv = $this->pushEnv();
802 $mixinParentEnv->storeParent = $mixin->parent->scope;
803 }
804
805 $haveArgs = false;
806 if (isset($mixin->args)) {
807 $haveArgs = true;
808 $this->pushEnv();
809 $this->zipSetArgs($mixin->args, $orderedArgs, $keywordArgs);
810 }
811
812 $oldParent = $mixin->parent;
813 if ($mixin != $block) {
814 $mixin->parent = $block;
815 }
816
817 foreach ($this->sortProps($mixin->props) as $subProp) {
818 if ($suffix !== null &&
819 $subProp[0] == "assign" &&
820 is_string($subProp[1]) &&
821 $subProp[1][0] != $this->vPrefix
822 ) {
823 $subProp[2] = array(
824 'list', ' ',
825 array($subProp[2], array('keyword', $suffix))
826 );
827 }
828
829 $this->compileProp($subProp, $mixin, $out);
830 }
831
832 $mixin->parent = $oldParent;
833
834 if ($haveArgs) {
835 $this->popEnv();
836 }
837 if ($haveScope) {
838 $this->popEnv();
839 }
840 }
841
842 break;
843 case 'raw':
844 $out->lines[] = $prop[1];
845 break;
846 case "directive":
847 list(, $name, $value) = $prop;
848 $out->lines[] = "@$name ".$this->compileValue($this->reduce($value)).';';
849 break;
850 case "comment":
851 $out->lines[] = $prop[1];
852 break;
853 case "import":
854 list(, $importPath, $importId) = $prop;
855 $importPath = $this->reduce($importPath);
856
857 if (!isset($this->env->imports)) {
858 $this->env->imports = array();
859 }
860
861 $result = $this->tryImport($importPath, $block, $out);
862
863 $this->env->imports[$importId] = $result === false ?
864 array(false, "@import ".$this->compileValue($importPath).";") : $result;
865
866 break;
867 case "import_mixin":
868 list(, $importId) = $prop;
869 $import = $this->env->imports[$importId];
870 if ($import[0] === false) {
871 if (isset($import[1])) {
872 $out->lines[] = $import[1];
873 }
874 } else {
875 list(, $bottom, $parser, $importDir) = $import;
876 $this->compileImportedProps($bottom, $block, $out, $parser, $importDir);
877 }
878
879 break;
880 default:
881 $this->throwError("unknown op: {$prop[0]}\n");
882 }
883 }
884
885
897 public function compileValue($value)
898 {
899 switch ($value[0]) {
900 case 'list':
901 // [1] - delimiter
902 // [2] - array of values
903 return implode($value[1], array_map(array($this, 'compileValue'), $value[2]));
904 case 'raw_color':
905 if (!empty($this->formatter->compressColors)) {
906 return $this->compileValue($this->coerceColor($value));
907 }
908 return $value[1];
909 case 'keyword':
910 // [1] - the keyword
911 return $value[1];
912 case 'number':
913 list(, $num, $unit) = $value;
914 // [1] - the number
915 // [2] - the unit
916 if ($this->numberPrecision !== null) {
917 $num = round($num, $this->numberPrecision);
918 }
919 return $num.$unit;
920 case 'string':
921 // [1] - contents of string (includes quotes)
922 list(, $delim, $content) = $value;
923 foreach ($content as &$part) {
924 if (is_array($part)) {
925 $part = $this->compileValue($part);
926 }
927 }
928 return $delim.implode($content).$delim;
929 case 'color':
930 // [1] - red component (either number or a %)
931 // [2] - green component
932 // [3] - blue component
933 // [4] - optional alpha component
934 list(, $r, $g, $b) = $value;
935 $r = round($r);
936 $g = round($g);
937 $b = round($b);
938
939 if (count($value) == 5 && $value[4] != 1) { // rgba
940 return 'rgba('.$r.','.$g.','.$b.','.$value[4].')';
941 }
942
943 $h = sprintf("#%02x%02x%02x", $r, $g, $b);
944
945 if (!empty($this->formatter->compressColors)) {
946 // Converting hex color to short notation (e.g. #003399 to #039)
947 if ($h[1] === $h[2] && $h[3] === $h[4] && $h[5] === $h[6]) {
948 $h = '#'.$h[1].$h[3].$h[5];
949 }
950 }
951
952 return $h;
953
954 case 'function':
955 list(, $name, $args) = $value;
956 return $name.'('.$this->compileValue($args).')';
957 default: // assumed to be unit
958 $this->throwError("unknown value type: $value[0]");
959 }
960 }
961
962 protected function lib_pow($args)
963 {
964 list($base, $exp) = $this->assertArgs($args, 2, "pow");
965 return pow($this->assertNumber($base), $this->assertNumber($exp));
966 }
967
968 protected function lib_pi()
969 {
970 return pi();
971 }
972
973 protected function lib_mod($args)
974 {
975 list($a, $b) = $this->assertArgs($args, 2, "mod");
976 return $this->assertNumber($a) % $this->assertNumber($b);
977 }
978
979 protected function lib_tan($num)
980 {
981 return tan($this->assertNumber($num));
982 }
983
984 protected function lib_sin($num)
985 {
986 return sin($this->assertNumber($num));
987 }
988
989 protected function lib_cos($num)
990 {
991 return cos($this->assertNumber($num));
992 }
993
994 protected function lib_atan($num)
995 {
996 $num = atan($this->assertNumber($num));
997 return array("number", $num, "rad");
998 }
999
1000 protected function lib_asin($num)
1001 {
1002 $num = asin($this->assertNumber($num));
1003 return array("number", $num, "rad");
1004 }
1005
1006 protected function lib_acos($num)
1007 {
1008 $num = acos($this->assertNumber($num));
1009 return array("number", $num, "rad");
1010 }
1011
1012 protected function lib_sqrt($num)
1013 {
1014 return sqrt($this->assertNumber($num));
1015 }
1016
1017 protected function lib_extract($value)
1018 {
1019 list($list, $idx) = $this->assertArgs($value, 2, "extract");
1020 $idx = $this->assertNumber($idx);
1021 // 1 indexed
1022 if ($list[0] == "list" && isset($list[2][$idx - 1])) {
1023 return $list[2][$idx - 1];
1024 }
1025 return '';
1026 }
1027
1028 protected function lib_isnumber($value)
1029 {
1030 return $this->toBool($value[0] == "number");
1031 }
1032
1033 protected function lib_isstring($value)
1034 {
1035 return $this->toBool($value[0] == "string");
1036 }
1037
1038 protected function lib_iscolor($value)
1039 {
1040 return $this->toBool($this->coerceColor($value));
1041 }
1042
1043 protected function lib_iskeyword($value)
1044 {
1045 return $this->toBool($value[0] == "keyword");
1046 }
1047
1048 protected function lib_ispixel($value)
1049 {
1050 return $this->toBool($value[0] == "number" && $value[2] == "px");
1051 }
1052
1053 protected function lib_ispercentage($value)
1054 {
1055 return $this->toBool($value[0] == "number" && $value[2] == "%");
1056 }
1057
1058 protected function lib_isem($value)
1059 {
1060 return $this->toBool($value[0] == "number" && $value[2] == "em");
1061 }
1062
1063 protected function lib_isrem($value)
1064 {
1065 return $this->toBool($value[0] == "number" && $value[2] == "rem");
1066 }
1067
1068 protected function lib_rgbahex($color)
1069 {
1070 $color = $this->coerceColor($color);
1071 if (is_null($color)) {
1072 $this->throwError("color expected for rgbahex");
1073 }
1074
1075 return sprintf(
1076 "#%02x%02x%02x%02x",
1077 isset($color[4]) ? $color[4] * 255 : 255,
1078 $color[1],
1079 $color[2],
1080 $color[3]
1081 );
1082 }
1083
1084 protected function lib_argb($color)
1085 {
1086 return $this->lib_rgbahex($color);
1087 }
1088
1095 protected function lib_data_uri($value)
1096 {
1097 $mime = ($value[0] === 'list') ? $value[2][0][2] : null;
1098 $url = ($value[0] === 'list') ? $value[2][1][2][0] : $value[2][0];
1099
1100 $fullpath = $this->findImport($url);
1101
1102 if ($fullpath && ($fsize = filesize($fullpath)) !== false) {
1103 // IE8 can't handle data uris larger than 32KB
1104 if ($fsize / 1024 < 32) {
1105 if (is_null($mime)) {
1106 if (class_exists('finfo')) { // php 5.3+
1107 $finfo = new finfo(FILEINFO_MIME);
1108 $mime = explode('; ', $finfo->file($fullpath));
1109 $mime = $mime[0];
1110 } elseif (function_exists('mime_content_type')) { // PHP 5.2
1111 $mime = mime_content_type($fullpath);
1112 }
1113 }
1114
1115 if (!is_null($mime)) { // fallback if the mime type is still unknown
1116 $url = sprintf('data:%s;base64,%s', $mime, base64_encode(file_get_contents($fullpath)));
1117 }
1118 }
1119 }
1120
1121 return 'url("'.$url.'")';
1122 }
1123
1124 // utility func to unquote a string
1125 protected function lib_e($arg)
1126 {
1127 switch ($arg[0]) {
1128 case "list":
1129 $items = $arg[2];
1130 if (isset($items[0])) {
1131 return $this->lib_e($items[0]);
1132 }
1133 $this->throwError("unrecognised input"); // This ends function by throwing an exception
1134 // no break
1135 case "string":
1136 $arg[1] = "";
1137 return $arg;
1138 case "keyword":
1139 return $arg;
1140 default:
1141 return array("keyword", $this->compileValue($arg));
1142 }
1143 }
1144
1145 protected function lib__sprintf($args)
1146 {
1147 if ($args[0] != "list") {
1148 return $args;
1149 }
1150 $values = $args[2];
1151 $string = array_shift($values);
1152 $template = $this->compileValue($this->lib_e($string));
1153
1154 $i = 0;
1155 $m = array();
1156 if (preg_match_all('/%[dsa]/', $template, $m)) {
1157 foreach ($m[0] as $match) {
1158 $val = isset($values[$i]) ?
1159 $this->reduce($values[$i]) : array('keyword', '');
1160
1161 // lessjs compat, renders fully expanded color, not raw color
1162 if ($color = $this->coerceColor($val)) {
1163 $val = $color;
1164 }
1165
1166 $i++;
1167 $rep = $this->compileValue($this->lib_e($val));
1168 $template = preg_replace(
1169 '/'.self::preg_quote($match).'/',
1170 $rep,
1171 $template,
1172 1
1173 );
1174 }
1175 }
1176
1177 $d = $string[0] == "string" ? $string[1] : '"';
1178 return array("string", $d, array($template));
1179 }
1180
1181 protected function lib_floor($arg)
1182 {
1183 $value = $this->assertNumber($arg);
1184 return array("number", floor($value), $arg[2]);
1185 }
1186
1187 protected function lib_ceil($arg)
1188 {
1189 $value = $this->assertNumber($arg);
1190 return array("number", ceil($value), $arg[2]);
1191 }
1192
1193 protected function lib_round($arg)
1194 {
1195 if ($arg[0] != "list") {
1196 $value = $this->assertNumber($arg);
1197 return array("number", round($value), $arg[2]);
1198 } else {
1199 $value = $this->assertNumber($arg[2][0]);
1200 $precision = $this->assertNumber($arg[2][1]);
1201 return array("number", round($value, $precision), $arg[2][0][2]);
1202 }
1203 }
1204
1205 protected function lib_unit($arg)
1206 {
1207 if ($arg[0] == "list") {
1208 list($number, $newUnit) = $arg[2];
1209 return array("number", $this->assertNumber($number),
1210 $this->compileValue($this->lib_e($newUnit)));
1211 } else {
1212 return array("number", $this->assertNumber($arg), "");
1213 }
1214 }
1215
1220 public function colorArgs($args)
1221 {
1222 if ($args[0] != 'list' || count($args[2]) < 2) {
1223 return array(array('color', 0, 0, 0), 0);
1224 }
1225 list($color, $delta) = $args[2];
1226 $color = $this->assertColor($color);
1227 $delta = (float) $delta[1];
1228
1229 return array($color, $delta);
1230 }
1231
1232 protected function lib_darken($args)
1233 {
1234 list($color, $delta) = $this->colorArgs($args);
1235
1236 $hsl = $this->toHSL($color);
1237 $hsl[3] = $this->clamp($hsl[3] - $delta, 100);
1238 return $this->toRGB($hsl);
1239 }
1240
1241 protected function lib_lighten($args)
1242 {
1243 list($color, $delta) = $this->colorArgs($args);
1244
1245 $hsl = $this->toHSL($color);
1246 $hsl[3] = $this->clamp($hsl[3] + $delta, 100);
1247 return $this->toRGB($hsl);
1248 }
1249
1250 protected function lib_saturate($args)
1251 {
1252 list($color, $delta) = $this->colorArgs($args);
1253
1254 $hsl = $this->toHSL($color);
1255 $hsl[2] = $this->clamp($hsl[2] + $delta, 100);
1256 return $this->toRGB($hsl);
1257 }
1258
1259 protected function lib_desaturate($args)
1260 {
1261 list($color, $delta) = $this->colorArgs($args);
1262
1263 $hsl = $this->toHSL($color);
1264 $hsl[2] = $this->clamp($hsl[2] - $delta, 100);
1265 return $this->toRGB($hsl);
1266 }
1267
1268 protected function lib_spin($args)
1269 {
1270 list($color, $delta) = $this->colorArgs($args);
1271
1272 $hsl = $this->toHSL($color);
1273
1274 $hsl[1] = $hsl[1] + $delta % 360;
1275 if ($hsl[1] < 0) {
1276 $hsl[1] += 360;
1277 }
1278
1279 return $this->toRGB($hsl);
1280 }
1281
1282 protected function lib_fadeout($args)
1283 {
1284 list($color, $delta) = $this->colorArgs($args);
1285 $color[4] = $this->clamp((isset($color[4]) ? $color[4] : 1) - $delta / 100);
1286 return $color;
1287 }
1288
1289 protected function lib_fadein($args)
1290 {
1291 list($color, $delta) = $this->colorArgs($args);
1292 $color[4] = $this->clamp((isset($color[4]) ? $color[4] : 1) + $delta / 100);
1293 return $color;
1294 }
1295
1296 protected function lib_hue($color)
1297 {
1298 $hsl = $this->toHSL($this->assertColor($color));
1299 return round($hsl[1]);
1300 }
1301
1302 protected function lib_saturation($color)
1303 {
1304 $hsl = $this->toHSL($this->assertColor($color));
1305 return round($hsl[2]);
1306 }
1307
1308 protected function lib_lightness($color)
1309 {
1310 $hsl = $this->toHSL($this->assertColor($color));
1311 return round($hsl[3]);
1312 }
1313
1314 // get the alpha of a color
1315 // defaults to 1 for non-colors or colors without an alpha
1316 protected function lib_alpha($value)
1317 {
1318 if (!is_null($color = $this->coerceColor($value))) {
1319 return isset($color[4]) ? $color[4] : 1;
1320 }
1321 return '';
1322 }
1323
1324 // set the alpha of the color
1325 protected function lib_fade($args)
1326 {
1327 list($color, $alpha) = $this->colorArgs($args);
1328 $color[4] = $this->clamp($alpha / 100.0);
1329 return $color;
1330 }
1331
1332 protected function lib_percentage($arg)
1333 {
1334 $num = $this->assertNumber($arg);
1335 return array("number", $num * 100, "%");
1336 }
1337
1349 protected function lib_tint($args)
1350 {
1351 $white = ['color', 255, 255, 255];
1352 if ($args[0] == 'color') {
1353 return $this->lib_mix(['list', ',', [$white, $args]]);
1354 } elseif ($args[0] == "list" && count($args[2]) == 2) {
1355 return $this->lib_mix([$args[0], $args[1], [$white, $args[2][0], $args[2][1]]]);
1356 } else {
1357 $this->throwError("tint expects (color, weight)");
1358 }
1359 return array();
1360 }
1361
1373 protected function lib_shade($args)
1374 {
1375 $black = ['color', 0, 0, 0];
1376 if ($args[0] == 'color') {
1377 return $this->lib_mix(['list', ',', [$black, $args]]);
1378 } elseif ($args[0] == "list" && count($args[2]) == 2) {
1379 return $this->lib_mix([$args[0], $args[1], [$black, $args[2][0], $args[2][1]]]);
1380 } else {
1381 $this->throwError("shade expects (color, weight)");
1382 }
1383 return array();
1384 }
1385
1395 protected function lib_mix($args)
1396 {
1397 if ($args[0] != "list" || count($args[2]) < 2) {
1398 $this->throwError("mix expects (color1, color2, weight)");
1399 }
1400
1401 list($first, $second) = $args[2];
1402 $first = $this->assertColor($first);
1403 $second = $this->assertColor($second);
1404
1405 $first_a = $this->lib_alpha($first);
1406 $second_a = $this->lib_alpha($second);
1407
1408 if (isset($args[2][2])) {
1409 $weight = $args[2][2][1] / 100.0;
1410 } else {
1411 $weight = 0.5;
1412 }
1413
1414 $w = $weight * 2 - 1;
1415 $a = $first_a - $second_a;
1416
1417 $w1 = (($w * $a == -1 ? $w : ($w + $a) / (1 + $w * $a)) + 1) / 2.0;
1418 $w2 = 1.0 - $w1;
1419
1420 $new = array('color',
1421 $w1 * $first[1] + $w2 * $second[1],
1422 $w1 * $first[2] + $w2 * $second[2],
1423 $w1 * $first[3] + $w2 * $second[3],
1424 );
1425
1426 if ($first_a != 1.0 || $second_a != 1.0) {
1427 $new[] = $first_a * $weight + $second_a * ($weight - 1);
1428 }
1429
1430 return $this->fixColor($new);
1431 }
1432
1439 protected function lib_contrast($args)
1440 {
1441 $darkColor = array('color', 0, 0, 0);
1442 $lightColor = array('color', 255, 255, 255);
1443 $threshold = 0.43;
1444
1445 if ($args[0] == 'list') {
1446 $inputColor = (isset($args[2][0])) ? $this->assertColor($args[2][0]) : $lightColor;
1447 $darkColor = (isset($args[2][1])) ? $this->assertColor($args[2][1]) : $darkColor;
1448 $lightColor = (isset($args[2][2])) ? $this->assertColor($args[2][2]) : $lightColor;
1449 $threshold = (isset($args[2][3])) ? $this->assertNumber($args[2][3]) : $threshold;
1450 } else {
1451 $inputColor = $this->assertColor($args);
1452 }
1453
1454 $inputColor = $this->coerceColor($inputColor);
1455 $darkColor = $this->coerceColor($darkColor);
1456 $lightColor = $this->coerceColor($lightColor);
1457
1458 //Figure out which is actually light and dark!
1459 if ($this->toLuma($darkColor) > $this->toLuma($lightColor)) {
1460 $t = $lightColor;
1461 $lightColor = $darkColor;
1462 $darkColor = $t;
1463 }
1464
1465 $inputColor_alpha = $this->lib_alpha($inputColor);
1466 if (($this->toLuma($inputColor) * $inputColor_alpha) < $threshold) {
1467 return $lightColor;
1468 }
1469 return $darkColor;
1470 }
1471
1472 private function toLuma($color)
1473 {
1474 list(, $r, $g, $b) = $this->coerceColor($color);
1475
1476 $r = $r / 255;
1477 $g = $g / 255;
1478 $b = $b / 255;
1479
1480 $r = ($r <= 0.03928) ? $r / 12.92 : pow((($r + 0.055) / 1.055), 2.4);
1481 $g = ($g <= 0.03928) ? $g / 12.92 : pow((($g + 0.055) / 1.055), 2.4);
1482 $b = ($b <= 0.03928) ? $b / 12.92 : pow((($b + 0.055) / 1.055), 2.4);
1483
1484 return (0.2126 * $r) + (0.7152 * $g) + (0.0722 * $b);
1485 }
1486
1487 protected function lib_luma($color)
1488 {
1489 return array("number", round($this->toLuma($color) * 100, 8), "%");
1490 }
1491
1492
1493 public function assertColor($value, $error = "expected color value")
1494 {
1495 $color = $this->coerceColor($value);
1496 if (is_null($color)) {
1497 $this->throwError($error);
1498 }
1499 return $color;
1500 }
1501
1502 public function assertNumber($value, $error = "expecting number")
1503 {
1504 if ($value[0] == "number") {
1505 return $value[1];
1506 }
1507 $this->throwError($error);
1508 }
1509
1510 public function assertArgs($value, $expectedArgs, $name = "")
1511 {
1512 if ($expectedArgs == 1) {
1513 return $value;
1514 } else {
1515 if ($value[0] !== "list" || $value[1] != ",") {
1516 $this->throwError("expecting list");
1517 }
1518 $values = $value[2];
1519 $numValues = count($values);
1520 if ($expectedArgs != $numValues) {
1521 if ($name) {
1522 $name = $name.": ";
1523 }
1524
1525 $this->throwError("{$name}expecting $expectedArgs arguments, got $numValues");
1526 }
1527
1528 return $values;
1529 }
1530 }
1531
1532 protected function toHSL($color)
1533 {
1534 if ($color[0] === 'hsl') {
1535 return $color;
1536 }
1537
1538 $r = $color[1] / 255;
1539 $g = $color[2] / 255;
1540 $b = $color[3] / 255;
1541
1542 $min = min($r, $g, $b);
1543 $max = max($r, $g, $b);
1544
1545 $L = ($min + $max) / 2;
1546 if ($min == $max) {
1547 $S = $H = 0;
1548 } else {
1549 if ($L < 0.5) {
1550 $S = ($max - $min) / ($max + $min);
1551 } else {
1552 $S = ($max - $min) / (2.0 - $max - $min);
1553 }
1554 if ($r == $max) {
1555 $H = ($g - $b) / ($max - $min);
1556 } elseif ($g == $max) {
1557 $H = 2.0 + ($b - $r) / ($max - $min);
1558 } elseif ($b == $max) {
1559 $H = 4.0 + ($r - $g) / ($max - $min);
1560 }
1561 }
1562
1563 $out = array('hsl',
1564 ($H < 0 ? $H + 6 : $H) * 60,
1565 $S * 100,
1566 $L * 100,
1567 );
1568
1569 if (count($color) > 4) {
1570 // copy alpha
1571 $out[] = $color[4];
1572 }
1573 return $out;
1574 }
1575
1576 protected function toRGB_helper($comp, $temp1, $temp2)
1577 {
1578 if ($comp < 0) {
1579 $comp += 1.0;
1580 } elseif ($comp > 1) {
1581 $comp -= 1.0;
1582 }
1583
1584 if (6 * $comp < 1) {
1585 return $temp1 + ($temp2 - $temp1) * 6 * $comp;
1586 }
1587 if (2 * $comp < 1) {
1588 return $temp2;
1589 }
1590 if (3 * $comp < 2) {
1591 return $temp1 + ($temp2 - $temp1) * ((2 / 3) - $comp) * 6;
1592 }
1593
1594 return $temp1;
1595 }
1596
1601 protected function toRGB($color)
1602 {
1603 if ($color[0] === 'color') {
1604 return $color;
1605 }
1606
1607 $H = $color[1] / 360;
1608 $S = $color[2] / 100;
1609 $L = $color[3] / 100;
1610
1611 if ($S == 0) {
1612 $r = $g = $b = $L;
1613 } else {
1614 $temp2 = $L < 0.5 ?
1615 $L * (1.0 + $S) : $L + $S - $L * $S;
1616
1617 $temp1 = 2.0 * $L - $temp2;
1618
1619 $r = $this->toRGB_helper($H + 1 / 3, $temp1, $temp2);
1620 $g = $this->toRGB_helper($H, $temp1, $temp2);
1621 $b = $this->toRGB_helper($H - 1 / 3, $temp1, $temp2);
1622 }
1623
1624 // $out = array('color', round($r*255), round($g*255), round($b*255));
1625 $out = array('color', $r * 255, $g * 255, $b * 255);
1626 if (count($color) > 4) {
1627 // copy alpha
1628 $out[] = $color[4];
1629 }
1630 return $out;
1631 }
1632
1633 protected function clamp($v, $max = 1, $min = 0)
1634 {
1635 return min($max, max($min, $v));
1636 }
1637
1642 protected function funcToColor($func)
1643 {
1644 $fname = $func[1];
1645 if ($func[2][0] != 'list') {
1646 // need a list of arguments
1647 return false;
1648 }
1649 $rawComponents = $func[2][2];
1650
1651 if ($fname == 'hsl' || $fname == 'hsla') {
1652 $hsl = array('hsl');
1653 $i = 0;
1654 foreach ($rawComponents as $c) {
1655 $val = $this->reduce($c);
1656 $val = isset($val[1]) ? (float) $val[1] : 0;
1657
1658 if ($i == 0) {
1659 $clamp = 360;
1660 } elseif ($i < 3) {
1661 $clamp = 100;
1662 } else {
1663 $clamp = 1;
1664 }
1665
1666 $hsl[] = $this->clamp($val, $clamp);
1667 $i++;
1668 }
1669
1670 while (count($hsl) < 4) {
1671 $hsl[] = 0;
1672 }
1673 return $this->toRGB($hsl);
1674
1675 } elseif ($fname == 'rgb' || $fname == 'rgba') {
1676 $components = array();
1677 $i = 1;
1678 foreach ($rawComponents as $c) {
1679 $c = $this->reduce($c);
1680 if ($i < 4) {
1681 if ($c[0] == "number" && $c[2] == "%") {
1682 $components[] = 255 * ($c[1] / 100);
1683 } else {
1684 $components[] = (float) $c[1];
1685 }
1686 } elseif ($i == 4) {
1687 if ($c[0] == "number" && $c[2] == "%") {
1688 $components[] = 1.0 * ($c[1] / 100);
1689 } else {
1690 $components[] = (float) $c[1];
1691 }
1692 } else {
1693 break;
1694 }
1695
1696 $i++;
1697 }
1698 while (count($components) < 3) {
1699 $components[] = 0;
1700 }
1701 array_unshift($components, 'color');
1702 return $this->fixColor($components);
1703 }
1704
1705 return false;
1706 }
1707
1708 protected function reduce($value, $forExpression = false)
1709 {
1710 switch ($value[0]) {
1711 case "interpolate":
1712 $reduced = $this->reduce($value[1]);
1713 $var = $this->compileValue($reduced);
1714 $res = $this->reduce(array("variable", $this->vPrefix.$var));
1715
1716 if ($res[0] == "raw_color") {
1717 $res = $this->coerceColor($res);
1718 }
1719
1720 if (empty($value[2])) {
1721 $res = $this->lib_e($res);
1722 }
1723
1724 return $res;
1725 case "variable":
1726 $key = $value[1];
1727 if (is_array($key)) {
1728 $key = $this->reduce($key);
1729 $key = $this->vPrefix.$this->compileValue($this->lib_e($key));
1730 }
1731
1732 $seen = & $this->env->seenNames;
1733
1734 if (!empty($seen[$key])) {
1735 $this->throwError("infinite loop detected: $key");
1736 }
1737
1738 $seen[$key] = true;
1739 $out = $this->reduce($this->get($key));
1740 $seen[$key] = false;
1741 return $out;
1742 case "list":
1743 foreach ($value[2] as &$item) {
1744 $item = $this->reduce($item, $forExpression);
1745 }
1746 return $value;
1747 case "expression":
1748 return $this->evaluate($value);
1749 case "string":
1750 foreach ($value[2] as &$part) {
1751 if (is_array($part)) {
1752 $strip = $part[0] == "variable";
1753 $part = $this->reduce($part);
1754 if ($strip) {
1755 $part = $this->lib_e($part);
1756 }
1757 }
1758 }
1759 return $value;
1760 case "escape":
1761 list(, $inner) = $value;
1762 return $this->lib_e($this->reduce($inner));
1763 case "function":
1764 $color = $this->funcToColor($value);
1765 if ($color) {
1766 return $color;
1767 }
1768
1769 list(, $name, $args) = $value;
1770 if ($name == "%") {
1771 $name = "_sprintf";
1772 }
1773
1774 $f = isset($this->libFunctions[$name]) ?
1775 $this->libFunctions[$name] : array($this, 'lib_'.str_replace('-', '_', $name));
1776
1777 if (is_callable($f)) {
1778 if ($args[0] == 'list') {
1779 $args = self::compressList($args[2], $args[1]);
1780 }
1781
1782 $ret = call_user_func($f, $this->reduce($args, true), $this);
1783
1784 if (is_null($ret)) {
1785 return array("string", "", array(
1786 $name, "(", $args, ")"
1787 ));
1788 }
1789
1790 // convert to a typed value if the result is a php primitive
1791 if (is_numeric($ret)) {
1792 $ret = array('number', $ret, "");
1793 } elseif (!is_array($ret)) {
1794 $ret = array('keyword', $ret);
1795 }
1796
1797 return $ret;
1798 }
1799
1800 // plain function, reduce args
1801 $value[2] = $this->reduce($value[2]);
1802 return $value;
1803 case "unary":
1804 list(, $op, $exp) = $value;
1805 $exp = $this->reduce($exp);
1806
1807 if ($exp[0] == "number") {
1808 switch ($op) {
1809 case "+":
1810 return $exp;
1811 case "-":
1812 $exp[1] *= -1;
1813 return $exp;
1814 }
1815 }
1816 return array("string", "", array($op, $exp));
1817 }
1818
1819 if ($forExpression) {
1820 switch ($value[0]) {
1821 case "keyword":
1822 if ($color = $this->coerceColor($value)) {
1823 return $color;
1824 }
1825 break;
1826 case "raw_color":
1827 return $this->coerceColor($value);
1828 }
1829 }
1830
1831 return $value;
1832 }
1833
1834
1835 // coerce a value for use in color operation
1836 protected function coerceColor($value)
1837 {
1838 switch ($value[0]) {
1839 case 'color':
1840 return $value;
1841 case 'raw_color':
1842 $c = array("color", 0, 0, 0);
1843 $colorStr = substr($value[1], 1);
1844 $num = hexdec($colorStr);
1845 $width = strlen($colorStr) == 3 ? 16 : 256;
1846
1847 for ($i = 3; $i > 0; $i--) { // 3 2 1
1848 $t = intval($num) % $width;
1849 $num /= $width;
1850
1851 $c[$i] = $t * (256 / $width) + $t * floor(16/$width);
1852 }
1853
1854 return $c;
1855 case 'keyword':
1856 $name = $value[1];
1857 if (isset(self::$cssColors[$name])) {
1858 $rgba = explode(',', self::$cssColors[$name]);
1859
1860 if (isset($rgba[3])) {
1861 return array('color', $rgba[0], $rgba[1], $rgba[2], $rgba[3]);
1862 }
1863 return array('color', $rgba[0], $rgba[1], $rgba[2]);
1864 }
1865 return null;
1866 }
1867 return null;
1868 }
1869
1870 // make something string like into a string
1871 protected function coerceString($value)
1872 {
1873 switch ($value[0]) {
1874 case "string":
1875 return $value;
1876 case "keyword":
1877 return array("string", "", array($value[1]));
1878 }
1879 return null;
1880 }
1881
1882 // turn list of length 1 into value type
1883 protected function flattenList($value)
1884 {
1885 if ($value[0] == "list" && count($value[2]) == 1) {
1886 return $this->flattenList($value[2][0]);
1887 }
1888 return $value;
1889 }
1890
1891 public function toBool($a)
1892 {
1893 return $a ? self::$TRUE : self::$FALSE;
1894 }
1895
1896 // evaluate an expression
1897 protected function evaluate($exp)
1898 {
1899 list(, $op, $left, $right, $whiteBefore, $whiteAfter) = $exp;
1900
1901 $left = $this->reduce($left, true);
1902 $right = $this->reduce($right, true);
1903
1904 if ($leftColor = $this->coerceColor($left)) {
1905 $left = $leftColor;
1906 }
1907
1908 if ($rightColor = $this->coerceColor($right)) {
1909 $right = $rightColor;
1910 }
1911
1912 $ltype = $left[0];
1913 $rtype = $right[0];
1914
1915 // operators that work on all types
1916 if ($op == "and") {
1917 return $this->toBool($left == self::$TRUE && $right == self::$TRUE);
1918 }
1919
1920 if ($op == "=") {
1921 return $this->toBool($this->eq($left, $right));
1922 }
1923
1924 if ($op == "+" && !is_null($str = $this->stringConcatenate($left, $right))) {
1925 return $str;
1926 }
1927
1928 // type based operators
1929 $fname = "op_{$ltype}_{$rtype}";
1930 if (is_callable(array($this, $fname))) {
1931 $out = $this->$fname($op, $left, $right);
1932 if (!is_null($out)) {
1933 return $out;
1934 }
1935 }
1936
1937 // make the expression look it did before being parsed
1938 $paddedOp = $op;
1939 if ($whiteBefore) {
1940 $paddedOp = " ".$paddedOp;
1941 }
1942 if ($whiteAfter) {
1943 $paddedOp .= " ";
1944 }
1945
1946 return array("string", "", array($left, $paddedOp, $right));
1947 }
1948
1949 protected function stringConcatenate($left, $right)
1950 {
1951 if ($strLeft = $this->coerceString($left)) {
1952 if ($right[0] == "string") {
1953 $right[1] = "";
1954 }
1955 $strLeft[2][] = $right;
1956 return $strLeft;
1957 }
1958
1959 if ($strRight = $this->coerceString($right)) {
1960 array_unshift($strRight[2], $left);
1961 return $strRight;
1962 }
1963 return '';
1964 }
1965
1966
1967 // make sure a color's components don't go out of bounds
1968 protected function fixColor($c)
1969 {
1970 foreach (range(1, 3) as $i) {
1971 if ($c[$i] < 0) {
1972 $c[$i] = 0;
1973 }
1974 if ($c[$i] > 255) {
1975 $c[$i] = 255;
1976 }
1977 }
1978
1979 return $c;
1980 }
1981
1982 protected function op_number_color($op, $lft, $rgt)
1983 {
1984 if ($op == '+' || $op == '*') {
1985 return $this->op_color_number($op, $rgt, $lft);
1986 }
1987 return array();
1988 }
1989
1990 protected function op_color_number($op, $lft, $rgt)
1991 {
1992 if ($rgt[0] == '%') {
1993 $rgt[1] /= 100;
1994 }
1995
1996 return $this->op_color_color(
1997 $op,
1998 $lft,
1999 array_fill(1, count($lft) - 1, $rgt[1])
2000 );
2001 }
2002
2003 protected function op_color_color($op, $left, $right)
2004 {
2005 $out = array('color');
2006 $max = count($left) > count($right) ? count($left) : count($right);
2007 foreach (range(1, $max - 1) as $i) {
2008 $lval = isset($left[$i]) ? $left[$i] : 0;
2009 $rval = isset($right[$i]) ? $right[$i] : 0;
2010 switch ($op) {
2011 case '+':
2012 $out[] = $lval + $rval;
2013 break;
2014 case '-':
2015 $out[] = $lval - $rval;
2016 break;
2017 case '*':
2018 $out[] = $lval * $rval;
2019 break;
2020 case '%':
2021 $out[] = $lval % $rval;
2022 break;
2023 case '/':
2024 if ($rval == 0) {
2025 $this->throwError("evaluate error: can't divide by zero");
2026 }
2027 $out[] = $lval / $rval;
2028 break;
2029 default:
2030 $this->throwError('evaluate error: color op number failed on op '.$op);
2031 }
2032 }
2033 return $this->fixColor($out);
2034 }
2035
2036 public function lib_red($color)
2037 {
2038 $color = $this->coerceColor($color);
2039 if (is_null($color)) {
2040 $this->throwError('color expected for red()');
2041 }
2042
2043 return $color[1];
2044 }
2045
2046 public function lib_green($color)
2047 {
2048 $color = $this->coerceColor($color);
2049 if (is_null($color)) {
2050 $this->throwError('color expected for green()');
2051 }
2052
2053 return $color[2];
2054 }
2055
2056 public function lib_blue($color)
2057 {
2058 $color = $this->coerceColor($color);
2059 if (is_null($color)) {
2060 $this->throwError('color expected for blue()');
2061 }
2062
2063 return $color[3];
2064 }
2065
2066
2067 // operator on two numbers
2068 protected function op_number_number($op, $left, $right)
2069 {
2070 $unit = empty($left[2]) ? $right[2] : $left[2];
2071
2072 $value = 0;
2073 switch ($op) {
2074 case '+':
2075 $value = $left[1] + $right[1];
2076 break;
2077 case '*':
2078 $value = $left[1] * $right[1];
2079 break;
2080 case '-':
2081 $value = $left[1] - $right[1];
2082 break;
2083 case '%':
2084 $value = $left[1] % $right[1];
2085 break;
2086 case '/':
2087 if ($right[1] == 0) {
2088 $this->throwError('parse error: divide by zero');
2089 }
2090 $value = $left[1] / $right[1];
2091 break;
2092 case '<':
2093 return $this->toBool($left[1] < $right[1]);
2094 case '>':
2095 return $this->toBool($left[1] > $right[1]);
2096 case '>=':
2097 return $this->toBool($left[1] >= $right[1]);
2098 case '=<':
2099 return $this->toBool($left[1] <= $right[1]);
2100 default:
2101 $this->throwError('parse error: unknown number operator: '.$op);
2102 }
2103
2104 return array("number", $value, $unit);
2105 }
2106
2107
2108 /* environment functions */
2109
2110 protected function makeOutputBlock($type, $selectors = null)
2111 {
2112 $b = new stdclass();
2113 $b->lines = array();
2114 $b->children = array();
2115 $b->selectors = $selectors;
2116 $b->type = $type;
2117 $b->parent = $this->scope;
2118 return $b;
2119 }
2120
2121 // the state of execution
2122 protected function pushEnv($block = null)
2123 {
2124 $e = new stdclass();
2125 $e->parent = $this->env;
2126 $e->store = array();
2127 $e->block = $block;
2128
2129 $this->env = $e;
2130 return $e;
2131 }
2132
2133 // pop something off the stack
2134 protected function popEnv()
2135 {
2136 $old = $this->env;
2137 $this->env = $this->env->parent;
2138 return $old;
2139 }
2140
2141 // set something in the current env
2142 protected function set($name, $value)
2143 {
2144 $this->env->store[$name] = $value;
2145 }
2146
2147
2148 // get the highest occurrence entry for a name
2149 protected function get($name)
2150 {
2151 $current = $this->env;
2152
2153 $isArguments = $name == $this->vPrefix.'arguments';
2154 while ($current) {
2155 if ($isArguments && isset($current->arguments)) {
2156 return array('list', ' ', $current->arguments);
2157 }
2158
2159 if (isset($current->store[$name])) {
2160 return $current->store[$name];
2161 }
2162
2163 $current = isset($current->storeParent) ?
2164 $current->storeParent : $current->parent;
2165 }
2166
2167 $this->throwError("variable $name is undefined");
2168 }
2169
2170 // inject array of unparsed strings into environment as variables
2171 protected function injectVariables($args)
2172 {
2173 $this->pushEnv();
2174 $parser = new lessc_parser($this, __METHOD__);
2175 $value = null;
2176 foreach ($args as $name => $strValue) {
2177 if ($name[0] !== '@') {
2178 $name = '@'.$name;
2179 }
2180 $parser->count = 0;
2181 $parser->buffer = (string) $strValue;
2182 if (!$parser->propertyValue($value)) {
2183 throw new Exception("failed to parse passed in variable $name: $strValue");
2184 }
2185
2186 $this->set($name, $value);
2187 }
2188 }
2189
2194 public function __construct($fname = null)
2195 {
2196 if ($fname !== null) {
2197 // used for deprecated parse method
2198 $this->_parseFile = $fname;
2199 }
2200 }
2201
2202 public function compile($string, $name = null)
2203 {
2204 $locale = setlocale(LC_NUMERIC, '0');
2205 setlocale(LC_NUMERIC, "C");
2206
2207 $this->parser = $this->makeParser($name);
2208 $root = $this->parser->parse($string);
2209
2210 $this->env = null;
2211 $this->scope = null;
2212
2213 $this->formatter = $this->newFormatter();
2214
2215 if (!empty($this->registeredVars)) {
2216 $this->injectVariables($this->registeredVars);
2217 }
2218
2219 $this->sourceParser = $this->parser; // used for error messages
2220 $this->compileBlock($root);
2221
2222 ob_start();
2223 $this->formatter->block($this->scope);
2224 $out = ob_get_clean();
2225 setlocale(LC_NUMERIC, $locale);
2226 return $out;
2227 }
2228
2229 public function compileFile($fname, $outFname = null)
2230 {
2231 if (!is_readable($fname)) {
2232 throw new Exception('load error: failed to find '.$fname);
2233 }
2234
2235 $pi = pathinfo($fname);
2236
2237 $oldImport = $this->importDir;
2238
2239 $this->importDir = (array) $this->importDir;
2240 $this->importDir[] = $pi['dirname'].'/';
2241
2242 $this->addParsedFile($fname);
2243
2244 $out = $this->compile(file_get_contents($fname), $fname);
2245
2246 $this->importDir = $oldImport;
2247
2248 if ($outFname !== null) {
2249 $res = file_put_contents($outFname, $out);
2250 dolChmod($outFname);
2251 return $res;
2252 }
2253
2254 return $out;
2255 }
2256
2257 // compile only if changed input has changed or output doesn't exist
2258 public function checkedCompile($in, $out)
2259 {
2260 if (!is_file($out) || filemtime($in) > filemtime($out)) {
2261 $this->compileFile($in, $out);
2262 return true;
2263 }
2264 return false;
2265 }
2266
2287 public function cachedCompile($in, $force = false)
2288 {
2289 // assume no root
2290 $root = null;
2291
2292 if (is_string($in)) {
2293 $root = $in;
2294 } elseif (is_array($in) && isset($in['root'])) {
2295 if ($force || !isset($in['files'])) {
2296 // If we are forcing a recompile or if for some reason the
2297 // structure does not contain any file information we should
2298 // specify the root to trigger a rebuild.
2299 $root = $in['root'];
2300 } elseif (isset($in['files']) && is_array($in['files'])) {
2301 foreach ($in['files'] as $fname => $ftime) {
2302 if (!file_exists($fname) || filemtime($fname) > $ftime) {
2303 // One of the files we knew about previously has changed
2304 // so we should look at our incoming root again.
2305 $root = $in['root'];
2306 break;
2307 }
2308 }
2309 }
2310 } else {
2311 // TODO: Throw an exception? We got neither a string nor something
2312 // that looks like a compatible lessphp cache structure.
2313 return null;
2314 }
2315
2316 if ($root !== null) {
2317 // If we have a root value which means we should rebuild.
2318 $out = array();
2319 $out['root'] = $root;
2320 $out['compiled'] = $this->compileFile($root);
2321 $out['files'] = $this->allParsedFiles();
2322 $out['updated'] = time();
2323 return $out;
2324 } else {
2325 // No changes, pass back the structure
2326 // we were given initially.
2327 return $in;
2328 }
2329 }
2330
2331 // parse and compile buffer
2332 // This is deprecated
2333 public function parse($str = null, $initialVariables = null)
2334 {
2335 if (is_array($str)) {
2336 $initialVariables = $str;
2337 $str = null;
2338 }
2339
2340 $oldVars = $this->registeredVars;
2341 if ($initialVariables !== null) {
2342 $this->setVariables($initialVariables);
2343 }
2344
2345 if ($str == null) {
2346 if (empty($this->_parseFile)) {
2347 throw new exception("nothing to parse");
2348 }
2349
2350 $out = $this->compileFile($this->_parseFile);
2351 } else {
2352 $out = $this->compile($str);
2353 }
2354
2355 $this->registeredVars = $oldVars;
2356 return $out;
2357 }
2358
2359 protected function makeParser($name)
2360 {
2361 $parser = new lessc_parser($this, $name);
2362 $parser->writeComments = $this->preserveComments;
2363
2364 return $parser;
2365 }
2366
2367 public function setFormatter($name)
2368 {
2369 $this->formatterName = $name;
2370 }
2371
2372 protected function newFormatter()
2373 {
2374 $className = "lessc_formatter_lessjs";
2375 if (!empty($this->formatterName)) {
2376 if (!is_string($this->formatterName)) {
2377 return $this->formatterName;
2378 }
2379 $className = "lessc_formatter_$this->formatterName";
2380 }
2381
2382 return new $className();
2383 }
2384
2385 public function setPreserveComments($preserve)
2386 {
2387 $this->preserveComments = $preserve;
2388 }
2389
2390 public function registerFunction($name, $func)
2391 {
2392 $this->libFunctions[$name] = $func;
2393 }
2394
2395 public function unregisterFunction($name)
2396 {
2397 unset($this->libFunctions[$name]);
2398 }
2399
2400 public function setVariables($variables)
2401 {
2402 $this->registeredVars = array_merge($this->registeredVars, $variables);
2403 }
2404
2405 public function unsetVariable($name)
2406 {
2407 unset($this->registeredVars[$name]);
2408 }
2409
2410 public function setImportDir($dirs)
2411 {
2412 $this->importDir = (array) $dirs;
2413 }
2414
2415 public function addImportDir($dir)
2416 {
2417 $this->importDir = (array) $this->importDir;
2418 $this->importDir[] = $dir;
2419 }
2420
2421 public function allParsedFiles()
2422 {
2423 return $this->allParsedFiles;
2424 }
2425
2426 public function addParsedFile($file)
2427 {
2428 $this->allParsedFiles[realpath($file)] = filemtime($file);
2429 }
2430
2434 public function throwError($msg = null)
2435 {
2436 if ($this->sourceLoc >= 0) {
2437 $this->sourceParser->throwError($msg, $this->sourceLoc);
2438 }
2439 throw new exception($msg);
2440 }
2441
2442 // compile file $in to file $out if $in is newer than $out
2443 // returns true when it compiles, false otherwise
2444 public static function ccompile($in, $out, $less = null)
2445 {
2446 if ($less === null) {
2447 $less = new self();
2448 }
2449 return $less->checkedCompile($in, $out);
2450 }
2451
2452 public static function cexecute($in, $force = false, $less = null)
2453 {
2454 if ($less === null) {
2455 $less = new self();
2456 }
2457 return $less->cachedCompile($in, $force);
2458 }
2459
2460 protected static $cssColors = array(
2461 'aliceblue' => '240,248,255',
2462 'antiquewhite' => '250,235,215',
2463 'aqua' => '0,255,255',
2464 'aquamarine' => '127,255,212',
2465 'azure' => '240,255,255',
2466 'beige' => '245,245,220',
2467 'bisque' => '255,228,196',
2468 'black' => '0,0,0',
2469 'blanchedalmond' => '255,235,205',
2470 'blue' => '0,0,255',
2471 'blueviolet' => '138,43,226',
2472 'brown' => '165,42,42',
2473 'burlywood' => '222,184,135',
2474 'cadetblue' => '95,158,160',
2475 'chartreuse' => '127,255,0',
2476 'chocolate' => '210,105,30',
2477 'coral' => '255,127,80',
2478 'cornflowerblue' => '100,149,237',
2479 'cornsilk' => '255,248,220',
2480 'crimson' => '220,20,60',
2481 'cyan' => '0,255,255',
2482 'darkblue' => '0,0,139',
2483 'darkcyan' => '0,139,139',
2484 'darkgoldenrod' => '184,134,11',
2485 'darkgray' => '169,169,169',
2486 'darkgreen' => '0,100,0',
2487 'darkgrey' => '169,169,169',
2488 'darkkhaki' => '189,183,107',
2489 'darkmagenta' => '139,0,139',
2490 'darkolivegreen' => '85,107,47',
2491 'darkorange' => '255,140,0',
2492 'darkorchid' => '153,50,204',
2493 'darkred' => '139,0,0',
2494 'darksalmon' => '233,150,122',
2495 'darkseagreen' => '143,188,143',
2496 'darkslateblue' => '72,61,139',
2497 'darkslategray' => '47,79,79',
2498 'darkslategrey' => '47,79,79',
2499 'darkturquoise' => '0,206,209',
2500 'darkviolet' => '148,0,211',
2501 'deeppink' => '255,20,147',
2502 'deepskyblue' => '0,191,255',
2503 'dimgray' => '105,105,105',
2504 'dimgrey' => '105,105,105',
2505 'dodgerblue' => '30,144,255',
2506 'firebrick' => '178,34,34',
2507 'floralwhite' => '255,250,240',
2508 'forestgreen' => '34,139,34',
2509 'fuchsia' => '255,0,255',
2510 'gainsboro' => '220,220,220',
2511 'ghostwhite' => '248,248,255',
2512 'gold' => '255,215,0',
2513 'goldenrod' => '218,165,32',
2514 'gray' => '128,128,128',
2515 'green' => '0,128,0',
2516 'greenyellow' => '173,255,47',
2517 'grey' => '128,128,128',
2518 'honeydew' => '240,255,240',
2519 'hotpink' => '255,105,180',
2520 'indianred' => '205,92,92',
2521 'indigo' => '75,0,130',
2522 'ivory' => '255,255,240',
2523 'khaki' => '240,230,140',
2524 'lavender' => '230,230,250',
2525 'lavenderblush' => '255,240,245',
2526 'lawngreen' => '124,252,0',
2527 'lemonchiffon' => '255,250,205',
2528 'lightblue' => '173,216,230',
2529 'lightcoral' => '240,128,128',
2530 'lightcyan' => '224,255,255',
2531 'lightgoldenrodyellow' => '250,250,210',
2532 'lightgray' => '211,211,211',
2533 'lightgreen' => '144,238,144',
2534 'lightgrey' => '211,211,211',
2535 'lightpink' => '255,182,193',
2536 'lightsalmon' => '255,160,122',
2537 'lightseagreen' => '32,178,170',
2538 'lightskyblue' => '135,206,250',
2539 'lightslategray' => '119,136,153',
2540 'lightslategrey' => '119,136,153',
2541 'lightsteelblue' => '176,196,222',
2542 'lightyellow' => '255,255,224',
2543 'lime' => '0,255,0',
2544 'limegreen' => '50,205,50',
2545 'linen' => '250,240,230',
2546 'magenta' => '255,0,255',
2547 'maroon' => '128,0,0',
2548 'mediumaquamarine' => '102,205,170',
2549 'mediumblue' => '0,0,205',
2550 'mediumorchid' => '186,85,211',
2551 'mediumpurple' => '147,112,219',
2552 'mediumseagreen' => '60,179,113',
2553 'mediumslateblue' => '123,104,238',
2554 'mediumspringgreen' => '0,250,154',
2555 'mediumturquoise' => '72,209,204',
2556 'mediumvioletred' => '199,21,133',
2557 'midnightblue' => '25,25,112',
2558 'mintcream' => '245,255,250',
2559 'mistyrose' => '255,228,225',
2560 'moccasin' => '255,228,181',
2561 'navajowhite' => '255,222,173',
2562 'navy' => '0,0,128',
2563 'oldlace' => '253,245,230',
2564 'olive' => '128,128,0',
2565 'olivedrab' => '107,142,35',
2566 'orange' => '255,165,0',
2567 'orangered' => '255,69,0',
2568 'orchid' => '218,112,214',
2569 'palegoldenrod' => '238,232,170',
2570 'palegreen' => '152,251,152',
2571 'paleturquoise' => '175,238,238',
2572 'palevioletred' => '219,112,147',
2573 'papayawhip' => '255,239,213',
2574 'peachpuff' => '255,218,185',
2575 'peru' => '205,133,63',
2576 'pink' => '255,192,203',
2577 'plum' => '221,160,221',
2578 'powderblue' => '176,224,230',
2579 'purple' => '128,0,128',
2580 'red' => '255,0,0',
2581 'rosybrown' => '188,143,143',
2582 'royalblue' => '65,105,225',
2583 'saddlebrown' => '139,69,19',
2584 'salmon' => '250,128,114',
2585 'sandybrown' => '244,164,96',
2586 'seagreen' => '46,139,87',
2587 'seashell' => '255,245,238',
2588 'sienna' => '160,82,45',
2589 'silver' => '192,192,192',
2590 'skyblue' => '135,206,235',
2591 'slateblue' => '106,90,205',
2592 'slategray' => '112,128,144',
2593 'slategrey' => '112,128,144',
2594 'snow' => '255,250,250',
2595 'springgreen' => '0,255,127',
2596 'steelblue' => '70,130,180',
2597 'tan' => '210,180,140',
2598 'teal' => '0,128,128',
2599 'thistle' => '216,191,216',
2600 'tomato' => '255,99,71',
2601 'transparent' => '0,0,0,0',
2602 'turquoise' => '64,224,208',
2603 'violet' => '238,130,238',
2604 'wheat' => '245,222,179',
2605 'white' => '255,255,255',
2606 'whitesmoke' => '245,245,245',
2607 'yellow' => '255,255,0',
2608 'yellowgreen' => '154,205,50'
2609 );
2610}
2611
2612// responsible for taking a string of LESS code and converting it into a
2613// syntax tree
2615{
2616 protected static $nextBlockId = 0; // used to uniquely identify blocks
2617
2618 protected static $precedence = array(
2619 '=<' => 0,
2620 '>=' => 0,
2621 '=' => 0,
2622 '<' => 0,
2623 '>' => 0,
2624
2625 '+' => 1,
2626 '-' => 1,
2627 '*' => 2,
2628 '/' => 2,
2629 '%' => 2,
2630 );
2631
2632 protected static $whitePattern;
2633 protected static $commentMulti;
2634
2635 protected static $commentSingle = "//";
2636 protected static $commentMultiLeft = "/*";
2637 protected static $commentMultiRight = "*/";
2638
2639 // regex string to match any of the operators
2640 protected static $operatorString;
2641
2642 // these properties will supress division unless it's inside parenthases
2643 protected static $supressDivisionProps =
2644 array('/border-radius$/i', '/^font$/i');
2645
2646 protected $blockDirectives = array("font-face", "keyframes", "page", "-moz-document", "viewport", "-moz-viewport", "-o-viewport", "-ms-viewport");
2647 protected $lineDirectives = array("charset");
2648
2658 protected $inParens = false;
2659
2660 // caches preg escaped literals
2661 protected static $literalCache = array();
2662
2663 public $env;
2664 public $buffer;
2665 public $count;
2666 public $line;
2667 public $eatWhiteDefault;
2668 public $lessc;
2669 public $sourceName;
2670 public $writeComments;
2671 public $seenComments;
2672 public $currentProperty;
2673 public $inExp;
2674
2675
2676 public function __construct($lessc, $sourceName = null)
2677 {
2678 $this->eatWhiteDefault = true;
2679 // reference to less needed for vPrefix, mPrefix, and parentSelector
2680 $this->lessc = $lessc;
2681
2682 $this->sourceName = $sourceName; // name used for error messages
2683
2684 $this->writeComments = false;
2685
2686 if (!self::$operatorString) {
2687 self::$operatorString =
2688 '('.implode('|', array_map(
2689 array('lessc', 'preg_quote'),
2690 array_keys(self::$precedence)
2691 )).')';
2692
2693 $commentSingle = Lessc::preg_quote(self::$commentSingle);
2694 $commentMultiLeft = Lessc::preg_quote(self::$commentMultiLeft);
2695 $commentMultiRight = Lessc::preg_quote(self::$commentMultiRight);
2696
2697 self::$commentMulti = $commentMultiLeft.'.*?'.$commentMultiRight;
2698 self::$whitePattern = '/'.$commentSingle.'[^\n]*\s*|('.self::$commentMulti.')\s*|\s+/Ais';
2699 }
2700 }
2701
2709 public function parse($buffer)
2710 {
2711 $this->count = 0;
2712 $this->line = 1;
2713
2714 $this->env = null; // block stack
2715 $this->buffer = $this->writeComments ? $buffer : $this->removeComments($buffer);
2716 $this->pushSpecialBlock("root");
2717 $this->eatWhiteDefault = true;
2718 $this->seenComments = array();
2719
2720 // trim whitespace on head
2721 // if (preg_match('/^\s+/', $this->buffer, $m)) {
2722 // $this->line += substr_count($m[0], "\n");
2723 // $this->buffer = ltrim($this->buffer);
2724 // }
2725 $this->whitespace();
2726
2727 // parse the entire file
2728 while (false !== $this->parseChunk());
2729
2730 if ($this->count != strlen($this->buffer)) {
2731 $this->throwError('parse error count '.$this->count.' != len buffer '.strlen($this->buffer));
2732
2733 }
2734
2735 // TODO report where the block was opened
2736 if (!property_exists($this->env, 'parent') || !is_null($this->env->parent)) {
2737 throw new exception('parse error: unclosed block');
2738 }
2739
2740 return $this->env;
2741 }
2742
2779 protected function parseChunk()
2780 {
2781 if (empty($this->buffer)) {
2782 return false;
2783 }
2784 $s = $this->seek();
2785
2786 if ($this->whitespace()) {
2787 return true;
2788 }
2789
2790 $key = null;
2791 $value = null;
2792 $mediaQueries = null;
2793 $dirName = null;
2794 $dirValue = null;
2795 $importValue = null;
2796 $guards = null;
2797 $tag = null;
2798 $args = null;
2799 $isVararg = null;
2800 $argv = null;
2801 $suffix = null;
2802 $var = null;
2803 $tags = null;
2804
2805 // setting a property
2806 if ($this->keyword($key) && $this->assign() &&
2807 $this->propertyValue($value, $key) && $this->end()
2808 ) {
2809 $this->append(array('assign', $key, $value), $s);
2810 return true;
2811 } else {
2812 $this->seek($s);
2813 }
2814
2815
2816 // look for special css blocks
2817 if ($this->literal('@', false)) {
2818 $this->count--;
2819
2820 // media
2821 if ($this->literal('@media')) {
2822 if ($this->mediaQueryList($mediaQueries)
2823 && $this->literal('{')
2824 ) {
2825 $media = $this->pushSpecialBlock("media");
2826 $media->queries = is_null($mediaQueries) ? array() : $mediaQueries;
2827 return true;
2828 } else {
2829 $this->seek($s);
2830 return false;
2831 }
2832 }
2833
2834 if ($this->literal("@", false) && $this->keyword($dirName)) {
2835 if ($this->isDirective($dirName, $this->blockDirectives)) {
2836 if ($this->openString("{", $dirValue, null, array(";")) &&
2837 $this->literal("{")
2838 ) {
2839 $dir = $this->pushSpecialBlock("directive");
2840 $dir->name = $dirName;
2841 if (isset($dirValue)) {
2842 $dir->value = $dirValue;
2843 }
2844 return true;
2845 }
2846 } elseif ($this->isDirective($dirName, $this->lineDirectives)) {
2847 if ($this->propertyValue($dirValue) && $this->end()) {
2848 $this->append(array("directive", $dirName, $dirValue));
2849 return true;
2850 }
2851 }
2852 }
2853
2854 $this->seek($s);
2855 }
2856
2857 // setting a variable
2858 if ($this->variable($var) && $this->assign() &&
2859 $this->propertyValue($value) && $this->end()
2860 ) {
2861 $this->append(array('assign', $var, $value), $s);
2862 return true;
2863 } else {
2864 $this->seek($s);
2865 }
2866
2867 if ($this->import($importValue)) {
2868 $this->append($importValue, $s);
2869 return true;
2870 }
2871
2872 // opening parametric mixin
2873 if ($this->tag($tag, true) && $this->argumentDef($args, $isVararg) &&
2874 $this->guards($guards) &&
2875 $this->literal('{')
2876 ) {
2877 $block = $this->pushBlock($this->fixTags(array($tag)));
2878 $block->args = $args;
2879 $block->isVararg = $isVararg;
2880 if (!empty($guards)) {
2881 $block->guards = $guards;
2882 }
2883 return true;
2884 } else {
2885 $this->seek($s);
2886 }
2887
2888 // opening a simple block
2889 if ($this->tags($tags) && $this->literal('{', false)) {
2890 $tags = $this->fixTags($tags);
2891 $this->pushBlock($tags);
2892 return true;
2893 } else {
2894 $this->seek($s);
2895 }
2896
2897 // closing a block
2898 if ($this->literal('}', false)) {
2899 try {
2900 $block = $this->pop();
2901 } catch (exception $e) {
2902 $this->seek($s);
2903 $this->throwError($e->getMessage());
2904 }
2905
2906 $hidden = false;
2907 if (is_null($block->type)) {
2908 $hidden = true;
2909 if (!isset($block->args)) {
2910 foreach ($block->tags as $tag) {
2911 if (!is_string($tag) || $tag[0] != $this->lessc->mPrefix) {
2912 $hidden = false;
2913 break;
2914 }
2915 }
2916 }
2917
2918 foreach ($block->tags as $tag) {
2919 if (is_string($tag)) {
2920 $this->env->children[$tag][] = $block;
2921 }
2922 }
2923 }
2924
2925 if (!$hidden) {
2926 $this->append(array('block', $block), $s);
2927 }
2928
2929 // this is done here so comments aren't bundled into he block that
2930 // was just closed
2931 $this->whitespace();
2932 return true;
2933 }
2934
2935 // mixin
2936 if ($this->mixinTags($tags) &&
2937 $this->argumentDef($argv, $isVararg) &&
2938 $this->keyword($suffix) && $this->end()
2939 ) {
2940 $tags = $this->fixTags($tags);
2941 $this->append(array('mixin', $tags, $argv, $suffix), $s);
2942 return true;
2943 } else {
2944 $this->seek($s);
2945 }
2946
2947 // spare ;
2948 if ($this->literal(';')) {
2949 return true;
2950 }
2951
2952 return false; // got nothing, throw error
2953 }
2954
2955 protected function isDirective($dirname, $directives)
2956 {
2957 // TODO: cache pattern in parser
2958 $pattern = implode(
2959 "|",
2960 array_map(array("lessc", "preg_quote"), $directives)
2961 );
2962 $pattern = '/^(-[a-z-]+-)?('.$pattern.')$/i';
2963
2964 return preg_match($pattern, $dirname);
2965 }
2966
2967 protected function fixTags($tags)
2968 {
2969 // move @ tags out of variable namespace
2970 foreach ($tags as &$tag) {
2971 if ($tag[0] == $this->lessc->vPrefix) {
2972 $tag[0] = $this->lessc->mPrefix;
2973 }
2974 }
2975 return $tags;
2976 }
2977
2978 // a list of expressions
2979 protected function expressionList(&$exps)
2980 {
2981 $exp = null;
2982
2983 $values = array();
2984
2985 while ($this->expression($exp)) {
2986 $values[] = $exp;
2987 }
2988
2989 if (count($values) == 0) {
2990 return false;
2991 }
2992
2993 $exps = Lessc::compressList($values, ' ');
2994 return true;
2995 }
2996
3001 protected function expression(&$out)
3002 {
3003 $lhs = null;
3004 $rhs = null;
3005
3006 if ($this->value($lhs)) {
3007 $out = $this->expHelper($lhs, 0);
3008
3009 // look for / shorthand
3010 if (!empty($this->env->supressedDivision)) {
3011 unset($this->env->supressedDivision);
3012 $s = $this->seek();
3013 if ($this->literal("/") && $this->value($rhs)) {
3014 $out = array("list", "",
3015 array($out, array("keyword", "/"), $rhs));
3016 } else {
3017 $this->seek($s);
3018 }
3019 }
3020
3021 return true;
3022 }
3023 return false;
3024 }
3025
3029 protected function expHelper($lhs, $minP)
3030 {
3031 $next = null;
3032 $rhs = null;
3033
3034 $this->inExp = true;
3035 $ss = $this->seek();
3036
3037 while (true) {
3038 $whiteBefore = isset($this->buffer[$this->count - 1]) &&
3039 ctype_space($this->buffer[$this->count - 1]);
3040
3041 // If there is whitespace before the operator, then we require
3042 // whitespace after the operator for it to be an expression
3043 $needWhite = $whiteBefore && !$this->inParens;
3044
3045 $m = array();
3046 if ($this->match(self::$operatorString.($needWhite ? '\s' : ''), $m) && self::$precedence[$m[1]] >= $minP) {
3047 if (!$this->inParens && isset($this->env->currentProperty) && $m[1] == "/" && empty($this->env->supressedDivision)) {
3048 foreach (self::$supressDivisionProps as $pattern) {
3049 if (preg_match($pattern, $this->env->currentProperty)) {
3050 $this->env->supressedDivision = true;
3051 break 2;
3052 }
3053 }
3054 }
3055
3056
3057 $whiteAfter = isset($this->buffer[$this->count - 1]) &&
3058 ctype_space($this->buffer[$this->count - 1]);
3059
3060 if (!$this->value($rhs)) {
3061 break;
3062 }
3063
3064 // peek for next operator to see what to do with rhs
3065 if ($this->peek(self::$operatorString, $next) && self::$precedence[$next[1]] > self::$precedence[$m[1]]) {
3066 $rhs = $this->expHelper($rhs, self::$precedence[$next[1]]);
3067 }
3068
3069 $lhs = array('expression', $m[1], $lhs, $rhs, $whiteBefore, $whiteAfter);
3070 $ss = $this->seek();
3071
3072 continue;
3073 }
3074
3075 break;
3076 }
3077
3078 $this->seek($ss);
3079
3080 return $lhs;
3081 }
3082
3083 // consume a list of values for a property
3084 public function propertyValue(&$value, $keyName = null)
3085 {
3086 $v = null;
3087 $values = array();
3088
3089 if ($keyName !== null) {
3090 $this->env->currentProperty = $keyName;
3091 }
3092
3093 $s = null;
3094 while ($this->expressionList($v)) {
3095 $values[] = $v;
3096 $s = $this->seek();
3097 if (!$this->literal(',')) {
3098 break;
3099 }
3100 }
3101
3102 if ($s) {
3103 $this->seek($s);
3104 }
3105
3106 if ($keyName !== null) {
3107 unset($this->env->currentProperty);
3108 }
3109
3110 if (count($values) == 0) {
3111 return false;
3112 }
3113
3114 $value = Lessc::compressList($values, ', ');
3115 return true;
3116 }
3117
3118 protected function parenValue(&$out)
3119 {
3120 $exp = null;
3121
3122 $s = $this->seek();
3123
3124 // speed shortcut
3125 if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] != "(") {
3126 return false;
3127 }
3128
3130 if ($this->literal("(") &&
3131 ($this->inParens = true) && $this->expression($exp) &&
3132 $this->literal(")")
3133 ) {
3134 $out = $exp;
3135 $this->inParens = $inParens;
3136 return true;
3137 } else {
3138 $this->inParens = $inParens;
3139 $this->seek($s);
3140 }
3141
3142 return false;
3143 }
3144
3145 // a single value
3146 protected function value(&$value)
3147 {
3148 $inner = null;
3149 $word = null;
3150 $str = null;
3151 $var = null;
3152
3153 $s = $this->seek();
3154
3155 // speed shortcut
3156 if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] == "-") {
3157 // negation
3158 if ($this->literal("-", false) &&
3159 (($this->variable($inner) && $inner = array("variable", $inner)) ||
3160 $this->unit($inner) ||
3161 $this->parenValue($inner))
3162 ) {
3163 $value = array("unary", "-", $inner);
3164 return true;
3165 } else {
3166 $this->seek($s);
3167 }
3168 }
3169
3170 if ($this->parenValue($value)) {
3171 return true;
3172 }
3173 if ($this->unit($value)) {
3174 return true;
3175 }
3176 if ($this->color($value)) {
3177 return true;
3178 }
3179 if ($this->func($value)) {
3180 return true;
3181 }
3182 if ($this->string($value)) {
3183 return true;
3184 }
3185
3186 if ($this->keyword($word)) {
3187 $value = array('keyword', $word);
3188 return true;
3189 }
3190
3191 // try a variable
3192 if ($this->variable($var)) {
3193 $value = array('variable', $var);
3194 return true;
3195 }
3196
3197 // unquote string (should this work on any type?
3198 if ($this->literal("~") && $this->string($str)) {
3199 $value = array("escape", $str);
3200 return true;
3201 } else {
3202 $this->seek($s);
3203 }
3204
3205 // css hack: \0
3206 $m = array();
3207 if ($this->literal('\\') && $this->match('([0-9]+)', $m)) {
3208 $value = array('keyword', '\\'.$m[1]);
3209 return true;
3210 } else {
3211 $this->seek($s);
3212 }
3213
3214 return false;
3215 }
3216
3217 // an import statement
3218 protected function import(&$out, $value = '')
3219 {
3220 if (!$this->literal('@import')) {
3221 return false;
3222 }
3223
3224 // @import "something.css" media;
3225 // @import url("something.css") media;
3226 // @import url(something.css) media;
3227
3228 if ($this->propertyValue($value)) {
3229 $out = array("import", $value);
3230 return true;
3231 }
3232
3233 return false;
3234 }
3235
3236 protected function mediaQueryList(&$out)
3237 {
3238 $list = null;
3239
3240 if ($this->genericList($list, "mediaQuery", ",", false)) {
3241 $out = $list[2];
3242 return true;
3243 }
3244 return false;
3245 }
3246
3247 protected function mediaQuery(&$out)
3248 {
3249 $mediaType = null;
3250
3251 $s = $this->seek();
3252
3253 $expressions = null;
3254 $parts = array();
3255
3256 if ((($this->literal("only") && ($only = true)) || ($this->literal("not") && ($not = true))) && $this->keyword($mediaType)) {
3257 $prop = array("mediaType");
3258 if (isset($only)) {
3259 $prop[] = "only";
3260 }
3261 if (isset($not)) {
3262 $prop[] = "not";
3263 }
3264 $prop[] = $mediaType;
3265 $parts[] = $prop;
3266 } else {
3267 $this->seek($s);
3268 }
3269
3270
3271 if (!empty($mediaType) && !$this->literal("and")) {
3272 // ~
3273 } else {
3274 $this->genericList($expressions, "mediaExpression", "and", false);
3275 if (is_array($expressions)) {
3276 $parts = array_merge($parts, $expressions[2]);
3277 }
3278 }
3279
3280 if (count($parts) == 0) {
3281 $this->seek($s);
3282 return false;
3283 }
3284
3285 $out = $parts;
3286 return true;
3287 }
3288
3289 protected function mediaExpression(&$out)
3290 {
3291 $feature = null;
3292 $variable = null;
3293
3294 $s = $this->seek();
3295 $value = null;
3296 if ($this->literal("(") &&
3297 $this->keyword($feature) &&
3298 ($this->literal(":") && $this->expression($value)) &&
3299 $this->literal(")")
3300 ) {
3301 $out = array("mediaExp", $feature);
3302 if ($value) {
3303 $out[] = $value;
3304 }
3305 return true;
3306 } elseif ($this->variable($variable)) {
3307 $out = array('variable', $variable);
3308 return true;
3309 }
3310
3311 $this->seek($s);
3312 return false;
3313 }
3314
3315 // an unbounded string stopped by $end
3316 protected function openString($end, &$out, $nestingOpen = null, $rejectStrs = null)
3317 {
3318 $str = null;
3319 $inter = null;
3320
3321 $oldWhite = $this->eatWhiteDefault;
3322 $this->eatWhiteDefault = false;
3323
3324 $stop = array("'", '"', "@{", $end);
3325 $stop = array_map(array("lessc", "preg_quote"), $stop);
3326 // $stop[] = self::$commentMulti;
3327
3328 if (!is_null($rejectStrs)) {
3329 $stop = array_merge($stop, $rejectStrs);
3330 }
3331
3332 $patt = '(.*?)('.implode("|", $stop).')';
3333
3334 $nestingLevel = 0;
3335
3336 $content = array();
3337 $m = array();
3338 while ($this->match($patt, $m, false)) {
3339 if (!empty($m[1])) {
3340 $content[] = $m[1];
3341 if ($nestingOpen) {
3342 $nestingLevel += substr_count($m[1], $nestingOpen);
3343 }
3344 }
3345
3346 $tok = $m[2];
3347
3348 $this->count -= strlen($tok);
3349 if ($tok == $end) {
3350 if ($nestingLevel == 0) {
3351 break;
3352 } else {
3353 $nestingLevel--;
3354 }
3355 }
3356
3357 if (($tok == "'" || $tok == '"') && $this->string($str)) {
3358 $content[] = $str;
3359 continue;
3360 }
3361
3362 if ($tok == "@{" && $this->interpolation($inter)) {
3363 $content[] = $inter;
3364 continue;
3365 }
3366
3367 if (!empty($rejectStrs) && in_array($tok, $rejectStrs)) {
3368 break;
3369 }
3370
3371 $content[] = $tok;
3372 $this->count += strlen($tok);
3373 }
3374
3375 $this->eatWhiteDefault = $oldWhite;
3376
3377 if (count($content) == 0) {
3378 return false;
3379 }
3380
3381 // trim the end
3382 if (is_string(end($content))) {
3383 $content[count($content) - 1] = rtrim(end($content));
3384 }
3385
3386 $out = array("string", "", $content);
3387 return true;
3388 }
3389
3390 protected function string(&$out)
3391 {
3392 $inter = null;
3393
3394 $s = $this->seek();
3395 if ($this->literal('"', false)) {
3396 $delim = '"';
3397 } elseif ($this->literal("'", false)) {
3398 $delim = "'";
3399 } else {
3400 return false;
3401 }
3402
3403 $content = array();
3404
3405 // look for either ending delim , escape, or string interpolation
3406 $patt = '([^\n]*?)(@\{|\\\\|'.
3407 Lessc::preg_quote($delim).')';
3408
3409 $oldWhite = $this->eatWhiteDefault;
3410 $this->eatWhiteDefault = false;
3411
3412 $m = array();
3413 while ($this->match($patt, $m, false)) {
3414 $content[] = $m[1];
3415 if ($m[2] == "@{") {
3416 $this->count -= strlen($m[2]);
3417 if ($this->interpolation($inter)) {
3418 $content[] = $inter;
3419 } else {
3420 $this->count += strlen($m[2]);
3421 $content[] = "@{"; // ignore it
3422 }
3423 } elseif ($m[2] == '\\') {
3424 $content[] = $m[2];
3425 if ($this->literal($delim, false)) {
3426 $content[] = $delim;
3427 }
3428 } else {
3429 $this->count -= strlen($delim);
3430 break; // delim
3431 }
3432 }
3433
3434 $this->eatWhiteDefault = $oldWhite;
3435
3436 if ($this->literal($delim)) {
3437 $out = array("string", $delim, $content);
3438 return true;
3439 }
3440
3441 $this->seek($s);
3442 return false;
3443 }
3444
3445 protected function interpolation(&$out)
3446 {
3447 $interp = array();
3448
3449 $oldWhite = $this->eatWhiteDefault;
3450 $this->eatWhiteDefault = true;
3451
3452 $s = $this->seek();
3453 if ($this->literal("@{") &&
3454 $this->openString("}", $interp, null, array("'", '"', ";")) &&
3455 $this->literal("}", false)
3456 ) {
3457 $out = array("interpolate", $interp);
3458 $this->eatWhiteDefault = $oldWhite;
3459 if ($this->eatWhiteDefault) {
3460 $this->whitespace();
3461 }
3462 return true;
3463 }
3464
3465 $this->eatWhiteDefault = $oldWhite;
3466 $this->seek($s);
3467 return false;
3468 }
3469
3470 protected function unit(&$unit)
3471 {
3472 $m = array();
3473
3474 // speed shortcut
3475 if (isset($this->buffer[$this->count])) {
3476 $char = $this->buffer[$this->count];
3477 if (!ctype_digit($char) && $char != ".") {
3478 return false;
3479 }
3480 }
3481
3482 if ($this->match('([0-9]+(?:\.[0-9]*)?|\.[0-9]+)([%a-zA-Z]+)?', $m)) {
3483 $unit = array("number", $m[1], empty($m[2]) ? "" : $m[2]);
3484 return true;
3485 }
3486 return false;
3487 }
3488
3489 // a # color
3490 protected function color(&$out)
3491 {
3492 $m = array();
3493
3494 if ($this->match('(#(?:[0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{3}))', $m)) {
3495 if (strlen($m[1]) > 7) {
3496 $out = array("string", "", array($m[1]));
3497 } else {
3498 $out = array("raw_color", $m[1]);
3499 }
3500 return true;
3501 }
3502
3503 return false;
3504 }
3505
3506 // consume an argument definition list surrounded by ()
3507 // each argument is a variable name with optional value
3508 // or at the end a ... or a variable named followed by ...
3509 // arguments are separated by , unless a ; is in the list, then ; is the
3510 // delimiter.
3511 protected function argumentDef(&$args, &$isVararg)
3512 {
3513 $value = array();
3514 $rhs = null;
3515
3516 $s = $this->seek();
3517 if (!$this->literal('(')) {
3518 return false;
3519 }
3520
3521 $values = array();
3522 $delim = ",";
3523 $method = "expressionList";
3524
3525 $isVararg = false;
3526 while (true) {
3527 if ($this->literal("...")) {
3528 $isVararg = true;
3529 break;
3530 }
3531
3532 if ($this->$method($value)) {
3533 if ($value[0] == "variable") {
3534 $arg = array("arg", $value[1]);
3535 $ss = $this->seek();
3536
3537 if ($this->assign() && $this->$method($rhs)) {
3538 $arg[] = $rhs;
3539 } else {
3540 $this->seek($ss);
3541 if ($this->literal("...")) {
3542 $arg[0] = "rest";
3543 $isVararg = true;
3544 }
3545 }
3546
3547 $values[] = $arg;
3548 if ($isVararg) {
3549 break;
3550 }
3551 continue;
3552 } else {
3553 $values[] = array("lit", $value);
3554 }
3555 }
3556
3557
3558 if (!$this->literal($delim)) {
3559 if ($delim == "," && $this->literal(";")) {
3560 // found new delim, convert existing args
3561 $delim = ";";
3562 $method = "propertyValue";
3563
3564 // transform arg list
3565 if (isset($values[1])) { // 2 items
3566 $newList = array();
3567 foreach ($values as $i => $arg) {
3568 switch ($arg[0]) {
3569 case "arg":
3570 if ($i) {
3571 $this->throwError("Cannot mix ; and , as delimiter types");
3572 }
3573 $newList[] = $arg[2];
3574 break;
3575 case "lit":
3576 $newList[] = $arg[1];
3577 break;
3578 case "rest":
3579 $this->throwError("Unexpected rest before semicolon");
3580 }
3581 }
3582
3583 $newList = array("list", ", ", $newList);
3584
3585 switch ($values[0][0]) {
3586 case "arg":
3587 $newArg = array("arg", $values[0][1], $newList);
3588 break;
3589 case "lit":
3590 $newArg = array("lit", $newList);
3591 break;
3592 }
3593
3594 } elseif ($values) { // 1 item
3595 $newArg = $values[0];
3596 }
3597
3598 if ($newArg) {
3599 $values = array($newArg);
3600 }
3601 } else {
3602 break;
3603 }
3604 }
3605 }
3606
3607 if (!$this->literal(')')) {
3608 $this->seek($s);
3609 return false;
3610 }
3611
3612 $args = $values;
3613
3614 return true;
3615 }
3616
3617 // consume a list of tags
3618 // this accepts a hanging delimiter
3619 protected function tags(&$tags, $simple = false, $delim = ',')
3620 {
3621 $tt = array();
3622
3623 $tags = array();
3624 while ($this->tag($tt, $simple)) {
3625 $tags[] = $tt;
3626 if (!$this->literal($delim)) {
3627 break;
3628 }
3629 }
3630 if (count($tags) == 0) {
3631 return false;
3632 }
3633
3634 return true;
3635 }
3636
3637 // list of tags of specifying mixin path
3638 // optionally separated by > (lazy, accepts extra >)
3639 protected function mixinTags(&$tags)
3640 {
3641 $tt = array();
3642
3643 $tags = array();
3644 while ($this->tag($tt, true)) {
3645 $tags[] = $tt;
3646 $this->literal(">");
3647 }
3648
3649 if (!$tags) {
3650 return false;
3651 }
3652
3653 return true;
3654 }
3655
3656 // a bracketed value (contained within in a tag definition)
3657 protected function tagBracket(&$parts, &$hasExpression)
3658 {
3659 $str = null;
3660 $inter = null;
3661 $word = null;
3662
3663 // speed shortcut
3664 if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] != "[") {
3665 return false;
3666 }
3667
3668 $s = $this->seek();
3669
3670 $hasInterpolation = false;
3671
3672 if ($this->literal("[", false)) {
3673 $attrParts = array("[");
3674 // keyword, string, operator
3675 while (true) {
3676 if ($this->literal("]", false)) {
3677 $this->count--;
3678 break; // get out early
3679 }
3680
3681 $m = array();
3682 if ($this->match('\s+', $m)) {
3683 $attrParts[] = " ";
3684 continue;
3685 }
3686 if ($this->string($str)) {
3687 // escape parent selector, (yuck)
3688 foreach ($str[2] as &$chunk) {
3689 $chunk = str_replace($this->lessc->parentSelector, "$&$", $chunk);
3690 }
3691
3692 $attrParts[] = $str;
3693 $hasInterpolation = true;
3694 continue;
3695 }
3696
3697 if ($this->keyword($word)) {
3698 $attrParts[] = $word;
3699 continue;
3700 }
3701
3702 if ($this->interpolation($inter)) {
3703 $attrParts[] = $inter;
3704 $hasInterpolation = true;
3705 continue;
3706 }
3707
3708 // operator, handles attr namespace too
3709 if ($this->match('[|-~\$\*\^=]+', $m)) {
3710 $attrParts[] = $m[0];
3711 continue;
3712 }
3713
3714 break;
3715 }
3716
3717 if ($this->literal("]", false)) {
3718 $attrParts[] = "]";
3719 foreach ($attrParts as $part) {
3720 $parts[] = $part;
3721 }
3722 $hasExpression = $hasExpression || $hasInterpolation;
3723 return true;
3724 }
3725 $this->seek($s);
3726 }
3727
3728 $this->seek($s);
3729 return false;
3730 }
3731
3732 // a space separated list of selectors
3733 protected function tag(&$tag, $simple = false)
3734 {
3735 $interp = null;
3736 $unit = null;
3737
3738 if ($simple) {
3739 $chars = '^@,:;{}\][>\‍(\‍) "\'';
3740 } else {
3741 $chars = '^@,;{}["\'';
3742 }
3743 $s = $this->seek();
3744
3745 $hasExpression = false;
3746 $parts = array();
3747 while ($this->tagBracket($parts, $hasExpression));
3748
3749 $oldWhite = $this->eatWhiteDefault;
3750 $this->eatWhiteDefault = false;
3751
3752 while (true) {
3753 $m = array();
3754 if ($this->match('(['.$chars.'0-9]['.$chars.']*)', $m)) {
3755 $parts[] = $m[1];
3756 if ($simple) {
3757 break;
3758 }
3759
3760 while ($this->tagBracket($parts, $hasExpression));
3761 continue;
3762 }
3763
3764 if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] == "@") {
3765 if ($this->interpolation($interp)) {
3766 $hasExpression = true;
3767 $interp[2] = true; // don't unescape
3768 $parts[] = $interp;
3769 continue;
3770 }
3771
3772 if ($this->literal("@")) {
3773 $parts[] = "@";
3774 continue;
3775 }
3776 }
3777
3778 if ($this->unit($unit)) { // for keyframes
3779 $parts[] = $unit[1];
3780 $parts[] = $unit[2];
3781 continue;
3782 }
3783
3784 break;
3785 }
3786
3787 $this->eatWhiteDefault = $oldWhite;
3788 if (!$parts) {
3789 $this->seek($s);
3790 return false;
3791 }
3792
3793 if ($hasExpression) {
3794 $tag = array("exp", array("string", "", $parts));
3795 } else {
3796 $tag = trim(implode($parts));
3797 }
3798
3799 $this->whitespace();
3800 return true;
3801 }
3802
3803 // a css function
3804 protected function func(&$func)
3805 {
3806 $s = $this->seek();
3807
3808 $m = array();
3809 $value = array();
3810 $string = array();
3811 $name = null;
3812
3813 if ($this->match('(%|[\w\-_][\w\-_:\.]+|[\w_])', $m) && $this->literal('(')) {
3814 $fname = $m[1];
3815
3816 $sPreArgs = $this->seek();
3817
3818 $args = array();
3819 while (true) {
3820 $ss = $this->seek();
3821 // this ugly nonsense is for ie filter properties
3822 if ($this->keyword($name) && $this->literal('=') && $this->expressionList($value)) {
3823 $args[] = array("string", "", array($name, "=", $value));
3824 } else {
3825 $this->seek($ss);
3826 if ($this->expressionList($value)) {
3827 $args[] = $value;
3828 }
3829 }
3830
3831 if (!$this->literal(',')) {
3832 break;
3833 }
3834 }
3835 $args = array('list', ',', $args);
3836
3837 if ($this->literal(')')) {
3838 $func = array('function', $fname, $args);
3839 return true;
3840 } elseif ($fname == 'url') {
3841 // couldn't parse and in url? treat as string
3842 $this->seek($sPreArgs);
3843 if ($this->openString(")", $string) && $this->literal(")")) {
3844 $func = array('function', $fname, $string);
3845 return true;
3846 }
3847 }
3848 }
3849
3850 $this->seek($s);
3851 return false;
3852 }
3853
3854 // consume a less variable
3855 protected function variable(&$name)
3856 {
3857 $sub = null;
3858 $name = null;
3859
3860 $s = $this->seek();
3861 if ($this->literal($this->lessc->vPrefix, false) &&
3862 ($this->variable($sub) || $this->keyword($name))
3863 ) {
3864 if (!empty($sub)) {
3865 $name = array('variable', $sub);
3866 } else {
3867 $name = $this->lessc->vPrefix.$name;
3868 }
3869 return true;
3870 }
3871
3872 $name = null;
3873 $this->seek($s);
3874 return false;
3875 }
3876
3881 protected function assign($name = null)
3882 {
3883 if ($name) {
3884 $this->currentProperty = $name;
3885 }
3886 return $this->literal(':') || $this->literal('=');
3887 }
3888
3889 // consume a keyword
3890 protected function keyword(&$word)
3891 {
3892 $m = array();
3893 if ($this->match('([\w_\-\*!"][\w\-_"]*)', $m)) {
3894 $word = $m[1];
3895 return true;
3896 }
3897 return false;
3898 }
3899
3900 // consume an end of statement delimiter
3901 protected function end()
3902 {
3903 if ($this->literal(';', false)) {
3904 return true;
3905 } elseif ($this->count == strlen($this->buffer) || $this->buffer[$this->count] == '}') {
3906 // if there is end of file or a closing block next then we don't need a ;
3907 return true;
3908 }
3909 return false;
3910 }
3911
3912 protected function guards(&$guards)
3913 {
3914 $g = null;
3915
3916 $s = $this->seek();
3917
3918 if (!$this->literal("when")) {
3919 $this->seek($s);
3920 return false;
3921 }
3922
3923 $guards = array();
3924
3925 while ($this->guardGroup($g)) {
3926 $guards[] = $g;
3927 if (!$this->literal(",")) {
3928 break;
3929 }
3930 }
3931
3932 if (count($guards) == 0) {
3933 $guards = null;
3934 $this->seek($s);
3935 return false;
3936 }
3937
3938 return true;
3939 }
3940
3941 // a bunch of guards that are and'd together
3942 // TODO rename to guardGroup
3943 protected function guardGroup(&$guardGroup)
3944 {
3945 $guard = null;
3946
3947 $s = $this->seek();
3948 $guardGroup = array();
3949 while ($this->guard($guard)) {
3950 $guardGroup[] = $guard;
3951 if (!$this->literal("and")) {
3952 break;
3953 }
3954 }
3955
3956 if (count($guardGroup) == 0) {
3957 $guardGroup = null;
3958 $this->seek($s);
3959 return false;
3960 }
3961
3962 return true;
3963 }
3964
3965 protected function guard(&$guard)
3966 {
3967 $exp = null;
3968
3969 $s = $this->seek();
3970 $negate = $this->literal("not");
3971
3972 if ($this->literal("(") && $this->expression($exp) && $this->literal(")")) {
3973 $guard = $exp;
3974 if ($negate) {
3975 $guard = array("negate", $guard);
3976 }
3977 return true;
3978 }
3979
3980 $this->seek($s);
3981 return false;
3982 }
3983
3984 /* raw parsing functions */
3985
3986 protected function literal($what, $eatWhitespace = null)
3987 {
3988 if ($eatWhitespace === null) {
3989 $eatWhitespace = $this->eatWhiteDefault;
3990 }
3991
3992 // shortcut on single letter
3993 if (!isset($what[1]) && isset($this->buffer[$this->count])) {
3994 if ($this->buffer[$this->count] == $what) {
3995 if (!$eatWhitespace) {
3996 $this->count++;
3997 return true;
3998 }
3999 // goes below...
4000 } else {
4001 return false;
4002 }
4003 }
4004
4005 if (!isset(self::$literalCache[$what])) {
4006 self::$literalCache[$what] = Lessc::preg_quote($what);
4007 }
4008
4009 $m = array();
4010 return $this->match(self::$literalCache[$what], $m, $eatWhitespace);
4011 }
4012
4013 protected function genericList(&$out, $parseItem, $delim = "", $flatten = true)
4014 {
4015 $value = null;
4016
4017 $s = $this->seek();
4018 $items = array();
4019 while ($this->$parseItem($value)) {
4020 $items[] = $value;
4021 if ($delim) {
4022 if (!$this->literal($delim)) {
4023 break;
4024 }
4025 }
4026 }
4027
4028 if (count($items) == 0) {
4029 $this->seek($s);
4030 return false;
4031 }
4032
4033 if ($flatten && count($items) == 1) {
4034 $out = $items[0];
4035 } else {
4036 $out = array("list", $delim, $items);
4037 }
4038
4039 return true;
4040 }
4041
4042
4043 // advance counter to next occurrence of $what
4044 // $until - don't include $what in advance
4045 // $allowNewline, if string, will be used as valid char set
4046 protected function to($what, &$out, $until = false, $allowNewline = false)
4047 {
4048 if (is_string($allowNewline)) {
4049 $validChars = $allowNewline;
4050 } else {
4051 $validChars = $allowNewline ? "." : "[^\n]";
4052 }
4053 $m = array();
4054 if (!$this->match('('.$validChars.'*?)'.Lessc::preg_quote($what), $m, !$until)) {
4055 return false;
4056 }
4057 if ($until) {
4058 $this->count -= strlen($what); // give back $what
4059 }
4060 $out = $m[1];
4061 return true;
4062 }
4063
4064 // try to match something on head of buffer
4065 protected function match($regex, &$out, $eatWhitespace = null)
4066 {
4067 if ($eatWhitespace === null) {
4068 $eatWhitespace = $this->eatWhiteDefault;
4069 }
4070
4071 $r = '/'.$regex.($eatWhitespace && !$this->writeComments ? '\s*' : '').'/Ais';
4072 if (preg_match($r, $this->buffer, $out, 0, $this->count)) {
4073 $this->count += strlen($out[0]);
4074 if ($eatWhitespace && $this->writeComments) {
4075 $this->whitespace();
4076 }
4077 return true;
4078 }
4079 return false;
4080 }
4081
4082 // match some whitespace
4083 protected function whitespace()
4084 {
4085 if ($this->writeComments) {
4086 $gotWhite = false;
4087 $m = array();
4088 while (preg_match(self::$whitePattern, $this->buffer, $m, 0, $this->count)) {
4089 if (isset($m[1]) && empty($this->seenComments[$this->count])) {
4090 $this->append(array("comment", $m[1]));
4091 $this->seenComments[$this->count] = true;
4092 }
4093 $this->count += strlen($m[0]);
4094 $gotWhite = true;
4095 }
4096 return $gotWhite;
4097 } else {
4098 $this->match("", $m);
4099 return strlen($m[0]) > 0;
4100 }
4101 }
4102
4103 // match something without consuming it
4104 protected function peek($regex, &$out = null, $from = null)
4105 {
4106 if (is_null($from)) {
4107 $from = $this->count;
4108 }
4109 $r = '/'.$regex.'/Ais';
4110 $result = preg_match($r, $this->buffer, $out, 0, $from);
4111
4112 return $result;
4113 }
4114
4115 // seek to a spot in the buffer or return where we are on no argument
4116 protected function seek($where = null)
4117 {
4118 if ($where === null) {
4119 return $this->count;
4120 } else {
4121 $this->count = $where;
4122 }
4123 return true;
4124 }
4125
4126 /* misc functions */
4127
4128 public function throwError($msg = "parse error", $count = null)
4129 {
4130 $count = is_null($count) ? $this->count : $count;
4131
4132 $line = $this->line +
4133 substr_count(substr($this->buffer, 0, $count), "\n");
4134
4135 if (!empty($this->sourceName)) {
4136 $loc = "$this->sourceName on line $line";
4137 } else {
4138 $loc = "line: $line";
4139 }
4140
4141 // TODO this depends on $this->count
4142 $m = array();
4143 if ($this->peek("(.*?)(\n|$)", $m, $count)) {
4144 throw new exception("$msg: failed at `$m[1]` $loc");
4145 } else {
4146 throw new exception("$msg: $loc");
4147 }
4148 }
4149
4150 protected function pushBlock($selectors = null, $type = null)
4151 {
4152 $b = new stdclass();
4153 $b->parent = $this->env;
4154
4155 $b->type = $type;
4156 $b->id = self::$nextBlockId++;
4157
4158 $b->isVararg = false; // TODO: kill me from here
4159 $b->tags = $selectors;
4160
4161 $b->props = array();
4162 $b->children = array();
4163
4164 $this->env = $b;
4165 return $b;
4166 }
4167
4168 // push a block that doesn't multiply tags
4169 protected function pushSpecialBlock($type)
4170 {
4171 return $this->pushBlock(null, $type);
4172 }
4173
4174 // append a property to the current block
4175 protected function append($prop, $pos = null)
4176 {
4177 if ($pos !== null) {
4178 $prop[-1] = $pos;
4179 }
4180 $this->env->props[] = $prop;
4181 }
4182
4183 // pop something off the stack
4184 protected function pop()
4185 {
4186 $old = $this->env;
4187 $this->env = $this->env->parent;
4188 return $old;
4189 }
4190
4191 // remove comments from $text
4192 // todo: make it work for all functions, not just url
4193 protected function removeComments($text)
4194 {
4195 $look = array(
4196 'url(', '//', '/*', '"', "'"
4197 );
4198
4199 $out = '';
4200 $min = null;
4201 while (true) {
4202 // find the next item
4203 foreach ($look as $token) {
4204 $pos = strpos($text, $token);
4205 if ($pos !== false) {
4206 if (!isset($min) || $pos < $min[1]) {
4207 $min = array($token, $pos);
4208 }
4209 }
4210 }
4211
4212 if (is_null($min)) {
4213 break;
4214 }
4215
4216 $count = $min[1];
4217 $skip = 0;
4218 $newlines = 0;
4219 switch ($min[0]) {
4220 case 'url(':
4221 $m = array();
4222 if (preg_match('/url\‍(.*?\‍)/', $text, $m, 0, $count)) {
4223 $count += strlen($m[0]) - strlen($min[0]);
4224 }
4225 break;
4226 case '"':
4227 case "'":
4228 $m = array();
4229 if (preg_match('/'.$min[0].'.*?(?<!\\\\)'.$min[0].'/', $text, $m, 0, $count)) {
4230 $count += strlen($m[0]) - 1;
4231 }
4232 break;
4233 case '//':
4234 $skip = strpos($text, "\n", $count);
4235 if ($skip === false) {
4236 $skip = strlen($text) - $count;
4237 } else {
4238 $skip -= $count;
4239 }
4240 break;
4241 case '/*':
4242 $m = array();
4243 if (preg_match('/\/\*.*?\*\//s', $text, $m, 0, $count)) {
4244 $skip = strlen($m[0]);
4245 $newlines = substr_count($m[0], "\n");
4246 }
4247 break;
4248 }
4249
4250 if ($skip == 0) {
4251 $count += strlen($min[0]);
4252 }
4253
4254 $out .= substr($text, 0, $count).str_repeat("\n", $newlines);
4255 $text = substr($text, $count + $skip);
4256
4257 $min = null;
4258 }
4259
4260 return $out.$text;
4261 }
4262}
4263
4265{
4266 public $indentChar = " ";
4267
4268 public $break = "\n";
4269 public $open = " {";
4270 public $close = "}";
4271 public $selectorSeparator = ", ";
4272 public $assignSeparator = ":";
4273
4274 public $openSingle = " { ";
4275 public $closeSingle = " }";
4276
4277 public $disableSingle = false;
4278 public $breakSelectors = false;
4279
4280 public $compressColors = false;
4281 public $indentLevel;
4282
4283 public function __construct()
4284 {
4285 $this->indentLevel = 0;
4286 }
4287
4288 public function indentStr($n = 0)
4289 {
4290 return str_repeat($this->indentChar, max($this->indentLevel + $n, 0));
4291 }
4292
4293 public function property($name, $value)
4294 {
4295 return $name.$this->assignSeparator.$value.";";
4296 }
4297
4298 protected function isEmpty($block)
4299 {
4300 if (empty($block->lines)) {
4301 foreach ($block->children as $child) {
4302 if (!$this->isEmpty($child)) {
4303 return false;
4304 }
4305 }
4306
4307 return true;
4308 }
4309 return false;
4310 }
4311
4312 public function block($block)
4313 {
4314 if ($this->isEmpty($block)) {
4315 return;
4316 }
4317
4318 $inner = $pre = $this->indentStr();
4319
4320 $isSingle = !$this->disableSingle &&
4321 is_null($block->type) && count($block->lines) == 1;
4322
4323 if (!empty($block->selectors)) {
4324 $this->indentLevel++;
4325
4326 if ($this->breakSelectors) {
4327 $selectorSeparator = $this->selectorSeparator.$this->break.$pre;
4328 } else {
4329 $selectorSeparator = $this->selectorSeparator;
4330 }
4331
4332 echo $pre.
4333 implode($selectorSeparator, $block->selectors);
4334 if ($isSingle) {
4335 echo $this->openSingle;
4336 $inner = "";
4337 } else {
4338 echo $this->open.$this->break;
4339 $inner = $this->indentStr();
4340 }
4341 }
4342
4343 if (!empty($block->lines)) {
4344 $glue = $this->break.$inner;
4345 echo $inner.implode($glue, $block->lines);
4346 if (!$isSingle && !empty($block->children)) {
4347 echo $this->break;
4348 }
4349 }
4350
4351 foreach ($block->children as $child) {
4352 $this->block($child);
4353 }
4354
4355 if (!empty($block->selectors)) {
4356 if (!$isSingle && empty($block->children)) {
4357 echo $this->break;
4358 }
4359
4360 if ($isSingle) {
4361 echo $this->closeSingle.$this->break;
4362 } else {
4363 echo $pre.$this->close.$this->break;
4364 }
4365
4366 $this->indentLevel--;
4367 }
4368 }
4369}
4370
4375{
4376 public $disableSingle = true;
4377 public $open = "{";
4378 public $selectorSeparator = ",";
4379 public $assignSeparator = ":";
4380 public $break = "";
4381 public $compressColors = true;
4382
4383 public function indentStr($n = 0)
4384 {
4385 return "";
4386 }
4387}
4388
4393{
4394 public $disableSingle = true;
4395 public $breakSelectors = true;
4396 public $assignSeparator = ": ";
4397 public $selectorSeparator = ",";
4398}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:47
$c
Definition line.php:331
The LESS compiler and parser.
compileBlock($block)
Recursively compiles a block.
lib_mix($args)
lib_mix mixes two colors by weight mix(@color1, @color2, [@weight: 50%]); http://sass-lang....
__construct($fname=null)
Initialize any static state, can initialize parser for a file $opts isn't used yet.
cachedCompile($in, $force=false)
Execute lessphp on a .less file or a lessphp cache structure.
lib_data_uri($value)
Given an url, decide whether to output a regular link or the base64-encoded contents of the file.
funcToColor($func)
Convert the rgb, rgba, hsl color literals of function type as returned by the parser into values of c...
deduplicate($lines)
Deduplicate lines in a block.
lib_shade($args)
Mix color with black in variable proportion.
fileExists($name)
fileExists
toRGB($color)
Converts a hsl array into a color value in rgb.
lib_contrast($args)
lib_contrast
throwError($msg=null)
Uses the current value of $this->count to show line and line number.
colorArgs($args)
Helper function to get arguments for color manipulation functions.
compileValue($value)
Compiles a primitive value into a CSS property value.
lib_tint($args)
Mix color with white in variable proportion.
Class for compressed result.
Class for lessjs.
expHelper($lhs, $minP)
recursively parse infix equation with $lhs at precedence $minP
parseChunk()
Parse a single chunk off the head of the buffer and append it to the current parse environment.
assign($name=null)
Consume an assignment operator Can optionally take a name that will be set to the current property na...
parse($buffer)
Parse a string.
$inParens
if we are in parens we can be more liberal with whitespace around operators because it must evaluate ...
expression(&$out)
Attempt to consume an expression.
dolChmod($filepath, $newmask='')
Change mod of a file.