color.module

You are here

  1. 7 modules/color/color.module
  2. 5 modules/color/color.module
  3. 6 modules/color/color.module
  4. 8 core/modules/color/color.module

Functions

Namesort descending Description
color_form_alter Implementation of hook_form_alter().
color_get_info Retrieve the color.module info for a particular theme.
color_get_palette Helper function to retrieve the color palette for a particular theme.
color_help Implementation of hook_help().
color_scheme_form Form callback. Returns the configuration form.
color_scheme_form_submit Submit handler for color change form.
color_scheme_form_validate Validation handler for color change form.
color_theme Implementation of hook_theme().
theme_color_scheme_form Theme color form.
_color_blend Blend two hex colors and return the GD color.
_color_gd Convert a hex triplet into a GD color.
_color_hsl2rgb Convert a HSL triplet into RGB
_color_hue2rgb Helper function for _color_hsl2rgb().
_color_pack Convert an RGB triplet to a hex color.
_color_page_alter Callback for the theme to alter the resources used.
_color_render_images Render images that match a given palette.
_color_rewrite_stylesheet Rewrite the stylesheet to match the colors in the palette.
_color_rgb2hsl Convert an RGB triplet to HSL.
_color_save_stylesheet Save the rewritten stylesheet to disk.
_color_shift Shift a given color, using a reference pair and a target blend color.
_color_unpack Convert a hex color into an RGB triplet.

File

modules/color/color.module
View source
  1. <?php
  2. /**
  3. * Implementation of hook_help().
  4. */
  5. function color_help($path, $arg) {
  6. switch ($path) {
  7. case 'admin/help#color':
  8. $output = '<p>'. t('The color module allows a site administrator to quickly and easily change the color scheme of certain themes. Although not all themes support color module, both Garland (the default theme) and Minnelli were designed to take advantage of its features. By using color module with a compatible theme, you can easily change the color of links, backgrounds, text, and other theme elements. Color module requires that your <a href="@url">file download method</a> be set to public.', array('@url' => url('admin/settings/file-system'))) .'</p>';
  9. $output .= '<p>'. t("It is important to remember that 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, you must save your color settings again, even if they haven't changed. This causes the color module generated version of the stylesheets in the files directory to be recreated using the new version of the original file.") .'</p>';
  10. $output .= '<p>'. t('To change the color settings for a compatible theme, select the "configure" link for the theme on the <a href="@themes">themes administration page</a>.', array('@themes' => url('admin/build/themes'))) .'</p>';
  11. $output .= '<p>'. t('For more information, see the online handbook entry for <a href="@color">Color module</a>.', array('@color' => 'http://drupal.org/handbook/modules/color/')) .'</p>';
  12. return $output;
  13. }
  14. }
  15. /**
  16. * Implementation of hook_theme().
  17. */
  18. function color_theme() {
  19. return array(
  20. 'color_scheme_form' => array(
  21. 'arguments' => array('form' => NULL),
  22. ),
  23. );
  24. }
  25. /**
  26. * Implementation of hook_form_alter().
  27. */
  28. function color_form_alter(&$form, $form_state, $form_id) {
  29. // Insert the color changer into the theme settings page.
  30. if ($form_id == 'system_theme_settings' && color_get_info(arg(4)) && function_exists('gd_info')) {
  31. if (variable_get('file_downloads', FILE_DOWNLOADS_PUBLIC) != FILE_DOWNLOADS_PUBLIC) {
  32. // Disables the color changer when the private download method is used.
  33. // TODO: This should be solved in a different way. See issue #181003.
  34. drupal_set_message(t('The color picker only works if the <a href="@url">download method</a> is set to public.', array('@url' => url('admin/settings/file-system'))), 'warning');
  35. }
  36. else {
  37. $form['color'] = array(
  38. '#type' => 'fieldset',
  39. '#title' => t('Color scheme'),
  40. '#weight' => -1,
  41. '#attributes' => array('id' => 'color_scheme_form'),
  42. '#theme' => 'color_scheme_form',
  43. );
  44. $form['color'] += color_scheme_form($form_state, arg(4));
  45. $form['#validate'][] = 'color_scheme_form_validate';
  46. $form['#submit'][] = 'color_scheme_form_submit';
  47. }
  48. }
  49. // Use the generated screenshot in the theme list.
  50. if ($form_id == 'system_theme_select_form' || $form_id == 'system_themes') {
  51. $themes = list_themes();
  52. foreach (element_children($form) as $theme) {
  53. if ($screenshot = variable_get('color_'. $theme .'_screenshot', NULL)) {
  54. if (isset($form[$theme]['screenshot'])) {
  55. $form[$theme]['screenshot']['#value'] = theme('image', $screenshot, '', '', array('class' => 'screenshot'), FALSE);
  56. }
  57. }
  58. }
  59. }
  60. }
  61. /**
  62. * Callback for the theme to alter the resources used.
  63. */
  64. function _color_page_alter(&$vars) {
  65. global $language, $theme_key;
  66. // Override stylesheets.
  67. $color_paths = variable_get('color_'. $theme_key .'_stylesheets', array());
  68. if (!empty($color_paths)) {
  69. // Loop over theme CSS files and try to rebuild CSS array with rewritten
  70. // stylesheets. Keep the orginal order intact for CSS cascading.
  71. $new_theme_css = array();
  72. foreach ($vars['css']['all']['theme'] as $old_path => $old_preprocess) {
  73. // Add the non-colored stylesheet first as we might not find a
  74. // re-colored stylesheet for replacement later.
  75. $new_theme_css[$old_path] = $old_preprocess;
  76. // Loop over the path array with recolored CSS files to find matching
  77. // paths which could replace the non-recolored paths.
  78. foreach ($color_paths as $color_path) {
  79. // Color module currently requires unique file names to be used,
  80. // which allows us to compare different file paths.
  81. if (basename($old_path) == basename($color_path)) {
  82. // Pull out the non-colored and add rewritten stylesheet.
  83. unset($new_theme_css[$old_path]);
  84. $new_theme_css[$color_path] = $old_preprocess;
  85. // If the current language is RTL and the CSS file had an RTL variant,
  86. // pull out the non-colored and add rewritten RTL stylesheet.
  87. if ($language->direction == LANGUAGE_RTL) {
  88. $rtl_old_path = str_replace('.css', '-rtl.css', $old_path);
  89. $rtl_color_path = str_replace('.css', '-rtl.css', $color_path);
  90. if (file_exists($rtl_color_path)) {
  91. unset($new_theme_css[$rtl_old_path]);
  92. $new_theme_css[$rtl_color_path] = $old_preprocess;
  93. }
  94. }
  95. break;
  96. }
  97. }
  98. }
  99. $vars['css']['all']['theme'] = $new_theme_css;
  100. $vars['styles'] = drupal_get_css($vars['css']);
  101. }
  102. // Override logo.
  103. $logo = variable_get('color_'. $theme_key .'_logo', NULL);
  104. if ($logo && $vars['logo'] && preg_match('!'. $theme_key .'/logo.png$!', $vars['logo'])) {
  105. $vars['logo'] = base_path() . $logo;
  106. }
  107. }
  108. /**
  109. * Retrieve the color.module info for a particular theme.
  110. */
  111. function color_get_info($theme) {
  112. $path = drupal_get_path('theme', $theme);
  113. $file = $path .'/color/color.inc';
  114. if ($path && file_exists($file)) {
  115. include $file;
  116. return $info;
  117. }
  118. }
  119. /**
  120. * Helper function to retrieve the color palette for a particular theme.
  121. */
  122. function color_get_palette($theme, $default = false) {
  123. // Fetch and expand default palette
  124. $fields = array('base', 'link', 'top', 'bottom', 'text');
  125. $info = color_get_info($theme);
  126. $keys = array_keys($info['schemes']);
  127. foreach (explode(',', array_shift($keys)) as $k => $scheme) {
  128. $palette[$fields[$k]] = $scheme;
  129. }
  130. // Load variable
  131. return $default ? $palette : variable_get('color_'. $theme .'_palette', $palette);
  132. }
  133. /**
  134. * Form callback. Returns the configuration form.
  135. */
  136. function color_scheme_form(&$form_state, $theme) {
  137. $base = drupal_get_path('module', 'color');
  138. $info = color_get_info($theme);
  139. // Add Farbtastic color picker
  140. drupal_add_css('misc/farbtastic/farbtastic.css', 'module', 'all', FALSE);
  141. drupal_add_js('misc/farbtastic/farbtastic.js');
  142. // Add custom CSS/JS
  143. drupal_add_css($base .'/color.css', 'module', 'all', FALSE);
  144. drupal_add_js($base .'/color.js');
  145. drupal_add_js(array('color' => array(
  146. 'reference' => color_get_palette($theme, true)
  147. )), 'setting');
  148. // See if we're using a predefined scheme
  149. $current = implode(',', variable_get('color_'. $theme .'_palette', array()));
  150. // Note: we use the original theme when the default scheme is chosen.
  151. $current = isset($info['schemes'][$current]) ? $current : ($current == '' ? reset($info['schemes']) : '');
  152. // Add scheme selector
  153. $info['schemes'][''] = t('Custom');
  154. $form['scheme'] = array(
  155. '#type' => 'select',
  156. '#title' => t('Color set'),
  157. '#options' => $info['schemes'],
  158. '#default_value' => $current,
  159. );
  160. // Add palette fields
  161. $palette = color_get_palette($theme);
  162. $names = array(
  163. 'base' => t('Base color'),
  164. 'link' => t('Link color'),
  165. 'top' => t('Header top'),
  166. 'bottom' => t('Header bottom'),
  167. 'text' => t('Text color')
  168. );
  169. $form['palette']['#tree'] = true;
  170. foreach ($palette as $name => $value) {
  171. $form['palette'][$name] = array(
  172. '#type' => 'textfield',
  173. '#title' => $names[$name],
  174. '#default_value' => $value,
  175. '#size' => 8,
  176. );
  177. }
  178. $form['theme'] = array('#type' => 'value', '#value' => arg(4));
  179. $form['info'] = array('#type' => 'value', '#value' => $info);
  180. return $form;
  181. }
  182. /**
  183. * Theme color form.
  184. *
  185. * @ingroup themeable
  186. */
  187. function theme_color_scheme_form($form) {
  188. // Include stylesheet
  189. $theme = $form['theme']['#value'];
  190. $info = $form['info']['#value'];
  191. $path = drupal_get_path('theme', $theme) .'/';
  192. drupal_add_css($path . $info['preview_css']);
  193. $output = '';
  194. // Wrapper
  195. $output .= '<div class="color-form clear-block">';
  196. // Color schemes
  197. $output .= drupal_render($form['scheme']);
  198. // Palette
  199. $output .= '<div id="palette" class="clear-block">';
  200. foreach (element_children($form['palette']) as $name) {
  201. $output .= drupal_render($form['palette'][$name]);
  202. }
  203. $output .= '</div>';
  204. // Preview
  205. $output .= drupal_render($form);
  206. $output .= '<h2>'. t('Preview') .'</h2>';
  207. $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>';
  208. // Close wrapper
  209. $output .= '</div>';
  210. return $output;
  211. }
  212. /**
  213. * Validation handler for color change form.
  214. */
  215. function color_scheme_form_validate($form, &$form_state) {
  216. // Only accept hexadecimal CSS color strings to avoid XSS upon use.
  217. foreach ($form_state['values']['palette'] as $key => $color) {
  218. if (!preg_match('/^#([a-f0-9]{3}){1,2}$/iD', $color)) {
  219. form_set_error('palette][' . $key, t('%name must be a valid hexadecimal CSS color value.', array('%name' => $form['color']['palette'][$key]['#title'])));
  220. }
  221. }
  222. }
  223. /**
  224. * Submit handler for color change form.
  225. */
  226. function color_scheme_form_submit($form, &$form_state) {
  227. // Get theme coloring info
  228. if (!isset($form_state['values']['info'])) {
  229. return;
  230. }
  231. $theme = $form_state['values']['theme'];
  232. $info = $form_state['values']['info'];
  233. // Resolve palette
  234. $palette = $form_state['values']['palette'];
  235. if ($form_state['values']['scheme'] != '') {
  236. $scheme = explode(',', $form_state['values']['scheme']);
  237. foreach ($palette as $k => $color) {
  238. $palette[$k] = array_shift($scheme);
  239. }
  240. }
  241. // Make sure enough memory is available, if PHP's memory limit is compiled in.
  242. if (function_exists('memory_get_usage')) {
  243. // Fetch source image dimensions.
  244. $source = drupal_get_path('theme', $theme) .'/'. $info['base_image'];
  245. list($width, $height) = getimagesize($source);
  246. // We need at least a copy of the source and a target buffer of the same
  247. // size (both at 32bpp).
  248. $required = $width * $height * 8;
  249. $usage = memory_get_usage();
  250. $limit = parse_size(ini_get('memory_limit'));
  251. if ($usage + $required > $limit) {
  252. 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/en/ini.core.php#ini.sect.resource-limits')), 'error');
  253. return;
  254. }
  255. }
  256. // Delete old files
  257. foreach (variable_get('color_'. $theme .'_files', array()) as $file) {
  258. @unlink($file);
  259. }
  260. if (isset($file) && $file = dirname($file)) {
  261. @rmdir($file);
  262. }
  263. // Don't render the default colorscheme, use the standard theme instead.
  264. if (implode(',', color_get_palette($theme, true)) == implode(',', $palette)
  265. || $form_state['values']['op'] == t('Reset to defaults')) {
  266. variable_del('color_'. $theme .'_palette');
  267. variable_del('color_'. $theme .'_stylesheets');
  268. variable_del('color_'. $theme .'_logo');
  269. variable_del('color_'. $theme .'_files');
  270. variable_del('color_'. $theme .'_screenshot');
  271. return;
  272. }
  273. // Prepare target locations for generated files.
  274. $id = $theme .'-'. substr(md5(serialize($palette) . microtime()), 0, 8);
  275. $paths['color'] = file_directory_path() .'/color';
  276. $paths['target'] = $paths['color'] .'/'. $id;
  277. foreach ($paths as $path) {
  278. file_check_directory($path, FILE_CREATE_DIRECTORY);
  279. }
  280. $paths['target'] = $paths['target'] .'/';
  281. $paths['id'] = $id;
  282. $paths['source'] = drupal_get_path('theme', $theme) .'/';
  283. $paths['files'] = $paths['map'] = array();
  284. // Save palette and logo location.
  285. variable_set('color_'. $theme .'_palette', $palette);
  286. variable_set('color_'. $theme .'_logo', $paths['target'] .'logo.png');
  287. // Copy over neutral images.
  288. foreach ($info['copy'] as $file) {
  289. $base = basename($file);
  290. $source = $paths['source'] . $file;
  291. file_copy($source, $paths['target'] . $base);
  292. $paths['map'][$file] = $base;
  293. $paths['files'][] = $paths['target'] . $base;
  294. }
  295. // Render new images, if image provided.
  296. if ($info['base_image']) {
  297. _color_render_images($theme, $info, $paths, $palette);
  298. }
  299. // Rewrite theme stylesheets.
  300. $css = array();
  301. foreach ($info['css'] as $stylesheet) {
  302. // Build a temporary array with LTR and RTL files.
  303. $files = array();
  304. if (file_exists($paths['source'] . $stylesheet)) {
  305. $files[] = $stylesheet;
  306. $rtl_file = str_replace('.css', '-rtl.css', $stylesheet);
  307. if (file_exists($paths['source'] . $rtl_file)) {
  308. $files[] = $rtl_file;
  309. }
  310. }
  311. foreach ($files as $file) {
  312. // Aggregate @imports recursively for each configured top level CSS file
  313. // without optimization. Aggregation and optimization will be
  314. // handled by drupal_build_css_cache() only.
  315. $style = drupal_load_stylesheet($paths['source'] . $file, FALSE);
  316. // Return the path to where this CSS file originated from, stripping
  317. // off the name of the file at the end of the path.
  318. $base = base_path() . dirname($paths['source'] . $file) .'/';
  319. _drupal_build_css_path(NULL, $base);
  320. // Prefix all paths within this CSS file, ignoring absolute paths.
  321. $style = preg_replace_callback('/url\([\'"]?(?![a-z]+:|\/+)([^\'")]+)[\'"]?\)/i', '_drupal_build_css_path', $style);
  322. // Rewrite stylesheet with new colors.
  323. $style = _color_rewrite_stylesheet($theme, $info, $paths, $palette, $style);
  324. $base_file = basename($file);
  325. $css[] = $paths['target'] . $base_file;
  326. _color_save_stylesheet($paths['target'] . $base_file, $style, $paths);
  327. }
  328. }
  329. // Maintain list of files.
  330. variable_set('color_'. $theme .'_stylesheets', $css);
  331. variable_set('color_'. $theme .'_files', $paths['files']);
  332. }
  333. /**
  334. * Rewrite the stylesheet to match the colors in the palette.
  335. */
  336. function _color_rewrite_stylesheet($theme, &$info, &$paths, $palette, $style) {
  337. $themes = list_themes();
  338. // Prepare color conversion table
  339. $conversion = $palette;
  340. unset($conversion['base']);
  341. foreach ($conversion as $k => $v) {
  342. $conversion[$k] = drupal_strtolower($v);
  343. }
  344. $default = color_get_palette($theme, true);
  345. // Split off the "Don't touch" section of the stylesheet.
  346. $split = "Color Module: Don't touch";
  347. if (strpos($style, $split) !== FALSE) {
  348. list($style, $fixed) = explode($split, $style);
  349. }
  350. // Find all colors in the stylesheet and the chunks in between.
  351. $style = preg_split('/(#[0-9a-f]{6}|#[0-9a-f]{3})/i', $style, -1, PREG_SPLIT_DELIM_CAPTURE);
  352. $is_color = false;
  353. $output = '';
  354. $base = 'base';
  355. // Iterate over all parts.
  356. foreach ($style as $chunk) {
  357. if ($is_color) {
  358. $chunk = drupal_strtolower($chunk);
  359. // Check if this is one of the colors in the default palette.
  360. if ($key = array_search($chunk, $default)) {
  361. $chunk = $conversion[$key];
  362. }
  363. // Not a pre-set color. Extrapolate from the base.
  364. else {
  365. $chunk = _color_shift($palette[$base], $default[$base], $chunk, $info['blend_target']);
  366. }
  367. }
  368. else {
  369. // Determine the most suitable base color for the next color.
  370. // 'a' declarations. Use link.
  371. if (preg_match('@[^a-z0-9_-](a)[^a-z0-9_-][^/{]*{[^{]+$@i', $chunk)) {
  372. $base = 'link';
  373. }
  374. // 'color:' styles. Use text.
  375. else if (preg_match('/(?<!-)color[^{:]*:[^{#]*$/i', $chunk)) {
  376. $base = 'text';
  377. }
  378. // Reset back to base.
  379. else {
  380. $base = 'base';
  381. }
  382. }
  383. $output .= $chunk;
  384. $is_color = !$is_color;
  385. }
  386. // Append fixed colors segment.
  387. if (isset($fixed)) {
  388. $output .= $fixed;
  389. }
  390. // Replace paths to images.
  391. foreach ($paths['map'] as $before => $after) {
  392. $before = base_path() . $paths['source'] . $before;
  393. $before = preg_replace('`(^|/)(?!../)([^/]+)/../`', '$1', $before);
  394. $output = str_replace($before, $after, $output);
  395. }
  396. return $output;
  397. }
  398. /**
  399. * Save the rewritten stylesheet to disk.
  400. */
  401. function _color_save_stylesheet($file, $style, &$paths) {
  402. // Write new stylesheet.
  403. file_save_data($style, $file, FILE_EXISTS_REPLACE);
  404. $paths['files'][] = $file;
  405. // Set standard file permissions for webserver-generated files.
  406. @chmod($file, 0664);
  407. }
  408. /**
  409. * Render images that match a given palette.
  410. */
  411. function _color_render_images($theme, &$info, &$paths, $palette) {
  412. // Prepare template image.
  413. $source = $paths['source'] .'/'. $info['base_image'];
  414. $source = imagecreatefrompng($source);
  415. $width = imagesx($source);
  416. $height = imagesy($source);
  417. // Prepare target buffer.
  418. $target = imagecreatetruecolor($width, $height);
  419. imagealphablending($target, true);
  420. // Fill regions of solid color.
  421. foreach ($info['fill'] as $color => $fill) {
  422. imagefilledrectangle($target, $fill[0], $fill[1], $fill[0] + $fill[2], $fill[1] + $fill[3], _color_gd($target, $palette[$color]));
  423. }
  424. // Render gradient.
  425. for ($y = 0; $y < $info['gradient'][3]; ++$y) {
  426. $color = _color_blend($target, $palette['top'], $palette['bottom'], $y / ($info['gradient'][3] - 1));
  427. imagefilledrectangle($target, $info['gradient'][0], $info['gradient'][1] + $y, $info['gradient'][0] + $info['gradient'][2], $info['gradient'][1] + $y + 1, $color);
  428. }
  429. // Blend over template.
  430. imagecopy($target, $source, 0, 0, 0, 0, $width, $height);
  431. // Clean up template image.
  432. imagedestroy($source);
  433. // Cut out slices.
  434. foreach ($info['slices'] as $file => $coord) {
  435. list($x, $y, $width, $height) = $coord;
  436. $base = basename($file);
  437. $image = $paths['target'] . $base;
  438. // Cut out slice.
  439. if ($file == 'screenshot.png') {
  440. $slice = imagecreatetruecolor(150, 90);
  441. imagecopyresampled($slice, $target, 0, 0, $x, $y, 150, 90, $width, $height);
  442. variable_set('color_'. $theme .'_screenshot', $image);
  443. }
  444. else {
  445. $slice = imagecreatetruecolor($width, $height);
  446. imagecopy($slice, $target, 0, 0, $x, $y, $width, $height);
  447. }
  448. // Save image.
  449. imagepng($slice, $image);
  450. imagedestroy($slice);
  451. $paths['files'][] = $image;
  452. // Set standard file permissions for webserver-generated files
  453. @chmod(realpath($image), 0664);
  454. // Build before/after map of image paths.
  455. $paths['map'][$file] = $base;
  456. }
  457. // Clean up target buffer.
  458. imagedestroy($target);
  459. }
  460. /**
  461. * Shift a given color, using a reference pair and a target blend color.
  462. *
  463. * Note: this function is significantly different from the JS version, as it
  464. * is written to match the blended images perfectly.
  465. *
  466. * Constraint: if (ref2 == target + (ref1 - target) * delta) for some fraction delta
  467. * then (return == target + (given - target) * delta)
  468. *
  469. * Loose constraint: Preserve relative positions in saturation and luminance
  470. * space.
  471. */
  472. function _color_shift($given, $ref1, $ref2, $target) {
  473. // We assume that ref2 is a blend of ref1 and target and find
  474. // delta based on the length of the difference vectors:
  475. // delta = 1 - |ref2 - ref1| / |white - ref1|
  476. $target = _color_unpack($target, true);
  477. $ref1 = _color_unpack($ref1, true);
  478. $ref2 = _color_unpack($ref2, true);
  479. $numerator = 0;
  480. $denominator = 0;
  481. for ($i = 0; $i < 3; ++$i) {
  482. $numerator += ($ref2[$i] - $ref1[$i]) * ($ref2[$i] - $ref1[$i]);
  483. $denominator += ($target[$i] - $ref1[$i]) * ($target[$i] - $ref1[$i]);
  484. }
  485. $delta = ($denominator > 0) ? (1 - sqrt($numerator / $denominator)) : 0;
  486. // Calculate the color that ref2 would be if the assumption was true.
  487. for ($i = 0; $i < 3; ++$i) {
  488. $ref3[$i] = $target[$i] + ($ref1[$i] - $target[$i]) * $delta;
  489. }
  490. // If the assumption is not true, there is a difference between ref2 and ref3.
  491. // We measure this in HSL space. Notation: x' = hsl(x).
  492. $ref2 = _color_rgb2hsl($ref2);
  493. $ref3 = _color_rgb2hsl($ref3);
  494. for ($i = 0; $i < 3; ++$i) {
  495. $shift[$i] = $ref2[$i] - $ref3[$i];
  496. }
  497. // Take the given color, and blend it towards the target.
  498. $given = _color_unpack($given, true);
  499. for ($i = 0; $i < 3; ++$i) {
  500. $result[$i] = $target[$i] + ($given[$i] - $target[$i]) * $delta;
  501. }
  502. // Finally, we apply the extra shift in HSL space.
  503. // Note: if ref2 is a pure blend of ref1 and target, then |shift| = 0.
  504. $result = _color_rgb2hsl($result);
  505. for ($i = 0; $i < 3; ++$i) {
  506. $result[$i] = min(1, max(0, $result[$i] + $shift[$i]));
  507. }
  508. $result = _color_hsl2rgb($result);
  509. // Return hex color.
  510. return _color_pack($result, true);
  511. }
  512. /**
  513. * Convert a hex triplet into a GD color.
  514. */
  515. function _color_gd($img, $hex) {
  516. $c = array_merge(array($img), _color_unpack($hex));
  517. return call_user_func_array('imagecolorallocate', $c);
  518. }
  519. /**
  520. * Blend two hex colors and return the GD color.
  521. */
  522. function _color_blend($img, $hex1, $hex2, $alpha) {
  523. $in1 = _color_unpack($hex1);
  524. $in2 = _color_unpack($hex2);
  525. $out = array($img);
  526. for ($i = 0; $i < 3; ++$i) {
  527. $out[] = $in1[$i] + ($in2[$i] - $in1[$i]) * $alpha;
  528. }
  529. return call_user_func_array('imagecolorallocate', $out);
  530. }
  531. /**
  532. * Convert a hex color into an RGB triplet.
  533. */
  534. function _color_unpack($hex, $normalize = false) {
  535. if (strlen($hex) == 4) {
  536. $hex = $hex[1] . $hex[1] . $hex[2] . $hex[2] . $hex[3] . $hex[3];
  537. }
  538. $c = hexdec($hex);
  539. for ($i = 16; $i >= 0; $i -= 8) {
  540. $out[] = (($c >> $i) & 0xFF) / ($normalize ? 255 : 1);
  541. }
  542. return $out;
  543. }
  544. /**
  545. * Convert an RGB triplet to a hex color.
  546. */
  547. function _color_pack($rgb, $normalize = false) {
  548. $out = 0;
  549. foreach ($rgb as $k => $v) {
  550. $out |= (($v * ($normalize ? 255 : 1)) << (16 - $k * 8));
  551. }
  552. return '#'. str_pad(dechex($out), 6, 0, STR_PAD_LEFT);
  553. }
  554. /**
  555. * Convert a HSL triplet into RGB
  556. */
  557. function _color_hsl2rgb($hsl) {
  558. $h = $hsl[0];
  559. $s = $hsl[1];
  560. $l = $hsl[2];
  561. $m2 = ($l <= 0.5) ? $l * ($s + 1) : $l + $s - $l*$s;
  562. $m1 = $l * 2 - $m2;
  563. return array(
  564. _color_hue2rgb($m1, $m2, $h + 0.33333),
  565. _color_hue2rgb($m1, $m2, $h),
  566. _color_hue2rgb($m1, $m2, $h - 0.33333),
  567. );
  568. }
  569. /**
  570. * Helper function for _color_hsl2rgb().
  571. */
  572. function _color_hue2rgb($m1, $m2, $h) {
  573. $h = ($h < 0) ? $h + 1 : (($h > 1) ? $h - 1 : $h);
  574. if ($h * 6 < 1) return $m1 + ($m2 - $m1) * $h * 6;
  575. if ($h * 2 < 1) return $m2;
  576. if ($h * 3 < 2) return $m1 + ($m2 - $m1) * (0.66666 - $h) * 6;
  577. return $m1;
  578. }
  579. /**
  580. * Convert an RGB triplet to HSL.
  581. */
  582. function _color_rgb2hsl($rgb) {
  583. $r = $rgb[0];
  584. $g = $rgb[1];
  585. $b = $rgb[2];
  586. $min = min($r, min($g, $b));
  587. $max = max($r, max($g, $b));
  588. $delta = $max - $min;
  589. $l = ($min + $max) / 2;
  590. $s = 0;
  591. if ($l > 0 && $l < 1) {
  592. $s = $delta / ($l < 0.5 ? (2 * $l) : (2 - 2 * $l));
  593. }
  594. $h = 0;
  595. if ($delta > 0) {
  596. if ($max == $r && $max != $g) $h += ($g - $b) / $delta;
  597. if ($max == $g && $max != $b) $h += (2 + ($b - $r) / $delta);
  598. if ($max == $b && $max != $r) $h += (4 + ($r - $g) / $delta);
  599. $h /= 6;
  600. }
  601. return array($h, $s, $l);
  602. }