fancyload-8.x-1.8/fancyload.module

fancyload.module
<?php

/**
 * @file
 * Hook implementations for the Fancyload Module.
 */

use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Template\Attribute;
use Drupal\fancyload\Hooks\ThemeRegistryAlter;

/**
 * Implements hook_theme_registry_alter().
 */
function fancyload_theme_registry_alter(&$theme_registry) {
  $alter = new ThemeRegistryAlter(\Drupal::moduleHandler(), \Drupal::configFactory());
  $alter->themeRegistryAlter($theme_registry);
}

/**
 * Implements hook_preprocess_image().
 */
function fancyload_preprocess_image(&$vars) {

  $config = \Drupal::config('fancyload.configuration');
  $anonymous_only = $config->get('anonymous');

  $is_visible = 1;
  if ($anonymous_only) {
    if (!\Drupal::currentUser()->isAnonymous()) {
      $is_visible = 0;
    }
  }

  // Disable on admin pages (prevent errors on node pages, views etc.).
  $is_admin = \Drupal::service('router.admin_context')->isAdminRoute();
  if ($is_admin) {
    $is_visible = 0;
  }

  if (!$is_visible) {
    return;
  }

  // Prevents search api error faults
  if (PHP_SAPI == 'cli') {
    return;
  }

  // Add new classes, set original image as data-src etc.
  $vars['old_attributes'] = new Attribute($vars['attributes']);
  $uri = $vars['uri'];
  unset($vars['attributes']['srcset']);
  $vars['attributes']['class'][] = 'fancyload';
  $vars['attributes']['data-src'] = file_create_url($uri);
  $width = $vars['attributes']['width'];
  $height = $vars['attributes']['height'];
  $vars['attributes']['data-src'] = file_create_url($uri);

  $path_to_files = file_create_url('public://');

  // see if image color is already collected.
  $name = pathinfo($uri);
  // strip whitespaces and dots.
  $filename = $name['filename'];
  $filename = preg_replace('/\s+/', '', $filename);
  $filename = str_replace(".", "", $filename);
  $filename = preg_replace('/[%()]/', '', $filename);

  $color_value = \Drupal::state()->get('fancyload_' . fancyload_remove_accents($filename));
  if (empty($color_value)) {
    // Get dominant color of image.
    $dominant_color = fancyload_get_dominant_color($uri);
    // Dave dominant color of image.
    \Drupal::state()->set('fancyload_' . fancyload_remove_accents($filename), $dominant_color);
    $color_value = \Drupal::state()->get('fancyload_' . $filename);
  }

  // set background to image.
  $vars['attributes']['style'][] = 'background-color:#' . $color_value . ';';

  // create subfolders for saving transparent png's.
  $style_name = $vars['style_name'];

  if (empty($style_name)) {
    $style_name = 'original';
  }

  $new_folder = 'public://fancyload';
  file_prepare_directory($new_folder, FILE_CREATE_DIRECTORY);

  $new_folder = 'public://fancyload/' . $style_name;
  file_prepare_directory($new_folder, FILE_CREATE_DIRECTORY);

  // Check if transparent png already exists, if not create.
  $transparent = 'public://fancyload/' . $style_name . '/' . $filename . '.png';
  if (!file_exists($transparent)) {
    fancyload_create_transparent_file($width, $height, $style_name, $filename);
  }

  // Set transparent png as source.
  $vars['attributes']['src'] = $path_to_files . 'fancyload/' . $style_name . '/' . $filename . '.png';

  $vars['#attached']['library'][] = fancyload_choose_library($config);
}

/**
 * Strips accents. Apparently drupals state system does not accept accents on filenames
 */
function fancyload_remove_accents($string) {
    return strtr($string,'àáâãäçèéêëìíîïñòóôõöùúûüýÿÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝ','aaaaaceeeeiiiinooooouuuuyyAAAAACEEEEIIIINOOOOOUUUUY');
}

/**
 * Fetches the dominant color of an image.
 *
 * @param string $uri
 *   The location of the image to get color from.
 *
 * @return string
 *   The hexadecimal representation of the dominant color.
 */
function fancyload_get_dominant_color($uri) {

  $filename = file_create_url($uri);

  // Use curl because allow fopen not always supported on shared servers.
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $filename);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  $contents = curl_exec($ch);
  curl_close($ch);
  $temp_image = ImageCreateFromString($contents);
  // fetch color from image
  $thumb = imagecreatetruecolor(1, 1);
  imagecopyresampled($thumb, $temp_image, 0, 0, 0, 0, 1, 1, imagesx($temp_image), imagesy($temp_image));
  $dominant_color = strtoupper(dechex(imagecolorat($thumb, 0, 0)));

  return $dominant_color;
}

/**
 * Creates a transparent file for a file
 *
 * @param int $width
 *   The image width.
 * @param int $height
 *   The image height.
 * @param string $style_name
 *   The image style.
 * @param string $filename
 *   The location of the image.
 */
function fancyload_create_transparent_file($width, $height, $style_name, $filename) {
  $destination = \Drupal::service('file_system')->realpath(file_default_scheme() . "://");
  $img = imagecreatetruecolor($width, $height);
  imagesavealpha($img, TRUE);
  $color = imagecolorallocatealpha($img, 0, 0, 0, 127);
  imagefill($img, 0, 0, $color);
  imagepng($img, $destination . '/fancyload/' . $style_name . '/' . $filename . '.png');
}

/**
 * Chooses if the library should be minified or not.
 *
 * @param $config
 *   The module configuration.
 *
 * @return string
 *   The name of the library.
 */
function fancyload_choose_library($config) {
  $minified = $config->get('minified');
  if ($minified == 1) {
    return 'fancyload/fancyload.min';
  } else {
    return 'fancyload/fancyload';
  }
}

/**
 * Implements hook_module_uninstall().
 */
function fancyload_uninstall() {
  // Delete the fancyload folder.
  file_unmanaged_delete_recursive('public://fancyload');

  // Remove the saved colors.
  $query = \Drupal::database()->select('key_value', 'k');
  $query->fields('k', ['name']);
  $query->condition('k.collection', 'state');
  $query->condition('k.name', $query->escapeLike('fancyload_') . '%', 'LIKE');
  $results = $query->execute()->fetchAll();
  foreach ($results as $row) {
    $query = \Drupal::database()->delete('key_value');
    $query->condition('name', $row->name);
    $query->execute();
  }
}

/**
 * Implements hook_help().
 */
function fancyload_help($route_name, RouteMatchInterface $route_match) {
  if ($route_name === 'help.page.fancyload') {
    $readme_file = file_exists(__DIR__ . '/README.md') ? __DIR__ . '/README.md' : __DIR__ . '/README.txt';
    if (!file_exists($readme_file)) {
      return NULL;
    }
    $text = file_get_contents($readme_file);
    if ($text && !\Drupal::moduleHandler()->moduleExists('markdown')) {
      return '<pre>' . $text . '</pre>';
    }
    else {
      // Use the Markdown filter to render the README.
      $filter_manager = \Drupal::service('plugin.manager.filter');
      $settings = \Drupal::configFactory()->get('markdown.settings')->getRawData();
      $config = ['settings' => $settings];
      $filter = $filter_manager->createInstance('markdown', $config);
      return $filter->process($text, 'en');
    }
  }
  return NULL;
}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc