? imagefield_import.patch
Index: imagefield_import.info
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/imagefield_import/imagefield_import.info,v
retrieving revision 1.2.4.2
diff -u -p -r1.2.4.2 imagefield_import.info
--- imagefield_import.info	15 Dec 2008 02:32:15 -0000	1.2.4.2
+++ imagefield_import.info	13 Nov 2009 11:18:09 -0000
@@ -1,6 +1,6 @@
 ; $Id: imagefield_import.info,v 1.2.4.2 2008/12/15 02:32:15 vordude Exp $
 name = Imagefield Import
-description = Allows batches of images to be imported to your site from a directory on your server.
+description = Import batches of images from a directory on your server.
 package = CCK
 dependencies[] = imagefield
 dependencies[] = content
Index: imagefield_import.install
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/imagefield_import/imagefield_import.install,v
retrieving revision 1.3.4.1
diff -u -p -r1.3.4.1 imagefield_import.install
--- imagefield_import.install	14 Dec 2008 03:52:30 -0000	1.3.4.1
+++ imagefield_import.install	13 Nov 2009 11:18:09 -0000
@@ -6,7 +6,21 @@
  * Imagefield Import Install
  * Cleans up variables after itself
  */
+
+/**
+ * Implementation of hook_uninstall().
+ */
 function imagefield_import_uninstall() {
   variable_del('imagefield_import_path');
+  variable_del('imagefield_import_field');
+}
+
+/**
+ * Implementation of hook_update_N().
+ */
+function imagefield_import_update_6100() {
+  variable_set('imagefield_import_path', variable_get('imagefield_import_source_path', ''));
+  variable_del('imagefield_import_source_path');
+  variable_set('imagefield_import_field', variable_get('imagefield_import_fieldname', ''));
   variable_del('imagefield_import_fieldname');
 }
Index: imagefield_import.module
===================================================================
RCS file: /cvs/drupal-contrib/contributions/modules/imagefield_import/imagefield_import.module,v
retrieving revision 1.8.2.5
diff -u -p -r1.8.2.5 imagefield_import.module
--- imagefield_import.module	19 Apr 2009 20:11:40 -0000	1.8.2.5
+++ imagefield_import.module	13 Nov 2009 11:18:09 -0000
@@ -1,450 +1,380 @@
 <?php
 // $Id: imagefield_import.module,v 1.8.2.5 2009/04/19 20:11:40 vordude Exp $
+
 /**
  * @file
- * Imports images (that the user has already uploaded to an import folder) into a CCK field's imagefield.
- * A Big shout out to the image_import.module folks,  Here's is most of your code again.
+ * Imports images from a directory on the server into nodes with CCK imagefields.
  */
 
+/* --- HOOKS ---------------------------------------------------------------- */
+
 /**
  * Implementation of hook_help().
- *
- * hook_help provides data for the $help on a page to help out the user
- *
  */
 function imagefield_import_help($path, $arg) {
-  switch (path) {
-    case 'admin/content/imagefield_import':
-      return '<p>'. t('This is where the Import Magic happens.  If there are images currently in the Directory you set up for import you will see them in the list below.  You can customize the Title and body text of each of the nodes before submitting them all for creation.  Do not forget to click the checkbox on the left that indicates you want to import this image into an imagefield node, or click the top checkbox to select or deslect all.') .'</p>';
+  switch ($path) {
     case 'admin/settings/imagefield_import':
-      return '<p>'. t('The Imagefield Import Path is where you want to transfer -likely FTP or SSH- your images that are in need of uploading, then select the targe field.  You will be creating one node for each image.  So here you are choosing what field you want your imported image to populate') .'</p>';
+      // this check is placed here to avoid duplicate messages (which would be
+      // the case if it was placed in imagefield_import_form()
+      $available = _imagefield_import_available_node_types();
+      if (count($available['matches']) == 0) {
+        drupal_set_message(t('In order to import images into an imagefield, you must first have a node type that has an imagefield associated with it. Configure this on the !url page', array('!url' => l(t('Content types'), 'admin/content/types'))), 'error');
+      }
+      break;
   }
 }
 
 /**
- * Implementation of hook_perm().
- *
- * Define Permissions for the module
- */
-function imagefield_import_perm() {
-  return array('import images');
-}
-
-/**
  * Implementation of hook_menu().
- *
- * 2 pages are created:
- * admin/content/imagefield_import (The Import Page),
- * and admin/settings/imagefield_import  (The Settings Page).
  */
 function imagefield_import_menu() {
+  $items = array();
+
   $items['admin/content/imagefield_import'] = array(
-    'title' => 'Imagefield Import',
+    'title' => 'Import images',
+    'description' => 'Import images into CCK imagefields from an import folder in filesystem.',
     'page callback' => 'drupal_get_form',
-    'page arguments' => array('imagefield_import_form', 2),
+    'page arguments' => array('imagefield_import_form'),
     'access arguments' => array('import images'),
-    'type' => MENU_NORMAL_ITEM,
-    'description' => 'Import images into CCK imagefields from an import folder in filesystem.'
   );
   $items['admin/settings/imagefield_import'] = array(
-    'title' => 'Imagefield Import',
+    'title' => 'Imagefield import',
+    'description' => 'Import images into CCK imagefields from an import folder in filesystem.',
     'page callback' => 'drupal_get_form',
-    'page arguments' => array('imagefield_import_admin_settings', 2),
+    'page arguments' => array('imagefield_import_admin_settings'),
     'access arguments' => array('administer site configuration'),
-    'type' => MENU_NORMAL_ITEM,
-    'description' => 'Import images into CCK imagefields from an import folder in filesystem.'
   );
+
   return $items;
 }
 
-// Create the imagefield_import_form that was defined in callback arguments in hook_menu().
+/**
+ * Implementation of hook_perm().
+ */
+function imagefield_import_perm() {
+  return array('import images');
+}
+
+/**
+ * Implementation of hook_theme().
+ */
+function imagefield_import_theme() {
+  return array(
+    'imagefield_import_filename' => array(
+      'arguments' => array(
+        'filename' => NULL,
+        'size' => NULL,
+        'dimensions' => NULL,
+      ),
+    ),
+    'imagefield_import_form' => array(
+      'arguments' => array(
+        'form' => NULL,
+      ),
+    ),
+  );
+}
+
+/* --- FORMS ---------------------------------------------------------------- */
+
+/**
+ * Menu callback; admin settings form.
+ */
+function imagefield_import_admin_settings() {
+  $form['imagefield_import_path'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Import path'),
+    '#default_value' => variable_get('imagefield_import_path', file_directory_path() .'/images/import'),
+    '#after_build' => array('_imagefield_import_check_directory'),
+    '#description' => t("A file system path where files are stored before being imported. This directory must exist and be writable by Drupal. Paths with a leading slash (e.g. '/upload') are relative to the server's root directory while paths without a leading slash (e.g. 'upload') are relative to the Drupal root directory."),
+  );
+
+  $available = _imagefield_import_available_node_types();
+  if (!empty($available['matches'])) {
+    $form['imagefield_import_field'] = array(
+      '#type' => 'select',
+      '#title' => 'Target field',
+      '#description' => t('Select the imagefield you want to import photos into. When you do the import, nodes of your selected type will be created and the selected field will be populated with the imported image.'),
+      '#options' => $available['matches'],
+      '#default_value' => variable_get('imagefield_import_field', $available['keys'][0]),
+    );
+  }
+
+  return system_settings_form($form);
+}
+
+/**
+ * Menu callback; image import form.
+ */
 function imagefield_import_form() {
   $form = array();
-  //get the content type and field names
-  $targetsetting = variable_get('imagefield_import_fieldname', FALSE);
-  list($type, $field) = split(":::", $targetsetting);
-  // Getting the path the user set as in import folder
-  $dirpath = variable_get('imagefield_import_source_path', '');
-
-  // Check it's configuration out and throw a DSM if it isn't configured properly
 
-  if (!file_check_directory($dirpath)) {
-    drupal_set_message(t("You need to configure the import directory on the imagefield_import module's <a href='!admin-settings-imagefield_import'>settings page</a>. <br />If you don't have the proper permissions to do that, please contact the site administrator.", array('!admin-settings-imagefield_import' => url('admin/settings/imagefield_import'))), 'error');
+  // make the upload directory is configured properly
+  $directory = variable_get('imagefield_import_path', '');
+  if (!file_check_directory($directory)) {
+    drupal_set_message(t("You need to configure the import directory on the !settings-url. If you don't have the proper permissions to do that, please contact the site administrator.", array('!settings-url' => l(t('Imagefield import settings page'), 'admin/settings/imagefield_import'))), 'error');
     return $form;
   }
 
-  // Drupal Function file_scan_directory($dir, $mask) -- Load Up the $files array will all of the files in the import directory
-  $files = file_scan_directory($dirpath, '.*');
-  // PHP function that sorts an array by key
-  ksort($files);
+  // get a list of all files in the upload directory
+  $files = file_scan_directory($directory, '.*');
+
   if ($files) {
-    if (module_exists('taxonomy')) {
-      // a little hack from the image_import.module to get the taxonmy controls onto our form---
-      $form['type'] = array('#type' => 'value', '#value' => $type);
-      $form['#node'] = new stdClass();
-      $form['#node']->type = $type;
-      $form_id = $type .'_node_form';
-      taxonomy_form_alter($form, $form_state, $form_id);
-      unset($form['type']);
-      unset($form['#node']);
-    }
-    // Put the image files into an array for the checkboxes and gather
-    // additional information like dimensions and filesizes. Make sure that
-    // there's no 0th element, because a checkbox with a zero value is seen as
-    // unchecked and won't be imported.
-    // a $fields multidimentional array for each of the files will need these elements
-    $fields = array('filesize', 'dimensions', 'title', 'body');
-    foreach ($fields as $field) {
-      $form['files'][$field][0] = NULL;
-      //$form['files'][filesize][0], etc. = null
-    }
-    $filelist = array(0 => NULL);
-    //cycle through each file that was found
+    ksort($files);
     foreach ($files as $file) {
-      // image_get_info is a Drupal Function That Gets Details about an image
       $info = image_get_info($file->filename);
-      // first checks out the files, to make shure they're of a supported filetype
-      // Then fills out the import form with information about each image (including 2 text areas for title and body)
+
       if ($info && isset($info['extension'])) {
-        $filelist[] = substr($file->filename, strlen($dirpath) + 1);
-        $form['files']['filesize'][] = array(          '#type' => 'item',          '#value' => format_size(filesize($file->filename)),        );
-        $form['files']['dimensions'][] = array(          '#type' => 'item',          '#value' => $info['width'] .'x'. $info['height'],        );
-        $form['files']['title'][] = array(          '#type' => 'textfield',          '#size' => 20,          '#default_value' => basename($file->name),        );
-        $form['files']['body'][] = array(          '#type' => 'textfield',          '#size' => 20,        );
+        $filename = basename($file->filename);
+        $filelist[$filename] = ''; // we don't need labels on the checkboxes
+        $form['files']['filesize'][$filename] = array('#value' => format_size(filesize($file->filename)));
+        $form['files']['dimensions'][$filename] = array('#value' => $info['width'] .'×'. $info['height']);
+        $form['files']['title'][$filename] = array(
+          '#type' => 'textfield',
+          '#size' => 20,
+          '#default_value' => $file->name, // FIXME: make this configurable
+        );
+        $form['files']['body'][$filename] = array(
+          '#type' => 'textfield',
+          '#size' => 20,
+        );
       }
     }
-    // Remove our 0 elements.
-    unset($filelist[0]);
-    foreach ($fields as $field) {
-      $form['files'][$field][0] = NULL;
-    }
-    // Put the titles into an array.
+
+    // mark as trees so we can access the individual values later
     $form['files']['title']['#tree'] = TRUE;
     $form['files']['body']['#tree'] = TRUE;
-    // Store a copy of the list into a form value so we can compare it to what
-    // they submit and not have to worry about files being added or removed from
-    // the filesystem.
-    $form['file_list']         = array('#type' => 'value',      '#value' => $filelist,    );
-    $form['import_file']       = array('#type' => 'checkboxes', '#options' => $filelist,    );
-    $form['buttons']['submit'] = array( '#type' => 'submit',    '#value' => t('Import'),    );
-    $targetsetting = variable_get('imagefield_import_fieldname', FALSE);
-    list($type, $field) = split(":::", $targetsetting);
-    $form['conf_message']      = array('#type'  => 'item',      '#value' => t("Will import images into content type <b>'$type'</b>, field <b>'$field'</b>. To configure this visit the !settings page.", array('!settings' => l("Imagefield import settings", "admin/settings/imagefield_import"))),    );
+
+    // add checkboxes for the files in the upload directory
+    $form['import'] = array(
+      '#type' => 'checkboxes',
+      '#options' => $filelist,
+    );
+
+    $available = _imagefield_import_available_node_types();
+    list($type, $field) = split(':::', variable_get('imagefield_import_field', $available['keys'][0]));
+    $form['explanation'] = array(
+      '#prefix' => '<p>',
+      '#value' => t('Images will be imported to the %field field on the %type content type.', array('%field' => $field, '%type' => $type)),
+      '#suffix' => '</p>',
+    );
+
+    if (module_exists('taxonomy')) {
+      _imagefield_import_taxonomy_form($form, $type);
+    }
+
+    $form['buttons']['submit'] = array(
+      '#type' => 'submit',
+      '#value' => t('Import'),
+    );
   }
   else {
-    $form['import_file'] = array(      '#type' => 'item',       '#value' => t('No files were found'),    );
+    drupal_set_message(t('The upload directory is empty.'), 'warning');
   }
-  return $form;
-}
 
-//Theme the import form
-function theme_imagefield_import_form($form) {
-  $output =  "";
-    if (isset($form['conf_message'])) $output .= drupal_render($form['conf_message']);
-    if (!variable_get('imagefield_import_fieldname', FALSE) ) {
-      drupal_set_message("Could not import images. Please make sure to set Target Field on the ". l("Imagefield Settings", "admin/settings/imagefield_import") ." page.", "error");
-      return;
-    }
-    if (isset($form['import_file']) && $form['import_file']['#type'] == 'checkboxes') {
-      $header = array(theme('table_select_header_cell'), t('Name'), t('Size'), t('Dimensions'), t('Title'), t('Body'));
-      $rows = array();
-      foreach (element_children($form['import_file']) as $key) {
-      $filename = $form['import_file'][$key]['#title'];
-      unset($form['import_file'][$key]['#title']);
-      $rows[] = array(drupal_render($form['import_file'][$key]), $filename, drupal_render($form['files']['filesize'][$key]), drupal_render($form['files']['dimensions'][$key]), drupal_render($form['files']['title'][$key]), drupal_render($form['files']['body'][$key]), );
-    }
-    $output .= theme('table', $header, $rows);
-  }
-  return $output . drupal_render($form);
+  return $form;
 }
 
+/**
+ * Submit handler for the import form.
+ */
 function imagefield_import_form_submit($form, &$form_state) {
-  $op = isset($form_state['values']['op']) ? $form_state['values']['op']: '';
-  if ($op == t('Import')) {
-    $source_path = variable_get('imagefield_import_source_path', '');
-    if (file_check_directory($source_path)) {
-      // determine the node type, and the target fieldname to import into
-      $targetsetting = variable_get('imagefield_import_fieldname', FALSE);
-      list($node_type, $field) = split(":::", $targetsetting);
-      // try to avoid php's script timeout with a bunch of large files or a slow machine
-      if (!ini_get('safe_mode'))
-      set_time_limit(0);
-      foreach (array_filter($form_state['values']['import_file']) as $index) {
-        // Check the file is OK
-        $filename = $form_state['values']['file_list'][$index];
-        $source_filepath = file_check_location($source_path .'/'. $filename, $source_path);
-        if ($source_filepath and file_validate_is_image($source_filepath)) {
-          $file_info = image_get_info($source_filepath);
-          $file_info['filepath'] = $source_filepath;
-          // This is follwoing the method suggested by: http://drupal.org/node/292904 ...
-          $file = array($field => $file_info);
-          $title = $form_state['values']['title'][$index];
-          $caption = $form_state['values']['body'][$index];
-          $taxonomy = $form_state['values']['taxonomy'];
-          if (_imagefield_import_process_form($file, $node_type, $title, $caption, $taxonomy))
-          // delete original if it all went well.
-          file_delete($source_filepath);
-        }
-        else {
-          drupal_set_message('Problem with the file location:'. $source_filepath, 'error');
-        }
-      } // foreach( file )
+  $operations = array();
+
+  $path = variable_get('imagefield_import_path', '');
+  if (file_check_directory($path)) {
+    // create a batch operation for each selected file...
+    foreach ($form_state['values']['import'] as $filename => $import) {
+      $filepath = $path .'/'. $filename;
+      if ($import && file_check_location($filepath, $path)) {
+        $operations[] = array(
+          'imagefield_import_batch_import',
+          array(
+            $filepath,
+            $form_state['values']['title'][$filename],
+            $form_state['values']['body'][$filename],
+            $form_state['values']['taxonomy'],
+          ),
+        );
+      }
     }
-    else {
-      drupal_set_message('Source directory has not been set in the settings?', 'error');
+
+    // ...and set up a batch job to execute the operations
+    if (!empty($operations)) {
+      $batch = array(
+        'operations' => $operations,
+        'finished' => 'imagefield_import_batch_finished',
+        'title' => t('Importing images'),
+        'init_message' => t('Image import is starting.'),
+        'progress_message' => t('Processed @current out of @total.'),
+        'error_message' => t('Image import has encountered an error.'),
+      );
+      batch_set($batch);
     }
   }
 }
 
-/**
- * see: http://drupal.org/node/292904
- */
-function _imagefield_import_process_form($file_list, $node_type, $title, $caption, $taxonomy) {
-  // For field_file_save_file()
-  module_load_include('inc', 'filefield', 'field_file');
-  // Loop over all the field/filepath pairs and create files objects.
-  $files = array();
-  foreach ($file_list as $field_name => $file_info) {
-    // Load the field and figure out the specific details.
-    $field = content_fields($field_name, $node_type);
+/* --- BATCH ---------------------------------------------------------------- */
+
+function imagefield_import_batch_import($filepath, $title, $body, $taxonomy, &$context) {
+  if ($info = image_get_info($filepath)) {
+    list($type, $field_name) = split(':::', variable_get('imagefield_import_field', ''));
+
+    // get the field and its validators
+    $field = content_fields($field_name, $type);
     $validators = filefield_widget_upload_validators($field);
-    $files_path = _imagefield_import_widget_files_directory($field);
-    if (!$file = field_file_save_file($file_info['filepath'], $validators, $files_path))
-    return FALSE;
-    // Set defaults
-    $file['data'] = array(
-      'alt' => $file['field']['widget']['alt'],
-      'title' => $file['field']['widget']['title']
-    );
-    $files[$field_name] = $file;
-  }
-  // Create the node object.
-  return _imagefield_import_create_node($node_type, $files, $title, $caption, $taxonomy);
-}
 
-/**
- * see: http://drupal.org/node/292904
- */
-function _imagefield_import_create_node($node_type, $files, $title, $caption, $taxonomy) {
-  // For node_object_prepare()
-  module_load_include('inc', 'node', 'node.pages');
-  $node = new stdClass();
-  $node->type = $node_type;
-  global $user;
-  $node->uid = $user->uid;
-  $node->name = $user->name;
-  $node->title = $title;
-  $node->body = $caption;
-  node_object_prepare($node);
-  $node->field_caption[0] = array('value' => $caption);
-  $node->taxonomy = $taxonomy;
-  // Get the filefield module to do the saving and marking the record as permanent.
-  foreach ($files as $field_name => $file) {
-    if (isset($node->$field_name)) {
-      array_push($node->$field_name, $file);
-    }
-    else {
-      $node->$field_name = array(0 => $file);
+    // make sure that the directory exists
+    $directory = filefield_widget_file_path($field);
+    field_file_check_directory(&$directory, FILE_CREATE_DIRECTORY);
+
+    // save the file and create a node
+    if ($file = field_file_save_file($filepath, $validators, $directory)) {
+      $node = _imagefield_import_create_node($field, $title, $body, $taxonomy, $file);
+      file_delete($filepath); // FIXME: make this configurable
+
+      $context['results'][] = $filepath;
     }
   }
-  $node = node_submit($node);
-  node_save($node);
-  return $node;
 }
 
-/**
- * Determine the widget's files directory
- *
- * @param $field CCK field
- * @return files directory path.
- * see: http://drupal.org/node/292904
- */
-function _imagefield_import_widget_files_directory($field) {
-  $widget_file_path = $field['widget']['file_path'];
-  if (module_exists('token')) {
-    global $user;
-    $widget_file_path = token_replace($widget_file_path, 'user', $user);
+function imagefield_import_batch_finished($success, $results, $operations) {
+  if ($success) {
+    $message = t('@count images imported.', array('@count' => count($results)));
+    $message .= theme('item_list', $results);
   }
-  return file_directory_path() .'/'. $widget_file_path;
+  else {
+    $error_operation = reset($operations);
+    $message = t('An error occurred while processing %error_operation with arguments: @arguments', array('%error_operation' => $error_operation[0], '@arguments' => print_r($error_operation[1], TRUE)));
+  }
+
+  drupal_set_message($message);
 }
 
+/* --- UTILITY -------------------------------------------------------------- */
+
 /**
- * Create the imagefield_import_admin_settings that was called in callback arguments in hook_menu().
- *
- * @return unknown
+ * Find all node types containing an imagefield.
  */
-function imagefield_import_admin_settings() {
-  $form['file_paths'] = array(
-  '#title' => t('Image file paths'),
-  '#type' => 'fieldset',
-  '#description' => t('<p>Drupal will need to have write access to these directories so we can move and remove the files.</p>') .
-                    t("<p><strong>Note:</strong> a path begining with a <kbd>/</kbd> indicates the path is relative to the server's root, not the website's root.") .
-                    t("One starting without a <kbd>/</kbd> specifies a path relative to Drupal's root.") .
-                    t("For example: <kbd>/tmp/image</kbd> would be the temp directory off the root of the <strong>server</strong> while <kbd>tmp/image</kbd> would be a path relative to the Drupal's directory."),
-  );
-  $form['file_paths']['imagefield_import_source_path'] = array(
-  '#type' => 'textfield',
-  '#title' => t('Source path'),
-  '#default_value' => variable_get('imagefield_import_source_path', file_directory_path() .'/images/import'),
-  '#after_build' => array('_imagefield_import_settings_check_directory'),
-  '#description' => t('Where to find the images to import.'),
-  '#required' => TRUE,
-  );
-  //examine the node types they have available and find ones that have an imagefield associated with them
+function _imagefield_import_available_node_types() {
+  $available = array();
+
   $types = content_types();
-  $matches = array();
-  $keys = array();
   foreach ($types as $key => $type) {
     foreach ($type['fields'] as $field) {
-      if ($field['type']== 'filefield' and
-          $field['widget']['type']=='imagefield_widget'
-         ) {
-        $matches["$key:::$field[field_name]"] = $type['name'] .": ". $field['widget']['label'];
-        $keys[] = "$key:::$field[field_name]";
+      if ($field['type'] == 'filefield' && $field['widget']['type'] == 'imagefield_widget') {
+        $available['matches'][$key .':::'. $field['field_name']] = $type['name'] .': '. $field['widget']['label'];
+        $available['keys'][] = $key .':::'. $field['field_name'];
       }
     }
   }
-  if (count($matches) == 0 ) {
-    drupal_set_message("In order to import images into an imagefield, you must first have a node type that has an imagefield associated with it. "."Configure this on the ". l('Content Types', 'admin/content/types') .' Page', 'error');
-  }
-  else {
-  // see if there is no imagefield_import_fieldname variable set yet,
-  // if there is not one, lets set it to the first field we found, just
-  // in case the user does not hit the "Save configuration" button on this page
-  if (!variable_get('imagefield_import_fieldname', TRUE) )    variable_set('imagefield_import_fieldname', $keys[0]);
-    $form['imagefield_import_fieldname'] = array(
-      '#type' => 'select',
-      '#title' => 'Target field',
-      '#description' => t('Select the imagefield you want to batch import photos into. When you do the import, nodes of your selected type will be auto created and the selected field will be populated with the imported image.'),
-      '#options' => $matches,
-      '#default_value' => variable_get('imagefield_import_fieldname', $keys[0]),
-      '#required' => TRUE
-    );
-  }
-  return system_settings_form($form);
+
+  return $available;
 }
 
 /**
  * Checks the existence of the directory specified in $form_element.
- *
- * @param $form_element
- *   The form element containing the name of the directory to check.
- * @see system_check_directory()
- */
-function _imagefield_import_settings_check_directory($form_element) {
-  $import_dir = $form_element['#value'];
-  file_check_directory($import_dir, 0, $form_element['#parents'][0]);
+ */
+function _imagefield_import_check_directory($form_element) {
+  $directory = $form_element['#value'];
+
+  file_check_directory($directory, 0, $form_element['#parents'][0]);
+
   $imagefield_dir = file_create_path(variable_get('imagefield_default_path', 'images'));
-  if (realpath($import_dir) == realpath($imagefield_dir)) {
+  if (realpath($directory) == realpath($imagefield_dir)) {
     form_set_error($form_element['#parents'][0], t("You can't import from the image module's directory. The import deletes the original files so you would just be asking for trouble."));
   }
+
   return $form_element;
 }
 
 /**
- * Function Jacked Straight from the image.module
- * also allows  other modules to use to create image nodes.
- *
- * @param $filepath
- *   String filepath of an image file. Note that this file will be moved into
- *   the image module's images directory.
- * @param $title
- *   String to be used as the node's title. If this is ommitted the filename
- *   will be used.
- * @param $body
- *   String to be used as the node's body.
- * @param $taxonomy
- *   Taxonomy terms to assign to the node if the taxonomy.module is installed.
- * @return
- *   A node object if the node is created successfully or FALSE on error.
+ * Create a new node with an attached image file.
  */
-function imagefield_create_node_from($filepath, $title = NULL, $body = '', $taxonomy = NULL) {
+function _imagefield_import_create_node($field, $title, $body, $taxonomy, $file) {
   global $user;
-  if (!user_access('import images')) {
-    drupal_access_denied();
-  }
-  // Ensure it's a valid image.
-  if (!$image_info = image_get_info($filepath)) {
-    return FALE;
-  }
-  // Make sure we can copy the file into our temp directory.
-  $original_path = $filepath;
-  if (!file_copy($filepath, _imagefield_import_filename($filepath, IMAGE_ORIGINAL, TRUE))) {
-    return FALSE;
-  }
-  // Build the node.
-  // determine the node type, and the target fieldname to import into
-  $targetsetting = variable_get('imagefield_import_fieldname', FALSE);
-  // we are assuming that $targetsetting is a string here, and not FALSE because this condition was checked in the function that calls us
-  list($type, $field) = split(":::", $targetsetting);
+
+  module_load_include('inc', 'node', 'node.pages');
+
   $node = new stdClass();
-  $node->type = $type;
+
+  $node->type = $field['type_name'];
   $node->uid = $user->uid;
   $node->name = $user->name;
-  $node->title = isset($title) ? $title :
-  basename($filepath);
+  $node->title = $title;
   $node->body = $body;
-  // Set the node's defaults... (copied this from node and comment.module)
-  $node_options = variable_get('node_options_'. $node->type, array('status', 'promote'));
-  $node->status = in_array('status', $node_options);
-  $node->promote = in_array('promote', $node_options);
-  if (module_exists('comment')) {
-    $node->comment = variable_get("comment_{$node->type}", COMMENT_NODE_READ_WRITE);
-  }
+
+  node_object_prepare($node);
+
   if (module_exists('taxonomy')) {
     $node->taxonomy = $taxonomy;
   }
-  $node->new_file = TRUE;
-  $node->$field = array(
-    array(
-      'fid'   => 'upload',
-      'title' => basename($filepath),
-      'filename' => basename($filepath),
-      'filepath' => $filepath,
-      'filesize' => filesize($filepath),
-    ),
-  );
-  // Save the node.
+
+  $field_name = $field['field_name'];
+  $node->$field_name = array($file);
+
   $node = node_submit($node);
   node_save($node);
-  // Remove the original image now that the import has completed.
-  file_delete($original_path);
+
   return $node;
 }
 
 /**
- * Creates an image filename.
+ * Add the standard taxonomy form to the image import form.
  */
-function _imagefield_import_filename($filename, $label = IMAGE_ORIGINAL, $temp = FALSE) {
-  $path = variable_get('image_default_path', 'images') .'/';
-  if ($temp) {
-    $path .= 'temp/';
-  }
-  $filename = basename($filename);
-  // Insert the resized name in non-original images
-  if ($label && ($label != IMAGE_ORIGINAL)) {
-    $pos = strrpos($filename, '.');
-    if ($pos === FALSE) {
-      // The file had no extension - which happens in really old image.module
-      // versions, so figure out the extension.
-      $image_info = image_get_info(file_create_path($path . $filename));
-      $filename = $filename .'.'. $label .'.'. $image_info['extension'];
-    }
-    else {
-    $filename = substr($filename, 0, $pos) .'.'. $label . substr($filename, $pos);
-    }
-  }
-  return file_create_path($path . $filename);
+function _imagefield_import_taxonomy_form(&$form, $type) {
+  $form_id = $type .'_node_form';
+
+  $form['type'] = array('#type' => 'value', '#value' => $type);
+  $form['#node'] = new stdClass();
+  $form['#node']->type = $type;
+
+  taxonomy_form_alter($form, NULL, $form_id);
+
+  unset($form['type']);
+  unset($form['#node']);
 }
 
+/* --- THEME ---------------------------------------------------------------- */
+
 /**
- * Implementation of hook_theme().
+ * Theme the filename in the table on the import form.
  */
-function imagefield_import_theme() {
-  return array(
-    'imagefield_import_form' => array(
-      'arguments' => array(
-        'form' => NULL),
-    ),
-  );
+function theme_imagefield_import_filename($filename, $size, $dimensions) {
+  $output = '';
+
+  $output .= check_plain($filename) .'<br />';
+  $output .= '<div class="container-inline"><small>';
+  $output .= $dimensions .' &nbsp; '. $size;
+  $output .= '</small></div>';
+
+  return $output;
+}
+
+/**
+ * Theme the image import form.
+ */
+function theme_imagefield_import_form($form) {
+  $output = '';
+
+  if (isset($form['import'])) {
+    $header = array(theme('table_select_header_cell'), t('File'), t('Title'), t('Body'));
+
+    $rows = array();
+    foreach (element_children($form['import']) as $key) {
+      $row = array();
+
+      $row[] = drupal_render($form['import'][$key]);
+      $row[] = theme('imagefield_import_filename', $key, drupal_render($form['files']['filesize'][$key]), drupal_render($form['files']['dimensions'][$key]));
+      $row[] = drupal_render($form['files']['title'][$key]);
+      $row[] = drupal_render($form['files']['body'][$key]);
+
+      $rows[] = $row;
+    }
+
+    $output .= theme('table', $header, $rows);
+    $output .= '<div class="description">'. t('Click the checkboxes next to the images you want to import. You can add a title and a body to each image before you start the import.') .'</div>';
+  }
+
+  return $output . drupal_render($form);
 }
