You are here

function term_merge_merge_form_submit in Term Merge 6

Same name and namespace in other branches
  1. 5 term_merge.module \term_merge_merge_form_submit()

Actually merges the terms

File

./term_merge.module, line 69

Code

function term_merge_merge_form_submit($form, &$form_state) {

  //print implode(",",$form_state['values']);
  $to_term = taxonomy_get_term($form_state['values']['to_tid']);
  $from_term = taxonomy_get_term($form_state['values']['from_tid']);
  $old_max_exec = ini_get('max_execution_time');
  if ($old_max_exec < 30) {
    $old_max_exec = 30;
  }
  set_time_limit(100);

  // Copy any Synonyms from from_term to to_term.
  // I'd love to do this with a Drupal func, but taxonomy_save_term() looks like way more trouble than it's worth
  db_query("INSERT INTO {term_synonym} (tid, name) (SELECT '%d',name from {term_synonym} where tid = '%d')", $to_term->tid, $from_term->tid);

  //TODO: This could lead to duplicate synonyms.

  // save a list of nodes we need to update to new term
  $nodes_to_update = _term_merge_select_nodes($from_term->tid);

  // Add from_node as a synonym to to_node to prevent future duplication
  db_query("INSERT INTO {term_synonym} (tid, name) VALUES (%d, '%s')", $to_term->tid, $from_term->name);

  //TODO: This could lead to duplicate synonyms.

  // update old nodes to new nodes
  while ($node_record = db_fetch_object($nodes_to_update)) {
    $node = node_load($node_record->nid);

    // gotta use node_load to get the taxonomies in there
    $save_node_changes = TRUE;
    $new_taxonomy = array();
    foreach ($node->taxonomy as $term) {
      if ($term->tid == $to_term->tid) {

        // If the node already has the destination tag, we don't need to change a thing!
        // (taxonomy_del_term will take care of removing the old tag)
        $save_node_changes = FALSE;
        break;
      }
      if ($term->tid == $from_term->tid) {
        $new_taxonomy[] = $to_term;

        // make the switch!
      }
      else {
        $new_taxonomy[] = $term;
      }
    }
    if ($save_node_changes) {
      taxonomy_node_save($node, $new_taxonomy);
    }

    // note for 6.x: taxonomy_node_save was changed to take a $node object instead of $nid
  }
  taxonomy_del_term($from_term->tid);
  set_time_limit($old_max_exec);
  drupal_set_message(t('The terms have been merged. Have a great day.'));
  $form_state['redirect'] = 'admin/content/taxonomy/' . $to_term->vid;
}