You are here

function _media_filter_add_file_usage_from_fields in D7 Media 7

Add file usage from file references in an entity's text fields.

2 calls to _media_filter_add_file_usage_from_fields()
media_field_attach_insert in includes/media.filter.inc
Implements hook_field_attach_insert().
media_field_attach_update in includes/media.filter.inc
Implements hook_field_attach_update().

File

includes/media.filter.inc, line 47
Functions related to the WYSIWYG editor and the media input filter.

Code

function _media_filter_add_file_usage_from_fields($entity_type, $entity) {

  // Track the total usage for files from all fields combined.
  $entity_files = media_entity_field_count_files($entity_type, $entity);
  list($entity_id, $entity_vid, $entity_bundle) = entity_extract_ids($entity_type, $entity);

  // When an entity has revisions and then is saved again NOT as new version the
  // previous revision of the entity has be loaded to get the last known good
  // count of files. The saved data is compared against the last version
  // so that a correct file count can be created for that (the current) version
  // id. This code may assume some things about entities that are only true for
  // node objects. This should be reviewed.
  // @TODO this conditional can probably be condensed
  if (empty($entity->revision) && empty($entity->old_vid) && empty($entity->is_new) && !empty($entity->original)) {
    $old_files = media_entity_field_count_files($entity_type, $entity->original);
    foreach ($old_files as $fid => $old_file_count) {

      // Were there more files on the node just prior to saving?
      if (empty($entity_files[$fid])) {
        $entity_files[$fid] = 0;
      }
      if ($old_file_count > $entity_files[$fid]) {
        $deprecate = $old_file_count - $entity_files[$fid];

        // Now deprecate this usage
        if ($file = file_load($fid)) {
          file_usage_delete($file, 'media', $entity_type, $entity_id, $deprecate);
        }

        // Usage is deleted, nothing more to do with this file
        unset($entity_files[$fid]);
      }
      elseif ($entity_files[$fid] == $old_file_count) {
        unset($entity_files[$fid]);
      }
      else {

        // We just need to adjust what the file count will account for the new
        // images that have been added since the increment process below will
        // just add these additional ones in
        $entity_files[$fid] = $entity_files[$fid] - $old_file_count;
      }
    }
  }

  // Each entity revision counts for file usage. If versions are not enabled
  // the file_usage table will have no entries for this because of the delete
  // query above.
  foreach ($entity_files as $fid => $entity_count) {
    if ($file = file_load($fid)) {
      file_usage_add($file, 'media', $entity_type, $entity_id, $entity_count);
    }
  }
}