You are here

filefield_paths.module in File (Field) Paths 6.2

Contains core functions for the FileField Paths module.

File

filefield_paths.module
View source
<?php

/**
 * @file
 * Contains core functions for the FileField Paths module.
 */
define('FILEFIELD_PATHS_API', 2);

/**
 * Implements hook_init().
 */
function filefield_paths_init() {

  // Load all module dependant includes.
  foreach (module_list() as $module) {
    if (file_exists($file = dirname(__FILE__) . "/modules/{$module}.inc")) {
      require_once $file;
    }
  }

  // Load all other includes.
  foreach (_filefield_paths_includes() as $include) {
    if (file_exists($file = dirname(__FILE__) . "/includes/{$include}.inc") || file_exists($file = dirname(__FILE__) . "/includes/{$include}/{$include}.inc")) {
      require_once $file;
    }
  }
}

/**
 *
 */
function _filefield_paths_includes() {
  static $includes = array();
  if (empty($includes)) {
    foreach (scandir(dirname(__FILE__) . '/includes') as $file) {
      $match = array();
      if (preg_match('/(.*?)\\.inc/', $file, $match) || file_exists(dirname(__FILE__) . "/includes/{$file}/{$file}.inc")) {
        $includes[] = isset($match[1]) ? $match[1] : $file;
      }
    }
  }
  return $includes;
}

/**
 * Implements hook_widget_settings_alter().
 */
function filefield_paths_widget_settings_alter(&$settings, $op, $widget) {
  if (_filefield_paths_module_supported($widget['module'])) {
    $fields = module_invoke_all('filefield_paths_field_settings');
    $options = module_invoke_all('filefield_paths_form_options', $widget);
    $field_options = module_invoke_all('filefield_paths_field_options');
    switch ($op) {
      case 'form':

        // FileField Paths FAPI defaults.
        $fapi = array(
          '#type' => 'textfield',
          '#maxlength' => '512',
        );

        // Build Fields.
        $count = 0;
        foreach ($fields as $key => $field) {
          $settings['path_settings'][$key] = array_merge($field['fapi'], $fapi, array(
            '#default_value' => isset($widget[$key]) ? $widget[$key] : $field['fapi']['#default_value'],
            '#attributes' => array(
              'class' => "filefield_paths filefield_paths-{$key}",
            ),
            '#weight' => isset($field['fapi']['#weight']) ? $field['fapi']['#weight'] + $count * 2 : $count * 2,
          ));

          // Build Field options.
          if (count($field_options) > 0) {
            $settings['path_settings']["{$key}_options-wrapper"] = array(
              '#type' => 'fieldset',
              '#attributes' => array(
                'class' => "filefield_paths filefield_paths_fieldset filefield_paths-{$key}",
              ),
              '#weight' => $count * 2 + 1,
            );
            $settings['path_settings']["{$key}_options-wrapper"]["{$key}_options"] = array(
              '#title' => t('!field options', array(
                '!field' => $field['fapi']['#title'],
              )),
              '#type' => 'checkboxes',
              '#options' => $field_options,
              '#default_value' => $widget["{$key}_options"],
            );
          }
          $count++;
        }

        // Attach additional options.
        $settings['path_settings']['options'] = array_merge($options, array(
          '#weight' => ($count + 1) * 2,
        ));

        // Token tree.
        // To prevent un-usable 'field' tokens (text, number, etc), FileField
        // Paths defines a 'filefield_paths' token type for internal use, which
        // in turn invokes hook_filefield_paths_tokens() to allow other modules
        // to include there own tokens.
        $settings['path_settings']['token_tree'] = array(
          '#value' => theme('token_tree', array(
            'filefield_paths',
            'node',
            'user',
            'global',
          )),
          '#weight' => ($count + 1) * 2 + 1,
        );
        break;
      case 'save':
        $settings = array_merge($settings, array_diff(array_keys($fields), $settings), array_keys($options));
        foreach (array_keys($fields) as $field) {
          $settings[] = "{$field}_options";
        }
        break;
    }
  }
  foreach (_filefield_paths_includes() as $include) {
    if (function_exists($function = "_filefield_paths_include_{$include}_widget_settings_alter")) {
      $function($settings, $op, $widget);
    }
  }
}

/**
 *
 */
function _filefield_paths_module_supported($module) {
  if (is_array($api = module_invoke($module, 'filefield_paths_api'))) {
    return $api['api'] == FILEFIELD_PATHS_API;
  }
  return FALSE;
}

/**
 * Implements hook_nodeapi().
 */
function filefield_paths_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  if (function_exists($function = "filefield_paths_node_{$op}")) {
    $function($node);
  }
}

/**
 * Implements hook_node_insert().
 */
function filefield_paths_node_insert(&$node) {
  filefield_paths_node_update($node);
}

/**
 * Implements hook_node_update().
 */
function filefield_paths_node_update(&$node) {
  $files = array();
  $content_type = content_types($node->type);
  foreach ($content_type['fields'] as $field) {
    if ($field['type'] == 'filefield' && is_array($node->{$field}['field_name'])) {
      foreach ($node->{$field['field_name']} as $count => &$file) {
        if (is_array($file) && !empty($file['filepath']) && _filefield_paths_process_file_check($file, $field)) {
          filefield_paths_process_file($file, $field['widget'], $node);
        }
      }
    }
  }

  //node_save($node);

  //_content_field_invoke_default('update', $node);

  //    // Re-write node entry if required.
  //    if ($update->node == TRUE) {
  //      global $user;
  //
  //      drupal_write_record('node', $node, 'nid');
  //      _node_save_revision($node, $user->uid, 'vid');
  //    }
  //
  //    // Re-write cck fields.
  //    if (module_exists('content')) {
  //      _content_field_invoke_default('update', $node);
  //      cache_clear_all('content:'. $node->nid . ':' . $node->vid, content_cache_tablename());
  //    }
}

/**
 * Helper function; Invokes hook_filefield_paths_process_file_check().
 */
function _filefield_paths_process_file_check($file, $field) {
  foreach (module_implements('filefield_paths_file_check') as $module) {
    if (module_invoke($module, 'filefield_paths_file_check', $file, $field) == TRUE) {
      return TRUE;
    }
  }
  return !$file['status'];
}

/**
 * Process FileField Paths settings, rename and move files.
 */
function filefield_paths_process_file(&$file, $settings, &$node) {
  $user = user_load($node->uid);
  $source = $file['filepath'];
  $fields = module_invoke_all('filefield_paths_field_settings');
  foreach (array_keys($fields) as $field) {
    $file[$fields[$field]['key']] = token_replace_multiple($settings[$field], array(
      'global' => NULL,
      'node' => $node,
      'filefield_paths' => array(
        $file,
      ),
      'user' => $user,
    ));

    // Invoke filefield_paths_postprocess_field().
    foreach (module_implements('filefield_paths_field_postprocess') as $module) {
      $function = "{$module}_filefield_paths_field_postprocess";
      $function(&$file[$fields[$field]['key']], $field, $settings["{$field}_options"]);
    }
  }

  // Prepare filepath.
  $file['filepath'] = !empty($file['filepath']) ? "{$file['filepath']}/{$file['filename']}" : $file['filename'];
  $file['filepath'] = file_directory_path() . "/{$file['filepath']}";

  // Finalize file if necessary.

  //if ($file['filepath'] != $source) {
  _filefield_paths_file_move($source, $file);

  // Invoke filefield_paths_postprocess_file().
  foreach (module_implements('filefield_paths_file_postprocess') as $module) {
    $function = "{$module}_filefield_paths_file_postprocess";
    $function($source, $file, &$node, $settings);
  }

  //}

  //    // Finalize files if necessary
  //    if (dirname($file['filepath']['new']) != dirname($file['field']['filepath']) || $file['filename']['new'] != $file['field']['filename']) {
  //      if (filefield_paths_file_move($file)) {
  //
  //        // Store new filename in file Array
  //        $file['field']['filename'] = $file['filename']['new'];
  //      }
  //    }
  //  }
}

/**
 * Move file and update its database record.
 */
function _filefield_paths_file_move($source, &$file) {

  // Backup messages.
  $messages = $_SESSION['messages'];

  // Create destination directories.
  $directories = array();
  foreach (explode('/', dirname($file['filepath'])) as $directory) {
    $directories[] = $directory;
    $path = file_create_path(implode($directories, '/'));
    if (!file_check_directory($path, FILE_CREATE_DIRECTORY)) {
      watchdog('filefield_paths', 'FileField Paths failed to create directory (%d).', array(
        '%d' => $path,
      ), WATCHDOG_ERROR);

      // Restore message.
      $_SESSION['messages'] = $messages;
      return FALSE;
    }
  }

  // Restore message.
  $_SESSION['messages'] = $messages;

  // Move file.
  if (!file_move($source, $file['filepath'])) {
    watchdog('filefield_paths', 'FileField Paths failed to move file (%o) to (%n).', array(
      '%o' => $source,
      '%n' => $file['filepath'],
    ), WATCHDOG_ERROR);
    return FALSE;
  }

  // Update database.
  drupal_write_record('files', $file, array(
    'fid',
  ));
  return TRUE;
}

Functions

Namesort descending Description
filefield_paths_init Implements hook_init().
filefield_paths_nodeapi Implements hook_nodeapi().
filefield_paths_node_insert Implements hook_node_insert().
filefield_paths_node_update Implements hook_node_update().
filefield_paths_process_file Process FileField Paths settings, rename and move files.
filefield_paths_widget_settings_alter Implements hook_widget_settings_alter().
_filefield_paths_file_move Move file and update its database record.
_filefield_paths_includes
_filefield_paths_module_supported
_filefield_paths_process_file_check Helper function; Invokes hook_filefield_paths_process_file_check().

Constants

Namesort descending Description
FILEFIELD_PATHS_API @file Contains core functions for the FileField Paths module.