color.module
<?php
function color_help($path, $arg) {
switch ($path) {
case 'admin/help#color':
$output = '<h3>' . t('About') . '</h3>';
$output .= '<p>' . t('The Color module allows users with the <em>Administer site configuration</em> permission to quickly and easily change the color scheme of themes that have been built to be compatible with it. For more information, see the online handbook entry for <a href="@color">Color module</a>.', array('@color' => 'http://drupal.org/handbook/modules/color')) . '</p>';
$output .= '<h3>' . t('Uses') . '</h3>';
$output .= '<dl>';
$output .= '<dt>' . t('Changing colors') . '</dt>';
$output .= '<dd>' . t("Using the Color module allows you to easily change the color of links, backgrounds, text, and other theme elements. To change the color settings for a compatible theme, select the <em>configure</em> link for your theme on the <a href='@configure'>Themes administration page</a>. If you don't see a color picker on that page, then your theme is not compatible with the color module. If you are sure that the theme does indeed support the color module, but the color picker does not appear, then <a href='@troubleshoot'>follow these troubleshooting procedures</a>.", array('@configure' => url('admin/appearance'), '@troubleshoot' => 'http://drupal.org/node/109457')) . '</dd>';
$output .= '<dd>' . t("The Color module saves a modified copy of the theme's specified stylesheets in the files directory. This means that if you make any manual changes to your theme's stylesheet, <em>you must save your color settings again, even if they haven't changed</em>. This step is required because the module stylesheets (in the files directory) need to be recreated to include your changes.") . '</dd>';
$output .= '</dl>';
return $output;
}
}
function color_theme() {
return array(
'color_scheme_form' => array(
'render element' => 'form',
),
);
}
function color_form_system_theme_settings_alter(&$form, &$form_state) {
if (isset($form_state['build_info']['args'][0]) && ($theme = $form_state['build_info']['args'][0]) && color_get_info($theme) && function_exists('gd_info')) {
$form['color'] = array(
'#type' => 'fieldset',
'#title' => t('Color scheme'),
'#weight' => -1,
'#attributes' => array('id' => 'color_scheme_form'),
'#theme' => 'color_scheme_form',
);
$form['color'] += color_scheme_form($form, $form_state, $theme);
$form['#submit'][] = 'color_scheme_form_submit';
}
}
function color_form_system_themes_alter(&$form, &$form_state) {
_color_theme_select_form_alter($form, $form_state);
}
function _color_theme_select_form_alter(&$form, &$form_state) {
$themes = list_themes();
foreach (element_children($form) as $theme) {
if ($screenshot = variable_get('color_' . $theme . '_screenshot')) {
if (isset($form[$theme]['screenshot'])) {
$form[$theme]['screenshot']['#markup'] = theme('image', array('path' => $screenshot, 'alt' => '', 'title' => '', 'attributes' => array('class' => array('screenshot')), 'getsize' => FALSE));
}
}
}
}
function _color_html_alter(&$vars) {
global $language, $theme_key;
$themes = list_themes();
$color_paths = variable_get('color_' . $theme_key . '_stylesheets', array());
if (!empty($color_paths)) {
foreach ($themes[$theme_key]->stylesheets['all'] as $base_filename => $old_path) {
foreach ($color_paths as $color_path) {
if (basename($old_path) == basename($color_path)) {
$vars['css'][$old_path]['data'] = $color_path;
}
}
}
$vars['styles'] = drupal_get_css($vars['css']);
}
}
function _color_page_alter(&$vars) {
global $language, $theme_key;
$logo = variable_get('color_' . $theme_key . '_logo');
if ($logo && $vars['logo'] && preg_match('!' . $theme_key . '/logo.png$!', $vars['logo'])) {
$vars['logo'] = file_create_url($logo);
}
}
function color_get_info($theme) {
$path = drupal_get_path('theme', $theme);
$file = DRUPAL_ROOT . '/' . $path . '/color/color.inc';
if ($path && file_exists($file)) {
include $file;
return $info;
}
}
function color_get_palette($theme, $default = FALSE) {
$fields = array('base', 'link', 'top', 'bottom', 'text');
$info = color_get_info($theme);
$keys = array_keys($info['schemes']);
foreach (explode(',', array_shift($keys)) as $k => $scheme) {
$palette[$fields[$k]] = $scheme;
}
return $default ? $palette : variable_get('color_' . $theme . '_palette', $palette);
}
function color_scheme_form($complete_form, &$form_state, $theme) {
$base = drupal_get_path('module', 'color');
$info = color_get_info($theme);
$current = implode(',', variable_get('color_' . $theme . '_palette', array()));
$current = isset($info['schemes'][$current]) ? $current : ($current == '' ? reset($info['schemes']) : '');
$info['schemes'][''] = t('Custom');
$form['scheme'] = array(
'#type' => 'select',
'#title' => t('Color set'),
'#options' => $info['schemes'],
'#default_value' => $current,
'#attached' => array(
'library' => array(
array('system', 'farbtastic'),
),
'css' => array(
$base . '/color.css' => array('preprocess' => FALSE),
),
'js' => array(
$base . '/color.js',
array(
'data' => array(
'color' => array('reference' => color_get_palette($theme, TRUE)),
),
'type' => 'setting',
),
),
),
);
$palette = color_get_palette($theme);
$names = array(
'base' => t('Base color'),
'link' => t('Link color'),
'top' => t('Header top'),
'bottom' => t('Header bottom'),
'text' => t('Text color'),
);
$form['palette']['#tree'] = TRUE;
foreach ($palette as $name => $value) {
$form['palette'][$name] = array(
'#type' => 'textfield',
'#title' => $names[$name],
'#default_value' => $value,
'#size' => 8,
);
}
$form['theme'] = array('#type' => 'value', '#value' => $theme);
$form['info'] = array('#type' => 'value', '#value' => $info);
return $form;
}
function theme_color_scheme_form($variables) {
$form = $variables['form'];
$theme = $form['theme']['#value'];
$info = $form['info']['#value'];
$path = drupal_get_path('theme', $theme) . '/';
drupal_add_css($path . $info['preview_css']);
$output = '';
$output .= '<div class="color-form clearfix">';
$output .= drupal_render($form['scheme']);
$output .= '<div id="palette" class="clearfix">';
foreach (element_children($form['palette']) as $name) {
$output .= drupal_render($form['palette'][$name]);
}
$output .= '</div>';
$output .= drupal_render_children($form);
$output .= '<h2>' . t('Preview') . '</h2>';
$output .= '<div id="preview"><div id="text"><h2>Lorem ipsum dolor</h2><p>Sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud <a href="#">exercitation ullamco</a> laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p></div><div id="img" style="background-image: url(' . base_path() . $path . $info['preview_image'] . ')"></div></div>';
$output .= '</div>';
return $output;
}
function color_scheme_form_submit($form, &$form_state) {
if (!isset($form_state['values']['info'])) {
return;
}
$theme = $form_state['values']['theme'];
$info = $form_state['values']['info'];
$palette = $form_state['values']['palette'];
if ($form_state['values']['scheme'] != '') {
$scheme = explode(',', $form_state['values']['scheme']);
foreach ($palette as $k => $color) {
$palette[$k] = array_shift($scheme);
}
}
if (function_exists('memory_get_usage')) {
$source = drupal_get_path('theme', $theme) . '/' . $info['base_image'];
list($width, $height) = getimagesize($source);
$required = $width * $height * 8;
$usage = memory_get_usage();
$limit = parse_size(ini_get('memory_limit'));
if ($usage + $required > $limit) {
drupal_set_message(t('There is not enough memory available to PHP to change this theme\'s color scheme. You need at least %size more. Check the <a href="@url">PHP documentation</a> for more information.', array('%size' => format_size($usage + $required - $limit), '@url' => 'http://www.php.net/manual/ini.core.php#ini.sect.resource-limits')), 'error');
return;
}
}
foreach (variable_get('color_' . $theme . '_files', array()) as $file) {
@unlink($file);
}
if (isset($file) && $file = dirname($file)) {
@rmdir($file);
}
if (implode(',', color_get_palette($theme, TRUE)) == implode(',', $palette)) {
variable_del('color_' . $theme . '_palette');
variable_del('color_' . $theme . '_stylesheets');
variable_del('color_' . $theme . '_logo');
variable_del('color_' . $theme . '_files');
variable_del('color_' . $theme . '_screenshot');
return;
}
$id = $theme . '-' . substr(md5(serialize($palette) . microtime()), 0, 8);
$paths['color'] = 'public://color';
$paths['target'] = $paths['color'] . '/' . $id;
foreach ($paths as $path) {
file_prepare_directory($path, FILE_CREATE_DIRECTORY);
}
$paths['target'] = $paths['target'] . '/';
$paths['id'] = $id;
$paths['source'] = drupal_get_path('theme', $theme) . '/';
$paths['files'] = $paths['map'] = array();
variable_set('color_' . $theme . '_palette', $palette);
variable_set('color_' . $theme . '_logo', $paths['target'] . 'logo.png');
foreach ($info['copy'] as $file) {
$base = basename($file);
$source = $paths['source'] . $file;
$filepath = file_unmanaged_copy($source, $paths['target'] . $base);
$paths['map'][$file] = $base;
$paths['files'][] = $filepath;
}
if ($info['base_image']) {
_color_render_images($theme, $info, $paths, $palette);
}
$css = array();
foreach ($info['css'] as $stylesheet) {
$files = array();
if (file_exists($paths['source'] . $stylesheet)) {
$files[] = $stylesheet;
$rtl_file = str_replace('.css', '-rtl.css', $stylesheet);
if (file_exists($paths['source'] . $rtl_file)) {
$files[] = $rtl_file;
}
}
foreach ($files as $file) {
$style = drupal_load_stylesheet($paths['source'] . $file, FALSE);
$base = base_path() . dirname($paths['source'] . $file) . '/';
_drupal_build_css_path(NULL, $base);
$style = preg_replace_callback('/url\([\'"]?(?![a-z]+:|\/+)([^\'")]+)[\'"]?\)/i', '_drupal_build_css_path', $style);
$style = _color_rewrite_stylesheet($theme, $info, $paths, $palette, $style);
$base_file = basename($file);
$css[] = $paths['target'] . $base_file;
_color_save_stylesheet($paths['target'] . $base_file, $style, $paths);
}
}
variable_set('color_' . $theme . '_stylesheets', $css);
variable_set('color_' . $theme . '_files', $paths['files']);
}
function _color_rewrite_stylesheet($theme, &$info, &$paths, $palette, $style) {
$themes = list_themes();
$conversion = $palette;
unset($conversion['base']);
foreach ($conversion as $k => $v) {
$conversion[$k] = drupal_strtolower($v);
}
$default = color_get_palette($theme, TRUE);
$split = "Color Module: Don't touch";
if (strpos($style, $split) !== FALSE) {
list($style, $fixed) = explode($split, $style);
}
$style = preg_split('/(#[0-9a-f]{6}|#[0-9a-f]{3})/i', $style, -1, PREG_SPLIT_DELIM_CAPTURE);
$is_color = FALSE;
$output = '';
$base = 'base';
foreach ($style as $chunk) {
if ($is_color) {
$chunk = drupal_strtolower($chunk);
if ($key = array_search($chunk, $default)) {
$chunk = $conversion[$key];
}
else {
$chunk = _color_shift($palette[$base], $default[$base], $chunk, $info['blend_target']);
}
}
else {
if (preg_match('@[^a-z0-9_-](a)[^a-z0-9_-][^/{]*{[^{]+$@i', $chunk)) {
$base = 'link';
}
elseif (preg_match('/(?<!-)color[^{:]*:[^{#]*$/i', $chunk)) {
$base = 'text';
}
else {
$base = 'base';
}
}
$output .= $chunk;
$is_color = !$is_color;
}
if (isset($fixed)) {
$output .= $fixed;
}
foreach ($paths['map'] as $before => $after) {
$before = base_path() . $paths['source'] . $before;
$before = preg_replace('`(^|/)(?!../)([^/]+)/../`', '$1', $before);
$output = str_replace($before, $after, $output);
}
return $output;
}
function _color_save_stylesheet($file, $style, &$paths) {
$filepath = file_unmanaged_save_data($style, $file, FILE_EXISTS_REPLACE);
$paths['files'][] = $filepath;
drupal_chmod($file);
}
function _color_render_images($theme, &$info, &$paths, $palette) {
$source = $paths['source'] . '/' . $info['base_image'];
$source = imagecreatefrompng($source);
$width = imagesx($source);
$height = imagesy($source);
$target = imagecreatetruecolor($width, $height);
imagealphablending($target, TRUE);
foreach ($info['fill'] as $color => $fill) {
imagefilledrectangle($target, $fill[0], $fill[1], $fill[0] + $fill[2], $fill[1] + $fill[3], _color_gd($target, $palette[$color]));
}
for ($y = 0; $y < $info['gradient'][3]; ++$y) {
$color = _color_blend($target, $palette['top'], $palette['bottom'], $y / ($info['gradient'][3] - 1));
imagefilledrectangle($target, $info['gradient'][0], $info['gradient'][1] + $y, $info['gradient'][0] + $info['gradient'][2], $info['gradient'][1] + $y + 1, $color);
}
imagecopy($target, $source, 0, 0, 0, 0, $width, $height);
imagedestroy($source);
foreach ($info['slices'] as $file => $coord) {
list($x, $y, $width, $height) = $coord;
$base = basename($file);
$image = drupal_realpath($paths['target'] . $base);
if ($file == 'screenshot.png') {
$slice = imagecreatetruecolor(150, 90);
imagecopyresampled($slice, $target, 0, 0, $x, $y, 150, 90, $width, $height);
variable_set('color_' . $theme . '_screenshot', $image);
}
else {
$slice = imagecreatetruecolor($width, $height);
imagecopy($slice, $target, 0, 0, $x, $y, $width, $height);
}
imagepng($slice, $image);
imagedestroy($slice);
$paths['files'][] = $image;
drupal_chmod($image);
$paths['map'][$file] = $base;
}
imagedestroy($target);
}
function _color_shift($given, $ref1, $ref2, $target) {
$target = _color_unpack($target, TRUE);
$ref1 = _color_unpack($ref1, TRUE);
$ref2 = _color_unpack($ref2, TRUE);
$numerator = 0;
$denominator = 0;
for ($i = 0; $i < 3; ++$i) {
$numerator += ($ref2[$i] - $ref1[$i]) * ($ref2[$i] - $ref1[$i]);
$denominator += ($target[$i] - $ref1[$i]) * ($target[$i] - $ref1[$i]);
}
$delta = ($denominator > 0) ? (1 - sqrt($numerator / $denominator)) : 0;
for ($i = 0; $i < 3; ++$i) {
$ref3[$i] = $target[$i] + ($ref1[$i] - $target[$i]) * $delta;
}
$ref2 = _color_rgb2hsl($ref2);
$ref3 = _color_rgb2hsl($ref3);
for ($i = 0; $i < 3; ++$i) {
$shift[$i] = $ref2[$i] - $ref3[$i];
}
$given = _color_unpack($given, TRUE);
for ($i = 0; $i < 3; ++$i) {
$result[$i] = $target[$i] + ($given[$i] - $target[$i]) * $delta;
}
$result = _color_rgb2hsl($result);
for ($i = 0; $i < 3; ++$i) {
$result[$i] = min(1, max(0, $result[$i] + $shift[$i]));
}
$result = _color_hsl2rgb($result);
return _color_pack($result, TRUE);
}
function _color_gd($img, $hex) {
$c = array_merge(array($img), _color_unpack($hex));
return call_user_func_array('imagecolorallocate', $c);
}
function _color_blend($img, $hex1, $hex2, $alpha) {
$in1 = _color_unpack($hex1);
$in2 = _color_unpack($hex2);
$out = array($img);
for ($i = 0; $i < 3; ++$i) {
$out[] = $in1[$i] + ($in2[$i] - $in1[$i]) * $alpha;
}
return call_user_func_array('imagecolorallocate', $out);
}
function _color_unpack($hex, $normalize = FALSE) {
if (strlen($hex) == 4) {
$hex = $hex[1] . $hex[1] . $hex[2] . $hex[2] . $hex[3] . $hex[3];
}
$c = hexdec($hex);
for ($i = 16; $i >= 0; $i -= 8) {
$out[] = (($c >> $i) & 0xFF) / ($normalize ? 255 : 1);
}
return $out;
}
function _color_pack($rgb, $normalize = FALSE) {
$out = 0;
foreach ($rgb as $k => $v) {
$out |= (($v * ($normalize ? 255 : 1)) << (16 - $k * 8));
}
return '#' . str_pad(dechex($out), 6, 0, STR_PAD_LEFT);
}
function _color_hsl2rgb($hsl) {
$h = $hsl[0];
$s = $hsl[1];
$l = $hsl[2];
$m2 = ($l <= 0.5) ? $l * ($s + 1) : $l + $s - $l*$s;
$m1 = $l * 2 - $m2;
return array(
_color_hue2rgb($m1, $m2, $h + 0.33333),
_color_hue2rgb($m1, $m2, $h),
_color_hue2rgb($m1, $m2, $h - 0.33333),
);
}
function _color_hue2rgb($m1, $m2, $h) {
$h = ($h < 0) ? $h + 1 : (($h > 1) ? $h - 1 : $h);
if ($h * 6 < 1) return $m1 + ($m2 - $m1) * $h * 6;
if ($h * 2 < 1) return $m2;
if ($h * 3 < 2) return $m1 + ($m2 - $m1) * (0.66666 - $h) * 6;
return $m1;
}
function _color_rgb2hsl($rgb) {
$r = $rgb[0];
$g = $rgb[1];
$b = $rgb[2];
$min = min($r, min($g, $b));
$max = max($r, max($g, $b));
$delta = $max - $min;
$l = ($min + $max) / 2;
$s = 0;
if ($l > 0 && $l < 1) {
$s = $delta / ($l < 0.5 ? (2 * $l) : (2 - 2 * $l));
}
$h = 0;
if ($delta > 0) {
if ($max == $r && $max != $g) $h += ($g - $b) / $delta;
if ($max == $g && $max != $b) $h += (2 + ($b - $r) / $delta);
if ($max == $b && $max != $r) $h += (4 + ($r - $g) / $delta);
$h /= 6;
}
return array($h, $s, $l);
}