<?php
/*

	应用主框架

*/

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

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

header('Content-Type:text/javascript; charset='.$charset.'');

//操作
$action		= getgpc('action');

//执行
$execute	= getgpc('execute');

//回调
$callback	= getgpc('callback') ? getgpc('callback') : "Serv.empty";
	
//连接数据库
System :: connect();
	
switch ($action){

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

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

			//查询用户最后登录时间
			$sql  = "SELECT last_login from `sys:admin` WHERE id=".$_SESSION['Manager']['id']." and `state`>0";
			
			//时间
			$last = System :: $db -> getValue( $sql );
			
			if( $last ){

				//更新用户最后活动时间
				$sql="UPDATE `sys:admin` SET last_active=".time()." WHERE id=".$_SESSION['Manager']['id'];
				System :: $db -> execute( $sql );

				//写入日志
				$sql="UPDATE `sys:event` SET `modify`=".time().",ip='".GetIP()."' WHERE aid=".$_SESSION['Manager']['id']." and event='login' and dateline='".$last."'";
				System :: $db -> execute( $sql );
				
			}

		}

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

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

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

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

	//设置主题
	case "theme":
	
		if( $_SESSION['Manager']['id'] ){
			
			$theme		= getgpc("theme");
		
			//更新数据
			$sql = "UPDATE `sys:admin` SET theme='".$theme."' WHERE id = ".$_SESSION['Manager']['id'];	
			System :: $db -> execute( $sql );
			
			$_SESSION['Manager']['theme'] = $theme;
			
		}

	break;

	//设置头像
	case "avatar":
	
		if( $_SESSION['Manager']['id'] ){
			
			$avatar		= getgpc("avatar");
		
			//更新数据
			$sql = "UPDATE `sys:admin` SET avatar='".$avatar."' WHERE id = ".$_SESSION['Manager']['id'];	
			System :: $db -> execute( $sql );
			
			$_SESSION['Manager']["avatar"] = $avatar;
			
		}

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

	//设置模块
	case "addons":

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

			$appid		= getgpc('appid');
			
			switch( $execute ){

				//添加插件
				case "added":
				
					//查询数据
					$sql="SELECT * FROM `sys:quick` WHERE aid='".$_SESSION['Manager']['id']."' and appid='".$appid."'";
					$row = System :: $db -> getOne( $sql );

                			if( empty( $row ) ){
	
						//插入数据
						$sql = "INSERT INTO `sys:quick`(aid,appid,sort,dateline) values(".$_SESSION['Manager']['id'].",'".$appid."','".$sort."',".time().")";	
	
						System :: $db -> execute( $sql );
					
					}

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

				break;

				//删除插件
				case "remove":

					//更新数据
					$sql = "DELETE FROM `sys:quick` WHERE aid='".$_SESSION['Manager']['id']."' and appid = '".$appid."'";

					System :: $db -> execute( $sql );
					
					//返回数据
					echo $callback.'( "'.$appid.'", true );';

				break;

				//插件排序
				case "order":
				
					$data = explode(",",getgpc("data"));
					
					for( $i=0; $i<count($data); $i++ ){

						//更新数据
						$sql = "UPDATE `sys:quick` SET sort = ".$i." WHERE aid='".$_SESSION['Manager']['id']."' and appid = '".$data[$i]."'";
	
						System :: $db -> execute( $sql );
					
					}
					
					//返回数据
					echo $callback.'();';

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

					//更新数据（按添加先后顺序排序）
					$sql = "SELECT appid,sort from `sys:quick` WHERE aid='".$_SESSION['Manager']['id']."' ORDER BY sort asc,dateline asc";
					
					$res = System :: $db -> getAll( $sql );
					
					$str = '';
					
					//插件名称
					foreach( $res as $key => $val ){
						$res[$key]["name"] = $_CACHE['system']['module'][$val["appid"]]["name"];
						
						$str .= ' "'.$res[$key]["appid"].'" ,';
					}
					
					//返回数据
					echo $callback.'( [ '.substr( $str , 0 , strlen( $str )-1 ).' ] );';

				break;
				

				//遍历模块
				case "module":
				
					$str = '';
				
					//遍历模块
					foreach( $_CACHE['system']['module'] as $appid => $config ){
						
						if( isset( $config['config'] ) ){
						
							//配置地址
							$self = VI_ROOT.$config['config'];
		
							//加载配置
							if ( $config['config'] && file_exists( $self ) && require( $self ) ) {
		
								$app = $_G['module'][$appid];
								
								//修正路径
								//$app['serve'] = $app['serve'] ? str_replace("config.php","",$config['config']).$app['serve'] : '';
								
								$str .= ' "'.$appid.'" : {"name":"'.$app["name"].'","serve":"'.( isset( $app['serve'] ) ? $app['serve'] : '' ).'"} ,';
								
							}
						
						}
						
					}
					
					//返回数据
					echo $callback.'( { '.substr( $str , 0 , strlen( $str )-1 ).' } );';
				
				break;
			
			}

		}

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

	//设置插件
	case "widget":

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

			$appid		= getgpc('appid');
			$widget		= getgpc('widget');
			
			switch( $execute ){

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

					$str = '{},';

					if ( file_exists( $self ) ) {

						//插件目录
						$doc = VI_ROOT.$self."config.xml";
						
						$config = xml_array( sreadfile( $doc ) );
						
						//UTF8 转 GBK
						if( $_G['product']['charset'] == "gbk" ){								
							foreach ($config['widget'] as $key => $val){
								$config['widget'][$key] = $val ? iconv('UTF-8', 'GBK//IGNORE', $val) : $val;
							}							
						}
						
						////////////////////////////////

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

						$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 = htmlentities( $xml, ENT_QUOTES );
						
						//exit($xml);

						//$xml = base64_encode( $xml );
						//$xml = base64_encode( rawurlencode($xml) );
						$xml = rawurlencode($xml);

						$str = ' {"appid":"'.$appid.'","widget":"'.$widget.'","name":"'.$config['widget']["name"].'","x":"'.$config['widget']["x"].'","y":"'.$config['widget']["y"].'","z":"'.$config['widget']["z"].'","fx":"'.$config['widget']["fx"].'","fy":"'.$config['widget']["fy"].'","xml":"'.$xml.'"},';

					}
				
					//////////////////////
				
					//查询数据
					$sql="SELECT * FROM `sys:widget` WHERE aid='".$_SESSION['Manager']['id']."' and appid='".$appid."' and widget='".$widget."'";
					
					$row = System :: $db -> getOne( $sql );

                			if( empty( $row ) ){
	
						//插入数据
						$sql = "INSERT INTO `sys:widget`(aid,appid,widget,x,y,z,fx,fy,dateline) values(".$_SESSION['Manager']['id'].",'".$appid."','".$widget."','".$config['widget']["x"]."','".$config['widget']["y"]."','".$config['widget']["z"]."','".$config['widget']["fx"]."','".$config['widget']["fy"]."',".time().")";
	
						System :: $db -> execute( $sql );
					
					}

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

				break;

				//删除插件
				case "remove":

					//更新数据
					$sql = "DELETE FROM `sys:widget` WHERE aid='".$_SESSION['Manager']['id']."' and appid = '".$appid."' and widget='".$widget."'";

					System :: $db -> execute( $sql );

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

				break;

				//设置插件
				case "saved":

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

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

					//更新数据
					$sql = "UPDATE `sys:widget` SET x = '".$x."',y = '".$y."',fx = '".$fx."',fy = '".$fy."' WHERE aid='".$_SESSION['Manager']['id']."' and appid = '".$appid."' and widget='".$widget."'";

					System :: $db -> execute( $sql );

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

				break;
				
				//前置插件
				case "front":
				
					$z		= getnum("z",0);
				
					//更新数据
					$sql = "UPDATE `sys:widget` SET z = '".$z."' WHERE aid='".$_SESSION['Manager']['id']."' and appid = '".$appid."' and widget='".$widget."'";

					System :: $db -> execute( $sql );

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

				break;
				
				//读取插件
				case "reader":
				
					//更新数据
					$sql = "SELECT appid,widget,x,y,z,fx,fy from `sys:widget` WHERE aid='".$_SESSION['Manager']['id']."' ORDER BY dateline desc";
					
					$res = System :: $db -> getAll( $sql );
					
					$str = '';
					
					//插件名称
					foreach( $res as $key => $val ){
						
						$res[$key]["name"] = $_CACHE['system']['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( $_G['product']['charset'] == "gbk" ){
							//$xml = iconv( $_G['product']['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 );
						
						//$xml = base64_encode( rawurlencode($xml) );
						$xml = rawurlencode($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 = getgpc('input');
	
					header('Content-type: text/xml');
					echo ("<?xml version='1.0' encoding='".$_G['product']['charset']."'?>");
					echo '<response>';
	
					if( !$_SESSION['Manager']['account'] ){
						
						echo '<result>false</result>';
						echo '<error>login</error>';
						
					}elseif( System :: check_func('sys-upload-bak') == false ){
						
						echo '<result>false</result>';
						echo '<error>config</error>';
						
					}elseif ( $input ){
	
						$isFile=false;
						$delFile=false;
	
						//查询数据库
						$sql="SELECT * FROM `sys:attach` WHERE input='$input' ORDER BY id desc limit 1";
	
						$row = System :: $db -> getOne( $sql );
	
						//删除数据
						if( $row ){
	
							if( $row["remote"] ){
								$link = url_merge(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>';
						}
		
					}
	
					echo '</response>';
	
				break;
	
				//删除文件
				case "delete":
	
					$file = getgpc('file');
					
					//转换成根目录相对地址
					$file = str_replace( VI_BASE, '/', $file );
					
					//转换远程地址为相对地址
					$file = str_replace( $_G['setting']["attach"]["FTP_SITE"], $_G['setting']["attach"]["FTP_ROOT"], $file );	
	
					$input = getgpc('input');
	
					if( !$_SESSION['Manager']['account'] ){
	
						echo 'login';
	
					}elseif( System :: check_func('sys-upload-del') == false ){
	
						echo 'config';
	
					}elseif ( $file ){
	
						$delFile=true;
	
						//查询数据库
						$sql="SELECT id,remote,name from `sys:attach` WHERE name like '%$file'";
						
						$row = System :: $db -> getOne( $sql );
	
						//删除数据
						if( $row ){
	
							//删除数据_记录
							$sql="DELETE FROM `sys:attach` WHERE id=".$row['id'];
							System :: $db -> execute( $sql );
	
							//远程附件
							if( $row["remote"] ){
	
								require_once("class/ftp.php");
	
								//连接 FTP
								$ftp = new ClsFTP($_G['setting']["attach"]["FTP_USER"], $_G['setting']["attach"]["FTP_PASS"], $_G['setting']["attach"]["FTP_HOST"], $_G['setting']["attach"]["FTP_PORT"]);
	
								//删除文件
								$delFile = @$ftp->delete($row['name']);
	
								//关闭 FTP
								$ftp->close();
	
							}else{
	
								//删除数据_文件
								//$delFile = @unlink($_G['project']["base"].$row['name']);
								//2011/7/6 修改，自动适应目录
								$delFile = @unlink( VI_ROOT.str_replace(VI_BASE,'/',$row['name']) );
	
							}
	
							echo 'complete';
	
						}else{
							
							//未找到文件
							echo 'file';
	
						}
	
					}
	
				break;
	
			}
		
		}
	
	break;

}	

//关闭数据库
System :: connect();
	
?>