Location: PHPKode > projects > Kwalbum > kwalbum/include/funcChangeTags.php
<?php
/**
 * Check a string list of tags for sql injection then use them to
 * replace the item's old mapped list in the database.
 * @version 2.1.1
 * @package kwalbum
 * @since 2.0
 * @param int $itemId id of the item the tags should be changed on
 * @param string $newTags new comma seperated tags to replace the old
 * tags.  It does not have to be checked for sql injection before
 * calling this function.
 * @param bool $echo if anything should be output to the browser
 * @param string $errorMsg what to say to the user when it fails
 * @return bool if it was successful or not
 */
function ChangeTags($itemId, $newTags, $echo = true, $errorMsg = '')
{
	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>';
		elseif ($echo)
			echo $errorMsg;
		return false;
	}
	$row = $result->fetch_array();
	if (USER_ID != $row[1] and !USER_IS_ADMIN)
	{
		if (TEST_MODE)
			echo '<p class="error">Invalid Permissions</p>';
		elseif ($echo)
			echo $errorMsg;
		return false;
	}

	// delete old tags
	$DB->UpdateSingle(TAG_TABLE, 'TagCount', 'TagCount-1', "TagId IN " .
			"(SELECT TagIdFk FROM " . TAG_MAP_TABLE .
			" WHERE ItemIdFk=$itemId)");
	$query = 'DELETE FROM ' . TAG_MAP_TABLE .
			" WHERE ItemIdFk=$itemId";
	$DB->Query($query);

	// 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>';
					elseif ($echo)
						echo $errorMsg;
					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);
			}
		}
	}

	if ($echo)
		echo $newTags;
	return true;
}
Return current item: Kwalbum