color.module 28 KB

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