<?php
/*
* CSS Mixin, Version 3
* Copyright 2007-2009 Chuck Houpt
* MIT License
*/
$cssrules = array();
$debug = FALSE;
$setheaders = FALSE;
// ETag based on the same formula as Apache 1.3
function etag($file)
{
return sprintf('%x-%x-%x', fileinode($file), filesize($file), filemtime($file));
}
// cssmixin_init must be called first to setup HTTP headers and load base CSS styles.
function cssmixin_init($cssfile, $debugflag)
{
global $cssrules;
global $debug;
global $setheaders;
$debug = $debugflag;
if (!$setheaders) {
$setheaders = TRUE;
$last_modified = max(filemtime($_SERVER['SCRIPT_FILENAME']), filemtime($cssfile));
$etag = '"' . etag($_SERVER['SCRIPT_FILENAME']) . '-' . etag($cssfile) . '"';
header('Content-type: text/css');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $last_modified) . ' GMT');
header("ETag: $etag");
if ((isset($_SERVER['HTTP_IF_NONE_MATCH']) && strcmp($_SERVER['HTTP_IF_NONE_MATCH'], $etag) == 0) ||
(isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= $last_modified)) {
header('HTTP/1.0 304 Not Modified');
exit;
}
print("/* Generated by CSS Mixin v3 http://habilis.net/cssmixin/ */\n");
if ($debug) print("/*\n PHP Style Script: {$_SERVER['PHP_SELF']}\n CSS Class File: $cssfile\n*/\n");
}
// load CSS
$f = file_get_contents($cssfile);
// Strip all the comments
$f = preg_replace('/\/\*.*\*\//sU', '', $f);
// Tokenize into selectors, and declariations.
// It's not a parser, it's a pharser (hackish, kludgy parser).
preg_match_all('/([>_a-z0-9-:\.\*][>_a-z0-9-:\.\* ]+[>_a-z0-9-:\.\*])|({[^}]+})/si', $f, $out, PREG_SET_ORDER);
//print_r($out);
// Construct descriptor by appending selectors
$selector_list = array();
foreach ($out as $o) {
$firstc = $o[0][0];
if ($firstc != '{') {
$selector_list[] = $o[1];
} else if ($firstc == '{') {
$descriptor = trim(trim($o[2], ' '), "\n\r");
foreach ($selector_list as $s) {
if (preg_match('/\.([_a-z0-9-]+)/si', $s, $matches)) {
$class = $matches[1];
if (array_key_exists($class, $cssrules)) $cssrules[$class][] = array($s, $descriptor);
else $cssrules[$class] = array(array($s, $descriptor));
}
}
$selector_list = array();
}
}
//print_r($cssrules);
}
// cssmixin creates new style descriptors for $newspec based on the $mixinclasses list.
function cssmixin($newspec, $mixinclasses)
{
global $cssrules;
global $debug;
$clist = explode(' ', $mixinclasses);
foreach ($clist as $c) {
if ($debug) {
print("/* Spec: $newspec Class: $c */\n\n");
}
if (array_key_exists($c, $cssrules)) {
foreach ($cssrules[$c] as $rule) {
$selector = $rule[0];
$description = $rule[1];
$selector = str_replace(".$c", $newspec, $selector);
print("$selector $description\n\n");
}
}
}
}
?>