<?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["form"]["form"]["stat"] ){
		
		$smarty->assign("error", "toplimit" );
		
	}elseif( $_CACHE["form"]["form"]["start"]>time() || !$_CACHE["form"]["form"]["state"] ){
		
		$smarty->assign("error", "state" );
		
	}elseif( $_CACHE["form"]["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;
			
			foreach( $_CACHE['form']['group'] as $gid => $group ){
				
				$item = '';				
				$temp = 'G-'.$gid;
				$gset = $group["config"];				
				$value = '';
				
				//类型换算
				switch($group["type"]){
						
					case 'checkbox':
					
						$array = is_array($_POST[$temp]) ? $_POST[$temp] : array('');						
						$value = implode(",", $array);
						
					break;
						
					case 'file':
						
						if( $_FILES[$temp]["name"] && !$_FILES[$temp]['error'] ){
							
							//检查上传文件
							$result = uploader_check( $_FILES[$temp]["name"] );
							
							//子文件夹
							$folder = VI_ROOT.$_G['project']['upload'].$result['type'];
							
							//创建子文件夹
							if( !file_exists($folder) ){
								create_dir($folder);
							}
							
							//文件大小
							$size = $_FILES[$temp]["size"];
							
							//临时名称
							$tmp = $_FILES[$temp]["tmp_name"];
						
							//如果是图片
							if( $result['type']=="image" ){
							
								list($width, $height, $image_type, $attr) = getimagesize($tmp);
								
							}else{
								$width=0;		$height=0;	
							}		
				
							//移动上传文件							
							$absval = uploader_save($folder,$tmp,$_FILES[$temp]["name"],$result["extra"]);
							
							//转换成相对路径
							$value = url_merge( str_replace( VI_ROOT, VI_BASE, $absval ) );
							
							//生成缩略图
							if( $result['type']=="image" && $gset['THUMB-WIDTH'] && $gset['THUMB-HEIGHT'] ){
							
								require_once VI_ROOT.'class/thumb.php';
								
								//缩略图            
								$t = new ThumbHandler();
								
								//源图片地址
								$t->setSrcImg( $absval );
								
								//输出文件名
								$t->setDstImg( fix_thumb( $absval ) );
								
								//生成图片
								$t->createImg( $gset['THUMB-WIDTH'] , $gset['THUMB-HEIGHT'] );
								
								//记录到数组
								$arr[$temp.'-EXT'] = fix_thumb( $value );
								
							}
							
						}
						
						//上传成功
						if( $value ){						
				
							//写入数据库
							$sql="INSERT INTO `sys:attach`(name,input,dateline,type,size,ip,width,height,remote) values('".$value."','".$temp."',".time().",'".$result["extra"]."',$size,'".GetIP()."',$width,$height,0)";
							
							System :: $db -> execute( $sql );
							
							//写入日志
							System :: insert_event('upload',time(),time(),'通过 Form 上传文件 <a href="'.$value.'" target="_blank">'.$value.'</a>，大小 '.sizecount($size).'，类型 '.$result["extra"]);
				  
						}
						
					break;
						
					default:					
						$value = $_POST[$temp];						
					break;
				}
				
				//不允许空值
				if( $gset["GROUP_MUST"] == "Y" && trim($value) == "" ){
					break;
				}
				
				//记录到数组
				$arr[$temp] = $value;
				
				//更新统计
				if ( $value && in_array($group["type"],array("radio","checkbox","select")) ){
					$sql="UPDATE `mod:option` SET stat=stat+1 WHERE id in(".$value.")";
					System :: $db -> execute( $sql );
					
					$res = true;
				}
				
				//更新统计
				if ( $value && in_array($group["type"],array("text","textarea","file")) ){
					$sql="UPDATE `mod:group` SET stat=stat+1 WHERE id = ".$gid;
					System :: $db -> execute( $sql );
					
					$res = true;
				}
				
				//处理扩展数据
				$extra = $_POST[$temp.'-EXT'];
				if ( $extra && in_array($group["type"],array("radio","checkbox")) ){
					
					//记录到数组
					$arr[$temp.'-EXT'] = $extra;
					
					$sql="UPDATE `mod:group` SET stat=stat+1 WHERE id = ".$gid;
					System :: $db -> execute( $sql );
					
					$res = true;
					
				}
				
			}
			
			//未收数据
			if( count( $_CACHE['form']['group'] ) && $res === false ){
			
				$smarty->assign("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['form']['form']['appid']."',".$fid.",'".$_SESSION['Member']['id']."','".$_SESSION['Member']['account']."','".$value."',0 ,".time().",'".GetIP()."')";
				System :: $db -> execute( $sql );
				
				$sid = System :: $db -> getInsertId();		
				
				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 );
				
				//更新缓存
				Cached :: form( $_CACHE['form']['form']['appid'], $fid );
				
				//记录验证码
				$_SESSION["__VERIFY"] = $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["form"]['form']['aid'] ]["email"];	

					if( $address ){

						$content = str_replace( array('{TIME}','{USER}','{EVENT}','{URL}','{VERYIDE}'),
									array( date('Y-m-d H:i:s') ,$_CACHE["form"]["form"]["account"], $_CACHE["form"]["form"]["name"], url_path()."?id=".$fid."&ref=email", VI_HOST ) ,$_G['setting']['passport']["event"] );

						if( $address ){

							System :: sendmail( $_CACHE["form"]["form"]["name"] ,$address,$config["FORM_SEND"], $content );

						}

					}

				}

				/////////////////////////////////
				
				//发短信
				/////////////////////////////////
				
				if( $config["SMS_STATE"] && Module::loader( "sms" ) ){
					
					$sms = new SMS();
					
					//电话号码
					$mob = $_POST["PHONE"] ? $_POST["PHONE"] : $_SESSION['Member']['phone'];
					
					//短信内容
					$tmp = array_var_convert( $config["SMS_TEMPLET"], array('{username}'=>$_SESSION['Member']['account'],'{formname}'=>$_CACHE["form"]["form"]["name"],'{phone}'=>$mob,'{dateline}'=>date('Y-m-d') ) );
					
					if( $sms->send( $appid, $mob, $tmp, array( 'fid'=>$_CACHE['form']['form']['id'], 'sid'=>$sid, 'uid'=>$_SESSION['Member']['id'], 'username'=>$_SESSION['Member']['account'] ) ) ) {
						//echo "<div id='state'>短信发送成功！</div>";
					} else {
						//echo "<div id='state' class='failure'>对不起，短信发送失败！（". $sms -> result ."）</div>";
					}
					
				}
				
				/////////////////////////////////
				
				//发站短
				/////////////////////////////////
				
				if( $config['USER_MODE'] == "REG" && $config["NOTICE_STATE"] ){
					
					//电话号码
					$mob = $_POST["PHONE"] ? $_POST["PHONE"] : $_SESSION['Member']['phone'];
					
					//短信内容
					$tmp = array_var_convert( $config["NOTICE_TEMPLET"], array('{username}'=>$_SESSION['Member']['account'],'{formname}'=>$_CACHE["form"]["form"]["name"],'{phone}'=>$mob,'{dateline}'=>date('Y-m-d') ) );
					
					Passport :: notice( $_SESSION['Member']['id'], $config["NOTICE_TITLE"], $tmp );
					
				}
				
				/////////////////////////////////
				
				//转支付
				/////////////////////////////////
				
				$payment = $_POST["payment"];

				if( $config["PAYMENT_MONEY"] && $payment ){

					//载入支付整合包
					require_once VI_ROOT.'module/payment/function.php';

					$trade = new Trade();
					$redir = $trade -> create( $payment, $appid, $config["PAYMENT_MONEY"], array(), array( 'subject'=>$_CACHE['form']['form']['name'], 'fid'=>$_CACHE['form']['form']['id'], 'sid'=>$sid, 'uid'=>$_SESSION['Member']['id'], 'username'=>$_SESSION['Member']['account'] ) );
					
					//跳转链接
					/*
					echo '<script>window.location ="'. $redir .'";</script>';
					*/
					
					$smarty->assign("redir", $redir );

				}

				/////////////////////////////////
				
				$smarty->assign("error", "" );
			
			}
	  
		}
		
	}
?>