<?php
	/********************************************************************
	 *									投票插件
	 *                            ----------------------
	 *   update               : 2010-11-18 
	 *   copyright            : (C) 2009 DirCMS.cn
	 *   website              : http://www.dircms.net
	 *
	 *   $Id: vote.php, 2010-11-18  M Exp $
	 ********************************************************************/
	@ini_set('display_errors','0');
	@error_reporting (E_ALL & ~E_NOTICE);
	define('DC_ROOT', str_replace("\\", '/',substr(dirname(__FILE__),0,-4)));
	include DC_ROOT.'include/common.inc.php';
	$action=isset($action)?$action:'view';
	switch($action)
	{
		case 'post': //提交投票
			if(!$voteitem)showmsg_nourl('请选择投票选项!');
			$id=intval($id);
			$r=$db->fetch_one("SELECT * FROM `".DB_PRE."vote` WHERE `".DB_PRE."vote`.`id`={$id}");
			if(!$r)showmsg_nourl('无此投票!');
			if($r['endtime']<TIME)showmsg_nourl('此投票已过期!');
			$t=$db->fetch_all("SELECT `".DB_PRE."vote_ip`.`ip`,`".DB_PRE."vote_ip`.`votetime` FROM `".DB_PRE."vote_ip` WHERE `".DB_PRE."vote_ip`.`voteid`={$id}");

			foreach($t as $_t)
			{
				$ip[$_t['ip']]=$_t['votetime'];
			}
			if(array_key_exists(IP,$ip) && $r['delay']>(TIME-$ip[IP]))showmsg_nourl('您已经投过票了!');
			$item=explode("\n",$r['votenote']);
			if($r['ismore'])
			{
				$voteitem=array_map('intval',$voteitem);
				foreach($voteitem as $v)
				{
					foreach($item as $k=>$_item)
					{
						unset($len,$lenreg);
						preg_match('/<vote id="'.$v.'" count="([0-9]+)">(.+?)<\/vote>/i',$_item,$lenreg);
						$len=$lenreg[1]+1;
						$item[$k]=preg_replace('/<vote id="'.$v.'" count="([0-9]+)">(.+?)<\/vote>/i','<vote id="'.$v.'" count="'.$len.'">\\2</vote>',$_item);
					}
				}
				$item=implode("\n",$item);
				$db->update(DB_PRE."vote",array('votenote'=>$item,'totalcount'=>intval($r['totalcount'])+sizeof($voteitem)),'id='.$id);
			}
			else
			{
				$voteitem=intval($voteitem);
				foreach($item as $k=>$_item)
				{
					unset($len,$lenreg);
					preg_match('/<vote id="'.$voteitem.'" count="([0-9]+)">(.+?)<\/vote>/i',$_item,$lenreg);
					$len=$lenreg[1]+1;
					$item[$k]=preg_replace('/<vote id="'.$voteitem.'" count="([0-9]+)">(.+?)<\/vote>/i','<vote id="'.$voteitem.'" count="'.$len.'">\\2</vote>',$_item);
				}
				$item=implode("\n",$item);
				$db->update(DB_PRE."vote",array('votenote'=>$item,'totalcount'=>intval($r['totalcount'])+1),'id='.$id);
			}
			if(array_key_exists(IP,$ip))
			{
				$db->update(DB_PRE.'vote_ip',array('votetime'=>TIME),'voteid='.$id.' AND ip=\''.IP.'\'');
			}
			else
			{
				$db->insert(DB_PRE.'vote_ip',array('voteid'=>$id,'ip'=>IP,'votetime'=>TIME),true);
			}
			showmsg('投票成功!',$DIRCMS['site_url'].'plus/vote.php?id='.$id);
			break;

		default: // 查看投票结果
			$id=intval($id);
			if(!$id)showmsg_nourl('无此投票!');
			$dir_postion='<a href="'.$DIRCMS['site_url'].'">首页</a> > 查看投票';
			include template('vote_view');
			break;
	}
?>