PageRenderTime 67ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 1ms

/libraries/gantry/core/utilities/gantrylesscompiler.class.php

https://bitbucket.org/biojazzard/joomla-eboracast
PHP | 3500 lines | 2629 code | 541 blank | 330 comment | 613 complexity | 23659eefffcdc8882ebaed72a07c456d MD5 | raw file
Possible License(s): LGPL-2.1, GPL-2.0, MIT, BSD-3-Clause

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

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

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