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

7
use Drupal\Core\Asset\CssOptimizer;
8
use Drupal\Component\Utility\String;
9
use Symfony\Component\HttpFoundation\Request;
10

11
/**
12
 * Implements hook_help().
13
 */
14 15 16
function color_help($route_name, Request $request) {
  switch ($route_name) {
    case 'help.page.color':
17
      $output = '<h3>' . t('About') . '</h3>';
18
      $output .= '<p>' . t('The Color module allows users with the <em>Administer site configuration</em> permission to change the color scheme (color of links, backgrounds, text, and other theme elements) of themes that are compatible with it. For more information, see <a href="!color_do">the online documentation for the Color module</a>.', array('!color_do' => 'https://drupal.org/documentation/modules/color')) . '</p>';
19 20
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
21
      $output .= '<dt>' . t('Changing colors') . '</dt>';
22 23
      $output .= '<dd><p>' . t('To change the color settings, select the <em>Settings</em> link for your theme on the <a href="!appearance">Appearance</a> page. If the color picker does not appear than the theme is not compatible with the Color module.', array('!appearance' => \Drupal::url('system.themes_page'))) . '</p>';
      $output .= '<p>' . 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.') . '</p></dd>';
24
      $output .= '</dl>';
25 26 27 28
      return $output;
  }
}

29
/**
30
 * Implements hook_theme().
31 32 33 34
 */
function color_theme() {
  return array(
    'color_scheme_form' => array(
35
      'render element' => 'form',
36
      'template' => 'color-scheme-form',
37 38 39
    ),
  );
}
40

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

60
/**
61
 * Implements hook_css_alter().
62
 *
63
 * Replaces style sheets with color-altered style sheets.
64
 */
65
function color_css_alter(&$css) {
66
  global $theme_key;
67
  $themes = list_themes();
68 69

  // Override stylesheets.
70
  $color_paths = \Drupal::config('color.theme.' . $theme_key)->get('stylesheets');
71 72

  if (!empty($color_paths) && !empty($themes[$theme_key]->stylesheets['all'])) {
73

74
    foreach ($themes[$theme_key]->stylesheets['all'] as $old_path) {
75 76 77 78 79
      // 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.
80
        if (drupal_basename($old_path) == drupal_basename($color_path)) {
81 82
          // Replace the path to the new css file.
          // This keeps the order of the stylesheets intact.
83
          $css[drupal_basename($old_path)]['data'] = $color_path;
84 85 86
        }
      }
    }
87
  }
88 89 90
}

/**
91
 * Implements hook_preprocess_page().
92
 *
93
 * Replace the logo with the colored version if available.
94
 */
95
function color_preprocess_page(&$variables) {
96
  global $theme_key;
97

98
  // Override logo.
99
  $logo = \Drupal::config('color.theme.' . $theme_key)->get('logo');
100 101
  if ($logo && $variables['logo'] && preg_match('!' . $theme_key . '/logo.png$!', $variables['logo'])) {
    $variables['logo'] = file_create_url($logo);
102 103 104 105
  }
}

/**
106
 * Retrieves the Color module information for a particular theme.
107 108
 */
function color_get_info($theme) {
109 110 111 112 113 114
  static $theme_info = array();

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

115
  $path = drupal_get_path('theme', $theme);
116
  $file = DRUPAL_ROOT . '/' . $path . '/color/color.inc';
117 118
  if ($path && file_exists($file)) {
    include $file;
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
    // Add in default values.
    $info += array(
      // CSS files (excluding @import) to rewrite with new color scheme.
      'css' => array(),
      // Files to copy.
      'copy' => array(),
      // Gradient definitions.
      'gradients' => array(),
      // Color areas to fill (x, y, width, height).
      'fill' => array(),
      // Coordinates of all the theme slices (x, y, width, height) with their
      // filename as used in the stylesheet.
      'slices' => array(),
      // Reference color used for blending.
      'blend_target' => '#ffffff',
    );
135
    $theme_info[$theme] = $info;
136 137 138 139 140
    return $info;
  }
}

/**
141
 * Retrieves the color palette for a particular theme.
142
 */
143
function color_get_palette($theme, $default = FALSE) {
144
  // Fetch and expand default palette.
145
  $info = color_get_info($theme);
146
  $palette = $info['schemes']['default']['colors'];
147

148 149 150 151
  if ($default) {
    return $palette;
  }

152
  // Load variable.
153
  // @todo Default color config should be moved to yaml in the theme.
154
  return \Drupal::config('color.theme.' . $theme)->get('palette') ?: $palette;
155 156 157
}

/**
158 159 160 161 162 163 164 165
 * 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
166
 */
167
function color_scheme_form($complete_form, &$form_state, $theme) {
168 169 170
  $base = drupal_get_path('module', 'color');
  $info = color_get_info($theme);

171 172 173 174 175 176 177 178 179
  $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'];
  }

180
  // See if we're using a predefined scheme.
181
  // Note: we use the original theme when the default scheme is chosen.
182
  $current_scheme = \Drupal::config('color.theme.' . $theme)->get('palette');
183 184 185 186 187 188 189 190 191 192 193 194 195 196
  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 = '';
    }
  }
197

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

228
  // Add palette fields.
229
  $palette = color_get_palette($theme);
230
  $names = $info['fields'];
231
  $form['palette']['#tree'] = TRUE;
232
  foreach ($palette as $name => $value) {
233 234 235
    if (isset($names[$name])) {
      $form['palette'][$name] = array(
        '#type' => 'textfield',
236
        '#title' => String::checkPlain($names[$name]),
237
        '#value_callback' => 'color_palette_color_value',
238 239
        '#default_value' => $value,
        '#size' => 8,
240
        '#attributes' => array('dir' => 'ltr'),
241 242
      );
    }
243
  }
244
  $form['theme'] = array('#type' => 'value', '#value' => $theme);
245 246 247 248 249 250
  $form['info'] = array('#type' => 'value', '#value' => $info);

  return $form;
}

/**
251
 * Prepares variables for color scheme form templates.
252
 *
253 254 255
 * Default template: color-scheme-form.html.twig.
 *
 * @param array $variables
256 257
 *   An associative array containing:
 *   - form: A render element representing the form.
258
 */
259
function template_preprocess_color_scheme_form(&$variables) {
260
  $form = &$variables['form'];
261

262 263
  $theme = $form['theme']['#value'];
  $info = $form['info']['#value'];
264
  $path = drupal_get_path('theme', $theme) . '/';
265

266 267 268 269
  if (isset($info['preview_css'])) {
    $preview_css_path = $path . $info['preview_css'];
    $form['scheme']['#attached']['css'][$preview_css_path] = array();
  }
270 271
  $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.
272
  $form['scheme']['#attached']['js'][$preview_js_path] = array('weight' => -1);
273

274 275
  // 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');
276
  $variables['html_preview'] = file_get_contents($preview_html_path);
277 278
}

279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
/**
 * Determines the value for a palette color field.
 *
 * @param array $element
 *   The form element whose value is being populated.
 * @param string|bool $input
 *   The incoming input to populate the form element. If this is FALSE,
 *   the element's default value should be returned.
 * @param array $form_state
 *   A keyed array containing the current state of the form.
 *
 * @return string
 *   The data that will appear in the $form_state['values'] collection for this
 *   element. Return nothing to use the default.
 */
function color_palette_color_value($element, $input = FALSE, $form_state = array()) {
  // If we suspect a possible cross-site request forgery attack, only accept
  // hexadecimal CSS color strings from user input, to avoid problems when this
  // value is used in the JavaScript preview.
  if ($input !== FALSE) {
    // Start with the provided value for this textfield, and validate that if
    // necessary, falling back on the default value.
    $value = form_type_textfield_value($element, $input, $form_state);
    if (!$value || !isset($form_state['complete form']['#token']) || color_valid_hexadecimal_string($value) || drupal_valid_token($form_state['values']['form_token'], $form_state['complete form']['#token'])) {
      return $value;
    }
    else {
      return $element['#default_value'];
    }
  }
}

/**
 * Determines if a hexadecimal CSS color string is valid.
 *
 * @param string $color
 *   The string to check.
 *
 * @return bool
 *   TRUE if the string is a valid hexadecimal CSS color string, or FALSE if it
 *   isn't.
 */
function color_valid_hexadecimal_string($color) {
  return preg_match('/^#([a-f0-9]{3}){1,2}$/iD', $color);
}

325
/**
326 327 328
 * Form validation handler for color_scheme_form().
 *
 * @see color_scheme_form_submit()
329 330 331 332
 */
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) {
333
    if (!color_valid_hexadecimal_string($color)) {
334
      form_set_error('palette][' . $key, $form_state, t('You must enter a valid hexadecimal color value for %name.', array('%name' => $form['color']['palette'][$key]['#title'])));
335 336 337 338
    }
  }
}

339
/**
340 341 342
 * Form submission handler for color_scheme_form().
 *
 * @see color_scheme_form_validate()
343
 */
344
function color_scheme_form_submit($form, &$form_state) {
345

346
  // Get theme coloring info.
347
  if (!isset($form_state['values']['info'])) {
348 349
    return;
  }
350 351
  $theme = $form_state['values']['theme'];
  $info = $form_state['values']['info'];
352

353
  $config = \Drupal::config('color.theme.' . $theme);
354

355
  // Resolve palette.
356 357
  $palette = $form_state['values']['palette'];
  if ($form_state['values']['scheme'] != '') {
358 359 360 361
    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];
      }
362
    }
363
    $palette += $info['schemes']['default']['colors'];
364 365
  }

366
  // Make sure enough memory is available.
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
  if (isset($info['base_image'])) {
    // Fetch source image dimensions.
    $source = drupal_get_path('theme', $theme) . '/' . $info['base_image'];
    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;
    // We intend to prevent color scheme changes if there isn't enough memory
    // 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);
    $memory_limit = ini_get('memory_limit');
    $size = parse_size($memory_limit);
    if (!drupal_check_memory_limit($usage + $required, $memory_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 - $size), '@url' => 'http://www.php.net/manual/ini.core.php#ini.sect.resource-limits')), 'error');
      return;
    }
386 387
  }

388
  // Delete old files.
389 390 391 392 393
  $files = $config->get('files');
  if (isset($files)) {
    foreach ($files as $file) {
      @drupal_unlink($file);
    }
394
  }
395
  if (isset($file) && $file = dirname($file)) {
396
    @drupal_rmdir($file);
397 398
  }

399
  // No change in color config, use the standard theme from color.inc.
400
  if (implode(',', color_get_palette($theme, TRUE)) == implode(',', $palette)) {
401
    $config->delete();
402 403 404
    return;
  }

405
  // Prepare target locations for generated files.
406
  $id = $theme . '-' . substr(hash('sha256', serialize($palette) . microtime()), 0, 8);
407
  $paths['color'] = 'public://color';
408
  $paths['target'] = $paths['color'] . '/' . $id;
409
  foreach ($paths as $path) {
410
    file_prepare_directory($path, FILE_CREATE_DIRECTORY);
411
  }
412
  $paths['target'] = $paths['target'] . '/';
413
  $paths['id'] = $id;
414
  $paths['source'] = drupal_get_path('theme', $theme) . '/';
415 416
  $paths['files'] = $paths['map'] = array();

417
  // Save palette and logo location.
418 419 420 421
  $config
    ->set('palette', $palette)
    ->set('logo', $paths['target'] . 'logo.png')
    ->save();
422

423
  // Copy over neutral images.
424
  foreach ($info['copy'] as $file) {
425
    $base = drupal_basename($file);
426
    $source = $paths['source'] . $file;
427
    $filepath = file_unmanaged_copy($source, $paths['target'] . $base);
428
    $paths['map'][$file] = $base;
429
    $paths['files'][] = $filepath;
430 431
  }

432
  // Render new images, if image has been provided.
433
  if (isset($info['base_image'])) {
434 435
    _color_render_images($theme, $info, $paths, $palette);
  }
436

437 438 439
  // Rewrite theme stylesheets.
  $css = array();
  foreach ($info['css'] as $stylesheet) {
440
    // Build a temporary array with CSS files.
441 442 443 444 445 446
    $files = array();
    if (file_exists($paths['source'] . $stylesheet)) {
      $files[] = $stylesheet;
    }

    foreach ($files as $file) {
447
      $css_optimizer = new CssOptimizer();
448 449
      // Aggregate @imports recursively for each configured top level CSS file
      // without optimization. Aggregation and optimization will be
450
      // handled by drupal_build_css_cache() only.
451
      $style = $css_optimizer->loadFile($paths['source'] . $file, FALSE);
452 453 454

      // Return the path to where this CSS file originated from, stripping
      // off the name of the file at the end of the path.
455
      $css_optimizer->rewriteFileURIBasePath = base_path() . dirname($paths['source'] . $file) . '/';
456 457

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

      // Rewrite stylesheet with new colors.
      $style = _color_rewrite_stylesheet($theme, $info, $paths, $palette, $style);
462
      $base_file = drupal_basename($file);
463 464
      $css[] = $paths['target'] . $base_file;
      _color_save_stylesheet($paths['target'] . $base_file, $style, $paths);
465
    }
466
  }
467

468
  // Maintain list of files.
469 470 471 472
  $config
    ->set('stylesheets', $css)
    ->set('files', $paths['files'])
    ->save();
473 474 475
}

/**
476
 * Rewrites the stylesheet to match the colors in the palette.
477
 */
478
function _color_rewrite_stylesheet($theme, &$info, &$paths, $palette, $style) {
479
  // Prepare color conversion table.
480 481 482 483
  $conversion = $palette;
  foreach ($conversion as $k => $v) {
    $conversion[$k] = drupal_strtolower($v);
  }
484
  $default = color_get_palette($theme, TRUE);
485 486

  // Split off the "Don't touch" section of the stylesheet.
487
  $split = "Color Module: Don't touch";
488
  if (strpos($style, $split) !== FALSE) {
489 490
    list($style, $fixed) = explode($split, $style);
  }
491 492 493

  // 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);
494
  $is_color = FALSE;
495 496 497
  $output = '';
  $base = 'base';

498
  // Iterate over all the parts.
499 500 501
  foreach ($style as $chunk) {
    if ($is_color) {
      $chunk = drupal_strtolower($chunk);
502
      // Check if this is one of the colors in the default palette.
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
      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.
519
      elseif (preg_match('/(?<!-)color[^{:]*:[^{#]*$/i', $chunk)) {
520 521 522 523 524 525 526 527 528 529
        $base = 'text';
      }
      // Reset back to base.
      else {
        $base = 'base';
      }
    }
    $output .= $chunk;
    $is_color = !$is_color;
  }
530 531 532 533
  // Append fixed colors segment.
  if (isset($fixed)) {
    $output .= $fixed;
  }
534

535
  // Replace paths to images.
536
  foreach ($paths['map'] as $before => $after) {
537 538
    $before = base_path() . $paths['source'] . $before;
    $before = preg_replace('`(^|/)(?!../)([^/]+)/../`', '$1', $before);
539 540 541
    $output = str_replace($before, $after, $output);
  }

542
  return $output;
543 544 545
}

/**
546
 * Saves the rewritten stylesheet to disk.
547
 */
548
function _color_save_stylesheet($file, $style, &$paths) {
549
  $filepath = file_unmanaged_save_data($style, $file, FILE_EXISTS_REPLACE);
550
  $paths['files'][] = $filepath;
551 552

  // Set standard file permissions for webserver-generated files.
553
  drupal_chmod($file);
554 555 556
}

/**
557
 * Renders images that match a given palette.
558 559
 */
function _color_render_images($theme, &$info, &$paths, $palette) {
Steven Wittens's avatar
Steven Wittens committed
560
  // Prepare template image.
561
  $source = $paths['source'] . '/' . $info['base_image'];
562 563 564
  $source = imagecreatefrompng($source);
  $width = imagesx($source);
  $height = imagesy($source);
Steven Wittens's avatar
Steven Wittens committed
565 566

  // Prepare target buffer.
567
  $target = imagecreatetruecolor($width, $height);
568
  imagealphablending($target, TRUE);
569 570 571 572 573 574

  // 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]));
  }

575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
  // 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);
      }
    }
592 593
  }

Steven Wittens's avatar
Steven Wittens committed
594
  // Blend over template.
595 596
  imagecopy($target, $source, 0, 0, 0, 0, $width, $height);

Steven Wittens's avatar
Steven Wittens committed
597
  // Clean up template image.
598 599
  imagedestroy($source);

Steven Wittens's avatar
Steven Wittens committed
600
  // Cut out slices.
601 602
  foreach ($info['slices'] as $file => $coord) {
    list($x, $y, $width, $height) = $coord;
603
    $base = drupal_basename($file);
604
    $image = drupal_realpath($paths['target'] . $base);
605

Steven Wittens's avatar
Steven Wittens committed
606
    // Cut out slice.
607 608 609
    if ($file == 'screenshot.png') {
      $slice = imagecreatetruecolor(150, 90);
      imagecopyresampled($slice, $target, 0, 0, $x, $y, 150, 90, $width, $height);
610
      \Drupal::config('color.theme.' . $theme)
611 612
        ->set('screenshot', $image)
        ->save();
613 614 615 616 617 618
    }
    else {
      $slice = imagecreatetruecolor($width, $height);
      imagecopy($slice, $target, 0, 0, $x, $y, $width, $height);
    }

Steven Wittens's avatar
Steven Wittens committed
619
    // Save image.
620 621 622 623
    imagepng($slice, $image);
    imagedestroy($slice);
    $paths['files'][] = $image;

624
    // Set standard file permissions for webserver-generated files
625
    drupal_chmod($image);
626

627 628 629 630
    // Build before/after map of image paths.
    $paths['map'][$file] = $base;
  }

Steven Wittens's avatar
Steven Wittens committed
631
  // Clean up target buffer.
632 633 634 635
  imagedestroy($target);
}

/**
636
 * Shifts a given color, using a reference pair and a target blend color.
637 638 639 640
 *
 * Note: this function is significantly different from the JS version, as it
 * is written to match the blended images perfectly.
 *
641 642
 * Constraint: if (ref2 == target + (ref1 - target) * delta) for some fraction
 * delta then (return == target + (given - target) * delta).
643 644
 *
 * Loose constraint: Preserve relative positions in saturation and luminance
645
 * space.
646 647 648
 */
function _color_shift($given, $ref1, $ref2, $target) {
  // We assume that ref2 is a blend of ref1 and target and find
649
  // delta based on the length of the difference vectors.
650 651

  // delta = 1 - |ref2 - ref1| / |white - ref1|
652 653 654
  $target = _color_unpack($target, TRUE);
  $ref1 = _color_unpack($ref1, TRUE);
  $ref2 = _color_unpack($ref2, TRUE);
655 656
  $numerator = 0;
  $denominator = 0;
657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676
  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.
677
  $given = _color_unpack($given, TRUE);
678 679 680 681 682 683 684 685 686 687 688 689 690
  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.
691
  return _color_pack($result, TRUE);
692 693 694
}

/**
695
 * Converts a hex triplet into a GD color.
696 697 698 699 700 701 702
 */
function _color_gd($img, $hex) {
  $c = array_merge(array($img), _color_unpack($hex));
  return call_user_func_array('imagecolorallocate', $c);
}

/**
703
 * Blends two hex colors and returns the GD color.
704 705 706 707 708 709 710 711
 */
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;
  }
712

713 714 715 716
  return call_user_func_array('imagecolorallocate', $out);
}

/**
717
 * Converts a hex color into an RGB triplet.
718
 */
719
function _color_unpack($hex, $normalize = FALSE) {
720 721 722 723 724 725 726
  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);
  }
727

728 729 730 731
  return $out;
}

/**
732
 * Converts an RGB triplet to a hex color.
733
 */
734
function _color_pack($rgb, $normalize = FALSE) {
735
  $out = 0;
736 737 738
  foreach ($rgb as $k => $v) {
    $out |= (($v * ($normalize ? 255 : 1)) << (16 - $k * 8));
  }
739

740
  return '#' . str_pad(dechex($out), 6, 0, STR_PAD_LEFT);
741 742 743
}

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

753 754 755 756 757
  return array(
    _color_hue2rgb($m1, $m2, $h + 0.33333),
    _color_hue2rgb($m1, $m2, $h),
    _color_hue2rgb($m1, $m2, $h - 0.33333),
  );
758 759 760 761 762 763 764 765 766 767
}

/**
 * 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;
768

769 770 771 772
  return $m1;
}

/**
773
 * Converts an RGB triplet to HSL.
774 775 776 777 778 779 780 781 782 783
 */
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;
784

785
  if ($l > 0 && $l < 1) {
Steven Wittens's avatar
Steven Wittens committed
786
    $s = $delta / ($l < 0.5 ? (2 * $l) : (2 - 2 * $l));
787
  }
788

789 790
  $h = 0;
  if ($delta > 0) {
Steven Wittens's avatar
Steven Wittens committed
791 792 793 794
    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;
795
  }
796

797
  return array($h, $s, $l);
798
}