public function add_term($term, $target_term = null, $before = false)
{
$new_term = $term;
if (is_string($term)) {
$new_term = new Term(array('term_display' => $term));
}
$new_term->vocabulary_id = $this->id;
$ref = 0;
DB::begin_transaction();
// If there are terms in the vocabulary, work out the reference point
if (!$this->is_empty()) {
if ($this->hierarchical) {
// If no parent is specified, put the new term after the last term
if (null == $target_term) {
$ref = DB::get_value('SELECT mptt_right FROM {terms} WHERE vocabulary_id=? ORDER BY mptt_right DESC LIMIT 1', array($this->id));
} else {
if (!$before) {
$ref = $target_term->mptt_right - 1;
} else {
$ref = $target_term->mptt_left - 1;
}
}
} else {
// If no before_term is specified, put the new term after the last term
if (!$before) {
$ref = DB::get_value('SELECT mptt_right FROM {terms} WHERE vocabulary_id=? ORDER BY mptt_right DESC LIMIT 1', array($this->id));
} else {
$ref = $target_term->mptt_left - 1;
}
}
// Make space for the new node
$params = array('vocab_id' => $this->id, 'ref' => $ref);
$res = DB::query('UPDATE {terms} SET mptt_right=mptt_right+2 WHERE vocabulary_id=:vocab_id AND mptt_right>:ref', $params);
if (!$res) {
DB::rollback();
return false;
}
$res = DB::query('UPDATE {terms} SET mptt_left=mptt_left+2 WHERE vocabulary_id=:vocab_id AND mptt_left>:ref', $params);
if (!$res) {
DB::rollback();
return false;
}
}
// Set the right and left appropriately
$new_term->mptt_left = $ref + 1;
$new_term->mptt_right = $ref + 2;
// Insert the new node
$result = $new_term->insert();
if ($result) {
DB::commit();
return $new_term;
} else {
DB::rollback();
return false;
}
}