You are here

function files_undo_remove_entity_presave in Files undo remove 7

Implements hook_entity_presave().

File

./files_undo_remove.module, line 73
Files undo remove.

Code

function files_undo_remove_entity_presave($entity, $entity_type) {
  $clear_cache = FALSE;
  list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
  $instances = field_info_instances($entity_type, $bundle);
  foreach ($instances as $field_name => $field_instance) {

    // Make sure the field exists.
    if (!isset($entity->{$field_name})) {
      continue;
    }

    // Check if the modules are file, image or linkimage.
    if (in_array($field_instance['widget']['module'], array(
      'image',
      'file',
      'linkimagefield',
    ))) {
      foreach ($entity->{$field_name} as $language => $items) {
        foreach ($items as $delta => $item) {

          // Check if there's a remove_state key on the file values.
          if (isset($item['remove_state']) && $item['remove_state']) {
            $file = file_load($item['fid']);

            // @todo we'll probably have to do this different, like checking
            // usage, dropping it by one and removing if none is found anymore.
            // For now, we force the file to delete.
            file_delete($file, TRUE);

            // Remove the item from the entity.
            unset($entity->{$field_name}[$language][$delta]);
          }
        }
        $entity->{$field_name}[$language] = array_values($entity->{$field_name}[$language]);
      }
    }
  }
  if ($clear_cache) {

    // @todo check with entity cache module.
    cache_clear_all('field:' . $entity_type . ':' . $id, 'cache_field');
  }
}