PageRenderTime 58ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/sparks/assets/1.5.1/libraries/lessc.php

https://bitbucket.org/inverse/ci-base
PHP | 3320 lines | 2495 code | 505 blank | 320 comment | 586 complexity | e16861b2c1977596090cf9f05bf226fe MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**
  3. * lessphp v0.3.7
  4. * http://leafo.net/lessphp
  5. *
  6. * LESS css compiler, adapted from http://lesscss.org
  7. *
  8. * Copyright 2012, Leaf Corcoran <leafot@gmail.com>
  9. * Licensed under MIT or GPLv3, see LICENSE
  10. */
  11. /**
  12. * The less compiler and parser.
  13. *
  14. * Converting LESS to CSS is a three stage process. The incoming file is parsed
  15. * by `lessc_parser` into a syntax tree, then it is compiled into another tree
  16. * representing the CSS structure by `lessc`. The CSS tree is fed into a
  17. * formatter, like `lessc_formatter` which then outputs CSS as a string.
  18. *
  19. * During the first compile, all values are *reduced*, which means that their
  20. * types are brought to the lowest form before being dump as strings. This
  21. * handles math equations, variable dereferences, and the like.
  22. *
  23. * The `parse` function of `lessc` is the entry point.
  24. *
  25. * In summary:
  26. *
  27. * The `lessc` class creates an intstance of the parser, feeds it LESS code,
  28. * then transforms the resulting tree to a CSS tree. This class also holds the
  29. * evaluation context, such as all available mixins and variables at any given
  30. * time.
  31. *
  32. * The `lessc_parser` class is only concerned with parsing its input.
  33. *
  34. * The `lessc_formatter` takes a CSS tree, and dumps it to a formatted string,
  35. * handling things like indentation.
  36. */
  37. class lessc {
  38. static public $VERSION = "v0.3.7";
  39. static protected $TRUE = array("keyword", "true");
  40. static protected $FALSE = array("keyword", "false");
  41. protected $libFunctions = array();
  42. protected $registeredVars = array();
  43. protected $preserveComments = false;
  44. public $vPrefix = '@'; // prefix of abstract properties
  45. public $mPrefix = '$'; // prefix of abstract blocks
  46. public $parentSelector = '&';
  47. public $importDisabled = false;
  48. public $importDir = '';
  49. protected $numberPrecision = null;
  50. // set to the parser that generated the current line when compiling
  51. // so we know how to create error messages
  52. protected $sourceParser = null;
  53. protected $sourceLoc = null;
  54. static public $defaultValue = array("keyword", "");
  55. // attempts to find the path of an import url, returns null for css files
  56. protected function findImport($url) {
  57. foreach ((array)$this->importDir as $dir) {
  58. $full = $dir.(substr($dir, -1) != '/' ? '/' : '').$url;
  59. if ($this->fileExists($file = $full.'.less') || $this->fileExists($file = $full)) {
  60. return $file;
  61. }
  62. }
  63. return null;
  64. }
  65. protected function fileExists($name) {
  66. return is_file($name);
  67. }
  68. static public function compressList($items, $delim) {
  69. if (!isset($items[1]) && isset($items[0])) return $items[0];
  70. else return array('list', $delim, $items);
  71. }
  72. static public function preg_quote($what) {
  73. return preg_quote($what, '/');
  74. }
  75. // attempt to import $import into $parentBlock
  76. // $props is the property array that will given to $parentBlock at the end
  77. protected function mixImport($import, $parentBlock, &$props) {
  78. list(, $url, $media) = $import;
  79. if (is_array($url)) {
  80. $url = $this->compileValue($this->lib_e($this->reduce($url)));
  81. }
  82. if (empty($media) && substr_compare($url, '.css', -4, 4) !== 0) {
  83. if ($this->importDisabled) {
  84. $props[] = array('raw', '/* import disabled */');
  85. return true;
  86. }
  87. $realPath = $this->findImport($url);
  88. if (!is_null($realPath)) {
  89. $this->addParsedFile($realPath);
  90. $parser = $this->makeParser($realPath);
  91. $root = $parser->parse(file_get_contents($realPath));
  92. $root->parent = $parentBlock;
  93. // handle all the imports in the new file
  94. $pi = pathinfo($realPath);
  95. $this->mixImports($root, $pi['dirname'].'/');
  96. // bring blocks from import into current block
  97. foreach ($root->children as $childName => $child) {
  98. if (isset($parentBlock->children[$childName])) {
  99. $parentBlock->children[$childName] = array_merge(
  100. $parentBlock->children[$childName],
  101. $child);
  102. } else {
  103. $parentBlock->children[$childName] = $child;
  104. }
  105. }
  106. // splice in the props
  107. foreach ($root->props as $prop) {
  108. // leave a reference to the file where it came from
  109. if (isset($prop[-1]) && !is_array($prop[-1])) {
  110. $prop[-1] = array($parser, $prop[-1]);
  111. }
  112. $props[] = $prop;
  113. }
  114. return true;
  115. }
  116. }
  117. // fallback to regular css import
  118. $props[] = array('raw', '@import url("'.$url.'")'.($media ? ' '.$media : '').';');
  119. return false;
  120. }
  121. // import all imports mentioned in the block
  122. protected function mixImports($block, $importDir = null) {
  123. $oldImport = $this->importDir;
  124. if ($importDir !== null) {
  125. $this->importDir = array_merge((array)$importDir, (array)$this->importDir);
  126. }
  127. $props = array();
  128. foreach ($block->props as $prop) {
  129. if ($prop[0] == 'import') {
  130. $this->mixImport($prop, $block, $props);
  131. } else {
  132. $props[] = $prop;
  133. }
  134. }
  135. $block->props = $props;
  136. $this->importDir = $oldImport;
  137. }
  138. /**
  139. * Recursively compiles a block.
  140. *
  141. * A block is analogous to a CSS block in most cases. A single LESS document
  142. * is encapsulated in a block when parsed, but it does not have parent tags
  143. * so all of it's children appear on the root level when compiled.
  144. *
  145. * Blocks are made up of props and children.
  146. *
  147. * Props are property instructions, array tuples which describe an action
  148. * to be taken, eg. write a property, set a variable, mixin a block.
  149. *
  150. * The children of a block are just all the blocks that are defined within.
  151. * This is used to look up mixins when performing a mixin.
  152. *
  153. * Compiling the block involves pushing a fresh environment on the stack,
  154. * and iterating through the props, compiling each one.
  155. *
  156. * See lessc::compileProp()
  157. *
  158. */
  159. protected function compileBlock($block) {
  160. switch ($block->type) {
  161. case "root":
  162. return $this->compileRoot($block);
  163. case null:
  164. return $this->compileCSSBlock($block);
  165. case "media":
  166. return $this->compileMedia($block);
  167. case "directive":
  168. $name = "@" . $block->name;
  169. if (!empty($block->value)) {
  170. $name .= " " . $this->compileValue($this->reduce($block->value));
  171. }
  172. return $this->compileNestedBlock($block, array($name));
  173. default:
  174. $this->throwError("unknown block type: $block->type\n");
  175. }
  176. }
  177. protected function compileCSSBlock($block) {
  178. $env = $this->pushEnv();
  179. $selectors = $this->compileSelectors($block->tags);
  180. $env->selectors = $this->multiplySelectors($selectors);
  181. $out = $this->makeOutputBlock(null, $env->selectors);
  182. $this->scope->children[] = $out;
  183. $this->compileProps($block, $out);
  184. $block->scope = $env; // mixins carry scope with them!
  185. $this->popEnv();
  186. }
  187. protected function compileMedia($media) {
  188. $env = $this->pushEnv($media);
  189. $parentScope = $this->mediaParent($this->scope);
  190. $query = $this->compileMediaQuery($this->multiplyMedia($env));
  191. $this->scope = $this->makeOutputBlock($media->type, array($query));
  192. $parentScope->children[] = $this->scope;
  193. $this->compileProps($media, $this->scope);
  194. if (count($this->scope->lines) > 0) {
  195. $orphanSelelectors = $this->findClosestSelectors();
  196. if (!is_null($orphanSelelectors)) {
  197. $orphan = $this->makeOutputBlock(null, $orphanSelelectors);
  198. $orphan->lines = $this->scope->lines;
  199. array_unshift($this->scope->children, $orphan);
  200. $this->scope->lines = array();
  201. }
  202. }
  203. $this->scope = $this->scope->parent;
  204. $this->popEnv();
  205. }
  206. protected function mediaParent($scope) {
  207. while (!empty($scope->parent)) {
  208. if (!empty($scope->type) && $scope->type != "media") {
  209. break;
  210. }
  211. $scope = $scope->parent;
  212. }
  213. return $scope;
  214. }
  215. protected function compileNestedBlock($block, $selectors) {
  216. $this->pushEnv($block);
  217. $this->scope = $this->makeOutputBlock($block->type, $selectors);
  218. $this->scope->parent->children[] = $this->scope;
  219. $this->compileProps($block, $this->scope);
  220. $this->scope = $this->scope->parent;
  221. $this->popEnv();
  222. }
  223. protected function compileRoot($root) {
  224. $this->pushEnv();
  225. $this->scope = $this->makeOutputBlock($root->type);
  226. $this->compileProps($root, $this->scope);
  227. $this->popEnv();
  228. }
  229. protected function compileProps($block, $out) {
  230. $this->mixImports($block);
  231. foreach ($this->sortProps($block->props) as $prop) {
  232. $this->compileProp($prop, $block, $out);
  233. }
  234. }
  235. protected function sortProps($props) {
  236. $vars = array();
  237. $other = array();
  238. foreach ($props as $prop) {
  239. if ($prop[0] == "assign" &&
  240. substr($prop[1], 0, 1) == $this->vPrefix) {
  241. $vars[] = $prop;
  242. } else {
  243. $other[] = $prop;
  244. }
  245. }
  246. return array_merge($vars, $other);
  247. }
  248. protected function compileMediaQuery($queries) {
  249. $compiledQueries = array();
  250. foreach ($queries as $query) {
  251. $parts = array();
  252. foreach ($query as $q) {
  253. switch ($q[0]) {
  254. case "mediaType":
  255. $parts[] = implode(" ", array_slice($q, 1));
  256. break;
  257. case "mediaExp":
  258. if (isset($q[2])) {
  259. $parts[] = "($q[1]: " .
  260. $this->compileValue($this->reduce($q[2])) . ")";
  261. } else {
  262. $parts[] = "($q[1])";
  263. }
  264. break;
  265. }
  266. }
  267. if (count($parts) > 0) {
  268. $compiledQueries[] = implode(" and ", $parts);
  269. }
  270. }
  271. $out = "@media";
  272. if (!empty($parts)) {
  273. $out .= " " .
  274. implode($this->formatter->selectorSeparator, $compiledQueries);
  275. }
  276. return $out;
  277. }
  278. protected function multiplyMedia($env, $childQueries = null) {
  279. if (is_null($env) ||
  280. !empty($env->block->type) && $env->block->type != "media")
  281. {
  282. return $childQueries;
  283. }
  284. // plain old block, skip
  285. if (empty($env->block->type)) {
  286. return $this->multiplyMedia($env->parent, $childQueries);
  287. }
  288. $out = array();
  289. $queries = $env->block->queries;
  290. if (is_null($childQueries)) {
  291. $out = $queries;
  292. } else {
  293. foreach ($queries as $parent) {
  294. foreach ($childQueries as $child) {
  295. $out[] = array_merge($parent, $child);
  296. }
  297. }
  298. }
  299. return $this->multiplyMedia($env->parent, $out);
  300. }
  301. protected function expandParentSelectors(&$tag, $replace) {
  302. $parts = explode("$&$", $tag);
  303. $count = 0;
  304. foreach ($parts as &$part) {
  305. $part = str_replace($this->parentSelector, $replace, $part, $c);
  306. $count += $c;
  307. }
  308. $tag = implode($this->parentSelector, $parts);
  309. return $count;
  310. }
  311. protected function findClosestSelectors() {
  312. $env = $this->env;
  313. $selectors = null;
  314. while ($env !== null) {
  315. if (isset($env->selectors)) {
  316. $selectors = $env->selectors;
  317. break;
  318. }
  319. $env = $env->parent;
  320. }
  321. return $selectors;
  322. }
  323. // multiply $selectors against the nearest selectors in env
  324. protected function multiplySelectors($selectors) {
  325. // find parent selectors
  326. $parentSelectors = $this->findClosestSelectors();
  327. if (is_null($parentSelectors)) {
  328. // kill parent reference in top level selector
  329. foreach ($selectors as &$s) {
  330. $this->expandParentSelectors($s, "");
  331. }
  332. return $selectors;
  333. }
  334. $out = array();
  335. foreach ($parentSelectors as $parent) {
  336. foreach ($selectors as $child) {
  337. $count = $this->expandParentSelectors($child, $parent);
  338. // don't prepend the parent tag if & was used
  339. if ($count > 0) {
  340. $out[] = trim($child);
  341. } else {
  342. $out[] = trim($parent . ' ' . $child);
  343. }
  344. }
  345. }
  346. return $out;
  347. }
  348. // reduces selector expressions
  349. protected function compileSelectors($selectors) {
  350. $out = array();
  351. foreach ($selectors as $s) {
  352. if (is_array($s)) {
  353. list(, $value) = $s;
  354. $out[] = $this->compileValue($this->reduce($value));
  355. } else {
  356. $out[] = $s;
  357. }
  358. }
  359. return $out;
  360. }
  361. protected function eq($left, $right) {
  362. return $left == $right;
  363. }
  364. protected function patternMatch($block, $callingArgs) {
  365. // match the guards if it has them
  366. // any one of the groups must have all its guards pass for a match
  367. if (!empty($block->guards)) {
  368. $groupPassed = false;
  369. foreach ($block->guards as $guardGroup) {
  370. foreach ($guardGroup as $guard) {
  371. $this->pushEnv();
  372. $this->zipSetArgs($block->args, $callingArgs);
  373. $negate = false;
  374. if ($guard[0] == "negate") {
  375. $guard = $guard[1];
  376. $negate = true;
  377. }
  378. $passed = $this->reduce($guard) == self::$TRUE;
  379. if ($negate) $passed = !$passed;
  380. $this->popEnv();
  381. if ($passed) {
  382. $groupPassed = true;
  383. } else {
  384. $groupPassed = false;
  385. break;
  386. }
  387. }
  388. if ($groupPassed) break;
  389. }
  390. if (!$groupPassed) {
  391. return false;
  392. }
  393. }
  394. $numCalling = count($callingArgs);
  395. if (empty($block->args)) {
  396. return $block->isVararg || $numCalling == 0;
  397. }
  398. $i = -1; // no args
  399. // try to match by arity or by argument literal
  400. foreach ($block->args as $i => $arg) {
  401. switch ($arg[0]) {
  402. case "lit":
  403. if (empty($callingArgs[$i]) || !$this->eq($arg[1], $callingArgs[$i])) {
  404. return false;
  405. }
  406. break;
  407. case "arg":
  408. // no arg and no default value
  409. if (!isset($callingArgs[$i]) && !isset($arg[2])) {
  410. return false;
  411. }
  412. break;
  413. case "rest":
  414. $i--; // rest can be empty
  415. break 2;
  416. }
  417. }
  418. if ($block->isVararg) {
  419. return true; // not having enough is handled above
  420. } else {
  421. $numMatched = $i + 1;
  422. // greater than becuase default values always match
  423. return $numMatched >= $numCalling;
  424. }
  425. }
  426. protected function patternMatchAll($blocks, $callingArgs) {
  427. $matches = null;
  428. foreach ($blocks as $block) {
  429. if ($this->patternMatch($block, $callingArgs)) {
  430. $matches[] = $block;
  431. }
  432. }
  433. return $matches;
  434. }
  435. // attempt to find blocks matched by path and args
  436. protected function findBlocks($searchIn, $path, $args, $seen=array()) {
  437. if ($searchIn == null) return null;
  438. if (isset($seen[$searchIn->id])) return null;
  439. $seen[$searchIn->id] = true;
  440. $name = $path[0];
  441. if (isset($searchIn->children[$name])) {
  442. $blocks = $searchIn->children[$name];
  443. if (count($path) == 1) {
  444. $matches = $this->patternMatchAll($blocks, $args);
  445. if (!empty($matches)) {
  446. // This will return all blocks that match in the closest
  447. // scope that has any matching block, like lessjs
  448. return $matches;
  449. }
  450. } else {
  451. $matches = array();
  452. foreach ($blocks as $subBlock) {
  453. $subMatches = $this->findBlocks($subBlock,
  454. array_slice($path, 1), $args, $seen);
  455. if (!is_null($subMatches)) {
  456. foreach ($subMatches as $sm) {
  457. $matches[] = $sm;
  458. }
  459. }
  460. }
  461. return count($matches) > 0 ? $matches : null;
  462. }
  463. }
  464. if ($searchIn->parent === $searchIn) return null;
  465. return $this->findBlocks($searchIn->parent, $path, $args, $seen);
  466. }
  467. // sets all argument names in $args to either the default value
  468. // or the one passed in through $values
  469. protected function zipSetArgs($args, $values) {
  470. $i = 0;
  471. $assignedValues = array();
  472. foreach ($args as $a) {
  473. if ($a[0] == "arg") {
  474. if ($i < count($values) && !is_null($values[$i])) {
  475. $value = $values[$i];
  476. } elseif (isset($a[2])) {
  477. $value = $a[2];
  478. } else $value = null;
  479. $value = $this->reduce($value);
  480. $this->set($a[1], $value);
  481. $assignedValues[] = $value;
  482. }
  483. $i++;
  484. }
  485. // check for a rest
  486. $last = end($args);
  487. if ($last[0] == "rest") {
  488. $rest = array_slice($values, count($args) - 1);
  489. $this->set($last[1], $this->reduce(array("list", " ", $rest)));
  490. }
  491. $this->env->arguments = $assignedValues;
  492. }
  493. // compile a prop and update $lines or $blocks appropriately
  494. protected function compileProp($prop, $block, $out) {
  495. // set error position context
  496. if (isset($prop[-1])) {
  497. if (is_array($prop[-1])) {
  498. list($parser, $count) = $prop[-1];
  499. $this->sourceParser = $parser;
  500. $this->sourceLoc = $count;
  501. } else {
  502. $this->sourceParser = $this->parser;
  503. $this->sourceLoc = $prop[-1];
  504. }
  505. } else {
  506. $this->sourceLoc = -1;
  507. }
  508. switch ($prop[0]) {
  509. case 'assign':
  510. list(, $name, $value) = $prop;
  511. if ($name[0] == $this->vPrefix) {
  512. $this->set($name, $value);
  513. } else {
  514. $out->lines[] = $this->formatter->property($name,
  515. $this->compileValue($this->reduce($value)));
  516. }
  517. break;
  518. case 'block':
  519. list(, $child) = $prop;
  520. $this->compileBlock($child);
  521. break;
  522. case 'mixin':
  523. list(, $path, $args, $suffix) = $prop;
  524. $args = array_map(array($this, "reduce"), (array)$args);
  525. $mixins = $this->findBlocks($block, $path, $args);
  526. if ($mixins === null) {
  527. // echo "failed to find block: ".implode(" > ", $path)."\n";
  528. break; // throw error here??
  529. }
  530. foreach ($mixins as $mixin) {
  531. $haveScope = false;
  532. if (isset($mixin->parent->scope)) {
  533. $haveScope = true;
  534. $mixinParentEnv = $this->pushEnv();
  535. $mixinParentEnv->storeParent = $mixin->parent->scope;
  536. }
  537. $haveArgs = false;
  538. if (isset($mixin->args)) {
  539. $haveArgs = true;
  540. $this->pushEnv();
  541. $this->zipSetArgs($mixin->args, $args);
  542. }
  543. $oldParent = $mixin->parent;
  544. if ($mixin != $block) $mixin->parent = $block;
  545. $this->mixImports($mixin);
  546. foreach ($this->sortProps($mixin->props) as $subProp) {
  547. if ($suffix !== null &&
  548. $subProp[0] == "assign" &&
  549. is_string($subProp[1]) &&
  550. $subProp[1]{0} != $this->vPrefix)
  551. {
  552. $subProp[2] = array(
  553. 'list', ' ',
  554. array($subProp[2], array('keyword', $suffix))
  555. );
  556. }
  557. $this->compileProp($subProp, $mixin, $out);
  558. }
  559. $mixin->parent = $oldParent;
  560. if ($haveArgs) $this->popEnv();
  561. if ($haveScope) $this->popEnv();
  562. }
  563. break;
  564. case 'raw':
  565. $out->lines[] = $prop[1];
  566. break;
  567. case "directive":
  568. list(, $name, $value) = $prop;
  569. $out->lines[] = "@$name " . $this->compileValue($this->reduce($value)).';';
  570. break;
  571. case "comment":
  572. $out->lines[] = $prop[1];
  573. break;
  574. default:
  575. $this->throwError("unknown op: {$prop[0]}\n");
  576. }
  577. }
  578. /**
  579. * Compiles a primitive value into a CSS property value.
  580. *
  581. * Values in lessphp are typed by being wrapped in arrays, their format is
  582. * typically:
  583. *
  584. * array(type, contents [, additional_contents]*)
  585. *
  586. * The input is expected to be reduced. This function will not work on
  587. * things like expressions and variables.
  588. */
  589. protected function compileValue($value) {
  590. switch ($value[0]) {
  591. case 'list':
  592. // [1] - delimiter
  593. // [2] - array of values
  594. return implode($value[1], array_map(array($this, 'compileValue'), $value[2]));
  595. case 'raw_color';
  596. case 'keyword':
  597. // [1] - the keyword
  598. return $value[1];
  599. case 'number':
  600. list(, $num, $unit) = $value;
  601. // [1] - the number
  602. // [2] - the unit
  603. if ($this->numberPrecision !== null) {
  604. $num = round($num, $this->numberPrecision);
  605. }
  606. return $num . $unit;
  607. case 'string':
  608. // [1] - contents of string (includes quotes)
  609. list(, $delim, $content) = $value;
  610. foreach ($content as &$part) {
  611. if (is_array($part)) {
  612. $part = $this->compileValue($part);
  613. }
  614. }
  615. return $delim . implode($content) . $delim;
  616. case 'color':
  617. // [1] - red component (either number or a %)
  618. // [2] - green component
  619. // [3] - blue component
  620. // [4] - optional alpha component
  621. list(, $r, $g, $b) = $value;
  622. $r = round($r);
  623. $g = round($g);
  624. $b = round($b);
  625. if (count($value) == 5 && $value[4] != 1) { // rgba
  626. return 'rgba('.$r.','.$g.','.$b.','.$value[4].')';
  627. }
  628. $h = sprintf("#%02x%02x%02x", $r, $g, $b);
  629. if (!empty($this->formatter->compressColors)) {
  630. // Converting hex color to short notation (e.g. #003399 to #039)
  631. if ($h[1] === $h[2] && $h[3] === $h[4] && $h[5] === $h[6]) {
  632. $h = '#' . $h[1] . $h[3] . $h[5];
  633. }
  634. }
  635. return $h;
  636. case 'function':
  637. list(, $name, $args) = $value;
  638. return $name.'('.$this->compileValue($args).')';
  639. default: // assumed to be unit
  640. $this->throwError("unknown value type: $value[0]");
  641. }
  642. }
  643. protected function lib_isnumber($value) {
  644. return $this->toBool($value[0] == "number");
  645. }
  646. protected function lib_isstring($value) {
  647. return $this->toBool($value[0] == "string");
  648. }
  649. protected function lib_iscolor($value) {
  650. return $this->toBool($this->coerceColor($value));
  651. }
  652. protected function lib_iskeyword($value) {
  653. return $this->toBool($value[0] == "keyword");
  654. }
  655. protected function lib_ispixel($value) {
  656. return $this->toBool($value[0] == "number" && $value[2] == "px");
  657. }
  658. protected function lib_ispercentage($value) {
  659. return $this->toBool($value[0] == "number" && $value[2] == "%");
  660. }
  661. protected function lib_isem($value) {
  662. return $this->toBool($value[0] == "number" && $value[2] == "em");
  663. }
  664. protected function lib_rgbahex($color) {
  665. $color = $this->coerceColor($color);
  666. if (is_null($color))
  667. $this->throwError("color expected for rgbahex");
  668. return sprintf("#%02x%02x%02x%02x",
  669. isset($color[4]) ? $color[4]*255 : 0,
  670. $color[1],$color[2], $color[3]);
  671. }
  672. protected function lib_argb($color){
  673. return $this->lib_rgbahex($color);
  674. }
  675. // utility func to unquote a string
  676. protected function lib_e($arg) {
  677. switch ($arg[0]) {
  678. case "list":
  679. $items = $arg[2];
  680. if (isset($items[0])) {
  681. return $this->lib_e($items[0]);
  682. }
  683. return self::$defaultValue;
  684. case "string":
  685. $arg[1] = "";
  686. return $arg;
  687. case "keyword":
  688. return $arg;
  689. default:
  690. return array("keyword", $this->compileValue($arg));
  691. }
  692. }
  693. protected function lib__sprintf($args) {
  694. if ($args[0] != "list") return $args;
  695. $values = $args[2];
  696. $string = array_shift($values);
  697. $template = $this->compileValue($this->lib_e($string));
  698. $i = 0;
  699. if (preg_match_all('/%[dsa]/', $template, $m)) {
  700. foreach ($m[0] as $match) {
  701. $val = isset($values[$i]) ?
  702. $this->reduce($values[$i]) : array('keyword', '');
  703. // lessjs compat, renders fully expanded color, not raw color
  704. if ($color = $this->coerceColor($val)) {
  705. $val = $color;
  706. }
  707. $i++;
  708. $rep = $this->compileValue($this->lib_e($val));
  709. $template = preg_replace('/'.self::preg_quote($match).'/',
  710. $rep, $template, 1);
  711. }
  712. }
  713. $d = $string[0] == "string" ? $string[1] : '"';
  714. return array("string", $d, array($template));
  715. }
  716. protected function lib_floor($arg) {
  717. $value = $this->assertNumber($arg);
  718. return array("number", floor($value), $arg[2]);
  719. }
  720. protected function lib_ceil($arg) {
  721. $value = $this->assertNumber($arg);
  722. return array("number", ceil($value), $arg[2]);
  723. }
  724. protected function lib_round($arg) {
  725. $value = $this->assertNumber($arg);
  726. return array("number", round($value), $arg[2]);
  727. }
  728. /**
  729. * Helper function to get arguments for color manipulation functions.
  730. * takes a list that contains a color like thing and a percentage
  731. */
  732. protected function colorArgs($args) {
  733. if ($args[0] != 'list' || count($args[2]) < 2) {
  734. return array(array('color', 0, 0, 0), 0);
  735. }
  736. list($color, $delta) = $args[2];
  737. $color = $this->assertColor($color);
  738. $delta = floatval($delta[1]);
  739. return array($color, $delta);
  740. }
  741. protected function lib_darken($args) {
  742. list($color, $delta) = $this->colorArgs($args);
  743. $hsl = $this->toHSL($color);
  744. $hsl[3] = $this->clamp($hsl[3] - $delta, 100);
  745. return $this->toRGB($hsl);
  746. }
  747. protected function lib_lighten($args) {
  748. list($color, $delta) = $this->colorArgs($args);
  749. $hsl = $this->toHSL($color);
  750. $hsl[3] = $this->clamp($hsl[3] + $delta, 100);
  751. return $this->toRGB($hsl);
  752. }
  753. protected function lib_saturate($args) {
  754. list($color, $delta) = $this->colorArgs($args);
  755. $hsl = $this->toHSL($color);
  756. $hsl[2] = $this->clamp($hsl[2] + $delta, 100);
  757. return $this->toRGB($hsl);
  758. }
  759. protected function lib_desaturate($args) {
  760. list($color, $delta) = $this->colorArgs($args);
  761. $hsl = $this->toHSL($color);
  762. $hsl[2] = $this->clamp($hsl[2] - $delta, 100);
  763. return $this->toRGB($hsl);
  764. }
  765. protected function lib_spin($args) {
  766. list($color, $delta) = $this->colorArgs($args);
  767. $hsl = $this->toHSL($color);
  768. $hsl[1] = $hsl[1] + $delta % 360;
  769. if ($hsl[1] < 0) $hsl[1] += 360;
  770. return $this->toRGB($hsl);
  771. }
  772. protected function lib_fadeout($args) {
  773. list($color, $delta) = $this->colorArgs($args);
  774. $color[4] = $this->clamp((isset($color[4]) ? $color[4] : 1) - $delta/100);
  775. return $color;
  776. }
  777. protected function lib_fadein($args) {
  778. list($color, $delta) = $this->colorArgs($args);
  779. $color[4] = $this->clamp((isset($color[4]) ? $color[4] : 1) + $delta/100);
  780. return $color;
  781. }
  782. protected function lib_hue($color) {
  783. $hsl = $this->toHSL($this->assertColor($color));
  784. return round($hsl[1]);
  785. }
  786. protected function lib_saturation($color) {
  787. $hsl = $this->toHSL($this->assertColor($color));
  788. return round($hsl[2]);
  789. }
  790. protected function lib_lightness($color) {
  791. $hsl = $this->toHSL($this->assertColor($color));
  792. return round($hsl[3]);
  793. }
  794. // get the alpha of a color
  795. // defaults to 1 for non-colors or colors without an alpha
  796. protected function lib_alpha($value) {
  797. if (!is_null($color = $this->coerceColor($value))) {
  798. return isset($color[4]) ? $color[4] : 1;
  799. }
  800. }
  801. // set the alpha of the color
  802. protected function lib_fade($args) {
  803. list($color, $alpha) = $this->colorArgs($args);
  804. $color[4] = $this->clamp($alpha / 100.0);
  805. return $color;
  806. }
  807. protected function lib_percentage($arg) {
  808. $num = $this->assertNumber($arg);
  809. return array("number", $num*100, "%");
  810. }
  811. // mixes two colors by weight
  812. // mix(@color1, @color2, @weight);
  813. // http://sass-lang.com/docs/yardoc/Sass/Script/Functions.html#mix-instance_method
  814. protected function lib_mix($args) {
  815. if ($args[0] != "list" || count($args[2]) < 3)
  816. $this->throwError("mix expects (color1, color2, weight)");
  817. list($first, $second, $weight) = $args[2];
  818. $first = $this->assertColor($first);
  819. $second = $this->assertColor($second);
  820. $first_a = $this->lib_alpha($first);
  821. $second_a = $this->lib_alpha($second);
  822. $weight = $weight[1] / 100.0;
  823. $w = $weight * 2 - 1;
  824. $a = $first_a - $second_a;
  825. $w1 = (($w * $a == -1 ? $w : ($w + $a)/(1 + $w * $a)) + 1) / 2.0;
  826. $w2 = 1.0 - $w1;
  827. $new = array('color',
  828. $w1 * $first[1] + $w2 * $second[1],
  829. $w1 * $first[2] + $w2 * $second[2],
  830. $w1 * $first[3] + $w2 * $second[3],
  831. );
  832. if ($first_a != 1.0 || $second_a != 1.0) {
  833. $new[] = $first_a * $weight + $second_a * ($weight - 1);
  834. }
  835. return $this->fixColor($new);
  836. }
  837. protected function assertColor($value, $error = "expected color value") {
  838. $color = $this->coerceColor($value);
  839. if (is_null($color)) $this->throwError($error);
  840. return $color;
  841. }
  842. protected function assertNumber($value, $error = "expecting number") {
  843. if ($value[0] == "number") return $value[1];
  844. $this->throwError($error);
  845. }
  846. protected function toHSL($color) {
  847. if ($color[0] == 'hsl') return $color;
  848. $r = $color[1] / 255;
  849. $g = $color[2] / 255;
  850. $b = $color[3] / 255;
  851. $min = min($r, $g, $b);
  852. $max = max($r, $g, $b);
  853. $L = ($min + $max) / 2;
  854. if ($min == $max) {
  855. $S = $H = 0;
  856. } else {
  857. if ($L < 0.5)
  858. $S = ($max - $min)/($max + $min);
  859. else
  860. $S = ($max - $min)/(2.0 - $max - $min);
  861. if ($r == $max) $H = ($g - $b)/($max - $min);
  862. elseif ($g == $max) $H = 2.0 + ($b - $r)/($max - $min);
  863. elseif ($b == $max) $H = 4.0 + ($r - $g)/($max - $min);
  864. }
  865. $out = array('hsl',
  866. ($H < 0 ? $H + 6 : $H)*60,
  867. $S*100,
  868. $L*100,
  869. );
  870. if (count($color) > 4) $out[] = $color[4]; // copy alpha
  871. return $out;
  872. }
  873. protected function toRGB_helper($comp, $temp1, $temp2) {
  874. if ($comp < 0) $comp += 1.0;
  875. elseif ($comp > 1) $comp -= 1.0;
  876. if (6 * $comp < 1) return $temp1 + ($temp2 - $temp1) * 6 * $comp;
  877. if (2 * $comp < 1) return $temp2;
  878. if (3 * $comp < 2) return $temp1 + ($temp2 - $temp1)*((2/3) - $comp) * 6;
  879. return $temp1;
  880. }
  881. /**
  882. * Converts a hsl array into a color value in rgb.
  883. * Expects H to be in range of 0 to 360, S and L in 0 to 100
  884. */
  885. protected function toRGB($color) {
  886. if ($color == 'color') return $color;
  887. $H = $color[1] / 360;
  888. $S = $color[2] / 100;
  889. $L = $color[3] / 100;
  890. if ($S == 0) {
  891. $r = $g = $b = $L;
  892. } else {
  893. $temp2 = $L < 0.5 ?
  894. $L*(1.0 + $S) :
  895. $L + $S - $L * $S;
  896. $temp1 = 2.0 * $L - $temp2;
  897. $r = $this->toRGB_helper($H + 1/3, $temp1, $temp2);
  898. $g = $this->toRGB_helper($H, $temp1, $temp2);
  899. $b = $this->toRGB_helper($H - 1/3, $temp1, $temp2);
  900. }
  901. // $out = array('color', round($r*255), round($g*255), round($b*255));
  902. $out = array('color', $r*255, $g*255, $b*255);
  903. if (count($color) > 4) $out[] = $color[4]; // copy alpha
  904. return $out;
  905. }
  906. protected function clamp($v, $max = 1, $min = 0) {
  907. return min($max, max($min, $v));
  908. }
  909. /**
  910. * Convert the rgb, rgba, hsl color literals of function type
  911. * as returned by the parser into values of color type.
  912. */
  913. protected function funcToColor($func) {
  914. $fname = $func[1];
  915. if ($func[2][0] != 'list') return false; // need a list of arguments
  916. $rawComponents = $func[2][2];
  917. if ($fname == 'hsl' || $fname == 'hsla') {
  918. $hsl = array('hsl');
  919. $i = 0;
  920. foreach ($rawComponents as $c) {
  921. $val = $this->reduce($c);
  922. $val = isset($val[1]) ? floatval($val[1]) : 0;
  923. if ($i == 0) $clamp = 360;
  924. elseif ($i < 3) $clamp = 100;
  925. else $clamp = 1;
  926. $hsl[] = $this->clamp($val, $clamp);
  927. $i++;
  928. }
  929. while (count($hsl) < 4) $hsl[] = 0;
  930. return $this->toRGB($hsl);
  931. } elseif ($fname == 'rgb' || $fname == 'rgba') {
  932. $components = array();
  933. $i = 1;
  934. foreach ($rawComponents as $c) {
  935. $c = $this->reduce($c);
  936. if ($i < 4) {
  937. if ($c[0] == "number" && $c[2] == "%") {
  938. $components[] = 255 * ($c[1] / 100);
  939. } else {
  940. $components[] = floatval($c[1]);
  941. }
  942. } elseif ($i == 4) {
  943. if ($c[0] == "number" && $c[2] == "%") {
  944. $components[] = 1.0 * ($c[1] / 100);
  945. } else {
  946. $components[] = floatval($c[1]);
  947. }
  948. } else break;
  949. $i++;
  950. }
  951. while (count($components) < 3) $components[] = 0;
  952. array_unshift($components, 'color');
  953. return $this->fixColor($components);
  954. }
  955. return false;
  956. }
  957. protected function reduce($value) {
  958. switch ($value[0]) {
  959. case "variable":
  960. $key = $value[1];
  961. if (is_array($key)) {
  962. $key = $this->reduce($key);
  963. $key = $this->vPrefix . $this->compileValue($this->lib_e($key));
  964. }
  965. $seen =& $this->env->seenNames;
  966. if (!empty($seen[$key])) {
  967. $this->throwError("infinite loop detected: $key");
  968. }
  969. $seen[$key] = true;
  970. $out = $this->reduce($this->get($key, self::$defaultValue));
  971. $seen[$key] = false;
  972. return $out;
  973. case "list":
  974. foreach ($value[2] as &$item) {
  975. $item = $this->reduce($item);
  976. }
  977. return $value;
  978. case "expression":
  979. return $this->evaluate($value);
  980. case "string":
  981. foreach ($value[2] as &$part) {
  982. if (is_array($part)) {
  983. $strip = $part[0] == "variable";
  984. $part = $this->reduce($part);
  985. if ($strip) $part = $this->lib_e($part);
  986. }
  987. }
  988. return $value;
  989. case "escape":
  990. list(,$inner) = $value;
  991. return $this->lib_e($this->reduce($inner));
  992. case "function":
  993. $color = $this->funcToColor($value);
  994. if ($color) return $color;
  995. list(, $name, $args) = $value;
  996. if ($name == "%") $name = "_sprintf";
  997. $f = isset($this->libFunctions[$name]) ?
  998. $this->libFunctions[$name] : array($this, 'lib_'.$name);
  999. if (is_callable($f)) {
  1000. if ($args[0] == 'list')
  1001. $args = self::compressList($args[2], $args[1]);
  1002. $ret = call_user_func($f, $this->reduce($args), $this);
  1003. if (is_null($ret)) {
  1004. return array("string", "", array(
  1005. $name, "(", $args, ")"
  1006. ));
  1007. }
  1008. // convert to a typed value if the result is a php primitive
  1009. if (is_numeric($ret)) $ret = array('number', $ret, "");
  1010. elseif (!is_array($ret)) $ret = array('keyword', $ret);
  1011. return $ret;
  1012. }
  1013. // plain function, reduce args
  1014. $value[2] = $this->reduce($value[2]);
  1015. return $value;
  1016. case "unary":
  1017. list(, $op, $exp) = $value;
  1018. $exp = $this->reduce($exp);
  1019. if ($exp[0] == "number") {
  1020. switch ($op) {
  1021. case "+":
  1022. return $exp;
  1023. case "-":
  1024. $exp[1] *= -1;
  1025. return $exp;
  1026. }
  1027. }
  1028. return array("string", "", array($op, $exp));
  1029. default:
  1030. return $value;
  1031. }
  1032. }
  1033. // coerce a value for use in color operation
  1034. protected function coerceColor($value) {
  1035. switch($value[0]) {
  1036. case 'color': return $value;
  1037. case 'raw_color':
  1038. $c = array("color", 0, 0, 0);
  1039. $colorStr = substr($value[1], 1);
  1040. $num = hexdec($colorStr);
  1041. $width = strlen($colorStr) == 3 ? 16 : 256;
  1042. for ($i = 3; $i > 0; $i--) { // 3 2 1
  1043. $t = $num % $width;
  1044. $num /= $width;
  1045. $c[$i] = $t * (256/$width) + $t * floor(16/$width);
  1046. }
  1047. return $c;
  1048. case 'keyword':
  1049. $name = $value[1];
  1050. if (isset(self::$cssColors[$name])) {
  1051. list($r, $g, $b) = explode(',', self::$cssColors[$name]);
  1052. return array('color', $r, $g, $b);
  1053. }
  1054. return null;
  1055. }
  1056. }
  1057. // make something string like into a string
  1058. protected function coerceString($value) {
  1059. switch ($value[0]) {
  1060. case "string":
  1061. return $value;
  1062. case "keyword":
  1063. return array("string", "", array($value[1]));
  1064. }
  1065. return null;
  1066. }
  1067. protected function toBool($a) {
  1068. if ($a) return self::$TRUE;
  1069. else return self::$FALSE;
  1070. }
  1071. // evaluate an expression
  1072. protected function evaluate($exp) {
  1073. list(, $op, $left, $right, $whiteBefore, $whiteAfter) = $exp;
  1074. $left = $this->reduce($left);
  1075. $right = $this->reduce($right);
  1076. if ($leftColor = $this->coerceColor($left)) {
  1077. $left = $leftColor;
  1078. }
  1079. if ($rightColor = $this->coerceColor($right)) {
  1080. $right = $rightColor;
  1081. }
  1082. $ltype = $left[0];
  1083. $rtype = $right[0];
  1084. // operators that work on all types
  1085. if ($op == "and") {
  1086. return $this->toBool($left == self::$TRUE && $right == self::$TRUE);
  1087. }
  1088. if ($op == "=") {
  1089. return $this->toBool($this->eq($left, $right) );
  1090. }
  1091. if ($op == "+" && !is_null($str = $this->stringConcatenate($left, $right))) {
  1092. return $str;
  1093. }
  1094. // type based operators
  1095. $fname = "op_${ltype}_${rtype}";
  1096. if (is_callable(array($this, $fname))) {
  1097. $out = $this->$fname($op, $left, $right);
  1098. if (!is_null($out)) return $out;
  1099. }
  1100. // make the expression look it did before being parsed
  1101. $paddedOp = $op;
  1102. if ($whiteBefore) $paddedOp = " " . $paddedOp;
  1103. if ($whiteAfter) $paddedOp .= " ";
  1104. return array("string", "", array($left, $paddedOp, $right));
  1105. }
  1106. protected function stringConcatenate($left, $right) {
  1107. if ($strLeft = $this->coerceString($left)) {
  1108. if ($right[0] == "string") {
  1109. $right[1] = "";
  1110. }
  1111. $strLeft[2][] = $right;
  1112. return $strLeft;
  1113. }
  1114. if ($strRight = $this->coerceString($right)) {
  1115. array_unshift($strRight[2], $left);
  1116. return $strRight;
  1117. }
  1118. }
  1119. // make sure a color's components don't go out of bounds
  1120. protected function fixColor($c) {
  1121. foreach (range(1, 3) as $i) {
  1122. if ($c[$i] < 0) $c[$i] = 0;
  1123. if ($c[$i] > 255) $c[$i] = 255;
  1124. }
  1125. return $c;
  1126. }
  1127. protected function op_number_color($op, $lft, $rgt) {
  1128. if ($op == '+' || $op == '*') {
  1129. return $this->op_color_number($op, $rgt, $lft);
  1130. }
  1131. }
  1132. protected function op_color_number($op, $lft, $rgt) {
  1133. if ($rgt[0] == '%') $rgt[1] /= 100;
  1134. return $this->op_color_color($op, $lft,
  1135. array_fill(1, count($lft) - 1, $rgt[1]));
  1136. }
  1137. protected function op_color_color($op, $left, $right) {
  1138. $out = array('color');
  1139. $max = count($left) > count($right) ? count($left) : count($right);
  1140. foreach (range(1, $max - 1) as $i) {
  1141. $lval = isset($left[$i]) ? $left[$i] : 0;
  1142. $rval = isset($right[$i]) ? $right[$i] : 0;
  1143. switch ($op) {
  1144. case '+':
  1145. $out[] = $lval + $rval;
  1146. break;
  1147. case '-':
  1148. $out[] = $lval - $rval;
  1149. break;
  1150. case '*':
  1151. $out[] = $lval * $rval;
  1152. break;
  1153. case '%':
  1154. $out[] = $lval % $rval;
  1155. break;
  1156. case '/':
  1157. if ($rval == 0) $this->throwError("evaluate error: can't divide by zero");
  1158. $out[] = $lval / $rval;
  1159. break;
  1160. default:
  1161. $this->throwError('evaluate error: color op number failed on op '.$op);
  1162. }
  1163. }
  1164. return $this->fixColor($out);
  1165. }
  1166. // operator on two numbers
  1167. protected function op_number_number($op, $left, $right) {
  1168. $unit = empty($left[2]) ? $right[2] : $left[2];
  1169. $value = 0;
  1170. switch ($op) {
  1171. case '+':
  1172. $value = $left[1] + $right[1];
  1173. break;
  1174. case '*':
  1175. $value = $left[1] * $right[1];
  1176. break;
  1177. case '-':
  1178. $value = $left[1] - $right[1];
  1179. break;
  1180. case '%':
  1181. $value = $left[1] % $right[1];
  1182. break;
  1183. case '/':
  1184. if ($right[1] == 0) $this->throwError('parse error: divide by zero');
  1185. $value = $left[1] / $right[1];
  1186. break;
  1187. case '<':
  1188. return $this->toBool($left[1] < $right[1]);
  1189. case '>':
  1190. return $this->toBool($left[1] > $right[1]);
  1191. case '>=':
  1192. return $this->toBool($left[1] >= $right[1]);
  1193. case '=<':
  1194. return $this->toBool($left[1] <= $right[1]);
  1195. default:
  1196. $this->throwError('parse error: unknown number operator: '.$op);
  1197. }
  1198. return array("number", $value, $unit);
  1199. }
  1200. /* environment functions */
  1201. protected function makeOutputBlock($type, $selectors = null) {
  1202. $b = new stdclass;
  1203. $b->lines = array();
  1204. $b->children = array();
  1205. $b->selectors = $selectors;
  1206. $b->type = $type;
  1207. $b->parent = $this->scope;
  1208. return $b;
  1209. }
  1210. // the state of execution
  1211. protected function pushEnv($block = null) {
  1212. $e = new stdclass;
  1213. $e->parent = $this->env;
  1214. $e->store = array();
  1215. $e->block = $block;
  1216. $this->env = $e;
  1217. return $e;
  1218. }
  1219. // pop something off the stack
  1220. protected function popEnv() {
  1221. $old = $this->env;
  1222. $this->env = $this->env->parent;
  1223. return $old;
  1224. }
  1225. // set something in the current env
  1226. protected function set($name, $value) {
  1227. $this->env->store[$name] = $value;
  1228. }
  1229. // get the highest occurrence entry for a name
  1230. protected function get($name, $default=null) {
  1231. $current = $this->env;
  1232. $isArguments = $name == $this->vPrefix . 'arguments';
  1233. while ($current) {
  1234. if ($isArguments && isset($current->arguments)) {
  1235. return array('list', ' ', $current->arguments);
  1236. }
  1237. if (isset($current->store[$name]))
  1238. return $current->store[$name];
  1239. else {
  1240. $current = isset($current->storeParent) ?
  1241. $current->storeParent : $current->parent;
  1242. }
  1243. }
  1244. return $default;
  1245. }
  1246. // inject array of unparsed strings into environment as variables
  1247. protected function injectVariables($args) {
  1248. $this->pushEnv();
  1249. $parser = new lessc_parser($this, __METHOD__);
  1250. foreach ($args as $name => $strValue) {
  1251. if ($name{0} != '@') $name = '@'.$name;
  1252. $parser->count = 0;
  1253. $parser->buffer = (string)$strValue;
  1254. if (!$parser->propertyValue($value)) {
  1255. throw new Exception("failed to parse passed in variable $name: $strValue");
  1256. }
  1257. $this->set($name, $value);
  1258. }
  1259. }
  1260. /**
  1261. * Initialize any static state, can initialize parser for a file
  1262. * $opts isn't used yet
  1263. */
  1264. public function __construct($fname = null) {
  1265. if ($fname !== null) {
  1266. // used for deprecated parse method
  1267. $this->_parseFile = $fname;
  1268. }
  1269. }
  1270. public function compile($string, $name = null) {
  1271. $locale = setlocale(LC_NUMERIC, 0);
  1272. setlocale(LC_NUMERIC, "C");
  1273. $this->parser = $this->makeParser($name);
  1274. $root = $this->parser->parse($string);
  1275. $this->env = null;
  1276. $this->scope = null;
  1277. $this->formatter = $this->newFormatter();
  1278. if (!empty($this->registeredVars)) {
  1279. $this->injectVariables($this->registeredVars);
  1280. }
  1281. $this->compileBlock($root);
  1282. ob_start();
  1283. $this->formatter->block($this->scope);
  1284. $out = ob_get_clean();
  1285. setlocale(LC_NUMERIC, $locale);
  1286. return $out;
  1287. }
  1288. public function compileFile($fname, $outFname = null) {
  1289. if (!is_readable($fname)) {
  1290. throw new Exception('load error: failed to find '.$fname);
  1291. }
  1292. $pi = pathinfo($fname);
  1293. $oldImport = $this->importDir;
  1294. $this->importDir = (array)$this->importDir;
  1295. $this->importDir[] = $pi['dirname'].'/';
  1296. $this->allParsedFiles = array();
  1297. $this->addParsedFile($fname);
  1298. $out = $this->compile(file_get_contents($fname), $fname);
  1299. $this->importDir = $oldImport;
  1300. if ($outFname !== null) {
  1301. return file_put_contents($outFname, $out);
  1302. }
  1303. return $out;
  1304. }
  1305. // compile only if changed input has changed or output doesn't exist
  1306. public function checkedCompile($in, $out) {
  1307. if (!is_file($out) || filemtime($in) > filemtime($out)) {
  1308. $this->compileFile($in, $out);
  1309. return true;
  1310. }
  1311. return false;
  1312. }
  1313. /**
  1314. * Execute lessphp on a .less file or a lessphp cache structure
  1315. *
  1316. * The lessphp cache structure contains information about a specific
  1317. * less file having been parsed. It can be used as a hint for future
  1318. * calls to determine whether or not a rebuild is required.
  1319. *
  1320. * The cache structure contains two important keys that may be used
  1321. * externally:
  1322. *
  1323. * compiled: The final compiled CSS
  1324. * updated: The time (in seconds) the CSS was last compiled
  1325. *
  1326. * The cache structure is a plain-ol' PHP associative array and can
  1327. * be serialized and unserialized without a hitch.
  1328. *
  1329. * @param mixed $in Input
  1330. * @param bool $force Force rebuild?
  1331. * @return array lessphp cache structure
  1332. */
  1333. public function cachedCompile($in, $force = false) {
  1334. // assume no root
  1335. $root = null;
  1336. if (is_string($in)) {
  1337. $root = $in;
  1338. } elseif (is_array($in) and isset($in['root'])) {
  1339. if ($force or ! isset($in['files'])) {
  1340. // If we are forcing a recompile or if for some reason the
  1341. // structure does not contain any file information we should
  1342. // specify the root to trigger a rebuild.
  1343. $root = $in['root'];
  1344. } elseif (isset($in['files']) and is_array($in['files'])) {
  1345. foreach ($in['files'] as $fname => $ftime ) {
  1346. if (!file_exists($fname) or filemtime($fname) > $ftime) {
  1347. // One of the files we knew about previously has changed
  1348. // so we should look at our incoming root again.
  1349. $root = $in['root'];
  1350. break;
  1351. }
  1352. }
  1353. }
  1354. } else {
  1355. // TODO: Throw an exception? We got neither a string nor something
  1356. // that looks like a compatible lessphp cache structure.
  1357. return null;
  1358. }
  1359. if ($root !== null) {
  1360. // If we have a root value which means we should rebuild.
  1361. $out = array();
  1362. $out['root'] = $root;
  1363. $out['compiled'] = $this->compileFile($root);
  1364. $out['files'] = $this->allParsedFiles();
  1365. $out['updated'] = time();
  1366. return $out;
  1367. } else {
  1368. // No changes, pass back the structure
  1369. // we were given initially.
  1370. return $in;
  1371. }
  1372. }
  1373. // parse and compile buffer
  1374. // This is deprecated
  1375. public function parse($str = null, $initialVariables = null) {
  1376. if (is_array($str)) {
  1377. $initialVariables = $str;
  1378. $str = null;
  1379. }
  1380. $oldVars = $this->registeredVars;
  1381. if ($initialVariables !== null) {
  1382. $this->setVariables($initialVariables);
  1383. }
  1384. if ($str == null) {
  1385. if (empty($this->_parseFile)) {
  1386. throw new exception("nothing to parse");
  1387. }
  1388. $out = $this->compileFile($this->_parseFile);
  1389. } else {
  1390. $out = $this->compile($str);
  1391. }
  1392. $this->registeredVars = $oldVars;
  1393. return $out;
  1394. }
  1395. protected function makeParser($name) {
  1396. $parser = new lessc_parser($this, $name);
  1397. $parser->writeComments = $this->preserveComments;
  1398. return $parser;
  1399. }
  1400. public function setFormatter($name) {
  1401. $this->formatterName = $name;
  1402. }
  1403. protected function newFormatter() {
  1404. $className = "lessc_formatter_lessjs";
  1405. if (!empty($this->formatterName)) {
  1406. if (!is_string($this->formatterName))
  1407. return $this->formatterName;
  1408. $className = "lessc_formatter_$this->formatterName";
  1409. }
  1410. return new $className;
  1411. }
  1412. public function setPreserveComments($preserve) {
  1413. $this->preserveComments = $preserve;
  1414. }
  1415. public function registerFunction($name, $func) {
  1416. $this->libFunctions[$name] = $func;
  1417. }
  1418. public function unregisterFunction($name) {
  1419. unset($this->libFunctions[$name]);
  1420. }
  1421. public function setVariables($variables) {
  1422. $this->registeredVars = array_merge($this->registeredVars, $variables);
  1423. }
  1424. public function unsetVariable($name) {
  1425. unset($this->registeredVars[name]);
  1426. }
  1427. public function allParsedFiles() {
  1428. return $this->allParsedFiles;
  1429. }
  1430. protected function addParsedFile($file) {
  1431. $this->allParsedFiles[realpath($file)] = filemtime($file);
  1432. }
  1433. /**
  1434. * Uses the current value of $this->count to show line and line number
  1435. */
  1436. protected function throwError($msg = null) {
  1437. if ($this->sourceLoc >= 0) {
  1438. $this->sourceParser->throwError($msg, $this->sourceLoc);
  1439. }
  1440. throw new exception($msg);
  1441. }
  1442. // compile file $in to file $out if $in is newer than $out
  1443. // returns true when it compiles, false otherwise
  1444. public static function ccompile($in, $out, $less = null) {
  1445. if ($less === null) {
  1446. $less = new self;
  1447. }
  1448. return $less->checkedCompile($in, $out);
  1449. }
  1450. public static function cexecute($in, $force = false, $less = null) {
  1451. if ($less === null) {
  1452. $less = new self;
  1453. }
  1454. return $less->cachedCompile($in, $force);
  1455. }
  1456. static protected $cssColors = array(
  1457. 'aliceblue' => '240,248,255',
  1458. 'antiquewhite' => '250,235,215',
  1459. 'aqua' => '0,255,255',
  1460. 'aquamarine' => '127,255,212',
  1461. 'azure' => '240,255,255',
  1462. 'beige' => '245,245,220',
  1463. 'bisque' => '255,228,196',
  1464. 'black' => '0,0,0',
  1465. 'blanchedalmond' => '255,235,205',
  1466. 'blue' => '0,0,255',
  1467. 'blueviolet' => '138,43,226',
  1468. 'brown' => '165,42,42',
  1469. 'burlywood' => '222,184,135',
  1470. 'cadetblue' => '95,158,160',
  1471. 'chartreuse' => '127,255,0',
  1472. 'chocolate' => '210,105,30',
  1473. 'coral' => '255,127,80',
  1474. 'cornflowerblue' => '100,149,237',
  1475. 'cornsilk' => '255,248,220',
  1476. 'crimson' => '220,20,60',
  1477. 'cyan' => '0,255,255',
  1478. 'darkblue' => '0,0,139',
  1479. 'darkcyan' => '0,139,139',
  1480. 'darkgoldenrod' => '184,134,11',
  1481. 'darkgray' => '169,169,169',
  1482. 'darkgreen' => '0,100,0',
  1483. 'darkgrey' => '169,169,169',
  1484. 'darkkhaki' => '189,183,107',
  1485. 'darkmagenta' => '139,0,139',
  1486. 'darkolivegreen' => '85,107,47',
  1487. 'darkorange' => '255,140,0',
  1488. 'darkorchid' => '153,50,204',
  1489. 'darkred' => '139,0,0',
  1490. 'darksalmon' => '233,150,122',
  1491. 'darkseagreen' => '143,188,143',
  1492. 'darkslateblue' => '72,61,139',
  1493. 'darkslategray' => '47,79,79',
  1494. 'darkslategrey' => '47,79,79',
  1495. 'darkturquoise' => '0,206,209',
  1496. 'darkviolet' => '148,0,211',
  1497. 'deeppink' => '255,20,147',
  1498. 'deepskyblue' => '0,191,255',
  1499. 'dimgray' => '105,105,105',
  1500. 'dimgrey' => '105,105,105',
  1501. 'dodgerblue' => '30,144,255',
  1502. 'firebrick' => '178,34,34',
  1503. 'floralwhite' => '255,250,240',
  1504. 'forestgreen' => '34,139,34',
  1505. 'fuchsia' => '255,0,255',
  1506. 'gainsboro' => '220,220,220',
  1507. 'ghostwhite' => '248,248,255',
  1508. 'gold' => '255,215,0',
  1509. 'goldenrod' => '218,165,32',
  1510. 'gray' => '128,128,128',
  1511. 'green' => '0,128,0',
  1512. 'greenyellow' => '173,255,47',
  1513. 'grey' => '128,128,128',
  1514. 'honeydew' => '240,255,240',
  1515. 'hotpink' => '255,105,180',
  1516. 'indianred' => '205,92,92',
  1517. 'indigo' => '75,0,130',
  1518. 'ivory' => '255,255,240',
  1519. 'khaki' => '240,230,140',
  1520. 'lavender' => '230,230,250',
  1521. 'lavenderblush' => '255,240,245',
  1522. 'lawngreen' => '124,252,0',
  1523. 'lemonchiffon' => '255,250,205',
  1524. 'lightblue' => '173,216,230',
  1525. 'lightcoral' => '240,128,128',
  1526. 'lightcyan' => '224,255,255',
  1527. 'lightgoldenrodyellow' => '250,250,210',
  1528. 'lightgray' => '211,211,211',
  1529. 'lightgreen' => '144,238,144',
  1530. 'lightgrey' => '211,211,211',
  1531. 'lightpink' => '255,182,193',
  1532. 'lightsalmon' => '255,160,122',
  1533. 'lightseagreen' => '32,178,170',
  1534. 'lightskyblue' => '135,206,250',
  1535. 'lightslategray' => '119,136,153',
  1536. 'lightslategrey' => '119,136,153',
  1537. 'lightsteelblue' => '176,196,222',
  1538. 'lightyellow' => '255,255,224',
  1539. 'lime' => '0,255,0',
  1540. 'limegreen' => '50,205,50',
  1541. 'linen' => '250,240,230',
  1542. 'magenta' => '255,0,255',
  1543. 'maroon' => '128,0,0',
  1544. 'mediumaquamarine' => '102,205,170',
  1545. 'mediumblue' => '0,0,205',
  1546. 'mediumorchid' => '186,85,211',
  1547. 'mediumpurple' => '147,112,219',
  1548. 'mediumseagreen' => '60,179,113',
  1549. 'mediumslateblue' => '123,104,238',
  1550. 'mediumspringgreen' => '0,250,154',
  1551. 'mediumturquoise' => '72,209,204',
  1552. 'mediumvioletred' => '199,21,133',
  1553. 'midnightblue' => '25,25,112',
  1554. 'mintcream' => '245,255,250',
  1555. 'mistyrose' => '255,228,225',
  1556. 'moccasin' => '255,228,181',
  1557. 'navajowhite' => '255,222,173',
  1558. 'navy' => '0,0,128',
  1559. 'oldlace' => '253,245,230',
  1560. 'olive' => '128,128,0',
  1561. 'olivedrab' => '107,142,35',
  1562. 'orange' => '255,165,0',
  1563. 'orangered' => '255,69,0',
  1564. 'orchid' => '218,112,214',
  1565. 'palegoldenrod' => '238,232,170',
  1566. 'palegreen' => '152,251,152',
  1567. 'paleturquoise' => '175,238,238',
  1568. 'palevioletred' => '219,112,147',
  1569. 'papayawhip' => '255,239,213',
  1570. 'peachpuff' => '255,218,185',
  1571. 'peru' => '205,133,63',
  1572. 'pink' => '255,192,203',
  1573. 'plum' => '221,160,221',
  1574. 'powderblue' => '176,224,230',
  1575. 'purple' => '128,0,128',
  1576. 'red' => '255,0,0',
  1577. 'rosybrown' => '188,143,143',
  1578. 'royalblue' => '65,105,225',
  1579. 'saddlebrown' => '139,69,19',
  1580. 'salmon' => '250,128,114',
  1581. 'san…

Large files files are truncated, but you can click here to view the full file