You are here

function _add_biblio_keywords in Bibliography Module 7.2

Same name and namespace in other branches
  1. 6 biblio.install \_add_biblio_keywords()
  2. 7 biblio.install \_add_biblio_keywords()

Copies keywords from the biblio_keyword column of the biblio table to a taxonomy vocabulary

Return value

none

File

./biblio.install, line 256

Code

function _add_biblio_keywords() {
  set_time_limit(300);
  $kw_sep = variable_get('biblio_keyword_sep', ',');
  $vid = ($vid = variable_get('biblio_keyword_vocabulary', 0)) ? $vid : _enable_biblio_keyword_vocabulary();
  if ($vid) {
    $db_result = db_query("SELECT b.biblio_keywords, b.nid, b.vid FROM {biblio} b");
    $result = array();
    foreach ($db_result as $row) {
      foreach (explode($kw_sep, $row->biblio_keywords) as $keyword) {
        $result[] = array(
          'value' => trim($keyword),
          'nid' => $row->nid,
          'vid' => $row->vid,
        );
      }
      db_query('DELETE tn.* FROM {term_node} tn INNER JOIN {term_data} td ON tn.tid = td.tid WHERE nid = %d AND td.vid = %d', $row->nid, $vid);
    }
    $inserted = array();
    $count = 0;
    foreach ($result as $keywords) {

      // See if the term exists in the chosen vocabulary
      // and return the tid; otherwise, add a new record.
      $possibilities = taxonomy_get_term_by_name($keywords['value']);
      $term_tid = NULL;

      // tid match, if any.
      foreach ($possibilities as $possibility) {
        if ($possibility->vid == $vid) {
          $term_tid = $possibility->tid;
        }
      }
      if (!$term_tid) {
        $term = array(
          'vid' => $vid,
          'name' => $keywords['value'],
        );
        $status = taxonomy_save_term($term);
        $term_tid = $term['tid'];
      }

      // Defend against duplicate, differently cased tags
      if (!isset($inserted[$keywords['vid']][$term_tid])) {
        db_query('INSERT INTO {term_node} (nid, vid, tid) VALUES (%d, %d, %d)', $keywords['nid'], $keywords['vid'], $term_tid);
        $inserted[$keywords['vid']][$term_tid] = TRUE;
        $count++;
      }
    }
    return array(
      'success' => TRUE,
      'query' => 'Added ' . $count . ' keywords to the biblio/taxonomy keyword vocabulary',
    );
  }
  return array(
    'success' => FALSE,
    'query' => 'Biblio keyword vocabulary not available',
  );
}