<?php
/*

	应用主框架

*/

//载入依赖库以及配置
require_once dirname(__FILE__)."/include/global.php";

//XML 处理类
require("class/xmlparser.php");

////////////////////////////////////////////

//操作
$action		= GetQuery("action");

//执行
$execute	= GetQuery("execute");

//回调
$callback	= GetQuery("callback") ? GetQuery("callback") : "Serv.empty";
	
//mysql open
reader_mysql();
	
switch ($action){

	//当前用户状态检查
	case "session":

		if( $_SESSION["Manager"]["id"] ){

			//查询用户最后登录时间
			$sql  = "select last_login from ".VI_DBMANPRE."admin where id=".$_SESSION["Manager"]["id"]." and status>0";
			
			//时间
			$last = $db -> getValue( $sql );
			
			if( $last ){

				//更新用户最后活动时间
				$sql="update ".VI_DBMANPRE."admin set last_active=".time()." where id=".$_SESSION["Manager"]["id"];
				mysql_query($sql,$mysql);

				//写入日志
				$sql="update ".VI_DBMANPRE."event set modify=".time().",ip='".GetIP()."' where aid=".$_SESSION["Manager"]["id"]." and event='login' and dateline='".$last."'";
				
				mysql_query($sql,$mysql);				
			}

		}

		//返回数据
		echo $callback.'({ "id":"'.$_SESSION["Manager"]["id"].'", "account":"'.$_SESSION["Manager"]["account"].'", "avatar":"'.$_SESSION["Manager"]["avatar"].'", "group":"'.$VICACHE["sys.group"][$_SESSION["Manager"]["gid"]]["name"].'" });';

	break;
	
	/////////////////////////////////////////////

	//退出登录
	case "logout":
	
		if( $_SESSION["Manager"]["id"] ){
			session_unset();
			session_destroy();			
		}
		
		//返回数据
		echo $callback.'( true );';

	break;
	
	/////////////////////////////////////////////

	//设置主题
	case "theme":
	
		if( $_SESSION["Manager"]["id"] ){
			
			$theme		= GetQuery("theme");
		
			//更新数据
			$sql = "update ".VI_DBMANPRE."admin set theme='".$theme."' where id = ".$_SESSION["Manager"]["id"];	
			
			mysql_query($sql,$mysql);
			
		}

	break;

	//设置头像
	case "avatar":
	
		if( $_SESSION["Manager"]["id"] ){
			
			$avatar		= GetQuery("avatar");
		
			//更新数据
			$sql = "update ".VI_DBMANPRE."admin set avatar='".$avatar."' where id = ".$_SESSION["Manager"]["id"];	
			
			mysql_query($sql,$mysql);
			
		}

	break;
	
	/////////////////////////////////////////////

	//设置模块
	case "addons":

		if( $_SESSION["Manager"]["id"] ){

			$appid		= GetQuery("appid");
			
			switch( $execute ){

				//添加插件
				case "added":
				
					//查询数据
					$sql="select * from ".VI_DBMANPRE."quick where aid='".$_SESSION["Manager"]["id"]."' and appid='".$appid."'";
					$result = mysql_query($sql,$mysql);
	
					//没有记录
					if( mysql_num_rows($result) == 0 ){
	
						//插入数据
						$sql = "insert into ".VI_DBMANPRE."quick(aid,appid,sort,dateline) values(".$_SESSION["Manager"]["id"].",'".$appid."','".$sort."',".time().")";	
	
						mysql_query($sql,$mysql);
					
					}

					//返回数据
					echo $callback.'( "'.$appid.'", true );';	

				break;

				//删除插件
				case "remove":

					//更新数据
					$sql = "delete from ".VI_DBMANPRE."quick where aid='".$_SESSION["Manager"]["id"]."' and appid = '".$appid."'";

					mysql_query($sql,$mysql);
					
					//返回数据
					echo $callback.'( "'.$appid.'", true );';

				break;
				
				//读取插件
				case "reader":

					//更新数据（按添加先后顺序排序）
					$sql = "select appid,sort from ".VI_DBMANPRE."quick where aid='".$_SESSION["Manager"]["id"]."' order by sort asc,dateline asc";
					
					$res = $db -> getAll( $sql );

					mysql_query($sql,$mysql);
					
					//插件名称
					foreach( $res as $key => $val ){
						$res[$key]["name"] = $VICACHE["sys.module"][$val["appid"]]["name"];
						
						$str .= ' "'.$res[$key]["appid"].'" ,';
					}
					
					//返回数据
					echo $callback.'( [ '.substr( $str , 0 , strlen( $str )-1 ).' ] );';

				break;
				

				//遍历插件
				case "module":
				
					//遍历模块
					foreach( $VICACHE["sys.module"] as $appid => $config ){
					
						//配置地址
						$self = VI_ROOT.$config["config"];
	
						//加载配置
						if ( $config["config"] && file_exists( $self ) && require( $self ) ) {
	
							$app = $Modules[$appid];
							
							$str .= ' "'.$appid.'" : {"name":"'.$app["name"].'","serve":"'.$app["serve"].'"} ,';
							
						}
						
					}
					
					//返回数据
					echo $callback.'( { '.substr( $str , 0 , strlen( $str )-1 ).' } );';
				
				break;
			
			}

		}

	break;
	
	/////////////////////////////////////////////

	//设置插件
	case "widget":

		if( $_SESSION["Manager"]["id"] ){

			$appid		= GetQuery("appid");
			$widget		= GetQuery("widget");
			
			switch( $execute ){

				//添加插件
				case "added":
				
					//模块路径
					$mode = "module/".$appid;
				
					//当前路径
					$self = $mode."/widget/".$widget."/";

					$str = '{},';

					if ( file_exists( $self ) ) {

						//插件目录
						$root = VI_ROOT."/".$self."/config.xml";

						//解析插件
						$xml = new xmlParser();
							$xml -> xmlOpen( $root );							
							$config = $xml -> xmlToArray();
							$config = $config["WIDGET"];

						//UTF8 转 GBK
						if( $Project["charset"] == "gbk" ){								
							foreach ($config as $key => $val){
								$config[$key] = iconv('UTF-8', 'GBK//IGNORE', $val);
							}
						}

						//装载内容
						$xml = sreadfile( $root );

						$xml = str_replace( array( '{HOST}','{MODULE}','{WIDGET}','{APPID}','{WGTID}' ) , array( VI_HOST, $mode, $self, $appid, $widget ) , $xml );

						$xml = mb_convert_encoding( $xml,'HTML-ENTITIES' , 'UTF-8' );

						$xml = base64_encode( $xml );

						$str = ' {"appid":"'.$appid.'","widget":"'.$widget.'","name":"'.$config["NAME"].'","x":"'.$config["X"].'","y":"'.$config["Y"].'","z":"'.$config["Z"].'","fx":"'.$config["FX"].'","fy":"'.$config["FY"].'","xml":"'.$xml.'"},';

					}
				
					//////////////////////
				
					//查询数据
					$sql="select * from ".VI_DBMANPRE."widget where aid='".$_SESSION["Manager"]["id"]."' and appid='".$appid."' and widget='".$widget."'";
					$result = mysql_query($sql,$mysql);
	
					//没有记录
					if( mysql_num_rows($result) == 0 ){
	
						//插入数据
						$sql = "insert into ".VI_DBMANPRE."widget(aid,appid,widget,x,y,z,fx,fy,dateline) values(".$_SESSION["Manager"]["id"].",'".$appid."','".$widget."','".$config["X"]."','".$config["Y"]."','".$config["Z"]."','".$config["FX"]."','".$config["FY"]."',".time().")";	
	
						mysql_query($sql,$mysql);
					
					}

					//返回数据
					echo $callback.'( "'.$appid.'", "'.$widget.'", true, '.substr( $str , 0 , strlen( $str )-1 ).' );';	

				break;

				//删除插件
				case "remove":

					//更新数据
					$sql = "delete from ".VI_DBMANPRE."widget where aid='".$_SESSION["Manager"]["id"]."' and appid = '".$appid."' and widget='".$widget."'";

					mysql_query($sql,$mysql);					

					//返回数据
					echo $callback.'( "'.$appid.'", "'.$widget.'", true );';	

				break;

				//设置插件
				case "saved":

					$x		= GetNumber("x",0);
					$y		= GetNumber("y",0);

					$fx		= GetNumber("fx",0);
					$fy		= GetNumber("fy",0);

					//更新数据
					$sql = "update ".VI_DBMANPRE."widget set x = '".$x."',y = '".$y."',fx = '".$fx."',fy = '".$fy."' where aid='".$_SESSION["Manager"]["id"]."' and appid = '".$appid."' and widget='".$widget."'";

					mysql_query($sql,$mysql);					

					//返回数据
					echo $callback.'( "'.$appid.'", "'.$widget.'", true );';	

				break;
				
				//前置插件
				case "front":
				
					$z		= GetNumber("z",0);
				
					//更新数据
					$sql = "update ".VI_DBMANPRE."widget set z = '".$z."' where aid='".$_SESSION["Manager"]["id"]."' and appid = '".$appid."' and widget='".$widget."'";

					mysql_query($sql,$mysql);					

					//返回数据
					echo $callback.'( "'.$appid.'", "'.$widget.'", true );';	

				break;
				
				//读取插件
				case "reader":
				
					//更新数据
					$sql = "select appid,widget,x,y,z,fx,fy from ".VI_DBMANPRE."widget where aid='".$_SESSION["Manager"]["id"]."' order by dateline desc";
					
					$res = $db -> getAll( $sql );
					
					//插件名称
					foreach( $res as $key => $val ){
						
						$res[$key]["name"] = $VICACHE["sys.module"][$val["appid"]]["name"];
						
						//模块路径
						$mode = "module/".$val["appid"];
						
						//当前路径
						$self = $mode."/widget/".$res[$key]["widget"]."/";
						
						//插件目录
						$root = VI_ROOT."/".$self."/config.xml";
						
						$xml = sreadfile( $root );
						
						//将 XML 中的 utf8 转 gbk
						if( $Project["charset"] == "gbk" ){
							//$xml = iconv( $Project["charset"], 'UTF-8', $xml);							
						}
						
						$xml = str_replace( array( '{HOST}','{MODULE}','{WIDGET}','{APPID}','{WGTID}' ) , array( VI_HOST, $mode, $self, $val["appid"], $res[$key]["widget"] ) , $xml );
						
						$xml = mb_convert_encoding( $xml,'HTML-ENTITIES' , 'UTF-8' );
						
						$xml = base64_encode( $xml );
						
						$str .= ' {"appid":"'.$res[$key]["appid"].'","widget":"'.$res[$key]["widget"].'","name":"'.$res[$key]["name"].'","x":"'.$res[$key]["x"].'","y":"'.$res[$key]["y"].'","z":"'.$res[$key]["z"].'","fx":"'.$res[$key]["fx"].'","fy":"'.$res[$key]["fy"].'","xml":"'.$xml.'"},';
					}
					
					//返回数据
					echo $callback.'([ '.substr( $str , 0 , strlen( $str )-1 ).' ]);';	

				break;				
			
			}

		}

	break;

	/////////////////////////////////////////////

	//处理附件
	case "attach":
	
		if( $_SESSION["Manager"]["id"] ){
	
			switch( $execute ){
	
				//返回最近一次上传
				case "lately":
	
					$input = GetQuery("input");
	
					header('Content-type: text/xml');
					echo ("<?xml version='1.0' encoding='".$Project["charset"]."'?>");
					echo ("<response>");
	
					if( !$_SESSION["Manager"]["account"] ){
						echo ("<result>false</result>");
						echo ("<error>login</error>");
					}elseif( $Group["sys-upload-bak"] != "Y" ){
						echo ("<result>false</result>");
						echo ("<error>config</error>");
					}elseif ( $input ){
	
						$isFile=false;
						$delFile=false;
	
						//mysql open
						reader_mysql();
	
						//查询数据库
						$sql="select * from ".VI_DBMANPRE."attach where input='$input' order by id desc limit 1";
	
						//echo $sql;
						$result=mysql_query($sql,$mysql);
	
						//删除数据
						if(mysql_num_rows($result)==1){
							$row=mysql_fetch_assoc($result);
	
							if( $row["remote"] ){
								$link = readpath(str_replace(FTP_ROOT,FTP_SITE,$row["name"]));	
							}else{
								$link = $row["name"];
							}
	
							echo "<result>";
								echo "<name>".$link."</name>";
								echo "<input>".$row["input"]."</input>";
								echo "<type>".$row["type"]."</type>";
								echo "<size>".$row["size"]."</size>";
								echo "<width>".$row["width"]."</width>";
								echo "<height>".$row["height"]."</height>";
							echo "</result>";
	
							echo ("<error>complete</error>");
	
						}else{
							echo ("<result>false</result>");
							echo ("<error>file</error>");
						}
	
						//mysql close
						reader_mysql(true);
					}
	
					echo ("</response>");
	
				break;
	
				//删除文件
				case "delete":
	
					$file = GetQuery("file");
					$file = str_replace(VI_BASE,'',$file);
					$file = str_replace(FTP_SITE,FTP_ROOT,$file);
	
	
					$input = GetQuery("input");
					$sCorp = GetQuery("corp");
	
					if( !$_SESSION["Manager"]["account"] ){
	
						echo ("<error>login</error>");
	
					}elseif( $Group["sys-upload-del"] != "Y" ){
	
						echo ("<error>config</error>");
	
					}elseif ( $file ){
	
						$delFile=true;
	
						//mysql open
						reader_mysql();
	
						//查询数据库
						$sql="select id,remote,name from ".VI_DBMANPRE."attach where name like '%$file'";
						$result=mysql_query($sql,$mysql);
	
						//echo '<sql>'.$sql.'</sql>';
	
						//删除数据
						if(mysql_num_rows($result)==1){
							$row=mysql_fetch_assoc($result);
	
							//删除数据_记录
							$sql="delete from ".VI_DBMANPRE."attach where id=".$row["id"];
							$result=mysql_query($sql,$mysql);
	
							//远程附件
							if( $row["remote"] ){
	
								require_once("class/ftp.php");
	
								//连接 FTP
								$ftp = new ClsFTP($Setting["ftp"]["FTP_USER"], $Setting["ftp"]["FTP_PASS"], $Setting["ftp"]["FTP_HOST"], $Setting["ftp"]["FTP_PORT"]);
	
								//删除文件
								$delFile = @$ftp->delete($row["name"]);
	
								//关闭 FTP
								$ftp->close();
	
							}else{
	
								//删除数据_文件
								$delFile = @unlink($Project["base"].$row["name"]);
	
							}
	
							echo "complete";
	
						}else{
	
							echo ("<error>file</error>");
	
						}
	
						//mysql close
						reader_mysql(true);
	
					}
	
				break;
	
			}
		
		}
	
	break;

}
	
//mysql close
reader_mysql(true);
	
?>