You are here

imagefield_crop.module in Imagefield Crop 7.3

File

imagefield_crop.module
View source
<?php

/**
 * Implements hook_field_info().
 */
function imagefield_crop_field_info() {
  return array(
    'imagefield_crop' => array(
      'label' => t('Image cropped'),
      'description' => t('This field stores the ID of an image file as an integer value.'),
      'settings' => array(
        'uri_scheme' => variable_get('file_default_scheme', 'public'),
        'default_image' => 0,
      ),
      'instance_settings' => array(
        'file_extensions' => 'png gif jpg jpeg',
        'file_directory' => '',
        'max_filesize' => '',
        'alt_field' => 0,
        'title_field' => 0,
        'max_resolution' => '',
        'min_resolution' => '',
        'default_image' => 0,
      ),
      'default_widget' => 'imagefield_crop_widget',
      'default_formatter' => 'image',
      'property_type' => 'field_item_image',
      'property_callbacks' => array(
        'entity_metadata_field_image_callback',
        'entity_metadata_field_file_callback',
        'entity_metadata_field_imagefield_crop_callback',
      ),
    ),
  );
}

/**
 * Additional callback to adapt the property info for image fields.
 * This callback gets invoked after entity_metadata_field_file_callback().
 * @see entity_metadata_field_entity_property_info().
 */
function entity_metadata_field_imagefield_crop_callback(&$info, $entity_type, $field, $instance, $field_type) {
  $property =& $info[$entity_type]['bundles'][$instance['bundle']]['properties'][$field['field_name']];

  // Update the property info with the info for image fields.
  $property['property info'] = entity_property_field_item_image_info();
  if (empty($instance['settings']['alt_field'])) {
    unset($property['property info']['alt']);
  }
  if (empty($field['settings']['title_field'])) {
    unset($property['property info']['title']);
  }
  $property['property info']['croped_image'] = array(
    'type' => 'struct',
    'getter callback' => 'imagefield_crop_get_renderable',
    'label' => 'Renderable array of cropped image',
    'entity token' => FALSE,
  );
}

/**
 * Implements property callback imagefield_crop_get_renderable().
 * @param $data
 * @param $options
 * @param $name
 * @param $type
 * @param $info
 * @return array|string
 */
function imagefield_crop_get_renderable($data, $options, $name, $type, &$info) {

  // Set contextual info useful for getters of any child properties.
  $field_info = $info['parent']
    ->info();
  $instance = $field_info['instance'];
  $entity = $field_info['parent']
    ->value();
  $entity_type = $field_info['parent']
    ->type();
  $langcode = isset($options['language']) ? $options['language']->language : LANGUAGE_NONE;
  $langcode = entity_metadata_field_get_language($entity_type, $entity, $field_info['field'], $langcode, TRUE);
  return imagefield_crop_field_formatter_view($entity_type, $entity, $field_info['field'], $instance, $langcode, array(
    $data,
  ), reset($instance['display']));
}

/**
 * Implements hook_field_settings_form().
 */
function imagefield_crop_field_settings_form($field, $instance) {
  return image_field_settings_form($field, $instance);
}

/**
 * Implements hook_field_instance_settings_form().
 */
function imagefield_crop_field_instance_settings_form($field, $instance) {
  return image_field_instance_settings_form($field, $instance);
}

/**
 * Implements hook_field_load().
 */
function imagefield_crop_field_load($entity_type, $entities, $field, $instances, $langcode, &$items, $age) {
  file_field_load($entity_type, $entities, $field, $instances, $langcode, $items, $age);
  foreach ($items as $eid => &$entity) {
    foreach ($entity as $delta => &$item) {
      $entity_w = entity_metadata_wrapper($entity_type, $entities[$eid]);
      $key = $entity_w
        ->entityKey('revision') ? $entity_w
        ->entityKey('revision') : $entity_w
        ->entityKey('id');
      $item['crop_config'] = imagefield_crop_variants_load_multiple($item['fid'], $entities[$eid]->{$key});
    }
  }
}

/**
 * Implements hook_field_prepare_view().
 */
function imagefield_crop_field_prepare_view($entity_type, $entities, $field, $instances, $langcode, &$items) {
  image_field_prepare_view($entity_type, $entities, $field, $instances, $langcode, $items);
}

/**
 * Implements hook_field_presave().
 */
function imagefield_crop_field_presave($entity_type, $entity, $field, $instance, $langcode, &$items) {
  file_field_presave($entity_type, $entity, $field, $instance, $langcode, $items);
}

/**
 * Implements hook_field_insert().
 */
function imagefield_crop_field_insert($entity_type, $entity, $field, $instance, $langcode, &$items) {
  file_field_insert($entity_type, $entity, $field, $instance, $langcode, $items);
  $widget_settings = $instance['widget']['settings'];
  $presets = imagefield_crop_presets_load_multiple_by_name(array_keys($widget_settings['presets']));
  $entity_w = entity_metadata_wrapper($entity_type, $entity);
  $key = $entity_w
    ->entityKey('revision') ? $entity_w
    ->entityKey('revision') : $entity_w
    ->entityKey('id');
  foreach ($items as &$item) {
    foreach ($item['crop_config'] as $pid => &$preset) {
      if (!is_object($preset)) {
        $preset = json_decode($preset);
        $keys = array_keys($item['crop_config']);
        $first = reset($keys);
        $item['crop_config'][$first]->active = TRUE;
      }
      $scale = $presets[$pid]->data['crop-type'] == 'resolution' ? $presets[$pid]->data['resolution'] : NULL;
      $src = file_load($item['fid']);
      $orig = imagefield_crop_create_copy($src);
      file_usage_add($orig, 'imagefield_crop', 'file', $src->fid);
      _imagefield_crop_resize(drupal_realpath($orig->uri), $preset, $scale, $orig);
      file_save($src);
      $preset->uri = $orig->uri;
      unset($preset->cropbox_changed);
      $record['data'] = $preset;
      $record['source_fid'] = $item['fid'];
      $record['pid'] = $pid;
      $record['fid'] = $orig->fid;
      $record['vid'] = $entity->{$key};
      drupal_write_record('imagefield_crop_variants', $record);
      $record = array();
    }
  }
}

/**
 * Implements hook_field_update().
 */
function imagefield_crop_field_update($entity_type, $entity, $field, $instance, $langcode, &$items) {
  list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
  $original = entity_create_stub_entity($entity_type, array(
    $id,
    $vid,
    $bundle,
  ));
  field_attach_load($entity_type, array(
    $id => $original,
  ), FIELD_LOAD_CURRENT, array(
    'field_id' => $field['id'],
  ));
  $original_items = array();
  if (!empty($original->{$field['field_name']}[$langcode])) {
    foreach ($original->{$field['field_name']}[$langcode] as $original_item) {
      $original_items[$original_item['fid']] = $original_item;
    }
  }
  $entity_w = entity_metadata_wrapper($entity_type, $entity);
  file_field_update($entity_type, $entity, $field, $instance, $langcode, $items);
  $presets = imagefield_crop_presets_load_multiple_by_name(array_keys($instance['widget']['settings']['presets']));
  $scale = NULL;
  $key = $entity_w
    ->entityKey('revision') ? $entity_w
    ->entityKey('revision') : $entity_w
    ->entityKey('id');
  foreach ($items as $delta => &$item) {
    $variants = imagefield_crop_variants_load_multiple($item['fid'], $vid);
    foreach ($item['crop_config'] as $pid => $preset) {
      $variant = !empty($variants[$pid]) ? $variants[$pid] : '';
      if (!is_object($preset)) {
        $preset = json_decode($preset);
        $first = reset(array_keys($item['crop_config']));
        $item['crop_config'][$first]->active = TRUE;
      }
      if (!empty($preset->cropbox_changed) || !empty($preset->new)) {
        $scale = $presets[$pid]->data['crop-type'] == 'resolution' ? $presets[$pid]->data['resolution'] : NULL;
        if (!in_array($item['fid'], array_keys($original_items)) || !empty($preset->new) || empty($variant)) {
          $src = file_load($item['fid']);
          $orig = imagefield_crop_create_copy($src);
          file_usage_add($orig, 'imagefield_crop', 'file', $src->fid);
          _imagefield_crop_resize(drupal_realpath($orig->uri), $preset, $scale, $orig);
          file_save($src);
        }
        else {
          $src = file_load($item['fid']);
          $orig = file_load($variant->fid);
          list($name, $ext) = explode('.', drupal_basename($orig->uri));
          $orig->uri = file_build_uri($name . '_' . time() . '.' . $ext);
          file_delete($orig);
          _imagefield_crop_resize(drupal_realpath($src->uri), $preset, $scale, $orig);
          file_save($src);
        }
        unset($preset->cropbox_changed);
        $preset->uri = $orig->uri;
        $record['fid'] = $orig->fid;
        $preset->updated = time();
      }
      $record['pid'] = $pid;
      $record['source_fid'] = $item['fid'];
      $record['vid'] = $entity->{$key};
      if (!empty($preset->uri)) {
        $record['data'] = $preset;
      }
      else {

        // If no any changes was made to the image -  copy old imagecrop data from loaded variant or if
        // data has pre populated by drupal and variant don't exist copy data from image crop preset
        $record['data'] = !empty($variant) ? $variant->data : $preset->data;
      }
      if (!empty($preset->new) || empty($variant)) {
        unset($record['data']->new);
        drupal_write_record('imagefield_crop_variants', $record);
      }
      elseif (!empty($variant)) {
        drupal_write_record('imagefield_crop_variants', $record, array(
          'source_fid',
          'vid',
          'pid',
        ));
      }
      $record = array();
    }
  }
}

/**
 * Implements hook_field_delete().
 */
function imagefield_crop_field_delete($entity_type, $entity, $field, $instance, $langcode, &$items) {
  list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
  $entity_w = entity_metadata_wrapper($entity_type, $entity);
  $key = $entity_w
    ->entityKey('revision') ? $entity_w
    ->entityKey('revision') : $entity_w
    ->entityKey('id');

  // Delete all file usages within this entity.
  foreach ($items as $item) {
    $variants = imagefield_crop_variants_load_multiple($item['fid'], $entity->{$key});
    foreach ($variants as $pid => $variant) {
      $file = file_load($variant->fid);
      file_usage_delete($file, 'imagefield_crop', NULL, NULL, 0);
      file_delete($file);
    }
    $orig_file = file_load($item['fid']);
    file_field_delete_file($orig_file, $field, $entity_type, $id, 0);
    imagefield_crop_variants_delete_multiple(array(), $item['fid'], $vid);
  }
}

/**
 * Implements hook_field_delete_revision().
 */
function imagefield_crop_field_delete_revision($entity_type, $entity, $field, $instance, $langcode, &$items) {
  list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
  foreach ($items as $delta => $item) {

    // Decrement the file usage count by 1 and delete the file if possible.
    if (file_field_delete_file($item, $field, $entity_type, $id)) {
      $orig_file = _imagefield_crop_file_to_crop($item['fid']);
      if ($orig_file && $orig_file->fid != $item['fid']) {
        file_usage_delete($orig_file, 'imagefield_crop', 'file', $item['fid']);
        file_delete($orig_file);
      }
      $items[$delta] = NULL;
    }
  }
}

/**
 * Implements hook_field_is_empty().
 */
function imagefield_crop_field_is_empty($item, $field) {
  return file_field_is_empty($item, $field);
}

/**
 * Implements hook_field_formatter_info().
 */
function imagefield_crop_field_formatter_info() {
  $formatters = array(
    'imagefield_crop' => array(
      'label' => t('Image Crop'),
      'field types' => array(
        'imagefield_crop',
      ),
      'settings' => array(
        'preset' => '',
        'image_style' => '',
        'image_link' => '',
        'image_link_style' => '',
      ),
    ),
  );
  return $formatters;
}

/**
 * Implements hook_field_formatter_settings_form().
 * @param $field
 * @param $instance
 * @param $view_mode
 * @param $form
 * @param $form_state
 */
function imagefield_crop_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];
  $form = image_field_formatter_settings_form($field, $instance, $view_mode, $form, $form_state);
  $presets = imagefield_crop_presets_load_multiple_by_name(array_keys($instance['widget']['settings']['presets']));
  $image_styles = image_style_options(FALSE);
  $options = array();
  foreach ($presets as $preset) {
    $options[$preset->name] = $preset->label;
  }
  $form['preset'] = array(
    '#title' => t('Imagefield crop preset'),
    '#type' => 'select',
    '#empty_option' => 'Default preset',
    '#options' => $options,
    '#weight' => -100,
    '#default_value' => $settings['preset'],
  );
  $form['image_link']['#attributes']['class'] = array(
    'image-link',
  );
  $form['image_link_style'] = array(
    '#title' => t('Image-style on linked image'),
    '#type' => 'select',
    '#default_value' => $settings['image_link_style'],
    '#empty_option' => t('None (original image)'),
    '#options' => $image_styles,
    '#states' => array(
      'visible' => array(
        'input.image-link' => array(
          'value' => 'file',
        ),
      ),
    ),
  );
  return $form;
}

/**
 * Implements hook_field_formatter_settings_summary().
 * @param $field
 * @param $instance
 * @param $view_mode
 */
function imagefield_crop_field_formatter_settings_summary($field, $instance, $view_mode) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];
  $summary = image_field_formatter_settings_summary($field, $instance, $view_mode);
  $preset = imagefield_crop_preset_load_by_name($settings['preset']);
  $summary = t('Imagefield crop preset: @name', array(
    '@name' => !empty($preset->label) ? $preset->label : 'Default Preset',
  )) . '<br>' . $summary;
  if (isset($settings['image_link']) && $settings['image_link'] == 'file') {
    $summary .= ' ' . t('with image style @style', array(
      '@style' => $settings['image_link_style'],
    ));
  }
  return $summary;
}

/**
 * Implementation hook__field_formatter_view().
 * @param $entity_type
 * @param $entity
 * @param $field
 * @param $instance
 * @param $langcode
 * @param $items
 * @param $display
 * @return array|string
 */
function imagefield_crop_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();
  $entity_w = entity_metadata_wrapper($entity_type, $entity);
  $key = $entity_w
    ->entityKey('revision') ? $entity_w
    ->entityKey('revision') : $entity_w
    ->entityKey('id');
  $settings = $display['settings'];

  // Check if the formatter involves a link.
  if ($settings['image_link'] == 'content') {
    $uri = entity_uri($entity_type, $entity);
  }
  elseif ($settings['image_link'] == 'file') {
    $link_file = TRUE;
  }
  if (!empty($items[0]) && !empty($items[0]['is_default'])) {
    $item = reset($items);
    if (isset($link_file)) {
      $uri = array(
        'path' => file_create_url($item['uri']),
        'options' => array(),
      );
    }
    $element[] = array(
      '#theme' => 'image_formatter',
      '#item' => $item,
      '#image_style' => $display['settings']['image_style'],
      '#path' => isset($uri) ? $uri : '',
    );
  }
  if (empty($display['settings']['preset'])) {
    foreach ($items as $delta => $item) {
      $presets = !empty($item['crop_config']) ? $item['crop_config'] : imagefield_crop_variants_load_multiple($item['fid'], $entity->{$key});
      foreach ($presets as $pid => $preset) {
        $preset = !empty($preset->data) ? $preset->data : (object) $preset;
        if (!empty($preset->active) || count($presets) == 1) {
          $item['uri'] = $preset->uri;
          if (isset($link_file)) {
            $link_url = !empty($settings['image_link_style']) ? image_style_url($settings['image_link_style'], $item['uri']) : file_create_url($item['uri']);
            $uri = array(
              'path' => $link_url,
              'options' => array(),
            );
          }
          $element[$delta] = array(
            '#theme' => 'image_formatter',
            '#item' => $item,
            '#image_style' => $display['settings']['image_style'],
            '#path' => isset($uri) ? $uri : '',
          );
        }
      }
    }
  }
  else {
    $preset = imagefield_crop_preset_load_by_name($display['settings']['preset']);
    foreach ($items as $delta => $item) {
      $presets = imagefield_crop_variants_load_multiple($item['fid'], $entity->{$key}, array(
        $preset->pid,
      ));
      $preset = reset($presets);
      if (!empty($preset)) {
        $item['uri'] = $preset->data->uri;
        if (isset($link_file)) {
          $link_url = !empty($settings['image_link_style']) ? image_style_url($settings['image_link_style'], $item['uri']) : file_create_url($item['uri']);
          $uri = array(
            'path' => $link_url,
            'options' => array(),
          );
        }
        $element[$delta] = array(
          '#theme' => 'image_formatter',
          '#item' => $item,
          '#image_style' => $display['settings']['image_style'],
          '#path' => isset($uri) ? $uri : '',
        );
      }
    }
  }
  return $element;
}

/**
 * Implements hook__crop_field_formatter_info_alter().
 */
function imagefield_crop_field_formatter_info_alter(&$info) {

  // Let a new field type re-use an existing formatter.
  $info['image']['field types'][] = 'imagefield_crop';
}

/**
 * Implements hook_field_widget_info().
 */
function imagefield_crop_field_widget_info() {
  return array(
    'imagefield_crop_widget' => array(
      'label' => t('Image with cropping'),
      'field types' => array(
        'imagefield_crop',
      ),
      'settings' => array(
        'progress_indicator' => 'throbber',
        'presets' => '',
        'preview_image_style' => 'thumbnail',
        'hide_preview' => FALSE,
        'preview' => array(
          'width' => 500,
          'height' => 500,
        ),
        'cropbox' => array(
          'width' => 500,
          'height' => 500,
        ),
      ),
      'behaviors' => array(
        'multiple values' => FIELD_BEHAVIOR_CUSTOM,
        'default value' => FIELD_BEHAVIOR_NONE,
      ),
    ),
  );
}

/**
 * Implements hook_field_widget_settings_form().
 */
function imagefield_crop_field_widget_settings_form($field, $instance) {
  $widget = $instance['widget'];
  $settings = $widget['settings'];

  // Use the image widget settings form.
  $form = image_field_widget_settings_form($field, $instance);
  $presets = imagefield_crop_presets_load_multiple();
  $options = array();
  foreach ($presets as $preset) {
    $options[$preset->name] = $preset->label;
  }
  $form['presets'] = array(
    '#type' => 'select',
    '#title' => t('Presets'),
    '#options' => $options,
    '#default_value' => $settings['presets'],
    '#multiple' => TRUE,
  );
  $form['hide_preview'] = array(
    '#type' => 'checkbox',
    '#title' => t('Hide preview'),
    '#default_value' => !empty($settings['hide_preview']) ? $settings['hide_preview'] : '',
    '#theme_wrappers' => array(
      'form_element',
    ),
  );
  $form['preview'] = array(
    '#type' => 'container',
    '#title' => t('Preview size'),
    '#theme_wrappers' => array(
      'form_element',
    ),
    '#description' => t('Ratio for crop area. For example 4:3 or 16:9 as width to height.'),
    '#markup' => '',
  );
  $form['preview']['width'] = array(
    '#type' => 'textfield',
    '#default_value' => !empty($settings['preview']['width']) ? $settings['preview']['width'] : '',
    '#size' => 5,
    '#maxlength' => 5,
    '#theme_wrappers' => array(),
  );
  $form['preview']['height'] = array(
    '#type' => 'textfield',
    '#default_value' => !empty($settings['preview']['height']) ? $settings['preview']['height'] : '',
    '#size' => 5,
    '#maxlength' => 5,
    '#theme_wrappers' => array(),
  );
  $form['cropbox'] = array(
    '#type' => 'container',
    '#title' => t('Cropbox size'),
    '#theme_wrappers' => array(
      'form_element',
    ),
    '#description' => t('Size of cropping box'),
    '#markup' => '',
  );
  $form['cropbox']['width'] = array(
    '#type' => 'textfield',
    '#default_value' => !empty($settings['cropbox']['width']) ? $settings['cropbox']['width'] : '',
    '#size' => 5,
    '#maxlength' => 5,
    '#theme_wrappers' => array(),
  );
  $form['cropbox']['height'] = array(
    '#type' => 'textfield',
    '#default_value' => !empty($settings['cropbox']['height']) ? $settings['cropbox']['height'] : '',
    '#size' => 5,
    '#maxlength' => 5,
    '#theme_wrappers' => array(),
  );
  return $form;
}

/**
 * Implements hook_field_widget_form().
 */
function imagefield_crop_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  $elements = image_field_widget_form($form, $form_state, $field, $instance, $langcode, $items, $delta, $element);
  foreach (element_children($elements) as $delta) {
    $elements[$delta]['#value_callback'] = 'imagefield_crop_value_callback';

    // Add all extra functionality provided by the imagefield_crop widget.
    $elements[$delta]['#process'][] = 'imagefield_crop_widget_process';
    $elements[$delta]['#upload_validators']['imagefield_crop_upload_validate'] = array(
      $field,
      $instance,
    );
  }
  return $elements;
}

/**
 * An element #process callback for the imagefield_crop field type.
 */
function imagefield_crop_widget_process($element, &$form_state, $form) {
  $item = $element['#value'];
  $item['fid'] = $element['fid']['#value'];
  $instance = field_widget_instance($element, $form_state);
  $settings = $instance['settings'];
  $widget_settings = $instance['widget']['settings'];
  $presets = imagefield_crop_presets_load_multiple_by_name(array_keys($widget_settings['presets']));
  $default_preset = reset($presets);
  $element['#theme'] = 'imagefield_crop_widget';
  $element['#description'] = t('Click on the image and drag to mark how the image will be cropped');
  $path = drupal_get_path('module', 'imagefield_crop');
  $element['#attached']['js'][] = "{$path}/Jcrop/js/jquery.Jcrop.js";
  $element['#attached']['js'][] = "{$path}/imagefield_crop.js";
  $element['#attached']['css'][] = "{$path}/Jcrop/css/jquery.Jcrop.css";
  $entity_w = entity_metadata_wrapper($element['#entity_type'], $element['#entity']);
  if ($element['#file']) {
    unset($element['filename']);
    $file_to_crop = $element['#file'];
    $cropbox_class = array(
      'cropbox',
      'jcrop-processed',
    );
    $parent = drupal_array_get_nested_value($form, array_slice($element['#parents'], 0, -1));
    if (isset($item['_weight']) && $parent['#file_upload_delta'] - 1 == $item['_weight'] && ($form_state['submitted'] && is_numeric(strpos($form_state['triggering_element']['#name'], 'upload_button')))) {
      unset($cropbox_class[1]);
    }
    elseif (!isset($item['_weight']) && ($form_state['submitted'] && is_numeric(strpos($form_state['triggering_element']['#name'], 'upload_button')))) {
      unset($cropbox_class[1]);
    }
    $element['cropbox'] = array(
      '#markup' => theme('image', array(
        'path' => $file_to_crop->uri,
        'attributes' => array(
          'class' => $cropbox_class,
          'id' => $element['#id'] . '-cropbox',
        ),
      )),
    );
    $element['recrop'] = array(
      '#type' => 'button',
      '#attributes' => array(
        'class' => array(
          'recrop-btn',
        ),
      ),
      '#value' => t('Recrop'),
    );
    $element['presets']['#theme'] = 'item_list';

    // Get image info to find out dimensions.
    $image_info = image_get_info(drupal_realpath($file_to_crop->uri));
    $element['crop_config'] = array(
      '#tree' => TRUE,
      '#type' => 'container',
    );
    $element['preview'] = array(
      '#type' => 'markup',
      '#file' => $file_to_crop,
      // This is used by the #process function
      '#process' => array(
        'imagefield_crop_widget_preview_process',
      ),
      '#theme' => 'imagefield_crop_preview',
      '#path' => $file_to_crop->uri,
    );
    foreach ($presets as $preset) {
      $class = array();
      $machine_name = strtolower(str_replace(' ', '-', $preset->name));
      if ($preset->data['crop-type'] == 'free') {
        $crop_area_height = $image_info['height'];
        $crop_area_width = $image_info['width'];
        $ratio = 0;

        //$crop_area_width / $crop_area_height;
      }
      elseif ($preset->data['crop-type'] == 'resolution') {
        $min_resolution_height = $resolution_height = $preset->data['resolution']['height'];
        $min_resolution_width = $resolution_width = $preset->data['resolution']['width'];
        $ratio = $resolution_width / $resolution_height;
        $crop_area_height = floor($image_info['width'] / $ratio);
        $crop_area_width = $image_info['width'];
        if ($crop_area_height > $image_info['height']) {
          $crop_area_width = floor($image_info['height'] * $ratio);
          $crop_area_height = $image_info['height'];
        }
        if ($image_info['width'] < $min_resolution_width || $image_info['height'] < $min_resolution_height) {
          $class[] = 'error';
        }
      }
      else {
        $min_resolution_height = $preset->data['min-resolution']['height'];
        $min_resolution_width = $preset->data['min-resolution']['width'];
        $ratio_width = $preset->data['ratio']['width'];
        $ratio_height = $preset->data['ratio']['height'];
        $crop_area_height = floor($image_info['width'] / $ratio_width * $ratio_height);
        $crop_area_width = $image_info['width'];
        if ($crop_area_height > $image_info['height']) {
          $crop_area_height = $image_info['height'];
          $crop_area_width = floor($image_info['height'] / $ratio_height * $ratio_width);
        }
        $ratio = $ratio_width / $ratio_height;
        if ($image_info['width'] < $crop_area_width || $image_info['height'] < $crop_area_height) {
          $class[] = 'error';
        }
      }
      $crop_config = array();
      if (!empty($item['crop_config'][$preset->pid]->data)) {
        $crop_config = (array) $item['crop_config'][$preset->pid]->data;
      }
      elseif (!empty($item['crop_config'][$preset->pid])) {
        $crop_config = imagefield_crop_fill_cropconfig(!empty($item['crop_config'][$preset->pid]) ? $item['crop_config'][$preset->pid] : array(), $crop_area_height, $crop_area_width);
        $crop_config['new'] = TRUE;
      }
      if (empty($crop_config)) {
        $crop_config = imagefield_crop_fill_cropconfig($item, $crop_area_height, $crop_area_width);
      }
      $crop_config = json_encode($crop_config);

      //      if(!empty($element['#default_value']['crop_config'][$preset->pid])){
      //        $element['#default_value']['crop_config'][$preset->pid] = $crop_config;
      //      }
      $element['crop_config'][$preset->pid] = array(
        '#type' => 'hidden',
        '#attributes' => array(
          'class' => array(
            'crop-config',
            $machine_name,
          ),
        ),
        '#default_value' => isset($crop_config) ? $crop_config : 0,
      );
      $class[] = 'preset';
      if (!empty($item['crop_config'][$preset->pid]->data->active)) {
        $class[] = 'active';
      }
      $element['presets']['#items'][] = '<a id="' . $machine_name . '" href="#" class="' . implode(' ', $class) . '">' . $preset->name . '</a>';
      $settings = array(
        $element['#id'] => array(
          $machine_name => array(),
        ),
      );
      $settings[$element['#id']]['hide_preview'] = $widget_settings['hide_preview'];
      $settings[$element['#id']][$machine_name] = array(
        'box' => array(
          'ratio' => isset($ratio) ? $ratio : 0,
          'box_width' => $widget_settings['cropbox']['width'],
          'box_height' => $widget_settings['cropbox']['height'],
        ),
        'minimum' => array(
          'width' => $preset->data['crop-type'] != 'free' ? $min_resolution_width : NULL,
          'height' => $preset->data['crop-type'] != 'free' ? $min_resolution_height : NULL,
        ),
      );
      $element['#attached']['js'][] = array(
        'data' => array(
          'imagefield_crop' => $settings,
        ),
        'type' => 'setting',
        'scope' => 'header',
      );
    }
  }
  return $element;
}

/**
 * Impletement imagefield_crop_widget_preview_process().
 * @param $element
 * @param $form_state
 * @param $form
 * @return mixed
 */
function imagefield_crop_widget_preview_process($element, &$form_state, $form) {
  $file = $element['#file'];
  if ($file->fid == 0) {
    return $element;
  }

  // The widget belongs to the parent, so we got to find it first
  $parents = array_slice($element['#array_parents'], 0, -1);
  $parent = drupal_array_get_nested_value($form, $parents);
  $instance = field_widget_instance($parent, $form_state);
  $presets = imagefield_crop_presets_load_multiple_by_name(array_keys($instance['widget']['settings']['presets']));
  $image_info = image_get_info(drupal_realpath($file->uri));
  $crop_config = !empty($parent['#value']['crop_config']) ? $parent['#value']['crop_config'] : array();
  foreach ($presets as $pid => $preset) {
    if ($preset->data['crop-type'] == 'free') {
      $img = $image_info;
      imagefield_crop_presize($img, $instance['widget']['settings']['preview']['width'], $instance['widget']['settings']['preview']['height']);
      $width = $img['width'];
      $height = $img['height'];
    }
    elseif ($preset->data['crop-type'] == 'resolution') {
      $img = $preset->data['resolution'];
      imagefield_crop_presize($img, $instance['widget']['settings']['preview']['width'], $instance['widget']['settings']['preview']['height']);
      $width = $img['width'];
      $height = $img['height'];
    }
    else {
      if ($preset->data['ratio']['width'] > $preset->data['ratio']['height']) {
        $width = $instance['widget']['settings']['preview']['width'];
        $height = $width / $preset->data['ratio']['width'] * $preset->data['ratio']['height'];
      }
      else {
        $height = $instance['widget']['settings']['preview']['width'];
        $width = $height / $preset->data['ratio']['height'] * $preset->data['ratio']['width'];
      }
    }

    //TODO: Ivestigate about preview size
    $machine_name = strtolower(str_replace(' ', '-', $preset->name));
    $settings[$parent['#id']][$machine_name] = array();
    $settings[$parent['#id']][$machine_name] = array(
      'preview' => array(
        'orig_width' => $image_info['width'],
        'orig_height' => $image_info['height'],
        'width' => (int) $width,
        'height' => (int) $height,
      ),
    );
    $element['#imagefield_crop']['#' . $machine_name] = array(
      '#file' => $element['#file'],
      '#width' => $width,
      '#height' => $height,
      '#name' => $machine_name,
      '#crop_config' => !empty($crop_config[$pid]) ? $crop_config[$pid] : FALSE,
    );
  }
  if (!empty($settings)) {
    $element['#attached']['js'][] = array(
      'data' => array(
        'imagefield_crop' => $settings,
      ),
      'type' => 'setting',
      'scope' => 'header',
    );
  }
  return $element;
}

/*********************/

/* Internal functions */

/*********************/
function _imagefield_crop_file_to_crop($fid) {

  // Try to find the original file for this image
  $source_fid = db_select('file_usage', 'fu')
    ->fields('fu', array(
    'fid',
  ))
    ->condition('module', 'imagefield_crop')
    ->condition('type', 'file')
    ->condition('id', $fid)
    ->condition('count', 0, '>')
    ->execute()
    ->fetchField();
  if ($source_fid) {
    return file_load($source_fid);
  }
  return file_load($fid);
}

/**
 * Crop the image and resize it
 */
function _imagefield_crop_resize($src, $preset, $scale = array(), $dst_file = NULL) {
  $image = image_load($src);
  if ($image) {
    $result = TRUE;
    if ($preset) {
      $result = $result && image_crop($image, $preset->cropbox_x, $preset->cropbox_y, $preset->cropbox_width, $preset->cropbox_height);
    }
    if ($scale && $scale['width'] < $preset->cropbox_width && $scale['height'] < $preset->cropbox_height) {
      $result = $result && image_scale_and_crop($image, $scale['width'], $scale['height']);
    }
    $result = $result && image_save($image, isset($dst_file->uri) ? drupal_realpath($dst_file->uri) : $src);
    module_invoke_all('imagefield_crop_image_crop_updated', $dst_file);
    return $result;
  }
  return FALSE;
}

/**
 * Element value callback. Used to set crop area to image size, if image is smaller then
 * output resolution, but validation isn't enabled.
 * @param $element
 * @param bool $input
 * @param $form_state
 * @return array|bool
 */
function imagefield_crop_value_callback($element, $input = FALSE, $form_state) {
  $crop_config = array();

  // We depend on the managed file element to handle uploads.
  $return = file_managed_file_value($element, $input, $form_state);
  $form_state_crop_config = $form_state['values'];
  foreach ($element['#parents'] as $parent) {
    $form_state_crop_config = isset($form_state_crop_config[$parent]) ? $form_state_crop_config[$parent] : array();
  }
  if (isset($form_state_crop_config['crop_config'])) {
    foreach ($form_state_crop_config['crop_config'] as $pid => $preset) {
      if (!is_object($preset)) {
        $crop_config[$pid] = json_decode($preset);
      }
      else {
        $crop_config[$pid] = $preset;
      }
    }
  }
  if (!empty($return['crop_config']) && $input) {
    $crop_config = $return['crop_config'];
    foreach ($crop_config as $pid => &$config) {
      $config = json_decode($config);
    }
  }

  //  hook_value_vallback should return values only from form.
  if (!empty($crop_config)) {
    $return['crop_config'] = $crop_config;
  }
  return $return;
}

/**
 * Validate function for images to be cropped.
 * Returns an error if output resolution for field is set, but file is smaller.
 * @param $file
 * @param $field
 * @param $instance
 * @return array
 */
function imagefield_crop_upload_validate($file, $field, $instance) {
  $errors = array();
  $widget_settings = $instance['widget']['settings'];
  $info = image_get_info($file->uri);
  if (!$info) {
    $errors[] = t('Image seems to be broken and can\'t be processed. Please try to upload another image or resave this current image with graphic editor');
  }

  //  TODO: Add validation of image resolution with preset support
  //  elseif ($info) {
  //    foreach($presets as $pid => $preset){
  //      if($preset->data['crop-type'] == 'resolution'){
  //        if ($info['width'] < $preset->data['resolution']['width'] || $info['height'] < $preset->data['resolution']['height']) {
  //          $errors[] = t('The image is too small for preset %preset; the minimum dimensions are %dimensions pixels.', array('%dimensions' => implode('x', $preset->data['resolution']), '%preset' => $preset->name));
  //        }
  //      }
  //
  //    }
  //  }
  return $errors;
}

/**
 * Creates a copy of the file.
 * @param $file
 * @return stdClass
 */
function imagefield_crop_create_copy($file) {
  if ($file->filemime == 'image/gif') {
    $realpath = drupal_realpath($file->uri);
    $new_uri = file_destination(substr($file->uri, 0, -4) . '.jpeg', FILE_EXISTS_RENAME);
    $image = image_load($realpath);
    $image->info['extension'] = 'jpeg';
    $image->info['mime_type'] = 'image/jpeg';
    $success = image_gd_save($image, $new_uri);
    if ($success) {
      $file->uri = $new_uri;
      $file->filename = basename($new_uri);
      $file->filemime = 'image/jpeg';
      file_save($file);
      file_unmanaged_delete($realpath);
    }
  }
  $new_uri = file_unmanaged_copy($file->uri, $file->uri);
  $new_file = clone $file;
  $new_file->fid = 0;
  $new_file->status = FILE_STATUS_PERMANENT;
  $new_file->uri = $new_uri;
  $new_file->filename = basename($new_uri);
  return file_save($new_file);

  //  return $new_file;
}

/** Implements hook_views_api().
 * @return array
 */
function imagefield_crop_views_api() {
  return array(
    'api' => views_api_version(),
    'path' => drupal_get_path('module', 'imagefield_crop') . '/includes',
  );
}

/**
 * Implements hook_theme().
 * @return array
 */
function imagefield_crop_theme() {
  $items = array();
  $extra = array(
    'file' => 'theme.inc',
    'path' => drupal_get_path('module', 'imagefield_crop') . '/theme',
  );
  $items['imagefield_crop_widget'] = array(
    'render element' => 'element',
  ) + $extra;
  $items['imagefield_crop_preview'] = array(
    'render element' => 'element',
  ) + $extra;
  $items['imagefield_crop_preset_list'] = array(
    'variables' => array(
      'presets' => NULL,
    ),
  ) + $extra;
  return $items;
}

/**
 * Implements hook_menu().
 * @return array
 */
function imagefield_crop_menu() {
  $items = array();
  $items['admin/config/media/imagefield-crop-preset-list'] = array(
    'title' => 'Preset List',
    'page callback' => 'imagefield_crop_preset_list',
    'page arguments' => array(),
    'access arguments' => array(
      'access administration pages',
    ),
    'type' => MENU_NORMAL_ITEM,
  );
  $items['admin/config/media/imagefield-crop-preset-list/add'] = array(
    'title' => 'Add preset',
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'imagefield_crop_preset_form',
    ),
    'access arguments' => array(
      'access administration pages',
    ),
    'type' => MENU_LOCAL_ACTION,
  );
  $items['admin/config/media/imagefield-crop-preset-list/%imagefield_crop_preset/edit'] = array(
    'title' => 'Edit preset',
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'imagefield_crop_preset_form',
      4,
    ),
    'access arguments' => array(
      'access administration pages',
    ),
    'type' => MENU_CALLBACK,
  );
  $items['admin/config/media/imagefield-crop-preset-list/%imagefield_crop_preset/delete'] = array(
    'title' => 'Edit preset',
    'page callback' => 'imagefield_crop_preset_delete',
    'page arguments' => array(
      4,
    ),
    'access arguments' => array(
      'access administration pages',
    ),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
 * Implements menu callback imagefield_crop_preset_list().
 * @return string
 */
function imagefield_crop_preset_list() {
  $presets = db_select('imagefield_crop_preset', 'icpr')
    ->fields('icpr', array(
    'pid',
    'name',
  ))
    ->execute()
    ->fetchAllKeyed();
  return theme('imagefield_crop_preset_list', array(
    'presets' => $presets,
  ));
}

/**
 * Implements form builder imagefield_crop_preset_form().
 * @param $form
 * @param $form_state
 * @param $preset
 * @return array
 */
function imagefield_crop_preset_form($form, $form_state, $preset = array()) {
  $form = array();
  if (!empty($preset)) {
    $form_state['preset'] = $preset;
    if (empty($preset->label)) {
      $preset->label = $preset->name;
    }
  }
  $form['label'] = array(
    '#type' => 'textfield',
    '#title' => t('Label'),
    '#default_value' => !empty($preset->label) ? $preset->label : '',
    '#required' => TRUE,
  );
  if (empty($preset)) {
    $form['name'] = array(
      '#type' => 'machine_name',
      '#description' => t('The name is used in URLs for generated images. Use only lowercase alphanumeric characters, underscores (_), and hyphens (-).'),
      '#size' => '64',
      '#required' => TRUE,
      '#machine_name' => array(
        'exists' => 'imagefield_crop_preset_load_by_name',
        'source' => array(
          'label',
        ),
        'replace_pattern' => '[^0-9a-z_\\-]',
        'error' => t('Please only use lowercase alphanumeric characters, underscores (_), and hyphens (-) for preset names.'),
      ),
    );
  }
  $form['preset'] = array(
    '#type' => 'container',
    '#markup' => '',
    '#tree' => TRUE,
  );
  $form['preset']['crop-type'] = array(
    '#type' => 'radios',
    '#default_value' => !empty($preset->data['crop-type']) ? $preset->data['crop-type'] : 'resolution',
    '#options' => array(
      'resolution' => t('Fixed resolution'),
      'ratio' => t('Ratio'),
    ),
    '#title' => t('Crop type'),
  );

  // Resolution settings.
  $form['preset']['resolution'] = array(
    '#tree' => TRUE,
    '#title' => t('The resolution to crop the image onto'),
    '#theme_wrappers' => array(
      'form_element',
    ),
    '#description' => t('The output resolution of the cropped image, expressed as WIDTHxHEIGHT (e.g. 640x480). Leave blank to skip rescale after cropping. Note: output resolution must be defined in order to present a dynamic preview.'),
    '#markup' => '',
    '#states' => array(
      'visible' => array(
        'input[name="preset[crop-type]"]' => array(
          'value' => 'resolution',
        ),
      ),
      'invisible' => array(
        'input[name="preset[crop-type]"]' => array(
          'value' => 'ratio',
        ),
      ),
    ),
  );
  $form['preset']['resolution']['width'] = array(
    '#type' => 'textfield',
    '#default_value' => !empty($preset->data['resolution']['width']) ? $preset->data['resolution']['width'] : '',
    '#size' => 5,
    '#maxlength' => 5,
    '#field_suffix' => ' x ',
    '#theme_wrappers' => array(),
  );
  $form['preset']['resolution']['height'] = array(
    '#type' => 'textfield',
    '#default_value' => !empty($preset->data['resolution']['height']) ? $preset->data['resolution']['height'] : '',
    '#size' => 5,
    '#maxlength' => 5,
    '#field_suffix' => ' ' . t('pixels'),
    '#theme_wrappers' => array(),
  );
  $form['preset']['ratio'] = array(
    '#type' => 'container',
    '#title' => t('Custom ratio'),
    '#theme_wrappers' => array(
      'form_element',
    ),
    '#description' => t('Ratio for crop area. For example 4:3 or 16:9 as width to height.'),
    '#markup' => '',
    '#states' => array(
      'visible' => array(
        'input[name="preset[crop-type]"]' => array(
          'value' => 'ratio',
        ),
      ),
      'invisible' => array(
        'input[name="preset[crop-type]"]' => array(
          'value' => 'resolution',
        ),
      ),
    ),
  );
  $form['preset']['ratio']['width'] = array(
    '#type' => 'textfield',
    '#default_value' => !empty($preset->data['ratio']['width']) ? $preset->data['ratio']['width'] : '',
    '#size' => 5,
    '#maxlength' => 5,
    '#field_suffix' => ' x ',
    '#theme_wrappers' => array(),
  );
  $form['preset']['ratio']['height'] = array(
    '#type' => 'textfield',
    '#default_value' => !empty($preset->data['ratio']['height']) ? $preset->data['ratio']['height'] : '',
    '#size' => 5,
    '#maxlength' => 5,
    '#field_suffix' => ' ' . t('pixels'),
    '#theme_wrappers' => array(),
  );
  $form['preset']['min-resolution'] = array(
    '#type' => 'container',
    '#title' => t('Minimal result resolution'),
    '#theme_wrappers' => array(
      'form_element',
    ),
    '#description' => t('Minimal resolution of result image.(e.g. 640x480).'),
    '#markup' => '',
    '#states' => array(
      'visible' => array(
        'input[name="preset[crop-type]"]' => array(
          'value' => 'ratio',
        ),
      ),
      'invisible' => array(
        'input[name="preset[crop-type]"]' => array(
          'value' => 'resolution',
        ),
      ),
    ),
  );
  $form['preset']['min-resolution']['width'] = array(
    '#type' => 'textfield',
    '#default_value' => !empty($preset->data['min-resolution']['width']) ? $preset->data['min-resolution']['width'] : '',
    '#size' => 5,
    '#maxlength' => 5,
    '#field_suffix' => ' x ',
    '#theme_wrappers' => array(),
  );
  $form['preset']['min-resolution']['height'] = array(
    '#type' => 'textfield',
    '#default_value' => !empty($preset->data['min-resolution']['height']) ? $preset->data['min-resolution']['height'] : '',
    '#size' => 5,
    '#maxlength' => 5,
    '#field_suffix' => ' ' . t('pixels'),
    '#theme_wrappers' => array(),
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
    '#submit' => array(
      'imagefield_crop_preset_form_submit',
    ),
  );
  return $form;
}
function imagefield_crop_preset_form_submit($form, &$form_state) {
  $l = l('preset list', 'admin/config/media/imagefield-crop-preset-list');
  if (!empty($form_state['preset'])) {
    $record = $form_state['preset'];
    $record->name = $form_state['values']['preset_name'];
    $record->data = $form_state['values']['preset'];
    drupal_write_record('imagefield_crop_preset', $record, 'pid');
    drupal_set_message(t('Preset successful updated. You can go to !lpreset', array(
      '!lpreset' => $l,
    )), 'status');
  }
  else {
    $record['name'] = $form_state['values']['preset_name'];
    $record['data'] = $form_state['values']['preset'];
    drupal_write_record('imagefield_crop_preset', $record);
    drupal_set_message(t('Preset successful added. You can go to !lpreset', array(
      '!lpreset' => $l,
    )), 'status');
  }
}

/**
 * Implements hook_load().
 * @param $pid
 * @return mixed
 */
function imagefield_crop_preset_load($pid) {
  $presets = imagefield_crop_presets_load_multiple(array(
    $pid,
  ));
  return reset($presets);
}

/**
 * Implements hook_load().
 * @param $pid
 * @return mixed
 */
function imagefield_crop_preset_load_by_name($name) {
  $presets = imagefield_crop_presets_load_multiple_by_name(array(
    $name,
  ));
  return reset($presets);
}

/**
 * Helper function imagefield_crop_presets_load_multiple().
 * Used to load multiple presets.
 * @param $pids
 * @return mixed
 */
function imagefield_crop_presets_load_multiple($pids = array()) {
  $query = db_select('imagefield_crop_preset', 'icpr')
    ->fields('icpr');
  if (!empty($pids)) {
    $query
      ->condition('pid', $pids);
  }
  $result = $query
    ->execute()
    ->fetchAllAssoc('pid');
  foreach ($result as &$preset) {
    $preset->data = unserialize($preset->data);
  }
  return $result;
}

/**
 * Helper function imagefield_crop_presets_load_multiple_by_name().
 * Used to load multiple presets.
 * @param $pids
 * @return mixed
 */
function imagefield_crop_presets_load_multiple_by_name($names = array()) {
  $query = db_select('imagefield_crop_preset', 'icpr')
    ->fields('icpr');
  if (!empty($names)) {
    $query
      ->condition('name', $names, 'IN');
  }
  $result = $query
    ->execute()
    ->fetchAllAssoc('pid');
  foreach ($result as &$preset) {
    $preset->data = unserialize($preset->data);
  }
  return $result;
}

/**
 * Helper function imagefield_crop_variants_load_multiple().
 * Used to load multiple variants.
 * @param $pids
 * @return mixed
 */
function imagefield_crop_variants_load_multiple($fid = '', $vid = '', $pids = array()) {
  $query = db_select('imagefield_crop_variants', 'icv')
    ->fields('icv');
  if (!empty($fid)) {
    $query
      ->condition('source_fid', $fid);
  }
  if (!empty($pids)) {
    $query
      ->condition('pid', $pids);
  }
  if (!empty($vid)) {
    $query
      ->condition('vid', $vid);
  }
  $args = func_num_args();
  if (!$args) {
    $result = $query
      ->execute()
      ->fetchAllAssoc('cvid');
  }
  else {
    $result = $query
      ->execute()
      ->fetchAllAssoc('pid');
  }
  foreach ($result as &$variant) {
    $variant->data = unserialize($variant->data);
  }
  return $result;
}

/**
 * Helper function imagefield_crop_variants_delete_multiple().
 * Used to load multiple variants.
 * @param $pids
 * @return mixed
 */
function imagefield_crop_variants_delete_multiple($cvids = array(), $fid = '', $vid = '', $pids = array()) {
  $query = db_delete('imagefield_crop_variants');
  if (!empty($fid)) {
    $query
      ->condition('source_fid', $fid);
  }
  if (!empty($cvids)) {
    $query
      ->condition('pid', $pids);
  }
  if (!empty($pids)) {
    $query
      ->condition('pid', $pids);
  }
  if (!empty($vid)) {
    $query
      ->condition('vid', $vid);
  }
  $result = $query
    ->execute();
  return $result;
}

/**
 * Menu callback -- ask for confirmation of presset deletion
 */
function imagefield_crop_preset_delete($preset) {
  $presets_used = array();
  foreach (field_info_instances() as $entity) {
    foreach ($entity as $fields) {
      foreach ($fields as $field_name => $instance) {
        if ($instance['widget']['module'] == 'imagefield_crop') {
          $presets_used += array_fill_keys(array_keys($instance['widget']['settings']['presets']), $instance['field_name']);
        }
      }
    }
  }
  if (in_array($preset->pid, array_keys($presets_used))) {
    drupal_set_message(t('Preset is used in field !field_name. ' . l('Back to preset list', 'admin/config/media/imagefield-crop-preset-list'), array(
      '!field_name' => $presets_used[$preset->pid],
    )));
    return array();
  }
  else {
    return drupal_get_form('imagefield_crop_preset_delete_confirm', $preset);
  }
}

/**
 * Implements form builder imagefield_crop_preset_delete_confirm().
 * @param $form
 * @param $form_state
 * @param $preset
 * @return mixed
 */
function imagefield_crop_preset_delete_confirm($form, &$form_state, $preset) {
  $form['#preset'] = $preset;
  return confirm_form($form, t('Are you sure you want to delete %title?', array(
    '%title' => $preset->name,
  )), 'admin/config/media/imagefield-crop-preset-list/' . $preset->pid . '/edit', t('Are you sure you want to delete %title?', array(
    '%title' => $preset->name,
  )) . '<br />' . t('This action cannot be undone.'), t('Delete'), t('Cancel'));
}

/**
 * Execute preset deletion
 */
function imagefield_crop_preset_delete_confirm_submit($form, &$form_state) {
  if ($form_state['values']['confirm']) {
    $preset = $form['#preset'];
    db_delete('imagefield_crop_preset')
      ->condition('pid', $preset->pid)
      ->execute();
    drupal_set_message(t('The entity %title (ID %id) has been deleted', array(
      '%title' => $preset->name,
      '%id' => $preset->pid,
    )));
    $form_state['redirect'] = '/admin/config/media/imagefield-crop-preset-list';
  }
}

/**
 * Helper function imagefield_crop_fill_cropconfig().
 * Fill new cropconfig array
 * @param $item
 * @param $crop_area_height
 * @param $crop_area_width
 * @return array
 */
function imagefield_crop_fill_cropconfig($preset, $crop_area_height, $crop_area_width) {
  return array(
    'cropbox_x' => isset($preset->cropbox_x) ? $preset->cropbox_x : 0,
    'cropbox_y' => isset($preset->cropbox_y) ? $preset->cropbox_y : 0,
    'cropbox_height' => isset($preset->cropbox_height) ? $preset->cropbox_height : $crop_area_height,
    'cropbox_width' => isset($preset->cropbox_width) ? $preset->cropbox_width : $crop_area_width,
    'cropbox_changed' => isset($preset->cropbox_changed) ? $preset->cropbox_changed : 0,
  );
}

/**
 * Helper func imagefield_crop_presize().
 * Used to presize image
 * @param $img_info
 * @param $w
 * @param $h
 */
function imagefield_crop_presize(&$img_info, $w, $h) {
  $nw = $img_info['width'];
  $nh = $img_info['height'];
  if ($nw > $w && $w > 0) {
    $nw = $w;
    $nh = $w / $img_info['width'] * $img_info['height'];
  }
  if ($nh > $h && $h > 0) {
    $nh = $h;
    $nw = $h / $img_info['height'] * $img_info['width'];
  }
  $img_info['xscale'] = $img_info['width'] / $nw;
  $img_info['yscale'] = $img_info['height'] / $nh;
  $img_info['height'] = $nh;
  $img_info['width'] = $nw;
}

Functions

Namesort descending Description
entity_metadata_field_imagefield_crop_callback Additional callback to adapt the property info for image fields. This callback gets invoked after entity_metadata_field_file_callback().
imagefield_crop_create_copy Creates a copy of the file.
imagefield_crop_field_delete Implements hook_field_delete().
imagefield_crop_field_delete_revision Implements hook_field_delete_revision().
imagefield_crop_field_formatter_info Implements hook_field_formatter_info().
imagefield_crop_field_formatter_info_alter Implements hook__crop_field_formatter_info_alter().
imagefield_crop_field_formatter_settings_form Implements hook_field_formatter_settings_form().
imagefield_crop_field_formatter_settings_summary Implements hook_field_formatter_settings_summary().
imagefield_crop_field_formatter_view Implementation hook__field_formatter_view().
imagefield_crop_field_info Implements hook_field_info().
imagefield_crop_field_insert Implements hook_field_insert().
imagefield_crop_field_instance_settings_form Implements hook_field_instance_settings_form().
imagefield_crop_field_is_empty Implements hook_field_is_empty().
imagefield_crop_field_load Implements hook_field_load().
imagefield_crop_field_prepare_view Implements hook_field_prepare_view().
imagefield_crop_field_presave Implements hook_field_presave().
imagefield_crop_field_settings_form Implements hook_field_settings_form().
imagefield_crop_field_update Implements hook_field_update().
imagefield_crop_field_widget_form Implements hook_field_widget_form().
imagefield_crop_field_widget_info Implements hook_field_widget_info().
imagefield_crop_field_widget_settings_form Implements hook_field_widget_settings_form().
imagefield_crop_fill_cropconfig Helper function imagefield_crop_fill_cropconfig(). Fill new cropconfig array
imagefield_crop_get_renderable Implements property callback imagefield_crop_get_renderable().
imagefield_crop_menu Implements hook_menu().
imagefield_crop_presets_load_multiple Helper function imagefield_crop_presets_load_multiple(). Used to load multiple presets.
imagefield_crop_presets_load_multiple_by_name Helper function imagefield_crop_presets_load_multiple_by_name(). Used to load multiple presets.
imagefield_crop_preset_delete Menu callback -- ask for confirmation of presset deletion
imagefield_crop_preset_delete_confirm Implements form builder imagefield_crop_preset_delete_confirm().
imagefield_crop_preset_delete_confirm_submit Execute preset deletion
imagefield_crop_preset_form Implements form builder imagefield_crop_preset_form().
imagefield_crop_preset_form_submit
imagefield_crop_preset_list Implements menu callback imagefield_crop_preset_list().
imagefield_crop_preset_load Implements hook_load().
imagefield_crop_preset_load_by_name Implements hook_load().
imagefield_crop_presize Helper func imagefield_crop_presize(). Used to presize image
imagefield_crop_theme Implements hook_theme().
imagefield_crop_upload_validate Validate function for images to be cropped. Returns an error if output resolution for field is set, but file is smaller.
imagefield_crop_value_callback Element value callback. Used to set crop area to image size, if image is smaller then output resolution, but validation isn't enabled.
imagefield_crop_variants_delete_multiple Helper function imagefield_crop_variants_delete_multiple(). Used to load multiple variants.
imagefield_crop_variants_load_multiple Helper function imagefield_crop_variants_load_multiple(). Used to load multiple variants.
imagefield_crop_views_api Implements hook_views_api().
imagefield_crop_widget_preview_process Impletement imagefield_crop_widget_preview_process().
imagefield_crop_widget_process An element #process callback for the imagefield_crop field type.
_imagefield_crop_file_to_crop
_imagefield_crop_resize Crop the image and resize it