You are here

function fe_paths_entity_presave in File Entity Paths 7.2

Implements hook_file_presave().

File

./fe_paths.module, line 130
Contains functions for the File Entity Paths module.

Code

function fe_paths_entity_presave($entity, $type) {
  if ($type == 'file') {

    // Store original filename in the database.
    if (empty($entity->origname)) {
      $entity->origname = $entity->filename;
    }
    if (!isset($entity->fe_paths_processed) && isset($entity->fid)) {
      drupal_register_shutdown_function('fe_paths_file_process', $entity->fid, $entity, $type);
      $entity->fe_paths_processed = TRUE;
    }
  }

  // Only passed to process, if entity was not processed before, and
  // and the entity is fieldable.
  if (!isset($entity->fe_paths_processed) && array_key_exists($type, fe_paths_get_fieldable_entities())) {
    $entity_info = entity_get_info($type);

    // Get all fields of the saved entity.
    $bundle = NULL;
    if (!empty($entity_info['entity keys']['bundle'])) {
      $bundle = $entity->{$entity_info['entity keys']['bundle']};
    }
    else {
      $bundle = $type;
    }
    $fields = field_info_instances($type, $bundle);

    // Get all allowed widgets, which need to be processed
    $allowed_types = fe_paths_get_allowed_widget_types($entity);

    // Let's collect all processable fields, and add it to register_shutdown
    // for processing.
    foreach ($fields as $field) {
      if (in_array($field['widget']['type'], $allowed_types) && ($files = field_get_items($type, $entity, $field['field_name']))) {
        foreach ($files as $file) {

          // Just for testing, in _registershutdown hard to debug.

          //fe_paths_file_process(file_load($file['fid']), $entity, $type);
          drupal_register_shutdown_function('fe_paths_file_process', $file['fid'], $entity, $type, $field['field_name']);
        }
      }

      // Searching in textfields for possibly embed files by media wysiwsg.
      if (!empty($field['settings']['text_processing']) && ($field_items = field_get_items($type, $entity, $field['field_name']))) {
        foreach ($field_items as $field_item) {
          preg_match_all('/\\[\\[.*?\\]\\]/s', $field_item['value'], $matches);
          foreach ($matches[0] as $tag) {
            $tag = str_replace(array(
              '[[',
              ']]',
            ), '', $tag);
            $tag_info = drupal_json_decode($tag);
            if (isset($tag_info['fid'])) {
              drupal_register_shutdown_function('fe_paths_file_process', $tag_info['fid'], $entity, $type, $field['field_name']);
            }
          }
        }
      }
    }
    $entity->fe_paths_processed = TRUE;
  }
}