public static function saveTags($otherId, $tags, $module, $language = null)
{
$otherId = (int) $otherId;
$module = (string) $module;
$language = $language != null ? (string) $language : BL::getWorkingLanguage();
// redefine the tags as an array
if (!is_array($tags)) {
$tags = (array) explode(',', (string) $tags);
}
// make sure the list of tags contains only unique and non-empty elements
$tags = array_filter(array_unique($tags));
// get db
$db = BackendModel::getContainer()->get('database');
// get current tags for item
$currentTags = (array) $db->getPairs('SELECT i.tag, i.id
FROM tags AS i
INNER JOIN modules_tags AS mt ON i.id = mt.tag_id
WHERE mt.module = ? AND mt.other_id = ? AND i.language = ?', array($module, $otherId, $language));
// remove old links
if (!empty($currentTags)) {
$db->delete('modules_tags', 'tag_id IN (' . implode(', ', array_values($currentTags)) . ') AND other_id = ? AND module = ?', array($otherId, $module));
}
if (!empty($tags)) {
// loop tags
foreach ($tags as $key => $tag) {
// cleanup
$tag = mb_strtolower(trim($tag));
// unset if the tag is empty
if ($tag == '') {
unset($tags[$key]);
} else {
$tags[$key] = $tag;
}
}
// don't do a regular implode, mysql injection might be possible
$placeholders = array_fill(0, count($tags), '?');
// get tag ids
$tagsAndIds = (array) $db->getPairs('SELECT i.tag, i.id
FROM tags AS i
WHERE i.tag IN (' . implode(',', $placeholders) . ') AND i.language = ?', array_merge($tags, array($language)));
// loop again and create tags that don't already exist
foreach ($tags as $tag) {
// doesn' exist yet
if (!isset($tagsAndIds[$tag])) {
// insert tag
$tagsAndIds[$tag] = self::insert($tag, $language);
}
}
// init items to insert
$rowsToInsert = array();
// loop again
foreach ($tags as $tag) {
// get tagId
$tagId = (int) $tagsAndIds[$tag];
// not linked before so increment the counter
if (!isset($currentTags[$tag])) {
$db->execute('UPDATE tags SET number = number + 1 WHERE id = ?', $tagId);
}
// add to insert array
$rowsToInsert[] = array('module' => $module, 'tag_id' => $tagId, 'other_id' => $otherId);
}
// insert the rows at once if there are items to insert
if (!empty($rowsToInsert)) {
$db->insert('modules_tags', $rowsToInsert);
}
}
// add to search index
BackendSearchModel::saveIndex($module, $otherId, array('tags' => implode(' ', (array) $tags)), $language);
// decrement number
foreach ($currentTags as $tag => $tagId) {
// if the tag can't be found in the new tags we lower the number of tags by one
if (array_search($tag, $tags) === false) {
$db->execute('UPDATE tags SET number = number - 1 WHERE id = ?', $tagId);
}
}
// remove all tags that don't have anything linked
$db->delete('tags', 'number = ?', 0);
}