PageRenderTime 59ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 1ms

/files/lib/system/theme/3rdParty/lessc.inc.php

https://github.com/moxeo/com.wcfsolutions.wcf.theme
PHP | 3675 lines | 2772 code | 570 blank | 333 comment | 643 complexity | b8ddd7795cbca49cad99e4a977d0b13d MD5 | raw file
Possible License(s): LGPL-3.0

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

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

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