2 // This file is part of Moodle - http://moodle.org/
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.
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.
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/>.
18 * This file contains CSS related class, and function for the CSS optimiser
20 * Please see the {@link css_optimiser} class for greater detail.
24 * @copyright 2012 Sam Hemelryk
25 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
28 // NOTE: do not verify MOODLE_INTERNAL here, this is used from themes too
31 * Stores CSS in a file at the given path.
33 * This function either succeeds or throws an exception.
35 * @param theme_config $theme The theme that the CSS belongs to.
36 * @param string $csspath The path to store the CSS at.
37 * @param array $cssfiles The CSS files to store.
39 function css_store_css(theme_config
$theme, $csspath, array $cssfiles) {
42 // Check if both the CSS optimiser is enabled and the theme supports it.
43 if (!empty($CFG->enablecssoptimiser
) && $theme->supportscssoptimisation
) {
44 // This is an experimental feature introduced in Moodle 2.3
45 // The CSS optimiser organises the CSS in order to reduce the overall number
46 // of rules and styles being sent to the client. It does this by collating
47 // the CSS before it is cached removing excess styles and rules and stripping
48 // out any extraneous content such as comments and empty rules.
49 $optimiser = new css_optimiser
;
51 foreach ($cssfiles as $file) {
52 $css .= file_get_contents($file)."\n";
54 $css = $theme->post_process($css);
55 $css = $optimiser->process($css);
57 // If cssoptimisestats is set then stats from the optimisation are collected
58 // and output at the beginning of the CSS
59 if (!empty($CFG->cssoptimiserstats
)) {
60 $css = $optimiser->output_stats_css().$css;
63 // This is the default behaviour.
64 // The cssoptimise setting was introduced in Moodle 2.3 and will hopefully
65 // in the future be changed from an experimental setting to the default.
66 // The css_minify_css will method will use the Minify library remove
67 // comments, additional whitespace and other minor measures to reduce the
68 // the overall CSS being sent.
69 // However it has the distinct disadvantage of having to minify the CSS
70 // before running the post process functions. Potentially things may break
71 // here if theme designers try to push things with CSS post processing.
72 $css = $theme->post_process(css_minify_css($cssfiles));
76 if (!file_exists(dirname($csspath))) {
77 @mkdir
(dirname($csspath), $CFG->directorypermissions
, true);
80 // Prevent serving of incomplete file from concurrent request,
81 // the rename() should be more atomic than fwrite().
82 ignore_user_abort(true);
83 if ($fp = fopen($csspath.'.tmp', 'xb')) {
86 rename($csspath.'.tmp', $csspath);
87 @chmod
($csspath, $CFG->filepermissions
);
88 @unlink
($csspath.'.tmp'); // just in case anything fails
90 ignore_user_abort(false);
91 if (connection_aborted()) {
97 * Sends IE specific CSS
99 * In writing the CSS parser I have a theory that we could optimise the CSS
100 * then split it based upon the number of selectors to ensure we dont' break IE
101 * and that we include only as many sub-stylesheets as we require.
102 * Of course just a theory but may be fun to code.
104 * @param string $themename The name of the theme we are sending CSS for.
105 * @param string $rev The revision to ensure we utilise the cache.
106 * @param string $etag The revision to ensure we utilise the cache.
107 * @param bool $slasharguments
109 function css_send_ie_css($themename, $rev, $etag, $slasharguments) {
112 $lifetime = 60*60*24*60; // 60 days only - the revision may get incremented quite often
114 $relroot = preg_replace('|^http.?://[^/]+|', '', $CFG->wwwroot
);
116 $css = "/** Unfortunately IE6/7 does not support more than 4096 selectors in one CSS file, which means we have to use some ugly hacks :-( **/";
117 if ($slasharguments) {
118 $css .= "\n@import url($relroot/styles.php/$themename/$rev/plugins);";
119 $css .= "\n@import url($relroot/styles.php/$themename/$rev/parents);";
120 $css .= "\n@import url($relroot/styles.php/$themename/$rev/theme);";
122 $css .= "\n@import url($relroot/styles.php?theme=$themename&rev=$rev&type=plugins);";
123 $css .= "\n@import url($relroot/styles.php?theme=$themename&rev=$rev&type=parents);";
124 $css .= "\n@import url($relroot/styles.php?theme=$themename&rev=$rev&type=theme);";
127 header('Etag: '.$etag);
128 header('Content-Disposition: inline; filename="styles.php"');
129 header('Last-Modified: '. gmdate('D, d M Y H:i:s', time()) .' GMT');
130 header('Expires: '. gmdate('D, d M Y H:i:s', time() +
$lifetime) .' GMT');
132 header('Cache-Control: public, max-age='.$lifetime);
133 header('Accept-Ranges: none');
134 header('Content-Type: text/css; charset=utf-8');
135 header('Content-Length: '.strlen($css));
142 * Sends a cached CSS file
144 * This function sends the cached CSS file. Remember it is generated on the first
145 * request, then optimised/minified, and finally cached for serving.
147 * @param string $csspath The path to the CSS file we want to serve.
148 * @param string $etag The revision to make sure we utilise any caches.
150 function css_send_cached_css($csspath, $etag) {
151 $lifetime = 60*60*24*60; // 60 days only - the revision may get incremented quite often
153 header('Etag: '.$etag);
154 header('Content-Disposition: inline; filename="styles.php"');
155 header('Last-Modified: '. gmdate('D, d M Y H:i:s', filemtime($csspath)) .' GMT');
156 header('Expires: '. gmdate('D, d M Y H:i:s', time() +
$lifetime) .' GMT');
158 header('Cache-Control: public, max-age='.$lifetime);
159 header('Accept-Ranges: none');
160 header('Content-Type: text/css; charset=utf-8');
161 if (!min_enable_zlib_compression()) {
162 header('Content-Length: '.filesize($csspath));
170 * Sends CSS directly without caching it.
172 * This function takes a raw CSS string, optimises it if required, and then
174 * Turning both themedesignermode and CSS optimiser on at the same time is awful
175 * for performance because of the optimiser running here. However it was done so
176 * that theme designers could utilise the optimised output during development to
177 * help them optimise their CSS... not that they should write lazy CSS.
181 function css_send_uncached_css($css, $themesupportsoptimisation = true) {
184 header('Content-Disposition: inline; filename="styles_debug.php"');
185 header('Last-Modified: '. gmdate('D, d M Y H:i:s', time()) .' GMT');
186 header('Expires: '. gmdate('D, d M Y H:i:s', time() + THEME_DESIGNER_CACHE_LIFETIME
) .' GMT');
188 header('Accept-Ranges: none');
189 header('Content-Type: text/css; charset=utf-8');
191 if (is_array($css)) {
192 $css = implode("\n\n", $css);
201 * Send file not modified headers
202 * @param int $lastmodified
203 * @param string $etag
205 function css_send_unmodified($lastmodified, $etag) {
206 $lifetime = 60*60*24*60; // 60 days only - the revision may get incremented quite often
207 header('HTTP/1.1 304 Not Modified');
208 header('Expires: '. gmdate('D, d M Y H:i:s', time() +
$lifetime) .' GMT');
209 header('Cache-Control: public, max-age='.$lifetime);
210 header('Content-Type: text/css; charset=utf-8');
211 header('Etag: '.$etag);
213 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
219 * Sends a 404 message about CSS not being found.
221 function css_send_css_not_found() {
222 header('HTTP/1.0 404 not found');
223 die('CSS was not found, sorry.');
227 * Uses the minify library to compress CSS.
229 * This is used if $CFG->enablecssoptimiser has been turned off. This was
230 * the original CSS optimisation library.
231 * It removes whitespace and shrinks things but does no apparent optimisation.
232 * Note the minify library is still being used for JavaScript.
234 * @param array $files An array of files to minify
235 * @return string The minified CSS
237 function css_minify_css($files) {
244 set_include_path($CFG->libdir
. '/minify/lib' . PATH_SEPARATOR
. get_include_path());
245 require_once('Minify.php');
247 if (0 === stripos(PHP_OS
, 'win')) {
248 Minify
::setDocRoot(); // IIS may need help
250 // disable all caching, we do it in moodle
251 Minify
::setCache(null, false);
254 'bubbleCssImports' => false,
255 // Don't gzip content we just want text for storage
256 'encodeOutput' => false,
257 // Maximum age to cache, not used but required
258 'maxAge' => (60*60*24*20),
259 // The files to minify
261 // Turn orr URI rewriting
262 'rewriteCssUris' => false,
263 // This returns the CSS rather than echoing it for display
269 $result = Minify
::serve('Files', $options);
270 if ($result['success']) {
271 return $result['content'];
273 } catch (Exception
$e) {
274 $error = $e->getMessage();
275 $error = str_replace("\r", ' ', $error);
276 $error = str_replace("\n", ' ', $error);
279 // minification failed - try to inform the theme developer and include the non-minified version
282 /* Problem detected during theme CSS minimisation, please review the following code */
283 /* ================================================================================ */
287 foreach ($files as $cssfile) {
288 $css .= file_get_contents($cssfile)."\n";
294 * Determines if the given value is a valid CSS colour.
296 * A CSS colour can be one of the following:
297 * - Hex colour: #AA66BB
298 * - RGB colour: rgb(0-255, 0-255, 0-255)
299 * - RGBA colour: rgba(0-255, 0-255, 0-255, 0-1)
300 * - HSL colour: hsl(0-360, 0-100%, 0-100%)
301 * - HSLA colour: hsla(0-360, 0-100%, 0-100%, 0-1)
303 * Or a recognised browser colour mapping {@link css_optimiser::$htmlcolours}
305 * @param string $value The colour value to check
308 function css_is_colour($value) {
309 $value = trim($value);
311 $hex = '/^#([a-fA-F0-9]{1,3}|[a-fA-F0-9]{6})$/';
312 $rgb = '#^rgb\s*\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$#i';
313 $rgba = '#^rgba\s*\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1}(\.\d+)?)\s*\)$#i';
314 $hsl = '#^hsl\s*\(\s*(\d{1,3})\s*,\s*(\d{1,3})\%\s*,\s*(\d{1,3})\%\s*\)$#i';
315 $hsla = '#^hsla\s*\(\s*(\d{1,3})\s*,\s*(\d{1,3})\%\s*,\s*(\d{1,3})\%\s*,\s*(\d{1}(\.\d+)?)\s*\)$#i';
317 if (in_array(strtolower($value), array('inherit'))) {
319 } else if (preg_match($hex, $value)) {
321 } else if (in_array(strtolower($value), array_keys(css_optimiser
::$htmlcolours))) {
323 } else if (preg_match($rgb, $value, $m) && $m[1] < 256 && $m[2] < 256 && $m[3] < 256) {
324 // It is an RGB colour
326 } else if (preg_match($rgba, $value, $m) && $m[1] < 256 && $m[2] < 256 && $m[3] < 256) {
327 // It is an RGBA colour
329 } else if (preg_match($hsl, $value, $m) && $m[1] <= 360 && $m[2] <= 100 && $m[3] <= 100) {
330 // It is an HSL colour
332 } else if (preg_match($hsla, $value, $m) && $m[1] <= 360 && $m[2] <= 100 && $m[3] <= 100) {
333 // It is an HSLA colour
336 // Doesn't look like a colour.
341 * Returns true is the passed value looks like a CSS width.
342 * In order to pass this test the value must be purely numerical or end with a
343 * valid CSS unit term.
345 * @param string|int $value
348 function css_is_width($value) {
349 $value = trim($value);
350 if (in_array(strtolower($value), array('auto', 'inherit'))) {
353 if ((string)$value === '0' ||
preg_match('#^(\-\s*)?(\d*\.)?(\d+)\s*(em|px|pt|\%|in|cm|mm|ex|pc)$#i', $value)) {
360 * A simple sorting function to sort two array values on the number of items they contain
366 function css_sort_by_count(array $a, array $b) {
372 return ($a > $b) ?
-1 : 1;
376 * A basic CSS optimiser that strips out unwanted things and then processing the
377 * CSS organising styles and moving duplicates and useless CSS.
379 * This CSS optimiser works by reading through a CSS string one character at a
380 * time and building an object structure of the CSS.
381 * As part of that processing styles are expanded out as much as they can be to
382 * ensure we collect all mappings, at the end of the processing those styles are
383 * then combined into an optimised form to keep them as short as possible.
387 * @copyright 2012 Sam Hemelryk
388 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
390 class css_optimiser
{
393 * Used when the processor is about to start processing.
394 * Processing states. Used internally.
396 const PROCESSING_START
= 0;
399 * Used when the processor is currently processing a selector.
400 * Processing states. Used internally.
402 const PROCESSING_SELECTORS
= 0;
405 * Used when the processor is currently processing a style.
406 * Processing states. Used internally.
408 const PROCESSING_STYLES
= 1;
411 * Used when the processor is currently processing a comment.
412 * Processing states. Used internally.
414 const PROCESSING_COMMENT
= 2;
417 * Used when the processor is currently processing an @ rule.
418 * Processing states. Used internally.
420 const PROCESSING_ATRULE
= 3;
423 * The raw string length before optimisation.
424 * Stats variables set during and after processing
427 protected $rawstrlen = 0;
430 * The number of comments that were removed during optimisation.
431 * Stats variables set during and after processing
434 protected $commentsincss = 0;
437 * The number of rules in the CSS before optimisation.
438 * Stats variables set during and after processing
441 protected $rawrules = 0;
444 * The number of selectors using in CSS rules before optimisation.
445 * Stats variables set during and after processing
448 protected $rawselectors = 0;
451 * The string length after optimisation.
452 * Stats variables set during and after processing
455 protected $optimisedstrlen = 0;
458 * The number of rules after optimisation.
459 * Stats variables set during and after processing
462 protected $optimisedrules = 0;
465 * The number of selectors used in rules after optimisation.
466 * Stats variables set during and after processing
469 protected $optimisedselectors = 0;
472 * The start time of the optimisation.
473 * Stats variables set during and after processing
476 protected $timestart = 0;
479 * The end time of the optimisation.
480 * Stats variables set during and after processing
483 protected $timecomplete = 0;
486 * Will be set to any errors that may have occured during processing.
487 * This is updated only at the end of processing NOT during.
491 protected $errors = array();
494 * Processes incoming CSS optimising it and then returning it.
496 * @param string $css The raw CSS to optimise
497 * @return string The optimised CSS
499 public function process($css) {
502 // Easiest win there is
505 $this->reset_stats();
506 $this->timestart
= microtime(true);
507 $this->rawstrlen
= strlen($css);
509 // Don't try to process files with no content... it just doesn't make sense.
510 // But we should produce an error for them, an empty CSS file will lead to a
511 // useless request for those running theme designer mode.
512 if ($this->rawstrlen
=== 0) {
513 $this->errors
[] = 'Skipping file as it has no content.';
517 // First up we need to remove all line breaks - this allows us to instantly
518 // reduce our processing requirements and as we will process everything
519 // into a new structure there's really nothing lost.
520 $css = preg_replace('#\r?\n#', ' ', $css);
522 // Next remove the comments... no need to them in an optimised world and
523 // knowing they're all gone allows us to REALLY make our processing simpler
524 $css = preg_replace('#/\*(.*?)\*/#m', '', $css, -1, $this->commentsincss
);
527 'all' => new css_media()
531 // Keyframes are used for CSS animation they will be processed right at the very end.
532 $keyframes = array();
534 $currentprocess = self
::PROCESSING_START
;
535 $currentrule = css_rule
::init();
536 $currentselector = css_selector
::init();
537 $inquotes = false; // ' or "
538 $inbraces = false; // {
539 $inbrackets = false; // [
540 $inparenthesis = false; // (
541 $currentmedia = $medias['all'];
542 $currentatrule = null;
543 $suspectatrule = false;
548 // Next we are going to iterate over every single character in $css.
549 // This is why we removed line breaks and comments!
550 for ($i = 0; $i < $this->rawstrlen
; $i++
) {
552 $char = substr($css, $i, 1);
553 if ($char == '@' && $buffer == '') {
554 $suspectatrule = true;
556 switch ($currentprocess) {
557 // Start processing an @ rule e.g. @media, @page, @keyframes
558 case self
::PROCESSING_ATRULE
:
563 if ($currentatrule == 'import') {
564 $imports[] = $buffer;
565 $currentprocess = self
::PROCESSING_SELECTORS
;
566 } else if ($currentatrule == 'charset') {
568 $currentprocess = self
::PROCESSING_SELECTORS
;
571 if ($currentatrule !== 'media') {
573 $currentatrule = false;
575 // continue 1: The switch processing chars
576 // continue 2: The switch processing the state
577 // continue 3: The for loop
580 if ($currentatrule == 'media' && preg_match('#\s*@media\s*([a-zA-Z0-9]+(\s*,\s*[a-zA-Z0-9]+)*)\s*{#', $buffer, $matches)) {
581 // Basic media declaration
582 $mediatypes = str_replace(' ', '', $matches[1]);
583 if (!array_key_exists($mediatypes, $medias)) {
584 $medias[$mediatypes] = new css_media($mediatypes);
586 $currentmedia = $medias[$mediatypes];
587 $currentprocess = self
::PROCESSING_SELECTORS
;
589 } else if ($currentatrule == 'media' && preg_match('#\s*@media\s*([^{]+)#', $buffer, $matches)) {
590 // Advanced media query declaration http://www.w3.org/TR/css3-mediaqueries/
591 $mediatypes = $matches[1];
592 $hash = md5($mediatypes);
593 $medias[$hash] = new css_media($mediatypes);
594 $currentmedia = $medias[$hash];
595 $currentprocess = self
::PROCESSING_SELECTORS
;
597 } else if ($currentatrule == 'keyframes' && preg_match('#@((\-moz\-|\-webkit\-)?keyframes)\s*([^\s]+)#', $buffer, $matches)) {
598 // Keyframes declaration, we treat it exactly like a @media declaration except we don't allow
599 // them to be overridden to ensure we don't mess anything up. (means we keep everything in order)
600 $keyframefor = $matches[1];
601 $keyframename = $matches[3];
602 $keyframe = new css_keyframe($keyframefor, $keyframename);
603 $keyframes[] = $keyframe;
604 $currentmedia = $keyframe;
605 $currentprocess = self
::PROCESSING_SELECTORS
;
608 // continue 1: The switch processing chars
609 // continue 2: The switch processing the state
610 // continue 3: The for loop
614 // Start processing selectors
615 case self
::PROCESSING_START
:
616 case self
::PROCESSING_SELECTORS
:
621 // continue 1: The switch processing chars
622 // continue 2: The switch processing the state
623 // continue 3: The for loop
628 // continue 1: The switch processing chars
629 // continue 2: The switch processing the state
630 // continue 3: The for loop
634 // continue 1: The switch processing chars
635 // continue 2: The switch processing the state
636 // continue 3: The for loop
639 if (!empty($buffer)) {
640 // Check for known @ rules
641 if ($suspectatrule && preg_match('#@(media|import|charset|(\-moz\-|\-webkit\-)?(keyframes))\s*#', $buffer, $matches)) {
642 $currentatrule = (!empty($matches[3]))?
$matches[3]:$matches[1];
643 $currentprocess = self
::PROCESSING_ATRULE
;
646 $currentselector->add($buffer);
650 $suspectatrule = false;
651 // continue 1: The switch processing chars
652 // continue 2: The switch processing the state
653 // continue 3: The for loop
657 // continue 1: The switch processing chars
658 // continue 2: The switch processing the state
659 // continue 3: The for loop
662 if ($buffer !== '') {
663 $currentselector->add($buffer);
665 $currentrule->add_selector($currentselector);
666 $currentselector = css_selector
::init();
667 $currentprocess = self
::PROCESSING_STYLES
;
670 // continue 1: The switch processing chars
671 // continue 2: The switch processing the state
672 // continue 3: The for loop
676 // continue 1: The switch processing chars
677 // continue 2: The switch processing the state
678 // continue 3: The for loop
681 if ($currentatrule == 'media') {
682 $currentmedia = $medias['all'];
683 $currentatrule = false;
685 } else if (strpos($currentatrule, 'keyframes') !== false) {
686 $currentmedia = $medias['all'];
687 $currentatrule = false;
690 // continue 1: The switch processing chars
691 // continue 2: The switch processing the state
692 // continue 3: The for loop
696 // continue 1: The switch processing chars
697 // continue 2: The switch processing the state
698 // continue 3: The for loop
701 $currentselector->add($buffer);
702 $currentrule->add_selector($currentselector);
703 $currentselector = css_selector
::init();
705 // continue 1: The switch processing chars
706 // continue 2: The switch processing the state
707 // continue 3: The for loop
711 // Start processing styles
712 case self
::PROCESSING_STYLES
:
713 if ($char == '"' ||
$char == "'") {
714 if ($inquotes === false) {
717 if ($inquotes === $char && $lastchar !== '\\') {
727 if ($inparenthesis) {
729 // continue 1: The switch processing chars
730 // continue 2: The switch processing the state
731 // continue 3: The for loop
734 $currentrule->add_style($buffer);
737 // continue 1: The switch processing chars
738 // continue 2: The switch processing the state
739 // continue 3: The for loop
742 $currentrule->add_style($buffer);
743 $this->rawselectors +
= $currentrule->get_selector_count();
745 $currentmedia->add_rule($currentrule);
747 $currentrule = css_rule
::init();
748 $currentprocess = self
::PROCESSING_SELECTORS
;
752 $inparenthesis = false;
753 // continue 1: The switch processing chars
754 // continue 2: The switch processing the state
755 // continue 3: The for loop
758 $inparenthesis = true;
760 // continue 1: The switch processing chars
761 // continue 2: The switch processing the state
762 // continue 3: The for loop
765 $inparenthesis = false;
767 // continue 1: The switch processing chars
768 // continue 2: The switch processing the state
769 // continue 3: The for loop
777 foreach ($medias as $media) {
778 $this->optimise($media);
780 $css = $this->produce_css($charset, $imports, $medias, $keyframes);
782 $this->timecomplete
= microtime(true);
787 * Produces CSS for the given charset, imports, media, and keyframes
788 * @param string $charset
789 * @param array $imports
790 * @param array $medias
791 * @param array $keyframes
794 protected function produce_css($charset, array $imports, array $medias, array $keyframes) {
796 if (!empty($charset)) {
797 $imports[] = $charset;
799 if (!empty($imports)) {
800 $css .= implode("\n", $imports);
805 $cssstandard = array();
806 $csskeyframes = array();
808 // Process each media declaration individually
809 foreach ($medias as $media) {
810 // If this declaration applies to all media types
811 if (in_array('all', $media->get_types())) {
812 // Collect all rules that represet reset rules and remove them from the media object at the same time.
813 // We do this because we prioritise reset rules to the top of a CSS output. This ensures that they
814 // can't end up out of order because of optimisation.
815 $resetrules = $media->get_reset_rules(true);
816 if (!empty($resetrules)) {
817 $cssreset[] = css_writer
::media('all', $resetrules);
820 // Get the standard cSS
821 $cssstandard[] = $media->out();
824 // Finally if there are any keyframe declarations process them now.
825 if (count($keyframes) > 0) {
826 foreach ($keyframes as $keyframe) {
827 $this->optimisedrules +
= $keyframe->count_rules();
828 $this->optimisedselectors +
= $keyframe->count_selectors();
829 if ($keyframe->has_errors()) {
830 $this->errors +
= $keyframe->get_errors();
832 $csskeyframes[] = $keyframe->out();
836 // Join it all together
837 $css .= join('', $cssreset);
838 $css .= join('', $cssstandard);
839 $css .= join('', $csskeyframes);
841 // Record the strlenght of the now optimised CSS.
842 $this->optimisedstrlen
= strlen($css);
844 // Return the now produced CSS
849 * Optimises the CSS rules within a rule collection of one form or another
851 * @param css_rule_collection $media
852 * @return void This function acts in reference
854 protected function optimise(css_rule_collection
$media) {
855 $media->organise_rules_by_selectors();
856 $this->optimisedrules +
= $media->count_rules();
857 $this->optimisedselectors +
= $media->count_selectors();
858 if ($media->has_errors()) {
859 $this->errors +
= $media->get_errors();
864 * Returns an array of stats from the last processing run
867 public function get_stats() {
869 'timestart' => $this->timestart
,
870 'timecomplete' => $this->timecomplete
,
871 'timetaken' => round($this->timecomplete
- $this->timestart
, 4),
872 'commentsincss' => $this->commentsincss
,
873 'rawstrlen' => $this->rawstrlen
,
874 'rawselectors' => $this->rawselectors
,
875 'rawrules' => $this->rawrules
,
876 'optimisedstrlen' => $this->optimisedstrlen
,
877 'optimisedrules' => $this->optimisedrules
,
878 'optimisedselectors' => $this->optimisedselectors
,
879 'improvementstrlen' => '-',
880 'improvementrules' => '-',
881 'improvementselectors' => '-',
883 // Avoid division by 0 errors by checking we have valid raw values
884 if ($this->rawstrlen
> 0) {
885 $stats['improvementstrlen'] = round(100 - ($this->optimisedstrlen
/ $this->rawstrlen
) * 100, 1).'%';
887 if ($this->rawrules
> 0) {
888 $stats['improvementrules'] = round(100 - ($this->optimisedrules
/ $this->rawrules
) * 100, 1).'%';
890 if ($this->rawselectors
> 0) {
891 $stats['improvementselectors'] = round(100 - ($this->optimisedselectors
/ $this->rawselectors
) * 100, 1).'%';
897 * Returns true if any errors have occured during processing
901 public function has_errors() {
902 return !empty($this->errors
);
906 * Returns an array of errors that have occured
908 * @param bool $clear If set to true the errors will be cleared after being returned.
911 public function get_errors($clear = false) {
912 $errors = $this->errors
;
914 // Reset the error array
915 $this->errors
= array();
921 * Returns any errors as a string that can be included in CSS.
925 public function output_errors_css() {
926 $computedcss = "/****************************************\n";
927 $computedcss .= " *--- Errors found during processing ----\n";
928 foreach ($this->errors
as $error) {
929 $computedcss .= preg_replace('#^#m', '* ', $error);
931 $computedcss .= " ****************************************/\n\n";
936 * Returns a string to display stats about the last generation within CSS output
940 public function output_stats_css() {
942 $computedcss = "/****************************************\n";
943 $computedcss .= " *------- CSS Optimisation stats --------\n";
945 if ($this->rawstrlen
=== 0) {
946 $computedcss .= " File not processed as it has no content /\n\n";
947 $computedcss .= " ****************************************/\n\n";
949 } else if ($this->rawrules
=== 0) {
950 $computedcss .= " File contained no rules to be processed /\n\n";
951 $computedcss .= " ****************************************/\n\n";
955 $stats = $this->get_stats();
957 $computedcss .= " * ".date('r')."\n";
958 $computedcss .= " * {$stats['commentsincss']} \t comments removed\n";
959 $computedcss .= " * Optimisation took {$stats['timetaken']} seconds\n";
960 $computedcss .= " *--------------- before ----------------\n";
961 $computedcss .= " * {$stats['rawstrlen']} \t chars read in\n";
962 $computedcss .= " * {$stats['rawrules']} \t rules read in\n";
963 $computedcss .= " * {$stats['rawselectors']} \t total selectors\n";
964 $computedcss .= " *---------------- after ----------------\n";
965 $computedcss .= " * {$stats['optimisedstrlen']} \t chars once optimized\n";
966 $computedcss .= " * {$stats['optimisedrules']} \t optimized rules\n";
967 $computedcss .= " * {$stats['optimisedselectors']} \t total selectors once optimized\n";
968 $computedcss .= " *---------------- stats ----------------\n";
969 $computedcss .= " * {$stats['improvementstrlen']} \t reduction in chars\n";
970 $computedcss .= " * {$stats['improvementrules']} \t reduction in rules\n";
971 $computedcss .= " * {$stats['improvementselectors']} \t reduction in selectors\n";
972 $computedcss .= " ****************************************/\n\n";
978 * Resets the stats ready for another fresh processing
980 public function reset_stats() {
981 $this->commentsincss
= 0;
982 $this->optimisedrules
= 0;
983 $this->optimisedselectors
= 0;
984 $this->optimisedstrlen
= 0;
986 $this->rawselectors
= 0;
987 $this->rawstrlen
= 0;
988 $this->timecomplete
= 0;
989 $this->timestart
= 0;
993 * An array of the common HTML colours that are supported by most browsers.
995 * This reference table is used to allow us to unify colours, and will aid
996 * us in identifying buggy CSS using unsupported colours.
1001 public static $htmlcolours = array(
1002 'aliceblue' => '#F0F8FF',
1003 'antiquewhite' => '#FAEBD7',
1004 'aqua' => '#00FFFF',
1005 'aquamarine' => '#7FFFD4',
1006 'azure' => '#F0FFFF',
1007 'beige' => '#F5F5DC',
1008 'bisque' => '#FFE4C4',
1009 'black' => '#000000',
1010 'blanchedalmond' => '#FFEBCD',
1011 'blue' => '#0000FF',
1012 'blueviolet' => '#8A2BE2',
1013 'brown' => '#A52A2A',
1014 'burlywood' => '#DEB887',
1015 'cadetblue' => '#5F9EA0',
1016 'chartreuse' => '#7FFF00',
1017 'chocolate' => '#D2691E',
1018 'coral' => '#FF7F50',
1019 'cornflowerblue' => '#6495ED',
1020 'cornsilk' => '#FFF8DC',
1021 'crimson' => '#DC143C',
1022 'cyan' => '#00FFFF',
1023 'darkblue' => '#00008B',
1024 'darkcyan' => '#008B8B',
1025 'darkgoldenrod' => '#B8860B',
1026 'darkgray' => '#A9A9A9',
1027 'darkgrey' => '#A9A9A9',
1028 'darkgreen' => '#006400',
1029 'darkKhaki' => '#BDB76B',
1030 'darkmagenta' => '#8B008B',
1031 'darkolivegreen' => '#556B2F',
1032 'arkorange' => '#FF8C00',
1033 'darkorchid' => '#9932CC',
1034 'darkred' => '#8B0000',
1035 'darksalmon' => '#E9967A',
1036 'darkseagreen' => '#8FBC8F',
1037 'darkslateblue' => '#483D8B',
1038 'darkslategray' => '#2F4F4F',
1039 'darkslategrey' => '#2F4F4F',
1040 'darkturquoise' => '#00CED1',
1041 'darkviolet' => '#9400D3',
1042 'deeppink' => '#FF1493',
1043 'deepskyblue' => '#00BFFF',
1044 'dimgray' => '#696969',
1045 'dimgrey' => '#696969',
1046 'dodgerblue' => '#1E90FF',
1047 'firebrick' => '#B22222',
1048 'floralwhite' => '#FFFAF0',
1049 'forestgreen' => '#228B22',
1050 'fuchsia' => '#FF00FF',
1051 'gainsboro' => '#DCDCDC',
1052 'ghostwhite' => '#F8F8FF',
1053 'gold' => '#FFD700',
1054 'goldenrod' => '#DAA520',
1055 'gray' => '#808080',
1056 'grey' => '#808080',
1057 'green' => '#008000',
1058 'greenyellow' => '#ADFF2F',
1059 'honeydew' => '#F0FFF0',
1060 'hotpink' => '#FF69B4',
1061 'indianred ' => '#CD5C5C',
1062 'indigo ' => '#4B0082',
1063 'ivory' => '#FFFFF0',
1064 'khaki' => '#F0E68C',
1065 'lavender' => '#E6E6FA',
1066 'lavenderblush' => '#FFF0F5',
1067 'lawngreen' => '#7CFC00',
1068 'lemonchiffon' => '#FFFACD',
1069 'lightblue' => '#ADD8E6',
1070 'lightcoral' => '#F08080',
1071 'lightcyan' => '#E0FFFF',
1072 'lightgoldenrodyellow' => '#FAFAD2',
1073 'lightgray' => '#D3D3D3',
1074 'lightgrey' => '#D3D3D3',
1075 'lightgreen' => '#90EE90',
1076 'lightpink' => '#FFB6C1',
1077 'lightsalmon' => '#FFA07A',
1078 'lightseagreen' => '#20B2AA',
1079 'lightskyblue' => '#87CEFA',
1080 'lightslategray' => '#778899',
1081 'lightslategrey' => '#778899',
1082 'lightsteelblue' => '#B0C4DE',
1083 'lightyellow' => '#FFFFE0',
1084 'lime' => '#00FF00',
1085 'limegreen' => '#32CD32',
1086 'linen' => '#FAF0E6',
1087 'magenta' => '#FF00FF',
1088 'maroon' => '#800000',
1089 'mediumaquamarine' => '#66CDAA',
1090 'mediumblue' => '#0000CD',
1091 'mediumorchid' => '#BA55D3',
1092 'mediumpurple' => '#9370D8',
1093 'mediumseagreen' => '#3CB371',
1094 'mediumslateblue' => '#7B68EE',
1095 'mediumspringgreen' => '#00FA9A',
1096 'mediumturquoise' => '#48D1CC',
1097 'mediumvioletred' => '#C71585',
1098 'midnightblue' => '#191970',
1099 'mintcream' => '#F5FFFA',
1100 'mistyrose' => '#FFE4E1',
1101 'moccasin' => '#FFE4B5',
1102 'navajowhite' => '#FFDEAD',
1103 'navy' => '#000080',
1104 'oldlace' => '#FDF5E6',
1105 'olive' => '#808000',
1106 'olivedrab' => '#6B8E23',
1107 'orange' => '#FFA500',
1108 'orangered' => '#FF4500',
1109 'orchid' => '#DA70D6',
1110 'palegoldenrod' => '#EEE8AA',
1111 'palegreen' => '#98FB98',
1112 'paleturquoise' => '#AFEEEE',
1113 'palevioletred' => '#D87093',
1114 'papayawhip' => '#FFEFD5',
1115 'peachpuff' => '#FFDAB9',
1116 'peru' => '#CD853F',
1117 'pink' => '#FFC0CB',
1118 'plum' => '#DDA0DD',
1119 'powderblue' => '#B0E0E6',
1120 'purple' => '#800080',
1122 'rosybrown' => '#BC8F8F',
1123 'royalblue' => '#4169E1',
1124 'saddlebrown' => '#8B4513',
1125 'salmon' => '#FA8072',
1126 'sandybrown' => '#F4A460',
1127 'seagreen' => '#2E8B57',
1128 'seashell' => '#FFF5EE',
1129 'sienna' => '#A0522D',
1130 'silver' => '#C0C0C0',
1131 'skyblue' => '#87CEEB',
1132 'slateblue' => '#6A5ACD',
1133 'slategray' => '#708090',
1134 'slategrey' => '#708090',
1135 'snow' => '#FFFAFA',
1136 'springgreen' => '#00FF7F',
1137 'steelblue' => '#4682B4',
1139 'teal' => '#008080',
1140 'thistle' => '#D8BFD8',
1141 'tomato' => '#FF6347',
1142 'transparent' => 'transparent',
1143 'turquoise' => '#40E0D0',
1144 'violet' => '#EE82EE',
1145 'wheat' => '#F5DEB3',
1146 'white' => '#FFFFFF',
1147 'whitesmoke' => '#F5F5F5',
1148 'yellow' => '#FFFF00',
1149 'yellowgreen' => '#9ACD32'
1154 * Used to prepare CSS strings
1158 * @copyright 2012 Sam Hemelryk
1159 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1161 abstract class css_writer
{
1164 * The current indent level
1167 protected static $indent = 0;
1170 * Returns true if the output should still maintain minimum formatting.
1173 protected static function is_pretty() {
1175 return (!empty($CFG->cssoptimiserpretty
));
1179 * Returns the indenting char to use for indenting things nicely.
1182 protected static function get_indent() {
1183 if (self
::is_pretty()) {
1184 return str_repeat(" ", self
::$indent);
1190 * Increases the current indent
1192 protected static function increase_indent() {
1197 * Decreases the current indent
1199 protected static function decrease_indent() {
1204 * Returns the string to use as a separator
1207 protected static function get_separator() {
1208 return (self
::is_pretty())?
"\n":' ';
1212 * Returns CSS for media
1214 * @param string $typestring
1215 * @param array $rules An array of css_rule objects
1218 public static function media($typestring, array &$rules) {
1219 $nl = self
::get_separator();
1222 if ($typestring !== 'all') {
1223 $output .= "\n@media {$typestring} {".$nl;
1224 self
::increase_indent();
1226 foreach ($rules as $rule) {
1227 $output .= $rule->out().$nl;
1229 if ($typestring !== 'all') {
1230 self
::decrease_indent();
1237 * Returns CSS for a keyframe
1239 * @param string $for The desired declaration. e.g. keyframes, -moz-keyframes, -webkit-keyframes
1240 * @param string $name The name for the keyframe
1241 * @param array $rules An array of rules belonging to the keyframe
1244 public static function keyframe($for, $name, array &$rules) {
1245 $nl = self
::get_separator();
1247 $output = "\n@{$for} {$name} {";
1248 foreach ($rules as $rule) {
1249 $output .= $rule->out();
1256 * Returns CSS for a rule
1258 * @param string $selector
1259 * @param string $styles
1262 public static function rule($selector, $styles) {
1263 $css = self
::get_indent()."{$selector}{{$styles}}";
1268 * Returns CSS for the selectors of a rule
1270 * @param array $selectors Array of css_selector objects
1273 public static function selectors(array $selectors) {
1274 $nl = self
::get_separator();
1275 $selectorstrings = array();
1276 foreach ($selectors as $selector) {
1277 $selectorstrings[] = $selector->out();
1279 return join(','.$nl, $selectorstrings);
1283 * Returns a selector given the components that make it up.
1285 * @param array $components
1288 public static function selector(array $components) {
1289 return trim(join(' ', $components));
1293 * Returns a CSS string for the provided styles
1295 * @param array $styles Array of css_style objects
1298 public static function styles(array $styles) {
1300 foreach ($styles as $style) {
1301 // Check if the style is an array. If it is then we are outputing an advanced style.
1302 // An advanced style is a style with one or more values, and can occur in situations like background-image
1303 // where browse specific values are being used.
1304 if (is_array($style)) {
1305 foreach ($style as $advstyle) {
1306 $bits[] = $advstyle->out();
1310 $bits[] = $style->out();
1312 return join('', $bits);
1316 * Returns a style CSS
1318 * @param string $name
1319 * @param string $value
1320 * @param bool $important
1323 public static function style($name, $value, $important = false) {
1324 $value = trim($value);
1325 if ($important && strpos($value, '!important') === false) {
1326 $value .= ' !important';
1328 return "{$name}:{$value};";
1333 * A structure to represent a CSS selector.
1335 * The selector is the classes, id, elements, and psuedo bits that make up a CSS
1340 * @copyright 2012 Sam Hemelryk
1341 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1343 class css_selector
{
1346 * An array of selector bits
1349 protected $selectors = array();
1352 * The number of selectors.
1355 protected $count = 0;
1358 * Is null if there are no selectors, true if all selectors are basic and false otherwise.
1359 * A basic selector is one that consists of just the element type. e.g. div, span, td, a
1362 protected $isbasic = null;
1365 * Initialises a new CSS selector
1366 * @return css_selector
1368 public static function init() {
1369 return new css_selector();
1373 * CSS selectors can only be created through the init method above.
1375 protected function __construct() {}
1378 * Adds a selector to the end of the current selector
1379 * @param string $selector
1381 public function add($selector) {
1382 $selector = trim($selector);
1384 $count +
= preg_match_all('/(\.|#)/', $selector, $matchesarray);
1385 if (strpos($selector, '.') !== 0 && strpos($selector, '#') !== 0) {
1388 // If its already false then no need to continue, its not basic
1389 if ($this->isbasic
!== false) {
1390 // If theres more than one part making up this selector its not basic
1392 $this->isbasic
= false;
1394 // Check whether it is a basic element (a-z+) with possible psuedo selector
1395 $this->isbasic
= (bool)preg_match('#^[a-z]+(:[a-zA-Z]+)?$#', $selector);
1398 $this->count
= $count;
1399 $this->selectors
[] = $selector;
1402 * Returns the number of individual components that make up this selector
1405 public function get_selector_count() {
1406 return $this->count
;
1410 * Returns the selector for use in a CSS rule
1413 public function out() {
1414 return css_writer
::selector($this->selectors
);
1418 * Returns true is all of the selectors act only upon basic elements (no classes/ids)
1421 public function is_basic() {
1422 return ($this->isbasic
=== true);
1427 * A structure to represent a CSS rule.
1431 * @copyright 2012 Sam Hemelryk
1432 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1437 * An array of CSS selectors {@link css_selector}
1440 protected $selectors = array();
1443 * An array of CSS styles {@link css_style}
1446 protected $styles = array();
1449 * Created a new CSS rule. This is the only way to create a new CSS rule externally.
1452 public static function init() {
1453 return new css_rule();
1457 * Constructs a new css rule.
1459 * @param string $selector The selector or array of selectors that make up this rule.
1460 * @param array $styles An array of styles that belong to this rule.
1462 protected function __construct($selector = null, array $styles = array()) {
1463 if ($selector != null) {
1464 if (is_array($selector)) {
1465 $this->selectors
= $selector;
1467 $this->selectors
= array($selector);
1469 $this->add_styles($styles);
1474 * Adds a new CSS selector to this rule
1476 * e.g. $rule->add_selector('.one #two.two');
1478 * @param css_selector $selector Adds a CSS selector to this rule.
1480 public function add_selector(css_selector
$selector) {
1481 $this->selectors
[] = $selector;
1485 * Adds a new CSS style to this rule.
1487 * @param css_style|string $style Adds a new style to this rule
1489 public function add_style($style) {
1490 if (is_string($style)) {
1491 $style = trim($style);
1492 if (empty($style)) {
1495 $bits = explode(':', $style, 2);
1496 if (count($bits) == 2) {
1497 list($name, $value) = array_map('trim', $bits);
1499 if (isset($name) && isset($value) && $name !== '' && $value !== '') {
1500 $style = css_style
::init_automatic($name, $value);
1502 } else if ($style instanceof css_style
) {
1503 // Clone the style as it may be coming from another rule and we don't
1504 // want references as it will likely be overwritten by proceeding
1506 $style = clone($style);
1508 if ($style instanceof css_style
) {
1509 $name = $style->get_name();
1510 $exists = array_key_exists($name, $this->styles
);
1511 // We need to find out if the current style support multiple values, or whether the style
1512 // is already set up to record multiple values. This can happen with background images which can have single
1513 // and multiple values.
1514 if ($style->allows_multiple_values() ||
($exists && is_array($this->styles
[$name]))) {
1516 $this->styles
[$name] = array();
1517 } else if ($this->styles
[$name] instanceof css_style
) {
1518 $this->styles
[$name] = array($this->styles
[$name]);
1520 $this->styles
[$name][] = $style;
1521 } else if ($exists) {
1522 $this->styles
[$name]->set_value($style->get_value());
1524 $this->styles
[$name] = $style;
1526 } else if (is_array($style)) {
1527 // We probably shouldn't worry about processing styles here but to
1528 // be truthful it doesn't hurt.
1529 foreach ($style as $astyle) {
1530 $this->add_style($astyle);
1536 * An easy method of adding several styles at once. Just calls add_style.
1538 * This method simply iterates over the array and calls {@link css_rule::add_style()}
1541 * @param array $styles Adds an array of styles
1543 public function add_styles(array $styles) {
1544 foreach ($styles as $style) {
1545 $this->add_style($style);
1550 * Returns the array of selectors
1554 public function get_selectors() {
1555 return $this->selectors
;
1559 * Returns the array of styles
1563 public function get_styles() {
1564 return $this->styles
;
1568 * Outputs this rule as a fragment of CSS
1572 public function out() {
1573 $selectors = css_writer
::selectors($this->selectors
);
1574 $styles = css_writer
::styles($this->get_consolidated_styles());
1575 return css_writer
::rule($selectors, $styles);
1579 * Consolidates all styles associated with this rule
1581 * @return array An array of consolidated styles
1583 public function get_consolidated_styles() {
1584 $organisedstyles = array();
1585 $finalstyles = array();
1586 $consolidate = array();
1587 $advancedstyles = array();
1588 foreach ($this->styles
as $style) {
1589 // If the style is an array then we are processing an advanced style. An advanced style is a style that can have
1590 // one or more values. Background-image is one such example as it can have browser specific styles.
1591 if (is_array($style)) {
1594 foreach ($style as $advstyle) {
1596 $advancedstyles[$key] = $advstyle;
1597 if (!$advstyle->allows_multiple_values()) {
1598 if (!is_null($single)) {
1599 unset($advancedstyles[$single]);
1604 if (!is_null($single)) {
1605 $style = $advancedstyles[$single];
1607 $consolidatetoclass = $style->consolidate_to();
1608 if (($style->is_valid() ||
$style->is_special_empty_value()) && !empty($consolidatetoclass) && class_exists('css_style_'.$consolidatetoclass)) {
1609 $class = 'css_style_'.$consolidatetoclass;
1610 if (!array_key_exists($class, $consolidate)) {
1611 $consolidate[$class] = array();
1612 $organisedstyles[$class] = true;
1614 $consolidate[$class][] = $style;
1615 unset($advancedstyles[$single]);
1621 $consolidatetoclass = $style->consolidate_to();
1622 if (($style->is_valid() ||
$style->is_special_empty_value()) && !empty($consolidatetoclass) && class_exists('css_style_'.$consolidatetoclass)) {
1623 $class = 'css_style_'.$consolidatetoclass;
1624 if (!array_key_exists($class, $consolidate)) {
1625 $consolidate[$class] = array();
1626 $organisedstyles[$class] = true;
1628 $consolidate[$class][] = $style;
1630 $organisedstyles[$style->get_name()] = $style;
1634 foreach ($consolidate as $class => $styles) {
1635 $organisedstyles[$class] = $class::consolidate($styles);
1638 foreach ($organisedstyles as $style) {
1639 if (is_array($style)) {
1640 foreach ($style as $s) {
1641 $finalstyles[] = $s;
1644 $finalstyles[] = $style;
1647 $finalstyles = array_merge($finalstyles, $advancedstyles);
1648 return $finalstyles;
1652 * Splits this rules into an array of CSS rules. One for each of the selectors
1653 * that make up this rule.
1655 * @return array(css_rule)
1657 public function split_by_selector() {
1659 foreach ($this->selectors
as $selector) {
1660 $return[] = new css_rule($selector, $this->styles
);
1666 * Splits this rule into an array of rules. One for each of the styles that
1669 * @return array Array of css_rule objects
1671 public function split_by_style() {
1673 foreach ($this->styles
as $style) {
1674 if (is_array($style)) {
1675 $return[] = new css_rule($this->selectors
, $style);
1678 $return[] = new css_rule($this->selectors
, array($style));
1684 * Gets a hash for the styles of this rule
1688 public function get_style_hash() {
1689 return md5(css_writer
::styles($this->styles
));
1693 * Gets a hash for the selectors of this rule
1697 public function get_selector_hash() {
1698 return md5(css_writer
::selectors($this->selectors
));
1702 * Gets the number of selectors that make up this rule.
1706 public function get_selector_count() {
1708 foreach ($this->selectors
as $selector) {
1709 $count +
= $selector->get_selector_count();
1715 * Returns true if there are any errors with this rule.
1719 public function has_errors() {
1720 foreach ($this->styles
as $style) {
1721 if (is_array($style)) {
1722 foreach ($style as $advstyle) {
1723 if ($advstyle->has_error()) {
1729 if ($style->has_error()) {
1737 * Returns the error strings that were recorded when processing this rule.
1739 * Before calling this function you should first call {@link css_rule::has_errors()}
1740 * to make sure there are errors (hopefully there arn't).
1744 public function get_error_string() {
1745 $css = $this->out();
1747 foreach ($this->styles
as $style) {
1748 if ($style->has_error()) {
1749 $errors[] = " * ".$style->get_last_error();
1752 return $css." has the following errors:\n".join("\n", $errors);
1756 * Returns true if this rule could be considered a reset rule.
1758 * A reset rule is a rule that acts upon an HTML element and does not include any other parts to its selector.
1762 public function is_reset_rule() {
1763 foreach ($this->selectors
as $selector) {
1764 if (!$selector->is_basic()) {
1773 * An abstract CSS rule collection class.
1775 * This class is extended by things such as media and keyframe declaration. They are declarations that
1776 * group rules together for a purpose.
1777 * When no declaration is specified rules accumulate into @media all.
1781 * @copyright 2012 Sam Hemelryk
1782 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1784 abstract class css_rule_collection
{
1786 * An array of rules within this collection instance
1789 protected $rules = array();
1792 * The collection must be able to print itself.
1794 abstract public function out();
1797 * Adds a new CSS rule to this collection instance
1799 * @param css_rule $newrule
1801 public function add_rule(css_rule
$newrule) {
1802 foreach ($newrule->split_by_selector() as $rule) {
1803 $hash = $rule->get_selector_hash();
1804 if (!array_key_exists($hash, $this->rules
)) {
1805 $this->rules
[$hash] = $rule;
1807 $this->rules
[$hash]->add_styles($rule->get_styles());
1813 * Returns the rules used by this collection
1817 public function get_rules() {
1818 return $this->rules
;
1822 * Organises rules by gropuing selectors based upon the styles and consolidating
1823 * those selectors into single rules.
1825 * @return bool True if the CSS was optimised by this method
1827 public function organise_rules_by_selectors() {
1828 $optimised = array();
1829 $beforecount = count($this->rules
);
1832 foreach ($this->rules
as $rule) {
1833 $hash = $rule->get_style_hash();
1834 if ($lastrule !== null && $lasthash !== null && $hash === $lasthash) {
1835 foreach ($rule->get_selectors() as $selector) {
1836 $lastrule->add_selector($selector);
1840 $lastrule = clone($rule);
1842 $optimised[] = $lastrule;
1844 $this->rules
= array();
1845 foreach ($optimised as $optimised) {
1846 $this->rules
[$optimised->get_selector_hash()] = $optimised;
1848 $aftercount = count($this->rules
);
1849 return ($beforecount < $aftercount);
1853 * Returns the total number of rules that exist within this collection
1857 public function count_rules() {
1858 return count($this->rules
);
1862 * Returns the total number of selectors that exist within this collection
1866 public function count_selectors() {
1868 foreach ($this->rules
as $rule) {
1869 $count +
= $rule->get_selector_count();
1875 * Returns true if the collection has any rules that have errors
1879 public function has_errors() {
1880 foreach ($this->rules
as $rule) {
1881 if ($rule->has_errors()) {
1889 * Returns any errors that have happened within rules in this collection.
1893 public function get_errors() {
1895 foreach ($this->rules
as $rule) {
1896 if ($rule->has_errors()) {
1897 $errors[] = $rule->get_error_string();
1905 * A media class to organise rules by the media they apply to.
1909 * @copyright 2012 Sam Hemelryk
1910 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1912 class css_media
extends css_rule_collection
{
1915 * An array of the different media types this instance applies to.
1918 protected $types = array();
1921 * Initalises a new media instance
1923 * @param string $for The media that the contained rules are destined for.
1925 public function __construct($for = 'all') {
1926 $types = explode(',', $for);
1927 $this->types
= array_map('trim', $types);
1931 * Returns the CSS for this media and all of its rules.
1935 public function out() {
1936 return css_writer
::media(join(',', $this->types
), $this->rules
);
1940 * Returns an array of media that this media instance applies to
1944 public function get_types() {
1945 return $this->types
;
1949 * Returns all of the reset rules known by this media set.
1950 * @param bool $remove If set to true reset rules will be removed before being returned.
1953 public function get_reset_rules($remove = false) {
1954 $resetrules = array();
1955 foreach ($this->rules
as $key => $rule) {
1956 if ($rule->is_reset_rule()) {
1957 $resetrules[] = clone $rule;
1959 unset($this->rules
[$key]);
1968 * A media class to organise rules by the media they apply to.
1972 * @copyright 2012 Sam Hemelryk
1973 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1975 class css_keyframe
extends css_rule_collection
{
1977 /** @var string $for The directive e.g. keyframes, -moz-keyframes, -webkit-keyframes */
1980 /** @var string $name The name for the keyframes */
1983 * Constructs a new keyframe
1985 * @param string $for The directive e.g. keyframes, -moz-keyframes, -webkit-keyframes
1986 * @param string $name The name for the keyframes
1988 public function __construct($for, $name) {
1990 $this->name
= $name;
1993 * Returns the directive of this keyframe
1995 * e.g. keyframes, -moz-keyframes, -webkit-keyframes
1998 public function get_for() {
2002 * Returns the name of this keyframe
2005 public function get_name() {
2009 * Returns the CSS for this collection of keyframes and all of its rules.
2013 public function out() {
2014 return css_writer
::keyframe($this->for, $this->name
, $this->rules
);
2019 * An absract class to represent CSS styles
2023 * @copyright 2012 Sam Hemelryk
2024 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2026 abstract class css_style
{
2028 /** Constant used for recongise a special empty value in a CSS style */
2029 const NULL_VALUE
= '@@$NULL$@@';
2032 * The name of the style
2038 * The value for the style
2044 * If set to true this style was defined with the !important rule.
2045 * Only trolls use !important.
2046 * Don't hide under bridges.. its not good for your skin. Do the proper thing
2047 * and fix the issue don't just force a fix that will undoubtedly one day
2048 * lead to further frustration.
2051 protected $important = false;
2054 * Gets set to true if this style has an error
2057 protected $error = false;
2060 * The last error message that occured
2063 protected $errormessage = null;
2066 * Initialises a new style.
2068 * This is the only public way to create a style to ensure they that appropriate
2069 * style class is used if it exists.
2071 * @param string $name The name of the style.
2072 * @param string $value The value of the style.
2073 * @return css_style_generic
2075 public static function init_automatic($name, $value) {
2076 $specificclass = 'css_style_'.preg_replace('#[^a-zA-Z0-9]+#', '', $name);
2077 if (class_exists($specificclass)) {
2078 return $specificclass::init($value);
2080 return new css_style_generic($name, $value);
2084 * Creates a new style when given its name and value
2086 * @param string $name The name of the style.
2087 * @param string $value The value of the style.
2089 protected function __construct($name, $value) {
2090 $this->name
= $name;
2091 $this->set_value($value);
2095 * Sets the value for the style
2097 * @param string $value
2099 final public function set_value($value) {
2100 $value = trim($value);
2101 $important = preg_match('#(\!important\s*;?\s*)$#', $value, $matches);
2103 $value = substr($value, 0, -(strlen($matches[1])));
2104 $value = rtrim($value);
2106 if (!$this->important ||
$important) {
2107 $this->value
= $this->clean_value($value);
2108 $this->important
= $important;
2110 if (!$this->is_valid()) {
2111 $this->set_error('Invalid value for '.$this->name
);
2116 * Returns true if the value associated with this style is valid
2120 public function is_valid() {
2125 * Returns the name for the style
2129 public function get_name() {
2134 * Returns the value for the style
2136 * @param bool $includeimportant If set to true and the rule is important !important postfix will be used.
2139 public function get_value($includeimportant = true) {
2140 $value = $this->value
;
2141 if ($includeimportant && $this->important
) {
2142 $value .= ' !important';
2148 * Returns the style ready for use in CSS
2150 * @param string|null $value A value to use to override the value for this style.
2153 public function out($value = null) {
2154 if (is_null($value)) {
2155 $value = $this->get_value();
2157 return css_writer
::style($this->name
, $value, $this->important
);
2161 * This can be overridden by a specific style allowing it to clean its values
2164 * @param mixed $value
2167 protected function clean_value($value) {
2172 * If this particular style can be consolidated into another style this function
2173 * should return the style that it can be consolidated into.
2175 * @return string|null
2177 public function consolidate_to() {
2182 * Sets the last error message.
2184 * @param string $message
2186 protected function set_error($message) {
2187 $this->error
= true;
2188 $this->errormessage
= $message;
2192 * Returns true if an error has occured
2196 public function has_error() {
2197 return $this->error
;
2201 * Returns the last error that occured or null if no errors have happened.
2205 public function get_last_error() {
2206 return $this->errormessage
;
2210 * Returns true if the value for this style is the special null value.
2212 * This should only be overriden in circumstances where a shorthand style can lead
2213 * to move explicit styles being overwritten. Not a common place occurenace.
2216 * This occurs if the shorthand background property was used but no proper value
2217 * was specified for this style.
2218 * This leads to a null value being used unless otherwise overridden.
2222 public function is_special_empty_value() {
2227 * Returns true if this style permits multiple values.
2229 * This occurs for styles such as background image that can have browser specific values that need to be maintained because
2230 * of course we don't know what browser the user is using, and optimisation occurs before caching.
2231 * Thus we must always server all values we encounter in the order we encounter them for when this is set to true.
2233 * @return boolean False by default, true if the style supports muliple values.
2235 public function allows_multiple_values() {
2240 * Returns true if this style was marked important.
2243 public function is_important() {
2244 return !empty($this->important
);
2248 * Sets the important flag for this style and its current value.
2249 * @param bool $important
2251 public function set_important($important = true) {
2252 $this->important
= (bool) $important;
2257 * A generic CSS style class to use when a more specific class does not exist.
2261 * @copyright 2012 Sam Hemelryk
2262 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2264 class css_style_generic
extends css_style
{
2267 * Cleans incoming values for typical things that can be optimised.
2269 * @param mixed $value Cleans the provided value optimising it if possible
2272 protected function clean_value($value) {
2273 if (trim($value) == '0px') {
2275 } else if (preg_match('/^#([a-fA-F0-9]{3,6})/', $value, $matches)) {
2276 $value = '#'.strtoupper($matches[1]);
2283 * A colour CSS style
2287 * @copyright 2012 Sam Hemelryk
2288 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2290 class css_style_color
extends css_style
{
2293 * Creates a new colour style
2295 * @param mixed $value Initialises a new colour style
2296 * @return css_style_color
2298 public static function init($value) {
2299 return new css_style_color('color', $value);
2303 * Cleans the colour unifing it to a 6 char hash colour if possible
2304 * Doing this allows us to associate identical colours being specified in
2305 * different ways. e.g. Red, red, #F00, and #F00000
2307 * @param mixed $value Cleans the provided value optimising it if possible
2310 protected function clean_value($value) {
2311 $value = trim($value);
2312 if (css_is_colour($value)) {
2313 if (preg_match('/#([a-fA-F0-9]{6})/', $value, $matches)) {
2314 $value = '#'.strtoupper($matches[1]);
2315 } else if (preg_match('/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/', $value, $matches)) {
2316 $value = $matches[1] . $matches[1] . $matches[2] . $matches[2] . $matches[3] . $matches[3];
2317 $value = '#'.strtoupper($value);
2318 } else if (array_key_exists(strtolower($value), css_optimiser
::$htmlcolours)) {
2319 $value = css_optimiser
::$htmlcolours[strtolower($value)];
2326 * Returns the colour style for use within CSS.
2327 * Will return an optimised hash colour.
2330 * #123 instead of #112233
2331 * #F00 instead of red
2333 * @param string $overridevalue If provided then this value will be used instead
2334 * of the styles current value.
2337 public function out($overridevalue = null) {
2338 if ($overridevalue === null) {
2339 $overridevalue = $this->value
;
2341 return parent
::out(self
::shrink_value($overridevalue));
2345 * Shrinks the colour value is possible.
2347 * @param string $value Shrinks the current value to an optimial form if possible
2350 public static function shrink_value($value) {
2351 if (preg_match('/#([a-fA-F0-9])\1([a-fA-F0-9])\2([a-fA-F0-9])\3/', $value, $matches)) {
2352 return '#'.$matches[1].$matches[2].$matches[3];
2358 * Returns true if the value is a valid colour.
2362 public function is_valid() {
2363 return css_is_colour($this->value
);
2372 * @copyright 2012 Sam Hemelryk
2373 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2375 class css_style_width
extends css_style
{
2378 * Checks if the width is valid
2381 public function is_valid() {
2382 return css_is_width($this->value
);
2386 * Cleans the provided value
2388 * @param mixed $value Cleans the provided value optimising it if possible
2391 protected function clean_value($value) {
2392 if (!css_is_width($value)) {
2393 // Note we don't actually change the value to something valid. That
2394 // would be bad for futureproofing.
2395 $this->set_error('Invalid width specified for '.$this->name
);
2396 } else if (preg_match('#^0\D+$#', $value)) {
2399 return trim($value);
2403 * Initialises a new width style
2405 * @param mixed $value The value this style has
2406 * @return css_style_width
2408 public static function init($value) {
2409 return new css_style_width('width', $value);
2418 * @copyright 2012 Sam Hemelryk
2419 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2421 class css_style_margin
extends css_style_width
{
2424 * Initialises a margin style.
2426 * In this case we split the margin into several other margin styles so that
2427 * we can properly condense overrides and then reconsolidate them later into
2430 * @param string $value The value the style has
2431 * @return array An array of margin values that can later be consolidated
2433 public static function init($value) {
2435 if (strpos($value, '!important') !== false) {
2436 $important = ' !important';
2437 $value = str_replace('!important', '', $value);
2440 $value = preg_replace('#\s+#', ' ', trim($value));
2441 $bits = explode(' ', $value, 4);
2443 $top = $right = $bottom = $left = null;
2444 if (count($bits) > 0) {
2445 $top = $right = $bottom = $left = array_shift($bits);
2447 if (count($bits) > 0) {
2448 $right = $left = array_shift($bits);
2450 if (count($bits) > 0) {
2451 $bottom = array_shift($bits);
2453 if (count($bits) > 0) {
2454 $left = array_shift($bits);
2457 new css_style_margintop('margin-top', $top.$important),
2458 new css_style_marginright('margin-right', $right.$important),
2459 new css_style_marginbottom('margin-bottom', $bottom.$important),
2460 new css_style_marginleft('margin-left', $left.$important)
2465 * Consolidates individual margin styles into a single margin style
2467 * @param array $styles
2468 * @return array An array of consolidated styles
2470 public static function consolidate(array $styles) {
2471 if (count($styles) != 4) {
2475 $someimportant = false;
2476 $allimportant = null;
2477 $notimportantequal = null;
2479 foreach ($styles as $style) {
2480 if ($style->is_important()) {
2481 $someimportant = true;
2482 if ($allimportant === null) {
2483 $allimportant = true;
2486 if ($allimportant === true) {
2487 $allimportant = false;
2489 if ($firstvalue == null) {
2490 $firstvalue = $style->get_value(false);
2491 $notimportantequal = true;
2492 } else if ($notimportantequal && $firstvalue !== $style->get_value(false)) {
2493 $notimportantequal = false;
2498 if ($someimportant && !$allimportant && !$notimportantequal) {
2502 if ($someimportant && !$allimportant && $notimportantequal) {
2504 new css_style_margin('margin', $firstvalue)
2506 foreach ($styles as $style) {
2507 if ($style->is_important()) {
2517 foreach ($styles as $style) {
2518 switch ($style->get_name()) {
2520 $top = $style->get_value(false);
2522 case 'margin-right' :
2523 $right = $style->get_value(false);
2525 case 'margin-bottom' :
2526 $bottom = $style->get_value(false);
2528 case 'margin-left' :
2529 $left = $style->get_value(false);
2533 if ($top == $bottom && $left == $right) {
2534 if ($top == $left) {
2535 $returnstyle = new css_style_margin('margin', $top);
2537 $returnstyle = new css_style_margin('margin', "{$top} {$left}");
2539 } else if ($left == $right) {
2540 $returnstyle = new css_style_margin('margin', "{$top} {$right} {$bottom}");
2542 $returnstyle = new css_style_margin('margin', "{$top} {$right} {$bottom} {$left}");
2544 if ($allimportant) {
2545 $returnstyle->set_important();
2547 return array($returnstyle);
2553 * A margin top style
2557 * @copyright 2012 Sam Hemelryk
2558 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2560 class css_style_margintop
extends css_style_margin
{
2563 * A simple init, just a single style
2565 * @param string $value The value the style has
2566 * @return css_style_margintop
2568 public static function init($value) {
2569 return new css_style_margintop('margin-top', $value);
2573 * This style can be consolidated into a single margin style
2577 public function consolidate_to() {
2583 * A margin right style
2587 * @copyright 2012 Sam Hemelryk
2588 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2590 class css_style_marginright
extends css_style_margin
{
2593 * A simple init, just a single style
2595 * @param string $value The value the style has
2596 * @return css_style_margintop
2598 public static function init($value) {
2599 return new css_style_marginright('margin-right', $value);
2603 * This style can be consolidated into a single margin style
2607 public function consolidate_to() {
2613 * A margin bottom style
2617 * @copyright 2012 Sam Hemelryk
2618 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2620 class css_style_marginbottom
extends css_style_margin
{
2623 * A simple init, just a single style
2625 * @param string $value The value the style has
2626 * @return css_style_margintop
2628 public static function init($value) {
2629 return new css_style_marginbottom('margin-bottom', $value);
2633 * This style can be consolidated into a single margin style
2637 public function consolidate_to() {
2643 * A margin left style
2647 * @copyright 2012 Sam Hemelryk
2648 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2650 class css_style_marginleft
extends css_style_margin
{
2653 * A simple init, just a single style
2655 * @param string $value The value the style has
2656 * @return css_style_margintop
2658 public static function init($value) {
2659 return new css_style_marginleft('margin-left', $value);
2663 * This style can be consolidated into a single margin style
2667 public function consolidate_to() {
2677 * @copyright 2012 Sam Hemelryk
2678 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2680 class css_style_border
extends css_style
{
2683 * Initalises the border style into an array of individual style compontents
2685 * @param string $value The value the style has
2686 * @return css_style_bordercolor
2688 public static function init($value) {
2689 $value = preg_replace('#\s+#', ' ', $value);
2690 $bits = explode(' ', $value, 3);
2693 if (count($bits) > 0) {
2694 $width = array_shift($bits);
2695 if (!css_style_borderwidth
::is_border_width($width)) {
2698 $return[] = new css_style_borderwidth('border-top-width', $width);
2699 $return[] = new css_style_borderwidth('border-right-width', $width);
2700 $return[] = new css_style_borderwidth('border-bottom-width', $width);
2701 $return[] = new css_style_borderwidth('border-left-width', $width);
2703 if (count($bits) > 0) {
2704 $style = array_shift($bits);
2705 $return[] = new css_style_borderstyle('border-top-style', $style);
2706 $return[] = new css_style_borderstyle('border-right-style', $style);
2707 $return[] = new css_style_borderstyle('border-bottom-style', $style);
2708 $return[] = new css_style_borderstyle('border-left-style', $style);
2710 if (count($bits) > 0) {
2711 $colour = array_shift($bits);
2712 $return[] = new css_style_bordercolor('border-top-color', $colour);
2713 $return[] = new css_style_bordercolor('border-right-color', $colour);
2714 $return[] = new css_style_bordercolor('border-bottom-color', $colour);
2715 $return[] = new css_style_bordercolor('border-left-color', $colour);
2721 * Consolidates all border styles into a single style
2723 * @param array $styles An array of border styles
2724 * @return array An optimised array of border styles
2726 public static function consolidate(array $styles) {
2728 $borderwidths = array('top' => null, 'right' => null, 'bottom' => null, 'left' => null);
2729 $borderstyles = array('top' => null, 'right' => null, 'bottom' => null, 'left' => null);
2730 $bordercolors = array('top' => null, 'right' => null, 'bottom' => null, 'left' => null);
2732 foreach ($styles as $style) {
2733 switch ($style->get_name()) {
2734 case 'border-top-width':
2735 $borderwidths['top'] = $style->get_value();
2737 case 'border-right-width':
2738 $borderwidths['right'] = $style->get_value();
2740 case 'border-bottom-width':
2741 $borderwidths['bottom'] = $style->get_value();
2743 case 'border-left-width':
2744 $borderwidths['left'] = $style->get_value();
2747 case 'border-top-style':
2748 $borderstyles['top'] = $style->get_value();
2750 case 'border-right-style':
2751 $borderstyles['right'] = $style->get_value();
2753 case 'border-bottom-style':
2754 $borderstyles['bottom'] = $style->get_value();
2756 case 'border-left-style':
2757 $borderstyles['left'] = $style->get_value();
2760 case 'border-top-color':
2761 $bordercolors['top'] = css_style_color
::shrink_value($style->get_value());
2763 case 'border-right-color':
2764 $bordercolors['right'] = css_style_color
::shrink_value($style->get_value());
2766 case 'border-bottom-color':
2767 $bordercolors['bottom'] = css_style_color
::shrink_value($style->get_value());
2769 case 'border-left-color':
2770 $bordercolors['left'] = css_style_color
::shrink_value($style->get_value());
2775 $uniquewidths = count(array_unique($borderwidths));
2776 $uniquestyles = count(array_unique($borderstyles));
2777 $uniquecolors = count(array_unique($bordercolors));
2779 $nullwidths = in_array(null, $borderwidths, true);
2780 $nullstyles = in_array(null, $borderstyles, true);
2781 $nullcolors = in_array(null, $bordercolors, true);
2783 $allwidthsthesame = ($uniquewidths === 1)?
1:0;
2784 $allstylesthesame = ($uniquestyles === 1)?
1:0;
2785 $allcolorsthesame = ($uniquecolors === 1)?
1:0;
2787 $allwidthsnull = $allwidthsthesame && $nullwidths;
2788 $allstylesnull = $allstylesthesame && $nullstyles;
2789 $allcolorsnull = $allcolorsthesame && $nullcolors;
2792 if ($allwidthsnull && $allstylesnull && $allcolorsnull) {
2793 // Everything is null still... boo
2794 return array(new css_style_border('border', ''));
2796 } else if ($allwidthsnull && $allstylesnull) {
2798 self
::consolidate_styles_by_direction($return, 'css_style_bordercolor', 'border-color', $bordercolors);
2801 } else if ($allwidthsnull && $allcolorsnull) {
2803 self
::consolidate_styles_by_direction($return, 'css_style_borderstyle', 'border-style', $borderstyles);
2806 } else if ($allcolorsnull && $allstylesnull) {
2808 self
::consolidate_styles_by_direction($return, 'css_style_borderwidth', 'border-width', $borderwidths);
2813 if ($allwidthsthesame +
$allstylesthesame +
$allcolorsthesame == 3) {
2815 $return[] = new css_style_border('border', $borderwidths['top'].' '.$borderstyles['top'].' '.$bordercolors['top']);
2817 } else if ($allwidthsthesame +
$allstylesthesame +
$allcolorsthesame == 2) {
2819 if ($allwidthsthesame && $allstylesthesame && !$nullwidths && !$nullstyles) {
2821 $return[] = new css_style_border('border', $borderwidths['top'].' '.$borderstyles['top']);
2822 self
::consolidate_styles_by_direction($return, 'css_style_bordercolor', 'border-color', $bordercolors);
2824 } else if ($allwidthsthesame && $allcolorsthesame && !$nullwidths && !$nullcolors) {
2826 $return[] = new css_style_border('border', $borderwidths['top'].' solid '.$bordercolors['top']);
2827 self
::consolidate_styles_by_direction($return, 'css_style_borderstyle', 'border-style', $borderstyles);
2829 } else if ($allstylesthesame && $allcolorsthesame && !$nullstyles && !$nullcolors) {
2831 $return[] = new css_style_border('border', '1px '.$borderstyles['top'].' '.$bordercolors['top']);
2832 self
::consolidate_styles_by_direction($return, 'css_style_borderwidth', 'border-width', $borderwidths);
2835 self
::consolidate_styles_by_direction($return, 'css_style_borderwidth', 'border-width', $borderwidths);
2836 self
::consolidate_styles_by_direction($return, 'css_style_borderstyle', 'border-style', $borderstyles);
2837 self
::consolidate_styles_by_direction($return, 'css_style_bordercolor', 'border-color', $bordercolors);
2840 } else if (!$nullwidths && !$nullcolors && !$nullstyles && max(array_count_values($borderwidths)) == 3 && max(array_count_values($borderstyles)) == 3 && max(array_count_values($bordercolors)) == 3) {
2841 $widthkeys = array();
2842 $stylekeys = array();
2843 $colorkeys = array();
2845 foreach ($borderwidths as $key => $value) {
2846 if (!array_key_exists($value, $widthkeys)) {
2847 $widthkeys[$value] = array();
2849 $widthkeys[$value][] = $key;
2851 usort($widthkeys, 'css_sort_by_count');
2852 $widthkeys = array_values($widthkeys);
2854 foreach ($borderstyles as $key => $value) {
2855 if (!array_key_exists($value, $stylekeys)) {
2856 $stylekeys[$value] = array();
2858 $stylekeys[$value][] = $key;
2860 usort($stylekeys, 'css_sort_by_count');
2861 $stylekeys = array_values($stylekeys);
2863 foreach ($bordercolors as $key => $value) {
2864 if (!array_key_exists($value, $colorkeys)) {
2865 $colorkeys[$value] = array();
2867 $colorkeys[$value][] = $key;
2869 usort($colorkeys, 'css_sort_by_count');
2870 $colorkeys = array_values($colorkeys);
2872 if ($widthkeys == $stylekeys && $stylekeys == $colorkeys) {
2873 $key = $widthkeys[0][0];
2874 self
::build_style_string($return, 'css_style_border', 'border', $borderwidths[$key], $borderstyles[$key], $bordercolors[$key]);
2875 $key = $widthkeys[1][0];
2876 self
::build_style_string($return, 'css_style_border'.$key, 'border-'.$key, $borderwidths[$key], $borderstyles[$key], $bordercolors[$key]);
2878 self
::build_style_string($return, 'css_style_bordertop', 'border-top', $borderwidths['top'], $borderstyles['top'], $bordercolors['top']);
2879 self
::build_style_string($return, 'css_style_borderright', 'border-right', $borderwidths['right'], $borderstyles['right'], $bordercolors['right']);
2880 self
::build_style_string($return, 'css_style_borderbottom', 'border-bottom', $borderwidths['bottom'], $borderstyles['bottom'], $bordercolors['bottom']);
2881 self
::build_style_string($return, 'css_style_borderleft', 'border-left', $borderwidths['left'], $borderstyles['left'], $bordercolors['left']);
2884 self
::build_style_string($return, 'css_style_bordertop', 'border-top', $borderwidths['top'], $borderstyles['top'], $bordercolors['top']);
2885 self
::build_style_string($return, 'css_style_borderright', 'border-right', $borderwidths['right'], $borderstyles['right'], $bordercolors['right']);
2886 self
::build_style_string($return, 'css_style_borderbottom', 'border-bottom', $borderwidths['bottom'], $borderstyles['bottom'], $bordercolors['bottom']);
2887 self
::build_style_string($return, 'css_style_borderleft', 'border-left', $borderwidths['left'], $borderstyles['left'], $bordercolors['left']);
2889 foreach ($return as $key => $style) {
2890 if ($style->get_value() == '') {
2891 unset($return[$key]);
2898 * Border styles get consolidated to a single border style.
2902 public function consolidate_to() {
2907 * Consolidates a series of border styles into an optimised array of border
2908 * styles by looking at the direction of the border and prioritising that
2909 * during the optimisation.
2911 * @param array $array An array to add styles into during consolidation. Passed by reference.
2912 * @param string $class The class type to initalise
2913 * @param string $style The style to create
2914 * @param string|array $top The top value
2915 * @param string $right The right value
2916 * @param string $bottom The bottom value
2917 * @param string $left The left value
2920 public static function consolidate_styles_by_direction(&$array, $class, $style, $top, $right = null, $bottom = null, $left = null) {
2921 if (is_array($top)) {
2922 $right = $top['right'];
2923 $bottom = $top['bottom'];
2924 $left = $top['left'];
2928 if ($top == $bottom && $left == $right && $top == $left) {
2929 if (is_null($top)) {
2930 $array[] = new $class($style, '');
2932 $array[] = new $class($style, $top);
2934 } else if ($top == null ||
$right == null ||
$bottom == null ||
$left == null) {
2935 if ($top !== null) {
2936 $array[] = new $class(str_replace('border-', 'border-top-', $style), $top);
2938 if ($right !== null) {
2939 $array[] = new $class(str_replace('border-', 'border-right-', $style), $right);
2941 if ($bottom !== null) {
2942 $array[] = new $class(str_replace('border-', 'border-bottom-', $style), $bottom);
2944 if ($left !== null) {
2945 $array[] = new $class(str_replace('border-', 'border-left-', $style), $left);
2947 } else if ($top == $bottom && $left == $right) {
2948 $array[] = new $class($style, $top.' '.$right);
2949 } else if ($left == $right) {
2950 $array[] = new $class($style, $top.' '.$right.' '.$bottom);
2952 $array[] = new $class($style, $top.' '.$right.' '.$bottom.' '.$left);
2958 * Builds a border style for a set of width, style, and colour values
2960 * @param array $array An array into which the generated style is added
2961 * @param string $class The class type to initialise
2962 * @param string $cssstyle The style to use
2963 * @param string $width The width of the border
2964 * @param string $style The style of the border
2965 * @param string $color The colour of the border
2968 public static function build_style_string(&$array, $class, $cssstyle, $width = null, $style = null, $color = null) {
2969 if (!is_null($width) && !is_null($style) && !is_null($color)) {
2970 $array[] = new $class($cssstyle, $width.' '.$style.' '.$color);
2971 } else if (!is_null($width) && !is_null($style) && is_null($color)) {
2972 $array[] = new $class($cssstyle, $width.' '.$style);
2973 } else if (!is_null($width) && is_null($style) && is_null($color)) {
2974 $array[] = new $class($cssstyle, $width);
2976 if (!is_null($width)) {
2977 $array[] = new $class($cssstyle, $width);
2979 if (!is_null($style)) {
2980 $array[] = new $class($cssstyle, $style);
2982 if (!is_null($color)) {
2983 $array[] = new $class($cssstyle, $color);
2991 * A border colour style
2995 * @copyright 2012 Sam Hemelryk
2996 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2998 class css_style_bordercolor
extends css_style_color
{
3001 * Creates a new border colour style
3003 * Based upon the colour style
3005 * @param mixed $value
3006 * @return Array of css_style_bordercolor
3008 public static function init($value) {
3009 $value = preg_replace('#\s+#', ' ', $value);
3010 $bits = explode(' ', $value, 4);
3012 $top = $right = $bottom = $left = null;
3013 if (count($bits) > 0) {
3014 $top = $right = $bottom = $left = array_shift($bits);
3016 if (count($bits) > 0) {
3017 $right = $left = array_shift($bits);
3019 if (count($bits) > 0) {
3020 $bottom = array_shift($bits);
3022 if (count($bits) > 0) {
3023 $left = array_shift($bits);
3026 css_style_bordertopcolor
::init($top),
3027 css_style_borderrightcolor
::init($right),
3028 css_style_borderbottomcolor
::init($bottom),
3029 css_style_borderleftcolor
::init($left)
3034 * Consolidate this to a single border style
3038 public function consolidate_to() {
3045 * @param string $value Cleans the provided value optimising it if possible
3048 protected function clean_value($value) {
3049 $values = explode(' ', $value);
3050 $values = array_map('parent::clean_value', $values);
3051 return join (' ', $values);
3055 * Outputs this style
3057 * @param string $overridevalue
3060 public function out($overridevalue = null) {
3061 if ($overridevalue === null) {
3062 $overridevalue = $this->value
;
3064 $values = explode(' ', $overridevalue);
3065 $values = array_map('css_style_color::shrink_value', $values);
3066 return parent
::out(join (' ', $values));
3071 * A border left style
3075 * @copyright 2012 Sam Hemelryk
3076 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3078 class css_style_borderleft
extends css_style_generic
{
3081 * Initialises the border left style into individual components
3083 * @param string $value
3084 * @return array Array of css_style_borderleftwidth|css_style_borderleftstyle|css_style_borderleftcolor
3086 public static function init($value) {
3087 $value = preg_replace('#\s+#', ' ', $value);
3088 $bits = explode(' ', $value, 3);
3091 if (count($bits) > 0) {
3092 $return[] = css_style_borderleftwidth
::init(array_shift($bits));
3094 if (count($bits) > 0) {
3095 $return[] = css_style_borderleftstyle
::init(array_shift($bits));
3097 if (count($bits) > 0) {
3098 $return[] = css_style_borderleftcolor
::init(array_shift($bits));
3104 * Consolidate this to a single border style
3108 public function consolidate_to() {
3114 * A border right style
3118 * @copyright 2012 Sam Hemelryk
3119 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3121 class css_style_borderright
extends css_style_generic
{
3124 * Initialises the border right style into individual components
3126 * @param string $value The value of the style
3127 * @return array Array of css_style_borderrightwidth|css_style_borderrightstyle|css_style_borderrightcolor
3129 public static function init($value) {
3130 $value = preg_replace('#\s+#', ' ', $value);
3131 $bits = explode(' ', $value, 3);
3134 if (count($bits) > 0) {
3135 $return[] = css_style_borderrightwidth
::init(array_shift($bits));
3137 if (count($bits) > 0) {
3138 $return[] = css_style_borderrightstyle
::init(array_shift($bits));
3140 if (count($bits) > 0) {
3141 $return[] = css_style_borderrightcolor
::init(array_shift($bits));
3147 * Consolidate this to a single border style
3151 public function consolidate_to() {
3157 * A border top style
3161 * @copyright 2012 Sam Hemelryk
3162 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3164 class css_style_bordertop
extends css_style_generic
{
3167 * Initialises the border top style into individual components
3169 * @param string $value The value of the style
3170 * @return array Array of css_style_bordertopwidth|css_style_bordertopstyle|css_style_bordertopcolor
3172 public static function init($value) {
3173 $value = preg_replace('#\s+#', ' ', $value);
3174 $bits = explode(' ', $value, 3);
3177 if (count($bits) > 0) {
3178 $return[] = css_style_bordertopwidth
::init(array_shift($bits));
3180 if (count($bits) > 0) {
3181 $return[] = css_style_bordertopstyle
::init(array_shift($bits));
3183 if (count($bits) > 0) {
3184 $return[] = css_style_bordertopcolor
::init(array_shift($bits));
3190 * Consolidate this to a single border style
3194 public function consolidate_to() {
3200 * A border bottom style
3204 * @copyright 2012 Sam Hemelryk
3205 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3207 class css_style_borderbottom
extends css_style_generic
{
3210 * Initialises the border bottom style into individual components
3212 * @param string $value The value of the style
3213 * @return array Array of css_style_borderbottomwidth|css_style_borderbottomstyle|css_style_borderbottomcolor
3215 public static function init($value) {
3216 $value = preg_replace('#\s+#', ' ', $value);
3217 $bits = explode(' ', $value, 3);
3220 if (count($bits) > 0) {
3221 $return[] = css_style_borderbottomwidth
::init(array_shift($bits));
3223 if (count($bits) > 0) {
3224 $return[] = css_style_borderbottomstyle
::init(array_shift($bits));
3226 if (count($bits) > 0) {
3227 $return[] = css_style_borderbottomcolor
::init(array_shift($bits));
3233 * Consolidate this to a single border style
3237 public function consolidate_to() {
3243 * A border width style
3247 * @copyright 2012 Sam Hemelryk
3248 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3250 class css_style_borderwidth
extends css_style_width
{
3253 * Creates a new border colour style
3255 * Based upon the colour style
3257 * @param string $value The value of the style
3258 * @return array Array of css_style_border*width
3260 public static function init($value) {
3261 $value = preg_replace('#\s+#', ' ', $value);
3262 $bits = explode(' ', $value, 4);
3264 $top = $right = $bottom = $left = null;
3265 if (count($bits) > 0) {
3266 $top = $right = $bottom = $left = array_shift($bits);
3268 if (count($bits) > 0) {
3269 $right = $left = array_shift($bits);
3271 if (count($bits) > 0) {
3272 $bottom = array_shift($bits);
3274 if (count($bits) > 0) {
3275 $left = array_shift($bits);
3278 css_style_bordertopwidth
::init($top),
3279 css_style_borderrightwidth
::init($right),
3280 css_style_borderbottomwidth
::init($bottom),
3281 css_style_borderleftwidth
::init($left)
3286 * Consolidate this to a single border style
3290 public function consolidate_to() {
3295 * Checks if the width is valid
3298 public function is_valid() {
3299 return self
::is_border_width($this->value
);
3303 * Cleans the provided value
3305 * @param mixed $value Cleans the provided value optimising it if possible
3308 protected function clean_value($value) {
3309 $isvalid = self
::is_border_width($value);
3311 $this->set_error('Invalid width specified for '.$this->name
);
3312 } else if (preg_match('#^0\D+$#', $value)) {
3315 return trim($value);
3319 * Returns true if the provided value is a permitted border width
3320 * @param string $value The value to check
3323 public static function is_border_width($value) {
3324 $altwidthvalues = array('thin', 'medium', 'thick');
3325 return css_is_width($value) ||
in_array($value, $altwidthvalues);
3330 * A border style style
3334 * @copyright 2012 Sam Hemelryk
3335 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3337 class css_style_borderstyle
extends css_style_generic
{
3340 * Creates a new border colour style
3342 * Based upon the colour style
3344 * @param string $value The value of the style
3345 * @return array Array of css_style_border*style
3347 public static function init($value) {
3348 $value = preg_replace('#\s+#', ' ', $value);
3349 $bits = explode(' ', $value, 4);
3351 $top = $right = $bottom = $left = null;
3352 if (count($bits) > 0) {
3353 $top = $right = $bottom = $left = array_shift($bits);
3355 if (count($bits) > 0) {
3356 $right = $left = array_shift($bits);
3358 if (count($bits) > 0) {
3359 $bottom = array_shift($bits);
3361 if (count($bits) > 0) {
3362 $left = array_shift($bits);
3365 css_style_bordertopstyle
::init($top),
3366 css_style_borderrightstyle
::init($right),
3367 css_style_borderbottomstyle
::init($bottom),
3368 css_style_borderleftstyle
::init($left)
3373 * Consolidate this to a single border style
3377 public function consolidate_to() {
3383 * A border top colour style
3387 * @copyright 2012 Sam Hemelryk
3388 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3390 class css_style_bordertopcolor
extends css_style_bordercolor
{
3393 * Initialises this style object
3395 * @param string $value The value of the style
3396 * @return css_style_bordertopcolor
3398 public static function init($value) {
3399 return new css_style_bordertopcolor('border-top-color', $value);
3403 * Consolidate this to a single border style
3407 public function consolidate_to() {
3413 * A border left colour style
3417 * @copyright 2012 Sam Hemelryk
3418 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3420 class css_style_borderleftcolor
extends css_style_bordercolor
{
3423 * Initialises this style object
3425 * @param string $value The value of the style
3426 * @return css_style_borderleftcolor
3428 public static function init($value) {
3429 return new css_style_borderleftcolor('border-left-color', $value);
3433 * Consolidate this to a single border style
3437 public function consolidate_to() {
3443 * A border right colour style
3447 * @copyright 2012 Sam Hemelryk
3448 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3450 class css_style_borderrightcolor
extends css_style_bordercolor
{
3453 * Initialises this style object
3455 * @param string $value The value of the style
3456 * @return css_style_borderrightcolor
3458 public static function init($value) {
3459 return new css_style_borderrightcolor('border-right-color', $value);
3463 * Consolidate this to a single border style
3467 public function consolidate_to() {
3473 * A border bottom colour style
3477 * @copyright 2012 Sam Hemelryk
3478 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3480 class css_style_borderbottomcolor
extends css_style_bordercolor
{
3483 * Initialises this style object
3485 * @param string $value The value of the style
3486 * @return css_style_borderbottomcolor
3488 public static function init($value) {
3489 return new css_style_borderbottomcolor('border-bottom-color', $value);
3493 * Consolidate this to a single border style
3497 public function consolidate_to() {
3503 * A border width top style
3507 * @copyright 2012 Sam Hemelryk
3508 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3510 class css_style_bordertopwidth
extends css_style_borderwidth
{
3513 * Initialises this style object
3515 * @param string $value The value of the style
3516 * @return css_style_bordertopwidth
3518 public static function init($value) {
3519 return new css_style_bordertopwidth('border-top-width', $value);
3523 * Consolidate this to a single border style
3527 public function consolidate_to() {
3533 * A border width left style
3537 * @copyright 2012 Sam Hemelryk
3538 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3540 class css_style_borderleftwidth
extends css_style_borderwidth
{
3543 * Initialises this style object
3545 * @param string $value The value of the style
3546 * @return css_style_borderleftwidth
3548 public static function init($value) {
3549 return new css_style_borderleftwidth('border-left-width', $value);
3553 * Consolidate this to a single border style
3557 public function consolidate_to() {
3563 * A border width right style
3567 * @copyright 2012 Sam Hemelryk
3568 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3570 class css_style_borderrightwidth
extends css_style_borderwidth
{
3573 * Initialises this style object
3575 * @param string $value The value of the style
3576 * @return css_style_borderrightwidth
3578 public static function init($value) {
3579 return new css_style_borderrightwidth('border-right-width', $value);
3583 * Consolidate this to a single border style
3587 public function consolidate_to() {
3593 * A border width bottom style
3597 * @copyright 2012 Sam Hemelryk
3598 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3600 class css_style_borderbottomwidth
extends css_style_borderwidth
{
3603 * Initialises this style object
3605 * @param string $value The value of the style
3606 * @return css_style_borderbottomwidth
3608 public static function init($value) {
3609 return new css_style_borderbottomwidth('border-bottom-width', $value);
3613 * Consolidate this to a single border style
3617 public function consolidate_to() {
3623 * A border top style
3627 * @copyright 2012 Sam Hemelryk
3628 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3630 class css_style_bordertopstyle
extends css_style_borderstyle
{
3633 * Initialises this style object
3635 * @param string $value The value of the style
3636 * @return css_style_bordertopstyle
3638 public static function init($value) {
3639 return new css_style_bordertopstyle('border-top-style', $value);
3643 * Consolidate this to a single border style
3647 public function consolidate_to() {
3653 * A border left style
3657 * @copyright 2012 Sam Hemelryk
3658 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3660 class css_style_borderleftstyle
extends css_style_borderstyle
{
3663 * Initialises this style object
3665 * @param string $value The value of the style
3666 * @return css_style_borderleftstyle
3668 public static function init($value) {
3669 return new css_style_borderleftstyle('border-left-style', $value);
3673 * Consolidate this to a single border style
3677 public function consolidate_to() {
3683 * A border right style
3687 * @copyright 2012 Sam Hemelryk
3688 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3690 class css_style_borderrightstyle
extends css_style_borderstyle
{
3693 * Initialises this style object
3695 * @param string $value The value of the style
3696 * @return css_style_borderrightstyle
3698 public static function init($value) {
3699 return new css_style_borderrightstyle('border-right-style', $value);
3703 * Consolidate this to a single border style
3707 public function consolidate_to() {
3713 * A border bottom style
3717 * @copyright 2012 Sam Hemelryk
3718 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3720 class css_style_borderbottomstyle
extends css_style_borderstyle
{
3723 * Initialises this style object
3725 * @param string $value The value for the style
3726 * @return css_style_borderbottomstyle
3728 public static function init($value) {
3729 return new css_style_borderbottomstyle('border-bottom-style', $value);
3733 * Consolidate this to a single border style
3737 public function consolidate_to() {
3743 * A background style
3747 * @copyright 2012 Sam Hemelryk
3748 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3750 class css_style_background
extends css_style
{
3753 * Initialises a background style
3755 * @param string $value The value of the style
3756 * @return array An array of background component.
3758 public static function init($value) {
3759 // colour - image - repeat - attachment - position
3762 if (preg_match('#url\(([^\)]+)\)#', $value, $matches)) {
3763 $imageurl = trim($matches[1]);
3764 $value = str_replace($matches[1], '', $value);
3767 // Switch out the brackets so that they don't get messed up when we explode
3768 $brackets = array();
3770 while (preg_match('#\([^\)\(]+\)#', $value, $matches)) {
3771 $key = "##BRACKET-{$bracketcount}##";
3773 $brackets[$key] = $matches[0];
3774 $value = str_replace($matches[0], $key, $value);
3777 $important = (stripos($value, '!important') !== false);
3779 // Great some genius put !important in the background shorthand property
3780 $value = str_replace('!important', '', $value);
3783 $value = preg_replace('#\s+#', ' ', $value);
3784 $bits = explode(' ', $value);
3786 foreach ($bits as $key => $bit) {
3787 $bits[$key] = self
::replace_bracket_placeholders($bit, $brackets);
3789 unset($bracketcount);
3792 $repeats = array('repeat', 'repeat-x', 'repeat-y', 'no-repeat', 'inherit');
3793 $attachments = array('scroll' , 'fixed', 'inherit');
3794 $positions = array('top', 'left', 'bottom', 'right', 'center');
3797 $unknownbits = array();
3799 $color = self
::NULL_VALUE
;
3800 if (count($bits) > 0 && css_is_colour(reset($bits))) {
3801 $color = array_shift($bits);
3804 $image = self
::NULL_VALUE
;
3805 if (count($bits) > 0 && preg_match('#^\s*(none|inherit|url\(\))\s*$#', reset($bits))) {
3806 $image = array_shift($bits);
3807 if ($image == 'url()') {
3808 $image = "url({$imageurl})";
3812 $repeat = self
::NULL_VALUE
;
3813 if (count($bits) > 0 && in_array(reset($bits), $repeats)) {
3814 $repeat = array_shift($bits);
3817 $attachment = self
::NULL_VALUE
;
3818 if (count($bits) > 0 && in_array(reset($bits), $attachments)) {
3819 // scroll , fixed, inherit
3820 $attachment = array_shift($bits);
3823 $position = self
::NULL_VALUE
;
3824 if (count($bits) > 0) {
3825 $widthbits = array();
3826 foreach ($bits as $bit) {
3827 if (in_array($bit, $positions) ||
css_is_width($bit)) {
3828 $widthbits[] = $bit;
3830 $unknownbits[] = $bit;
3833 if (count($widthbits)) {
3834 $position = join(' ', $widthbits);
3838 if (count($unknownbits)) {
3839 foreach ($unknownbits as $bit) {
3841 if ($color === self
::NULL_VALUE
&& css_is_colour($bit)) {
3843 } else if ($repeat === self
::NULL_VALUE
&& in_array($bit, $repeats)) {
3845 } else if ($attachment === self
::NULL_VALUE
&& in_array($bit, $attachments)) {
3847 } else if ($bit !== '') {
3848 $advanced = css_style_background_advanced
::init($bit);
3850 $advanced->set_important();
3852 $return[] = $advanced;
3857 if ($color === self
::NULL_VALUE
&& $image === self
::NULL_VALUE
&& $repeat === self
::NULL_VALUE
&& $attachment === self
::NULL_VALUE
&& $position === self
::NULL_VALUE
) {
3858 // All primaries are null, return without doing anything else. There may be advanced madness there.
3862 $return[] = new css_style_backgroundcolor('background-color', $color);
3863 $return[] = new css_style_backgroundimage('background-image', $image);
3864 $return[] = new css_style_backgroundrepeat('background-repeat', $repeat);
3865 $return[] = new css_style_backgroundattachment('background-attachment', $attachment);
3866 $return[] = new css_style_backgroundposition('background-position', $position);
3869 foreach ($return as $style) {
3870 $style->set_important();
3878 * Static helper method to switch in bracket replacements
3880 * @param string $value
3881 * @param array $placeholders
3884 protected static function replace_bracket_placeholders($value, array $placeholders) {
3885 while (preg_match('/##BRACKET-\d+##/', $value, $matches)) {
3886 $value = str_replace($matches[0], $placeholders[$matches[0]], $value);
3892 * Consolidates background styles into a single background style
3894 * @param array $styles Consolidates the provided array of background styles
3895 * @return array Consolidated optimised background styles
3897 public static function consolidate(array $styles) {
3899 if (empty($styles)) {
3912 $someimportant = false;
3913 $allimportant = null;
3914 foreach ($styles as $style) {
3915 if ($style instanceof css_style_backgroundimage_advanced
) {
3918 if ($style->is_important()) {
3919 $someimportant = true;
3920 if ($allimportant === null) {
3921 $allimportant = true;
3923 } else if ($allimportant === true) {
3924 $allimportant = false;
3928 $organisedstyles = array();
3929 $advancedstyles = array();
3930 $importantstyles = array();
3931 foreach ($styles as $style) {
3932 if ($style instanceof css_style_backgroundimage_advanced
) {
3933 $advancedstyles[] = $style;
3936 if ($someimportant && !$allimportant && $style->is_important()) {
3937 $importantstyles[] = $style;
3940 $organisedstyles[$style->get_name()] = $style;
3941 switch ($style->get_name()) {
3942 case 'background-color' :
3943 $color = css_style_color
::shrink_value($style->get_value(false));
3945 case 'background-image' :
3946 $image = $style->get_value(false);
3948 case 'background-repeat' :
3949 $repeat = $style->get_value(false);
3951 case 'background-attachment' :
3952 $attachment = $style->get_value(false);
3954 case 'background-position' :
3955 $position = $style->get_value(false);
3957 case 'background-clip' :
3958 $clip = $style->get_value();
3960 case 'background-origin' :
3961 $origin = $style->get_value();
3963 case 'background-size' :
3964 $size = $style->get_value();
3969 $consolidatetosingle = array();
3970 if (!is_null($color) && !is_null($image) && !is_null($repeat) && !is_null($attachment) && !is_null($position)) {
3971 // We can use the shorthand background-style!
3972 if (!$organisedstyles['background-color']->is_special_empty_value()) {
3973 $consolidatetosingle[] = $color;
3975 if (!$organisedstyles['background-image']->is_special_empty_value()) {
3976 $consolidatetosingle[] = $image;
3978 if (!$organisedstyles['background-repeat']->is_special_empty_value()) {
3979 $consolidatetosingle[] = $repeat;
3981 if (!$organisedstyles['background-attachment']->is_special_empty_value()) {
3982 $consolidatetosingle[] = $attachment;
3984 if (!$organisedstyles['background-position']->is_special_empty_value()) {
3985 $consolidatetosingle[] = $position;
3987 // Reset them all to null so we don't use them again.
3996 // Single background style needs to come first;
3997 if (count($consolidatetosingle) > 0) {
3998 $returnstyle = new css_style_background('background', join(' ', $consolidatetosingle));
3999 if ($allimportant) {
4000 $returnstyle->set_important();
4002 $return[] = $returnstyle;
4004 foreach ($styles as $style) {
4006 switch ($style->get_name()) {
4007 case 'background-color' : $value = $color; break;
4008 case 'background-image' : $value = $image; break;
4009 case 'background-repeat' : $value = $repeat; break;
4010 case 'background-attachment' : $value = $attachment; break;
4011 case 'background-position' : $value = $position; break;
4012 case 'background-clip' : $value = $clip; break;
4013 case 'background-origin' : $value = $origin; break;
4014 case 'background-size' : $value = $size; break;
4016 if (!is_null($value)) {
4020 $return = array_merge($return, $importantstyles, $advancedstyles);
4026 * A advanced background style that allows multiple values to preserve unknown entities
4030 * @copyright 2012 Sam Hemelryk
4031 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4033 class css_style_background_advanced
extends css_style_generic
{
4035 * Creates a new background colour style
4037 * @param string $value The value of the style
4038 * @return css_style_backgroundimage
4040 public static function init($value) {
4041 $value = preg_replace('#\s+#', ' ', $value);
4042 return new css_style_background_advanced('background', $value);
4046 * Returns true because the advanced background image supports multiple values.
4047 * e.g. -webkit-linear-gradient and -moz-linear-gradient.
4051 public function allows_multiple_values() {
4057 * A background colour style.
4059 * Based upon the colour style.
4063 * @copyright 2012 Sam Hemelryk
4064 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4066 class css_style_backgroundcolor
extends css_style_color
{
4069 * Creates a new background colour style
4071 * @param string $value The value of the style
4072 * @return css_style_backgroundcolor
4074 public static function init($value) {
4075 return new css_style_backgroundcolor('background-color', $value);
4079 * css_style_backgroundcolor consolidates to css_style_background
4083 public function consolidate_to() {
4084 return 'background';
4088 * Returns true if the value for this style is the special null value.
4090 * This occurs if the shorthand background property was used but no proper value
4091 * was specified for this style.
4092 * This leads to a null value being used unless otherwise overridden.
4096 public function is_special_empty_value() {
4097 return ($this->value
=== self
::NULL_VALUE
);
4101 * Returns true if the value for this style is valid
4104 public function is_valid() {
4105 return $this->is_special_empty_value() || parent
::is_valid();
4110 * A background image style.
4114 * @copyright 2012 Sam Hemelryk
4115 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4117 class css_style_backgroundimage
extends css_style_generic
{
4120 * Creates a new background image style
4122 * @param string $value The value of the style
4123 * @return css_style_backgroundimage
4125 public static function init($value) {
4126 if (!preg_match('#^\s*(none|inherit|url\()#i', $value)) {
4127 return css_style_backgroundimage_advanced
::init($value);
4129 return new css_style_backgroundimage('background-image', $value);
4133 * Consolidates this style into a single background style
4137 public function consolidate_to() {
4138 return 'background';
4142 * Returns true if the value for this style is the special null value.
4144 * This occurs if the shorthand background property was used but no proper value
4145 * was specified for this style.
4146 * This leads to a null value being used unless otherwise overridden.
4150 public function is_special_empty_value() {
4151 return ($this->value
=== self
::NULL_VALUE
);
4155 * Returns true if the value for this style is valid
4158 public function is_valid() {
4159 return $this->is_special_empty_value() || parent
::is_valid();
4164 * A background image style that supports mulitple values and masquerades as a background-image
4168 * @copyright 2012 Sam Hemelryk
4169 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4171 class css_style_backgroundimage_advanced
extends css_style_generic
{
4173 * Creates a new background colour style
4175 * @param string $value The value of the style
4176 * @return css_style_backgroundimage
4178 public static function init($value) {
4179 $value = preg_replace('#\s+#', ' ', $value);
4180 return new css_style_backgroundimage_advanced('background-image', $value);
4184 * Returns true because the advanced background image supports multiple values.
4185 * e.g. -webkit-linear-gradient and -moz-linear-gradient.
4189 public function allows_multiple_values() {
4195 * A background repeat style.
4199 * @copyright 2012 Sam Hemelryk
4200 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4202 class css_style_backgroundrepeat
extends css_style_generic
{
4205 * Creates a new background colour style
4207 * @param string $value The value of the style
4208 * @return css_style_backgroundrepeat
4210 public static function init($value) {
4211 return new css_style_backgroundrepeat('background-repeat', $value);
4215 * Consolidates this style into a single background style
4219 public function consolidate_to() {
4220 return 'background';
4224 * Returns true if the value for this style is the special null value.
4226 * This occurs if the shorthand background property was used but no proper value
4227 * was specified for this style.
4228 * This leads to a null value being used unless otherwise overridden.
4232 public function is_special_empty_value() {
4233 return ($this->value
=== self
::NULL_VALUE
);
4237 * Returns true if the value for this style is valid
4240 public function is_valid() {
4241 return $this->is_special_empty_value() || parent
::is_valid();
4246 * A background attachment style.
4250 * @copyright 2012 Sam Hemelryk
4251 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4253 class css_style_backgroundattachment
extends css_style_generic
{
4256 * Creates a new background colour style
4258 * @param string $value The value of the style
4259 * @return css_style_backgroundattachment
4261 public static function init($value) {
4262 return new css_style_backgroundattachment('background-attachment', $value);
4266 * Consolidates this style into a single background style
4270 public function consolidate_to() {
4271 return 'background';
4275 * Returns true if the value for this style is the special null value.
4277 * This occurs if the shorthand background property was used but no proper value
4278 * was specified for this style.
4279 * This leads to a null value being used unless otherwise overridden.
4283 public function is_special_empty_value() {
4284 return ($this->value
=== self
::NULL_VALUE
);
4288 * Returns true if the value for this style is valid
4291 public function is_valid() {
4292 return $this->is_special_empty_value() || parent
::is_valid();
4297 * A background position style.
4301 * @copyright 2012 Sam Hemelryk
4302 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4304 class css_style_backgroundposition
extends css_style_generic
{
4307 * Creates a new background colour style
4309 * @param string $value The value of the style
4310 * @return css_style_backgroundposition
4312 public static function init($value) {
4313 return new css_style_backgroundposition('background-position', $value);
4317 * Consolidates this style into a single background style
4321 public function consolidate_to() {
4322 return 'background';
4326 * Returns true if the value for this style is the special null value.
4328 * This occurs if the shorthand background property was used but no proper value
4329 * was specified for this style.
4330 * This leads to a null value being used unless otherwise overridden.
4334 public function is_special_empty_value() {
4335 return ($this->value
=== self
::NULL_VALUE
);
4339 * Returns true if the value for this style is valid
4342 public function is_valid() {
4343 return $this->is_special_empty_value() || parent
::is_valid();
4348 * A background size style.
4352 * @copyright 2012 Sam Hemelryk
4353 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4355 class css_style_backgroundsize
extends css_style_generic
{
4358 * Creates a new background size style
4360 * @param string $value The value of the style
4361 * @return css_style_backgroundposition
4363 public static function init($value) {
4364 return new css_style_backgroundsize('background-size', $value);
4368 * Consolidates this style into a single background style
4372 public function consolidate_to() {
4373 return 'background';
4378 * A background clip style.
4382 * @copyright 2012 Sam Hemelryk
4383 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4385 class css_style_backgroundclip
extends css_style_generic
{
4388 * Creates a new background clip style
4390 * @param string $value The value of the style
4391 * @return css_style_backgroundposition
4393 public static function init($value) {
4394 return new css_style_backgroundclip('background-clip', $value);
4398 * Consolidates this style into a single background style
4402 public function consolidate_to() {
4403 return 'background';
4408 * A background origin style.
4412 * @copyright 2012 Sam Hemelryk
4413 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4415 class css_style_backgroundorigin
extends css_style_generic
{
4418 * Creates a new background origin style
4420 * @param string $value The value of the style
4421 * @return css_style_backgroundposition
4423 public static function init($value) {
4424 return new css_style_backgroundorigin('background-origin', $value);
4428 * Consolidates this style into a single background style
4432 public function consolidate_to() {
4433 return 'background';
4442 * @copyright 2012 Sam Hemelryk
4443 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4445 class css_style_padding
extends css_style_width
{
4448 * Initialises this padding style into several individual padding styles
4450 * @param string $value The value fo the style
4451 * @return array An array of padding styles
4453 public static function init($value) {
4455 if (strpos($value, '!important') !== false) {
4456 $important = ' !important';
4457 $value = str_replace('!important', '', $value);
4460 $value = preg_replace('#\s+#', ' ', trim($value));
4461 $bits = explode(' ', $value, 4);
4463 $top = $right = $bottom = $left = null;
4464 if (count($bits) > 0) {
4465 $top = $right = $bottom = $left = array_shift($bits);
4467 if (count($bits) > 0) {
4468 $right = $left = array_shift($bits);
4470 if (count($bits) > 0) {
4471 $bottom = array_shift($bits);
4473 if (count($bits) > 0) {
4474 $left = array_shift($bits);
4477 new css_style_paddingtop('padding-top', $top.$important),
4478 new css_style_paddingright('padding-right', $right.$important),
4479 new css_style_paddingbottom('padding-bottom', $bottom.$important),
4480 new css_style_paddingleft('padding-left', $left.$important)
4485 * Consolidates several padding styles into a single style.
4487 * @param array $styles Array of padding styles
4488 * @return array Optimised+consolidated array of padding styles
4490 public static function consolidate(array $styles) {
4491 if (count($styles) != 4) {
4495 $someimportant = false;
4496 $allimportant = null;
4497 $notimportantequal = null;
4499 foreach ($styles as $style) {
4500 if ($style->is_important()) {
4501 $someimportant = true;
4502 if ($allimportant === null) {
4503 $allimportant = true;
4506 if ($allimportant === true) {
4507 $allimportant = false;
4509 if ($firstvalue == null) {
4510 $firstvalue = $style->get_value(false);
4511 $notimportantequal = true;
4512 } else if ($notimportantequal && $firstvalue !== $style->get_value(false)) {
4513 $notimportantequal = false;
4518 if ($someimportant && !$allimportant && !$notimportantequal) {
4522 if ($someimportant && !$allimportant && $notimportantequal) {
4524 new css_style_padding('padding', $firstvalue)
4526 foreach ($styles as $style) {
4527 if ($style->is_important()) {
4537 foreach ($styles as $style) {
4538 switch ($style->get_name()) {
4539 case 'padding-top' : $top = $style->get_value(false);break;
4540 case 'padding-right' : $right = $style->get_value(false);break;
4541 case 'padding-bottom' : $bottom = $style->get_value(false);break;
4542 case 'padding-left' : $left = $style->get_value(false);break;
4545 if ($top == $bottom && $left == $right) {
4546 if ($top == $left) {
4547 $returnstyle = new css_style_padding('padding', $top);
4549 $returnstyle = new css_style_padding('padding', "{$top} {$left}");
4551 } else if ($left == $right) {
4552 $returnstyle = new css_style_padding('padding', "{$top} {$right} {$bottom}");
4554 $returnstyle = new css_style_padding('padding', "{$top} {$right} {$bottom} {$left}");
4556 if ($allimportant) {
4557 $returnstyle->set_important();
4559 return array($returnstyle);
4565 * A padding top style.
4569 * @copyright 2012 Sam Hemelryk
4570 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4572 class css_style_paddingtop
extends css_style_padding
{
4575 * Initialises this style
4577 * @param string $value The value of the style
4578 * @return css_style_paddingtop
4580 public static function init($value) {
4581 return new css_style_paddingtop('padding-top', $value);
4585 * Consolidates this style into a single padding style
4589 public function consolidate_to() {
4595 * A padding right style.
4599 * @copyright 2012 Sam Hemelryk
4600 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4602 class css_style_paddingright
extends css_style_padding
{
4605 * Initialises this style
4607 * @param string $value The value of the style
4608 * @return css_style_paddingright
4610 public static function init($value) {
4611 return new css_style_paddingright('padding-right', $value);
4615 * Consolidates this style into a single padding style
4619 public function consolidate_to() {
4625 * A padding bottom style.
4629 * @copyright 2012 Sam Hemelryk
4630 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4632 class css_style_paddingbottom
extends css_style_padding
{
4635 * Initialises this style
4637 * @param string $value The value of the style
4638 * @return css_style_paddingbottom
4640 public static function init($value) {
4641 return new css_style_paddingbottom('padding-bottom', $value);
4645 * Consolidates this style into a single padding style
4649 public function consolidate_to() {
4655 * A padding left style.
4659 * @copyright 2012 Sam Hemelryk
4660 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4662 class css_style_paddingleft
extends css_style_padding
{
4665 * Initialises this style
4667 * @param string $value The value of the style
4668 * @return css_style_paddingleft
4670 public static function init($value) {
4671 return new css_style_paddingleft('padding-left', $value);
4675 * Consolidates this style into a single padding style
4679 public function consolidate_to() {
4689 * @copyright 2012 Sam Hemelryk
4690 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4692 class css_style_cursor
extends css_style_generic
{
4694 * Initialises a new cursor style
4695 * @param string $value
4696 * @return css_style_cursor
4698 public static function init($value) {
4699 return new css_style_cursor('cursor', $value);
4702 * Cleans the given value and returns it.
4704 * @param string $value
4707 protected function clean_value($value) {
4708 // Allowed values for the cursor style
4709 $allowed = array('auto', 'crosshair', 'default', 'e-resize', 'help', 'move', 'n-resize', 'ne-resize', 'nw-resize',
4710 'pointer', 'progress', 's-resize', 'se-resize', 'sw-resize', 'text', 'w-resize', 'wait', 'inherit');
4711 // Has to be one of the allowed values of an image to use. Loosely match the image... doesn't need to be thorough
4712 if (!in_array($value, $allowed) && !preg_match('#\.[a-zA-Z0-9_\-]{1,5}$#', $value)) {
4713 $this->set_error('Invalid or unexpected cursor value specified: '.$value);
4715 return trim($value);
4720 * A vertical alignment style.
4724 * @copyright 2012 Sam Hemelryk
4725 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4727 class css_style_verticalalign
extends css_style_generic
{
4729 * Initialises a new vertical alignment style
4730 * @param string $value
4731 * @return css_style_verticalalign
4733 public static function init($value) {
4734 return new css_style_verticalalign('vertical-align', $value);
4737 * Cleans the given value and returns it.
4739 * @param string $value
4742 protected function clean_value($value) {
4743 $allowed = array('baseline', 'sub', 'super', 'top', 'text-top', 'middle', 'bottom', 'text-bottom', 'inherit');
4744 if (!css_is_width($value) && !in_array($value, $allowed)) {
4745 $this->set_error('Invalid vertical-align value specified: '.$value);
4747 return trim($value);
4756 * @copyright 2012 Sam Hemelryk
4757 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4759 class css_style_float
extends css_style_generic
{
4761 * Initialises a new float style
4762 * @param string $value
4763 * @return css_style_float
4765 public static function init($value) {
4766 return new css_style_float('float', $value);
4769 * Cleans the given value and returns it.
4771 * @param string $value
4774 protected function clean_value($value) {
4775 $allowed = array('left', 'right', 'none', 'inherit');
4776 if (!css_is_width($value) && !in_array($value, $allowed)) {
4777 $this->set_error('Invalid float value specified: '.$value);
4779 return trim($value);