color.module 25.2 KB
Newer Older
1
<?php
2 3 4 5
/**
 * @file
 * Allows users to change the color scheme of themes.
 */
6

7
/**
8
 * Implements hook_help().
9 10 11 12
 */
function color_help($path, $arg) {
  switch ($path) {
    case 'admin/help#color':
13 14 15 16
      $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>';
17
      $output .= '<dt>' . t('Changing colors') . '</dt>';
18
      $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>Settings</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>';
19 20
      $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>';
21 22 23 24
      return $output;
  }
}

25
/**
26
 * Implements hook_theme().
27 28 29 30
 */
function color_theme() {
  return array(
    'color_scheme_form' => array(
31
      'render element' => 'form',
32 33 34
    ),
  );
}
35

36
/**
37
 * Implements hook_form_FORM_ID_alter().
38
 */
39
function color_form_system_theme_settings_alter(&$form, &$form_state) {
40
  if (isset($form_state['build_info']['args'][0]) && ($theme = $form_state['build_info']['args'][0]) && color_get_info($theme) && function_exists('gd_info')) {
41 42 43 44 45 46 47
    $form['color'] = array(
      '#type' => 'fieldset',
      '#title' => t('Color scheme'),
      '#weight' => -1,
      '#attributes' => array('id' => 'color_scheme_form'),
      '#theme' => 'color_scheme_form',
    );
48
    $form['color'] += color_scheme_form($form, $form_state, $theme);
49
    $form['#validate'][] = 'color_scheme_form_validate';
50
    $form['#submit'][] = 'color_scheme_form_submit';
51
  }
52 53 54
}

/**
55
 * Implements hook_form_FORM_ID_alter().
56 57 58 59
 */
function color_form_system_themes_alter(&$form, &$form_state) {
  _color_theme_select_form_alter($form, $form_state);
}
60

61 62 63 64
/**
 * Helper for hook_form_FORM_ID_alter() implementations.
 */
function _color_theme_select_form_alter(&$form, &$form_state) {
65
  // Use the generated screenshot in the theme list.
66 67
  $themes = list_themes();
  foreach (element_children($form) as $theme) {
68
    if ($screenshot = variable_get('color_' . $theme . '_screenshot')) {
69
      if (isset($form[$theme]['screenshot'])) {
70
        $form[$theme]['screenshot']['#markup'] = theme('image', array('uri' => $screenshot, 'title' => '', 'attributes' => array('class' => array('screenshot'))));
71 72 73 74 75 76
      }
    }
  }
}

/**
77 78 79 80 81 82 83
 * Replaces style sheets with color-altered style sheets.
 *
 * A theme that supports the color module should call this function from its
 * THEME_process_html() function, so that the correct style sheets are
 * included when html.tpl.php is rendered.
 *
 * @see theme()
84
 */
85
function _color_html_alter(&$vars) {
86
  global $theme_key;
87
  $themes = list_themes();
88 89

  // Override stylesheets.
90
  $color_paths = variable_get('color_' . $theme_key . '_stylesheets', array());
91 92
  if (!empty($color_paths)) {

93
    foreach ($themes[$theme_key]->stylesheets['all'] as $base_filename => $old_path) {
94 95 96 97 98 99
      // Loop over the path array with recolored CSS files to find matching
      // paths which could replace the non-recolored paths.
      foreach ($color_paths as $color_path) {
        // Color module currently requires unique file names to be used,
        // which allows us to compare different file paths.
        if (basename($old_path) == basename($color_path)) {
100 101 102
          // Replace the path to the new css file.
          // This keeps the order of the stylesheets intact.
          $vars['css'][$old_path]['data'] = $color_path;
103 104 105
        }
      }
    }
106

107 108
    $vars['styles'] = drupal_get_css($vars['css']);
  }
109 110 111
}

/**
112 113 114 115 116 117 118
 * Replaces the logo with a color-altered logo.
 *
 * A theme that supports the color module should call this function from its
 * THEME_process_page() function, so that the correct logo is included when
 * page.tpl.php is rendered.
 *
 * @see theme()
119 120
 */
function _color_page_alter(&$vars) {
121
  global $theme_key;
122

123
  // Override logo.
124
  $logo = variable_get('color_' . $theme_key . '_logo');
125
  if ($logo && $vars['logo'] && preg_match('!' . $theme_key . '/logo.png$!', $vars['logo'])) {
126
    $vars['logo'] = file_create_url($logo);
127 128 129 130
  }
}

/**
131
 * Retrieves the Color module information for a particular theme.
132 133
 */
function color_get_info($theme) {
134 135 136 137 138 139
  static $theme_info = array();

  if (isset($theme_info[$theme])) {
    return $theme_info[$theme];
  }

140
  $path = drupal_get_path('theme', $theme);
141
  $file = DRUPAL_ROOT . '/' . $path . '/color/color.inc';
142 143
  if ($path && file_exists($file)) {
    include $file;
144
    $theme_info[$theme] = $info;
145 146 147 148 149
    return $info;
  }
}

/**
150
 * Retrieves the color palette for a particular theme.
151
 */
152
function color_get_palette($theme, $default = FALSE) {
153
  // Fetch and expand default palette.
154
  $info = color_get_info($theme);
155
  $palette = $info['schemes']['default']['colors'];
156

157
  // Load variable.
158
  return $default ? $palette : variable_get('color_' . $theme . '_palette', $palette);
159 160 161
}

/**
162 163 164 165 166 167 168 169
 * Form constructor for the color configuration form for a particular theme.
 *
 * @param $theme
 *   The machine name of the theme whose color settings are being configured.
 *
 * @see color_scheme_form_validate()
 * @see color_scheme_form_submit()
 * @ingroup forms
170
 */
171
function color_scheme_form($complete_form, &$form_state, $theme) {
172 173 174
  $base = drupal_get_path('module', 'color');
  $info = color_get_info($theme);

175 176 177 178 179 180 181 182 183
  $info['schemes'][''] = array('title' => t('Custom'), 'colors' => array());
  $color_sets = array();
  $schemes = array();
  foreach ($info['schemes'] as $key => $scheme) {
    $color_sets[$key] = $scheme['title'];
    $schemes[$key] = $scheme['colors'];
    $schemes[$key] += $info['schemes']['default']['colors'];
  }

184
  // See if we're using a predefined scheme.
185
  // Note: we use the original theme when the default scheme is chosen.
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
  $current_scheme = variable_get('color_' . $theme . '_palette', array());
  foreach ($schemes as $key => $scheme) {
    if ($current_scheme == $scheme) {
      $scheme_name = $key;
      break;
    }
  }
  if (empty($scheme_name)) {
    if (empty($current_scheme)) {
      $scheme_name = 'default';
    }
    else {
      $scheme_name = '';
    }
  }
201

202
  // Add scheme selector.
203 204 205
  $form['scheme'] = array(
    '#type' => 'select',
    '#title' => t('Color set'),
206 207
    '#options' => $color_sets,
    '#default_value' => $scheme_name,
208 209 210 211 212 213 214
    '#attached' => array(
      // Add Farbtastic color picker.
      'library' => array(
        array('system', 'farbtastic'),
      ),
      // Add custom CSS.
      'css' => array(
215
        $base . '/color.admin.css' => array(),
216 217 218 219 220 221
      ),
      // Add custom JavaScript.
      'js' => array(
        $base . '/color.js',
        array(
          'data' => array(
222 223 224 225 226
            'color' => array(
              'reference' => color_get_palette($theme, TRUE),
              'schemes' => $schemes,
            ),
            'gradients' => $info['gradients'],
227 228 229
          ),
          'type' => 'setting',
        ),
230 231
      ),
    ),
232 233
  );

234
  // Add palette fields.
235
  $palette = color_get_palette($theme);
236
  $names = $info['fields'];
237
  $form['palette']['#tree'] = TRUE;
238
  foreach ($palette as $name => $value) {
239 240 241
    if (isset($names[$name])) {
      $form['palette'][$name] = array(
        '#type' => 'textfield',
242
        '#title' => check_plain($names[$name]),
243 244 245 246
        '#default_value' => $value,
        '#size' => 8,
      );
    }
247
  }
248
  $form['theme'] = array('#type' => 'value', '#value' => $theme);
249 250 251 252 253 254
  $form['info'] = array('#type' => 'value', '#value' => $info);

  return $form;
}

/**
255 256 257 258 259
 * Returns HTML for a theme's color form.
 *
 * @param $variables
 *   An associative array containing:
 *   - form: A render element representing the form.
260
 *
261
 * @ingroup themeable
262
 */
263 264 265
function theme_color_scheme_form($variables) {
  $form = $variables['form'];

266 267
  $theme = $form['theme']['#value'];
  $info = $form['info']['#value'];
268
  $path = drupal_get_path('theme', $theme) . '/';
269
  drupal_add_css($path . $info['preview_css']);
270

271 272
  $preview_js_path = isset($info['preview_js']) ? $path . $info['preview_js'] : drupal_get_path('module', 'color') . '/' . 'preview.js';
  // Add the JS at a weight below color.js.
273
  drupal_add_js($preview_js_path, array('weight' => -1));
274

275
  $output  = '';
276
  $output .= '<div class="color-form clearfix">';
277
  // Color schemes
278 279
  $output .= drupal_render($form['scheme']);
  // Palette
280
  $output .= '<div id="palette" class="clearfix">';
281 282 283 284 285
  foreach (element_children($form['palette']) as $name) {
    $output .= drupal_render($form['palette'][$name]);
  }
  $output .= '</div>';
  // Preview
286
  $output .= drupal_render_children($form);
287
  $output .= '<h2>' . t('Preview') . '</h2>';
288 289 290
  // Attempt to load preview HTML if the theme provides it.
  $preview_html_path = DRUPAL_ROOT . '/' . (isset($info['preview_html']) ? drupal_get_path('theme', $theme) . '/' . $info['preview_html'] : drupal_get_path('module', 'color') . '/preview.html');
  $output .= file_get_contents($preview_html_path);
291
  // Close the wrapper div.
292
  $output .= '</div>';
293 294 295 296

  return $output;
}

297
/**
298 299 300
 * Form validation handler for color_scheme_form().
 *
 * @see color_scheme_form_submit()
301 302 303 304 305 306 307 308 309 310
 */
function color_scheme_form_validate($form, &$form_state) {
  // Only accept hexadecimal CSS color strings to avoid XSS upon use.
  foreach ($form_state['values']['palette'] as $key => $color) {
    if (!preg_match('/^#([a-f0-9]{3}){1,2}$/iD', $color)) {
      form_set_error('palette][' . $key, t('You must enter a valid hexadecimal color value for %name.', array('%name' => $form['color']['palette'][$key]['#title'])));
    }
  }
}

311
/**
312 313 314
 * Form submission handler for color_scheme_form().
 *
 * @see color_scheme_form_validate()
315
 */
316
function color_scheme_form_submit($form, &$form_state) {
317
  // Get theme coloring info.
318
  if (!isset($form_state['values']['info'])) {
319 320
    return;
  }
321 322
  $theme = $form_state['values']['theme'];
  $info = $form_state['values']['info'];
323

324
  // Resolve palette.
325 326
  $palette = $form_state['values']['palette'];
  if ($form_state['values']['scheme'] != '') {
327 328 329 330
    foreach ($palette as $key => $color) {
      if (isset($info['schemes'][$form_state['values']['scheme']]['colors'][$key])) {
        $palette[$key] = $info['schemes'][$form_state['values']['scheme']]['colors'][$key];
      }
331
    }
332
    $palette += $info['schemes']['default']['colors'];
333 334
  }

335 336 337
  // Make sure enough memory is available, if PHP's memory limit is compiled in.
  if (function_exists('memory_get_usage')) {
    // Fetch source image dimensions.
338
    $source = drupal_get_path('theme', $theme) . '/' . $info['base_image'];
339 340 341 342 343
    list($width, $height) = getimagesize($source);

    // We need at least a copy of the source and a target buffer of the same
    // size (both at 32bpp).
    $required = $width * $height * 8;
344
    // We intend to prevent color scheme changes if there isn't enough memory
345 346 347 348
    // available.  memory_get_usage(TRUE) returns a more accurate number than
    // memory_get_usage(), therefore we won't inadvertently reject a color
    // scheme change based on a faulty memory calculation.
    $usage = memory_get_usage(TRUE);
349 350
    $limit = parse_size(ini_get('memory_limit'));
    if ($usage + $required > $limit) {
351
      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');
352 353 354 355
      return;
    }
  }

356
  // Delete old files.
357
  foreach (variable_get('color_' . $theme . '_files', array()) as $file) {
358
    @drupal_unlink($file);
359
  }
360
  if (isset($file) && $file = dirname($file)) {
361
    @drupal_rmdir($file);
362 363 364
  }

  // Don't render the default colorscheme, use the standard theme instead.
365
  if (implode(',', color_get_palette($theme, TRUE)) == implode(',', $palette)) {
366 367 368 369 370
    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');
371 372 373
    return;
  }

374
  // Prepare target locations for generated files.
375
  $id = $theme . '-' . substr(hash('sha256', serialize($palette) . microtime()), 0, 8);
376
  $paths['color'] = 'public://color';
377
  $paths['target'] = $paths['color'] . '/' . $id;
378
  foreach ($paths as $path) {
379
    file_prepare_directory($path, FILE_CREATE_DIRECTORY);
380
  }
381
  $paths['target'] = $paths['target'] . '/';
382
  $paths['id'] = $id;
383
  $paths['source'] = drupal_get_path('theme', $theme) . '/';
384 385
  $paths['files'] = $paths['map'] = array();

386
  // Save palette and logo location.
387 388
  variable_set('color_' . $theme . '_palette', $palette);
  variable_set('color_' . $theme . '_logo', $paths['target'] . 'logo.png');
389

390
  // Copy over neutral images.
391 392
  foreach ($info['copy'] as $file) {
    $base = basename($file);
393
    $source = $paths['source'] . $file;
394
    $filepath = file_unmanaged_copy($source, $paths['target'] . $base);
395
    $paths['map'][$file] = $base;
396
    $paths['files'][] = $filepath;
397 398
  }

399
  // Render new images, if image has been provided.
400 401 402
  if ($info['base_image']) {
    _color_render_images($theme, $info, $paths, $palette);
  }
403

404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
  // Rewrite theme stylesheets.
  $css = array();
  foreach ($info['css'] as $stylesheet) {
    // Build a temporary array with LTR and RTL files.
    $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) {
419 420
      // Aggregate @imports recursively for each configured top level CSS file
      // without optimization. Aggregation and optimization will be
421 422 423 424 425
      // handled by drupal_build_css_cache() only.
      $style = drupal_load_stylesheet($paths['source'] . $file, FALSE);

      // Return the path to where this CSS file originated from, stripping
      // off the name of the file at the end of the path.
426
      $base = base_path() . dirname($paths['source'] . $file) . '/';
427 428 429 430 431 432 433 434 435 436
      _drupal_build_css_path(NULL, $base);

      // Prefix all paths within this CSS file, ignoring absolute paths.
      $style = preg_replace_callback('/url\([\'"]?(?![a-z]+:|\/+)([^\'")]+)[\'"]?\)/i', '_drupal_build_css_path', $style);

      // Rewrite stylesheet with new colors.
      $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);
437
    }
438
  }
439

440
  // Maintain list of files.
441 442
  variable_set('color_' . $theme . '_stylesheets', $css);
  variable_set('color_' . $theme . '_files', $paths['files']);
443 444 445
}

/**
446
 * Rewrites the stylesheet to match the colors in the palette.
447
 */
448
function _color_rewrite_stylesheet($theme, &$info, &$paths, $palette, $style) {
449
  $themes = list_themes();
450
  // Prepare color conversion table.
451 452 453 454
  $conversion = $palette;
  foreach ($conversion as $k => $v) {
    $conversion[$k] = drupal_strtolower($v);
  }
455
  $default = color_get_palette($theme, TRUE);
456 457

  // Split off the "Don't touch" section of the stylesheet.
458
  $split = "Color Module: Don't touch";
459
  if (strpos($style, $split) !== FALSE) {
460 461
    list($style, $fixed) = explode($split, $style);
  }
462 463 464

  // Find all colors in the stylesheet and the chunks in between.
  $style = preg_split('/(#[0-9a-f]{6}|#[0-9a-f]{3})/i', $style, -1, PREG_SPLIT_DELIM_CAPTURE);
465
  $is_color = FALSE;
466 467 468
  $output = '';
  $base = 'base';

469
  // Iterate over all the parts.
470 471 472
  foreach ($style as $chunk) {
    if ($is_color) {
      $chunk = drupal_strtolower($chunk);
473
      // Check if this is one of the colors in the default palette.
474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
      if ($key = array_search($chunk, $default)) {
        $chunk = $conversion[$key];
      }
      // Not a pre-set color. Extrapolate from the base.
      else {
        $chunk = _color_shift($palette[$base], $default[$base], $chunk, $info['blend_target']);
      }
    }
    else {
      // Determine the most suitable base color for the next color.

      // 'a' declarations. Use link.
      if (preg_match('@[^a-z0-9_-](a)[^a-z0-9_-][^/{]*{[^{]+$@i', $chunk)) {
        $base = 'link';
      }
      // 'color:' styles. Use text.
490
      elseif (preg_match('/(?<!-)color[^{:]*:[^{#]*$/i', $chunk)) {
491 492 493 494 495 496 497 498 499 500
        $base = 'text';
      }
      // Reset back to base.
      else {
        $base = 'base';
      }
    }
    $output .= $chunk;
    $is_color = !$is_color;
  }
501 502 503 504
  // Append fixed colors segment.
  if (isset($fixed)) {
    $output .= $fixed;
  }
505

506
  // Replace paths to images.
507
  foreach ($paths['map'] as $before => $after) {
508 509
    $before = base_path() . $paths['source'] . $before;
    $before = preg_replace('`(^|/)(?!../)([^/]+)/../`', '$1', $before);
510 511 512
    $output = str_replace($before, $after, $output);
  }

513
  return $output;
514 515 516
}

/**
517
 * Saves the rewritten stylesheet to disk.
518
 */
519
function _color_save_stylesheet($file, $style, &$paths) {
520
  $filepath = file_unmanaged_save_data($style, $file, FILE_EXISTS_REPLACE);
521
  $paths['files'][] = $filepath;
522 523

  // Set standard file permissions for webserver-generated files.
524
  drupal_chmod($file);
525 526 527
}

/**
528
 * Renders images that match a given palette.
529 530
 */
function _color_render_images($theme, &$info, &$paths, $palette) {
Steven Wittens's avatar
Steven Wittens committed
531
  // Prepare template image.
532
  $source = $paths['source'] . '/' . $info['base_image'];
533 534 535
  $source = imagecreatefrompng($source);
  $width = imagesx($source);
  $height = imagesy($source);
Steven Wittens's avatar
Steven Wittens committed
536 537

  // Prepare target buffer.
538
  $target = imagecreatetruecolor($width, $height);
539
  imagealphablending($target, TRUE);
540 541 542 543 544 545

  // Fill regions of solid color.
  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]));
  }

546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562
  // Render gradients.
  foreach ($info['gradients'] as $gradient) {
    // Get direction of the gradient.
    if (isset($gradient['direction']) && $gradient['direction'] == 'horizontal') {
      // Horizontal gradient.
      for ($x = 0; $x < $gradient['dimension'][2]; $x++) {
        $color = _color_blend($target, $palette[$gradient['colors'][0]], $palette[$gradient['colors'][1]], $x / ($gradient['dimension'][2] - 1));
        imagefilledrectangle($target, ($gradient['dimension'][0] + $x), $gradient['dimension'][1], ($gradient['dimension'][0] + $x + 1), ($gradient['dimension'][1] + $gradient['dimension'][3]), $color);
      }
    }
    else {
      // Vertical gradient.
      for ($y = 0; $y < $gradient['dimension'][3]; $y++) {
        $color = _color_blend($target, $palette[$gradient['colors'][0]], $palette[$gradient['colors'][1]], $y / ($gradient['dimension'][3] - 1));
        imagefilledrectangle($target, $gradient['dimension'][0], $gradient['dimension'][1] + $y, $gradient['dimension'][0] + $gradient['dimension'][2], $gradient['dimension'][1] + $y + 1, $color);
      }
    }
563 564
  }

Steven Wittens's avatar
Steven Wittens committed
565
  // Blend over template.
566 567
  imagecopy($target, $source, 0, 0, 0, 0, $width, $height);

Steven Wittens's avatar
Steven Wittens committed
568
  // Clean up template image.
569 570
  imagedestroy($source);

Steven Wittens's avatar
Steven Wittens committed
571
  // Cut out slices.
572 573 574
  foreach ($info['slices'] as $file => $coord) {
    list($x, $y, $width, $height) = $coord;
    $base = basename($file);
575
    $image = drupal_realpath($paths['target'] . $base);
576

Steven Wittens's avatar
Steven Wittens committed
577
    // Cut out slice.
578 579 580
    if ($file == 'screenshot.png') {
      $slice = imagecreatetruecolor(150, 90);
      imagecopyresampled($slice, $target, 0, 0, $x, $y, 150, 90, $width, $height);
581
      variable_set('color_' . $theme . '_screenshot', $image);
582 583 584 585 586 587
    }
    else {
      $slice = imagecreatetruecolor($width, $height);
      imagecopy($slice, $target, 0, 0, $x, $y, $width, $height);
    }

Steven Wittens's avatar
Steven Wittens committed
588
    // Save image.
589 590 591 592
    imagepng($slice, $image);
    imagedestroy($slice);
    $paths['files'][] = $image;

593
    // Set standard file permissions for webserver-generated files
594
    drupal_chmod($image);
595

596 597 598 599
    // Build before/after map of image paths.
    $paths['map'][$file] = $base;
  }

Steven Wittens's avatar
Steven Wittens committed
600
  // Clean up target buffer.
601 602 603 604
  imagedestroy($target);
}

/**
605
 * Shifts a given color, using a reference pair and a target blend color.
606 607 608 609
 *
 * Note: this function is significantly different from the JS version, as it
 * is written to match the blended images perfectly.
 *
610 611
 * Constraint: if (ref2 == target + (ref1 - target) * delta) for some fraction
 * delta then (return == target + (given - target) * delta).
612 613
 *
 * Loose constraint: Preserve relative positions in saturation and luminance
614
 * space.
615 616 617
 */
function _color_shift($given, $ref1, $ref2, $target) {
  // We assume that ref2 is a blend of ref1 and target and find
618
  // delta based on the length of the difference vectors.
619 620

  // delta = 1 - |ref2 - ref1| / |white - ref1|
621 622 623
  $target = _color_unpack($target, TRUE);
  $ref1 = _color_unpack($ref1, TRUE);
  $ref2 = _color_unpack($ref2, TRUE);
624 625
  $numerator = 0;
  $denominator = 0;
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645
  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;

  // Calculate the color that ref2 would be if the assumption was true.
  for ($i = 0; $i < 3; ++$i) {
    $ref3[$i] = $target[$i] + ($ref1[$i] - $target[$i]) * $delta;
  }

  // If the assumption is not true, there is a difference between ref2 and ref3.
  // We measure this in HSL space. Notation: x' = hsl(x).
  $ref2 = _color_rgb2hsl($ref2);
  $ref3 = _color_rgb2hsl($ref3);
  for ($i = 0; $i < 3; ++$i) {
    $shift[$i] = $ref2[$i] - $ref3[$i];
  }

  // Take the given color, and blend it towards the target.
646
  $given = _color_unpack($given, TRUE);
647 648 649 650 651 652 653 654 655 656 657 658 659
  for ($i = 0; $i < 3; ++$i) {
    $result[$i] = $target[$i] + ($given[$i] - $target[$i]) * $delta;
  }

  // Finally, we apply the extra shift in HSL space.
  // Note: if ref2 is a pure blend of ref1 and target, then |shift| = 0.
  $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 hex color.
660
  return _color_pack($result, TRUE);
661 662 663
}

/**
664
 * Converts a hex triplet into a GD color.
665 666 667 668 669 670 671
 */
function _color_gd($img, $hex) {
  $c = array_merge(array($img), _color_unpack($hex));
  return call_user_func_array('imagecolorallocate', $c);
}

/**
672
 * Blends two hex colors and returns the GD color.
673 674 675 676 677 678 679 680
 */
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;
  }
681

682 683 684 685
  return call_user_func_array('imagecolorallocate', $out);
}

/**
686
 * Converts a hex color into an RGB triplet.
687
 */
688
function _color_unpack($hex, $normalize = FALSE) {
689 690 691 692 693 694 695
  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);
  }
696

697 698 699 700
  return $out;
}

/**
701
 * Converts an RGB triplet to a hex color.
702
 */
703
function _color_pack($rgb, $normalize = FALSE) {
704
  $out = 0;
705 706 707
  foreach ($rgb as $k => $v) {
    $out |= (($v * ($normalize ? 255 : 1)) << (16 - $k * 8));
  }
708

709
  return '#' . str_pad(dechex($out), 6, 0, STR_PAD_LEFT);
710 711 712
}

/**
713
 * Converts an HSL triplet into RGB.
714 715 716 717 718 719 720
 */
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;
721

722 723 724 725 726
  return array(
    _color_hue2rgb($m1, $m2, $h + 0.33333),
    _color_hue2rgb($m1, $m2, $h),
    _color_hue2rgb($m1, $m2, $h - 0.33333),
  );
727 728 729 730 731 732 733 734 735 736
}

/**
 * Helper function for _color_hsl2rgb().
 */
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;
737

738 739 740 741
  return $m1;
}

/**
742
 * Converts an RGB triplet to HSL.
743 744 745 746 747 748 749 750 751 752
 */
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;
753

754
  if ($l > 0 && $l < 1) {
Steven Wittens's avatar
Steven Wittens committed
755
    $s = $delta / ($l < 0.5 ? (2 * $l) : (2 - 2 * $l));
756
  }
757

758 759
  $h = 0;
  if ($delta > 0) {
Steven Wittens's avatar
Steven Wittens committed
760 761 762 763
    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;
764
  }
765

766
  return array($h, $s, $l);
767
}