color.module 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816
  1. <?php
  2. /**
  3. * @file
  4. * Allows users to change the color scheme of themes.
  5. */
  6. /**
  7. * Implements hook_help().
  8. */
  9. function color_help($path, $arg) {
  10. switch ($path) {
  11. case 'admin/help#color':
  12. $output = '<h3>' . t('About') . '</h3>';
  13. $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/documentation/modules/color')) . '</p>';
  14. $output .= '<h3>' . t('Uses') . '</h3>';
  15. $output .= '<dl>';
  16. $output .= '<dt>' . t('Changing colors') . '</dt>';
  17. $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>';
  18. $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>';
  19. $output .= '</dl>';
  20. return $output;
  21. }
  22. }
  23. /**
  24. * Implements hook_theme().
  25. */
  26. function color_theme() {
  27. return array(
  28. 'color_scheme_form' => array(
  29. 'render element' => 'form',
  30. ),
  31. );
  32. }
  33. /**
  34. * Implements hook_form_FORM_ID_alter().
  35. */
  36. function color_form_system_theme_settings_alter(&$form, &$form_state) {
  37. if (isset($form_state['build_info']['args'][0]) && ($theme = $form_state['build_info']['args'][0]) && color_get_info($theme) && function_exists('gd_info')) {
  38. $form['color'] = array(
  39. '#type' => 'fieldset',
  40. '#title' => t('Color scheme'),
  41. '#weight' => -1,
  42. '#attributes' => array('id' => 'color_scheme_form'),
  43. '#theme' => 'color_scheme_form',
  44. );
  45. $form['color'] += color_scheme_form($form, $form_state, $theme);
  46. $form['#validate'][] = 'color_scheme_form_validate';
  47. $form['#submit'][] = 'color_scheme_form_submit';
  48. }
  49. }
  50. /**
  51. * Implements hook_form_FORM_ID_alter().
  52. */
  53. function color_form_system_themes_alter(&$form, &$form_state) {
  54. _color_theme_select_form_alter($form, $form_state);
  55. }
  56. /**
  57. * Helper for hook_form_FORM_ID_alter() implementations.
  58. */
  59. function _color_theme_select_form_alter(&$form, &$form_state) {
  60. // Use the generated screenshot in the theme list.
  61. $themes = list_themes();
  62. foreach (element_children($form) as $theme) {
  63. if ($screenshot = variable_get('color_' . $theme . '_screenshot')) {
  64. if (isset($form[$theme]['screenshot'])) {
  65. $form[$theme]['screenshot']['#markup'] = theme('image', array('path' => $screenshot, 'title' => '', 'attributes' => array('class' => array('screenshot'))));
  66. }
  67. }
  68. }
  69. }
  70. /**
  71. * Replaces style sheets with color-altered style sheets.
  72. *
  73. * A theme that supports the color module should call this function from its
  74. * THEME_process_html() function, so that the correct style sheets are
  75. * included when html.tpl.php is rendered.
  76. *
  77. * @see theme()
  78. */
  79. function _color_html_alter(&$vars) {
  80. global $theme_key;
  81. $themes = list_themes();
  82. // Override stylesheets.
  83. $color_paths = variable_get('color_' . $theme_key . '_stylesheets', array());
  84. if (!empty($color_paths)) {
  85. foreach ($themes[$theme_key]->stylesheets['all'] as $base_filename => $old_path) {
  86. // Loop over the path array with recolored CSS files to find matching
  87. // paths which could replace the non-recolored paths.
  88. foreach ($color_paths as $color_path) {
  89. // Color module currently requires unique file names to be used,
  90. // which allows us to compare different file paths.
  91. if (drupal_basename($old_path) == drupal_basename($color_path)) {
  92. // Replace the path to the new css file.
  93. // This keeps the order of the stylesheets intact.
  94. $vars['css'][$old_path]['data'] = $color_path;
  95. }
  96. }
  97. }
  98. $vars['styles'] = drupal_get_css($vars['css']);
  99. }
  100. }
  101. /**
  102. * Replaces the logo with a color-altered logo.
  103. *
  104. * A theme that supports the color module should call this function from its
  105. * THEME_process_page() function, so that the correct logo is included when
  106. * page.tpl.php is rendered.
  107. *
  108. * @see theme()
  109. */
  110. function _color_page_alter(&$vars) {
  111. global $theme_key;
  112. // Override logo.
  113. $logo = variable_get('color_' . $theme_key . '_logo');
  114. if ($logo && $vars['logo'] && preg_match('!' . $theme_key . '/logo.png$!', $vars['logo'])) {
  115. $vars['logo'] = file_create_url($logo);
  116. }
  117. }
  118. /**
  119. * Retrieves the Color module information for a particular theme.
  120. */
  121. function color_get_info($theme) {
  122. static $theme_info = array();
  123. if (isset($theme_info[$theme])) {
  124. return $theme_info[$theme];
  125. }
  126. $path = drupal_get_path('theme', $theme);
  127. $file = DRUPAL_ROOT . '/' . $path . '/color/color.inc';
  128. if ($path && file_exists($file)) {
  129. include $file;
  130. $theme_info[$theme] = $info;
  131. return $info;
  132. }
  133. }
  134. /**
  135. * Retrieves the color palette for a particular theme.
  136. */
  137. function color_get_palette($theme, $default = FALSE) {
  138. // Fetch and expand default palette.
  139. $info = color_get_info($theme);
  140. $palette = $info['schemes']['default']['colors'];
  141. // Load variable.
  142. return $default ? $palette : variable_get('color_' . $theme . '_palette', $palette);
  143. }
  144. /**
  145. * Form constructor for the color configuration form for a particular theme.
  146. *
  147. * @param $theme
  148. * The machine name of the theme whose color settings are being configured.
  149. *
  150. * @see color_scheme_form_validate()
  151. * @see color_scheme_form_submit()
  152. * @ingroup forms
  153. */
  154. function color_scheme_form($complete_form, &$form_state, $theme) {
  155. $base = drupal_get_path('module', 'color');
  156. $info = color_get_info($theme);
  157. $info['schemes'][''] = array('title' => t('Custom'), 'colors' => array());
  158. $color_sets = array();
  159. $schemes = array();
  160. foreach ($info['schemes'] as $key => $scheme) {
  161. $color_sets[$key] = $scheme['title'];
  162. $schemes[$key] = $scheme['colors'];
  163. $schemes[$key] += $info['schemes']['default']['colors'];
  164. }
  165. // See if we're using a predefined scheme.
  166. // Note: we use the original theme when the default scheme is chosen.
  167. $current_scheme = variable_get('color_' . $theme . '_palette', array());
  168. foreach ($schemes as $key => $scheme) {
  169. if ($current_scheme == $scheme) {
  170. $scheme_name = $key;
  171. break;
  172. }
  173. }
  174. if (empty($scheme_name)) {
  175. if (empty($current_scheme)) {
  176. $scheme_name = 'default';
  177. }
  178. else {
  179. $scheme_name = '';
  180. }
  181. }
  182. // Add scheme selector.
  183. $form['scheme'] = array(
  184. '#type' => 'select',
  185. '#title' => t('Color set'),
  186. '#options' => $color_sets,
  187. '#default_value' => $scheme_name,
  188. '#attached' => array(
  189. // Add Farbtastic color picker.
  190. 'library' => array(
  191. array('system', 'farbtastic'),
  192. ),
  193. // Add custom CSS.
  194. 'css' => array(
  195. $base . '/color.css' => array(),
  196. ),
  197. // Add custom JavaScript.
  198. 'js' => array(
  199. $base . '/color.js',
  200. array(
  201. 'data' => array(
  202. 'color' => array(
  203. 'reference' => color_get_palette($theme, TRUE),
  204. 'schemes' => $schemes,
  205. ),
  206. 'gradients' => $info['gradients'],
  207. ),
  208. 'type' => 'setting',
  209. ),
  210. ),
  211. ),
  212. );
  213. // Add palette fields.
  214. $palette = color_get_palette($theme);
  215. $names = $info['fields'];
  216. $form['palette']['#tree'] = TRUE;
  217. foreach ($palette as $name => $value) {
  218. if (isset($names[$name])) {
  219. $form['palette'][$name] = array(
  220. '#type' => 'textfield',
  221. '#title' => check_plain($names[$name]),
  222. '#value_callback' => 'color_palette_color_value',
  223. '#default_value' => $value,
  224. '#size' => 8,
  225. );
  226. }
  227. }
  228. $form['theme'] = array('#type' => 'value', '#value' => $theme);
  229. $form['info'] = array('#type' => 'value', '#value' => $info);
  230. return $form;
  231. }
  232. /**
  233. * Returns HTML for a theme's color form.
  234. *
  235. * @param $variables
  236. * An associative array containing:
  237. * - form: A render element representing the form.
  238. *
  239. * @ingroup themeable
  240. */
  241. function theme_color_scheme_form($variables) {
  242. $form = $variables['form'];
  243. $theme = $form['theme']['#value'];
  244. $info = $form['info']['#value'];
  245. $path = drupal_get_path('theme', $theme) . '/';
  246. drupal_add_css($path . $info['preview_css']);
  247. $preview_js_path = isset($info['preview_js']) ? $path . $info['preview_js'] : drupal_get_path('module', 'color') . '/' . 'preview.js';
  248. // Add the JS at a weight below color.js.
  249. drupal_add_js($preview_js_path, array('weight' => -1));
  250. $output = '';
  251. $output .= '<div class="color-form clearfix">';
  252. // Color schemes
  253. $output .= drupal_render($form['scheme']);
  254. // Palette
  255. $output .= '<div id="palette" class="clearfix">';
  256. foreach (element_children($form['palette']) as $name) {
  257. $output .= drupal_render($form['palette'][$name]);
  258. }
  259. $output .= '</div>';
  260. // Preview
  261. $output .= drupal_render_children($form);
  262. $output .= '<h2>' . t('Preview') . '</h2>';
  263. // Attempt to load preview HTML if the theme provides it.
  264. $preview_html_path = DRUPAL_ROOT . '/' . (isset($info['preview_html']) ? drupal_get_path('theme', $theme) . '/' . $info['preview_html'] : drupal_get_path('module', 'color') . '/preview.html');
  265. $output .= file_get_contents($preview_html_path);
  266. // Close the wrapper div.
  267. $output .= '</div>';
  268. return $output;
  269. }
  270. /**
  271. * Determines the value for a palette color field.
  272. *
  273. * @param $element
  274. * The form element whose value is being populated.
  275. * @param $input
  276. * The incoming input to populate the form element. If this is FALSE,
  277. * the element's default value should be returned.
  278. * @param $form_state
  279. * A keyed array containing the current state of the form.
  280. *
  281. * @return
  282. * The data that will appear in the $form_state['values'] collection for this
  283. * element. Return nothing to use the default.
  284. */
  285. function color_palette_color_value($element, $input = FALSE, $form_state = array()) {
  286. // If we suspect a possible cross-site request forgery attack, only accept
  287. // hexadecimal CSS color strings from user input, to avoid problems when this
  288. // value is used in the JavaScript preview.
  289. if ($input !== FALSE) {
  290. // Start with the provided value for this textfield, and validate that if
  291. // necessary, falling back on the default value.
  292. $value = form_type_textfield_value($element, $input, $form_state);
  293. 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'])) {
  294. return $value;
  295. }
  296. else {
  297. return $element['#default_value'];
  298. }
  299. }
  300. }
  301. /**
  302. * Determines if a hexadecimal CSS color string is valid.
  303. *
  304. * @param $color
  305. * The string to check.
  306. *
  307. * @return
  308. * TRUE if the string is a valid hexadecimal CSS color string, or FALSE if it
  309. * isn't.
  310. */
  311. function color_valid_hexadecimal_string($color) {
  312. return preg_match('/^#([a-f0-9]{3}){1,2}$/iD', $color);
  313. }
  314. /**
  315. * Form validation handler for color_scheme_form().
  316. *
  317. * @see color_scheme_form_submit()
  318. */
  319. function color_scheme_form_validate($form, &$form_state) {
  320. // Only accept hexadecimal CSS color strings to avoid XSS upon use.
  321. foreach ($form_state['values']['palette'] as $key => $color) {
  322. if (!color_valid_hexadecimal_string($color)) {
  323. form_set_error('palette][' . $key, t('%name must be a valid hexadecimal CSS color value.', array('%name' => $form['color']['palette'][$key]['#title'])));
  324. }
  325. }
  326. }
  327. /**
  328. * Form submission handler for color_scheme_form().
  329. *
  330. * @see color_scheme_form_validate()
  331. */
  332. function color_scheme_form_submit($form, &$form_state) {
  333. // Get theme coloring info.
  334. if (!isset($form_state['values']['info'])) {
  335. return;
  336. }
  337. $theme = $form_state['values']['theme'];
  338. $info = $form_state['values']['info'];
  339. // Resolve palette.
  340. $palette = $form_state['values']['palette'];
  341. if ($form_state['values']['scheme'] != '') {
  342. foreach ($palette as $key => $color) {
  343. if (isset($info['schemes'][$form_state['values']['scheme']]['colors'][$key])) {
  344. $palette[$key] = $info['schemes'][$form_state['values']['scheme']]['colors'][$key];
  345. }
  346. }
  347. $palette += $info['schemes']['default']['colors'];
  348. }
  349. // Make sure enough memory is available, if PHP's memory limit is compiled in.
  350. if (function_exists('memory_get_usage')) {
  351. // Fetch source image dimensions.
  352. $source = drupal_get_path('theme', $theme) . '/' . $info['base_image'];
  353. list($width, $height) = getimagesize($source);
  354. // We need at least a copy of the source and a target buffer of the same
  355. // size (both at 32bpp).
  356. $required = $width * $height * 8;
  357. // We intend to prevent color scheme changes if there isn't enough memory
  358. // available. memory_get_usage(TRUE) returns a more accurate number than
  359. // memory_get_usage(), therefore we won't inadvertently reject a color
  360. // scheme change based on a faulty memory calculation.
  361. $usage = memory_get_usage(TRUE);
  362. $memory_limit = ini_get('memory_limit');
  363. $size = parse_size($memory_limit);
  364. if (!drupal_check_memory_limit($usage + $required, $memory_limit)) {
  365. 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');
  366. return;
  367. }
  368. }
  369. // Delete old files.
  370. foreach (variable_get('color_' . $theme . '_files', array()) as $file) {
  371. @drupal_unlink($file);
  372. }
  373. if (isset($file) && $file = dirname($file)) {
  374. @drupal_rmdir($file);
  375. }
  376. // Don't render the default colorscheme, use the standard theme instead.
  377. if (implode(',', color_get_palette($theme, TRUE)) == implode(',', $palette)) {
  378. variable_del('color_' . $theme . '_palette');
  379. variable_del('color_' . $theme . '_stylesheets');
  380. variable_del('color_' . $theme . '_logo');
  381. variable_del('color_' . $theme . '_files');
  382. variable_del('color_' . $theme . '_screenshot');
  383. return;
  384. }
  385. // Prepare target locations for generated files.
  386. $id = $theme . '-' . substr(hash('sha256', serialize($palette) . microtime()), 0, 8);
  387. $paths['color'] = 'public://color';
  388. $paths['target'] = $paths['color'] . '/' . $id;
  389. foreach ($paths as $path) {
  390. file_prepare_directory($path, FILE_CREATE_DIRECTORY);
  391. }
  392. $paths['target'] = $paths['target'] . '/';
  393. $paths['id'] = $id;
  394. $paths['source'] = drupal_get_path('theme', $theme) . '/';
  395. $paths['files'] = $paths['map'] = array();
  396. // Save palette and logo location.
  397. variable_set('color_' . $theme . '_palette', $palette);
  398. variable_set('color_' . $theme . '_logo', $paths['target'] . 'logo.png');
  399. // Copy over neutral images.
  400. foreach ($info['copy'] as $file) {
  401. $base = drupal_basename($file);
  402. $source = $paths['source'] . $file;
  403. $filepath = file_unmanaged_copy($source, $paths['target'] . $base);
  404. $paths['map'][$file] = $base;
  405. $paths['files'][] = $filepath;
  406. }
  407. // Render new images, if image has been provided.
  408. if ($info['base_image']) {
  409. _color_render_images($theme, $info, $paths, $palette);
  410. }
  411. // Rewrite theme stylesheets.
  412. $css = array();
  413. foreach ($info['css'] as $stylesheet) {
  414. // Build a temporary array with LTR and RTL files.
  415. $files = array();
  416. if (file_exists($paths['source'] . $stylesheet)) {
  417. $files[] = $stylesheet;
  418. $rtl_file = str_replace('.css', '-rtl.css', $stylesheet);
  419. if (file_exists($paths['source'] . $rtl_file)) {
  420. $files[] = $rtl_file;
  421. }
  422. }
  423. foreach ($files as $file) {
  424. // Aggregate @imports recursively for each configured top level CSS file
  425. // without optimization. Aggregation and optimization will be
  426. // handled by drupal_build_css_cache() only.
  427. $style = drupal_load_stylesheet($paths['source'] . $file, FALSE);
  428. // Return the path to where this CSS file originated from, stripping
  429. // off the name of the file at the end of the path.
  430. $base = base_path() . dirname($paths['source'] . $file) . '/';
  431. _drupal_build_css_path(NULL, $base);
  432. // Prefix all paths within this CSS file, ignoring absolute paths.
  433. $style = preg_replace_callback('/url\([\'"]?(?![a-z]+:|\/+)([^\'")]+)[\'"]?\)/i', '_drupal_build_css_path', $style);
  434. // Rewrite stylesheet with new colors.
  435. $style = _color_rewrite_stylesheet($theme, $info, $paths, $palette, $style);
  436. $base_file = drupal_basename($file);
  437. $css[] = $paths['target'] . $base_file;
  438. _color_save_stylesheet($paths['target'] . $base_file, $style, $paths);
  439. }
  440. }
  441. // Maintain list of files.
  442. variable_set('color_' . $theme . '_stylesheets', $css);
  443. variable_set('color_' . $theme . '_files', $paths['files']);
  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. $conversion = $palette;
  452. foreach ($conversion as $k => $v) {
  453. $conversion[$k] = drupal_strtolower($v);
  454. }
  455. $default = color_get_palette($theme, TRUE);
  456. // Split off the "Don't touch" section of the stylesheet.
  457. $split = "Color Module: Don't touch";
  458. if (strpos($style, $split) !== FALSE) {
  459. list($style, $fixed) = explode($split, $style);
  460. }
  461. // Find all colors in the stylesheet and the chunks in between.
  462. $style = preg_split('/(#[0-9a-f]{6}|#[0-9a-f]{3})/i', $style, -1, PREG_SPLIT_DELIM_CAPTURE);
  463. $is_color = FALSE;
  464. $output = '';
  465. $base = 'base';
  466. // Iterate over all the parts.
  467. foreach ($style as $chunk) {
  468. if ($is_color) {
  469. $chunk = drupal_strtolower($chunk);
  470. // Check if this is one of the colors in the default palette.
  471. if ($key = array_search($chunk, $default)) {
  472. $chunk = $conversion[$key];
  473. }
  474. // Not a pre-set color. Extrapolate from the base.
  475. else {
  476. $chunk = _color_shift($palette[$base], $default[$base], $chunk, $info['blend_target']);
  477. }
  478. }
  479. else {
  480. // Determine the most suitable base color for the next color.
  481. // 'a' declarations. Use link.
  482. if (preg_match('@[^a-z0-9_-](a)[^a-z0-9_-][^/{]*{[^{]+$@i', $chunk)) {
  483. $base = 'link';
  484. }
  485. // 'color:' styles. Use text.
  486. elseif (preg_match('/(?<!-)color[^{:]*:[^{#]*$/i', $chunk)) {
  487. $base = 'text';
  488. }
  489. // Reset back to base.
  490. else {
  491. $base = 'base';
  492. }
  493. }
  494. $output .= $chunk;
  495. $is_color = !$is_color;
  496. }
  497. // Append fixed colors segment.
  498. if (isset($fixed)) {
  499. $output .= $fixed;
  500. }
  501. // Replace paths to images.
  502. foreach ($paths['map'] as $before => $after) {
  503. $before = base_path() . $paths['source'] . $before;
  504. $before = preg_replace('`(^|/)(?!../)([^/]+)/../`', '$1', $before);
  505. $output = str_replace($before, $after, $output);
  506. }
  507. return $output;
  508. }
  509. /**
  510. * Saves the rewritten stylesheet to disk.
  511. */
  512. function _color_save_stylesheet($file, $style, &$paths) {
  513. $filepath = file_unmanaged_save_data($style, $file, FILE_EXISTS_REPLACE);
  514. $paths['files'][] = $filepath;
  515. // Set standard file permissions for webserver-generated files.
  516. drupal_chmod($file);
  517. }
  518. /**
  519. * Renders images that match a given palette.
  520. */
  521. function _color_render_images($theme, &$info, &$paths, $palette) {
  522. // Prepare template image.
  523. $source = $paths['source'] . '/' . $info['base_image'];
  524. $source = imagecreatefrompng($source);
  525. $width = imagesx($source);
  526. $height = imagesy($source);
  527. // Prepare target buffer.
  528. $target = imagecreatetruecolor($width, $height);
  529. imagealphablending($target, TRUE);
  530. // Fill regions of solid color.
  531. foreach ($info['fill'] as $color => $fill) {
  532. imagefilledrectangle($target, $fill[0], $fill[1], $fill[0] + $fill[2], $fill[1] + $fill[3], _color_gd($target, $palette[$color]));
  533. }
  534. // Render gradients.
  535. foreach ($info['gradients'] as $gradient) {
  536. // Get direction of the gradient.
  537. if (isset($gradient['direction']) && $gradient['direction'] == 'horizontal') {
  538. // Horizontal gradient.
  539. for ($x = 0; $x < $gradient['dimension'][2]; $x++) {
  540. $color = _color_blend($target, $palette[$gradient['colors'][0]], $palette[$gradient['colors'][1]], $x / ($gradient['dimension'][2] - 1));
  541. imagefilledrectangle($target, ($gradient['dimension'][0] + $x), $gradient['dimension'][1], ($gradient['dimension'][0] + $x + 1), ($gradient['dimension'][1] + $gradient['dimension'][3]), $color);
  542. }
  543. }
  544. else {
  545. // Vertical gradient.
  546. for ($y = 0; $y < $gradient['dimension'][3]; $y++) {
  547. $color = _color_blend($target, $palette[$gradient['colors'][0]], $palette[$gradient['colors'][1]], $y / ($gradient['dimension'][3] - 1));
  548. imagefilledrectangle($target, $gradient['dimension'][0], $gradient['dimension'][1] + $y, $gradient['dimension'][0] + $gradient['dimension'][2], $gradient['dimension'][1] + $y + 1, $color);
  549. }
  550. }
  551. }
  552. // Blend over template.
  553. imagecopy($target, $source, 0, 0, 0, 0, $width, $height);
  554. // Clean up template image.
  555. imagedestroy($source);
  556. // Cut out slices.
  557. foreach ($info['slices'] as $file => $coord) {
  558. list($x, $y, $width, $height) = $coord;
  559. $base = drupal_basename($file);
  560. $image = drupal_realpath($paths['target'] . $base);
  561. // Cut out slice.
  562. if ($file == 'screenshot.png') {
  563. $slice = imagecreatetruecolor(150, 90);
  564. imagecopyresampled($slice, $target, 0, 0, $x, $y, 150, 90, $width, $height);
  565. variable_set('color_' . $theme . '_screenshot', $image);
  566. }
  567. else {
  568. $slice = imagecreatetruecolor($width, $height);
  569. imagecopy($slice, $target, 0, 0, $x, $y, $width, $height);
  570. }
  571. // Save image.
  572. imagepng($slice, $image);
  573. imagedestroy($slice);
  574. $paths['files'][] = $image;
  575. // Set standard file permissions for webserver-generated files
  576. drupal_chmod($image);
  577. // Build before/after map of image paths.
  578. $paths['map'][$file] = $base;
  579. }
  580. // Clean up target buffer.
  581. imagedestroy($target);
  582. }
  583. /**
  584. * Shifts a given color, using a reference pair and a target blend color.
  585. *
  586. * Note: this function is significantly different from the JS version, as it
  587. * is written to match the blended images perfectly.
  588. *
  589. * Constraint: if (ref2 == target + (ref1 - target) * delta) for some fraction
  590. * delta then (return == target + (given - target) * delta).
  591. *
  592. * Loose constraint: Preserve relative positions in saturation and luminance
  593. * space.
  594. */
  595. function _color_shift($given, $ref1, $ref2, $target) {
  596. // We assume that ref2 is a blend of ref1 and target and find
  597. // delta based on the length of the difference vectors.
  598. // delta = 1 - |ref2 - ref1| / |white - ref1|
  599. $target = _color_unpack($target, TRUE);
  600. $ref1 = _color_unpack($ref1, TRUE);
  601. $ref2 = _color_unpack($ref2, TRUE);
  602. $numerator = 0;
  603. $denominator = 0;
  604. for ($i = 0; $i < 3; ++$i) {
  605. $numerator += ($ref2[$i] - $ref1[$i]) * ($ref2[$i] - $ref1[$i]);
  606. $denominator += ($target[$i] - $ref1[$i]) * ($target[$i] - $ref1[$i]);
  607. }
  608. $delta = ($denominator > 0) ? (1 - sqrt($numerator / $denominator)) : 0;
  609. // Calculate the color that ref2 would be if the assumption was true.
  610. for ($i = 0; $i < 3; ++$i) {
  611. $ref3[$i] = $target[$i] + ($ref1[$i] - $target[$i]) * $delta;
  612. }
  613. // If the assumption is not true, there is a difference between ref2 and ref3.
  614. // We measure this in HSL space. Notation: x' = hsl(x).
  615. $ref2 = _color_rgb2hsl($ref2);
  616. $ref3 = _color_rgb2hsl($ref3);
  617. for ($i = 0; $i < 3; ++$i) {
  618. $shift[$i] = $ref2[$i] - $ref3[$i];
  619. }
  620. // Take the given color, and blend it towards the target.
  621. $given = _color_unpack($given, TRUE);
  622. for ($i = 0; $i < 3; ++$i) {
  623. $result[$i] = $target[$i] + ($given[$i] - $target[$i]) * $delta;
  624. }
  625. // Finally, we apply the extra shift in HSL space.
  626. // Note: if ref2 is a pure blend of ref1 and target, then |shift| = 0.
  627. $result = _color_rgb2hsl($result);
  628. for ($i = 0; $i < 3; ++$i) {
  629. $result[$i] = min(1, max(0, $result[$i] + $shift[$i]));
  630. }
  631. $result = _color_hsl2rgb($result);
  632. // Return hex color.
  633. return _color_pack($result, TRUE);
  634. }
  635. /**
  636. * Converts a hex triplet into a GD color.
  637. */
  638. function _color_gd($img, $hex) {
  639. $c = array_merge(array($img), _color_unpack($hex));
  640. return call_user_func_array('imagecolorallocate', $c);
  641. }
  642. /**
  643. * Blends two hex colors and returns the GD color.
  644. */
  645. function _color_blend($img, $hex1, $hex2, $alpha) {
  646. $in1 = _color_unpack($hex1);
  647. $in2 = _color_unpack($hex2);
  648. $out = array($img);
  649. for ($i = 0; $i < 3; ++$i) {
  650. $out[] = $in1[$i] + ($in2[$i] - $in1[$i]) * $alpha;
  651. }
  652. return call_user_func_array('imagecolorallocate', $out);
  653. }
  654. /**
  655. * Converts a hex color into an RGB triplet.
  656. */
  657. function _color_unpack($hex, $normalize = FALSE) {
  658. $hex = substr($hex, 1);
  659. if (strlen($hex) == 3) {
  660. $hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
  661. }
  662. $c = hexdec($hex);
  663. for ($i = 16; $i >= 0; $i -= 8) {
  664. $out[] = (($c >> $i) & 0xFF) / ($normalize ? 255 : 1);
  665. }
  666. return $out;
  667. }
  668. /**
  669. * Converts an RGB triplet to a hex color.
  670. */
  671. function _color_pack($rgb, $normalize = FALSE) {
  672. $out = 0;
  673. foreach ($rgb as $k => $v) {
  674. $out |= (($v * ($normalize ? 255 : 1)) << (16 - $k * 8));
  675. }
  676. return '#' . str_pad(dechex($out), 6, 0, STR_PAD_LEFT);
  677. }
  678. /**
  679. * Converts an HSL triplet into RGB.
  680. */
  681. function _color_hsl2rgb($hsl) {
  682. $h = $hsl[0];
  683. $s = $hsl[1];
  684. $l = $hsl[2];
  685. $m2 = ($l <= 0.5) ? $l * ($s + 1) : $l + $s - $l*$s;
  686. $m1 = $l * 2 - $m2;
  687. return array(
  688. _color_hue2rgb($m1, $m2, $h + 0.33333),
  689. _color_hue2rgb($m1, $m2, $h),
  690. _color_hue2rgb($m1, $m2, $h - 0.33333),
  691. );
  692. }
  693. /**
  694. * Helper function for _color_hsl2rgb().
  695. */
  696. function _color_hue2rgb($m1, $m2, $h) {
  697. $h = ($h < 0) ? $h + 1 : (($h > 1) ? $h - 1 : $h);
  698. if ($h * 6 < 1) return $m1 + ($m2 - $m1) * $h * 6;
  699. if ($h * 2 < 1) return $m2;
  700. if ($h * 3 < 2) return $m1 + ($m2 - $m1) * (0.66666 - $h) * 6;
  701. return $m1;
  702. }
  703. /**
  704. * Converts an RGB triplet to HSL.
  705. */
  706. function _color_rgb2hsl($rgb) {
  707. $r = $rgb[0];
  708. $g = $rgb[1];
  709. $b = $rgb[2];
  710. $min = min($r, min($g, $b));
  711. $max = max($r, max($g, $b));
  712. $delta = $max - $min;
  713. $l = ($min + $max) / 2;
  714. $s = 0;
  715. if ($l > 0 && $l < 1) {
  716. $s = $delta / ($l < 0.5 ? (2 * $l) : (2 - 2 * $l));
  717. }
  718. $h = 0;
  719. if ($delta > 0) {
  720. if ($max == $r && $max != $g) $h += ($g - $b) / $delta;
  721. if ($max == $g && $max != $b) $h += (2 + ($b - $r) / $delta);
  722. if ($max == $b && $max != $r) $h += (4 + ($r - $g) / $delta);
  723. $h /= 6;
  724. }
  725. return array($h, $s, $l);
  726. }