/** * Vote for the entry * * @param integer $vote The vote [-1, 1, like, dislike, yes, no, positive, negative] * @param integer $user_id Optinal user ID to set as voter * @return boolean False if error, True on success */ public function vote($vote = 0, $user_id = 0) { if ($this->isNew()) { $this->setError(Lang::txt('No record found')); return false; } $al = new Vote(); $vote = $al->automaticVote(array('vote' => $vote)); if ($vote === 0) { $this->setError(Lang::txt('No vote provided')); return false; } $user = $user_id ? User::getInstance($user_id) : User::getRoot(); $al->set('object_id', $this->get('id')); $al->set('type', 'article'); $al->set('ip', Request::ip()); $al->set('user_id', $user->get('id')); $al->set('vote', $vote); // Has user voted before? $previous = $al->find($al->get('object_id'), $al->get('user_id'), $al->get('ip'), $al->get('type')); if ($previous->get('vote')) { $voted = $al->automaticVote(array('vote' => $previous->get('vote'))); // If the old vote is not the same as the new vote if ($voted != $vote) { // Remove old vote $previous->destroy(); // Reset the vote count switch ($voted) { case 'like': $this->set('helpful', (int) $this->get('helpful') - 1); break; case 'dislike': $this->set('nothelpful', (int) $this->get('nothelpful') - 1); break; } } else { return true; } } if ($this->get('created_by') == $user->get('id')) { $this->setError(Lang::txt('COM_KB_NOTICE_CANT_VOTE_FOR_OWN')); return false; } switch ($vote) { case 'like': $this->set('helpful', (int) $this->get('helpful') + 1); break; case 'dislike': $this->set('nothelpful', (int) $this->get('nothelpful') + 1); break; } // Store the changes to vote count if (!$this->save()) { return false; } // Store the vote log if (!$al->save()) { $this->setError($al->getError()); return false; } return true; }