Index: import_typepad/LICENSE.txt
===================================================================
Index: import_typepad/import_typepad.module
===================================================================
--- import_typepad/import_typepad.module	(revision 13667)
+++ import_typepad/import_typepad.module	(working copy)
@@ -1,9 +1,11 @@
 <?php 
+// $Id$
 /**
  * Module to import Type Pad exports into drupal
  * Based on node_import (the cvs content importer)
  * 
  * Nigel Sim <nigel.sim@gmail.com> 2005, 2006
+ * Sarah Jancich <sjancich@gmail.com> 2010
  */
 
 ini_set('auto_detect_line_endings', TRUE);
@@ -12,199 +14,277 @@
 define('_IMPORT_TYPEPAD', 'import_typepad');
 define('_ACTION_DELETE_FILE', 'Delete file from server');
 
-function import_typepad_help($section) {
-  switch ($section) {
-    case 'admin/modules#description':
-      return t('Import nodes from a typepad file.');
-    case 'admin/help#import_typepad': 
-      return t(' ', array('%admin-node-import_typepad' => url('admin/node/import_typepad'), '%admin-access-permission' => url('admin/access/permission')));
-  }
+/**
+ * Implementation of hook_perm().
+ */
+function import_typepad_perm() {
+  return array('import nodes');
 }
 
-function import_typepad_menu($may_cache) {
-  $links = array();
-  if ($may_cache) {
-    $links[] = array('path' => 'admin/node/import_typepad', 'title' => t('type pad'), 'callback' => 'import_typepad_page', 'weight' => 5, 'access' => user_access('import nodes'));
-    $links[] = array('path' => 'admin/node/import_typepad/preview', 'title' => t('type pad'), 'callback' => 'import_typepad_preview', 'weight' => 5, 'access' => user_access('import nodes'), 'type' => MENU_CALLBACK);
-  }
-  return $links;
+/**
+ * Implementation of hook_menu().
+ */
+function import_typepad_menu() {
+  $items['admin/content/import_typepad'] = array(
+    'title' => t('Import Typepad'),
+    'description' => t('Import posts from Typepad'),
+    'page callback' => 'import_typepad_page',
+    'page arguments' => array($form_values),
+    'access arguments' => array('import nodes'),
+  );
+
+  $items['admin/content/import_typepad/preview'] = array(
+    'title' => t('Import Typepad Preview'),
+    'page callback' => 'import_typepad_preview',
+    'page arguments' => array($previewCount),
+    'description' => t('Import posts from Typepad'),
+    'access arguments' => array('import nodes'),
+    'type' => MENU_CALLBACK
+  );
+  return $items;
 }
 
-function import_typepad_perm() {
-  return array('import nodes');  
+
+
+/**
+ * Show the front page, with either the current working file or a file selection form
+ */
+function import_typepad_page() {
+
+  $output = drupal_get_form('import_typepad_step1_form');
+  //is the comment module enabled?
+  if (!(module_exists('comment'))) {
+    drupal_set_message(t('If you would like to import comments, please enable the comments module prior to importing your Typepad posts. Otherwise, all Typepad comments will be lost.'), 'warning');
+  }
+  return $output;
 }
 
 /**
- * Show the front page, with either the current working file, or a file selection form
+ * Implementation of hook_form().
  */
-function import_typepad_page($form_values=NULL) {
+function import_typepad_step1_form($form_state) {
+  // get all of the content types for this Drupal installation
+  $types = db_query('SELECT DISTINCT type, name FROM {node_type} ORDER BY name ASC');
+  while ($row = db_fetch_object($types)) {
+    $opts[$row->type] = $row->name;
+  }
 
-  if ($edit[_WORKING_FILE]) {
-    $output .= form_item(t('File'), $edit[_WORKING_FILE] .' ('. format_size( filesize($edit[_WORKING_FILE]) ) .')<br />'. form_submit(t('Use a different file')));
+  // get all of the vocabs for this Drupal installation
+  $vocabs = taxonomy_get_vocabularies();
+  foreach ($vocabs as $v) {
+    $vocab[$v->name] = $v->name;
   }
-  else {
+
+  $form['#attributes'] = array('enctype' => 'multipart/form-data');
+
     $form['upload_file'] = array(
       '#type' => 'file',
       '#title' => t('Upload Type Pad/Movable Type file'),
-      '#description' => t('The export file you wish to import'));
+      '#description' => t('The export file you wish to import')
+  );
+
     $form['serverside_file'] = array(
       '#type' => 'textfield',
       '#title' => t('Server side file'),
-      '#description' => t('The file located on the server you wish to import'));
-  }
-  
-  // todo add an insert/update option
-  $form['submit'] = array(
-    '#type' => 'submit',
-    '#value' => t('Step 2'));
+      '#description' => t('The file located on the server you wish to import')
+  );
 
-  $form['#attributes'] = array('enctype' => 'multipart/form-data');
+  $form['content_type'] = array(
+      '#type' => 'select',
+      '#title' => t('Content type'),
+      '#default_value' => variable_get('import_typepad_content_type', NULL),
+      '#options' => $opts,
+      '#description' => t('The content type the new nodes will have.'),
+      '#required' => TRUE,
+  );
   
-  $output = drupal_get_form('typepad_step1', $form);
+  $form['vocab'] = array(
+      '#type' => 'select',
+      '#title' => t('Vocabulary'),
+      '#default_value' => variable_get('import_typepad_vocab', NULL),
+      '#options' => $vocab,
+      '#description' => t('The vocabulary with which you want to map taxonomy terms.'),
+      '#required' => TRUE,
+  );
 
-  return $output;
+  $form['submit'] = array(
+    '#type' => 'submit',
+    '#value' => t('Step 2')
+  );
+  return $form;
 }
 
 /**
- * Discover which file we are using, and move it into the appropriate position
+ * Complete the file upload and move it within the file store
  */
-function typepad_step1_validate($form_id, $form_values){
+function import_typepad_step1_form_validate($form, &$form_state) {
   global $user;
   global $base_url;
 
   $file = file_save_upload('upload_file');
-
   if (is_object($file) && $file->error == 0 && $file->filesize > 0) {
     drupal_set_message(t('Using uploaded file'));
-    file_move($file->filepath, 'drupal.import_typepad.'. strtr($base_url, array('http://' => '', '/' => '.')) .'.'. $user->uid, 1);
-    //$_SESSION[_IMPORT_TYPEPAD][_WORKING_FILE] = $file->filepath;
+    file_move($file->filepath, 'drupal.import_typepad.'.
+      strtr($base_url, array('http://' => '', '/' => '.')) .'.'. $user->uid, 1);
+
     variable_set(_WORKING_FILE, $file->filepath);
     variable_set(_FILE_TYPE, 'UPLOAD');
-  } else if (strlen($form_values['serverside_file'])>0 && file_exists($form_values['serverside_file'])){
-    drupal_set_message("Using server file ".$form_values['serverside_file']);
-    // See if there was a server file
-    variable_set(_WORKING_FILE, $form_values['serverside_file']);
+  }
+  elseif (strlen($form_state['values']['serverside_file']) > 0 && file_exists($form_state['values']['serverside_file'])) {
+    drupal_set_message('Using server file ' . $form_values['serverside_file']);
+    variable_set(_WORKING_FILE, $form_state['values']['serverside_file']);
     variable_set(_FILE_TYPE, 'SERVER');
-    //$_SESSION[_IMPORT_TYPEPAD][_WORKING_FILE] = $edit['serverfile'];
   }
 
-  if ( variable_get(_WORKING_FILE, null) == null ) {
+  if (!($file-->filename)) {
     form_set_error('file', t('You must select a file to import.'.variable_get(_FILE_TYPE,'missing')));
   }
+  //make sure the selected vocabulary is associated with the selected node type
+  if ($vocab = taxonomy_get_vocabularies($form_state['values']['content_type'])) {
+    foreach ($vocab as $v) {
+      if (strtolower($v->name) == strtolower($form_state['values']['vocab'])) {
+        $match = TRUE;
+      }
+    }
 }
+  if (!($match)) {
+    // get the vid
+    $vid = import_typepad_get_vocabulary_by_name($form_state['values']['vocab']);
+
+    form_set_error('content_type', t('Your selected content type is not associated with your selected vocabulary. Please <a href="@vocab/@vid">correct</a> and try again.', array('@vocab' => url('admin/content/taxonomy/edit/vocabulary'), '@vid' => $vid)));
+  }
+}
+
 
 /**
- * If the validation passed then simple redirect to the preview
+* Helper function that looks up a vid when we pass the vocab name
+* @return int
  */
-function typepad_step1_submit($form_id, $form_values){
-  return 'admin/node/import_typepad/preview';
+
+function import_typepad_get_vocabulary_by_name($vocabulary_name) {
+  $vocabs = taxonomy_get_vocabularies(NULL);
+  foreach ($vocabs as $vocab_object) {
+    if ($vocab_object->name == $vocabulary_name) {
+      return $vocab_object->vid;
+    }
+  }
+  return;
 }
 
 /**
- * If there is no file in progress then redirect to start
- * else display preview form
- * In due course we'll pass the preview count via the parameters
+ * If the validation passed, send the user to the preview page
+ */
+function import_typepad_step1_form_submit($form, &$form_state) {
+  variable_set('import_typepad_content_type', $form_state['values']['content_type']);
+  variable_set('import_typepad_vocab', $form_state['values']['vocab']);
+  $form_state['redirect'] = 'admin/content/import_typepad/preview';
+}
+
+/**
+ * If there is no file in progress then redirect to front page
+ * Otherwise, display preview form
  */
 function import_typepad_preview($previewCount = 10) {
   $authors = array();
   $cats = array();
-  $output = '';
-
-  $items = _import_typepad_get_nodes( variable_get(_WORKING_FILE, null), $edit['type'], $previewCount, $authors, $cats, array());
-
-
-  // Refresh preview w/ entry count
-
   // Previews
-  $output .= $items;
+  $output .= _import_typepad_get_nodes(variable_get(_WORKING_FILE, NULL), 'import_typepad', $previewCount = 10, $authors, $cats, array());
 
   // Mappings and import
   // Get user list
   $users = array();
 
-  $result = db_query('SELECT uid, name FROM {users};');
+  $result = db_query('SELECT uid, name FROM {users} where status = 1');
   while ($user = db_fetch_object($result)) {
     $users[$user->uid] = $user->name;
   }
+  return $output . drupal_get_form('import_typepad_process_form', $users, $authors, $cats);
+}
+
+function import_typepad_process_form($form_state, $users, $authors, $cats) {
+  $import_form['author_title'] = array(
+    '#type' => 'markup',
+    '#value' => t('<span>Author mappings</span>')
+  );
 
-  $import_form["author_title"] = array(
-    "#type" => "markup",
-    "#value" => t("<span>Author mappings</span>"));
   foreach ($authors as $author=>$uid){
     $import_form[$author] = array(
-      "#type" => 'select',
-      "#title"=> $author,
-      '#options' => $users);
+      '#type' => 'select',
+      '#title' => $author,
+      '#options' => $users,
+      '#required' => true
+    );
   }
 
-  $import_form["taxonomy_title"] = array(
-    "#type" => "markup",
-    "#value" => t("<span>Taxonomy mappings</span>"));
+  $import_form['taxonomy_title'] = array(
+    '#type' => 'markup',
+    '#value' => t('<span>Taxonomy mappings</span>')
+  );
 
   foreach ($cats as $cat=>$count){
-    $item = _import_typepad_taxonomy_list($cat);
-    $item['#title'] = "$cat ($count)";
+    $item = _import_typepad_taxonomy_list($cat, $count);
     $import_form['taxonomy_'.str_replace(' ','_',$cat)] = $item;
   }
+  $import_form['import_warning'] = array(
+    '#type' => 'markup',
+    '#value' => t('<span>Importing may take awhile, do not click \'Import\' more than once. To see progress, look at the <a href="?q=admin/node" target="_new">Administer -> Content</a> page in a new window.</span>')
+  );
 
-  $import_form["import_warning"] = array (
-    "#type" => "markup",
-    "#value" => t('<span>Importing may take awhile, do not click \'Import\' more than once. To see progress, look at the <a href="?q=admin/node" target="_new">Administer -> Content</a> page in a new window.</span>')  );
-
-  $import_form['submit'] = array('#type' => 'submit', '#value' => t('Import'));
-
-  $output .= drupal_get_form('import_typepad_process', $import_form);
+  $import_form['submit'] = array(
+    '#type' => 'submit',
+    '#value' => t('Import')
+  );
 
-  return $output;
+  return $import_form;
 }
 
 /**
  * This function returns a select box of name taxonomy_ESCAPEDNAME
- * with all the blog categories in it.
+ * with all terms from the selected vocabulary
  */
-function _import_typepad_taxonomy_list($name){
+function _import_typepad_taxonomy_list($name, $count) {
   if (user_access('access content')) {
-    $default = '';
-    $vocabs = taxonomy_get_vocabularies('blog');
-    $items = array();
-    foreach ($vocabs as $vocab) {
-      $tree = taxonomy_get_tree($vocab->vid);
-      foreach ($tree as $term) {
-        $items[$term->tid] = _taxonomy_depth($term->depth) .' '.$term->name;
-	if ($name == $term->name){
-          $default = $term->tid;
+    $v = variable_get('import_typepad_content_type', FALSE);
+    if ($v) {
+      $title = "$name ($count)";
+      $vocab = db_fetch_object(db_query("select vid, tags from {vocabulary} where name = '%s'", variable_get('import_typepad_vocab', '')));
+      if ($vocab) {
+        if ($vocab->tags) {
+          return array(
+            '#type' => 'textfield',
+            '#title' => $title,
+            '#default_value' => $name,
+          );
 	}
+        else
+          return _taxonomy_term_select($title, null, $name, $vocab->vid, null, false, '');
       }
     }
-    return array(
-      "#type" => "select",
-      "#default_value" => $default,
-      "#options" => $items );
   }
 }
 
 /**
- * Simply run the import, passing the form in for the taxonomy and author maps
+ * Run the import, passing the form values for the taxonomy and author maps
  */
-function import_typepad_process_submit($formid, $form_elements){
+function import_typepad_process_form_submit($form, &$form_state) {
   $cats = array(); // unused
-  $items = _import_typepad_get_nodes( variable_get(_WORKING_FILE, null), $edit['type'], 0, $form_elements, $cats, $form_elements);
-  if ( variable_get(_FILE_TYPE, null) == 'UPLOAD'){
-    unlink( variable_get(_WORKING_FILE, null) );
+  $items = _import_typepad_get_nodes( variable_get(_WORKING_FILE, NULL), 'import_typepad', 0, $form_state['values'], $cats, $form_state['values']);
+  if (variable_get(_FILE_TYPE, FALSE) == 'UPLOAD') {
+    unlink( variable_get(_WORKING_FILE, FALSE) );
   }
   variable_del(_WORKING_FILE);
   variable_del(_FILE_TYPE);
-  return 'admin/node/import_typepad';
+  variable_del('import_typepad_content_type');
+  variable_del('import_typepad_content_type');
+  $form_state['redirect'] = 'admin/content/import_typepad';
 }
 
 /**
  * Setup and perform the import
- * STEP 3
  */
 function _import_typepad_import(&$edit) {
   $output .= form_item(t('File'), $edit[_WORKING_FILE] .' ('. format_size( filesize($edit[_WORKING_FILE]) ) .')');
   $output .= form_submit(t(_ACTION_DELETE_FILE)); 
-
   $authorMap = array();
   $cats = array();
   foreach ($_POST['edit'] as $id=>$val){
@@ -212,31 +292,12 @@
   	  $authorMap[substr($id, strlen("author_map_"))] = $val;
   	}
   }
-
   $edit['errors'] = 0;
-  $output .= _import_typepad_get_nodes($edit[_WORKING_FILE], $edit['type'], $edit['type'] == 'import_typepad' ? NULL : $edit['match'], $edit['global'], $edit['errors'], $authorMap, $cats, $edit);
+  $output .= _import_typepad_get_nodes(variable_get(_WORKING_FILE, NULL), 'import_typepad', 'import_typepad', $edit['global'], $edit['errors'], $authorMap, $cats, $edit);
   unset($edit['match']);
-
-  return form($output);
+  return $output;
 }
 
-/**
- * Perform the delete function and return to the start page
- */ /*
-function import_typepad_delete($form, $edit) {
-  echo "<!-- _import_typepad_import_validate -->";
-  if ($op == t(_ACTION_DELETE_FILE)) {
-    if (file_delete($edit['file']->filepath)) {
-      drupal_set_message(t('Deleted the CSV file from the server.'));
-    }
-    $edit = array();
-  }
-  else if ($op == t('Download rows with errors')) {
-    $_SESSION['import_typepad_page'] = '_import_typepad_errors';
-  }
-  return 'admin/content/import_typepad';
-}
-*/
 function _import_typepad_errors($edit) {
   header('Content-type: text/comma-separated-values');
   header('Content-Disposition: attachment; filename="rejected-'. $edit['filename'] .'"');
@@ -267,20 +328,21 @@
  * @return preview
  */
 function _import_typepad_get_nodes($path, $type, $preview, &$authors, &$cats, $taxonomy) {
+
   $handle = fopen($path, 'r');
-  if ($handle == null)
-    return false;
+  if ($handle == NULL)
+    return FALSE;
 
   $success = 0;
 
-  $run = true;
-  $currentBlog = null;
+  $run = TRUE;
+  $currentBlog = NULL;
   $state = 0; // 0-unknown, 1-blog, 2-comment, 3-skip, 4-blog body, 5-blog excerpt
   $previewCount = 0;
   $blogCats = array();
   
-  $mapping = array('TITLE:'=>'title',
-    'ALLOW COMMENTS:'=>'comment', 'EMAIL:'=>'mail', 'IP:'=>'hostname', 'URL:'=>'homepage');
+  $mapping = array('TITLE:' => 'title', 'ALLOW COMMENTS:' => 'comment',  'EMAIL:' => 'mail',
+    'IP:' => 'hostname', 'URL:' => 'homepage');
     
   while ($run){
     while ($line = fgets($handle)){
@@ -289,45 +351,52 @@
       $line = trim($line);
       if ($line == "-----"){
         $state = 0;
-      } else if ($line == "--------"){
+      }
+      elseif ($line == "--------") {
         $state = 0;
         // We currently want to ignore these sections
-      } else if (in_array($line, array("EXCERPT:","KEYWORDS:"))) {
+      }
+      elseif (in_array($line, array("EXCERPT:", "KEYWORDS:"))) {
       	$state = 3;
-      } else if ($line == "EXTENDED BODY:"){
+      }
+      elseif ($line == "EXTENDED BODY:") {
       	$state = 4;
-      } else if ($line == "BODY:"){
+      }
+      elseif ($line == "BODY:") {
       	$state = 5;
-      } else if ( !(strpos($line,"COMMENT:") === FALSE) ){
-      	// We are working on a comment
-	//echo "<!-- Starting new comment -->\n";
+      }
+      elseif (!(strpos($line, "COMMENT:") === FALSE)) {
       	$state = 2;
-        $currentBlog->comments[] = new StdClass();
-      } else if ( !(strpos($line, "DATE:") === FALSE )){
+        $currentBlog->comments[] = new stdClass();
+      }
+      elseif (!(strpos($line, "DATE:") === FALSE )) {
       	if ($state == 1){
       	  $currentBlog->created = strtotime(substr($line,strlen("DATE:")));
-      	} else if ($state == 2) {
+        }
+        elseif ($state == 2) {
       	  $currentBlog->comments[count($currentBlog->comments)-1]->timestamp = strtotime(substr($line,strlen("DATE:")));
-      	} else {
-	  //echo "<!-- ERROR -->\n";
 	}
-      } else if ( !(strpos($line, "STATUS:") === FALSE ) ){
+      }
+      elseif (!(strpos($line, "STATUS:") === FALSE)) {
       	$value = trim(substr($line,strlen("STATUS:")));
       	if (strcmp($value, "Publish") == 0){
           $currentBlog->status = 1;
-      	} else {
+        }
+        else {
           $currentBlog->status = 0;
       	}
-      } else if ( !(strpos($line,"CATEGORY:") === FALSE) ){
+      }
+      elseif (!(strpos($line, "CATEGORY:") === FALSE)) {
         $category = trim(substr($line, strpos($line,"CATEGORY:") + strlen("CATEGORY:")));
 	$cats[$category]++;
 	$blogCats[] = $category; // Add the category to this entry
-      } else if ( !(strpos($line,"AUTHOR:") === FALSE) ){
+      }
+      elseif (!(strpos($line, "AUTHOR:") === FALSE) ) {
       	// If state is unknown, then the new item is a blog, not a comment
       	if ($state == 0){
       	  $state = 1;
       	  // Save the last blog
-      	  if ($currentBlog != null){
+          if ($currentBlog != NULL) {
             $currentBlog->body = strlen(trim($currentBlog->body))==0?$currentBlog->teaser:$currentBlog->body;
       	    if (!$preview){
               $c = array();
@@ -336,7 +405,8 @@
               }
               _import_typepad_save($currentBlog, $c);
               $success++;
-      	    } else if ($previewCount < $preview){
+            }
+            elseif ($previewCount < $preview) {
     	      $output .= node_view($currentBlog);
     	      $previewCount++;
             }
@@ -344,63 +414,71 @@
       		
       	  // Start new blog
           $blogCats = array();
-      	  $currentBlog = new StdClass();
-      	  $currentBlog->type = 'blog';
+          $currentBlog = new stdClass();
+          $currentBlog->type = variable_get('import_typepad_content_type', 'blog');
       	  $currentBlog->author = trim( substr($line, strpos($line,"AUTHOR:") + strlen("AUTHOR:")) );
       	  // We generate a hash for the author name which can be used in HTML forms
       	  $authorHash = 'author_map_'.str_replace(" ","_",$currentBlog->author);
       	  if (!array_key_exists($authorHash, $authors)){
       	    $authors[$authorHash] = 0;
-      	  } else if (!$preview) {
+          }
+          elseif (!$preview) {
       	    $currentBlog->uid = $authors[$authorHash];
       	  }
-
       	  $currentBlog->comments = array();
-      		
-      	} else if ($state == 2) {
+        }
+        elseif ($state == 2) {
       	  $currentBlog->comments[count($currentBlog->comments)-1]->name = substr($line, strlen("AUTHOR:"));
-      	} else {
-      		echo "<h1>ERROR 1 State = $state</h1>";
       	}
-      } else {
-        //echo "<!-- $state $rawLine -->\n";
-        
+        else {
+          echo "<h1>ERROR 1 State = ". $state . "</h1>";
+        }
+      }
+      else {
   	$sep = strpos($line, ":");
-	if ($sep === false){ // || !array_key_exists($name, $mapping)){
+        if ($sep === FALSE) {
           $name = "";
 	  $value = "";
-	} else {
+        }
+        else {
   	  $name = substr($line, 0, $sep+1);
   	  $value = substr($line, $sep+1);
 	}
-
       	if ($state == 1){
       	  $prop = $mapping[$name];
-	  if (strlen($prop) > 0 )
+          if (strlen($prop) > 0 ) {
   	    $currentBlog->$prop = $value;
-      	} else if ($state == 2){
-	  //echo "<!-- $name $val $sep -->\n";
+          }
+        }
+        elseif ($state == 2) {
       	  if (strlen($name) > 0 && array_key_exists($name, $mapping)){
       	    $currentBlog->comments[count($currentBlog->comments)-1]->$mapping[$name] = $value;
-      	  } else {
+          }
+          else {
       	    $currentBlog->comments[count($currentBlog->comments)-1]->comment .= $rawLine;
       	  }
-      	} else if ($state == 3){
+        }
+        elseif ($state == 3) {
       		// Do nothing (Skip)
-      	} else if ($state == 4){
+        }
+        elseif ($state == 4) {
       		// Blog body
       		$currentBlog->body .= $rawLine;
-      	} else if ($state == 5){
+          $currentBlog->format = 2;
+        }
+        elseif ($state == 5) {
       		$currentBlog->teaser .= $rawLine;
-      	} else if ($state == 0){
+        }
+        elseif ($state == 0) {
       		//Do nothing, to avioid errors over nothing
-      	} else {
+        }
+        else {
       		echo "<h1>ERROR 2</h1>";
-      		echo "<pre>$state : $line</pre>";
+          echo '<pre>' . $state . ' : ' . $line . '</pre>';
       	}
       }
     }
-    $run = false;
+    $run = FALSE;
     $currentBlog->body = strlen(trim($currentBlog->body))==0?$currentBlog->teaser:$currentBlog->body;
     if (!$preview){
       $c = array();
@@ -409,25 +487,18 @@
       }
       _import_typepad_save($currentBlog, $c);
       $success++;
-    } else if ($previewCount < $preview){
+    }
+    elseif ($previewCount < $preview) {
       $output .= node_view($currentBlog);
       $previewCount++;
     }
   }
 
   fclose($handle);
-  /*
-  if ($errors) {
-    // todo use drupal_set_message?
-    drupal_set_message(t('%errors. Click \'Download rows with errors\' for a CSV file of the failed rows.', array('%errors' => format_plural(count($errors), 'There was 1 error', 'There were %count errors'))));
-    $output = form_submit(t('Download rows with errors')) . $output;
-    $errors;
-  }
-  */
   if ($success) {
-    drupal_set_message(t('Successfully imported %count.', array('%count' => format_plural($success, '1 node', '%count nodes'))));
+    drupal_set_message(t('Successfully imported %count.',
+      array('%count' => format_plural($success, '1 node', $success .' nodes'))));
   }
-  
   return $output;
 }
 
@@ -435,40 +506,53 @@
  * Save the content into the database, first the blogs, then the comments
  */
 function _import_typepad_save($currentBlog, $terms){
-  if ($currentBlog != null){
+  if ($currentBlog != NULL) {
   // Apply all the substitutions
   $subReplace = $_REQUEST['import_typepad_substitution_replace'];
   $subWith = $_REQUEST['import_typepad_substitution_with'];
   
-  if (!is_null($subReplace))
+    if (!is_null($subReplace)) {
     foreach ($subReplace as $id=>$val){
       $currentBlog->teaser = str_replace($val, $subWith[$id], $currentBlog->teaser);
       $currentBlog->body = str_replace($val, $subWith[$id], $currentBlog->body);
     }
+    }
   
   // Save the entry
   node_save($currentBlog);
 
   // Save taxonomy items
   $terms = array_unique($terms);
-  taxonomy_node_save($currentBlog->nid, $terms);
   
-  //echo "<!-- Number of comments = ".count($currentBlog->comments)." -->\n";
+     if ($terms) {
+       $vocab = db_fetch_object(db_query("select vid, tags from {vocabulary} where name = '%s'", variable_get('import_typepad_vocab', '')));
+       if ($vocab->tags)
+         $taxonomy['tags'][$vocab->vid] = implode(', ', $terms);
+       else {
+         foreach ($terms as $t) {
+           $taxonomy[] = taxonomy_get_term($t);
+         }
+       }
+       taxonomy_node_save($currentBlog, $taxonomy);
+     }
+
+     if (module_exists('comment')) {
   foreach ($currentBlog->comments as $comment){
     // Most of the following code is ripped straight from comment.module
-    $cid = db_next_id('{comments}_cid');
+         $cid = db_last_insert_id('{comments}_cid', 'cid');
   	
     // This is a comment with no parent comment (depth 0): we start
     // by retrieving the maximum thread level.
     $max = db_result(db_query('SELECT MAX(thread) FROM {comments} WHERE nid = %d', $edit['nid']));
-    //echo "<!-- max thread = $max -->\n";
     // Strip the "/" from the end of the thread.
     $max = rtrim($max, '/');
 
-    // Next, we increase this value by one.  Note that we can't
-    // use 1, 2, 3, ... 9, 10, 11 because we order by string and
-    // 10 would be right after 1.  We use 1, 2, 3, ..., 9, 91,
-    // 92, 93, ... instead.  Ugly but fast.
+         /**
+          * Next, we increase this value by one.  Note that we can't
+          * use 1, 2, 3, ... 9, 10, 11 because we order by string and
+          * 10 would be right after 1.  We use 1, 2, 3, ..., 9, 91,
+          * 92, 93, ... instead.
+          */
     $decimals = (string) substr($max, 0, strlen($max) - 1);
     $units = substr($max, -1, 1);
     if ($units) {
@@ -477,19 +561,21 @@
     else {
       $units = 1;
     }
-
     if ($units == 10) {
       $units = '90';
     }
-
     // Finally, build the thread field for this new comment.
     $thread = $decimals . $units .'/';
           
     // Type pad doesn't have threaded comments, or subject lines, so we have to improvise them
-  	db_query("INSERT INTO {comments} (cid, nid, pid, uid, subject, comment, format, hostname, timestamp, status, score, users, thread, name, mail, homepage) VALUES (%d, %d, %d, %d, '%s', '%s', %d, '%s', %d, %d, %d, '%s', '%s', '%s', '%s', '%s')", 
-  	  $cid, $currentBlog->nid, 0/*pid*/, 0, "re: ".$currentBlog->title, $comment->comment, 1/*format*/, $comment->hostname, $comment->timestamp, 0/*status*/, 0/*score*/, ''/*$users*/, $thread, $comment->name, $comment->mail, $comment->homepage);
-  	_comment_update_node_statistics($nid);
+         db_query("INSERT INTO {comments} (nid, pid, uid, subject, comment, format, hostname,
+        timestamp, status, thread, name, mail, homepage) VALUES (%d, %d, %d, '%s', '%s', %d, '%s', %d,
+          %d, '%s', '%s', '%s', '%s')", $currentBlog->nid, 0/*pid*/, 0, "re: ". $currentBlog->title,
+                  $comment->comment, 1/*format*/, $comment->hostname, $comment->timestamp, 0/*status*/,
+                  $thread, $comment->name, $comment->mail, $comment->homepage);
+
+         _comment_update_node_statistics($currentBlog->nid);
+       }
   }
 }
 }
-?>
Index: import_typepad/import_typepad.info
===================================================================
--- import_typepad/import_typepad.info	(revision 13667)
+++ import_typepad/import_typepad.info	(working copy)
@@ -1,17 +1,10 @@
+; $Id$
 name = "Import Typepad"
-description = "Imports Typepad/MoveableType backup files to Content Types"
-version = "5.x-dev"
-project = "import_typepad"
-
-; Information added by drupal.org packaging script on 2008-09-24
-version = "5.x-1.0"
-project = "import_typepad"
-datestamp = "1222234217"
-
+description = "Imports content from Typepad"
+core = 6.x
 
 ; Information added by drupal.org packaging script on 2008-09-25
 version = "6.x-1.0"
 core = "6.x"
 project = "import_typepad"
 datestamp = "1222316414"
-
Index: import_typepad/README.txt
===================================================================
--- import_typepad/README.txt	(revision 0)
+++ import_typepad/README.txt	(revision 0)
@@ -0,0 +1,18 @@
+Import TypePad export into Drupal
+Nigel Sim <nigel.sim@gmail.com>
+
+http://ihpc.jcu.edu.au/~jc118215/index.php?n=Main.TypePadToDrupal
+
+Instructions
+-----------------------------------
+   1. Download your type pad export
+   2. Upload the export file to the server (optional)
+   3. Download the latest release
+   4. gunzip it in the DRUPAL/modules directory
+   5. Log in to drupal as admin
+   6. Goto admin/modules and activate the import_tp module
+   7. Goto admin -> content -> type pad
+   8. Select the file from the local machine, or put in the location on the server. Click next
+   9. See the preview. At the bottom of the page there is a list of distinct bloggers. Select the local user to map to each of them. Also select mappings for categories, as well as setting up substitutions, such as URLs for images.
+  10. Click next... wait
+  11. DONE! 
Index: import_typepad/README
===================================================================
--- import_typepad/README	(revision 13667)
+++ import_typepad/README	(working copy)
@@ -1,18 +0,0 @@
-Import TypePad export into Drupal
-Nigel Sim <nigel.sim@gmail.com>
-
-http://ihpc.jcu.edu.au/~jc118215/index.php?n=Main.TypePadToDrupal
-
-Instructions
------------------------------------
-   1. Download your type pad export
-   2. Upload the export file to the server (optional)
-   3. Download the latest release
-   4. gunzip it in the DRUPAL/modules directory
-   5. Log in to drupal as admin
-   6. Goto admin/modules and activate the import_tp module
-   7. Goto admin -> content -> type pad
-   8. Select the file from the local machine, or put in the location on the server. Click next
-   9. See the preview. At the bottom of the page there is a list of distinct bloggers. Select the local user to map to each of them. Also select mappings for categories, as well as setting up substitutions, such as URLs for images.
-  10. Click next... wait
-  11. DONE! 
