<?php
	
	if(!defined('VI_BASE')) {
		ob_clean();
		exit('Access Denied');
	}
	
	/////////////////////////////////
	
	//载入客户端函数包
	require(VI_ROOT."function/client.php");

	//加密验证
	$keys = $_POST["keys"];
	
	//错误信息
	$error = '';
	
	function getcip() {
		$unknown = 'unknown'; 
		if ( isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] && strcasecmp($_SERVER['HTTP_X_FORWARDED_FOR'],  $unknown ) ) {  
			$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];  
		}elseif( isset($_SERVER['REMOTE_ADDR'])  && $_SERVER['REMOTE_ADDR'] &&  strcasecmp( $_SERVER['REMOTE_ADDR'], $unknown ) ) {  
			$ip = $_SERVER['REMOTE_ADDR'];  
		}  
		/*  
		处理多层代理的情况  
		或者使用正则方式：$ip = preg_match("/[\d\.] {7,15}/", $ip, $matches) ? $matches[0] : $unknown;  
		*/  
		if( false !== strpos($ip, ',') ){
			$ip = reset(explode(',', $ip));
		}
		return $ip;  
	} 

	
	//当前IP
	$ip = getcip();
	
	//没有安装加密模块
	if( !function_exists("mcrypt_module_open") || !$keys ){	
	
		$error = "mcrypt";
		
	}else{
		
		$hash = unserialize( authcrypt( $keys, VI_START, 'decode' ) );
		
		/*
		var_dump( $hash );
		var_dump( $_SESSION );
		var_dump( $ip );
		*/
		
		//验证码出错
		if( !is_array($hash) || $hash['ip'] != GetIP() || $hash['verify'] != $_SESSION["verify"] || $hash['verify'] == $_SESSION["before"] ){		
			$error = "verify";
		}
		
	}
	
	// || !$_SESSION['Member']['modify']
	if( !$error && $config['USER_MODE'] == "REG" && !$_SESSION['Member']['id'] ){		
		$error = "login";		
	}
	
	if( !$error && $config["VERIFY_CAPTCHA"] && ( !$_SESSION['captcha'] || strtolower($_POST[$hash['captcha']]) != $_SESSION['captcha'] ) ){		
		$error = "captcha";		
	}
	
	if( !$error && $config["FORM_MAX"]>0 && $config["FORM_MAX"] <= $_CACHE[$appid]['form']["stat"] ){		
		$error = "toplimit";		
	}
	
	if( !$error && $_CACHE[$appid]['form']["start"]>time() || !$_CACHE[$appid]['form']['state'] ){		
		$error = "state";		
	}
	
	if( !$error && $_CACHE[$appid]['form']["expire"]<time() ){		
		$error = "expire";		
	}
	
	if( !$error && $config["USER_ZONE"] && strpos( convertip( $ip ), $config["USER_ZONE"] ) === false ){		
		$smarty->assign("zone", convertip( $ip ) );
		$error = "zone";		
	}
	
	//没有错误
	if( $error == '' ){	
		
		$post = true;
		
		////////////////////////////
		
		//开始时间
		$start = mktime( 0, 0, 0, date('m'), date('d'), date('Y') );
		
		//到期时间
		$close = mktime( 23, 59, 59, date('m'), date('d'), date('Y') );
		
		//
		
		//var_dump( $start );
		//var_dump( $close );
			
		///////////////////////////
		
		//IP 验证次数验证	
		if( $config["FORM_SPEED"] ){			
					
			$sql="SELECT count(id) FROM `mod:value` WHERE ip = '".$ip."' and fid=".$fid;
			
			//按天计算
			if( $config["VERIFY_MODE"] == 'DAY' ) $sql.=" and  dateline >".$start." and dateline < ".$close;
			
			if( System :: $db -> getValue($sql) >= $config['FORM_SPEED'] ){
				
				$error = "ip";
				
				$post = false;
			}
					
		}
		
		//注册用户，不允许用户名重复
		if( $post && $config['USER_MODE'] == "REG" && $config['FORM_NUMBER'] ){
			
			$sql="SELECT count(id) FROM `mod:value` WHERE uid = '".$_SESSION['Member']['id']."' and fid=".$fid;
			
			//按天计算
			if( $config['FORM_DATEDIFF'] == 'DAY' ) $sql.=" and  dateline >".$start." and dateline < ".$close;
					
			if( System :: $db -> getValue($sql) >= $config['FORM_NUMBER'] ){
				
				$error = "number";
				
				$post = false;
			}
			
		}
		
		//注册用户，特定积分限制
		if( $post && $config['USER_MODE'] == "REG" && $config['FORM_SCORE'] ){
			
			$score = Passport :: money( $_SESSION['Member']['id'] );
					
			if( $score < $config['FORM_SCORE'] ){
				
				$error = "score";
				$smarty->assign("score", $score );
				
				$post = false;
			}
			
		}
		
		//exit( date( 'Y-m-d', $_SESSION['Member']['regdate'] ) );
		
		//注册用户，注册时间限制
		if( $post && $config['USER_MODE'] == "REG" && $config['FORM_REGDATE'] ){
					
			if( !$_SESSION['Member']['regdate'] || $_SESSION['Member']['regdate'] > $config['FORM_REGDATE'] ){
				
				$error = "regdate";
				
				$post = false;
			}
			
		}
		
		if( $post ){
		
			//处理表单
			$arr = array();
			
			//收集标记
			$res = false;			
			
			foreach( $_CACHE[$appid]['group'] as $gid => $group ){
				
				$item = '';				
				$temp = 'G-'.$gid;
				$gset = $group["config"];
				
				//忽略空值
				if( empty( $_POST[$temp] ) ){
					continue;
				}else{
					$value = $_POST[$temp];	
				}
				
				//类型换算
				/*
				
				$value = '';
				switch($group["type"]){
						
					case 'checkbox':
					
						//获取数组数据
						$array = isset($_POST[$temp]) ? $_POST[$temp] : array();
						
						//数组转成字符串
						$value = implode(",", $array);
						
					break;
					
					case 'button':
						
						//提取按钮名称
						foreach( $_POST as $key => $val ){
							
							//G-XXXX
							if( strpos($key, $temp) === 0  && $val ){								
								$array = explode("-", $key);								
								$value = $array[2];								
							}							
							
						}
						
					break;
						
					default:
						$value = $_POST[$temp];
					break;
				}
				*/
				
				//////////////////////

				$new = array();
				foreach( $value as $v ){
					//将没有找到的（和禁用的）子选项排除
					if( $_CACHE['vote']['option'][ $gid ][ $v ] && $_CACHE['vote']['option'][ $gid ][ $v ]['state'] ){
						array_push( $new , $v );
					}
				}
				
				//数组转成字符串
				$value = implode(",", $new);
				
				//////////////////////
				
				$arr[$temp] = $value;
				
				//更新统计
				if ( $value && in_array($group["type"],array("radio","checkbox","button")) ){
					
					$sql="UPDATE `mod:option` SET stat=stat+1 WHERE state>0 and id in(".$value.")";
					System :: $db -> execute( $sql );
					
					$res = true;
				}
			}
			
			//未收数据
			if( count( $_CACHE[$appid]['group'] ) && $res === false ){	
				
				$error = "null";
			
			}else{
				
				//使用匿名扩展模式
				//ACCOUNT	姓名	PHONE	电话号码	IDCARD	身份证	EMAIL	电子邮箱
				//!$_SESSION['Member']['id'] && 
				if( $config['USER_MODE'] == "ANY" ){
					$arr["ACCOUNT"] = $_POST["ACCOUNT"];
					$arr["NAME"] = $_POST["NAME"];
					$arr["PHONE"] 	= $_POST["PHONE"];
					$arr["IDCARD"] 	= $_POST["IDCARD"];
					$arr["QQ"] 	= $_POST["QQ"];
					$arr["EMAIL"] 	= $_POST["EMAIL"];
				}

				//记录用户提交数据	
				$value = format_json( fix_json($arr) );
				
				$sql="INSERT INTO `mod:value`(appid,fid,uid,account,config,state,dateline,ip) values('".$_CACHE[$appid]['form']["appid"]."',".$fid.",'".$_SESSION['Member']['id']."','".$_SESSION['Member']['account']."','".$value."',0 ,".time().",'".$ip."')";
				System :: $db -> execute( $sql );
				
				if( $_SESSION['Member']['id'] ){
				
					//更新活跃统计
					$sql="UPDATE `mod:member` SET stat_level=stat_level+1 WHERE id=".$_SESSION['Member']['id'];
					System :: $db -> execute( $sql );		
				
				}
				
				//更新人数统计
				$sql="UPDATE `mod:form` SET stat=stat+1 WHERE id = ".$fid;
				System :: $db -> execute( $sql );
				
				//记录验证码
				$_SESSION["before"] = $hash['verify'];
				
				//清空验证码
				$_SESSION['captcha'] = $_SESSION["verify"] = '';
				
				//写入Cookies
				$expire=time() + (60*$config["FORM_SPEED"]);
				setcookie($cookie, 'Y', $expire ,"" ,"");
				
				//送积分
				/////////////////////////////////
				
				if( $config["FORM_MONEY"] && $_SESSION['Member']['id'] ){
					
					//更新用户积分
					$money = Passport :: money( $_SESSION['Member']['id'] , $config["FORM_MONEY"] );
					
					$smarty->assign("money", $money );
					
				}
				
				/////////////////////////////////				
				
				//发邮件
				/////////////////////////////////
				
				if( $config["FORM_NOTICE"] == "Y" ){
					
					//创建者邮件地址
					$address = $_CACHE['system']['admin'][ $_CACHE[$appid]['form']["aid"] ]["email"];	
					
					if( $address ){
					
						$content = str_replace( array('{TIME}','{USER}','{EVENT}','{URL}','{VERYIDE}'),
									array( date('Y-m-d H:i:s') ,$_CACHE[$appid]['form']["account"], $_CACHE[$appid]['form']["name"], Module::get_index($appid)."?id=".$fid."&ref=email", VI_HOST ) ,$_G['setting']['passport']["event"] );
						
						if( $address ){
						
							System :: sendmail( $_CACHE[$appid]['form']["name"] ,$address,$config["FORM_SEND"], $content );
						
						}
					
					}
				
				}
				
				/////////////////////////////////
				
				$error = "";
			
			}
	  
		}
		
	}
	
	$smarty->assign("error", $error );
	
	//////////////// 写日志
	/*
	$f = './log.txt';	
	if (!file_exists($f)) touch($f);
	$of = file_get_contents($f);
	$str = '$_POST '.var_export($_POST, 1);
	$str .= "\r\n\$_SERVER ".var_export($_SERVER, 1);
	$str .= "\r\n\$hash ".var_export($hash, 1);
	$str .= "\r\n\$ip ".$ip;
	$str .= "\r\n\$error ".$error;
	file_put_contents($f, "\r\n".$str."\r\n------------------------------------------------" . $of);
	*/
	
?>