You are here

function recipe_recipeML_import_form_submit in Recipe 6

Same name and namespace in other branches
  1. 7.2 modules/recipe_recipeML.module \recipe_recipeML_import_form_submit()
  2. 7 includes/recipe_recipeML.module \recipe_recipeML_import_form_submit()

File

plugins/recipe_recipeML.module, line 160
recipe_recipeML.module - Enables importing and exporting of recipeML format recipes.

Code

function recipe_recipeML_import_form_submit($form, &$form_state) {
  global $ingredient, $yield, $data_string, $recipes, $recipe, $user, $preptime;

  // save to a temp files
  if ($file = file_save_upload('recipe_import_file', array(), 'files', FILE_EXISTS_RENAME)) {
    drupal_set_message(t('The attached file was successfully uploaded'));
  }
  else {
    drupal_set_message(t('The attched file failed to upload.'), 'error');
    return;
  }
  $output = '';
  if ($file) {

    // Load the xml string.
    $data = file_get_contents($file->filepath);

    // Parse the data.
    $xml_parser = drupal_xml_parser_create($data);
    xml_set_element_handler($xml_parser, 'recipe_import_element_start', 'recipe_import_element_end');
    xml_set_character_data_handler($xml_parser, 'recipe_import_element_data');
    if (!xml_parse($xml_parser, $data, 1)) {
      $message = t('Failed to parse RecipeML file: %error at line %line.', array(
        '%error' => xml_error_string(xml_get_error_code($xml_parser)),
        '%line' => xml_get_current_line_number($xml_parser),
      ));
      watchdog('recipe', $message, WATCHDOG_WARNING);
      drupal_set_message($message, 'error');
    }

    // Free the parser.
    xml_parser_free($xml_parser);

    // Delete the upload file.
    file_delete($file->filepath);
    if ($_POST['op'] == t('Import')) {
      $vocabs = taxonomy_get_vocabularies('recipe');
      list($lightest_vid, $vocab) = each($vocabs);
      reset($vocabs);
      foreach ($recipes as $recipe) {
        $recipe->taxonomy = array();
        foreach ($recipe->_categories as $category) {

          // Search the lightest weight recipe vocab for this term.
          $term = recipe_get_term_by_name($category, $lightest_vid);

          // You didn't find that term, so add it.
          if ($term == FALSE && isset($lightest_vid)) {
            $term = array(
              'name' => $category,
              'vid' => $lightest_vid,
            );
            drupal_set_message(t('Adding term %term_name', array(
              '%term_name' => $category,
            )));
            taxonomy_save_term($term);

            // Cast back to object so it's like the return value from recipe_get_term_by_name().
            $term = (object) $term;
          }

          // You have the term now (existing or new), link it ink.
          if (isset($term)) {
            $recipe->taxonomy[] = $term->tid;
          }
        }

        // Save the recipe into its proper tables.
        node_save($recipe);
      }
    }
  }
}