<?php

// -----------------------------------------------------------------------
// This file is part of aroundme
//
// Copyright (C) 2003, 2005 Barnraiser
// http://www.barnraiser.org/
// info@barnraiser.org
//
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the
// Free Software Foundation; either version 2, or (at your option) any
// later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with program; see the file COPYING. If not, write to the Free
// Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
// 02111-1307, USA.
// -----------------------------------------------------------------------



class Poll {
	// CLASS FUNCTIONS
	// Poll
	// getPoll
	// getOptions
	// answerSummary
	// pollUserCurrentVote
	// selPolls
	// getRspPolls
	// updatePoll
	// insertPoll
	// deletePoll
	// insertOption
	// updateOption
	// deleteOption
	// pollUserVoteHistory
	// getUserPollParticipation
	// updateAnswer
	// getPollCount



	// Poll --------------------------------------------------------------------
	// the constuctor
	// tom calthrop - 24th Feb 2004
	//
	function Poll($db, $rsp_item_type_id, $date) {
		$this->db = $db;
		$this->rsp_item_type_id = $rsp_item_type_id;
		$this->date = $date;
	}//EO Poll




	// getPoll --------------------------------------------------------------------
	// returns a single record from the DB
	// tom calthrop - 24th Feb 2004
	//
	function getPoll() {

		$query = "
			SELECT p.*
			FROM " . $this->db->prefix . "_poll p
			WHERE
			p.poll_id=" . $this->poll_id
		;

		$result = $this->db->Execute($query);

		if (isset($result->fields)) {

			$temp = $result->fields;

			$temp['display_poll_start_datetime'] = $this->date->formatDate($temp['poll_start_datetime']);
			$temp['display_poll_end_datetime'] = $this->date->formatDate($temp['poll_end_datetime']);

			$temp['options'] = $this->getOptions();
			$temp['total_votes'] = $this->total_votes;


			//get percentages
			foreach($temp['options'] as $key => $i):
				$temp['options'][$key]['percent'] = 0;

				if ($i['votes'] > 0) {
				    $percent = round((100/$this->total_votes)* $i['votes']);
					$temp['options'][$key]['percent'] = $percent;
				}
			endforeach;

			$result->Close();
			return $temp;
		}
		else {
			$error_info = "function=getPoll class=Poll.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['am_error_log'][] = array(1, 1, $error_info);
		}
	}//EO getPoll



	// getOptions --------------------------------------------------------------------
	// get the options for the poll
	// tom calthrop - 24th Feb 2004
	//
	function getOptions() {
		$total_votes = 0;

		$query = "
			SELECT option_id, option_body, option_create_datetime
			FROM " . $this->db->prefix . "_poll_option
			WHERE
			poll_id=" . $this->poll_id
		;

		$result = $this->db->Execute($query);

		if (isset($result->fields)) {

			$temp = array();

			while (!$result->EOF) {
				$temp1 =  $result->fields;
				$temp1['votes'] = $this->answerSummary($temp1['option_id']);
				$total_votes = $total_votes + $temp1['votes'];
				array_push($temp, $temp1);
				$result->MoveNext();
			}

			$result->Close();

			$this->total_votes = $total_votes;
			return $temp;
		}
		else {
			$error_info = "function=getOptions class=Poll.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['am_error_log'][] = array(1, 1, $error_info);
		}
	}//EO getOptions



	// answerSummary --------------------------------------------------------------------
	// returns count of the ansers received per poll option given
	// tom calthrop - 24th Feb 2004
	//
	function answerSummary($option_id) {
		$query = "
			SELECT count(answer_id) as total
			FROM " . $this->db->prefix . "_poll_answer
			WHERE
			current_answer=1 and
			option_id=" . $option_id
		;

		$result = $this->db->Execute($query);

		if (isset($result->fields)) {
			$temp = $result->fields;
			$result->Close();
			return $temp['total'];
		}
		else {
			$error_info = "function=answerSummary class=Poll.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['am_error_log'][] = array(1, 1, $error_info);
		}
	}//EO answerSummary



	// pollUserCurrentVote --------------------------------------------------------------------
	// returns the current vote for a user
	// tom calthrop - 24th Feb 2004
	//
	function pollUserCurrentVote($user_id = null) {

		if (empty($user_id)) {
		    $user_id = $this->user_id;
		}

		$query = "
			SELECT answer_id, poll_id, current_answer, answer_create_datetime,
			option_id
			FROM " . $this->db->prefix . "_poll_answer
			WHERE
			user_id=" . $user_id . " and
			poll_id=" . $this->poll_id . " and
			current_answer=1
			order by answer_create_datetime"
		;
		$result = $this->db->Execute($query);

		if (isset($result->fields)) {
			$temp = $result->fields;
			$result->Close();
			return $temp;
		}
		else {
			$error_info = "function=pollUserCurrentVote class=Poll.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['am_error_log'][] = array(1, 1, $error_info);
		}
	}//EO pollUserCurrentVote



	// selPolls --------------------------------------------------------------------
	// returns multiple rows of polls
	// tom calthrop - 24th Feb 2004
	//
	function selPolls() {

		$query = "
			SELECT p.poll_id, p.poll_question, p.poll_anon, p.vote_required,
			p.poll_create_datetime, p.poll_start_datetime, p.poll_end_datetime, p.group_id 
			FROM " . $this->db->prefix . "_poll p
			WHERE "
		;
		
		if (isset($this->user_id)) {
		    $query .= "p.user_id=" . $this->user_id . " AND ";
		}
		
		if (isset($this->group_id)) {
		    $query .= "p.group_id=" . $this->group_id . " AND ";
		}
		
		if (isset($this->poll_ids)) { //used for bookmarks
			$poll_ids = "";
			foreach($this->poll_ids as $key => $i):
				$poll_ids .= $i;
				if (count($this->poll_ids) > $key+1) {
					$poll_ids .=",";
				}
			endforeach;
			$query .= "p.poll_id in (" . $poll_ids . ") AND ";
		}
	
		if (isset($this->before_start_timestamp)) {
			$datetime = date("Y-m-d H:i:s", $this->before_start_timestamp);
			$datetime = $this->db->DBDate($datetime);
			$query .= "p.poll_start_datetime <= " . $datetime . " AND ";
		}

		if (isset($this->after_start_timestamp)) {
			$datetime = date("Y-m-d H:i:s", $this->after_start_timestamp);
			$datetime = $this->db->DBDate($datetime);
			$query .= "p.poll_start_datetime >= " . $datetime . " AND ";
		}
	
		if (isset($this->before_end_timestamp)) {
			$datetime = date("Y-m-d H:i:s", $this->before_end_timestamp);
			$datetime = $this->db->DBDate($datetime);
			$query .= "p.poll_end_datetime <= " . $datetime . " AND ";
		}

		if (isset($this->after_end_timestamp)) {
			$datetime = date("Y-m-d H:i:s", $this->after_end_timestamp);
			$datetime = $this->db->DBDate($datetime);
			$query .= "p.poll_end_datetime >= " . $datetime . " AND ";
		}
		
		$query .="1=1 ";

		if (isset($this->order_by)) {
		    $query .= "order by " . $this->order_by;
		}
		else {
			$query .= "order by p.poll_question";
		}

		if (isset($this->limit)) {
			$result = $this->db->SelectLimit($query, $this->limit);
		} else {
			$result = $this->db->Execute($query);
		}

		$result = $this->db->Execute($query);

		if (isset($result->fields)) {

			$temp = array();

			while (!$result->EOF) {
				$temp1 = $result->fields;

				$temp1['display_poll_start_datetime'] = $this->date->formatDate($temp1['poll_start_datetime'], 1);
				$temp1['display_poll_end_datetime'] = $this->date->formatDate($temp1['poll_end_datetime'], 1);

				$this->poll_id = $temp1['poll_id'];

				$temp1['options'] = $this->getOptions();
				$temp1['total_votes'] = $this->total_votes;


				//get percentages
				if (isset($temp1['options'])) {

					foreach($temp1['options'] as $key => $i):
						$temp1['options'][$key]['percent'] = 0;

						if ($i['votes'] > 0) {
						    $percent = round((100/$this->total_votes)* $i['votes']);
							$temp1['options'][$key]['percent'] = $percent;
						}
					endforeach;
				}

				array_push($temp, $temp1);
				$result->MoveNext();
			}

			$result->Close();
			return $temp;
		}
		else {
			$error_info = "function=selPolls class=Poll.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['am_error_log'][] = array(1, 1, $error_info);
		}
	}//EO selPolls



	// selRspPolls --------------------------------------------------------------------
	// returns multiple rows of polls
	// tom calthrop - 24th Feb 2004
	//
	function selRspPolls($search = null) {

		$query = "
			SELECT p.poll_id, p.group_id, p.poll_question, p.poll_anon, p.vote_required,
			p.poll_create_datetime, p.poll_start_datetime, p.poll_end_datetime,
			rsp.rsp_sticky
			FROM " . $this->db->prefix . "_poll p, " .$this->db->prefix . "_rsp rsp
			WHERE
			rsp.item_id=p.poll_id AND
			rsp.level_id=" . $this->rsp_level_id . " AND 
			rsp.rsp_item_type_id=" . $this->rsp_item_type_id . " AND "
		;
		
		if (isset($this->rsp_status_id)) {
		    $query .= "rsp.status_id=" . $this->rsp_status_id . " AND ";
		}
		
		if (isset($this->degree_id)) {
		    $query .= "rsp.degree_id>=" . $this->degree_id . " AND ";
		}

		if (isset($this->user_id)) {
		    $query .= "p.user_id=" . $this->user_id . " AND ";
		}
		
		if (isset($this->group_id)) {
		    $query .= "p.group_id=" . $this->group_id . " AND ";
		}

		if (isset($this->before_start_timestamp)) {
			$datetime = date("Y-m-d H:i:s", $this->before_start_timestamp);
			$datetime = $this->db->DBDate($datetime);
			$query .= "poll_start_datetime <= " . $datetime . " AND ";
		}

		if (isset($this->after_start_timestamp)) {
			$datetime = date("Y-m-d H:i:s", $this->after_start_timestamp);
			$datetime = $this->db->DBDate($datetime);
			$query .= "poll_start_datetime >= " . $datetime . " AND ";
		}

		if (isset($this->before_end_timestamp)) {
			$datetime = date("Y-m-d H:i:s", $this->before_end_timestamp);
			$datetime = $this->db->DBDate($datetime);
			$query .= "poll_end_datetime <= " . $datetime . " AND ";
		}

		if (isset($this->after_end_timestamp)) {
			$datetime = date("Y-m-d H:i:s", $this->after_end_timestamp);
			$datetime = $this->db->DBDate($datetime);
			$query .= "poll_end_datetime >= " . $datetime . " AND ";
		}

		if (isset($search)) {
			$query .= "
				(p.poll_question like " . $this->db->qstr("%" . $search . "%", get_magic_quotes_gpc()) . ") AND "
			;
		}

		if (isset($this->user_ids)) {
			$user_ids = "";
			foreach($this->user_ids as $key => $i):
				$user_ids .= $i;
				if (count($this->user_ids) > $key+1) {
					$user_ids .=",";
				}
			endforeach;
			$query .="p.user_id in (" . $user_ids . ") and ";
		}

		$query .="1=1 ";

		if (isset($this->order_by)) {
		    $query .= "order by " . $this->order_by;
		}
		else {
			$query .= "order by p.poll_question";
		}

		if (isset($this->limit)) {
			$result = $this->db->SelectLimit($query, $this->limit);
		} else {
			$result = $this->db->Execute($query);
		}

		$result = $this->db->Execute($query);

		if (isset($result->fields)) {

			$temp = array();

			while (!$result->EOF) {
				$temp1 = $result->fields;

				$temp1['display_poll_start_datetime'] = $this->date->formatDate($temp1['poll_start_datetime'], 1);
				$temp1['display_poll_end_datetime'] = $this->date->formatDate($temp1['poll_end_datetime'], 1);

				$this->poll_id = $temp1['poll_id'];

				$temp1['options'] = $this->getOptions();
				$temp1['total_votes'] = $this->total_votes;


				//get percentages
				if (isset($temp1['options'])) {

					foreach($temp1['options'] as $key => $i):
						$temp1['options'][$key]['percent'] = 0;

						if ($i['votes'] > 0) {
						    $percent = round((100/$this->total_votes)* $i['votes']);
							$temp1['options'][$key]['percent'] = $percent;
						}
					endforeach;
				}

				if (isset($search)) { //format search results
					$temp1['poll_question'] = searchTextFormat($search, $temp1['poll_question']);
				}

				array_push($temp, $temp1);
				$result->MoveNext();
			}

			$result->Close();
			return $temp;
		}
		else {
			$error_info = "function=selRspPolls class=Poll.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['am_error_log'][] = array(1, 1, $error_info);
		}
	}//EO selRspPolls




	// updatePoll --------------------------------------------------------------------
	// updates a single poll record in DB
	// tom calthrop - 24th Feb 2004
	//
	function updatePoll($data) {
		
		if (empty($data['poll_start_datetime'])) {
		    $data['poll_start_datetime'] = "null";
		}
		
		if (empty($data['poll_end_datetime'])) {
		    $data['poll_end_datetime'] = "null";
		}
		
		if (isset($data['poll_anon'])) {
			$poll_anon = 1;
		}
		else {
			$poll_anon = "null";
		}

		if (isset($data['vote_required'])) {
			$vote_required = 1;
		}
		else {
			$vote_required = "null";
		}
		
		$query = "
			SELECT * FROM " . $this->db->prefix . "_poll 
			WHERE 
			poll_id=" . $this->poll_id
		;
		
		$result = $this->db->Execute($query);
		
		$rec = array();
		$rec['poll_question'] = $data['poll_question'];
		$rec['poll_start_datetime'] = $data['poll_start_datetime'];
		$rec['poll_end_datetime'] = $data['poll_end_datetime'];
		$rec['poll_edit_datetime'] = time();
		$rec['poll_anon'] = $poll_anon;
		$rec['vote_required'] = $vote_required;
		
		$query = $this->db->GetUpdateSQL($result, $rec, false, get_magic_quotes_gpc());
		$result = $this->db->Execute($query);
		
	}//EO updatePoll



	// insertPoll --------------------------------------------------------------------
	// inserts a single poll record in DB
	// tom calthrop - 24th Feb 2004
	//
	function insertPoll($data) {
		
		if (empty($data['poll_start_datetime'])) {
		    $data['poll_start_datetime'] = "null";
		}
		
		if (empty($data['poll_end_datetime'])) {
		    $data['poll_end_datetime'] = "null";
		}
		
		if (isset($data['poll_anon'])) {
			$poll_anon = 1;
		}
		else {
			$poll_anon = "null";
		}

		if (isset($data['vote_required'])) {
			$vote_required = 1;
		}
		else {
			$vote_required = "null";
		}
		
		if (isset($this->group_id)) {
		    $group_id = $this->group_id;
		}
		else {
			$group_id = "null";
		}
		
		$rec = array();
		$rec['group_id'] = $group_id;
		$rec['poll_question'] = $data['poll_question'];
		$rec['poll_start_datetime'] = $data['poll_start_datetime'];
		$rec['poll_end_datetime'] = $data['poll_end_datetime'];
		$rec['poll_anon'] = $poll_anon;
		$rec['poll_create_datetime'] = time();
		$rec['user_id'] = $this->user_id;
		$rec['vote_required'] = $vote_required;
		
		$table = $this->db->prefix . "_poll";
		
		$query = $this->db->GetInsertSQL($table, $rec, get_magic_quotes_gpc());
		$result = $this->db->Execute($query);
		
		if (isset($result->fields)) {
				
			$this->poll_id = $this->db->Insert_ID();
		}
		else {
			$error_info = "function=insertPoll class=Poll.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['am_error_log'][] = array(1, 1, $error_info);
		}
	}//EO insertPoll



	// deletePoll --------------------------------------------------------------------
	// inserts a single poll record in DB
	// tom calthrop - 24th Feb 2004
	//
	function deletePoll() {

		$query = "
			DELETE FROM " . $this->db->prefix . "_poll
			WHERE
			poll_id=" .  $this->poll_id
		;

		$result = $this->db->Execute($query);

		if (empty($result->fields)) {
			$error_info = "function=deletePoll class=Poll.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['am_error_log'][] = array(1, 1, $error_info);
		}
	}//EO deletePoll



	// insertOption --------------------------------------------------------------------
	// inserts a single poll record in DB
	// tom calthrop - 24th Feb 2004
	//
	function insertOption($option_body) {
		
		$rec = array();
		$rec['poll_id'] = $this->poll_id;
		$rec['option_body'] = $option_body;
		$rec['option_create_datetime'] = time();
		$rec['user_id'] = $this->user_id;
		
		$table = $this->db->prefix . "_poll_option";
			
		$query = $this->db->GetInsertSQL($table, $rec, get_magic_quotes_gpc());
		$result = $this->db->Execute($query);
		
	}//EO insertOption



	// updateOption --------------------------------------------------------------------
	// updates a single poll record in DB
	// tom calthrop - 24th Feb 2004
	//
	function updateOption($option_id, $option_body) {
		
		$query = "
			SELECT * FROM " . $this->db->prefix . "_poll_option
			WHERE 
			option_id=" . $option_id
		;
		
		$result = $this->db->Execute($query);
		
		$rec = array();
		$rec['option_body'] = $option_body;
		$rec['option_edit_datetime'] = time();
		$rec['user_id'] = $this->user_id;
		
		$query = $this->db->GetUpdateSQL($result, $rec, false, get_magic_quotes_gpc());
		$result = $this->db->Execute($query);
		
	}//EO updateOption



	// deleteOption --------------------------------------------------------------------
	// deletes a single poll record in DB
	// tom calthrop - 24th Feb 2004
	//
	function deleteOption($option_id) {

		$query = "
			DELETE FROM " . $this->db->prefix . "_poll_option
			WHERE
			option_id=" . $option_id
		;

		$result = $this->db->Execute($query);

		if (empty($result->fields)) {
			$error_info = "function=deleteOption class=Poll.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['am_error_log'][] = array(1, 1, $error_info);
		}
	}//EO deleteOption




	// pollUserVoteHistory --------------------------------------------------------------------
	// returns the history of the votes given by a user to a poll (used in forum subjects)
	// tom calthrop - 24th Feb 2004
	//
	function pollUserVoteHistory($user_id) {

		//display a poll
		$query = "
			SELECT pa.answer_create_datetime, o.option_body
			FROM " . $this->db->prefix . "_poll_answer pa, " . $this->db->prefix . "_poll_option o
			where
			pa.option_id = o.option_id and
			pa.user_id=" . $user_id . " and
			pa.poll_id=" . $this->poll_id . "
			order by pa.answer_create_datetime"
		;

		$result = $this->db->Execute($query);

		if (isset($result->fields)) {

			$temp = array();

			while (!$result->EOF) {
				$temp1 = $result->fields;

				$temp1['answer_create_datetime'] = $this->date->formatDate($temp1['answer_create_datetime'],1);

				array_push($temp, $temp1);
				$result->MoveNext();
			}
			$result->Close();

			return $temp;
		}
		else {
			$error_info = "function=pollUserVoteHistory class=Poll.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['am_error_log'][] = array(1, 1, $error_info);
		}

	}//EO pollUserVoteHistory



	// getUserPollParticipation --------------------------------------------------------------------
	// returns the history of the polls and votes by a given user (for user publishing page)
	// tom calthrop - 11th December 2004
	//
	function getUserPollParticipation () {

		$query = "
			SELECT p.poll_question, pa.answer_create_datetime, o.option_body
			FROM " . $this->db->prefix . "_poll p,
			" . $this->db->prefix . "_poll_option o,
			" . $this->db->prefix . "_poll_answer pa
			WHERE
			p.poll_id=o.poll_id and
			o.option_id=pa.option_id and
			pa.user_id=" . $this->user_id . " and
			pa.current_answer=1 and
			p.poll_anon is null
			order by pa.answer_create_datetime desc"
		;

		$result = $this->db->Execute($query);

		if (isset($result->fields)) {
			$temp = array();

			while (!$result->EOF) {
				$temp1 = $result->fields;
				$temp1['answer_create_datetime'] = $this->date->formatDate($temp1['answer_create_datetime']);

				array_push($temp, $temp1);
				$result->MoveNext();
			}

			$result->Close();
			return $temp;
		}
		else {
			$error_info = "function=getUserPollParticipation class=Poll.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['am_error_log'][] = array(1, 1, $error_info);
		}
	}//EO getUserPollParticipation




	// updateAnswer --------------------------------------------------------------------
	// update defaults and insert new answer
	// tom calthrop - 28th December 2004
	//
	function updateAnswer($option_id) {
		$query = "
			SELECT * FROM " . $this->db->prefix . "_poll_answer
			WHERE 
			poll_id=" . $this->poll_id . " AND
			user_id=" . $this->user_id
		;
		
		$result = $this->db->Execute($query);
		
		$rec = array();
		$rec['current_answer'] = "null";
		
		$query = $this->db->GetUpdateSQL($result, $rec, false, get_magic_quotes_gpc());
		$result = $this->db->Execute($query);
		
		$rec = array();
		$rec['user_id'] = $this->user_id;
		$rec['poll_id'] = $this->poll_id;
		$rec['option_id'] = $option_id;
		$rec['current_answer'] = 1;
		$rec['answer_create_datetime'] = time();
		
		$table = $this->db->prefix . "_poll_answer";
			
		$query = $this->db->GetInsertSQL($table, $rec, get_magic_quotes_gpc());
		$result = $this->db->Execute($query);
		
	}//EO updateAnswer




	// getPollCount --------------------------------------------------------------------
	// will get the coutn of unique page names
	// tom calthrop - 27th December 2004
	//
	function getPollCount($user_id = null) {
		$query = "
			SELECT poll_id as total
			FROM " . $this->db->prefix . "_poll
			WHERE "
		;
		
		if (isset($this->user_id)) {
		    $query .= "p.user_id=" . $this->user_id . " AND ";
		}
		
		if (isset($this->group_id)) {
		    $query .= "p.group_id=" . $this->group_id . " AND ";
		}

		$query .= "1=1 ";

		$result = $this->db->Execute($query);

		if (isset($result->fields['total'])) {
			return $result->fields['total'];
		}
		else {
			$error_info = "function=getPollCount class=Poll.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['am_error_log'][] = array(1, 1, $error_info);
		}

	}//EO getPollCount
}
?>
