<?php

/**
 *      [Dzz!] (C)2010-2011 dzz.cc
 *      This is NOT a freeware, use is subject to license terms
 *
 * ============================================================================
 * 版权所有 2010-2011 Dzz!Desktop，并保留所有权利。
 * 网站地址: http://dzz.cc；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式、任何目的的再发布。
 * ============================================================================
 */
if(!defined('IN_DISCUZ') || !defined('IN_ADMINCP')) {
	exit('Access Denied');
}
$refer=dreferer();
dzz_cpheader();
if(submitcheck('appsubmit')) {
	if($operation=='edit' || $operation=='add'){
		$appid=intval($_GET['appid']);
		$appurl=addslashes(trim($_POST['appurl']));
		$_POST['appdesc'] = getstr($_POST['appdesc']);
		$setarr=array(
				'appname'=>getstr($_POST['appname'],80,0,0,0,-1),
				'appurl'=>trim($_POST['appurl']),
				'open'=>intval($_POST['open']),
				'classid'=>intval($_POST['classid']),
				'classids'=>implode(',',$_POST['subids']),
				'width'=>intval($_POST['width']),
				'height'=>intval($_POST['height']),
				'default'=>intval($_POST['default']),
				'haveflash'=>intval($_POST['haveflash']),
				'vendor'=>trim($_POST['vendor']),
				'titlebuttons'=>implode(',',$_POST['titlebuttons']),
				'ismarket'=>intval($_POST['ismarket']),
				'appdesc'=>($_POST['appdesc']),
				'isshow'=>intval($_POST['isshow']),
				'havetask'=>intval($_POST['havetask']),
				'idtype'=>'',
				'typeid'=>0
			);
		if(preg_match("/mod=plugin:(\w+)&op=/i",$setarr['appurl'],$matches)){
			$identifier=$matches[1];
			if($plugin=DB::fetch_first("select * from ".DB::table('dzz_plugin')." where identifier='{$identifier}'")){
				$setarr['idtype']='pluginid';
				$setarr['typeid']=$plugin['pluginid'];
			}
		}
		//判断依序的参数是否有值
		$msg='';
		if(!$setarr['appname']) $msg=$lang['not_empty_appname'];
		if(!$setarr['appurl']) $msg=$lang['not_empty_appurl'];
		//if(!$setarr['classid']) $msg=$lang['not_empty_appclass'];
		if($msg) cpmsg($msg,'','error');
		
		//处理应用图标
		$iconnew='';
		$target='';
		if($appid){
			$target=DB::result_first("select appico from ".DB::table('dzz_apps')." where appid='{$appid}'");
		}
		if($_FILES['iconnew']) {
			//print_r($_FILES['iconnew']);
			//cpmsg('dfdsfd');
			if($_FILES['iconnew']['tmp_name']) {
				if($appico=uploadtolocal($_FILES['iconnew'],'appico',$target)){
					$setarr['appico']=$appico;
				}
			}
		} else {
			if(!$_GET['iconnew']) $_GET['iconnew']='dzz/images/default/icodefault.png';
			if($_GET['iconnew'] && $_GET['iconnew']!=$_G['setting']['attachurl'].$target){
				if($appico=imagetolocal($_GET['iconnew'],'appico',$target)){
					$setarr['appico']=$appico;
				}
			}
		}
		$picids=$_POST['picids'];
		//删除已有图片
		$delete_picids=$_POST['delete_pics'];
		if($delete_picids) delete_pic($delete_picids);
		//判断此网址的应用是否存在于应用市场，存在的话转到编辑此应用
		if($oappid=DB::result_first("select appid from ".DB::table('dzz_apps')." where appurl='{$appurl}' and `ismarket`>0 ") && !$appid){
			if($picids) delete_pic($picids);
			cpmsg($lang['app_exist'],"$_G[siteurl]".ADMINSCRIPT."?action=$action&operation=$operation&do=edit&appid=$oappid");
			
		}
		if($appid){
			DB::update('dzz_apps',daddslashes($setarr),"appid='{$appid}'");
			if($plugin['pluginid']) DB::update('dzz_plugin',array('appid'=>$appid),"pluginid='{plugin[pluginid]}'");
			/*//如果是插件的话，更新插件相关数据；
			if($pluginid=DB::result_first("select typeid from ".DB::table('dzz_apps')." where appid='{$appid}' and idtype='plugin'")){
				$plugin=array('open'=>intval($_POST['open']),
								'wwidth'=>intval($_POST['width']),
								'wheight'=>intval($_POST['height']),
								'titlebuttons'=>implode(',',$_POST['titlebuttons']),
								'isshow'=>intval($_POST['isshow']),
								'havetask'=>intval($_POST['havetask']),
								);
				DB::update('dzz_plugin',daddslashes($plugin),"pluginid='{$pluginid}'");
			}*/
			//设置默认应用
			set_ico_position($appid,'app');
			//维护关系表
			if($_POST['subids']){
				 DB::delete('dzz_relative',"appid ='{$appid}'");
				foreach($_POST['subids'] as $cid){
					DB::insert('dzz_relative',array('appid'=>$appid,'classid'=>intval($cid)));
				}
			}
			//更新上传图片的id
			if($picids) DB::update('dzz_pic',array('id'=>$appid),"picid IN (".dimplode($picids).")");
			
			cpmsg($lang['do_success'],$refer,'succeed');
		}else{
			$setarr['dateline']=$_G['timestamp'];
			$setarr['uid']=$_G['uid'];
			$setarr['username']=$_G['username'];
			if(!$setarr['appico']) $setarr['appico']='dzz/images/default/icodefault.png';
			$appid=DB::insert('dzz_apps',daddslashes($setarr),1);
			if($plugin['pluginid']) DB::update('dzz_plugin',array('appid'=>$appid),"pluginid='{plugin[pluginid]}'");
			set_ico_position($appid,'app');
			//维护关系表
			if($_POST['subids']){
				 DB::delete('dzz_relative',"appid ='{$appid}'");
				foreach($_POST['subids'] as $cid){
					DB::insert('dzz_relative',array('appid'=>$appid,'classid'=>intval($cid)));
				}
			}
			if($picids) DB::update('dzz_pic',array('id'=>$appid),"picid IN (".dimplode($picids).")");
			cpmsg($lang['do_success'],"$_G[siteurl]".ADMINSCRIPT."?action=$action&operation=$operation&do=edit&appid=$appid",'succeed');
		}
		
	}elseif($operation=='appclass'){
		foreach($_POST['classname'] as $key => $value){
			if(!$value['parent']) $value['parent']=$lang['new_classname'];
			if($_POST['add'][$key]['parent']=='add'){
				$fup=DB::insert('dzz_appclass',array('classname'=>daddslashes($value['parent']),'disp'=>intval($_POST['disp'][$key]['parent'])),1);
			}else{
				DB::update('dzz_appclass',array('classname'=>daddslashes($value['parent']),'disp'=>intval($_POST['disp'][$key]['parent'])),"classid='{$key}'");
				$fup=$key;
			}
			//showmessage('dddd');
			foreach($value['sub'] as $key1=> $value1){
				
				if($_POST['isadd'][$key]['sub'][$key1]!='add'){
					DB::update('dzz_appclass',array('fupid'=>$fup,'classname'=>daddslashes($value1),'disp'=>intval($_POST['disp'][$key]['sub'][$key1])),"classid='{$key1}'");
				}else{
					DB::insert('dzz_appclass',array('fupid'=>$fup,'classname'=>daddslashes($value1),'disp'=>intval($_POST['disp'][$key]['sub'][$key1])));
				}
			}
		}
		
	}else{
		if($_POST['optype']=='delete'){
			$ids=$_POST['ids'];
			if($ids){
				$picids=array();
				$query=DB::query("select picid from ".DB::table('dzz_pic')." where id IN (".dimplode($ids).")");
				while($value=DB::fetch($query)){
					$picids[]=$value['picid'];
				}
				if($picids){
					delete_pic($picids);
				}
				$query=DB::query("select icoid from ".DB::table('dzz_icos')." where oid IN (".dimplode($ids).") and type='app'");
				while($icoarr=DB::fetch($query)){
					dzz_delete_ico($icoarr['icoid']);
				}
				DB::delete('dzz_icos',"oid IN (".dimplode($ids).") and type='app'");
			 	DB::delete('dzz_apps',"appid IN (".dimplode($ids).")");
				//删除插件表中此应用的指向;
				DB::update('dzz_plugin',array('appid'=>0),"appid IN (".dimplode($ids).")");
			}
			
		}elseif($_POST['optype']=='market'){
			$ids=$_POST['ids'];
			$appid=$_POST['appid'];
			if($operation=='market'){
				if($ids) DB::query("update ".DB::table('dzz_apps')." set `ismarket`=0 where appid IN (".dimplode($ids).")");
				foreach($appid as $key => $value){
					
					DB::query("update ".DB::table('dzz_apps')." set `default`='{$_POST['default'][$value]}',`disp`='{$_POST['disp'][$value]}' where appid ='{$value}'");
					set_ico_position($value,'app');
					
				}
			}elseif($operation=='default'){
				if($ids) DB::query("update ".DB::table('dzz_apps')." set `default`=0, defaultopen=0,notdelete=0 where appid IN (".dimplode($ids).")");
				foreach($appid as $key => $value){
					DB::query("update ".DB::table('dzz_apps')." set `default`='{$_POST['default'][$value]}',`disp`='{$_POST['disp'][$value]}' where appid ='{$value}'");
					set_ico_position($value,'app');
				}
			}else{
				if($ids) DB::query("update ".DB::table('dzz_apps')." set `ismarket`=1 where appid IN (".dimplode($ids).")");
			}
			
		}else{
			$appid=$_POST['appid'];
			if($operation=='market'){
					foreach($appid as $key => $value){
						DB::query("update ".DB::table('dzz_apps')." set `default`='{$_POST['default'][$value]}',`disp`='{$_POST['disp'][$value]}' where appid ='{$value}'");
						set_ico_position($value,'app');
					}
			}elseif($operation=='default'){
					foreach($appid as $key => $value){
						DB::query("update ".DB::table('dzz_apps')." set `default`='{$_POST['default'][$value]}',`disp`='{$_POST['disp'][$value]}',defaultopen=".intval($_POST['defaultopen'][$value]).",notdelete=".intval($_POST['notdelete'][$value])." where appid ='{$value}'");
						set_ico_position($value,'app');
					}
			}
		}
	}
	cpmsg($lang['do_success'],$refer,'succeed');
}else{
	

	if($operation=='appclass'){
		if($do=='delete'){
			$classid=intval($_GET['classid']);
			if(DB::result_first("select COUNT(*) from ".DB::table('dzz_apps')." where classid='{$classid}'") || DB::result_first("select COUNT(*) from ".DB::table('dzz_appclass')." where fupid='{$classid}'")){
				cpmsg($lang['delete_appclass_failure'],$refer,'error');
			}else{
				DB::delete('dzz_appclass',"classid='{$classid}'");
				cpmsg($lang['do_success'],$refer,'succeed');
			}
		}else{
			dzz_shownav($lang['menu_app'],$lang['menu_app_class']);
			$appclass=array();$class=array();
			$query=DB::query("select * from ".DB::table('dzz_appclass')." where 1 order by disp");
			while($value=dstripslashes(DB::fetch($query))){
				$class[]=$value;
			}
			foreach($class as $value){
				if($value['fupid']==0) $appclass[$value['classid']]=$value;
			}
			foreach($class as $value){
				if($value['fupid']>0) $appclass[$value['fupid']]['sub'][]=$value;
			}
		}
	}elseif($operation=='edit' || $operation=='add'){
		if($do=='upload'){
			$picid = 0;
			$uploadfiles = dzz_pic_save($_FILES['attach']);
			if($uploadfiles && is_array($uploadfiles)) {
				$picid = $uploadfiles['picid'];
				$uploadStat = 1;
			} else {
				$uploadStat = $uploadfiles;
			}
				echo "<script>";
				echo "parent.uploadStat = '$uploadStat';";
				echo "parent.picid = $picid;";
				echo "parent.upload();";
				echo "</script>";
			exit();

		}else{
			//应用分类
			$appclass=array();
			$query=DB::query("select * from ".DB::table('dzz_appclass')." where 1 order by disp");
			while($value=dstripslashes(DB::fetch($query))){
				$appclass[$value['fupid']][]=$value;
			}
			$appclassjson=json_encode_gbk($appclass);
			if($operation=='add'){
				dzz_shownav($lang['menu_app'],$lang['menu_app_add']);
				$app=array();
				$app['ismarket']=1;
				$app['subids']=array();
				$json_subids=json_encode_gbk($app['subids']);
				$app['width']=800;
				$app['height']=600;
				$app['isshow']=1;
				$app['havetask']=1;
			}else{
				dzz_shownav($lang['menu_app'],$lang['menu_app_edit']);
				$appid=intval($_GET['appid']);
				
				$app=array();
				$app=dstripslashes(DB::fetch_first("select * from ".DB::table('dzz_apps')." where appid='{$appid}'"));
				if($app['classids']) $app['subids']=explode(',',$app['classids']);
				else $app['subids']=array();
				$json_subids=json_encode_gbk($app['subids']);
				if($app['appico']!='dzz/images/default/icodefault.png' && !preg_match("/^(http|ftp|https|mms)\:\/\/(.+?)/i", $app['appico'])){
					$app['appico']=$_G['setting']['attachurl'].$app['appico'];
				}
				if($app['titlebuttons'])	$app['titlebuttons']=explode(',',$app['titlebuttons']);
				else $app['titlebuttons']=array();
				//获取图片列表
				if ($_G['uid'] && $_G['group']['radminid'] >= 1) $wheresql = "id='$appid'";
				else	$wheresql = "id='$appid' and (`checked`>0 OR uid='{$_G[uid]}')";
				$count = DB::result_first("SELECT COUNT(*) FROM ".DB::table('dzz_pic')." WHERE $wheresql");
				$piclist=array();
				if($count){
					$query = DB::query("SELECT * FROM ".DB::table('dzz_pic')." WHERE $wheresql ORDER BY dateline DESC");
					while ($value = DB::fetch($query)) {
						$value['pic'] = pic_get($value['filepath'], '', $value['thumb'], $value['remote'],0,1);
						$value['dateline']=dgmdate($value['dateline'],'d');
						$piclist[] = $value;
					}
				}
			}
		}
	}else{
		
		if($operation=='market'){
			dzz_shownav($lang['menu_app'],$lang['menu_app_market']);
		}elseif($operation=='default'){
			dzz_shownav($lang['menu_app'],$lang['menu_app_default']);
		}else{
			dzz_shownav($lang['menu_app'],$lang['menu_app_user']);
		}
		
		$page = empty($_GET['page'])?1:intval($_GET['page']);
		$username=trim($_GET['username']);
		$day=intval($_GET['day']);
		$classid=intval($_GET['classid']);
		$subclassid=intval($_GET['subclassid']);
		$default=intval($_GET['default']);
		$perpage = 12;
		$start = ($page-1)*$perpage;
		$gets = array(
				'action'=>$action,
				'operation'=>$operation,
				'username' => $username,
				'day'=>$day,
				'default'=>$default,
				'classid'=>$classid,
				'subclassid'=>$subclassid,
				'vendor'=>trim($_GET['vendor']),
				'srchtxt'=>trim($_GET['srchtxt'])
			);
		$theurl = ADMINSCRIPT."?".url_implode($gets);
		//获取所有分类
		$appclass=array();
		$class=array();
		$query=DB::query("select * from ".DB::table('dzz_appclass')." where 1 order by disp ");
		while($value=dstripslashes(DB::fetch($query))){
			$appclass[$value['classid']]=$value;
			$class[$value['fupid']][]=$value;
		}
		$list=array();
			$time=$_G['timestamp']-$day;
			$wheresql="1";
			if($operation=='market') $wheresql.=" and ismarket>0";
			elseif($operation=='default') $wheresql.=" and `default`!='0'";
			else $wheresql.=" and `default`='0' and ismarket='0'";
			//日期选项
			if($day>0) $wheresql.=" and dateline>$time";
			//默认应用里的应用默认位置
			if($operation=='default' && $default!=0){
				 if($default==-2) $wheresql.=" and `notdelete`>0";
				 elseif($default==-3) $wheresql.=" and `defaultopen`>0";
				 else $wheresql.=" and `default`='{$default}'";
			}
			
			//主分类选项
			if($classid) $wheresql.=" and classid='{$classid}'";
			//子分类选项
			if($subclassid){
				$appids=array();
				$query=DB::query("select appid from ".DB::table('dzz_relative')." where classid='{$subclassid}'");
				while($value=DB::fetch($query)){
					$appids[]=$value['appid'];
				}
				if($appids) $wheresql.=" and appid IN (".dimplode($appids).")";
			}
			//用户选项
			if($username) $wheresql.=" and username='{$username}'";
			if($operation=='market' || $operation=='default')	$ordersql=" ORDER BY `disp` ,`dateline` DESC";
			else $ordersql=" ORDER BY `dateline` DESC";
			//应用名称模糊搜索
			$srchtxt=trim($_GET['srchtxt']);
			if($srchtxt){
				$wheresql.=" and appname LIKE '%".$srchtxt."%'";
			}
			
			//应用提供者模糊搜索
			$vendor=trim($_GET['vendor']);
			if($vendor){
				$wheresql.=" and vendor LIKE '%".$vendor."%'";
			}
			//取得所有符合条件的应用列表

			$count=DB::result_first("SELECT COUNT(*) FROM ".DB::table('dzz_apps')." where $wheresql  ");
			if($count){
				$query=DB::query("SELECT * FROM ".DB::table('dzz_apps')."  where $wheresql $ordersql   LIMIT $start,$perpage" );
				while($values=dstripslashes(DB::fetch($query))){
					$values['dateline']=dgmdate($values['dateline'],'Y-m-d');
					$values['classname']=$appclass[$values['classid']]['classname'];
					
					$values['subclass']='';
					if($values['classids']){
						$subids=explode(',',$values['classids']);
						foreach($subids as $class_id){
							$values['subclass'].='<a style="margin:2px 10px;" href="'.ADMINSCRIPT.'?action='.$action.'&operation='.$operation.'&classid='.$values['classid'].'&subclassid='.$class_id.'">'.$appclass[$class_id]['classname'].'</a>';
						}
						//cpmsg($values['subclass']);
					}
					if($values['appico']!='dzz/images/default/icodefault.png' && !preg_match("/^(http|ftp|https|mms)\:\/\/(.+?)/i", $values['appico'])){
						$values['appico']=$_G['setting']['attachurl'].$values['appico'];
					}
					$list[$values['appid']]=$values;
				}
			}
			$multi = multi($count, $perpage, $page, $theurl);
			
	}
}
include dzztemplate('admin/dzz_apps');
dzzfooter();

?>