<?php
/**
* @version	$Id: poll_eh.php 12740 2009-10-20 19:39:07Z alex $
* @package	In-Bulletin
* @copyright	Copyright (C) 1997 - 2009 Intechnic. All rights reserved.
* @license      GNU/GPL
* In-Portal is Open Source software.
* This means that this software may have been modified pursuant
* the GNU General Public License, and as distributed it includes
* or is derivative of works licensed under the GNU General Public License
* or other free or open source software licenses.
* See http://www.in-portal.org/license for copyright notices and details.
*/

	defined('FULL_PATH') or die('restricted access!');

	class PollEventHandler extends kDBEventHandler {

		/**
		 * Allows to override standart permission mapping
		 *
		 */
		function mapPermissions()
		{
			parent::mapPermissions();
			$permissions = Array(
									'OnResetVotes'	=>	Array('self' => 'edit'),
									'OnMakeVote'	=>	Array('self' => true),
									'OnItemBuild'	=>	Array('self' => true),
							);
			$this->permMapping = array_merge($this->permMapping, $permissions);
		}

		/**
		 * Applies special filter, that allows to select all poll from given date range
		 *
		 * @param kEvent $event
		 */
		function SetCustomQuery(&$event)
		{
			if ($this->Application->isAdminUser) {
				return ;
			}

			$object =& $event->getObject();
			/* @var $object kDBList */

			$object->addFilter('poll_range_filter', '(%1$s.StartDate <= ' .adodb_mktime(). ') AND (%1$s.EndDate >= ' .adodb_mktime(). ' OR EndDate IS NULL)');
			$object->addFilter('poll_status', '(%1$s.Status = ' .STATUS_ACTIVE. ')');
		}

		/**
		 * Reset votes statistics for current poll
		 *
		 * @param kEvent $event
		 */
		function OnResetVotes(&$event)
		{
			$object =& $event->getObject();
			/* @var $object kDBItem */

			$sql = 'DELETE FROM '.TABLE_PREFIX.'PollsStatistics
					WHERE '.$object->IDField.' = '.$object->GetID();
			$this->Conn->Query($sql);


			$poll_answers_table = $this->Application->getUnitOption('poll-answer', 'TableName');
			$poll_answers_table = $this->Application->GetTempName($poll_answers_table);

			$sql = 'UPDATE '.$poll_answers_table.' SET VotesQty = 0
						WHERE '.$object->IDField.' = '.$object->GetID();
			$this->Conn->Query($sql);
		}

		/**
		 * Reset votes statistics for current poll
		 *
		 * @param kEvent $event
		 */
		function OnBeforeItemCreate(&$event)
		{
			$object =& $event->getObject();
			/* @var $object kDBItem */

			$object->SetDBField('ResourceId', $this->Application->NextResourceId());
		}

		/**
		 * Make vote to current poll
		 *
		 * @param kEvent $event
		 */
		function OnMakeVote(&$event)
		{
			$object =& $event->getObject($this->Application->GetVar('poll_id'));
			/* @var $object kDBItem */

			$poll_answer_id = $this->Application->GetVar('option_id');

			if (!$poll_answer_id) {
				$event->redirect = false;
				return ;
			}

			$ip_address = $_SERVER['REMOTE_ADDR'];

			if (!$object->GetDBField('AllowMultipleVotings')) {
				$sql = 'SELECT StatisticsId
						FROM '.TABLE_PREFIX.'PollsStatistics
						WHERE PollId = '.$object->GetID().' AND UserIP = '.$this->Conn->qstr($ip_address);
				$voted = $this->Conn->GetOne($sql) > 0;
			}

			if (!$voted) {
				$user_id = $this->Application->LoggedIn()? $this->Application->RecallVar('user_id') : '-2';
				$fields_hash = 	Array (
										'PollId'		=>	$object->GetID(),
										'AnswerId'		=>	$poll_answer_id,
										'UserIP'		=>	$ip_address,
										'CreatedById'	=>	$user_id,
										'AnswerDate'	=>	adodb_mktime(),
								);

				$this->Conn->doInsert($fields_hash, TABLE_PREFIX.'PollsStatistics');

				$poll_table = $this->Application->getUnitOption('poll', 'TableName');
				$this->Conn->Query('UPDATE '.$poll_table.' SET CachedVotesQty = CachedVotesQty + 1
										WHERE PollId = '.$object->GetID());

				// update table with answers
				$poll_answers_table = $this->Application->getUnitOption('poll-answer', 'TableName');
				$this->Conn->Query('UPDATE '.$poll_answers_table.' SET VotesQty = VotesQty + 1
										WHERE PollId = '.$object->GetID().' AND AnswerId = '.$poll_answer_id);
			}
			$event->setEventParam('PollId', $this->Application->GetVar('poll_id'));
			$event->redirect = false;
		}


		/**
		 * Cleanup by removing items from PollStatistics before Poll is deleted
		 *
		 * @param kEvent $event
		 */
		function OnAfterItemDelete(&$event)
		{
			$object =& $event->getObject();
			/* @var $object kDBItem */

			$sql = 'DELETE FROM '.TABLE_PREFIX.'PollsStatistics
						WHERE PollId = '.$object->GetID();
			$this->Conn->Query($sql);
		}
	}