You are here

function file_entity_uuid_presave in Universally Unique IDentifier 7

Implements hook_entity_uuid_presave().

Related topics

File

./uuid.core.inc, line 170
Implementation of UUID hooks for all core modules.

Code

function file_entity_uuid_presave(&$entity, $entity_type) {
  if ($entity_type == 'file') {

    // entity_make_entity_local() may have unset fid, add back if necessary.
    if (!isset($entity->fid)) {
      $entity->fid = NULL;
    }
    entity_property_uuid_to_id($entity, 'user', 'uid');

    // Write the new file to the local filesystem.
    if (isset($entity->file_contents) && !empty($entity->filesize)) {

      // Don't try to write it if it uses a stream wrapper that isn't writeable
      // (for example, if it is a remotely-hosted video).
      $scheme = file_uri_scheme($entity->uri);
      $wrappers = file_get_stream_wrappers(STREAM_WRAPPERS_WRITE);
      if (empty($wrappers[$scheme])) {
        return;
      }

      // Check for an existing file with the same URI.
      $existing_files = file_load_multiple(array(), array(
        'uri' => $entity->uri,
      ));
      $existing = (object) array(
        'uri' => NULL,
        'uuid' => NULL,
      );
      if (count($existing_files)) {
        $existing = reset($existing_files);
      }

      // If this is a new file and there is an existing file with the same URI,
      // but a different uuid then rename this file.
      if ($entity->is_new && $entity->uri == $existing->uri && $entity->uuid != $existing->uuid) {
        $uri = $entity->uri;
        $replace = FILE_EXISTS_RENAME;
      }
      elseif ($entity->uri == $existing->uri && $entity->uuid != $existing->uuid) {
        $file = file_load($entity->fid);
        $uri = $file->uri;
        $replace = FILE_EXISTS_REPLACE;
      }
      else {
        $uri = $entity->uri;
        $replace = FILE_EXISTS_REPLACE;
      }
      $directory = drupal_dirname($uri);
      if (!empty($directory) && file_prepare_directory($directory, FILE_CREATE_DIRECTORY)) {
        $entity->uri = file_unmanaged_save_data(base64_decode($entity->file_contents), $uri, $replace);
      }
    }
  }
}