You are here

function heartbeat_edit_tags in Heartbeat 6.4

Edit (add, update) the heartbeat tags

2 calls to heartbeat_edit_tags()
heartbeat_message_insert in ./heartbeat.module
Inserts a heartbeat message
heartbeat_message_update in ./heartbeat.module
Updates a heartbeat message

File

./heartbeat.module, line 1534

Code

function heartbeat_edit_tags($hid, $_tags) {
  $stored_tags = heartbeat_get_available_tags();
  $message_tags = heartbeat_get_available_tags($hid);
  $tags = empty($_tags) ? array() : (is_string($_tags) ? explode(",", $_tags) : $_tags);

  // Insert non existing tags
  if (!empty($tags)) {
    foreach ($tags as $tag) {
      $tag = trim($tag);

      // If the tag itself is not known yet, insert it
      if (!in_array($tag, $stored_tags)) {
        db_query("INSERT INTO {heartbeat_tags} (name) VALUES ('%s')", $tag);
        $last_htid = db_last_insert_id('heartbeat_tags', 'htid');
      }
      else {
        $last_htid = array_search($tag, $message_tags) | array_search($tag, $stored_tags);
      }

      // The tag certainly exists now, check if it's linked to this message yet
      if (!isset($message_tags[$last_htid])) {
        db_query("INSERT INTO {heartbeat_mt} (htid, hid) VALUES (%d, %d)", $last_htid, $hid);
      }
    }
  }

  // Check if tags should be deleted
  if (!empty($message_tags)) {
    foreach ($message_tags as $htid => $message_tag) {
      if (!in_array($message_tag, $tags)) {

        // Always check if this was the last reference to the tag
        if (db_result(db_query("SELECT COUNT(mtid) FROM {heartbeat_tags} ht INNER JOIN {heartbeat_mt} hmt ON ht.htid = hmt.htid WHERE ht.name = '%s'", $message_tag)) == 1) {
          db_query("DELETE FROM {heartbeat_tags} WHERE htid = %d", $htid);
        }

        // Delete the reference to the heartbeat message
        db_query("DELETE FROM {heartbeat_mt} WHERE hid = %d AND htid = %d", $hid, $htid);
      }
    }
  }
  return TRUE;
}