PageRenderTime 118ms CodeModel.GetById 28ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/csslib.php

https://bitbucket.org/ngmares/moodle
PHP | 4781 lines | 2406 code | 405 blank | 1970 comment | 482 complexity | 81f7fa13994cb0ad9399fcde3ec855bb MD5 | raw file
Possible License(s): LGPL-2.1, AGPL-3.0, MPL-2.0-no-copyleft-exception, GPL-3.0, Apache-2.0, BSD-3-Clause
  1. <?php
  2. // This file is part of Moodle - http://moodle.org/
  3. //
  4. // Moodle is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // Moodle is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
  16. /**
  17. * This file contains CSS related class, and function for the CSS optimiser
  18. *
  19. * Please see the {@link css_optimiser} class for greater detail.
  20. *
  21. * @package core
  22. * @category css
  23. * @copyright 2012 Sam Hemelryk
  24. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  25. */
  26. // NOTE: do not verify MOODLE_INTERNAL here, this is used from themes too
  27. /**
  28. * Stores CSS in a file at the given path.
  29. *
  30. * This function either succeeds or throws an exception.
  31. *
  32. * @param theme_config $theme The theme that the CSS belongs to.
  33. * @param string $csspath The path to store the CSS at.
  34. * @param array $cssfiles The CSS files to store.
  35. */
  36. function css_store_css(theme_config $theme, $csspath, array $cssfiles) {
  37. global $CFG;
  38. // Check if both the CSS optimiser is enabled and the theme supports it.
  39. if (!empty($CFG->enablecssoptimiser) && $theme->supportscssoptimisation) {
  40. // This is an experimental feature introduced in Moodle 2.3
  41. // The CSS optimiser organises the CSS in order to reduce the overall number
  42. // of rules and styles being sent to the client. It does this by collating
  43. // the CSS before it is cached removing excess styles and rules and stripping
  44. // out any extraneous content such as comments and empty rules.
  45. $optimiser = new css_optimiser;
  46. $css = '';
  47. foreach ($cssfiles as $file) {
  48. $css .= file_get_contents($file)."\n";
  49. }
  50. $css = $theme->post_process($css);
  51. $css = $optimiser->process($css);
  52. // If cssoptimisestats is set then stats from the optimisation are collected
  53. // and output at the beginning of the CSS
  54. if (!empty($CFG->cssoptimiserstats)) {
  55. $css = $optimiser->output_stats_css().$css;
  56. }
  57. } else {
  58. // This is the default behaviour.
  59. // The cssoptimise setting was introduced in Moodle 2.3 and will hopefully
  60. // in the future be changed from an experimental setting to the default.
  61. // The css_minify_css will method will use the Minify library remove
  62. // comments, additional whitespace and other minor measures to reduce the
  63. // the overall CSS being sent.
  64. // However it has the distinct disadvantage of having to minify the CSS
  65. // before running the post process functions. Potentially things may break
  66. // here if theme designers try to push things with CSS post processing.
  67. $css = $theme->post_process(css_minify_css($cssfiles));
  68. }
  69. clearstatcache();
  70. if (!file_exists(dirname($csspath))) {
  71. @mkdir(dirname($csspath), $CFG->directorypermissions, true);
  72. }
  73. // Prevent serving of incomplete file from concurrent request,
  74. // the rename() should be more atomic than fwrite().
  75. ignore_user_abort(true);
  76. if ($fp = fopen($csspath.'.tmp', 'xb')) {
  77. fwrite($fp, $css);
  78. fclose($fp);
  79. rename($csspath.'.tmp', $csspath);
  80. @chmod($csspath, $CFG->filepermissions);
  81. @unlink($csspath.'.tmp'); // just in case anything fails
  82. }
  83. ignore_user_abort(false);
  84. if (connection_aborted()) {
  85. die;
  86. }
  87. }
  88. /**
  89. * Sends IE specific CSS
  90. *
  91. * In writing the CSS parser I have a theory that we could optimise the CSS
  92. * then split it based upon the number of selectors to ensure we dont' break IE
  93. * and that we include only as many sub-stylesheets as we require.
  94. * Of course just a theory but may be fun to code.
  95. *
  96. * @param string $themename The name of the theme we are sending CSS for.
  97. * @param string $rev The revision to ensure we utilise the cache.
  98. * @param string $etag The revision to ensure we utilise the cache.
  99. * @param bool $slasharguments
  100. */
  101. function css_send_ie_css($themename, $rev, $etag, $slasharguments) {
  102. global $CFG;
  103. $lifetime = 60*60*24*60; // 60 days only - the revision may get incremented quite often
  104. $relroot = preg_replace('|^http.?://[^/]+|', '', $CFG->wwwroot);
  105. $css = "/** Unfortunately IE6/7 does not support more than 4096 selectors in one CSS file, which means we have to use some ugly hacks :-( **/";
  106. if ($slasharguments) {
  107. $css .= "\n@import url($relroot/styles.php/$themename/$rev/plugins);";
  108. $css .= "\n@import url($relroot/styles.php/$themename/$rev/parents);";
  109. $css .= "\n@import url($relroot/styles.php/$themename/$rev/theme);";
  110. } else {
  111. $css .= "\n@import url($relroot/styles.php?theme=$themename&rev=$rev&type=plugins);";
  112. $css .= "\n@import url($relroot/styles.php?theme=$themename&rev=$rev&type=parents);";
  113. $css .= "\n@import url($relroot/styles.php?theme=$themename&rev=$rev&type=theme);";
  114. }
  115. header('Etag: '.$etag);
  116. header('Content-Disposition: inline; filename="styles.php"');
  117. header('Last-Modified: '. gmdate('D, d M Y H:i:s', time()) .' GMT');
  118. header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
  119. header('Pragma: ');
  120. header('Cache-Control: public, max-age='.$lifetime);
  121. header('Accept-Ranges: none');
  122. header('Content-Type: text/css; charset=utf-8');
  123. header('Content-Length: '.strlen($css));
  124. echo $css;
  125. die;
  126. }
  127. /**
  128. * Sends a cached CSS file
  129. *
  130. * This function sends the cached CSS file. Remember it is generated on the first
  131. * request, then optimised/minified, and finally cached for serving.
  132. *
  133. * @param string $csspath The path to the CSS file we want to serve.
  134. * @param string $etag The revision to make sure we utilise any caches.
  135. */
  136. function css_send_cached_css($csspath, $etag) {
  137. $lifetime = 60*60*24*60; // 60 days only - the revision may get incremented quite often
  138. header('Etag: '.$etag);
  139. header('Content-Disposition: inline; filename="styles.php"');
  140. header('Last-Modified: '. gmdate('D, d M Y H:i:s', filemtime($csspath)) .' GMT');
  141. header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
  142. header('Pragma: ');
  143. header('Cache-Control: public, max-age='.$lifetime);
  144. header('Accept-Ranges: none');
  145. header('Content-Type: text/css; charset=utf-8');
  146. if (!min_enable_zlib_compression()) {
  147. header('Content-Length: '.filesize($csspath));
  148. }
  149. readfile($csspath);
  150. die;
  151. }
  152. /**
  153. * Sends CSS directly without caching it.
  154. *
  155. * This function takes a raw CSS string, optimises it if required, and then
  156. * serves it.
  157. * Turning both themedesignermode and CSS optimiser on at the same time is aweful
  158. * for performance because of the optimiser running here. However it was done so
  159. * that theme designers could utilise the optimised output during development to
  160. * help them optimise their CSS... not that they should write lazy CSS.
  161. *
  162. * @param string $css
  163. */
  164. function css_send_uncached_css($css, $themesupportsoptimisation = true) {
  165. global $CFG;
  166. header('Content-Disposition: inline; filename="styles_debug.php"');
  167. header('Last-Modified: '. gmdate('D, d M Y H:i:s', time()) .' GMT');
  168. header('Expires: '. gmdate('D, d M Y H:i:s', time() + THEME_DESIGNER_CACHE_LIFETIME) .' GMT');
  169. header('Pragma: ');
  170. header('Accept-Ranges: none');
  171. header('Content-Type: text/css; charset=utf-8');
  172. if (is_array($css)) {
  173. $css = implode("\n\n", $css);
  174. }
  175. echo $css;
  176. die;
  177. }
  178. /**
  179. * Send file not modified headers
  180. * @param int $lastmodified
  181. * @param string $etag
  182. */
  183. function css_send_unmodified($lastmodified, $etag) {
  184. $lifetime = 60*60*24*60; // 60 days only - the revision may get incremented quite often
  185. header('HTTP/1.1 304 Not Modified');
  186. header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
  187. header('Cache-Control: public, max-age='.$lifetime);
  188. header('Content-Type: text/css; charset=utf-8');
  189. header('Etag: '.$etag);
  190. if ($lastmodified) {
  191. header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
  192. }
  193. die;
  194. }
  195. /**
  196. * Sends a 404 message about CSS not being found.
  197. */
  198. function css_send_css_not_found() {
  199. header('HTTP/1.0 404 not found');
  200. die('CSS was not found, sorry.');
  201. }
  202. /**
  203. * Uses the minify library to compress CSS.
  204. *
  205. * This is used if $CFG->enablecssoptimiser has been turned off. This was
  206. * the original CSS optimisation library.
  207. * It removes whitespace and shrinks things but does no apparent optimisation.
  208. * Note the minify library is still being used for JavaScript.
  209. *
  210. * @param array $files An array of files to minify
  211. * @return string The minified CSS
  212. */
  213. function css_minify_css($files) {
  214. global $CFG;
  215. if (empty($files)) {
  216. return '';
  217. }
  218. set_include_path($CFG->libdir . '/minify/lib' . PATH_SEPARATOR . get_include_path());
  219. require_once('Minify.php');
  220. if (0 === stripos(PHP_OS, 'win')) {
  221. Minify::setDocRoot(); // IIS may need help
  222. }
  223. // disable all caching, we do it in moodle
  224. Minify::setCache(null, false);
  225. $options = array(
  226. 'bubbleCssImports' => false,
  227. // Don't gzip content we just want text for storage
  228. 'encodeOutput' => false,
  229. // Maximum age to cache, not used but required
  230. 'maxAge' => (60*60*24*20),
  231. // The files to minify
  232. 'files' => $files,
  233. // Turn orr URI rewriting
  234. 'rewriteCssUris' => false,
  235. // This returns the CSS rather than echoing it for display
  236. 'quiet' => true
  237. );
  238. $error = 'unknown';
  239. try {
  240. $result = Minify::serve('Files', $options);
  241. if ($result['success']) {
  242. return $result['content'];
  243. }
  244. } catch (Exception $e) {
  245. $error = $e->getMessage();
  246. $error = str_replace("\r", ' ', $error);
  247. $error = str_replace("\n", ' ', $error);
  248. }
  249. // minification failed - try to inform the theme developer and include the non-minified version
  250. $css = <<<EOD
  251. /* Error: $error */
  252. /* Problem detected during theme CSS minimisation, please review the following code */
  253. /* ================================================================================ */
  254. EOD;
  255. foreach ($files as $cssfile) {
  256. $css .= file_get_contents($cssfile)."\n";
  257. }
  258. return $css;
  259. }
  260. /**
  261. * Determines if the given value is a valid CSS colour.
  262. *
  263. * A CSS colour can be one of the following:
  264. * - Hex colour: #AA66BB
  265. * - RGB colour: rgb(0-255, 0-255, 0-255)
  266. * - RGBA colour: rgba(0-255, 0-255, 0-255, 0-1)
  267. * - HSL colour: hsl(0-360, 0-100%, 0-100%)
  268. * - HSLA colour: hsla(0-360, 0-100%, 0-100%, 0-1)
  269. *
  270. * Or a recognised browser colour mapping {@link css_optimiser::$htmlcolours}
  271. *
  272. * @param string $value The colour value to check
  273. * @return bool
  274. */
  275. function css_is_colour($value) {
  276. $value = trim($value);
  277. $hex = '/^#([a-fA-F0-9]{1,3}|[a-fA-F0-9]{6})$/';
  278. $rgb = '#^rgb\s*\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$#i';
  279. $rgba = '#^rgba\s*\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1}(\.\d+)?)\s*\)$#i';
  280. $hsl = '#^hsl\s*\(\s*(\d{1,3})\s*,\s*(\d{1,3})\%\s*,\s*(\d{1,3})\%\s*\)$#i';
  281. $hsla = '#^hsla\s*\(\s*(\d{1,3})\s*,\s*(\d{1,3})\%\s*,\s*(\d{1,3})\%\s*,\s*(\d{1}(\.\d+)?)\s*\)$#i';
  282. if (in_array(strtolower($value), array('inherit'))) {
  283. return true;
  284. } else if (preg_match($hex, $value)) {
  285. return true;
  286. } else if (in_array(strtolower($value), array_keys(css_optimiser::$htmlcolours))) {
  287. return true;
  288. } else if (preg_match($rgb, $value, $m) && $m[1] < 256 && $m[2] < 256 && $m[3] < 256) {
  289. // It is an RGB colour
  290. return true;
  291. } else if (preg_match($rgba, $value, $m) && $m[1] < 256 && $m[2] < 256 && $m[3] < 256) {
  292. // It is an RGBA colour
  293. return true;
  294. } else if (preg_match($hsl, $value, $m) && $m[1] <= 360 && $m[2] <= 100 && $m[3] <= 100) {
  295. // It is an HSL colour
  296. return true;
  297. } else if (preg_match($hsla, $value, $m) && $m[1] <= 360 && $m[2] <= 100 && $m[3] <= 100) {
  298. // It is an HSLA colour
  299. return true;
  300. }
  301. // Doesn't look like a colour.
  302. return false;
  303. }
  304. /**
  305. * Returns true is the passed value looks like a CSS width.
  306. * In order to pass this test the value must be purely numerical or end with a
  307. * valid CSS unit term.
  308. *
  309. * @param string|int $value
  310. * @return boolean
  311. */
  312. function css_is_width($value) {
  313. $value = trim($value);
  314. if (in_array(strtolower($value), array('auto', 'inherit'))) {
  315. return true;
  316. }
  317. if ((string)$value === '0' || preg_match('#^(\-\s*)?(\d*\.)?(\d+)\s*(em|px|pt|\%|in|cm|mm|ex|pc)$#i', $value)) {
  318. return true;
  319. }
  320. return false;
  321. }
  322. /**
  323. * A simple sorting function to sort two array values on the number of items they contain
  324. *
  325. * @param array $a
  326. * @param array $b
  327. * @return int
  328. */
  329. function css_sort_by_count(array $a, array $b) {
  330. $a = count($a);
  331. $b = count($b);
  332. if ($a == $b) {
  333. return 0;
  334. }
  335. return ($a > $b) ? -1 : 1;
  336. }
  337. /**
  338. * A basic CSS optimiser that strips out unwanted things and then processing the
  339. * CSS organising styles and moving duplicates and useless CSS.
  340. *
  341. * This CSS optimiser works by reading through a CSS string one character at a
  342. * time and building an object structure of the CSS.
  343. * As part of that processing styles are expanded out as much as they can be to
  344. * ensure we collect all mappings, at the end of the processing those styles are
  345. * then combined into an optimised form to keep them as short as possible.
  346. *
  347. * @package core
  348. * @category css
  349. * @copyright 2012 Sam Hemelryk
  350. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  351. */
  352. class css_optimiser {
  353. /**
  354. * Used when the processor is about to start processing.
  355. * Processing states. Used internally.
  356. */
  357. const PROCESSING_START = 0;
  358. /**
  359. * Used when the processor is currently processing a selector.
  360. * Processing states. Used internally.
  361. */
  362. const PROCESSING_SELECTORS = 0;
  363. /**
  364. * Used when the processor is currently processing a style.
  365. * Processing states. Used internally.
  366. */
  367. const PROCESSING_STYLES = 1;
  368. /**
  369. * Used when the processor is currently processing a comment.
  370. * Processing states. Used internally.
  371. */
  372. const PROCESSING_COMMENT = 2;
  373. /**
  374. * Used when the processor is currently processing an @ rule.
  375. * Processing states. Used internally.
  376. */
  377. const PROCESSING_ATRULE = 3;
  378. /**
  379. * The raw string length before optimisation.
  380. * Stats variables set during and after processing
  381. * @var int
  382. */
  383. protected $rawstrlen = 0;
  384. /**
  385. * The number of comments that were removed during optimisation.
  386. * Stats variables set during and after processing
  387. * @var int
  388. */
  389. protected $commentsincss = 0;
  390. /**
  391. * The number of rules in the CSS before optimisation.
  392. * Stats variables set during and after processing
  393. * @var int
  394. */
  395. protected $rawrules = 0;
  396. /**
  397. * The number of selectors using in CSS rules before optimisation.
  398. * Stats variables set during and after processing
  399. * @var int
  400. */
  401. protected $rawselectors = 0;
  402. /**
  403. * The string length after optimisation.
  404. * Stats variables set during and after processing
  405. * @var int
  406. */
  407. protected $optimisedstrlen = 0;
  408. /**
  409. * The number of rules after optimisation.
  410. * Stats variables set during and after processing
  411. * @var int
  412. */
  413. protected $optimisedrules = 0;
  414. /**
  415. * The number of selectors used in rules after optimisation.
  416. * Stats variables set during and after processing
  417. * @var int
  418. */
  419. protected $optimisedselectors = 0;
  420. /**
  421. * The start time of the optimisation.
  422. * Stats variables set during and after processing
  423. * @var int
  424. */
  425. protected $timestart = 0;
  426. /**
  427. * The end time of the optimisation.
  428. * Stats variables set during and after processing
  429. * @var int
  430. */
  431. protected $timecomplete = 0;
  432. /**
  433. * Will be set to any errors that may have occured during processing.
  434. * This is updated only at the end of processing NOT during.
  435. *
  436. * @var array
  437. */
  438. protected $errors = array();
  439. /**
  440. * Processes incoming CSS optimising it and then returning it.
  441. *
  442. * @param string $css The raw CSS to optimise
  443. * @return string The optimised CSS
  444. */
  445. public function process($css) {
  446. global $CFG;
  447. // Easiest win there is
  448. $css = trim($css);
  449. $this->reset_stats();
  450. $this->timestart = microtime(true);
  451. $this->rawstrlen = strlen($css);
  452. // Don't try to process files with no content... it just doesn't make sense.
  453. // But we should produce an error for them, an empty CSS file will lead to a
  454. // useless request for those running theme designer mode.
  455. if ($this->rawstrlen === 0) {
  456. $this->errors[] = 'Skipping file as it has no content.';
  457. return '';
  458. }
  459. // First up we need to remove all line breaks - this allows us to instantly
  460. // reduce our processing requirements and as we will process everything
  461. // into a new structure there's really nothing lost.
  462. $css = preg_replace('#\r?\n#', ' ', $css);
  463. // Next remove the comments... no need to them in an optimised world and
  464. // knowing they're all gone allows us to REALLY make our processing simpler
  465. $css = preg_replace('#/\*(.*?)\*/#m', '', $css, -1, $this->commentsincss);
  466. $medias = array(
  467. 'all' => new css_media()
  468. );
  469. $imports = array();
  470. $charset = false;
  471. // Keyframes are used for CSS animation they will be processed right at the very end.
  472. $keyframes = array();
  473. $currentprocess = self::PROCESSING_START;
  474. $currentrule = css_rule::init();
  475. $currentselector = css_selector::init();
  476. $inquotes = false; // ' or "
  477. $inbraces = false; // {
  478. $inbrackets = false; // [
  479. $inparenthesis = false; // (
  480. $currentmedia = $medias['all'];
  481. $currentatrule = null;
  482. $suspectatrule = false;
  483. $buffer = '';
  484. $char = null;
  485. // Next we are going to iterate over every single character in $css.
  486. // This is why we removed line breaks and comments!
  487. for ($i = 0; $i < $this->rawstrlen; $i++) {
  488. $lastchar = $char;
  489. $char = substr($css, $i, 1);
  490. if ($char == '@' && $buffer == '') {
  491. $suspectatrule = true;
  492. }
  493. switch ($currentprocess) {
  494. // Start processing an @ rule e.g. @media, @page, @keyframes
  495. case self::PROCESSING_ATRULE:
  496. switch ($char) {
  497. case ';':
  498. if (!$inbraces) {
  499. $buffer .= $char;
  500. if ($currentatrule == 'import') {
  501. $imports[] = $buffer;
  502. $currentprocess = self::PROCESSING_SELECTORS;
  503. } else if ($currentatrule == 'charset') {
  504. $charset = $buffer;
  505. $currentprocess = self::PROCESSING_SELECTORS;
  506. }
  507. }
  508. if ($currentatrule !== 'media') {
  509. $buffer = '';
  510. $currentatrule = false;
  511. }
  512. // continue 1: The switch processing chars
  513. // continue 2: The switch processing the state
  514. // continue 3: The for loop
  515. continue 3;
  516. case '{':
  517. if ($currentatrule == 'media' && preg_match('#\s*@media\s*([a-zA-Z0-9]+(\s*,\s*[a-zA-Z0-9]+)*)\s*{#', $buffer, $matches)) {
  518. // Basic media declaration
  519. $mediatypes = str_replace(' ', '', $matches[1]);
  520. if (!array_key_exists($mediatypes, $medias)) {
  521. $medias[$mediatypes] = new css_media($mediatypes);
  522. }
  523. $currentmedia = $medias[$mediatypes];
  524. $currentprocess = self::PROCESSING_SELECTORS;
  525. $buffer = '';
  526. } else if ($currentatrule == 'media' && preg_match('#\s*@media\s*([^{]+)#', $buffer, $matches)) {
  527. // Advanced media query declaration http://www.w3.org/TR/css3-mediaqueries/
  528. $mediatypes = $matches[1];
  529. $hash = md5($mediatypes);
  530. $medias[$hash] = new css_media($mediatypes);
  531. $currentmedia = $medias[$hash];
  532. $currentprocess = self::PROCESSING_SELECTORS;
  533. $buffer = '';
  534. } else if ($currentatrule == 'keyframes' && preg_match('#@((\-moz\-|\-webkit\-)?keyframes)\s*([^\s]+)#', $buffer, $matches)) {
  535. // Keyframes declaration, we treat it exactly like a @media declaration except we don't allow
  536. // them to be overridden to ensure we don't mess anything up. (means we keep everything in order)
  537. $keyframefor = $matches[1];
  538. $keyframename = $matches[3];
  539. $keyframe = new css_keyframe($keyframefor, $keyframename);
  540. $keyframes[] = $keyframe;
  541. $currentmedia = $keyframe;
  542. $currentprocess = self::PROCESSING_SELECTORS;
  543. $buffer = '';
  544. }
  545. // continue 1: The switch processing chars
  546. // continue 2: The switch processing the state
  547. // continue 3: The for loop
  548. continue 3;
  549. }
  550. break;
  551. // Start processing selectors
  552. case self::PROCESSING_START:
  553. case self::PROCESSING_SELECTORS:
  554. switch ($char) {
  555. case '[':
  556. $inbrackets ++;
  557. $buffer .= $char;
  558. // continue 1: The switch processing chars
  559. // continue 2: The switch processing the state
  560. // continue 3: The for loop
  561. continue 3;
  562. case ']':
  563. $inbrackets --;
  564. $buffer .= $char;
  565. // continue 1: The switch processing chars
  566. // continue 2: The switch processing the state
  567. // continue 3: The for loop
  568. continue 3;
  569. case ' ':
  570. if ($inbrackets) {
  571. // continue 1: The switch processing chars
  572. // continue 2: The switch processing the state
  573. // continue 3: The for loop
  574. continue 3;
  575. }
  576. if (!empty($buffer)) {
  577. // Check for known @ rules
  578. if ($suspectatrule && preg_match('#@(media|import|charset|(\-moz\-|\-webkit\-)?(keyframes))\s*#', $buffer, $matches)) {
  579. $currentatrule = (!empty($matches[3]))?$matches[3]:$matches[1];
  580. $currentprocess = self::PROCESSING_ATRULE;
  581. $buffer .= $char;
  582. } else {
  583. $currentselector->add($buffer);
  584. $buffer = '';
  585. }
  586. }
  587. $suspectatrule = false;
  588. // continue 1: The switch processing chars
  589. // continue 2: The switch processing the state
  590. // continue 3: The for loop
  591. continue 3;
  592. case '{':
  593. if ($inbrackets) {
  594. // continue 1: The switch processing chars
  595. // continue 2: The switch processing the state
  596. // continue 3: The for loop
  597. continue 3;
  598. }
  599. if ($buffer !== '') {
  600. $currentselector->add($buffer);
  601. }
  602. $currentrule->add_selector($currentselector);
  603. $currentselector = css_selector::init();
  604. $currentprocess = self::PROCESSING_STYLES;
  605. $buffer = '';
  606. // continue 1: The switch processing chars
  607. // continue 2: The switch processing the state
  608. // continue 3: The for loop
  609. continue 3;
  610. case '}':
  611. if ($inbrackets) {
  612. // continue 1: The switch processing chars
  613. // continue 2: The switch processing the state
  614. // continue 3: The for loop
  615. continue 3;
  616. }
  617. if ($currentatrule == 'media') {
  618. $currentmedia = $medias['all'];
  619. $currentatrule = false;
  620. $buffer = '';
  621. } else if (strpos($currentatrule, 'keyframes') !== false) {
  622. $currentmedia = $medias['all'];
  623. $currentatrule = false;
  624. $buffer = '';
  625. }
  626. // continue 1: The switch processing chars
  627. // continue 2: The switch processing the state
  628. // continue 3: The for loop
  629. continue 3;
  630. case ',':
  631. if ($inbrackets) {
  632. // continue 1: The switch processing chars
  633. // continue 2: The switch processing the state
  634. // continue 3: The for loop
  635. continue 3;
  636. }
  637. $currentselector->add($buffer);
  638. $currentrule->add_selector($currentselector);
  639. $currentselector = css_selector::init();
  640. $buffer = '';
  641. // continue 1: The switch processing chars
  642. // continue 2: The switch processing the state
  643. // continue 3: The for loop
  644. continue 3;
  645. }
  646. break;
  647. // Start processing styles
  648. case self::PROCESSING_STYLES:
  649. if ($char == '"' || $char == "'") {
  650. if ($inquotes === false) {
  651. $inquotes = $char;
  652. }
  653. if ($inquotes === $char && $lastchar !== '\\') {
  654. $inquotes = false;
  655. }
  656. }
  657. if ($inquotes) {
  658. $buffer .= $char;
  659. continue 2;
  660. }
  661. switch ($char) {
  662. case ';':
  663. if ($inparenthesis) {
  664. $buffer .= $char;
  665. // continue 1: The switch processing chars
  666. // continue 2: The switch processing the state
  667. // continue 3: The for loop
  668. continue 3;
  669. }
  670. $currentrule->add_style($buffer);
  671. $buffer = '';
  672. $inquotes = false;
  673. // continue 1: The switch processing chars
  674. // continue 2: The switch processing the state
  675. // continue 3: The for loop
  676. continue 3;
  677. case '}':
  678. $currentrule->add_style($buffer);
  679. $this->rawselectors += $currentrule->get_selector_count();
  680. $currentmedia->add_rule($currentrule);
  681. $currentrule = css_rule::init();
  682. $currentprocess = self::PROCESSING_SELECTORS;
  683. $this->rawrules++;
  684. $buffer = '';
  685. $inquotes = false;
  686. $inparenthesis = false;
  687. // continue 1: The switch processing chars
  688. // continue 2: The switch processing the state
  689. // continue 3: The for loop
  690. continue 3;
  691. case '(':
  692. $inparenthesis = true;
  693. $buffer .= $char;
  694. // continue 1: The switch processing chars
  695. // continue 2: The switch processing the state
  696. // continue 3: The for loop
  697. continue 3;
  698. case ')':
  699. $inparenthesis = false;
  700. $buffer .= $char;
  701. // continue 1: The switch processing chars
  702. // continue 2: The switch processing the state
  703. // continue 3: The for loop
  704. continue 3;
  705. }
  706. break;
  707. }
  708. $buffer .= $char;
  709. }
  710. foreach ($medias as $media) {
  711. $this->optimise($media);
  712. }
  713. $css = $this->produce_css($charset, $imports, $medias, $keyframes);
  714. $this->timecomplete = microtime(true);
  715. return trim($css);
  716. }
  717. /**
  718. * Produces CSS for the given charset, imports, media, and keyframes
  719. * @param string $charset
  720. * @param array $imports
  721. * @param array $medias
  722. * @param array $keyframes
  723. * @return string
  724. */
  725. protected function produce_css($charset, array $imports, array $medias, array $keyframes) {
  726. $css = '';
  727. if (!empty($charset)) {
  728. $imports[] = $charset;
  729. }
  730. if (!empty($imports)) {
  731. $css .= implode("\n", $imports);
  732. $css .= "\n\n";
  733. }
  734. $cssreset = array();
  735. $cssstandard = array();
  736. $csskeyframes = array();
  737. // Process each media declaration individually
  738. foreach ($medias as $media) {
  739. // If this declaration applies to all media types
  740. if (in_array('all', $media->get_types())) {
  741. // Collect all rules that represet reset rules and remove them from the media object at the same time.
  742. // We do this because we prioritise reset rules to the top of a CSS output. This ensures that they
  743. // can't end up out of order because of optimisation.
  744. $resetrules = $media->get_reset_rules(true);
  745. if (!empty($resetrules)) {
  746. $cssreset[] = css_writer::media('all', $resetrules);
  747. }
  748. }
  749. // Get the standard cSS
  750. $cssstandard[] = $media->out();
  751. }
  752. // Finally if there are any keyframe declarations process them now.
  753. if (count($keyframes) > 0) {
  754. foreach ($keyframes as $keyframe) {
  755. $this->optimisedrules += $keyframe->count_rules();
  756. $this->optimisedselectors += $keyframe->count_selectors();
  757. if ($keyframe->has_errors()) {
  758. $this->errors += $keyframe->get_errors();
  759. }
  760. $csskeyframes[] = $keyframe->out();
  761. }
  762. }
  763. // Join it all together
  764. $css .= join('', $cssreset);
  765. $css .= join('', $cssstandard);
  766. $css .= join('', $csskeyframes);
  767. // Record the strlenght of the now optimised CSS.
  768. $this->optimisedstrlen = strlen($css);
  769. // Return the now produced CSS
  770. return $css;
  771. }
  772. /**
  773. * Optimises the CSS rules within a rule collection of one form or another
  774. *
  775. * @param css_rule_collection $media
  776. * @return void This function acts in reference
  777. */
  778. protected function optimise(css_rule_collection $media) {
  779. $media->organise_rules_by_selectors();
  780. $this->optimisedrules += $media->count_rules();
  781. $this->optimisedselectors += $media->count_selectors();
  782. if ($media->has_errors()) {
  783. $this->errors += $media->get_errors();
  784. }
  785. }
  786. /**
  787. * Returns an array of stats from the last processing run
  788. * @return string
  789. */
  790. public function get_stats() {
  791. $stats = array(
  792. 'timestart' => $this->timestart,
  793. 'timecomplete' => $this->timecomplete,
  794. 'timetaken' => round($this->timecomplete - $this->timestart, 4),
  795. 'commentsincss' => $this->commentsincss,
  796. 'rawstrlen' => $this->rawstrlen,
  797. 'rawselectors' => $this->rawselectors,
  798. 'rawrules' => $this->rawrules,
  799. 'optimisedstrlen' => $this->optimisedstrlen,
  800. 'optimisedrules' => $this->optimisedrules,
  801. 'optimisedselectors' => $this->optimisedselectors,
  802. 'improvementstrlen' => '-',
  803. 'improvementrules' => '-',
  804. 'improvementselectors' => '-',
  805. );
  806. // Avoid division by 0 errors by checking we have valid raw values
  807. if ($this->rawstrlen > 0) {
  808. $stats['improvementstrlen'] = round(100 - ($this->optimisedstrlen / $this->rawstrlen) * 100, 1).'%';
  809. }
  810. if ($this->rawrules > 0) {
  811. $stats['improvementrules'] = round(100 - ($this->optimisedrules / $this->rawrules) * 100, 1).'%';
  812. }
  813. if ($this->rawselectors > 0) {
  814. $stats['improvementselectors'] = round(100 - ($this->optimisedselectors / $this->rawselectors) * 100, 1).'%';
  815. }
  816. return $stats;
  817. }
  818. /**
  819. * Returns true if any errors have occured during processing
  820. *
  821. * @return bool
  822. */
  823. public function has_errors() {
  824. return !empty($this->errors);
  825. }
  826. /**
  827. * Returns an array of errors that have occured
  828. *
  829. * @param bool $clear If set to true the errors will be cleared after being returned.
  830. * @return array
  831. */
  832. public function get_errors($clear = false) {
  833. $errors = $this->errors;
  834. if ($clear) {
  835. // Reset the error array
  836. $this->errors = array();
  837. }
  838. return $errors;
  839. }
  840. /**
  841. * Returns any errors as a string that can be included in CSS.
  842. *
  843. * @return string
  844. */
  845. public function output_errors_css() {
  846. $computedcss = "/****************************************\n";
  847. $computedcss .= " *--- Errors found during processing ----\n";
  848. foreach ($this->errors as $error) {
  849. $computedcss .= preg_replace('#^#m', '* ', $error);
  850. }
  851. $computedcss .= " ****************************************/\n\n";
  852. return $computedcss;
  853. }
  854. /**
  855. * Returns a string to display stats about the last generation within CSS output
  856. *
  857. * @return string
  858. */
  859. public function output_stats_css() {
  860. $computedcss = "/****************************************\n";
  861. $computedcss .= " *------- CSS Optimisation stats --------\n";
  862. if ($this->rawstrlen === 0) {
  863. $computedcss .= " File not processed as it has no content /\n\n";
  864. $computedcss .= " ****************************************/\n\n";
  865. return $computedcss;
  866. } else if ($this->rawrules === 0) {
  867. $computedcss .= " File contained no rules to be processed /\n\n";
  868. $computedcss .= " ****************************************/\n\n";
  869. return $computedcss;
  870. }
  871. $stats = $this->get_stats();
  872. $computedcss .= " * ".date('r')."\n";
  873. $computedcss .= " * {$stats['commentsincss']} \t comments removed\n";
  874. $computedcss .= " * Optimisation took {$stats['timetaken']} seconds\n";
  875. $computedcss .= " *--------------- before ----------------\n";
  876. $computedcss .= " * {$stats['rawstrlen']} \t chars read in\n";
  877. $computedcss .= " * {$stats['rawrules']} \t rules read in\n";
  878. $computedcss .= " * {$stats['rawselectors']} \t total selectors\n";
  879. $computedcss .= " *---------------- after ----------------\n";
  880. $computedcss .= " * {$stats['optimisedstrlen']} \t chars once optimized\n";
  881. $computedcss .= " * {$stats['optimisedrules']} \t optimized rules\n";
  882. $computedcss .= " * {$stats['optimisedselectors']} \t total selectors once optimized\n";
  883. $computedcss .= " *---------------- stats ----------------\n";
  884. $computedcss .= " * {$stats['improvementstrlen']} \t reduction in chars\n";
  885. $computedcss .= " * {$stats['improvementrules']} \t reduction in rules\n";
  886. $computedcss .= " * {$stats['improvementselectors']} \t reduction in selectors\n";
  887. $computedcss .= " ****************************************/\n\n";
  888. return $computedcss;
  889. }
  890. /**
  891. * Resets the stats ready for another fresh processing
  892. */
  893. public function reset_stats() {
  894. $this->commentsincss = 0;
  895. $this->optimisedrules = 0;
  896. $this->optimisedselectors = 0;
  897. $this->optimisedstrlen = 0;
  898. $this->rawrules = 0;
  899. $this->rawselectors = 0;
  900. $this->rawstrlen = 0;
  901. $this->timecomplete = 0;
  902. $this->timestart = 0;
  903. }
  904. /**
  905. * An array of the common HTML colours that are supported by most browsers.
  906. *
  907. * This reference table is used to allow us to unify colours, and will aid
  908. * us in identifying buggy CSS using unsupported colours.
  909. *
  910. * @staticvar array
  911. * @var array
  912. */
  913. public static $htmlcolours = array(
  914. 'aliceblue' => '#F0F8FF',
  915. 'antiquewhite' => '#FAEBD7',
  916. 'aqua' => '#00FFFF',
  917. 'aquamarine' => '#7FFFD4',
  918. 'azure' => '#F0FFFF',
  919. 'beige' => '#F5F5DC',
  920. 'bisque' => '#FFE4C4',
  921. 'black' => '#000000',
  922. 'blanchedalmond' => '#FFEBCD',
  923. 'blue' => '#0000FF',
  924. 'blueviolet' => '#8A2BE2',
  925. 'brown' => '#A52A2A',
  926. 'burlywood' => '#DEB887',
  927. 'cadetblue' => '#5F9EA0',
  928. 'chartreuse' => '#7FFF00',
  929. 'chocolate' => '#D2691E',
  930. 'coral' => '#FF7F50',
  931. 'cornflowerblue' => '#6495ED',
  932. 'cornsilk' => '#FFF8DC',
  933. 'crimson' => '#DC143C',
  934. 'cyan' => '#00FFFF',
  935. 'darkblue' => '#00008B',
  936. 'darkcyan' => '#008B8B',
  937. 'darkgoldenrod' => '#B8860B',
  938. 'darkgray' => '#A9A9A9',
  939. 'darkgrey' => '#A9A9A9',
  940. 'darkgreen' => '#006400',
  941. 'darkKhaki' => '#BDB76B',
  942. 'darkmagenta' => '#8B008B',
  943. 'darkolivegreen' => '#556B2F',
  944. 'arkorange' => '#FF8C00',
  945. 'darkorchid' => '#9932CC',
  946. 'darkred' => '#8B0000',
  947. 'darksalmon' => '#E9967A',
  948. 'darkseagreen' => '#8FBC8F',
  949. 'darkslateblue' => '#483D8B',
  950. 'darkslategray' => '#2F4F4F',
  951. 'darkslategrey' => '#2F4F4F',
  952. 'darkturquoise' => '#00CED1',
  953. 'darkviolet' => '#9400D3',
  954. 'deeppink' => '#FF1493',
  955. 'deepskyblue' => '#00BFFF',
  956. 'dimgray' => '#696969',
  957. 'dimgrey' => '#696969',
  958. 'dodgerblue' => '#1E90FF',
  959. 'firebrick' => '#B22222',
  960. 'floralwhite' => '#FFFAF0',
  961. 'forestgreen' => '#228B22',
  962. 'fuchsia' => '#FF00FF',
  963. 'gainsboro' => '#DCDCDC',
  964. 'ghostwhite' => '#F8F8FF',
  965. 'gold' => '#FFD700',
  966. 'goldenrod' => '#DAA520',
  967. 'gray' => '#808080',
  968. 'grey' => '#808080',
  969. 'green' => '#008000',
  970. 'greenyellow' => '#ADFF2F',
  971. 'honeydew' => '#F0FFF0',
  972. 'hotpink' => '#FF69B4',
  973. 'indianred ' => '#CD5C5C',
  974. 'indigo ' => '#4B0082',
  975. 'ivory' => '#FFFFF0',
  976. 'khaki' => '#F0E68C',
  977. 'lavender' => '#E6E6FA',
  978. 'lavenderblush' => '#FFF0F5',
  979. 'lawngreen' => '#7CFC00',
  980. 'lemonchiffon' => '#FFFACD',
  981. 'lightblue' => '#ADD8E6',
  982. 'lightcoral' => '#F08080',
  983. 'lightcyan' => '#E0FFFF',
  984. 'lightgoldenrodyellow' => '#FAFAD2',
  985. 'lightgray' => '#D3D3D3',
  986. 'lightgrey' => '#D3D3D3',
  987. 'lightgreen' => '#90EE90',
  988. 'lightpink' => '#FFB6C1',
  989. 'lightsalmon' => '#FFA07A',
  990. 'lightseagreen' => '#20B2AA',
  991. 'lightskyblue' => '#87CEFA',
  992. 'lightslategray' => '#778899',
  993. 'lightslategrey' => '#778899',
  994. 'lightsteelblue' => '#B0C4DE',
  995. 'lightyellow' => '#FFFFE0',
  996. 'lime' => '#00FF00',
  997. 'limegreen' => '#32CD32',
  998. 'linen' => '#FAF0E6',
  999. 'magenta' => '#FF00FF',
  1000. 'maroon' => '#800000',
  1001. 'mediumaquamarine' => '#66CDAA',
  1002. 'mediumblue' => '#0000CD',
  1003. 'mediumorchid' => '#BA55D3',
  1004. 'mediumpurple' => '#9370D8',
  1005. 'mediumseagreen' => '#3CB371',
  1006. 'mediumslateblue' => '#7B68EE',
  1007. 'mediumspringgreen' => '#00FA9A',
  1008. 'mediumturquoise' => '#48D1CC',
  1009. 'mediumvioletred' => '#C71585',
  1010. 'midnightblue' => '#191970',
  1011. 'mintcream' => '#F5FFFA',
  1012. 'mistyrose' => '#FFE4E1',
  1013. 'moccasin' => '#FFE4B5',
  1014. 'navajowhite' => '#FFDEAD',
  1015. 'navy' => '#000080',
  1016. 'oldlace' => '#FDF5E6',
  1017. 'olive' => '#808000',
  1018. 'olivedrab' => '#6B8E23',
  1019. 'orange' => '#FFA500',
  1020. 'orangered' => '#FF4500',
  1021. 'orchid' => '#DA70D6',
  1022. 'palegoldenrod' => '#EEE8AA',
  1023. 'palegreen' => '#98FB98',
  1024. 'paleturquoise' => '#AFEEEE',
  1025. 'palevioletred' => '#D87093',
  1026. 'papayawhip' => '#FFEFD5',
  1027. 'peachpuff' => '#FFDAB9',
  1028. 'peru' => '#CD853F',
  1029. 'pink' => '#FFC0CB',
  1030. 'plum' => '#DDA0DD',
  1031. 'powderblue' => '#B0E0E6',
  1032. 'purple' => '#800080',
  1033. 'red' => '#FF0000',
  1034. 'rosybrown' => '#BC8F8F',
  1035. 'royalblue' => '#4169E1',
  1036. 'saddlebrown' => '#8B4513',
  1037. 'salmon' => '#FA8072',
  1038. 'sandybrown' => '#F4A460',
  1039. 'seagreen' => '#2E8B57',
  1040. 'seashell' => '#FFF5EE',
  1041. 'sienna' => '#A0522D',
  1042. 'silver' => '#C0C0C0',
  1043. 'skyblue' => '#87CEEB',
  1044. 'slateblue' => '#6A5ACD',
  1045. 'slategray' => '#708090',
  1046. 'slategrey' => '#708090',
  1047. 'snow' => '#FFFAFA',
  1048. 'springgreen' => '#00FF7F',
  1049. 'steelblue' => '#4682B4',
  1050. 'tan' => '#D2B48C',
  1051. 'teal' => '#008080',
  1052. 'thistle' => '#D8BFD8',
  1053. 'tomato' => '#FF6347',
  1054. 'transparent' => 'transparent',
  1055. 'turquoise' => '#40E0D0',
  1056. 'violet' => '#EE82EE',
  1057. 'wheat' => '#F5DEB3',
  1058. 'white' => '#FFFFFF',
  1059. 'whitesmoke' => '#F5F5F5',
  1060. 'yellow' => '#FFFF00',
  1061. 'yellowgreen' => '#9ACD32'
  1062. );
  1063. }
  1064. /**
  1065. * Used to prepare CSS strings
  1066. *
  1067. * @package core
  1068. * @category css
  1069. * @copyright 2012 Sam Hemelryk
  1070. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  1071. */
  1072. abstract class css_writer {
  1073. /**
  1074. * The current indent level
  1075. * @var int
  1076. */
  1077. protected static $indent = 0;
  1078. /**
  1079. * Returns true if the output should still maintain minimum formatting.
  1080. * @return bool
  1081. */
  1082. protected static function is_pretty() {
  1083. global $CFG;
  1084. return (!empty($CFG->cssoptimiserpretty));
  1085. }
  1086. /**
  1087. * Returns the indenting char to use for indenting things nicely.
  1088. * @return string
  1089. */
  1090. protected static function get_indent() {
  1091. if (self::is_pretty()) {
  1092. return str_repeat(" ", self::$indent);
  1093. }
  1094. return '';
  1095. }
  1096. /**
  1097. * Increases the current indent
  1098. */
  1099. protected static function increase_indent() {
  1100. self::$indent++;
  1101. }
  1102. /**
  1103. * Decreases the current indent
  1104. */
  1105. protected static function decrease_indent() {
  1106. self::$indent--;
  1107. }
  1108. /**
  1109. * Returns the string to use as a separator
  1110. * @return string
  1111. */
  1112. protected static function get_separator() {
  1113. return (self::is_pretty())?"\n":' ';
  1114. }
  1115. /**
  1116. * Returns CSS for media
  1117. *
  1118. * @param string $typestring
  1119. * @param array $rules An array of css_rule objects
  1120. * @return string
  1121. */
  1122. public static function media($typestring, array &$rules) {
  1123. $nl = self::get_separator();
  1124. $output = '';
  1125. if ($typestring !== 'all') {
  1126. $output .= "\n@media {$typestring} {".$nl;
  1127. self::increase_indent();
  1128. }
  1129. foreach ($rules as $rule) {
  1130. $output .= $rule->out().$nl;
  1131. }
  1132. if ($typestring !== 'all') {
  1133. self::decrease_indent();
  1134. $output .= '}';
  1135. }
  1136. return $output;
  1137. }
  1138. /**
  1139. * Returns CSS for a keyframe
  1140. *
  1141. * @param string $for The desired declaration. e.g. keyframes, -moz-keyframes, -webkit-keyframes
  1142. * @param string $name The name for the keyframe
  1143. * @param array $rules An array of rules belonging to the keyframe
  1144. * @return string
  1145. */
  1146. public static function keyframe($for, $name, array &$rules) {
  1147. $nl = self::get_separator();
  1148. $output = "\n@{$for} {$name} {";
  1149. foreach ($rules as $rule) {
  1150. $output .= $rule->out();
  1151. }
  1152. $output .= '}';
  1153. return $output;
  1154. }
  1155. /**
  1156. * Returns CSS for a rule
  1157. *
  1158. * @param string $selector
  1159. * @param string $styles
  1160. * @return string
  1161. */
  1162. public static function rule($selector, $styles) {
  1163. $css = self::get_indent()."{$selector}{{$styles}}";
  1164. return $css;
  1165. }
  1166. /**
  1167. * Returns CSS for the selectors of a rule
  1168. *
  1169. * @param array $selectors Array of css_selector objects
  1170. * @return string
  1171. */
  1172. public static function selectors(array $selectors) {
  1173. $nl = self::get_separator();
  1174. $selectorstrings = array();
  1175. foreach ($selectors as $selector) {
  1176. $selectorstrings[] = $selector->out();
  1177. }
  1178. return join(','.$nl, $selectorstrings);
  1179. }
  1180. /**
  1181. * Returns a selector given the components that make it up.
  1182. *
  1183. * @param array $components
  1184. * @return string
  1185. */
  1186. public static function selector(array $components) {
  1187. return trim(join(' ', $components));
  1188. }
  1189. /**
  1190. * Returns a CSS string for the provided styles
  1191. *
  1192. * @param array $styles Array of css_style objects
  1193. * @return string
  1194. */
  1195. public static function styles(array $styles) {
  1196. $bits = array();
  1197. foreach ($styles as $style) {
  1198. // Check if the style is an array. If it is then we are outputing an advanced style.
  1199. // An advanced style is a style with one or more values, and can occur in situations like background-image
  1200. // where browse specific values are being used.
  1201. if (is_array($style)) {
  1202. foreach ($style as $advstyle) {
  1203. $bits[] = $advstyle->out();
  1204. }
  1205. continue;
  1206. }
  1207. $bits[] = $style->out();
  1208. }
  1209. return join('', $bits);
  1210. }
  1211. /**
  1212. * Returns a style CSS
  1213. *
  1214. * @param string $name
  1215. * @param string $value
  1216. * @param bool $important
  1217. * @return string
  1218. */
  1219. public static function style($name, $value, $important = false) {
  1220. $value = trim($value);
  1221. if ($important && strpos($value, '!important') === false) {
  1222. $value .= ' !important';
  1223. }
  1224. return "{$name}:{$value};";
  1225. }
  1226. }
  1227. /**
  1228. * A structure to represent a CSS selector.
  1229. *
  1230. * The selector is the classes, id, elements, and psuedo bits that make up a CSS
  1231. * rule.
  1232. *
  1233. * @package core
  1234. * @category css
  1235. * @copyright 2012 Sam Hemelryk
  1236. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  1237. */
  1238. class css_selector {
  1239. /**
  1240. * An array of selector bits
  1241. * @var array
  1242. */
  1243. protected $selectors = array();
  1244. /**
  1245. * The number of selectors.
  1246. * @var int
  1247. */
  1248. protected $count = 0;
  1249. /**
  1250. * Is null if there are no selectors, true if all selectors are basic and false otherwise.
  1251. * A basic selector is one that consists of just the element type. e.g. div, span, td, a
  1252. * @var bool|null
  1253. */
  1254. protected $isbasic = null;
  1255. /**
  1256. * Initialises a new CSS selector
  1257. * @return css_selector
  1258. */
  1259. public static function init() {
  1260. return new css_selector();
  1261. }
  1262. /**
  1263. * CSS selectors can only be created through the init method above.
  1264. */
  1265. protected function __construct() {}
  1266. /**
  1267. * Adds a selector to the end of the current selector
  1268. * @param string $selector
  1269. */
  1270. public function add($selector) {
  1271. $selector = trim($selector);
  1272. $count = 0;
  1273. $count += preg_match_all('/(\.|#)/', $selector, $matchesarray);
  1274. if (strpos($selector, '.') !== 0 && strpos($selector, '#') !== 0) {
  1275. $count ++;
  1276. }
  1277. // If its already false then no need to continue, its not basic
  1278. if ($this->isbasic !== false) {
  1279. // If theres more than one part making up this selector its not basic
  1280. if ($count > 1) {
  1281. $this->isbasic = false;
  1282. } else {
  1283. // Check whether it is a basic element (a-z+) with possible psuedo selector
  1284. $this->isbasic = (bool)preg_match('#^[a-z]+(:[a-zA-Z]+)?$#', $selector);
  1285. }
  1286. }
  1287. $this->count = $count;
  1288. $this->selectors[] = $selector;
  1289. }
  1290. /**
  1291. * Returns the number of individual components that make up this selector
  1292. * @return int
  1293. */
  1294. public function get_selector_count() {
  1295. return $this->count;
  1296. }
  1297. /**
  1298. * Returns the selector for use in a CSS rule
  1299. * @return string
  1300. */
  1301. public function out() {
  1302. return css_writer::selector($this->selectors);
  1303. }
  1304. /**
  1305. * Returns true is all of the selectors act only upon basic elements (no classes/ids)
  1306. * @return bool
  1307. */
  1308. public function is_basic() {
  1309. return ($this->isbasic === true);
  1310. }
  1311. }
  1312. /**
  1313. * A structure to represent a CSS rule.
  1314. *
  1315. * @package core
  1316. * @category css
  1317. * @copyright 2012 Sam Hemelryk
  1318. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  1319. */
  1320. class css_rule {
  1321. /**
  1322. * An array of CSS selectors {@link css_selector}
  1323. * @var array
  1324. */
  1325. protected $selectors = array();
  1326. /**
  1327. * An array of CSS styles {@link css_style}
  1328. * @var array
  1329. */
  1330. protected $styles = array();
  1331. /**
  1332. * Created a new CSS rule. This is the only way to create a new CSS rule externally.
  1333. * @return css_rule
  1334. */
  1335. public static function init() {
  1336. return new css_rule();
  1337. }
  1338. /**
  1339. * Constructs a new css rule.
  1340. *
  1341. * @param string $selector The selector or array of selectors that make up this rule.
  1342. * @param array $styles An array of styles that belong to this rule.
  1343. */
  1344. protected function __construct($selector = null, array $styles = array()) {
  1345. if ($selector != null) {
  1346. if (is_array($selector)) {
  1347. $this->selectors = $selector;
  1348. } else {
  1349. $this->selectors = array($selector);
  1350. }
  1351. $this->add_styles($styles);
  1352. }
  1353. }
  1354. /**
  1355. * Adds a new CSS selector to this rule
  1356. *
  1357. * e.g. $rule->add_selector('.one #two.two');
  1358. *
  1359. * @param css_selector $selector Adds a CSS selector to this rule.
  1360. */
  1361. public function add_selector(css_selector $selector) {
  1362. $this->selectors[] = $selector;
  1363. }
  1364. /**
  1365. * Adds a new CSS style to this rule.
  1366. *
  1367. * @param css_style|string $style Adds a new style to this rule
  1368. */
  1369. public function add_style($style) {
  1370. if (is_string($style)) {
  1371. $style = trim($style);
  1372. if (empty($style)) {
  1373. return;
  1374. }
  1375. $bits = explode(':', $style, 2);
  1376. if (count($bits) == 2) {
  1377. list($name, $value) = array_map('trim', $bits);
  1378. }
  1379. if (isset($name) && isset($value) && $name !== '' && $value !== '') {
  1380. $style = css_style::init_automatic($name, $value);
  1381. }
  1382. } else if ($style instanceof css_style) {
  1383. // Clone the style as it may be coming from another rule and we don't
  1384. // want references as it will likely be overwritten by proceeding
  1385. // rules
  1386. $style = clone($style);
  1387. }
  1388. if ($style instanceof css_style) {
  1389. $name = $style->get_name();
  1390. $exists = array_key_exists($name, $this->styles);
  1391. // We need to find out if the current style support multiple values, or whether the style
  1392. // is already set up to record multiple values. This can happen with background images which can have single
  1393. // and multiple values.
  1394. if ($style->allows_multiple_values() || ($exists && is_array($this->styles[$name]))) {
  1395. if (!$exists) {
  1396. $this->styles[$name] = array();
  1397. } else if ($this->styles[$name] instanceof css_style) {
  1398. $this->styles[$name] = array($this->styles[$name]);
  1399. }
  1400. $this->styles[$name][] = $style;
  1401. } else if ($exists) {
  1402. $this->styles[$name]->set_value($style->get_value());
  1403. } else {
  1404. $this->styles[$name] = $style;
  1405. }
  1406. } else if (is_array($style)) {
  1407. // We probably shouldn't worry about processing styles here but to
  1408. // be truthful it doesn't hurt.
  1409. foreach ($style as $astyle) {
  1410. $this->add_style($astyle);
  1411. }
  1412. }
  1413. }
  1414. /**
  1415. * An easy method of adding several styles at once. Just calls add_style.
  1416. *
  1417. * This method simply iterates over the array and calls {@link css_rule::add_style()}
  1418. * with each.
  1419. *
  1420. * @param array $styles Adds an array of styles
  1421. */
  1422. public function add_styles(array $styles) {
  1423. foreach ($styles as $style) {
  1424. $this->add_style($style);
  1425. }
  1426. }
  1427. /**
  1428. * Returns the array of selectors
  1429. *
  1430. * @return array
  1431. */
  1432. public function get_selectors() {
  1433. return $this->selectors;
  1434. }
  1435. /**
  1436. * Returns the array of styles
  1437. *
  1438. * @return array
  1439. */
  1440. public function get_styles() {
  1441. return $this->styles;
  1442. }
  1443. /**
  1444. * Outputs this rule as a fragment of CSS
  1445. *
  1446. * @return string
  1447. */
  1448. public function out() {
  1449. $selectors = css_writer::selectors($this->selectors);
  1450. $styles = css_writer::styles($this->get_consolidated_styles());
  1451. return css_writer::rule($selectors, $styles);
  1452. }
  1453. /**
  1454. * Consolidates all styles associated with this rule
  1455. *
  1456. * @return array An array of consolidated styles
  1457. */
  1458. public function get_consolidated_styles() {
  1459. $organisedstyles = array();
  1460. $finalstyles = array();
  1461. $consolidate = array();
  1462. $advancedstyles = array();
  1463. foreach ($this->styles as $style) {
  1464. // If the style is an array then we are processing an advanced style. An advanced style is a style that can have
  1465. // one or more values. Background-image is one such example as it can have browser specific styles.
  1466. if (is_array($style)) {
  1467. $single = null;
  1468. $count = 0;
  1469. foreach ($style as $advstyle) {
  1470. $key = $count++;
  1471. $advancedstyles[$key] = $advstyle;
  1472. if (!$advstyle->allows_multiple_values()) {
  1473. if (!is_null($single)) {
  1474. unset($advancedstyles[$single]);
  1475. }
  1476. $single = $key;
  1477. }
  1478. }
  1479. if (!is_null($single)) {
  1480. $style = $advancedstyles[$single];
  1481. $consolidatetoclass = $style->consolidate_to();
  1482. if (($style->is_valid() || $style->is_special_empty_value()) && !empty($consolidatetoclass) && class_exists('css_style_'.$consolidatetoclass)) {
  1483. $class = 'css_style_'.$consolidatetoclass;
  1484. if (!array_key_exists($class, $consolidate)) {
  1485. $consolidate[$class] = array();
  1486. $organisedstyles[$class] = true;
  1487. }
  1488. $consolidate[$class][] = $style;
  1489. unset($advancedstyles[$single]);
  1490. }
  1491. }
  1492. continue;
  1493. }
  1494. $consolidatetoclass = $style->consolidate_to();
  1495. if (($style->is_valid() || $style->is_special_empty_value()) && !empty($consolidatetoclass) && class_exists('css_style_'.$consolidatetoclass)) {
  1496. $class = 'css_style_'.$consolidatetoclass;
  1497. if (!array_key_exists($class, $consolidate)) {
  1498. $consolidate[$class] = array();
  1499. $organisedstyles[$class] = true;
  1500. }
  1501. $consolidate[$class][] = $style;
  1502. } else {
  1503. $organisedstyles[$style->get_name()] = $style;
  1504. }
  1505. }
  1506. foreach ($consolidate as $class => $styles) {
  1507. $organisedstyles[$class] = $class::consolidate($styles);
  1508. }
  1509. foreach ($organisedstyles as $style) {
  1510. if (is_array($style)) {
  1511. foreach ($style as $s) {
  1512. $finalstyles[] = $s;
  1513. }
  1514. } else {
  1515. $finalstyles[] = $style;
  1516. }
  1517. }
  1518. $finalstyles = array_merge($finalstyles, $advancedstyles);
  1519. return $finalstyles;
  1520. }
  1521. /**
  1522. * Splits this rules into an array of CSS rules. One for each of the selectors
  1523. * that make up this rule.
  1524. *
  1525. * @return array(css_rule)
  1526. */
  1527. public function split_by_selector() {
  1528. $return = array();
  1529. foreach ($this->selectors as $selector) {
  1530. $return[] = new css_rule($selector, $this->styles);
  1531. }
  1532. return $return;
  1533. }
  1534. /**
  1535. * Splits this rule into an array of rules. One for each of the styles that
  1536. * make up this rule
  1537. *
  1538. * @return array Array of css_rule objects
  1539. */
  1540. public function split_by_style() {
  1541. $return = array();
  1542. foreach ($this->styles as $style) {
  1543. if (is_array($style)) {
  1544. $return[] = new css_rule($this->selectors, $style);
  1545. continue;
  1546. }
  1547. $return[] = new css_rule($this->selectors, array($style));
  1548. }
  1549. return $return;
  1550. }
  1551. /**
  1552. * Gets a hash for the styles of this rule
  1553. *
  1554. * @return string
  1555. */
  1556. public function get_style_hash() {
  1557. return md5(css_writer::styles($this->styles));
  1558. }
  1559. /**
  1560. * Gets a hash for the selectors of this rule
  1561. *
  1562. * @return string
  1563. */
  1564. public function get_selector_hash() {
  1565. return md5(css_writer::selectors($this->selectors));
  1566. }
  1567. /**
  1568. * Gets the number of selectors that make up this rule.
  1569. *
  1570. * @return int
  1571. */
  1572. public function get_selector_count() {
  1573. $count = 0;
  1574. foreach ($this->selectors as $selector) {
  1575. $count += $selector->get_selector_count();
  1576. }
  1577. return $count;
  1578. }
  1579. /**
  1580. * Returns true if there are any errors with this rule.
  1581. *
  1582. * @return bool
  1583. */
  1584. public function has_errors() {
  1585. foreach ($this->styles as $style) {
  1586. if (is_array($style)) {
  1587. foreach ($style as $advstyle) {
  1588. if ($advstyle->has_error()) {
  1589. return true;
  1590. }
  1591. }
  1592. continue;
  1593. }
  1594. if ($style->has_error()) {
  1595. return true;
  1596. }
  1597. }
  1598. return false;
  1599. }
  1600. /**
  1601. * Returns the error strings that were recorded when processing this rule.
  1602. *
  1603. * Before calling this function you should first call {@link css_rule::has_errors()}
  1604. * to make sure there are errors (hopefully there arn't).
  1605. *
  1606. * @return string
  1607. */
  1608. public function get_error_string() {
  1609. $css = $this->out();
  1610. $errors = array();
  1611. foreach ($this->styles as $style) {
  1612. if ($style->has_error()) {
  1613. $errors[] = " * ".$style->get_last_error();
  1614. }
  1615. }
  1616. return $css." has the following errors:\n".join("\n", $errors);
  1617. }
  1618. /**
  1619. * Returns true if this rule could be considered a reset rule.
  1620. *
  1621. * A reset rule is a rule that acts upon an HTML element and does not include any other parts to its selector.
  1622. *
  1623. * @return bool
  1624. */
  1625. public function is_reset_rule() {
  1626. foreach ($this->selectors as $selector) {
  1627. if (!$selector->is_basic()) {
  1628. return false;
  1629. }
  1630. }
  1631. return true;
  1632. }
  1633. }
  1634. /**
  1635. * An abstract CSS rule collection class.
  1636. *
  1637. * This class is extended by things such as media and keyframe declaration. They are declarations that
  1638. * group rules together for a purpose.
  1639. * When no declaration is specified rules accumulate into @media all.
  1640. *
  1641. * @package core
  1642. * @category css
  1643. * @copyright 2012 Sam Hemelryk
  1644. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  1645. */
  1646. abstract class css_rule_collection {
  1647. /**
  1648. * An array of rules within this collection instance
  1649. * @var array
  1650. */
  1651. protected $rules = array();
  1652. /**
  1653. * The collection must be able to print itself.
  1654. */
  1655. abstract public function out();
  1656. /**
  1657. * Adds a new CSS rule to this collection instance
  1658. *
  1659. * @param css_rule $newrule
  1660. */
  1661. public function add_rule(css_rule $newrule) {
  1662. foreach ($newrule->split_by_selector() as $rule) {
  1663. $hash = $rule->get_selector_hash();
  1664. if (!array_key_exists($hash, $this->rules)) {
  1665. $this->rules[$hash] = $rule;
  1666. } else {
  1667. $this->rules[$hash]->add_styles($rule->get_styles());
  1668. }
  1669. }
  1670. }
  1671. /**
  1672. * Returns the rules used by this collection
  1673. *
  1674. * @return array
  1675. */
  1676. public function get_rules() {
  1677. return $this->rules;
  1678. }
  1679. /**
  1680. * Organises rules by gropuing selectors based upon the styles and consolidating
  1681. * those selectors into single rules.
  1682. *
  1683. * @return bool True if the CSS was optimised by this method
  1684. */
  1685. public function organise_rules_by_selectors() {
  1686. $optimised = array();
  1687. $beforecount = count($this->rules);
  1688. $lasthash = null;
  1689. $lastrule = null;
  1690. foreach ($this->rules as $rule) {
  1691. $hash = $rule->get_style_hash();
  1692. if ($lastrule !== null && $lasthash !== null && $hash === $lasthash) {
  1693. foreach ($rule->get_selectors() as $selector) {
  1694. $lastrule->add_selector($selector);
  1695. }
  1696. continue;
  1697. }
  1698. $lastrule = clone($rule);
  1699. $lasthash = $hash;
  1700. $optimised[] = $lastrule;
  1701. }
  1702. $this->rules = array();
  1703. foreach ($optimised as $optimised) {
  1704. $this->rules[$optimised->get_selector_hash()] = $optimised;
  1705. }
  1706. $aftercount = count($this->rules);
  1707. return ($beforecount < $aftercount);
  1708. }
  1709. /**
  1710. * Returns the total number of rules that exist within this collection
  1711. *
  1712. * @return int
  1713. */
  1714. public function count_rules() {
  1715. return count($this->rules);
  1716. }
  1717. /**
  1718. * Returns the total number of selectors that exist within this collection
  1719. *
  1720. * @return int
  1721. */
  1722. public function count_selectors() {
  1723. $count = 0;
  1724. foreach ($this->rules as $rule) {
  1725. $count += $rule->get_selector_count();
  1726. }
  1727. return $count;
  1728. }
  1729. /**
  1730. * Returns true if the collection has any rules that have errors
  1731. *
  1732. * @return boolean
  1733. */
  1734. public function has_errors() {
  1735. foreach ($this->rules as $rule) {
  1736. if ($rule->has_errors()) {
  1737. return true;
  1738. }
  1739. }
  1740. return false;
  1741. }
  1742. /**
  1743. * Returns any errors that have happened within rules in this collection.
  1744. *
  1745. * @return string
  1746. */
  1747. public function get_errors() {
  1748. $errors = array();
  1749. foreach ($this->rules as $rule) {
  1750. if ($rule->has_errors()) {
  1751. $errors[] = $rule->get_error_string();
  1752. }
  1753. }
  1754. return $errors;
  1755. }
  1756. }
  1757. /**
  1758. * A media class to organise rules by the media they apply to.
  1759. *
  1760. * @package core
  1761. * @category css
  1762. * @copyright 2012 Sam Hemelryk
  1763. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  1764. */
  1765. class css_media extends css_rule_collection {
  1766. /**
  1767. * An array of the different media types this instance applies to.
  1768. * @var array
  1769. */
  1770. protected $types = array();
  1771. /**
  1772. * Initalises a new media instance
  1773. *
  1774. * @param string $for The media that the contained rules are destined for.
  1775. */
  1776. public function __construct($for = 'all') {
  1777. $types = explode(',', $for);
  1778. $this->types = array_map('trim', $types);
  1779. }
  1780. /**
  1781. * Returns the CSS for this media and all of its rules.
  1782. *
  1783. * @return string
  1784. */
  1785. public function out() {
  1786. return css_writer::media(join(',', $this->types), $this->rules);
  1787. }
  1788. /**
  1789. * Returns an array of media that this media instance applies to
  1790. *
  1791. * @return array
  1792. */
  1793. public function get_types() {
  1794. return $this->types;
  1795. }
  1796. /**
  1797. * Returns all of the reset rules known by this media set.
  1798. * @param bool $remove If set to true reset rules will be removed before being returned.
  1799. * @return array
  1800. */
  1801. public function get_reset_rules($remove = false) {
  1802. $resetrules = array();
  1803. foreach ($this->rules as $key => $rule) {
  1804. if ($rule->is_reset_rule()) {
  1805. $resetrules[] = clone $rule;
  1806. if ($remove) {
  1807. unset($this->rules[$key]);
  1808. }
  1809. }
  1810. }
  1811. return $resetrules;
  1812. }
  1813. }
  1814. /**
  1815. * A media class to organise rules by the media they apply to.
  1816. *
  1817. * @package core
  1818. * @category css
  1819. * @copyright 2012 Sam Hemelryk
  1820. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  1821. */
  1822. class css_keyframe extends css_rule_collection {
  1823. /** @var string $for The directive e.g. keyframes, -moz-keyframes, -webkit-keyframes */
  1824. protected $for;
  1825. /** @var string $name The name for the keyframes */
  1826. protected $name;
  1827. /**
  1828. * Constructs a new keyframe
  1829. *
  1830. * @param string $for The directive e.g. keyframes, -moz-keyframes, -webkit-keyframes
  1831. * @param string $name The name for the keyframes
  1832. */
  1833. public function __construct($for, $name) {
  1834. $this->for = $for;
  1835. $this->name = $name;
  1836. }
  1837. /**
  1838. * Returns the directive of this keyframe
  1839. *
  1840. * e.g. keyframes, -moz-keyframes, -webkit-keyframes
  1841. * @return string
  1842. */
  1843. public function get_for() {
  1844. return $this->for;
  1845. }
  1846. /**
  1847. * Returns the name of this keyframe
  1848. * @return string
  1849. */
  1850. public function get_name() {
  1851. return $this->name;
  1852. }
  1853. /**
  1854. * Returns the CSS for this collection of keyframes and all of its rules.
  1855. *
  1856. * @return string
  1857. */
  1858. public function out() {
  1859. return css_writer::keyframe($this->for, $this->name, $this->rules);
  1860. }
  1861. }
  1862. /**
  1863. * An absract class to represent CSS styles
  1864. *
  1865. * @package core
  1866. * @category css
  1867. * @copyright 2012 Sam Hemelryk
  1868. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  1869. */
  1870. abstract class css_style {
  1871. /** Constant used for recongise a special empty value in a CSS style */
  1872. const NULL_VALUE = '@@$NULL$@@';
  1873. /**
  1874. * The name of the style
  1875. * @var string
  1876. */
  1877. protected $name;
  1878. /**
  1879. * The value for the style
  1880. * @var mixed
  1881. */
  1882. protected $value;
  1883. /**
  1884. * If set to true this style was defined with the !important rule.
  1885. * Only trolls use !important.
  1886. * Don't hide under bridges.. its not good for your skin. Do the proper thing
  1887. * and fix the issue don't just force a fix that will undoubtedly one day
  1888. * lead to further frustration.
  1889. * @var bool
  1890. */
  1891. protected $important = false;
  1892. /**
  1893. * Gets set to true if this style has an error
  1894. * @var bool
  1895. */
  1896. protected $error = false;
  1897. /**
  1898. * The last error message that occured
  1899. * @var string
  1900. */
  1901. protected $errormessage = null;
  1902. /**
  1903. * Initialises a new style.
  1904. *
  1905. * This is the only public way to create a style to ensure they that appropriate
  1906. * style class is used if it exists.
  1907. *
  1908. * @param string $name The name of the style.
  1909. * @param string $value The value of the style.
  1910. * @return css_style_generic
  1911. */
  1912. public static function init_automatic($name, $value) {
  1913. $specificclass = 'css_style_'.preg_replace('#[^a-zA-Z0-9]+#', '', $name);
  1914. if (class_exists($specificclass)) {
  1915. return $specificclass::init($value);
  1916. }
  1917. return new css_style_generic($name, $value);
  1918. }
  1919. /**
  1920. * Creates a new style when given its name and value
  1921. *
  1922. * @param string $name The name of the style.
  1923. * @param string $value The value of the style.
  1924. */
  1925. protected function __construct($name, $value) {
  1926. $this->name = $name;
  1927. $this->set_value($value);
  1928. }
  1929. /**
  1930. * Sets the value for the style
  1931. *
  1932. * @param string $value
  1933. */
  1934. final public function set_value($value) {
  1935. $value = trim($value);
  1936. $important = preg_match('#(\!important\s*;?\s*)$#', $value, $matches);
  1937. if ($important) {
  1938. $value = substr($value, 0, -(strlen($matches[1])));
  1939. $value = rtrim($value);
  1940. }
  1941. if (!$this->important || $important) {
  1942. $this->value = $this->clean_value($value);
  1943. $this->important = $important;
  1944. }
  1945. if (!$this->is_valid()) {
  1946. $this->set_error('Invalid value for '.$this->name);
  1947. }
  1948. }
  1949. /**
  1950. * Returns true if the value associated with this style is valid
  1951. *
  1952. * @return bool
  1953. */
  1954. public function is_valid() {
  1955. return true;
  1956. }
  1957. /**
  1958. * Returns the name for the style
  1959. *
  1960. * @return string
  1961. */
  1962. public function get_name() {
  1963. return $this->name;
  1964. }
  1965. /**
  1966. * Returns the value for the style
  1967. *
  1968. * @param bool $includeimportant If set to true and the rule is important !important postfix will be used.
  1969. * @return string
  1970. */
  1971. public function get_value($includeimportant = true) {
  1972. $value = $this->value;
  1973. if ($includeimportant && $this->important) {
  1974. $value .= ' !important';
  1975. }
  1976. return $value;
  1977. }
  1978. /**
  1979. * Returns the style ready for use in CSS
  1980. *
  1981. * @param string|null $value A value to use to override the value for this style.
  1982. * @return string
  1983. */
  1984. public function out($value = null) {
  1985. if (is_null($value)) {
  1986. $value = $this->get_value();
  1987. }
  1988. return css_writer::style($this->name, $value, $this->important);
  1989. }
  1990. /**
  1991. * This can be overridden by a specific style allowing it to clean its values
  1992. * consistently.
  1993. *
  1994. * @param mixed $value
  1995. * @return mixed
  1996. */
  1997. protected function clean_value($value) {
  1998. return $value;
  1999. }
  2000. /**
  2001. * If this particular style can be consolidated into another style this function
  2002. * should return the style that it can be consolidated into.
  2003. *
  2004. * @return string|null
  2005. */
  2006. public function consolidate_to() {
  2007. return null;
  2008. }
  2009. /**
  2010. * Sets the last error message.
  2011. *
  2012. * @param string $message
  2013. */
  2014. protected function set_error($message) {
  2015. $this->error = true;
  2016. $this->errormessage = $message;
  2017. }
  2018. /**
  2019. * Returns true if an error has occured
  2020. *
  2021. * @return bool
  2022. */
  2023. public function has_error() {
  2024. return $this->error;
  2025. }
  2026. /**
  2027. * Returns the last error that occured or null if no errors have happened.
  2028. *
  2029. * @return string
  2030. */
  2031. public function get_last_error() {
  2032. return $this->errormessage;
  2033. }
  2034. /**
  2035. * Returns true if the value for this style is the special null value.
  2036. *
  2037. * This should only be overriden in circumstances where a shorthand style can lead
  2038. * to move explicit styles being overwritten. Not a common place occurenace.
  2039. *
  2040. * Example:
  2041. * This occurs if the shorthand background property was used but no proper value
  2042. * was specified for this style.
  2043. * This leads to a null value being used unless otherwise overridden.
  2044. *
  2045. * @return bool
  2046. */
  2047. public function is_special_empty_value() {
  2048. return false;
  2049. }
  2050. /**
  2051. * Returns true if this style permits multiple values.
  2052. *
  2053. * This occurs for styles such as background image that can have browser specific values that need to be maintained because
  2054. * of course we don't know what browser the user is using, and optimisation occurs before caching.
  2055. * Thus we must always server all values we encounter in the order we encounter them for when this is set to true.
  2056. *
  2057. * @return boolean False by default, true if the style supports muliple values.
  2058. */
  2059. public function allows_multiple_values() {
  2060. return false;
  2061. }
  2062. /**
  2063. * Returns true if this style was marked important.
  2064. * @return bool
  2065. */
  2066. public function is_important() {
  2067. return !empty($this->important);
  2068. }
  2069. /**
  2070. * Sets the important flag for this style and its current value.
  2071. * @param bool $important
  2072. */
  2073. public function set_important($important = true) {
  2074. $this->important = (bool) $important;
  2075. }
  2076. }
  2077. /**
  2078. * A generic CSS style class to use when a more specific class does not exist.
  2079. *
  2080. * @package core
  2081. * @category css
  2082. * @copyright 2012 Sam Hemelryk
  2083. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2084. */
  2085. class css_style_generic extends css_style {
  2086. /**
  2087. * Cleans incoming values for typical things that can be optimised.
  2088. *
  2089. * @param mixed $value Cleans the provided value optimising it if possible
  2090. * @return string
  2091. */
  2092. protected function clean_value($value) {
  2093. if (trim($value) == '0px') {
  2094. $value = 0;
  2095. } else if (preg_match('/^#([a-fA-F0-9]{3,6})/', $value, $matches)) {
  2096. $value = '#'.strtoupper($matches[1]);
  2097. }
  2098. return $value;
  2099. }
  2100. }
  2101. /**
  2102. * A colour CSS style
  2103. *
  2104. * @package core
  2105. * @category css
  2106. * @copyright 2012 Sam Hemelryk
  2107. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2108. */
  2109. class css_style_color extends css_style {
  2110. /**
  2111. * Creates a new colour style
  2112. *
  2113. * @param mixed $value Initialises a new colour style
  2114. * @return css_style_color
  2115. */
  2116. public static function init($value) {
  2117. return new css_style_color('color', $value);
  2118. }
  2119. /**
  2120. * Cleans the colour unifing it to a 6 char hash colour if possible
  2121. * Doing this allows us to associate identical colours being specified in
  2122. * different ways. e.g. Red, red, #F00, and #F00000
  2123. *
  2124. * @param mixed $value Cleans the provided value optimising it if possible
  2125. * @return string
  2126. */
  2127. protected function clean_value($value) {
  2128. $value = trim($value);
  2129. if (css_is_colour($value)) {
  2130. if (preg_match('/#([a-fA-F0-9]{6})/', $value, $matches)) {
  2131. $value = '#'.strtoupper($matches[1]);
  2132. } else if (preg_match('/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/', $value, $matches)) {
  2133. $value = $matches[1] . $matches[1] . $matches[2] . $matches[2] . $matches[3] . $matches[3];
  2134. $value = '#'.strtoupper($value);
  2135. } else if (array_key_exists(strtolower($value), css_optimiser::$htmlcolours)) {
  2136. $value = css_optimiser::$htmlcolours[strtolower($value)];
  2137. }
  2138. }
  2139. return $value;
  2140. }
  2141. /**
  2142. * Returns the colour style for use within CSS.
  2143. * Will return an optimised hash colour.
  2144. *
  2145. * e.g #123456
  2146. * #123 instead of #112233
  2147. * #F00 instead of red
  2148. *
  2149. * @param string $overridevalue If provided then this value will be used instead
  2150. * of the styles current value.
  2151. * @return string
  2152. */
  2153. public function out($overridevalue = null) {
  2154. if ($overridevalue === null) {
  2155. $overridevalue = $this->value;
  2156. }
  2157. return parent::out(self::shrink_value($overridevalue));
  2158. }
  2159. /**
  2160. * Shrinks the colour value is possible.
  2161. *
  2162. * @param string $value Shrinks the current value to an optimial form if possible
  2163. * @return string
  2164. */
  2165. public static function shrink_value($value) {
  2166. if (preg_match('/#([a-fA-F0-9])\1([a-fA-F0-9])\2([a-fA-F0-9])\3/', $value, $matches)) {
  2167. return '#'.$matches[1].$matches[2].$matches[3];
  2168. }
  2169. return $value;
  2170. }
  2171. /**
  2172. * Returns true if the value is a valid colour.
  2173. *
  2174. * @return bool
  2175. */
  2176. public function is_valid() {
  2177. return css_is_colour($this->value);
  2178. }
  2179. }
  2180. /**
  2181. * A width style
  2182. *
  2183. * @package core
  2184. * @category css
  2185. * @copyright 2012 Sam Hemelryk
  2186. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2187. */
  2188. class css_style_width extends css_style {
  2189. /**
  2190. * Checks if the width is valid
  2191. * @return bool
  2192. */
  2193. public function is_valid() {
  2194. return css_is_width($this->value);
  2195. }
  2196. /**
  2197. * Cleans the provided value
  2198. *
  2199. * @param mixed $value Cleans the provided value optimising it if possible
  2200. * @return string
  2201. */
  2202. protected function clean_value($value) {
  2203. if (!css_is_width($value)) {
  2204. // Note we don't actually change the value to something valid. That
  2205. // would be bad for futureproofing.
  2206. $this->set_error('Invalid width specified for '.$this->name);
  2207. } else if (preg_match('#^0\D+$#', $value)) {
  2208. $value = 0;
  2209. }
  2210. return trim($value);
  2211. }
  2212. /**
  2213. * Initialises a new width style
  2214. *
  2215. * @param mixed $value The value this style has
  2216. * @return css_style_width
  2217. */
  2218. public static function init($value) {
  2219. return new css_style_width('width', $value);
  2220. }
  2221. }
  2222. /**
  2223. * A margin style
  2224. *
  2225. * @package core
  2226. * @category css
  2227. * @copyright 2012 Sam Hemelryk
  2228. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2229. */
  2230. class css_style_margin extends css_style_width {
  2231. /**
  2232. * Initialises a margin style.
  2233. *
  2234. * In this case we split the margin into several other margin styles so that
  2235. * we can properly condense overrides and then reconsolidate them later into
  2236. * an optimal form.
  2237. *
  2238. * @param string $value The value the style has
  2239. * @return array An array of margin values that can later be consolidated
  2240. */
  2241. public static function init($value) {
  2242. $important = '';
  2243. if (strpos($value, '!important') !== false) {
  2244. $important = ' !important';
  2245. $value = str_replace('!important', '', $value);
  2246. }
  2247. $value = preg_replace('#\s+#', ' ', trim($value));
  2248. $bits = explode(' ', $value, 4);
  2249. $top = $right = $bottom = $left = null;
  2250. if (count($bits) > 0) {
  2251. $top = $right = $bottom = $left = array_shift($bits);
  2252. }
  2253. if (count($bits) > 0) {
  2254. $right = $left = array_shift($bits);
  2255. }
  2256. if (count($bits) > 0) {
  2257. $bottom = array_shift($bits);
  2258. }
  2259. if (count($bits) > 0) {
  2260. $left = array_shift($bits);
  2261. }
  2262. return array(
  2263. new css_style_margintop('margin-top', $top.$important),
  2264. new css_style_marginright('margin-right', $right.$important),
  2265. new css_style_marginbottom('margin-bottom', $bottom.$important),
  2266. new css_style_marginleft('margin-left', $left.$important)
  2267. );
  2268. }
  2269. /**
  2270. * Consolidates individual margin styles into a single margin style
  2271. *
  2272. * @param array $styles
  2273. * @return array An array of consolidated styles
  2274. */
  2275. public static function consolidate(array $styles) {
  2276. if (count($styles) != 4) {
  2277. return $styles;
  2278. }
  2279. $someimportant = false;
  2280. $allimportant = null;
  2281. $notimportantequal = null;
  2282. $firstvalue = null;
  2283. foreach ($styles as $style) {
  2284. if ($style->is_important()) {
  2285. $someimportant = true;
  2286. if ($allimportant === null) {
  2287. $allimportant = true;
  2288. }
  2289. } else {
  2290. if ($allimportant === true) {
  2291. $allimportant = false;
  2292. }
  2293. if ($firstvalue == null) {
  2294. $firstvalue = $style->get_value(false);
  2295. $notimportantequal = true;
  2296. } else if ($notimportantequal && $firstvalue !== $style->get_value(false)) {
  2297. $notimportantequal = false;
  2298. }
  2299. }
  2300. }
  2301. if ($someimportant && !$allimportant && !$notimportantequal) {
  2302. return $styles;
  2303. }
  2304. if ($someimportant && !$allimportant && $notimportantequal) {
  2305. $return = array(
  2306. new css_style_margin('margin', $firstvalue)
  2307. );
  2308. foreach ($styles as $style) {
  2309. if ($style->is_important()) {
  2310. $return[] = $style;
  2311. }
  2312. }
  2313. return $return;
  2314. } else {
  2315. $top = null;
  2316. $right = null;
  2317. $bottom = null;
  2318. $left = null;
  2319. foreach ($styles as $style) {
  2320. switch ($style->get_name()) {
  2321. case 'margin-top' :
  2322. $top = $style->get_value(false);
  2323. break;
  2324. case 'margin-right' :
  2325. $right = $style->get_value(false);
  2326. break;
  2327. case 'margin-bottom' :
  2328. $bottom = $style->get_value(false);
  2329. break;
  2330. case 'margin-left' :
  2331. $left = $style->get_value(false);
  2332. break;
  2333. }
  2334. }
  2335. if ($top == $bottom && $left == $right) {
  2336. if ($top == $left) {
  2337. $returnstyle = new css_style_margin('margin', $top);
  2338. } else {
  2339. $returnstyle = new css_style_margin('margin', "{$top} {$left}");
  2340. }
  2341. } else if ($left == $right) {
  2342. $returnstyle = new css_style_margin('margin', "{$top} {$right} {$bottom}");
  2343. } else {
  2344. $returnstyle = new css_style_margin('margin', "{$top} {$right} {$bottom} {$left}");
  2345. }
  2346. if ($allimportant) {
  2347. $returnstyle->set_important();
  2348. }
  2349. return array($returnstyle);
  2350. }
  2351. }
  2352. }
  2353. /**
  2354. * A margin top style
  2355. *
  2356. * @package core
  2357. * @category css
  2358. * @copyright 2012 Sam Hemelryk
  2359. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2360. */
  2361. class css_style_margintop extends css_style_margin {
  2362. /**
  2363. * A simple init, just a single style
  2364. *
  2365. * @param string $value The value the style has
  2366. * @return css_style_margintop
  2367. */
  2368. public static function init($value) {
  2369. return new css_style_margintop('margin-top', $value);
  2370. }
  2371. /**
  2372. * This style can be consolidated into a single margin style
  2373. *
  2374. * @return string
  2375. */
  2376. public function consolidate_to() {
  2377. return 'margin';
  2378. }
  2379. }
  2380. /**
  2381. * A margin right style
  2382. *
  2383. * @package core
  2384. * @category css
  2385. * @copyright 2012 Sam Hemelryk
  2386. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2387. */
  2388. class css_style_marginright extends css_style_margin {
  2389. /**
  2390. * A simple init, just a single style
  2391. *
  2392. * @param string $value The value the style has
  2393. * @return css_style_margintop
  2394. */
  2395. public static function init($value) {
  2396. return new css_style_marginright('margin-right', $value);
  2397. }
  2398. /**
  2399. * This style can be consolidated into a single margin style
  2400. *
  2401. * @return string
  2402. */
  2403. public function consolidate_to() {
  2404. return 'margin';
  2405. }
  2406. }
  2407. /**
  2408. * A margin bottom style
  2409. *
  2410. * @package core
  2411. * @category css
  2412. * @copyright 2012 Sam Hemelryk
  2413. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2414. */
  2415. class css_style_marginbottom extends css_style_margin {
  2416. /**
  2417. * A simple init, just a single style
  2418. *
  2419. * @param string $value The value the style has
  2420. * @return css_style_margintop
  2421. */
  2422. public static function init($value) {
  2423. return new css_style_marginbottom('margin-bottom', $value);
  2424. }
  2425. /**
  2426. * This style can be consolidated into a single margin style
  2427. *
  2428. * @return string
  2429. */
  2430. public function consolidate_to() {
  2431. return 'margin';
  2432. }
  2433. }
  2434. /**
  2435. * A margin left style
  2436. *
  2437. * @package core
  2438. * @category css
  2439. * @copyright 2012 Sam Hemelryk
  2440. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2441. */
  2442. class css_style_marginleft extends css_style_margin {
  2443. /**
  2444. * A simple init, just a single style
  2445. *
  2446. * @param string $value The value the style has
  2447. * @return css_style_margintop
  2448. */
  2449. public static function init($value) {
  2450. return new css_style_marginleft('margin-left', $value);
  2451. }
  2452. /**
  2453. * This style can be consolidated into a single margin style
  2454. *
  2455. * @return string
  2456. */
  2457. public function consolidate_to() {
  2458. return 'margin';
  2459. }
  2460. }
  2461. /**
  2462. * A border style
  2463. *
  2464. * @package core
  2465. * @category css
  2466. * @copyright 2012 Sam Hemelryk
  2467. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2468. */
  2469. class css_style_border extends css_style {
  2470. /**
  2471. * Initalises the border style into an array of individual style compontents
  2472. *
  2473. * @param string $value The value the style has
  2474. * @return css_style_bordercolor
  2475. */
  2476. public static function init($value) {
  2477. $value = preg_replace('#\s+#', ' ', $value);
  2478. $bits = explode(' ', $value, 3);
  2479. $return = array();
  2480. if (count($bits) > 0) {
  2481. $width = array_shift($bits);
  2482. if (!css_style_borderwidth::is_border_width($width)) {
  2483. $width = '0';
  2484. }
  2485. $return[] = new css_style_borderwidth('border-top-width', $width);
  2486. $return[] = new css_style_borderwidth('border-right-width', $width);
  2487. $return[] = new css_style_borderwidth('border-bottom-width', $width);
  2488. $return[] = new css_style_borderwidth('border-left-width', $width);
  2489. }
  2490. if (count($bits) > 0) {
  2491. $style = array_shift($bits);
  2492. $return[] = new css_style_borderstyle('border-top-style', $style);
  2493. $return[] = new css_style_borderstyle('border-right-style', $style);
  2494. $return[] = new css_style_borderstyle('border-bottom-style', $style);
  2495. $return[] = new css_style_borderstyle('border-left-style', $style);
  2496. }
  2497. if (count($bits) > 0) {
  2498. $colour = array_shift($bits);
  2499. $return[] = new css_style_bordercolor('border-top-color', $colour);
  2500. $return[] = new css_style_bordercolor('border-right-color', $colour);
  2501. $return[] = new css_style_bordercolor('border-bottom-color', $colour);
  2502. $return[] = new css_style_bordercolor('border-left-color', $colour);
  2503. }
  2504. return $return;
  2505. }
  2506. /**
  2507. * Consolidates all border styles into a single style
  2508. *
  2509. * @param array $styles An array of border styles
  2510. * @return array An optimised array of border styles
  2511. */
  2512. public static function consolidate(array $styles) {
  2513. $borderwidths = array('top' => null, 'right' => null, 'bottom' => null, 'left' => null);
  2514. $borderstyles = array('top' => null, 'right' => null, 'bottom' => null, 'left' => null);
  2515. $bordercolors = array('top' => null, 'right' => null, 'bottom' => null, 'left' => null);
  2516. foreach ($styles as $style) {
  2517. switch ($style->get_name()) {
  2518. case 'border-top-width':
  2519. $borderwidths['top'] = $style->get_value();
  2520. break;
  2521. case 'border-right-width':
  2522. $borderwidths['right'] = $style->get_value();
  2523. break;
  2524. case 'border-bottom-width':
  2525. $borderwidths['bottom'] = $style->get_value();
  2526. break;
  2527. case 'border-left-width':
  2528. $borderwidths['left'] = $style->get_value();
  2529. break;
  2530. case 'border-top-style':
  2531. $borderstyles['top'] = $style->get_value();
  2532. break;
  2533. case 'border-right-style':
  2534. $borderstyles['right'] = $style->get_value();
  2535. break;
  2536. case 'border-bottom-style':
  2537. $borderstyles['bottom'] = $style->get_value();
  2538. break;
  2539. case 'border-left-style':
  2540. $borderstyles['left'] = $style->get_value();
  2541. break;
  2542. case 'border-top-color':
  2543. $bordercolors['top'] = css_style_color::shrink_value($style->get_value());
  2544. break;
  2545. case 'border-right-color':
  2546. $bordercolors['right'] = css_style_color::shrink_value($style->get_value());
  2547. break;
  2548. case 'border-bottom-color':
  2549. $bordercolors['bottom'] = css_style_color::shrink_value($style->get_value());
  2550. break;
  2551. case 'border-left-color':
  2552. $bordercolors['left'] = css_style_color::shrink_value($style->get_value());
  2553. break;
  2554. }
  2555. }
  2556. $uniquewidths = count(array_unique($borderwidths));
  2557. $uniquestyles = count(array_unique($borderstyles));
  2558. $uniquecolors = count(array_unique($bordercolors));
  2559. $nullwidths = in_array(null, $borderwidths, true);
  2560. $nullstyles = in_array(null, $borderstyles, true);
  2561. $nullcolors = in_array(null, $bordercolors, true);
  2562. $allwidthsthesame = ($uniquewidths === 1)?1:0;
  2563. $allstylesthesame = ($uniquestyles === 1)?1:0;
  2564. $allcolorsthesame = ($uniquecolors === 1)?1:0;
  2565. $allwidthsnull = $allwidthsthesame && $nullwidths;
  2566. $allstylesnull = $allstylesthesame && $nullstyles;
  2567. $allcolorsnull = $allcolorsthesame && $nullcolors;
  2568. $return = array();
  2569. if ($allwidthsnull && $allstylesnull && $allcolorsnull) {
  2570. // Everything is null still... boo
  2571. return array(new css_style_border('border', ''));
  2572. } else if ($allwidthsnull && $allstylesnull) {
  2573. self::consolidate_styles_by_direction($return, 'css_style_bordercolor', 'border-color', $bordercolors);
  2574. return $return;
  2575. } else if ($allwidthsnull && $allcolorsnull) {
  2576. self::consolidate_styles_by_direction($return, 'css_style_borderstyle', 'border-style', $borderstyles);
  2577. return $return;
  2578. } else if ($allcolorsnull && $allstylesnull) {
  2579. self::consolidate_styles_by_direction($return, 'css_style_borderwidth', 'border-width', $borderwidths);
  2580. return $return;
  2581. }
  2582. if ($allwidthsthesame + $allstylesthesame + $allcolorsthesame == 3) {
  2583. $return[] = new css_style_border('border', $borderwidths['top'].' '.$borderstyles['top'].' '.$bordercolors['top']);
  2584. } else if ($allwidthsthesame + $allstylesthesame + $allcolorsthesame == 2) {
  2585. if ($allwidthsthesame && $allstylesthesame && !$nullwidths && !$nullstyles) {
  2586. $return[] = new css_style_border('border', $borderwidths['top'].' '.$borderstyles['top']);
  2587. self::consolidate_styles_by_direction($return, 'css_style_bordercolor', 'border-color', $bordercolors);
  2588. } else if ($allwidthsthesame && $allcolorsthesame && !$nullwidths && !$nullcolors) {
  2589. $return[] = new css_style_border('border', $borderwidths['top'].' solid '.$bordercolors['top']);
  2590. self::consolidate_styles_by_direction($return, 'css_style_borderstyle', 'border-style', $borderstyles);
  2591. } else if ($allstylesthesame && $allcolorsthesame && !$nullstyles && !$nullcolors) {
  2592. $return[] = new css_style_border('border', '1px '.$borderstyles['top'].' '.$bordercolors['top']);
  2593. self::consolidate_styles_by_direction($return, 'css_style_borderwidth', 'border-width', $borderwidths);
  2594. } else {
  2595. self::consolidate_styles_by_direction($return, 'css_style_borderwidth', 'border-width', $borderwidths);
  2596. self::consolidate_styles_by_direction($return, 'css_style_borderstyle', 'border-style', $borderstyles);
  2597. self::consolidate_styles_by_direction($return, 'css_style_bordercolor', 'border-color', $bordercolors);
  2598. }
  2599. } else if (!$nullwidths && !$nullcolors && !$nullstyles && max(array_count_values($borderwidths)) == 3 && max(array_count_values($borderstyles)) == 3 && max(array_count_values($bordercolors)) == 3) {
  2600. $widthkeys = array();
  2601. $stylekeys = array();
  2602. $colorkeys = array();
  2603. foreach ($borderwidths as $key => $value) {
  2604. if (!array_key_exists($value, $widthkeys)) {
  2605. $widthkeys[$value] = array();
  2606. }
  2607. $widthkeys[$value][] = $key;
  2608. }
  2609. usort($widthkeys, 'css_sort_by_count');
  2610. $widthkeys = array_values($widthkeys);
  2611. foreach ($borderstyles as $key => $value) {
  2612. if (!array_key_exists($value, $stylekeys)) {
  2613. $stylekeys[$value] = array();
  2614. }
  2615. $stylekeys[$value][] = $key;
  2616. }
  2617. usort($stylekeys, 'css_sort_by_count');
  2618. $stylekeys = array_values($stylekeys);
  2619. foreach ($bordercolors as $key => $value) {
  2620. if (!array_key_exists($value, $colorkeys)) {
  2621. $colorkeys[$value] = array();
  2622. }
  2623. $colorkeys[$value][] = $key;
  2624. }
  2625. usort($colorkeys, 'css_sort_by_count');
  2626. $colorkeys = array_values($colorkeys);
  2627. if ($widthkeys == $stylekeys && $stylekeys == $colorkeys) {
  2628. $key = $widthkeys[0][0];
  2629. self::build_style_string($return, 'css_style_border', 'border', $borderwidths[$key], $borderstyles[$key], $bordercolors[$key]);
  2630. $key = $widthkeys[1][0];
  2631. self::build_style_string($return, 'css_style_border'.$key, 'border-'.$key, $borderwidths[$key], $borderstyles[$key], $bordercolors[$key]);
  2632. } else {
  2633. self::build_style_string($return, 'css_style_bordertop', 'border-top', $borderwidths['top'], $borderstyles['top'], $bordercolors['top']);
  2634. self::build_style_string($return, 'css_style_borderright', 'border-right', $borderwidths['right'], $borderstyles['right'], $bordercolors['right']);
  2635. self::build_style_string($return, 'css_style_borderbottom', 'border-bottom', $borderwidths['bottom'], $borderstyles['bottom'], $bordercolors['bottom']);
  2636. self::build_style_string($return, 'css_style_borderleft', 'border-left', $borderwidths['left'], $borderstyles['left'], $bordercolors['left']);
  2637. }
  2638. } else {
  2639. self::build_style_string($return, 'css_style_bordertop', 'border-top', $borderwidths['top'], $borderstyles['top'], $bordercolors['top']);
  2640. self::build_style_string($return, 'css_style_borderright', 'border-right', $borderwidths['right'], $borderstyles['right'], $bordercolors['right']);
  2641. self::build_style_string($return, 'css_style_borderbottom', 'border-bottom', $borderwidths['bottom'], $borderstyles['bottom'], $bordercolors['bottom']);
  2642. self::build_style_string($return, 'css_style_borderleft', 'border-left', $borderwidths['left'], $borderstyles['left'], $bordercolors['left']);
  2643. }
  2644. foreach ($return as $key => $style) {
  2645. if ($style->get_value() == '') {
  2646. unset($return[$key]);
  2647. }
  2648. }
  2649. return $return;
  2650. }
  2651. /**
  2652. * Border styles get consolidated to a single border style.
  2653. *
  2654. * @return string
  2655. */
  2656. public function consolidate_to() {
  2657. return 'border';
  2658. }
  2659. /**
  2660. * Consolidates a series of border styles into an optimised array of border
  2661. * styles by looking at the direction of the border and prioritising that
  2662. * during the optimisation.
  2663. *
  2664. * @param array $array An array to add styles into during consolidation. Passed by reference.
  2665. * @param string $class The class type to initalise
  2666. * @param string $style The style to create
  2667. * @param string|array $top The top value
  2668. * @param string $right The right value
  2669. * @param string $bottom The bottom value
  2670. * @param string $left The left value
  2671. * @return bool
  2672. */
  2673. public static function consolidate_styles_by_direction(&$array, $class, $style, $top, $right = null, $bottom = null, $left = null) {
  2674. if (is_array($top)) {
  2675. $right = $top['right'];
  2676. $bottom = $top['bottom'];
  2677. $left = $top['left'];
  2678. $top = $top['top'];
  2679. }
  2680. if ($top == $bottom && $left == $right && $top == $left) {
  2681. if (is_null($top)) {
  2682. $array[] = new $class($style, '');
  2683. } else {
  2684. $array[] = new $class($style, $top);
  2685. }
  2686. } else if ($top == null || $right == null || $bottom == null || $left == null) {
  2687. if ($top !== null) {
  2688. $array[] = new $class(str_replace('border-', 'border-top-', $style), $top);
  2689. }
  2690. if ($right !== null) {
  2691. $array[] = new $class(str_replace('border-', 'border-right-', $style), $right);
  2692. }
  2693. if ($bottom !== null) {
  2694. $array[] = new $class(str_replace('border-', 'border-bottom-', $style), $bottom);
  2695. }
  2696. if ($left !== null) {
  2697. $array[] = new $class(str_replace('border-', 'border-left-', $style), $left);
  2698. }
  2699. } else if ($top == $bottom && $left == $right) {
  2700. $array[] = new $class($style, $top.' '.$right);
  2701. } else if ($left == $right) {
  2702. $array[] = new $class($style, $top.' '.$right.' '.$bottom);
  2703. } else {
  2704. $array[] = new $class($style, $top.' '.$right.' '.$bottom.' '.$left);
  2705. }
  2706. return true;
  2707. }
  2708. /**
  2709. * Builds a border style for a set of width, style, and colour values
  2710. *
  2711. * @param array $array An array into which the generated style is added
  2712. * @param string $class The class type to initialise
  2713. * @param string $cssstyle The style to use
  2714. * @param string $width The width of the border
  2715. * @param string $style The style of the border
  2716. * @param string $color The colour of the border
  2717. * @return bool
  2718. */
  2719. public static function build_style_string(&$array, $class, $cssstyle, $width = null, $style = null, $color = null) {
  2720. if (!is_null($width) && !is_null($style) && !is_null($color)) {
  2721. $array[] = new $class($cssstyle, $width.' '.$style.' '.$color);
  2722. } else if (!is_null($width) && !is_null($style) && is_null($color)) {
  2723. $array[] = new $class($cssstyle, $width.' '.$style);
  2724. } else if (!is_null($width) && is_null($style) && is_null($color)) {
  2725. $array[] = new $class($cssstyle, $width);
  2726. } else {
  2727. if (!is_null($width)) {
  2728. $array[] = new $class($cssstyle, $width);
  2729. }
  2730. if (!is_null($style)) {
  2731. $array[] = new $class($cssstyle, $style);
  2732. }
  2733. if (!is_null($color)) {
  2734. $array[] = new $class($cssstyle, $color);
  2735. }
  2736. }
  2737. return true;
  2738. }
  2739. }
  2740. /**
  2741. * A border colour style
  2742. *
  2743. * @package core
  2744. * @category css
  2745. * @copyright 2012 Sam Hemelryk
  2746. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2747. */
  2748. class css_style_bordercolor extends css_style_color {
  2749. /**
  2750. * Creates a new border colour style
  2751. *
  2752. * Based upon the colour style
  2753. *
  2754. * @param mixed $value
  2755. * @return Array of css_style_bordercolor
  2756. */
  2757. public static function init($value) {
  2758. $value = preg_replace('#\s+#', ' ', $value);
  2759. $bits = explode(' ', $value, 4);
  2760. $top = $right = $bottom = $left = null;
  2761. if (count($bits) > 0) {
  2762. $top = $right = $bottom = $left = array_shift($bits);
  2763. }
  2764. if (count($bits) > 0) {
  2765. $right = $left = array_shift($bits);
  2766. }
  2767. if (count($bits) > 0) {
  2768. $bottom = array_shift($bits);
  2769. }
  2770. if (count($bits) > 0) {
  2771. $left = array_shift($bits);
  2772. }
  2773. return array(
  2774. css_style_bordertopcolor::init($top),
  2775. css_style_borderrightcolor::init($right),
  2776. css_style_borderbottomcolor::init($bottom),
  2777. css_style_borderleftcolor::init($left)
  2778. );
  2779. }
  2780. /**
  2781. * Consolidate this to a single border style
  2782. *
  2783. * @return string
  2784. */
  2785. public function consolidate_to() {
  2786. return 'border';
  2787. }
  2788. /**
  2789. * Cleans the value
  2790. *
  2791. * @param string $value Cleans the provided value optimising it if possible
  2792. * @return string
  2793. */
  2794. protected function clean_value($value) {
  2795. $values = explode(' ', $value);
  2796. $values = array_map('parent::clean_value', $values);
  2797. return join (' ', $values);
  2798. }
  2799. /**
  2800. * Outputs this style
  2801. *
  2802. * @param string $overridevalue
  2803. * @return string
  2804. */
  2805. public function out($overridevalue = null) {
  2806. if ($overridevalue === null) {
  2807. $overridevalue = $this->value;
  2808. }
  2809. $values = explode(' ', $overridevalue);
  2810. $values = array_map('css_style_color::shrink_value', $values);
  2811. return parent::out(join (' ', $values));
  2812. }
  2813. }
  2814. /**
  2815. * A border left style
  2816. *
  2817. * @package core
  2818. * @category css
  2819. * @copyright 2012 Sam Hemelryk
  2820. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2821. */
  2822. class css_style_borderleft extends css_style_generic {
  2823. /**
  2824. * Initialises the border left style into individual components
  2825. *
  2826. * @param string $value
  2827. * @return array Array of css_style_borderleftwidth|css_style_borderleftstyle|css_style_borderleftcolor
  2828. */
  2829. public static function init($value) {
  2830. $value = preg_replace('#\s+#', ' ', $value);
  2831. $bits = explode(' ', $value, 3);
  2832. $return = array();
  2833. if (count($bits) > 0) {
  2834. $return[] = css_style_borderleftwidth::init(array_shift($bits));
  2835. }
  2836. if (count($bits) > 0) {
  2837. $return[] = css_style_borderleftstyle::init(array_shift($bits));
  2838. }
  2839. if (count($bits) > 0) {
  2840. $return[] = css_style_borderleftcolor::init(array_shift($bits));
  2841. }
  2842. return $return;
  2843. }
  2844. /**
  2845. * Consolidate this to a single border style
  2846. *
  2847. * @return string
  2848. */
  2849. public function consolidate_to() {
  2850. return 'border';
  2851. }
  2852. }
  2853. /**
  2854. * A border right style
  2855. *
  2856. * @package core
  2857. * @category css
  2858. * @copyright 2012 Sam Hemelryk
  2859. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2860. */
  2861. class css_style_borderright extends css_style_generic {
  2862. /**
  2863. * Initialises the border right style into individual components
  2864. *
  2865. * @param string $value The value of the style
  2866. * @return array Array of css_style_borderrightwidth|css_style_borderrightstyle|css_style_borderrightcolor
  2867. */
  2868. public static function init($value) {
  2869. $value = preg_replace('#\s+#', ' ', $value);
  2870. $bits = explode(' ', $value, 3);
  2871. $return = array();
  2872. if (count($bits) > 0) {
  2873. $return[] = css_style_borderrightwidth::init(array_shift($bits));
  2874. }
  2875. if (count($bits) > 0) {
  2876. $return[] = css_style_borderrightstyle::init(array_shift($bits));
  2877. }
  2878. if (count($bits) > 0) {
  2879. $return[] = css_style_borderrightcolor::init(array_shift($bits));
  2880. }
  2881. return $return;
  2882. }
  2883. /**
  2884. * Consolidate this to a single border style
  2885. *
  2886. * @return string
  2887. */
  2888. public function consolidate_to() {
  2889. return 'border';
  2890. }
  2891. }
  2892. /**
  2893. * A border top style
  2894. *
  2895. * @package core
  2896. * @category css
  2897. * @copyright 2012 Sam Hemelryk
  2898. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2899. */
  2900. class css_style_bordertop extends css_style_generic {
  2901. /**
  2902. * Initialises the border top style into individual components
  2903. *
  2904. * @param string $value The value of the style
  2905. * @return array Array of css_style_bordertopwidth|css_style_bordertopstyle|css_style_bordertopcolor
  2906. */
  2907. public static function init($value) {
  2908. $value = preg_replace('#\s+#', ' ', $value);
  2909. $bits = explode(' ', $value, 3);
  2910. $return = array();
  2911. if (count($bits) > 0) {
  2912. $return[] = css_style_bordertopwidth::init(array_shift($bits));
  2913. }
  2914. if (count($bits) > 0) {
  2915. $return[] = css_style_bordertopstyle::init(array_shift($bits));
  2916. }
  2917. if (count($bits) > 0) {
  2918. $return[] = css_style_bordertopcolor::init(array_shift($bits));
  2919. }
  2920. return $return;
  2921. }
  2922. /**
  2923. * Consolidate this to a single border style
  2924. *
  2925. * @return string
  2926. */
  2927. public function consolidate_to() {
  2928. return 'border';
  2929. }
  2930. }
  2931. /**
  2932. * A border bottom style
  2933. *
  2934. * @package core
  2935. * @category css
  2936. * @copyright 2012 Sam Hemelryk
  2937. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2938. */
  2939. class css_style_borderbottom extends css_style_generic {
  2940. /**
  2941. * Initialises the border bottom style into individual components
  2942. *
  2943. * @param string $value The value of the style
  2944. * @return array Array of css_style_borderbottomwidth|css_style_borderbottomstyle|css_style_borderbottomcolor
  2945. */
  2946. public static function init($value) {
  2947. $value = preg_replace('#\s+#', ' ', $value);
  2948. $bits = explode(' ', $value, 3);
  2949. $return = array();
  2950. if (count($bits) > 0) {
  2951. $return[] = css_style_borderbottomwidth::init(array_shift($bits));
  2952. }
  2953. if (count($bits) > 0) {
  2954. $return[] = css_style_borderbottomstyle::init(array_shift($bits));
  2955. }
  2956. if (count($bits) > 0) {
  2957. $return[] = css_style_borderbottomcolor::init(array_shift($bits));
  2958. }
  2959. return $return;
  2960. }
  2961. /**
  2962. * Consolidate this to a single border style
  2963. *
  2964. * @return string
  2965. */
  2966. public function consolidate_to() {
  2967. return 'border';
  2968. }
  2969. }
  2970. /**
  2971. * A border width style
  2972. *
  2973. * @package core
  2974. * @category css
  2975. * @copyright 2012 Sam Hemelryk
  2976. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2977. */
  2978. class css_style_borderwidth extends css_style_width {
  2979. /**
  2980. * Creates a new border colour style
  2981. *
  2982. * Based upon the colour style
  2983. *
  2984. * @param string $value The value of the style
  2985. * @return array Array of css_style_border*width
  2986. */
  2987. public static function init($value) {
  2988. $value = preg_replace('#\s+#', ' ', $value);
  2989. $bits = explode(' ', $value, 4);
  2990. $top = $right = $bottom = $left = null;
  2991. if (count($bits) > 0) {
  2992. $top = $right = $bottom = $left = array_shift($bits);
  2993. }
  2994. if (count($bits) > 0) {
  2995. $right = $left = array_shift($bits);
  2996. }
  2997. if (count($bits) > 0) {
  2998. $bottom = array_shift($bits);
  2999. }
  3000. if (count($bits) > 0) {
  3001. $left = array_shift($bits);
  3002. }
  3003. return array(
  3004. css_style_bordertopwidth::init($top),
  3005. css_style_borderrightwidth::init($right),
  3006. css_style_borderbottomwidth::init($bottom),
  3007. css_style_borderleftwidth::init($left)
  3008. );
  3009. }
  3010. /**
  3011. * Consolidate this to a single border style
  3012. *
  3013. * @return string
  3014. */
  3015. public function consolidate_to() {
  3016. return 'border';
  3017. }
  3018. /**
  3019. * Checks if the width is valid
  3020. * @return bool
  3021. */
  3022. public function is_valid() {
  3023. return self::is_border_width($this->value);
  3024. }
  3025. /**
  3026. * Cleans the provided value
  3027. *
  3028. * @param mixed $value Cleans the provided value optimising it if possible
  3029. * @return string
  3030. */
  3031. protected function clean_value($value) {
  3032. $isvalid = self::is_border_width($value);
  3033. if (!$isvalid) {
  3034. $this->set_error('Invalid width specified for '.$this->name);
  3035. } else if (preg_match('#^0\D+$#', $value)) {
  3036. return '0';
  3037. }
  3038. return trim($value);
  3039. }
  3040. /**
  3041. * Returns true if the provided value is a permitted border width
  3042. * @param string $value The value to check
  3043. * @return bool
  3044. */
  3045. public static function is_border_width($value) {
  3046. $altwidthvalues = array('thin', 'medium', 'thick');
  3047. return css_is_width($value) || in_array($value, $altwidthvalues);
  3048. }
  3049. }
  3050. /**
  3051. * A border style style
  3052. *
  3053. * @package core
  3054. * @category css
  3055. * @copyright 2012 Sam Hemelryk
  3056. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  3057. */
  3058. class css_style_borderstyle extends css_style_generic {
  3059. /**
  3060. * Creates a new border colour style
  3061. *
  3062. * Based upon the colour style
  3063. *
  3064. * @param string $value The value of the style
  3065. * @return array Array of css_style_border*style
  3066. */
  3067. public static function init($value) {
  3068. $value = preg_replace('#\s+#', ' ', $value);
  3069. $bits = explode(' ', $value, 4);
  3070. $top = $right = $bottom = $left = null;
  3071. if (count($bits) > 0) {
  3072. $top = $right = $bottom = $left = array_shift($bits);
  3073. }
  3074. if (count($bits) > 0) {
  3075. $right = $left = array_shift($bits);
  3076. }
  3077. if (count($bits) > 0) {
  3078. $bottom = array_shift($bits);
  3079. }
  3080. if (count($bits) > 0) {
  3081. $left = array_shift($bits);
  3082. }
  3083. return array(
  3084. css_style_bordertopstyle::init($top),
  3085. css_style_borderrightstyle::init($right),
  3086. css_style_borderbottomstyle::init($bottom),
  3087. css_style_borderleftstyle::init($left)
  3088. );
  3089. }
  3090. /**
  3091. * Consolidate this to a single border style
  3092. *
  3093. * @return string
  3094. */
  3095. public function consolidate_to() {
  3096. return 'border';
  3097. }
  3098. }
  3099. /**
  3100. * A border top colour style
  3101. *
  3102. * @package core
  3103. * @category css
  3104. * @copyright 2012 Sam Hemelryk
  3105. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  3106. */
  3107. class css_style_bordertopcolor extends css_style_bordercolor {
  3108. /**
  3109. * Initialises this style object
  3110. *
  3111. * @param string $value The value of the style
  3112. * @return css_style_bordertopcolor
  3113. */
  3114. public static function init($value) {
  3115. return new css_style_bordertopcolor('border-top-color', $value);
  3116. }
  3117. /**
  3118. * Consolidate this to a single border style
  3119. *
  3120. * @return string
  3121. */
  3122. public function consolidate_to() {
  3123. return 'border';
  3124. }
  3125. }
  3126. /**
  3127. * A border left colour style
  3128. *
  3129. * @package core
  3130. * @category css
  3131. * @copyright 2012 Sam Hemelryk
  3132. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  3133. */
  3134. class css_style_borderleftcolor extends css_style_bordercolor {
  3135. /**
  3136. * Initialises this style object
  3137. *
  3138. * @param string $value The value of the style
  3139. * @return css_style_borderleftcolor
  3140. */
  3141. public static function init($value) {
  3142. return new css_style_borderleftcolor('border-left-color', $value);
  3143. }
  3144. /**
  3145. * Consolidate this to a single border style
  3146. *
  3147. * @return string
  3148. */
  3149. public function consolidate_to() {
  3150. return 'border';
  3151. }
  3152. }
  3153. /**
  3154. * A border right colour style
  3155. *
  3156. * @package core
  3157. * @category css
  3158. * @copyright 2012 Sam Hemelryk
  3159. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  3160. */
  3161. class css_style_borderrightcolor extends css_style_bordercolor {
  3162. /**
  3163. * Initialises this style object
  3164. *
  3165. * @param string $value The value of the style
  3166. * @return css_style_borderrightcolor
  3167. */
  3168. public static function init($value) {
  3169. return new css_style_borderrightcolor('border-right-color', $value);
  3170. }
  3171. /**
  3172. * Consolidate this to a single border style
  3173. *
  3174. * @return string
  3175. */
  3176. public function consolidate_to() {
  3177. return 'border';
  3178. }
  3179. }
  3180. /**
  3181. * A border bottom colour style
  3182. *
  3183. * @package core
  3184. * @category css
  3185. * @copyright 2012 Sam Hemelryk
  3186. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  3187. */
  3188. class css_style_borderbottomcolor extends css_style_bordercolor {
  3189. /**
  3190. * Initialises this style object
  3191. *
  3192. * @param string $value The value of the style
  3193. * @return css_style_borderbottomcolor
  3194. */
  3195. public static function init($value) {
  3196. return new css_style_borderbottomcolor('border-bottom-color', $value);
  3197. }
  3198. /**
  3199. * Consolidate this to a single border style
  3200. *
  3201. * @return string
  3202. */
  3203. public function consolidate_to() {
  3204. return 'border';
  3205. }
  3206. }
  3207. /**
  3208. * A border width top style
  3209. *
  3210. * @package core
  3211. * @category css
  3212. * @copyright 2012 Sam Hemelryk
  3213. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  3214. */
  3215. class css_style_bordertopwidth extends css_style_borderwidth {
  3216. /**
  3217. * Initialises this style object
  3218. *
  3219. * @param string $value The value of the style
  3220. * @return css_style_bordertopwidth
  3221. */
  3222. public static function init($value) {
  3223. return new css_style_bordertopwidth('border-top-width', $value);
  3224. }
  3225. /**
  3226. * Consolidate this to a single border style
  3227. *
  3228. * @return string
  3229. */
  3230. public function consolidate_to() {
  3231. return 'border';
  3232. }
  3233. }
  3234. /**
  3235. * A border width left style
  3236. *
  3237. * @package core
  3238. * @category css
  3239. * @copyright 2012 Sam Hemelryk
  3240. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  3241. */
  3242. class css_style_borderleftwidth extends css_style_borderwidth {
  3243. /**
  3244. * Initialises this style object
  3245. *
  3246. * @param string $value The value of the style
  3247. * @return css_style_borderleftwidth
  3248. */
  3249. public static function init($value) {
  3250. return new css_style_borderleftwidth('border-left-width', $value);
  3251. }
  3252. /**
  3253. * Consolidate this to a single border style
  3254. *
  3255. * @return string
  3256. */
  3257. public function consolidate_to() {
  3258. return 'border';
  3259. }
  3260. }
  3261. /**
  3262. * A border width right style
  3263. *
  3264. * @package core
  3265. * @category css
  3266. * @copyright 2012 Sam Hemelryk
  3267. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  3268. */
  3269. class css_style_borderrightwidth extends css_style_borderwidth {
  3270. /**
  3271. * Initialises this style object
  3272. *
  3273. * @param string $value The value of the style
  3274. * @return css_style_borderrightwidth
  3275. */
  3276. public static function init($value) {
  3277. return new css_style_borderrightwidth('border-right-width', $value);
  3278. }
  3279. /**
  3280. * Consolidate this to a single border style
  3281. *
  3282. * @return string
  3283. */
  3284. public function consolidate_to() {
  3285. return 'border';
  3286. }
  3287. }
  3288. /**
  3289. * A border width bottom style
  3290. *
  3291. * @package core
  3292. * @category css
  3293. * @copyright 2012 Sam Hemelryk
  3294. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  3295. */
  3296. class css_style_borderbottomwidth extends css_style_borderwidth {
  3297. /**
  3298. * Initialises this style object
  3299. *
  3300. * @param string $value The value of the style
  3301. * @return css_style_borderbottomwidth
  3302. */
  3303. public static function init($value) {
  3304. return new css_style_borderbottomwidth('border-bottom-width', $value);
  3305. }
  3306. /**
  3307. * Consolidate this to a single border style
  3308. *
  3309. * @return string
  3310. */
  3311. public function consolidate_to() {
  3312. return 'border';
  3313. }
  3314. }
  3315. /**
  3316. * A border top style
  3317. *
  3318. * @package core
  3319. * @category css
  3320. * @copyright 2012 Sam Hemelryk
  3321. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  3322. */
  3323. class css_style_bordertopstyle extends css_style_borderstyle {
  3324. /**
  3325. * Initialises this style object
  3326. *
  3327. * @param string $value The value of the style
  3328. * @return css_style_bordertopstyle
  3329. */
  3330. public static function init($value) {
  3331. return new css_style_bordertopstyle('border-top-style', $value);
  3332. }
  3333. /**
  3334. * Consolidate this to a single border style
  3335. *
  3336. * @return string
  3337. */
  3338. public function consolidate_to() {
  3339. return 'border';
  3340. }
  3341. }
  3342. /**
  3343. * A border left style
  3344. *
  3345. * @package core
  3346. * @category css
  3347. * @copyright 2012 Sam Hemelryk
  3348. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  3349. */
  3350. class css_style_borderleftstyle extends css_style_borderstyle {
  3351. /**
  3352. * Initialises this style object
  3353. *
  3354. * @param string $value The value of the style
  3355. * @return css_style_borderleftstyle
  3356. */
  3357. public static function init($value) {
  3358. return new css_style_borderleftstyle('border-left-style', $value);
  3359. }
  3360. /**
  3361. * Consolidate this to a single border style
  3362. *
  3363. * @return string
  3364. */
  3365. public function consolidate_to() {
  3366. return 'border';
  3367. }
  3368. }
  3369. /**
  3370. * A border right style
  3371. *
  3372. * @package core
  3373. * @category css
  3374. * @copyright 2012 Sam Hemelryk
  3375. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  3376. */
  3377. class css_style_borderrightstyle extends css_style_borderstyle {
  3378. /**
  3379. * Initialises this style object
  3380. *
  3381. * @param string $value The value of the style
  3382. * @return css_style_borderrightstyle
  3383. */
  3384. public static function init($value) {
  3385. return new css_style_borderrightstyle('border-right-style', $value);
  3386. }
  3387. /**
  3388. * Consolidate this to a single border style
  3389. *
  3390. * @return string
  3391. */
  3392. public function consolidate_to() {
  3393. return 'border';
  3394. }
  3395. }
  3396. /**
  3397. * A border bottom style
  3398. *
  3399. * @package core
  3400. * @category css
  3401. * @copyright 2012 Sam Hemelryk
  3402. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  3403. */
  3404. class css_style_borderbottomstyle extends css_style_borderstyle {
  3405. /**
  3406. * Initialises this style object
  3407. *
  3408. * @param string $value The value for the style
  3409. * @return css_style_borderbottomstyle
  3410. */
  3411. public static function init($value) {
  3412. return new css_style_borderbottomstyle('border-bottom-style', $value);
  3413. }
  3414. /**
  3415. * Consolidate this to a single border style
  3416. *
  3417. * @return string
  3418. */
  3419. public function consolidate_to() {
  3420. return 'border';
  3421. }
  3422. }
  3423. /**
  3424. * A background style
  3425. *
  3426. * @package core
  3427. * @category css
  3428. * @copyright 2012 Sam Hemelryk
  3429. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  3430. */
  3431. class css_style_background extends css_style {
  3432. /**
  3433. * Initialises a background style
  3434. *
  3435. * @param string $value The value of the style
  3436. * @return array An array of background component.
  3437. */
  3438. public static function init($value) {
  3439. // colour - image - repeat - attachment - position
  3440. $imageurl = null;
  3441. if (preg_match('#url\(([^\)]+)\)#', $value, $matches)) {
  3442. $imageurl = trim($matches[1]);
  3443. $value = str_replace($matches[1], '', $value);
  3444. }
  3445. // Switch out the brackets so that they don't get messed up when we explode
  3446. $brackets = array();
  3447. $bracketcount = 0;
  3448. while (preg_match('#\([^\)\(]+\)#', $value, $matches)) {
  3449. $key = "##BRACKET-{$bracketcount}##";
  3450. $bracketcount++;
  3451. $brackets[$key] = $matches[0];
  3452. $value = str_replace($matches[0], $key, $value);
  3453. }
  3454. $important = (stripos($value, '!important') !== false);
  3455. if ($important) {
  3456. // Great some genius put !important in the background shorthand property
  3457. $value = str_replace('!important', '', $value);
  3458. }
  3459. $value = preg_replace('#\s+#', ' ', $value);
  3460. $bits = explode(' ', $value);
  3461. foreach ($bits as $key => $bit) {
  3462. $bits[$key] = self::replace_bracket_placeholders($bit, $brackets);
  3463. }
  3464. unset($bracketcount);
  3465. unset($brackets);
  3466. $repeats = array('repeat', 'repeat-x', 'repeat-y', 'no-repeat', 'inherit');
  3467. $attachments = array('scroll' , 'fixed', 'inherit');
  3468. $positions = array('top', 'left', 'bottom', 'right', 'center');
  3469. $return = array();
  3470. $unknownbits = array();
  3471. $color = self::NULL_VALUE;
  3472. if (count($bits) > 0 && css_is_colour(reset($bits))) {
  3473. $color = array_shift($bits);
  3474. }
  3475. $image = self::NULL_VALUE;
  3476. if (count($bits) > 0 && preg_match('#^\s*(none|inherit|url\(\))\s*$#', reset($bits))) {
  3477. $image = array_shift($bits);
  3478. if ($image == 'url()') {
  3479. $image = "url({$imageurl})";
  3480. }
  3481. }
  3482. $repeat = self::NULL_VALUE;
  3483. if (count($bits) > 0 && in_array(reset($bits), $repeats)) {
  3484. $repeat = array_shift($bits);
  3485. }
  3486. $attachment = self::NULL_VALUE;
  3487. if (count($bits) > 0 && in_array(reset($bits), $attachments)) {
  3488. // scroll , fixed, inherit
  3489. $attachment = array_shift($bits);
  3490. }
  3491. $position = self::NULL_VALUE;
  3492. if (count($bits) > 0) {
  3493. $widthbits = array();
  3494. foreach ($bits as $bit) {
  3495. if (in_array($bit, $positions) || css_is_width($bit)) {
  3496. $widthbits[] = $bit;
  3497. } else {
  3498. $unknownbits[] = $bit;
  3499. }
  3500. }
  3501. if (count($widthbits)) {
  3502. $position = join(' ', $widthbits);
  3503. }
  3504. }
  3505. if (count($unknownbits)) {
  3506. foreach ($unknownbits as $bit) {
  3507. $bit = trim($bit);
  3508. if ($color === self::NULL_VALUE && css_is_colour($bit)) {
  3509. $color = $bit;
  3510. } else if ($repeat === self::NULL_VALUE && in_array($bit, $repeats)) {
  3511. $repeat = $bit;
  3512. } else if ($attachment === self::NULL_VALUE && in_array($bit, $attachments)) {
  3513. $attachment = $bit;
  3514. } else if ($bit !== '') {
  3515. $advanced = css_style_background_advanced::init($bit);
  3516. if ($important) {
  3517. $advanced->set_important();
  3518. }
  3519. $return[] = $advanced;
  3520. }
  3521. }
  3522. }
  3523. if ($color === self::NULL_VALUE && $image === self::NULL_VALUE && $repeat === self::NULL_VALUE && $attachment === self::NULL_VALUE && $position === self::NULL_VALUE) {
  3524. // All primaries are null, return without doing anything else. There may be advanced madness there.
  3525. return $return;
  3526. }
  3527. $return[] = new css_style_backgroundcolor('background-color', $color);
  3528. $return[] = new css_style_backgroundimage('background-image', $image);
  3529. $return[] = new css_style_backgroundrepeat('background-repeat', $repeat);
  3530. $return[] = new css_style_backgroundattachment('background-attachment', $attachment);
  3531. $return[] = new css_style_backgroundposition('background-position', $position);
  3532. if ($important) {
  3533. foreach ($return as $style) {
  3534. $style->set_important();
  3535. }
  3536. }
  3537. return $return;
  3538. }
  3539. /**
  3540. * Static helper method to switch in bracket replacements
  3541. *
  3542. * @param string $value
  3543. * @param array $placeholders
  3544. * @return string
  3545. */
  3546. protected static function replace_bracket_placeholders($value, array $placeholders) {
  3547. while (preg_match('/##BRACKET-\d+##/', $value, $matches)) {
  3548. $value = str_replace($matches[0], $placeholders[$matches[0]], $value);
  3549. }
  3550. return $value;
  3551. }
  3552. /**
  3553. * Consolidates background styles into a single background style
  3554. *
  3555. * @param array $styles Consolidates the provided array of background styles
  3556. * @return array Consolidated optimised background styles
  3557. */
  3558. public static function consolidate(array $styles) {
  3559. if (empty($styles)) {
  3560. return $styles;
  3561. }
  3562. $color = null;
  3563. $image = null;
  3564. $repeat = null;
  3565. $attachment = null;
  3566. $position = null;
  3567. $size = null;
  3568. $origin = null;
  3569. $clip = null;
  3570. $someimportant = false;
  3571. $allimportant = null;
  3572. foreach ($styles as $style) {
  3573. if ($style instanceof css_style_backgroundimage_advanced) {
  3574. continue;
  3575. }
  3576. if ($style->is_important()) {
  3577. $someimportant = true;
  3578. if ($allimportant === null) {
  3579. $allimportant = true;
  3580. }
  3581. } else if ($allimportant === true) {
  3582. $allimportant = false;
  3583. }
  3584. }
  3585. $organisedstyles = array();
  3586. $advancedstyles = array();
  3587. $importantstyles = array();
  3588. foreach ($styles as $style) {
  3589. if ($style instanceof css_style_backgroundimage_advanced) {
  3590. $advancedstyles[] = $style;
  3591. continue;
  3592. }
  3593. if ($someimportant && !$allimportant && $style->is_important()) {
  3594. $importantstyles[] = $style;
  3595. continue;
  3596. }
  3597. $organisedstyles[$style->get_name()] = $style;
  3598. switch ($style->get_name()) {
  3599. case 'background-color' :
  3600. $color = css_style_color::shrink_value($style->get_value(false));
  3601. break;
  3602. case 'background-image' :
  3603. $image = $style->get_value(false);
  3604. break;
  3605. case 'background-repeat' :
  3606. $repeat = $style->get_value(false);
  3607. break;
  3608. case 'background-attachment' :
  3609. $attachment = $style->get_value(false);
  3610. break;
  3611. case 'background-position' :
  3612. $position = $style->get_value(false);
  3613. break;
  3614. case 'background-clip' :
  3615. $clip = $style->get_value();
  3616. break;
  3617. case 'background-origin' :
  3618. $origin = $style->get_value();
  3619. break;
  3620. case 'background-size' :
  3621. $size = $style->get_value();
  3622. break;
  3623. }
  3624. }
  3625. $consolidatetosingle = array();
  3626. if (!is_null($color) && !is_null($image) && !is_null($repeat) && !is_null($attachment) && !is_null($position)) {
  3627. // We can use the shorthand background-style!
  3628. if (!$organisedstyles['background-color']->is_special_empty_value()) {
  3629. $consolidatetosingle[] = $color;
  3630. }
  3631. if (!$organisedstyles['background-image']->is_special_empty_value()) {
  3632. $consolidatetosingle[] = $image;
  3633. }
  3634. if (!$organisedstyles['background-repeat']->is_special_empty_value()) {
  3635. $consolidatetosingle[] = $repeat;
  3636. }
  3637. if (!$organisedstyles['background-attachment']->is_special_empty_value()) {
  3638. $consolidatetosingle[] = $attachment;
  3639. }
  3640. if (!$organisedstyles['background-position']->is_special_empty_value()) {
  3641. $consolidatetosingle[] = $position;
  3642. }
  3643. // Reset them all to null so we don't use them again.
  3644. $color = null;
  3645. $image = null;
  3646. $repeat = null;
  3647. $attachment = null;
  3648. $position = null;
  3649. }
  3650. $return = array();
  3651. // Single background style needs to come first;
  3652. if (count($consolidatetosingle) > 0) {
  3653. $returnstyle = new css_style_background('background', join(' ', $consolidatetosingle));
  3654. if ($allimportant) {
  3655. $returnstyle->set_important();
  3656. }
  3657. $return[] = $returnstyle;
  3658. }
  3659. foreach ($styles as $style) {
  3660. $value = null;
  3661. switch ($style->get_name()) {
  3662. case 'background-color' : $value = $color; break;
  3663. case 'background-image' : $value = $image; break;
  3664. case 'background-repeat' : $value = $repeat; break;
  3665. case 'background-attachment' : $value = $attachment; break;
  3666. case 'background-position' : $value = $position; break;
  3667. case 'background-clip' : $value = $clip; break;
  3668. case 'background-origin' : $value = $origin; break;
  3669. case 'background-size' : $value = $size; break;
  3670. }
  3671. if (!is_null($value)) {
  3672. $return[] = $style;
  3673. }
  3674. }
  3675. $return = array_merge($return, $importantstyles, $advancedstyles);
  3676. return $return;
  3677. }
  3678. }
  3679. /**
  3680. * A advanced background style that allows multiple values to preserve unknown entities
  3681. *
  3682. * @package core
  3683. * @category css
  3684. * @copyright 2012 Sam Hemelryk
  3685. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  3686. */
  3687. class css_style_background_advanced extends css_style_generic {
  3688. /**
  3689. * Creates a new background colour style
  3690. *
  3691. * @param string $value The value of the style
  3692. * @return css_style_backgroundimage
  3693. */
  3694. public static function init($value) {
  3695. $value = preg_replace('#\s+#', ' ', $value);
  3696. return new css_style_background_advanced('background', $value);
  3697. }
  3698. /**
  3699. * Returns true because the advanced background image supports multiple values.
  3700. * e.g. -webkit-linear-gradient and -moz-linear-gradient.
  3701. *
  3702. * @return boolean
  3703. */
  3704. public function allows_multiple_values() {
  3705. return true;
  3706. }
  3707. }
  3708. /**
  3709. * A background colour style.
  3710. *
  3711. * Based upon the colour style.
  3712. *
  3713. * @package core
  3714. * @category css
  3715. * @copyright 2012 Sam Hemelryk
  3716. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  3717. */
  3718. class css_style_backgroundcolor extends css_style_color {
  3719. /**
  3720. * Creates a new background colour style
  3721. *
  3722. * @param string $value The value of the style
  3723. * @return css_style_backgroundcolor
  3724. */
  3725. public static function init($value) {
  3726. return new css_style_backgroundcolor('background-color', $value);
  3727. }
  3728. /**
  3729. * css_style_backgroundcolor consolidates to css_style_background
  3730. *
  3731. * @return string
  3732. */
  3733. public function consolidate_to() {
  3734. return 'background';
  3735. }
  3736. /**
  3737. * Returns true if the value for this style is the special null value.
  3738. *
  3739. * This occurs if the shorthand background property was used but no proper value
  3740. * was specified for this style.
  3741. * This leads to a null value being used unless otherwise overridden.
  3742. *
  3743. * @return bool
  3744. */
  3745. public function is_special_empty_value() {
  3746. return ($this->value === self::NULL_VALUE);
  3747. }
  3748. /**
  3749. * Returns true if the value for this style is valid
  3750. * @return bool
  3751. */
  3752. public function is_valid() {
  3753. return $this->is_special_empty_value() || parent::is_valid();
  3754. }
  3755. }
  3756. /**
  3757. * A background image style.
  3758. *
  3759. * @package core
  3760. * @category css
  3761. * @copyright 2012 Sam Hemelryk
  3762. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  3763. */
  3764. class css_style_backgroundimage extends css_style_generic {
  3765. /**
  3766. * Creates a new background image style
  3767. *
  3768. * @param string $value The value of the style
  3769. * @return css_style_backgroundimage
  3770. */
  3771. public static function init($value) {
  3772. if (!preg_match('#^\s*(none|inherit|url\()#i', $value)) {
  3773. return css_style_backgroundimage_advanced::init($value);
  3774. }
  3775. return new css_style_backgroundimage('background-image', $value);
  3776. }
  3777. /**
  3778. * Consolidates this style into a single background style
  3779. *
  3780. * @return string
  3781. */
  3782. public function consolidate_to() {
  3783. return 'background';
  3784. }
  3785. /**
  3786. * Returns true if the value for this style is the special null value.
  3787. *
  3788. * This occurs if the shorthand background property was used but no proper value
  3789. * was specified for this style.
  3790. * This leads to a null value being used unless otherwise overridden.
  3791. *
  3792. * @return bool
  3793. */
  3794. public function is_special_empty_value() {
  3795. return ($this->value === self::NULL_VALUE);
  3796. }
  3797. /**
  3798. * Returns true if the value for this style is valid
  3799. * @return bool
  3800. */
  3801. public function is_valid() {
  3802. return $this->is_special_empty_value() || parent::is_valid();
  3803. }
  3804. }
  3805. /**
  3806. * A background image style that supports mulitple values and masquerades as a background-image
  3807. *
  3808. * @package core
  3809. * @category css
  3810. * @copyright 2012 Sam Hemelryk
  3811. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  3812. */
  3813. class css_style_backgroundimage_advanced extends css_style_generic {
  3814. /**
  3815. * Creates a new background colour style
  3816. *
  3817. * @param string $value The value of the style
  3818. * @return css_style_backgroundimage
  3819. */
  3820. public static function init($value) {
  3821. $value = preg_replace('#\s+#', ' ', $value);
  3822. return new css_style_backgroundimage_advanced('background-image', $value);
  3823. }
  3824. /**
  3825. * Returns true because the advanced background image supports multiple values.
  3826. * e.g. -webkit-linear-gradient and -moz-linear-gradient.
  3827. *
  3828. * @return boolean
  3829. */
  3830. public function allows_multiple_values() {
  3831. return true;
  3832. }
  3833. }
  3834. /**
  3835. * A background repeat style.
  3836. *
  3837. * @package core
  3838. * @category css
  3839. * @copyright 2012 Sam Hemelryk
  3840. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  3841. */
  3842. class css_style_backgroundrepeat extends css_style_generic {
  3843. /**
  3844. * Creates a new background colour style
  3845. *
  3846. * @param string $value The value of the style
  3847. * @return css_style_backgroundrepeat
  3848. */
  3849. public static function init($value) {
  3850. return new css_style_backgroundrepeat('background-repeat', $value);
  3851. }
  3852. /**
  3853. * Consolidates this style into a single background style
  3854. *
  3855. * @return string
  3856. */
  3857. public function consolidate_to() {
  3858. return 'background';
  3859. }
  3860. /**
  3861. * Returns true if the value for this style is the special null value.
  3862. *
  3863. * This occurs if the shorthand background property was used but no proper value
  3864. * was specified for this style.
  3865. * This leads to a null value being used unless otherwise overridden.
  3866. *
  3867. * @return bool
  3868. */
  3869. public function is_special_empty_value() {
  3870. return ($this->value === self::NULL_VALUE);
  3871. }
  3872. /**
  3873. * Returns true if the value for this style is valid
  3874. * @return bool
  3875. */
  3876. public function is_valid() {
  3877. return $this->is_special_empty_value() || parent::is_valid();
  3878. }
  3879. }
  3880. /**
  3881. * A background attachment style.
  3882. *
  3883. * @package core
  3884. * @category css
  3885. * @copyright 2012 Sam Hemelryk
  3886. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  3887. */
  3888. class css_style_backgroundattachment extends css_style_generic {
  3889. /**
  3890. * Creates a new background colour style
  3891. *
  3892. * @param string $value The value of the style
  3893. * @return css_style_backgroundattachment
  3894. */
  3895. public static function init($value) {
  3896. return new css_style_backgroundattachment('background-attachment', $value);
  3897. }
  3898. /**
  3899. * Consolidates this style into a single background style
  3900. *
  3901. * @return string
  3902. */
  3903. public function consolidate_to() {
  3904. return 'background';
  3905. }
  3906. /**
  3907. * Returns true if the value for this style is the special null value.
  3908. *
  3909. * This occurs if the shorthand background property was used but no proper value
  3910. * was specified for this style.
  3911. * This leads to a null value being used unless otherwise overridden.
  3912. *
  3913. * @return bool
  3914. */
  3915. public function is_special_empty_value() {
  3916. return ($this->value === self::NULL_VALUE);
  3917. }
  3918. /**
  3919. * Returns true if the value for this style is valid
  3920. * @return bool
  3921. */
  3922. public function is_valid() {
  3923. return $this->is_special_empty_value() || parent::is_valid();
  3924. }
  3925. }
  3926. /**
  3927. * A background position style.
  3928. *
  3929. * @package core
  3930. * @category css
  3931. * @copyright 2012 Sam Hemelryk
  3932. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  3933. */
  3934. class css_style_backgroundposition extends css_style_generic {
  3935. /**
  3936. * Creates a new background colour style
  3937. *
  3938. * @param string $value The value of the style
  3939. * @return css_style_backgroundposition
  3940. */
  3941. public static function init($value) {
  3942. return new css_style_backgroundposition('background-position', $value);
  3943. }
  3944. /**
  3945. * Consolidates this style into a single background style
  3946. *
  3947. * @return string
  3948. */
  3949. public function consolidate_to() {
  3950. return 'background';
  3951. }
  3952. /**
  3953. * Returns true if the value for this style is the special null value.
  3954. *
  3955. * This occurs if the shorthand background property was used but no proper value
  3956. * was specified for this style.
  3957. * This leads to a null value being used unless otherwise overridden.
  3958. *
  3959. * @return bool
  3960. */
  3961. public function is_special_empty_value() {
  3962. return ($this->value === self::NULL_VALUE);
  3963. }
  3964. /**
  3965. * Returns true if the value for this style is valid
  3966. * @return bool
  3967. */
  3968. public function is_valid() {
  3969. return $this->is_special_empty_value() || parent::is_valid();
  3970. }
  3971. }
  3972. /**
  3973. * A background size style.
  3974. *
  3975. * @package core
  3976. * @category css
  3977. * @copyright 2012 Sam Hemelryk
  3978. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  3979. */
  3980. class css_style_backgroundsize extends css_style_generic {
  3981. /**
  3982. * Creates a new background size style
  3983. *
  3984. * @param string $value The value of the style
  3985. * @return css_style_backgroundposition
  3986. */
  3987. public static function init($value) {
  3988. return new css_style_backgroundsize('background-size', $value);
  3989. }
  3990. /**
  3991. * Consolidates this style into a single background style
  3992. *
  3993. * @return string
  3994. */
  3995. public function consolidate_to() {
  3996. return 'background';
  3997. }
  3998. }
  3999. /**
  4000. * A background clip style.
  4001. *
  4002. * @package core
  4003. * @category css
  4004. * @copyright 2012 Sam Hemelryk
  4005. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  4006. */
  4007. class css_style_backgroundclip extends css_style_generic {
  4008. /**
  4009. * Creates a new background clip style
  4010. *
  4011. * @param string $value The value of the style
  4012. * @return css_style_backgroundposition
  4013. */
  4014. public static function init($value) {
  4015. return new css_style_backgroundclip('background-clip', $value);
  4016. }
  4017. /**
  4018. * Consolidates this style into a single background style
  4019. *
  4020. * @return string
  4021. */
  4022. public function consolidate_to() {
  4023. return 'background';
  4024. }
  4025. }
  4026. /**
  4027. * A background origin style.
  4028. *
  4029. * @package core
  4030. * @category css
  4031. * @copyright 2012 Sam Hemelryk
  4032. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  4033. */
  4034. class css_style_backgroundorigin extends css_style_generic {
  4035. /**
  4036. * Creates a new background origin style
  4037. *
  4038. * @param string $value The value of the style
  4039. * @return css_style_backgroundposition
  4040. */
  4041. public static function init($value) {
  4042. return new css_style_backgroundorigin('background-origin', $value);
  4043. }
  4044. /**
  4045. * Consolidates this style into a single background style
  4046. *
  4047. * @return string
  4048. */
  4049. public function consolidate_to() {
  4050. return 'background';
  4051. }
  4052. }
  4053. /**
  4054. * A padding style.
  4055. *
  4056. * @package core
  4057. * @category css
  4058. * @copyright 2012 Sam Hemelryk
  4059. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  4060. */
  4061. class css_style_padding extends css_style_width {
  4062. /**
  4063. * Initialises this padding style into several individual padding styles
  4064. *
  4065. * @param string $value The value fo the style
  4066. * @return array An array of padding styles
  4067. */
  4068. public static function init($value) {
  4069. $important = '';
  4070. if (strpos($value, '!important') !== false) {
  4071. $important = ' !important';
  4072. $value = str_replace('!important', '', $value);
  4073. }
  4074. $value = preg_replace('#\s+#', ' ', trim($value));
  4075. $bits = explode(' ', $value, 4);
  4076. $top = $right = $bottom = $left = null;
  4077. if (count($bits) > 0) {
  4078. $top = $right = $bottom = $left = array_shift($bits);
  4079. }
  4080. if (count($bits) > 0) {
  4081. $right = $left = array_shift($bits);
  4082. }
  4083. if (count($bits) > 0) {
  4084. $bottom = array_shift($bits);
  4085. }
  4086. if (count($bits) > 0) {
  4087. $left = array_shift($bits);
  4088. }
  4089. return array(
  4090. new css_style_paddingtop('padding-top', $top.$important),
  4091. new css_style_paddingright('padding-right', $right.$important),
  4092. new css_style_paddingbottom('padding-bottom', $bottom.$important),
  4093. new css_style_paddingleft('padding-left', $left.$important)
  4094. );
  4095. }
  4096. /**
  4097. * Consolidates several padding styles into a single style.
  4098. *
  4099. * @param array $styles Array of padding styles
  4100. * @return array Optimised+consolidated array of padding styles
  4101. */
  4102. public static function consolidate(array $styles) {
  4103. if (count($styles) != 4) {
  4104. return $styles;
  4105. }
  4106. $someimportant = false;
  4107. $allimportant = null;
  4108. $notimportantequal = null;
  4109. $firstvalue = null;
  4110. foreach ($styles as $style) {
  4111. if ($style->is_important()) {
  4112. $someimportant = true;
  4113. if ($allimportant === null) {
  4114. $allimportant = true;
  4115. }
  4116. } else {
  4117. if ($allimportant === true) {
  4118. $allimportant = false;
  4119. }
  4120. if ($firstvalue == null) {
  4121. $firstvalue = $style->get_value(false);
  4122. $notimportantequal = true;
  4123. } else if ($notimportantequal && $firstvalue !== $style->get_value(false)) {
  4124. $notimportantequal = false;
  4125. }
  4126. }
  4127. }
  4128. if ($someimportant && !$allimportant && !$notimportantequal) {
  4129. return $styles;
  4130. }
  4131. if ($someimportant && !$allimportant && $notimportantequal) {
  4132. $return = array(
  4133. new css_style_padding('padding', $firstvalue)
  4134. );
  4135. foreach ($styles as $style) {
  4136. if ($style->is_important()) {
  4137. $return[] = $style;
  4138. }
  4139. }
  4140. return $return;
  4141. } else {
  4142. $top = null;
  4143. $right = null;
  4144. $bottom = null;
  4145. $left = null;
  4146. foreach ($styles as $style) {
  4147. switch ($style->get_name()) {
  4148. case 'padding-top' : $top = $style->get_value(false);break;
  4149. case 'padding-right' : $right = $style->get_value(false);break;
  4150. case 'padding-bottom' : $bottom = $style->get_value(false);break;
  4151. case 'padding-left' : $left = $style->get_value(false);break;
  4152. }
  4153. }
  4154. if ($top == $bottom && $left == $right) {
  4155. if ($top == $left) {
  4156. $returnstyle = new css_style_padding('padding', $top);
  4157. } else {
  4158. $returnstyle = new css_style_padding('padding', "{$top} {$left}");
  4159. }
  4160. } else if ($left == $right) {
  4161. $returnstyle = new css_style_padding('padding', "{$top} {$right} {$bottom}");
  4162. } else {
  4163. $returnstyle = new css_style_padding('padding', "{$top} {$right} {$bottom} {$left}");
  4164. }
  4165. if ($allimportant) {
  4166. $returnstyle->set_important();
  4167. }
  4168. return array($returnstyle);
  4169. }
  4170. }
  4171. }
  4172. /**
  4173. * A padding top style.
  4174. *
  4175. * @package core
  4176. * @category css
  4177. * @copyright 2012 Sam Hemelryk
  4178. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  4179. */
  4180. class css_style_paddingtop extends css_style_padding {
  4181. /**
  4182. * Initialises this style
  4183. *
  4184. * @param string $value The value of the style
  4185. * @return css_style_paddingtop
  4186. */
  4187. public static function init($value) {
  4188. return new css_style_paddingtop('padding-top', $value);
  4189. }
  4190. /**
  4191. * Consolidates this style into a single padding style
  4192. *
  4193. * @return string
  4194. */
  4195. public function consolidate_to() {
  4196. return 'padding';
  4197. }
  4198. }
  4199. /**
  4200. * A padding right style.
  4201. *
  4202. * @package core
  4203. * @category css
  4204. * @copyright 2012 Sam Hemelryk
  4205. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  4206. */
  4207. class css_style_paddingright extends css_style_padding {
  4208. /**
  4209. * Initialises this style
  4210. *
  4211. * @param string $value The value of the style
  4212. * @return css_style_paddingright
  4213. */
  4214. public static function init($value) {
  4215. return new css_style_paddingright('padding-right', $value);
  4216. }
  4217. /**
  4218. * Consolidates this style into a single padding style
  4219. *
  4220. * @return string
  4221. */
  4222. public function consolidate_to() {
  4223. return 'padding';
  4224. }
  4225. }
  4226. /**
  4227. * A padding bottom style.
  4228. *
  4229. * @package core
  4230. * @category css
  4231. * @copyright 2012 Sam Hemelryk
  4232. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  4233. */
  4234. class css_style_paddingbottom extends css_style_padding {
  4235. /**
  4236. * Initialises this style
  4237. *
  4238. * @param string $value The value of the style
  4239. * @return css_style_paddingbottom
  4240. */
  4241. public static function init($value) {
  4242. return new css_style_paddingbottom('padding-bottom', $value);
  4243. }
  4244. /**
  4245. * Consolidates this style into a single padding style
  4246. *
  4247. * @return string
  4248. */
  4249. public function consolidate_to() {
  4250. return 'padding';
  4251. }
  4252. }
  4253. /**
  4254. * A padding left style.
  4255. *
  4256. * @package core
  4257. * @category css
  4258. * @copyright 2012 Sam Hemelryk
  4259. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  4260. */
  4261. class css_style_paddingleft extends css_style_padding {
  4262. /**
  4263. * Initialises this style
  4264. *
  4265. * @param string $value The value of the style
  4266. * @return css_style_paddingleft
  4267. */
  4268. public static function init($value) {
  4269. return new css_style_paddingleft('padding-left', $value);
  4270. }
  4271. /**
  4272. * Consolidates this style into a single padding style
  4273. *
  4274. * @return string
  4275. */
  4276. public function consolidate_to() {
  4277. return 'padding';
  4278. }
  4279. }
  4280. /**
  4281. * A cursor style.
  4282. *
  4283. * @package core
  4284. * @category css
  4285. * @copyright 2012 Sam Hemelryk
  4286. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  4287. */
  4288. class css_style_cursor extends css_style_generic {
  4289. /**
  4290. * Initialises a new cursor style
  4291. * @param string $value
  4292. * @return css_style_cursor
  4293. */
  4294. public static function init($value) {
  4295. return new css_style_cursor('cursor', $value);
  4296. }
  4297. /**
  4298. * Cleans the given value and returns it.
  4299. *
  4300. * @param string $value
  4301. * @return string
  4302. */
  4303. protected function clean_value($value) {
  4304. // Allowed values for the cursor style
  4305. $allowed = array('auto', 'crosshair', 'default', 'e-resize', 'help', 'move', 'n-resize', 'ne-resize', 'nw-resize',
  4306. 'pointer', 'progress', 's-resize', 'se-resize', 'sw-resize', 'text', 'w-resize', 'wait', 'inherit');
  4307. // Has to be one of the allowed values of an image to use. Loosely match the image... doesn't need to be thorough
  4308. if (!in_array($value, $allowed) && !preg_match('#\.[a-zA-Z0-9_\-]{1,5}$#', $value)) {
  4309. $this->set_error('Invalid or unexpected cursor value specified: '.$value);
  4310. }
  4311. return trim($value);
  4312. }
  4313. }
  4314. /**
  4315. * A vertical alignment style.
  4316. *
  4317. * @package core
  4318. * @category css
  4319. * @copyright 2012 Sam Hemelryk
  4320. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  4321. */
  4322. class css_style_verticalalign extends css_style_generic {
  4323. /**
  4324. * Initialises a new vertical alignment style
  4325. * @param string $value
  4326. * @return css_style_verticalalign
  4327. */
  4328. public static function init($value) {
  4329. return new css_style_verticalalign('vertical-align', $value);
  4330. }
  4331. /**
  4332. * Cleans the given value and returns it.
  4333. *
  4334. * @param string $value
  4335. * @return string
  4336. */
  4337. protected function clean_value($value) {
  4338. $allowed = array('baseline', 'sub', 'super', 'top', 'text-top', 'middle', 'bottom', 'text-bottom', 'inherit');
  4339. if (!css_is_width($value) && !in_array($value, $allowed)) {
  4340. $this->set_error('Invalid vertical-align value specified: '.$value);
  4341. }
  4342. return trim($value);
  4343. }
  4344. }
  4345. /**
  4346. * A float style.
  4347. *
  4348. * @package core
  4349. * @category css
  4350. * @copyright 2012 Sam Hemelryk
  4351. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  4352. */
  4353. class css_style_float extends css_style_generic {
  4354. /**
  4355. * Initialises a new float style
  4356. * @param string $value
  4357. * @return css_style_float
  4358. */
  4359. public static function init($value) {
  4360. return new css_style_float('float', $value);
  4361. }
  4362. /**
  4363. * Cleans the given value and returns it.
  4364. *
  4365. * @param string $value
  4366. * @return string
  4367. */
  4368. protected function clean_value($value) {
  4369. $allowed = array('left', 'right', 'none', 'inherit');
  4370. if (!css_is_width($value) && !in_array($value, $allowed)) {
  4371. $this->set_error('Invalid float value specified: '.$value);
  4372. }
  4373. return trim($value);
  4374. }
  4375. }