Exemplo n.º 1
0
  /**
   * return "OK" only delete
   *        > 0 - usual behavior: first delete then insert
   *        0  error
   */
	function insert_vote($value = 0) {
		global $current_user, $db;

		if (!$value) $value = $current_user->user_karma;

		$vote = new Vote('comments', $this->id, $current_user->user_id);

    $result = 'CREATE'; // vote doesn't exits?

		if ($old_value = $vote->exists(false)) { // save old vote value
      $result = 'REPLACE';
      $vote->delete_comment_vote($old_value); // always destroy current vote

      // check if they have the same sign
      if ($value * $old_value > 0) {
        return Array('DELETE',$old_value); // equal => only delete
      }
		}

		// Affinity
		if ($current_user->user_id != $this->author
				&& ($affinity = User::get_affinity($this->author, $current_user->user_id)) ) {
			if ($value < -1 && $affinity < 0) {
					$value = round(min(-1, $value *  abs($affinity/100)));
			} elseif ($value > 1 && $affinity > 0) {
					$value = round(max($value * $affinity/100, 1));
			}
		}

    $value>0?$svalue='+'.$value:$svalue=$value;

		$vote->value = $value;
		$db->transaction();
		if($vote->insert()) {
			if ($current_user->user_id != $this->author) {
        //echo "update comments set comment_votes=comment_votes+1, comment_karma=comment_karma$svalue, comment_date=comment_date where comment_id=$this->id";
				$db->query("update comments set comment_votes=comment_votes+1, comment_karma=comment_karma$svalue, comment_date=comment_date where comment_id=$this->id");
			}
		} else {
			$vote->value = false;
		}
		$db->commit();

    if ($result == 'CREATE') {
      return Array($result, $vote->value);
    } else { // replace
      return Array($result, $old_value);
    }
	}