<?php
	
	if(!defined('VI_BASE')) {
		ob_clean();
		exit('Access Denied');
	}
	
	/////////////////////////////////
	
	//防止重复提交
	$verify = $_POST["verify"];
	
	if( $config['USER_MODE'] == "REG" && !$_SESSION['Member']['id'] ){
		
		$smarty->assign("error", "login" );
		
	}elseif( !$verify || $verify == $_SESSION["__VERIFY"] ){
		
		$smarty->assign("error", "verify" );
		
	}elseif( $config["FORM_MAX"]>0 && $config["FORM_MAX"] <= $_CACHE[$appid]['form']["stat"] ){
		
		$smarty->assign("error", "toplimit" );
		
	}elseif( $_CACHE[$appid]['form']["start"]>time() || !$_CACHE[$appid]['form']['state'] ){
		
		$smarty->assign("error", "state" );
		
	}elseif( $_CACHE[$appid]['form']["expire"]<time() ){
		
		$smarty->assign("error", "expire" );
		
	}else{
		
		$post = true;
		
		//会话验证		
		if( $config["FORM_SPEED"] ){
			
			switch( $config["VERIFY_MODE"] ){
				
				//Cookies验证
				case "CK":
				
					$cookie = $appid."-".$fid;
					
					if( $_COOKIE[$cookie] ){
						
						$smarty->assign("error", "cookie" );
												
						$post = false;
					}				
				break;
				
				//IP提交数检查
				case "IP":
					
					$sql="SELECT id FROM `mod:value` WHERE ip = '".GetIP()."' and dateline>".(time()-$config["FORM_SPEED"]*60)." and fid=".$fid;
							
					$row = System :: $db -> getOne( $sql );

               		if( $row ){
						
						$smarty->assign("error", "ip" );
												
						$post = false;
					}
					
				break;				
			}
		}
		
		//注册用户，不允许用户名重复
		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( System :: $db -> getValue($sql) >= $config['FORM_NUMBER'] ){
				
				$smarty->assign("error", "number" );
				
				$post = false;
			}
			
		}
		
		if( $post ){
		
			//处理表单
			$arr = array();
			
			//收集标记
			$res = false;
			
			//收集正确数
			$right = 0;
			
			//收集错误数
			$fault = 0;
			
			//分数统计
			$score = -1;
			
			foreach( $_CACHE[$appid]['group'] as $gid => $group ){
				
				$item = '';				
				$temp = 'G-'.$gid;
				$gset = $group["config"];
				
				//如果需要计算得分
				if( $score == -1 && $gset["GROUP_SCORE"] ){
					$score = 0;	
				}
				
				$value = '';
				
				//类型换算
				switch($group["type"]){
					
					//忽略分隔线
					case 'compart':
						
						continue 2;
						
					break;
						
					case 'checkbox':
						
						$array = isset($_POST[$temp]) ? $_POST[$temp] : array();
						
						$value = implode(",", $array);
						
					break;
						
					default:
						$value = $_POST[$temp];
					break;
				}
				
				$arr[$temp] = $value;
				
				//更新统计
				if ( $value ){
					
					$sql="UPDATE `mod:option` SET stat=stat+1 WHERE id in(".$value.")";
					System :: $db -> execute( $sql );
					
					$res = true;
				}
				
				//判断对错			
				$try = false;
				
				if( $value && $group["selected"] ){
					switch( $group["type"] ){
					
						case "radio":
						case "select":
							if( $value == $group["selected"] ){
								$try = true;	
							}
						break;
					
						case "checkbox":
							if( count(array_diff( explode(",",$group["selected"]) , $array )) == 0 ){
								$try = true;
							}					
						break;
					}
					
				}elseif( $value && !$group["selected"] ){
					$try = true;
				}
				
				if( $try ){
					
					$sql="UPDATE `mod:group` SET stat=stat+1 WHERE id = ".$gid;
					System :: $db -> execute( $sql );
					
					//累加正确
					$right++;
					
					//累加得分
					$score += $gset["GROUP_SCORE"];
					
				}else{
					
					//累加错误
					$fault++;
				}				
				
			}
			
			$smarty->assign("score", $score );
			
			//未收数据
			if( count( $_CACHE[$appid]['group'] ) && $res === false ){
				
				$smarty->assign("error", "null" );		
			
			}else{
				
				//是否测试成功
				$arr["RESULT"] = ( $fault ? "N" : "Y" );
				
				//本次得分
				$arr["SCORES"] = $score;
				
				//使用匿名扩展模式
				//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"];
					$arr["COMPANY"] 	= $_POST["COMPANY"];
				}

				//记录用户提交数据	
				$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().",'".GetIP()."')";
				
				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 );
				
				}
				
				/***********************************/
				
				//按每份试题计算积分
				if( $config["FORM_SETTLE"] == "FORM" ){
				
					//扣积分
					/////////////////////////////////
					
					if( $fault && $config["FORM_DEDUCT"] && $_SESSION['Member']['id'] ){
						
						//更新用户积分
						$money = Passport :: money( $_SESSION['Member']['id'] , -$config["FORM_DEDUCT"] );
						
						$smarty->assign("money", $money );
						
						
					//送积分
					/////////////////////////////////
					
					}elseif( $config["FORM_MONEY"] && $_SESSION['Member']['id'] ){
						
						//更新用户积分
						$money = Passport :: money( $_SESSION['Member']['id'] , $config["FORM_MONEY"] );
						
						$smarty->assign("money", $money );
						
					}
					
					/////////////////////////////////
				
				}else{	//按单个问题计算积分
					
					//扣积分
					/////////////////////////////////
					
					if( $fault && $config["FORM_DEDUCT"] && $_SESSION['Member']['id'] ){
						
						//更新用户积分
						$money = Passport :: money( $_SESSION['Member']['id'] , -$config["FORM_DEDUCT"]*$fault );
						
						$smarty->assign("money", $money );
					
					}
					
					//送积分
					/////////////////////////////////
					if( $right && $config["FORM_MONEY"] && $_SESSION['Member']['id'] ){
						
						//更新用户积分
						$money = Passport :: money( $_SESSION['Member']['id'] , $config["FORM_MONEY"]*$right );
						
						$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 );
						
						}
					
					}
				
				}

				/////////////////////////////////
				
				//测试结果统计（回答正确）
				$config["RESULT"] = ( is_numeric($config["RESULT"]) ? $config["RESULT"] : 0 );
				$config["RESULT"] = ( $fault ? $config["RESULT"] : $config["RESULT"]+=1 );
				
				//exit( $config );
				
				//更新人数统计
				$sql="UPDATE `mod:form` SET stat=stat+1,config='". format_json( fix_json($config) ) ."' WHERE id = ".$fid;
				System :: $db -> execute( $sql );
				
				//更新缓存
				Cached :: form( $_CACHE[$appid]['form']['appid'], $fid );				
				
				//记录验证码
				$_SESSION["__VERIFY"] = $verify;
				
				//写入Cookies
				setcookie($cookie, 'Y', time() + (60*$config["FORM_SPEED"]) ,"" ,"");

				/////////////////////////////////
				
				//错误次数
				$smarty->assign("fault", $fault );
				
				//正确次数
				$smarty->assign("right", $right );
				
				if( $fault ){
					$smarty->assign("error", $fault );
				}else{
					$smarty->assign("error", "" );
				}
			
			}
			
		}
		
	}
?>