How to get rid of unused tags? And how to merge tags?

Hi.
I’ve been working on the “merge” part, and manage to have it working by changing the code (if anybody wants to try to turn the changes into a plugin, is more than welcome, although maybe the changes could be implemented in the core of a future release). Here’s what I’ve done:

file application/controllers/TagsController.php (modified the last 5 lines)

public function renameAjaxAction() {
        $csrf = new Omeka_Form_SessionCsrf;
        $oldTagId = $_POST['pk'];
        $oldTag = $this->_helper->db->findById($oldTagId);
        $oldName = $oldTag->name;
        $newName = trim($_POST['value']);
        $error = __('Error occurred.');

        $oldTag->name = $newName;
        $this->_helper->viewRenderer->setNoRender();
        if ($csrf->isValid($_POST)) {
			if ($oldTag->save(false)) {
				$this->getResponse()->setBody($newName);
			} else {
				$newTag = $this->_helper->db->findOrNew($newName);
				$newTagId = $newTag->id;
				$this->_helper->db->mergeTags($oldTagId, $newTagID);
			}
		} else {
	        $this->getResponse()->setHttpResponseCode(500);
			$this->getResponse()->setBody($error);
        }
    }
}

and file application/models/Table/Tag.php (new function added)

public function mergeTags($oldTagId, $newTagId) {
        $db = $this->getDb();
        $sql = "UPDATE $db->RecordsTag SET tag_id = $newTagId, time = CURRENT_TIMESTAMP WHERE tag_id = $oldTagId AND record_id NOT IN (SELECT record_id FROM (SELECT DISTINCT record_id FROM $db->RecordsTag WHERE tag_id = $newTagId) AS tmptable)";
		$db->query($sql);
		$sql = "DELETE FROM $db->RecordsTag WHERE tag_id = $oldTagId";
		$db->query($sql);
		$sql = "DELETE FROM $db->Tag WHERE id = $oldTagId";
		$db->query($sql);
}

Now, here’re some possible improvements, in case anybody wanted to contribute:

  1. before the merging takes place, a message box asking for confirmation;
  2. after the merging has taken place, update the count of the tag, at the same time hiding the emptied one;
  3. error message in case of mishap during the merging.

Hope this helps.