PageRenderTime 214ms CodeModel.GetById 36ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-content/plugins/all-in-one-event-calendar/vendor/lessphp/lessc.inc.php

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

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