public function vote($suggestId, $direction)
{
if ($direction != "up" && $direction != "down") {
throw new Exception(L::get("SUGGESTION_VOTE_ERROR"));
}
$sth = $this->db->prepare("SELECT 1 FROM suggestions WHERE id = ?");
$sth->bindParam(1, $suggestId, PDO::PARAM_INT);
$sth->execute();
$suggest = $sth->fetch(PDO::FETCH_ASSOC);
if (!$suggest) {
throw new Exception(L::get("SUGGESTION_NOT_FOUND"), 404);
}
$userVoteWeight = $this->getUserVoteWeight($this->user->getClass(), $direction);
$sth = $this->db->prepare("SELECT voteWeight FROM suggestions_votes WHERE suggestionId = ? AND userid = ?");
$sth->bindParam(1, $suggestId, PDO::PARAM_INT);
$sth->bindValue(2, $this->user->getId(), PDO::PARAM_INT);
$sth->execute();
$res = $sth->fetch();
if (!$res) {
$sth = $this->db->prepare("INSERT INTO suggestions_votes (userid, suggestionId, voteWeight) VALUES(?, ?, ?)");
$sth->bindValue(1, $this->user->getId(), PDO::PARAM_INT);
$sth->bindParam(2, $suggestId, PDO::PARAM_INT);
$sth->bindParam(3, $userVoteWeight, PDO::PARAM_INT);
$sth->execute();
} else {
if ($res[0] > 0 && $direction == "down" || $res[0] < 0 && $direction == "up") {
$this->db->query('DELETE FROM suggestions_votes WHERE userid = ' . $this->user->getId() . ' AND suggestionId = ' . $suggestId);
} else {
if ($res[0] != $userVoteWeight) {
$this->db->query('UPDATE suggestions_votes SET voteWeight = ' . $userVoteWeight . ' WHERE userid = ' . $this->user->getId() . ' AND suggestionId = ' . $suggestId);
}
}
}
$numVotes = $this->getNumVotesBySuggestion($suggestId);
$this->updateSuggestionWithVoteSum($numVotes, $suggestId);
return array("numVotes" => $numVotes);
}