Index: filefield_paths.module
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/filefield_paths/filefield_paths.module,v
retrieving revision 1.19.2.29
diff -u -r1.19.2.29 filefield_paths.module
--- filefield_paths.module	3 Jul 2009 07:06:50 -0000	1.19.2.29
+++ filefield_paths.module	6 Nov 2009 12:48:51 -0000
@@ -1,37 +1,37 @@
-<?php
+<?php
 // $Id: filefield_paths.module,v 1.19.2.29 2009/07/03 07:06:50 deciphered Exp $
-
-/**
- * @file
- * Adds extra functionality to FileFields Path settings.
- */
-
-/**
- * Implementation of hook_filefield_paths_field_settings().
- */
-function filefield_paths_filefield_paths_field_settings() {
-  return array(
-    'file_path' => array(
-      'title' => 'File path',
-      'sql' => 'filepath',
-    ),
-
-    'file_name' => array(
-      'title' => 'File name',
-      'sql' => 'filename',
-
-      'form' => array(
-        'file_name' => array(
-          '#type' => 'textfield',
-          '#title' => t('File name'),
+
+/**
+ * @file
+ * Adds extra functionality to FileFields Path settings.
+ */
+
+/**
+ * Implementation of hook_filefield_paths_field_settings().
+ */
+function filefield_paths_filefield_paths_field_settings() {
+  return array(
+    'file_path' => array(
+      'title' => 'File path',
+      'sql' => 'filepath',
+    ),
+
+    'file_name' => array(
+      'title' => 'File name',
+      'sql' => 'filename',
+
+      'form' => array(
+        'file_name' => array(
+          '#type' => 'textfield',
+          '#title' => t('File name'),
           '#default_value' => '[filefield-onlyname-original].[filefield-extension-original]',
-        )
-      ),
-    )
-  );
-}
-
-/**
+        )
+      ),
+    )
+  );
+}
+
+/**
  * Implementation of hook_theme().
  */
 function filefield_paths_theme() {
@@ -45,11 +45,11 @@
 function theme_filefield_paths_token_help($prefix = '[', $suffix = ']') {
   token_include();
   $full_list = array_merge(filefield_paths_token_list(), token_get_list('node'));
-  if (function_exists('filefield_token_list')) {
-    $temp_tokens = filefield_token_list();
-    $full_list['file'] = array_merge($temp_tokens['file'], $full_list['file']);
+  if (function_exists('filefield_token_list')) {
+    $temp_tokens = filefield_token_list();
+    $full_list['file'] = array_merge($temp_tokens['file'], $full_list['file']);
   }
-  
+  
   $headers = array(t('Token'), t('Replacement value'));
   $rows = array();
   foreach ($full_list as $key => $category) {
@@ -65,9 +65,9 @@
   $output = theme('table', $headers, $rows, array('class' => 'description'));
   return $output;
 }
-
-/**
- * Implementation of hook_init().
+
+/**
+ * Implementation of hook_init().
  */
 function filefield_paths_init() {
   foreach (module_list() as $module) {
@@ -78,32 +78,32 @@
 }
 
 /**
- * Implementation of hook_form_alter().
- */
-function filefield_paths_form_alter(&$form, $form_state, $form_id) {
+ * Implementation of hook_form_alter().
+ */
+function filefield_paths_form_alter(&$form, $form_state, $form_id) {
   $ffp = array();
-
-  // Invoke hook_filefield_paths_form_alter().
-  foreach (module_implements('filefield_paths_form_alter') as $module) {
+
+  // Invoke hook_filefield_paths_form_alter().
+  foreach (module_implements('filefield_paths_form_alter') as $module) {
     $function = $module .'_filefield_paths_form_alter';
     $function($form, $ffp);
-  }
-
-  // If supporting module enabled, show FileField Paths settings form.
+  }
+
+  // If supporting module enabled, show FileField Paths settings form.
   if (count($ffp) > 0) {
-    $fields = module_invoke_all('filefield_paths_field_settings');
+    $fields = module_invoke_all('filefield_paths_field_settings');
     foreach ($ffp as $field_name => $field_data) {
-
+
       $result = db_fetch_object(
         db_query("SELECT * FROM {filefield_paths} WHERE type = '%s' AND field = '%s'", $field_data['type'], $field_name)
-      );
+      );
       if (!empty($result)) {
         foreach ($fields as &$field) {
           $field['settings'] = unserialize($result->$field['sql']);
         }
         unset($field);
-      }
-
+      }
+
       $count = 0;
       foreach ($fields as $name => $field) {
         $count++;
@@ -114,13 +114,13 @@
             $field['form'][$keys[$i]]['#weight'] = ($count - 1) * 3 + 2 + $i;
           }
           unset($keys);
-
+
           $field_data['form_path'] = array_merge($field_data['form_path'], $field['form']);
         }
-
-        $field_data['form_path']['#tree'] = TRUE;
+
+        $field_data['form_path']['#tree'] = TRUE;
         $field_data['form_path'][$name]['#weight'] = ($count - 1) * 3;
-
+
         // Set defualt value for patterns.
         if (isset($field['settings']['value'])) {
           $field_data['form_path'][$name]['#default_value'] = $field['settings']['value'];
@@ -129,9 +129,9 @@
             foreach ($field['data'] as $key => $value) {
               $field_data['form_path'][$value]['#default_value'] = $field['settings'][$key];
             }
-          }
-        }
-
+          }
+        }
+
         $field_data['form_path'][$name .'_cleanup'] = array(
           '#type' => 'fieldset',
           '#title' => t('!title cleanup settings', array('!title' => $field['title'])),
@@ -157,7 +157,7 @@
           $field_data['form_path'][$name .'_cleanup'][$name .'_pathauto']['#disabled'] = TRUE;
           $field_data['form_path'][$name .'_cleanup'][$name .'_pathauto']['#default_value'] = 0;
         }
-
+
         // Convert field to lower case.
         $field_data['form_path'][$name .'_cleanup'][$name .'_tolower'] = array(
           '#type' => 'checkbox',
@@ -168,7 +168,7 @@
           ,
           '#description' => t('Convert !title to lower case', array('!title' => $field['title'])) .'.'
         );
-
+
         // Transliterate field with Transliteration module.
         $field_data['form_path'][$name .'_cleanup'][$name .'_transliterate'] = array(
           '#type' => 'checkbox',
@@ -183,7 +183,7 @@
           $field_data['form_path'][$name .'_cleanup'][$name .'_transliterate']['#disabled'] = TRUE;
           $field_data['form_path'][$name .'_cleanup'][$name .'_transliterate']['#default_value'] = 0;
         }
-
+
         // Replacement patterns for field.
         $field_data['form_path'][$name .'_tokens'] = array(
           '#type' => 'fieldset',
@@ -196,54 +196,54 @@
             'class' => $name .' tokens'
           )
         );
-      }
-
-      // Retroactive updates.
+      }
+
+      // Retroactive updates.
       $field_data['form_path']['retroactive_update'] = array(
-        '#type' => 'checkbox',
+        '#type' => 'checkbox',
         '#title' => t('Retroactive update'),
         '#description' => t('Move and rename previously uploaded files') .'.'.
           '<br /> <strong style="color: #FF0000;">'. t('Warning') .':</strong> '.
           t('This feature should only be used on developmental servers or with extreme caution') .'.',
         '#weight' => 10
-      );
-
-      if (!in_array('filefield_paths_form_submit', $form['#submit'])) {
-        $form['#submit'][] = 'filefield_paths_form_submit';
-      }
-    }
-  }
-}
-
-/**
- * Implementation of hook_form_submit().
- */
-function filefield_paths_form_submit($form, &$form_state) {
+      );
+
+      if (!in_array('filefield_paths_form_submit', $form['#submit'])) {
+        $form['#submit'][] = 'filefield_paths_form_submit';
+      }
+    }
+  }
+}
+
+/**
+ * Implementation of hook_form_submit().
+ */
+function filefield_paths_form_submit($form, &$form_state) {
   $ffp = array();
-
-  // Invoke hook_filefield_paths_form_submit().
+
+  // Invoke hook_filefield_paths_form_submit().
   foreach (module_implements('filefield_paths_form_submit') as $module) {
-    $function = $module .'_filefield_paths_form_submit';
-    $function($form_state, $ffp);
-  }
-
-  if (count($ffp) > 0) {
-    $retroactive_update = FALSE;
-    $fields = module_invoke_all('filefield_paths_field_settings');
-    foreach ($ffp as $field_name => $field_data) {
-      $cols = $vals = $data = array();
+    $function = $module .'_filefield_paths_form_submit';
+    $function($form_state, $ffp);
+  }
 
-      foreach ($fields as $name => &$field) {
+  if (count($ffp) > 0) {
+    $retroactive_update = FALSE;
+    $fields = module_invoke_all('filefield_paths_field_settings');
+    foreach ($ffp as $field_name => $field_data) {
+      $cols = $vals = $data = array();
+
+      foreach ($fields as $name => &$field) {
         $field['settings'] = array(
           'value' => $form_state['values']['ffp_'. $field_name][$name],
           'tolower' => $form_state['values']['ffp_'. $field_name][$name .'_cleanup'][$name .'_tolower'],
           'pathauto' => $form_state['values']['ffp_'. $field_name][$name .'_cleanup'][$name .'_pathauto'],
           'transliterate' => $form_state['values']['ffp_'. $field_name][$name .'_cleanup'][$name .'_transliterate']
-        );
-
-        // Store additional settings from addon modules.
+        );
+
+        // Store additional settings from addon modules.
         if (isset($field['data'])) {
-          foreach ($field['data'] as $key => $value) {
+          foreach ($field['data'] as $key => $value) {
             $field['settings'][$key] = $form_state['values']['ffp_'. $field_name][$value];
           }
         }
@@ -254,9 +254,9 @@
       }
 
       $result = db_fetch_object(
-        db_query(
-          "SELECT * FROM {filefield_paths} WHERE type = '%s' AND field = '%s'",
-          $field_data['type'], $field_name
+        db_query(
+          "SELECT * FROM {filefield_paths} WHERE type = '%s' AND field = '%s'",
+          $field_data['type'], $field_name
         )
       );
 
@@ -278,448 +278,448 @@
         );
       }
 
-      if ($form_state['values']['ffp_'. $field_name]['retroactive_update']) {
+      if ($form_state['values']['ffp_'. $field_name]['retroactive_update']) {
         $retroactive_update = TRUE;
         filefield_paths_batch_update(arg(5), $field_name, arg(3));
-      }
-    }
-
-    if ($retroactive_update) {
-      // Run batch.
-      batch_process($form_state['redirect']);
-    }
-  }
-}
-
-function filefield_paths_batch_update($field_name = NULL, $field_module, $type_name) {
-  $objects = array();
-  $module = (!empty($field_name)) ? 'filefield' : $field_module;
-
-  // Invoke hook_filefield_paths_update().
-  if (function_exists($function = $module .'_filefield_paths_batch_update')) {
-    $function($field_name, str_replace('-', '_', $type_name), $objects);
-  }
-
-  // Create batch.
+      }
+    }
+
+    if ($retroactive_update) {
+      // Run batch.
+      batch_process($form_state['redirect']);
+    }
+  }
+}
+
+function filefield_paths_batch_update($field_name = NULL, $field_module, $type_name) {
+  $objects = array();
+  $module = (!empty($field_name)) ? 'filefield' : $field_module;
+
+  // Invoke hook_filefield_paths_update().
+  if (function_exists($function = $module .'_filefield_paths_batch_update')) {
+    $function($field_name, str_replace('-', '_', $type_name), $objects);
+  }
+
+  // Create batch.
   $batch = array(
-    'title' => t('Updating FileField Paths'),
+    'title' => t('Updating FileField Paths'),
     'operations' => array(
       array('_filefield_paths_batch_update_process', array($objects, $field_name))
     ),
   );
-  batch_set($batch);
+  batch_set($batch);
+}
+
+function _filefield_paths_batch_update_process($objects, $field_name, &$context) {
+  if (!isset($context['sandbox']['progress'])) {
+    $context['sandbox']['progress'] = 0;
+    $context['sandbox']['max'] = count($objects);
+    $context['sandbox']['objects'] = $objects;
+  }
+
+  // Process nodes by groups of 5.
+  $count = min(5, count($context['sandbox']['objects']));
+  for ($i = 1; $i <= $count; $i++) {
+    // For each oid, load the object, update the files and save it.
+    $oid = array_shift($context['sandbox']['objects']);
+
+    foreach (module_implements('filefield_paths_update') as $module) {
+      $function = $module .'_filefield_paths_update';
+      $function($oid, $field_name);
+    }
+
+    // Update our progress information.
+    $context['sandbox']['progress']++;
+  }
+
+  // Inform the batch engine that we are not finished,
+  // and provide an estimation of the completion level we reached.
+  if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
+    $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
+  }
 }
 
-function _filefield_paths_batch_update_process($objects, $field_name, &$context) {
-  if (!isset($context['sandbox']['progress'])) {
-    $context['sandbox']['progress'] = 0;
-    $context['sandbox']['max'] = count($objects);
-    $context['sandbox']['objects'] = $objects;
-  }
-
-  // Process nodes by groups of 5.
-  $count = min(5, count($context['sandbox']['objects']));
-  for ($i = 1; $i <= $count; $i++) {
-    // For each oid, load the object, update the files and save it.
-    $oid = array_shift($context['sandbox']['objects']);
-
-    foreach (module_implements('filefield_paths_update') as $module) {
-      $function = $module .'_filefield_paths_update';
-      $function($oid, $field_name);
-    }
-
-    // Update our progress information.
-    $context['sandbox']['progress']++;
-  }
-
-  // Inform the batch engine that we are not finished,
-  // and provide an estimation of the completion level we reached.
-  if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
-    $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
-  }
-}
-
-/**
- * Implementation of hook_nodeapi().
- */
-function filefield_paths_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
-
-  switch ($op) {
-    case 'presave':
-      if (module_exists('content')) {
-        $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 (empty($file['filepath'])) {
-                continue;
-              }
-
-              // If file is newly uploaded, flag to be processed
-              if ($file['status'] == 0) {
-                $file['data']['process'] = TRUE;
-              }
-            }
-
-          }
-        }
-      }
-      break;
-
-    case 'insert':
-    case 'update':
-      $update = new stdClass;
-      $update->node = FALSE;
-
-      if (($ffp = filefield_paths_get_fields($node)) == FALSE) {
-        break;
-      }
-
-      // Process files.
-      foreach ($ffp['#files'] as &$file) {
-        // Invoke hook_filefield_paths_process_file().
-        foreach (module_implements('filefield_paths_process_file') as $module) {
-          $function = $module .'_filefield_paths_process_file';
-          $function($file['new'], $file, $ffp['#settings'][$file['name']], $node, $update);
-        }
-      }
-
-      // Re-write node entry if required.
-      if ($update->node == TRUE) {
-        global $user;
-
-        drupal_write_record('node', $node, 'nid');
-        if (!empty($node->revision)) {
-          _node_save_revision($node, $user->uid);
-          db_query('UPDATE {node} SET vid = %d WHERE nid = %d', $node->vid, $node->nid);
-        }
-        else {
-          _node_save_revision($node, $user->uid, 'vid');
-        }
-      }
-
+/**
+ * Implementation of hook_nodeapi().
+ */
+function filefield_paths_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
+
+  switch ($op) {
+    case 'presave':
+      if (module_exists('content')) {
+        $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'])) {
+                continue;
+              }
+
+              // If file is newly uploaded, flag to be processed
+              if ($file['status'] == 0) {
+                $file['data']['process'] = TRUE;
+              }
+            }
+
+          }
+        }
+      }
+      break;
+
+    case 'insert':
+    case 'update':
+      $update = new stdClass;
+      $update->node = FALSE;
+
+      if (($ffp = filefield_paths_get_fields($node)) == FALSE) {
+        break;
+      }
+
+      // Process files.
+      foreach ($ffp['#files'] as &$file) {
+        // Invoke hook_filefield_paths_process_file().
+        foreach (module_implements('filefield_paths_process_file') as $module) {
+          $function = $module .'_filefield_paths_process_file';
+          $function($file['new'], $file, $ffp['#settings'][$file['name']], $node, $update);
+        }
+      }
+
+      // Re-write node entry if required.
+      if ($update->node == TRUE) {
+        global $user;
+
+        drupal_write_record('node', $node, 'nid');
+        if (!empty($node->revision)) {
+          _node_save_revision($node, $user->uid);
+          db_query('UPDATE {node} SET vid = %d WHERE nid = %d', $node->vid, $node->nid);
+        }
+        else {
+          _node_save_revision($node, $user->uid, 'vid');
+        }
+      }
+
       // Re-write cck fields.
       if (module_exists('content')) {
-        _content_field_invoke_default('update', $node);
+        _content_field_invoke_default('update', $node);
         cache_clear_all('content:'. $node->nid .':'. $node->vid, content_cache_tablename());
       }
-
-      // Cleanup temporary paths.
-      if ($ffp['#settings']) {
+
+      // Cleanup temporary paths.
+      if ($ffp['#settings']) {
         foreach ($ffp['#settings'] as $name => $field) {
-          $paths = explode('/', $field['filepath']['value']);
-          filefield_paths_cleanup_temp($paths);
-
-          // Invoke hook_filefield_paths_cleanup().
-          foreach (module_implements('filefield_paths_cleanup') as $module) {
-            $function = $module .'_filefield_paths_cleanup';
-            $function($ffp, $paths, $name);
-          }
-        }
-      }
-
-      break;
-  }
-}
-
-function filefield_paths_cleanup_temp($paths) {
-  while ($paths) {
-    if (@rmdir(file_directory_path() .'/'. implode('/', $paths)) === TRUE) {
-      array_pop($paths);
-      continue;
-    }
-    break;
-  }
-}
-
-function filefield_paths_get_fields(&$node, $op = NULL) {
-  $ffp = array();
-
-  // Invoke hook_filefield_paths_get_fields().
-  foreach (module_implements('filefield_paths_get_fields') as $module) {
-    $function = $module .'_filefield_paths_get_fields';
-    $function($node, $ffp);
-  }
-
-  if (count($ffp) == 0 || (isset($ffp['#types']) && !is_array($ffp['#types']))) {
-    return FALSE;
-  }
-
-  $fields = module_invoke_all('filefield_paths_field_settings');
-
-  // Load fields settings
-  foreach ($ffp['#types'] as $name => $temp) {
-    $result = db_fetch_object(
-      db_query("SELECT * FROM {filefield_paths} WHERE type = '%s' AND field = '%s'", $node->type, $name)
-    );
-
-    if (!empty($result)) {
-      foreach ($fields as $field) {
-        $ffp['#settings'][$name][$field['sql']] = unserialize($result->$field['sql']);
-      }
-    }
-  }
-
-  return $ffp;
-}
-
-/**
- * Implementation of hook_filefield_paths_process_file().
- */
-function filefield_paths_filefield_paths_process_file($new, &$file, $settings, &$node, &$update) {
-  if ($new) {
-    // Process filepath
-    $file['filepath']['old'] = $file['field']['filepath'];
-    $file['filepath']['new'] = filefield_paths_process_string(file_directory_path() .'/'. $settings['filepath']['value'] .'/'. $file['field']['filename'], 'node', $node, $settings['filepath']);
-    $file['filepath']['new'] = filefield_paths_process_string($file['filepath']['new'], 'field', array(0 => $file['field']), $settings['filepath']);
-
-    // Process filename
-    $file['filename']['old'] = $file['field']['filename'];
-    if (($file['filename']['new'] = $settings['filename']['value']) != '') {
-      $file['filename']['new'] = filefield_paths_process_string($file['filename']['new'], 'node', $node, $settings['filename']);
-      $file['filename']['new'] = filefield_paths_process_string($file['filename']['new'], 'field', array(0 => $file['field']), $settings['filename']);
-    }
-    else {
-      $file['filename']['new'] = $file['field']['filename'];
-    }
-
-    // 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)) {
-
-        // Fix reference to old paths in Body and Teaser
-        // TODO: allow for CCK fields
-        // TODO: preg_reaplce to better support FileField Insert.
-        if (isset($node->body)) {
-          $file['filepath']['new'] = str_replace($file['filename']['old'], $file['filename']['new'], $file['filepath']['new']);
-
-          $body = str_replace($file['filepath']['old'], $file['filepath']['new'], $node->body);
-          $body = str_replace(drupal_urlencode($file['filepath']['old']), $file['filepath']['new'], $body);
-
-          $teaser = str_replace($file['filepath']['old'], $file['filepath']['new'], $node->teaser);
-          $teaser = str_replace(drupal_urlencode($file['filepath']['old']), $file['filepath']['new'], $teaser);
-
-          if ($body != $node->body || $teaser != $node->teaser) {
-            $node->body = $body;
-            $node->teaser = $teaser;
-
-            $update->node = TRUE;
-          }
-        }
-
-        // Store new filename in file Array
-        $file['field']['filename'] = $file['filename']['new'];
-      }
-    }
-  }
-}
-
-/**
- * Implementation of hook_token_list().
- */
+          $paths = explode('/', $field['filepath']['value']);
+          filefield_paths_cleanup_temp($paths);
+
+          // Invoke hook_filefield_paths_cleanup().
+          foreach (module_implements('filefield_paths_cleanup') as $module) {
+            $function = $module .'_filefield_paths_cleanup';
+            $function($ffp, $paths, $name);
+          }
+        }
+      }
+
+      break;
+  }
+}
+
+function filefield_paths_cleanup_temp($paths) {
+  while ($paths) {
+    if (@rmdir(file_directory_path() .'/'. implode('/', $paths)) === TRUE) {
+      array_pop($paths);
+      continue;
+    }
+    break;
+  }
+}
+
+function filefield_paths_get_fields(&$node, $op = NULL) {
+  $ffp = array();
+
+  // Invoke hook_filefield_paths_get_fields().
+  foreach (module_implements('filefield_paths_get_fields') as $module) {
+    $function = $module .'_filefield_paths_get_fields';
+    $function($node, $ffp);
+  }
+
+  if (count($ffp) == 0 || (isset($ffp['#types']) && !is_array($ffp['#types']))) {
+    return FALSE;
+  }
+
+  $fields = module_invoke_all('filefield_paths_field_settings');
+
+  // Load fields settings
+  foreach ($ffp['#types'] as $name => $temp) {
+    $result = db_fetch_object(
+      db_query("SELECT * FROM {filefield_paths} WHERE type = '%s' AND field = '%s'", $node->type, $name)
+    );
+
+    if (!empty($result)) {
+      foreach ($fields as $field) {
+        $ffp['#settings'][$name][$field['sql']] = unserialize($result->$field['sql']);
+      }
+    }
+  }
+
+  return $ffp;
+}
+
+/**
+ * Implementation of hook_filefield_paths_process_file().
+ */
+function filefield_paths_filefield_paths_process_file($new, &$file, $settings, &$node, &$update) {
+  if ($new) {
+    // Process filepath
+    $file['filepath']['old'] = $file['field']['filepath'];
+    $file['filepath']['new'] = filefield_paths_process_string(file_directory_path() .'/'. $settings['filepath']['value'] .'/'. $file['field']['filename'], 'node', $node, $settings['filepath']);
+    $file['filepath']['new'] = filefield_paths_process_string($file['filepath']['new'], 'field', array(0 => $file['field']), $settings['filepath']);
+
+    // Process filename
+    $file['filename']['old'] = $file['field']['filename'];
+    if (($file['filename']['new'] = $settings['filename']['value']) != '') {
+      $file['filename']['new'] = filefield_paths_process_string($file['filename']['new'], 'node', $node, $settings['filename']);
+      $file['filename']['new'] = filefield_paths_process_string($file['filename']['new'], 'field', array(0 => $file['field']), $settings['filename']);
+    }
+    else {
+      $file['filename']['new'] = $file['field']['filename'];
+    }
+
+    // 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)) {
+
+        // Fix reference to old paths in Body and Teaser
+        // TODO: allow for CCK fields
+        // TODO: preg_reaplce to better support FileField Insert.
+        if (isset($node->body)) {
+          $file['filepath']['new'] = str_replace($file['filename']['old'], $file['filename']['new'], $file['filepath']['new']);
+
+          $body = str_replace($file['filepath']['old'], $file['filepath']['new'], $node->body);
+          $body = str_replace(drupal_urlencode($file['filepath']['old']), $file['filepath']['new'], $body);
+
+          $teaser = str_replace($file['filepath']['old'], $file['filepath']['new'], $node->teaser);
+          $teaser = str_replace(drupal_urlencode($file['filepath']['old']), $file['filepath']['new'], $teaser);
+
+          if ($body != $node->body || $teaser != $node->teaser) {
+            $node->body = $body;
+            $node->teaser = $teaser;
+
+            $update->node = TRUE;
+          }
+        }
+
+        // Store new filename in file Array
+        $file['field']['filename'] = $file['filename']['new'];
+      }
+    }
+  }
+}
+
+/**
+ * Implementation of hook_token_list().
+ */
 function filefield_paths_token_list($type = 'all') {
   if ($type == 'field' || $type == 'all') {
-    $tokens = array();
-    if (!module_exists('filefield')) {
+    $tokens = array();
+    if (!module_exists('filefield')) {
       $tokens['file']['filefield-onlyname'] = t("File name without extension");
-      $tokens['file']['filefield-extension'] = t("File extension");
-    }
-    $tokens['file']['filefield-onlyname-original'] = t("File name without extension - original");
+      $tokens['file']['filefield-extension'] = t("File extension");
+    }
+    $tokens['file']['filefield-onlyname-original'] = t("File name without extension - original");
     $tokens['file']['filefield-extension-original'] = t("File extension - original");
-    // Tokens for Image module integration.
-    if (module_exists('image')) {
-      $tokens['image']['image-derivative'] = t("Image derivative (thumbnail, preview, etc)");
+    // Tokens for Image module integration.
+    if (module_exists('image')) {
+      $tokens['image']['image-derivative'] = t("Image derivative (thumbnail, preview, etc)");
     }
     return $tokens;
-  }
+  }
 }
-
-/**
- * Implementation of hook_token_values().
- */
+
+/**
+ * Implementation of hook_token_values().
+ */
 function filefield_paths_token_values($type, $object = NULL) {
   if ($type == 'field') {
-    $item = pathinfo($object[0]['filename']);
-    $tokens = array();
-    if (!module_exists('filefield')) {
-      $tokens['filefield-onlyname'] = $item['filename'];
-      $tokens['filefield-extension'] = $item['extension'];
-    }
-    // Original filename
-    $orig = $item;
-    if (!empty($object[0]['origname'])) {
-      $orig = pathinfo($object[0]['origname']);
-    }
-    $tokens['filefield-onlyname-original'] = $orig['filename'];
-    $tokens['filefield-extension-original'] = $orig['extension'];
-    // Tokens for Image module integration.
-    if (module_exists('image')) {
-      $tokens['image-derivative'] = (isset($object[0]['type']) && $object[0]['type'] !== '_original')
-        ? '.'. $object[0]['type']
-        : '';
-    }
+    $item = pathinfo($object[0]['filename']);
+    $tokens = array();
+    if (!module_exists('filefield')) {
+      $tokens['filefield-onlyname'] = $item['filename'];
+      $tokens['filefield-extension'] = $item['extension'];
+    }
+    // Original filename
+    $orig = $item;
+    if (!empty($object[0]['origname'])) {
+      $orig = pathinfo($object[0]['origname']);
+    }
+    $tokens['filefield-onlyname-original'] = $orig['filename'];
+    $tokens['filefield-extension-original'] = $orig['extension'];
+    // Tokens for Image module integration.
+    if (module_exists('image')) {
+      $tokens['image-derivative'] = (isset($object[0]['type']) && $object[0]['type'] !== '_original')
+        ? '.'. $object[0]['type']
+        : '';
+    }
     return $tokens;
-  }
-}
-
-/**
- * Process and cleanup strings.
- */
+  }
+}
+
+/**
+ * Process and cleanup strings.
+ */
 function filefield_paths_process_string($value, $type, $object, $settings = array()) {
-
+
   // Process string tokens.
   $placeholders = _filefield_paths_get_values($type, $object, (module_exists('pathauto') && isset($settings['pathauto']) && $settings['pathauto']));
   $value = str_replace($placeholders['tokens'], $placeholders['values'], $value);
-
-  // Transliterate string.
-  if (module_exists('transliteration') && isset($settings['transliterate']) && $$settings['transliterate']) {
-    $value = transliteration_get($value);
-    if ($type == 'field') {
-      $paths = explode('/', $value);
-      foreach ($paths as &$path) {
-        $path = transliteration_clean_filename($path);
-      }
-
-      $value = implode('/', $paths);
-    }
-  }
-
-  // Convert string to lower case.
-  if ((isset($settings['tolower']) && $settings['tolower']) || (isset($settings['pathauto']) && $settings['pathauto'] && variable_get('pathauto_case', 0))) {
-    // Convert string to lower case
-    $value = drupal_strtolower($value);
-  }
-
-  return $value;
-}
-
+
+  // Transliterate string.
+  if (module_exists('transliteration') && isset($settings['transliterate']) && $$settings['transliterate']) {
+    $value = transliteration_get($value);
+    if ($type == 'field') {
+      $paths = explode('/', $value);
+      foreach ($paths as &$path) {
+        $path = transliteration_clean_filename($path);
+      }
+
+      $value = implode('/', $paths);
+    }
+  }
+
+  // Convert string to lower case.
+  if ((isset($settings['tolower']) && $settings['tolower']) || (isset($settings['pathauto']) && $settings['pathauto'] && variable_get('pathauto_case', 0))) {
+    // Convert string to lower case
+    $value = drupal_strtolower($value);
+  }
+
+  return $value;
+}
+
 function _filefield_paths_get_values($type, $object, $pathauto = FALSE) {
   switch ($type) {
     case 'node':
       $full = token_get_values($type, $object, TRUE);
       break;
-
+
     case 'field':
       $all = filefield_paths_token_values($type, $object);
-      if (function_exists('filefield_token_values')) {
-        $all = array_merge(filefield_token_values($type, $object), $all);
-      }
+      if (function_exists('filefield_token_values')) {
+        $all = array_merge(filefield_token_values($type, $object), $all);
+      }
 
       $full = new stdClass();
       $full->tokens = array_keys($all);
       $full->values = array_values($all);
       break;
   }
-
+
   $full->tokens = token_prepare_tokens($full->tokens);
   if ($pathauto) {
-    $temp = clone $full;
-
-    // Strip square brackets from tokens for Pathauto.
-    foreach ($temp->tokens as &$token) {
-      $token = trim($token, "[]");
-    }
-
-    $full->values = pathauto_clean_token_values($temp);
-  }
-
-  // Temporary fix: Remove double slashes from token values.
-  // TODO: Remove when #420856 is committed to Pathauto.
-  foreach ($full->values as &$value) {
-    $value = str_replace('//', '/', $value);
-  }
-
+    $temp = clone $full;
+
+    // Strip square brackets from tokens for Pathauto.
+    foreach ($temp->tokens as &$token) {
+      $token = trim($token, "[]");
+    }
+
+    $full->values = pathauto_clean_token_values($temp);
+  }
+
+  // Temporary fix: Remove double slashes from token values.
+  // TODO: Remove when #420856 is committed to Pathauto.
+  foreach ($full->values as &$value) {
+    $value = str_replace('//', '/', $value);
+  }
+
   return array('tokens' => $full->tokens, 'values' => $full->values);
-}
-
-/**
- * Move file and update its database record.
- */
-function filefield_paths_file_move(&$file, $replace = FILE_EXISTS_RENAME) {
-  $dest = _filefield_paths_strip_path(dirname($file['filepath']['new']));
-
-  foreach (explode('/', $dest) as $dir) {
-    $dirs[] = $dir;
-    $path = file_create_path(implode($dirs, '/'));
-    if (!_filefield_paths_check_directory($path, FILE_CREATE_DIRECTORY)) {
-      watchdog('filefield_paths', 'FileField Paths failed to create directory (%d).', array('%d' => $path), WATCHDOG_ERROR);
-      return FALSE;
-    }
-  }
-
-  if (!file_move($file['field']['filepath'], $dest .'/'. $file['filename']['new'], $replace)) {
-    watchdog('filefield_paths', 'FileField Paths failed to move file (%o) to (%n).', array('%o' => $file['filepath']['old'], '%n' => $dest .'/'. $file['filename']['new']), WATCHDOG_ERROR);
-    return FALSE;
-  }
-
-  $result = db_fetch_object(db_query("SELECT origname FROM {files} WHERE fid = %d", $file['field']['fid']));
-
-  // Set 'origname' and update 'filename'.
-  if (empty($result->origname)) {
-    db_query(
-      "UPDATE {files} SET filename = '%s', filepath = '%s', origname = '%s' WHERE fid = %d",
-      $file['filename']['new'], $file['field']['filepath'], $file['filename']['old'], $file['field']['fid']
-    );
-  }
-
-  // Update 'filename'.
+}
+
+/**
+ * Move file and update its database record.
+ */
+function filefield_paths_file_move(&$file, $replace = FILE_EXISTS_RENAME) {
+  $dest = _filefield_paths_strip_path(dirname($file['filepath']['new']));
+
+  foreach (explode('/', $dest) as $dir) {
+    $dirs[] = $dir;
+    $path = file_create_path(implode($dirs, '/'));
+    if (!_filefield_paths_check_directory($path, FILE_CREATE_DIRECTORY)) {
+      watchdog('filefield_paths', 'FileField Paths failed to create directory (%d).', array('%d' => $path), WATCHDOG_ERROR);
+      return FALSE;
+    }
+  }
+
+  if (!file_move($file['field']['filepath'], $dest .'/'. $file['filename']['new'], $replace)) {
+    watchdog('filefield_paths', 'FileField Paths failed to move file (%o) to (%n).', array('%o' => $file['filepath']['old'], '%n' => $dest .'/'. $file['filename']['new']), WATCHDOG_ERROR);
+    return FALSE;
+  }
+
+  $result = db_fetch_object(db_query("SELECT origname FROM {files} WHERE fid = %d", $file['field']['fid']));
+
+  // Set 'origname' and update 'filename'.
+  if (empty($result->origname)) {
+    db_query(
+      "UPDATE {files} SET filename = '%s', filepath = '%s', origname = '%s' WHERE fid = %d",
+      $file['filename']['new'], $file['field']['filepath'], $file['filename']['old'], $file['field']['fid']
+    );
+  }
+
+  // Update 'filename'.
   else {
-    db_query(
-      "UPDATE {files} SET filename = '%s', filepath = '%s' WHERE fid = %d",
-      $file['filename']['new'], $file['field']['filepath'], $file['field']['fid']
+    db_query(
+      "UPDATE {files} SET filename = '%s', filepath = '%s' WHERE fid = %d",
+      $file['filename']['new'], $file['field']['filepath'], $file['field']['fid']
     );
-  }
-
-  return TRUE;
-}
-
-function _filefield_paths_strip_path($path) {
-  $dirpath = file_directory_path();
-  $dirlen = drupal_strlen($dirpath);
-  if (drupal_substr($path, 0, $dirlen + 1) == $dirpath .'/') {
-    $path = drupal_substr($path, $dirlen + 1);
-  }
-  return $path;
-}
-
-function _filefield_paths_check_directory(&$directory, $mode = 0, $form_item = NULL) {
-  $directory = rtrim($directory, '/\\');
-
-  // error if dir is a file.
-  if (is_file($directory)) {
-    watchdog('file system',  'check_directory: The path  %directory is a file.',  array('%directory' => $directory), WATCHDOG_ERROR);
-    if ($form_item)  form_set_error($form_item, t('The directory %directory is a file!', array('%directory' => $directory)));
-    return FALSE;
-  }
-
-  // create the directory if it is missing.
-  if (!is_dir($directory) && $mode & FILE_CREATE_DIRECTORY && !@mkdir($directory, 0775, TRUE)) {
-    watchdog('file system', 'The directory %directory does not exist.', array('%directory' => $directory), WATCHDOG_ERROR);
-    if ($form_item) form_set_error($form_item, t('The directory %directory does not exist.', array('%directory' => $directory)));
-    return FALSE;
-  }
-
-  // Check to see if the directory is writable.
-  if (!is_writable($directory) && $mode & FILE_MODIFY_PERMISSIONS && !@chmod($directory, 0775)) {
-    watchdog('file system', 'The directory %directory is not writable, because it does not have the correct permissions set.', array('%directory' => $directory), WATCHDOG_ERROR);
-    if ($form_item) form_set_error($form_item, t('The directory %directory is not writable', array('%directory' => $directory)));
-    return FALSE;
-  }
-
-  if ((file_directory_path() == $directory || file_directory_temp() == $directory) && !is_file("$directory/.htaccess")) {
-    $htaccess_lines = "SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006\nOptions None\nOptions +FollowSymLinks";
-    if (($fp = fopen("$directory/.htaccess", 'w')) && fputs($fp, $htaccess_lines)) {
-      fclose($fp);
-      chmod($directory .'/.htaccess', 0664);
-    }
-    else {
-      $repl = array('%directory' => $directory, '!htaccess' => nl2br(check_plain($htaccess_lines)));
-      form_set_error($form_item, t("Security warning: Couldn't write .htaccess file. Please create a .htaccess file in your %directory directory which contains the following lines:<br /><code>!htaccess</code>", $repl));
-      watchdog('security', "Security warning: Couldn't write .htaccess file.  Please create a .htaccess file in your %directory directory which contains the following lines:<br /><code>!htaccess</code>", $repl, WATCHDOG_ERROR);
-    }
-  }
-
-  return TRUE;
-}
+  }
+
+  return TRUE;
+}
+
+function _filefield_paths_strip_path($path) {
+  $dirpath = file_directory_path();
+  $dirlen = drupal_strlen($dirpath);
+  if (drupal_substr($path, 0, $dirlen + 1) == $dirpath .'/') {
+    $path = drupal_substr($path, $dirlen + 1);
+  }
+  return $path;
+}
+
+function _filefield_paths_check_directory(&$directory, $mode = 0, $form_item = NULL) {
+  $directory = rtrim($directory, '/\\');
+
+  // error if dir is a file.
+  if (is_file($directory)) {
+    watchdog('file system',  'check_directory: The path  %directory is a file.',  array('%directory' => $directory), WATCHDOG_ERROR);
+    if ($form_item)  form_set_error($form_item, t('The directory %directory is a file!', array('%directory' => $directory)));
+    return FALSE;
+  }
+
+  // create the directory if it is missing.
+  if (!is_dir($directory) && $mode & FILE_CREATE_DIRECTORY && !@mkdir($directory, 0775, TRUE)) {
+    watchdog('file system', 'The directory %directory does not exist.', array('%directory' => $directory), WATCHDOG_ERROR);
+    if ($form_item) form_set_error($form_item, t('The directory %directory does not exist.', array('%directory' => $directory)));
+    return FALSE;
+  }
+
+  // Check to see if the directory is writable.
+  if (!is_writable($directory) && $mode & FILE_MODIFY_PERMISSIONS && !@chmod($directory, 0775)) {
+    watchdog('file system', 'The directory %directory is not writable, because it does not have the correct permissions set.', array('%directory' => $directory), WATCHDOG_ERROR);
+    if ($form_item) form_set_error($form_item, t('The directory %directory is not writable', array('%directory' => $directory)));
+    return FALSE;
+  }
+
+  if ((file_directory_path() == $directory || file_directory_temp() == $directory) && !is_file("$directory/.htaccess")) {
+    $htaccess_lines = "SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006\nOptions None\nOptions +FollowSymLinks";
+    if (($fp = fopen("$directory/.htaccess", 'w')) && fputs($fp, $htaccess_lines)) {
+      fclose($fp);
+      chmod($directory .'/.htaccess', 0664);
+    }
+    else {
+      $repl = array('%directory' => $directory, '!htaccess' => nl2br(check_plain($htaccess_lines)));
+      form_set_error($form_item, t("Security warning: Couldn't write .htaccess file. Please create a .htaccess file in your %directory directory which contains the following lines:<br /><code>!htaccess</code>", $repl));
+      watchdog('security', "Security warning: Couldn't write .htaccess file.  Please create a .htaccess file in your %directory directory which contains the following lines:<br /><code>!htaccess</code>", $repl, WATCHDOG_ERROR);
+    }
+  }
+
+  return TRUE;
+}
