<?php
// 2.0
function AppendTags($itemId, $newTags)
{
global $DB, $P;
$query = 'SELECT ItemId, ItemUserIdFk FROM ' . ITEM_TABLE .
" WHERE ItemId='$itemId'" .
" LIMIT 1";
$result = $DB->Query($query);
if (0 == $result->num_rows)
{
if (TEST_MODE)
echo '<p class="error">Item ID ('.$itemId.') was not found in the DB.</p>';
return;
}
$row = $result->fetch_array();
if (!USER_CAN_ADD or (USER_ID != $row[1] and !USER_IS_ADMIN))
{
if (TEST_MODE)
echo '<p class="error">Invalid Permissions</p>';
return;
}
// save new tags
$tags = explode(',',$newTags);
foreach ($tags as $tag)
{
$tag = $DB->FilterString(trim($tag));
if (!empty($tag))
{
$alreadyAdded = false; // to prevent duplicates from "tag1,tag2,tag1" type input
$query = 'SELECT TagId FROM ' . TAG_TABLE .
" WHERE Tag='$tag'" .
" LIMIT 1";
$result = $DB->Query($query);
if (!$row = $result->fetch_array())
{
$insertData = array (
'Tag' => $tag,
'TagCount' => 1
);
$tagId = $DB->Insert(TAG_TABLE, $insertData);
if (false === $tagId)
{
if (TEST_MODE)
echo '<p class="error">Error inserting into tag table.</p>';
return false;
}
} else
{
$tagId = $row[0];
$query = 'SELECT TagIdFk FROM ' . TAG_MAP_TABLE .
" WHERE TagIdFk=$tagId AND ItemIdFk=$itemId" .
" LIMIT 1";
$result = $DB->Query($query);
if (1 == $result->num_rows)
$alreadyAdded = true;
else
$DB->UpdateSingle(TAG_TABLE, 'TagCount', 'TagCount+1', "TagId=$tagId");
}
if (false == $alreadyAdded)
{
$insertData = array (
'ItemIdFk' => $itemId,
'TagIdFk' => $tagId
);
$DB->Insert(TAG_MAP_TABLE, $insertData);
}
}
}
}
?>