<?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('widgetsubmit')) {
	if($operation=='edit' || $operation=='add'){
		$wid=intval($_GET['wid']);
		$url=addslashes(trim($_POST['url']));
		$setarr=array(
				'name'=>getstr($_POST['name'],80,0,0,0,-1),
				'url'=>trim($_POST['url']),
				'open'=>intval($_POST['open']),
				'classid'=>intval($_POST['classid']),
				'classids'=>implode(',',$_POST['subids']),
				'width'=>intval($_POST['width']),
				'height'=>intval($_POST['height']),
				'default'=>intval($_POST['default']),
				'classname'=>trim($_POST['classname']),
				'href'=>trim($_POST['href']),
				'type'=>trim($_POST['type'])
			);
		//判断依序的参数是否有值
		$msg='';
		
		if(!$setarr['url']) $msg=$lang['widget_url_not_empty'];
		
		if($msg) cpmsg($msg,'','error');
		
		//处理应用图标
		$iconnew='';
		$target='';
		if($wid){
			$target=DB::result_first("select icon from ".DB::table('dzz_widget_market')." where wid='{$wid}'");
		}
		if($_FILES['iconnew']) {
			//print_r($_FILES['iconnew']);
			//cpmsg('dfdsfd');
			if($_FILES['iconnew']['tmp_name']) {
				if($icon=uploadtolocal($_FILES['iconnew'],'appico',$target)){
					//生成缩略图
					require_once dzz_libfile('class/image');
					$image = new image;
					if($thumb = $image->Thumb($_G['setting']['attachurl'].$icon,'',101, 101,1)){
						@unlink($_G['setting']['attachurl'].$icon);
						$setarr['icon']=$icon.'.thumb.jpg';
					}else{
						$setarr['icon']=$icon;
					}
				}
			}
		} else {
			if($_POST['iconnew'] && $_POST['iconnew']!=$_G['setting']['attachurl'].$target){
				if($icon=imagetolocal($_POST['iconnew'],'appico',$target)){
					//生成缩略图
					require_once dzz_libfile('class/image');
					$image = new image;
					if($thumb = $image->Thumb($_G['setting']['attachurl'].$icon,'',101, 101,1)){
						@unlink($_G['setting']['attachurl'].$icon);
						$setarr['icon']=$icon.'.thumb.jpg';
					}else{
						$setarr['icon']=$icon;
					}
				}
			}
		}
		
		//判断此网址的应用是否存在于挂件市场，存在的话转到编辑此应用
		if($owid=DB::result_first("select wid from ".DB::table('dzz_widget_market')." where url='{$url}'") && !$wid){
			
			cpmsg($lang['app_exist'],"$_G[siteurl]".ADMINSCRIPT."?action=$action&operation=$operation&do=edit&wid=$owid");
			
		}
		if($wid){
			DB::update('dzz_widget_market',daddslashes($setarr),"wid='{$wid}'");
			/*//如果是插件的话，更新插件相关数据；
			if($pluginid=DB::result_first("select typeid from ".DB::table('dzz_widget_market')." where wid='{$wid}' 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($wid,'widget');
			//维护关系表
			if($_POST['subids']){
				 DB::delete('dzz_widget_relative',"wid ='{$wid}'");
				foreach($_POST['subids'] as $cid){
					DB::insert('dzz_widget_relative',array('wid'=>$wid,'classid'=>intval($cid)));
				}
			}
			cpmsg($lang['do_success'],$refer,'succeed');
		}else{
			$setarr['dateline']=$_G['timestamp'];
			$setarr['uid']=$_G['uid'];
			$setarr['username']=$_G['username'];
			$wid=DB::insert('dzz_widget_market',daddslashes($setarr),1);
			set_ico_position($wid,'widget');
			//维护关系表
			if($_POST['subids']){
				 DB::delete('dzz_widget_relative',"wid ='{$wid}'");
				foreach($_POST['subids'] as $cid){
					DB::insert('dzz_widget_relative',array('wid'=>$wid,'classid'=>intval($cid)));
				}
			}
			
			cpmsg($lang['do_success'],"$_G[siteurl]".ADMINSCRIPT."?action=$action&operation=$operation&do=edit&wid=$wid",'succeed');
		}
		
	
	}elseif($operation=='class'){
		foreach($_POST['classname'] as $key => $value){
			if(!$value['parent']) $value['parent']=$lang['new_classname'];
			if($_POST['add'][$key]['parent']=='add'){
				$fup=DB::insert('dzz_widget_class',array('classname'=>daddslashes($value['parent']),'disp'=>intval($_POST['disp'][$key]['parent'])),1);
			}else{
				DB::update('dzz_widget_class',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_widget_class',array('fupid'=>$fup,'classname'=>daddslashes($value1),'disp'=>intval($_POST['disp'][$key]['sub'][$key1])),"classid='{$key1}'");
				}else{
					DB::insert('dzz_widget_class',array('fupid'=>$fup,'classname'=>daddslashes($value1),'disp'=>intval($_POST['disp'][$key]['sub'][$key1])));
				}
			}
		}
		
	}else{
		if($_POST['optype']=='delete'){
			$ids=$_POST['ids'];
			$pluginids=array();
			if($ids){
				$query=DB::query("select * from ".DB::table('dzz_widget_market')." where wid IN (".dimplode($ids).")");
				while($value=DB::fetch($query)){
					if($value['icon']!='' && $value['icon']!='dzz/images/default/icodefault.png' && !preg_match("/^(http|ftp|https|mms)\:\/\/(.+?)/i", $value['icon'])){
						@unlink($_G['setting']['attachdir'].$value['icon']);//删除图标;
						if($value['idtype']=='pluginid'){ //处理挂件推送
							$pluginids[]=$value['typeid'];
						}
					}
				}
				if($pluginids){
					DB::update('dzz_plugin',array('wid'=>0),"wid IN (".dimplode($pluginids).")");
				}
				
				DB::delete('dzz_widget',"oid IN (".dimplode($ids).") and uid='-1'");
			 	DB::delete('dzz_widget_market',"wid IN (".dimplode($ids).")");
			}
			
		}elseif($_POST['optype']=='market'){
			$ids=$_POST['ids'];
			foreach($ids as $key => $value){
				DB::query("update ".DB::table('dzz_widget_market')." set `default`='0',`disp`='{$_POST['disp'][$value]}',notdelete='0' where wid ='{$value}'");
				set_ico_position($value,'widget');
			}
			
		}else{
			
			$wid=$_POST['wid'];
			if($operation=='market'){
					foreach($wid as $key => $value){
						DB::query("update ".DB::table('dzz_widget_market')." set `default`='{$_POST['default'][$value]}',`disp`='{$_POST['disp'][$value]}' where wid ='{$value}'");
						set_ico_position($value,'widget');
					}
			}elseif($operation=='default'){
			
					foreach($wid as $key => $value){
						DB::query("update ".DB::table('dzz_widget_market')." set `default`='{$_POST['default'][$value]}',`disp`='{$_POST['disp'][$value]}',notdelete=".intval($_POST['notdelete'][$value])." where wid ='{$value}'");
						set_ico_position($value,'widget');
					}
			}
		}
	}
	cpmsg($lang['do_success'],$refer,'succeed');
}else{
	
	$sysconfig=dstripslashes(unserialize(stripslashes($_G['setting']['dzz_sysconfig'])));

	if($operation=='class'){
		if($do=='delete'){
			$classid=intval($_GET['classid']);
			if(DB::result_first("select COUNT(*) from ".DB::table('dzz_widget_market')." where classid='{$classid}'") || DB::result_first("select COUNT(*) from ".DB::table('dzz_widget_class')." where fupid='{$classid}'")){
				cpmsg(dzzlang('admin/template','delete_widgetclass_failure'),$refer,'error');
			}else{
				DB::delete('dzz_widget_class',"classid='{$classid}'");
				cpmsg($lang['do_success'],$refer,'succeed');
			}
		}else{
			dzz_shownav($lang['menu_widget'],$lang['menu_widget_class']);
			$appclass=array();$class=array();
			$query=DB::query("select * from ".DB::table('dzz_widget_class')." 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'){
		
			//应用分类
			$appclass=array();
			$query=DB::query("select * from ".DB::table('dzz_widget_class')." where 1 order by disp");
			while($value=DB::fetch($query)){
				$appclass[$value['fupid']][]=$value;
			}
			$appclassjson=json_encode_gbk($appclass);
			if($operation=='add'){
				dzz_shownav($lang['menu_widget'],$lang['menu_widget_add']);
				$widget=array();
				$widget['subids']=array();
				$json_subids=json_encode_gbk($widget['subids']);
				$widget['width']=100;
				$widget['height']=100;
				
			}else{
				dzz_shownav($lang['menu_widget'],$lang['menu_widget_edit']);
				$wid=intval($_GET['wid']);
				
				$widget=array();
				$widget=dstripslashes(DB::fetch_first("select * from ".DB::table('dzz_widget_market')." where wid='{$wid}'"));
				if($widget['classids']) $widget['subids']=explode(',',$widget['classids']);
				else $widget['subids']=array();
				$json_subids=json_encode_gbk($widget['subids']);
				if($widget['icon']!='' && $widget['icon']!='dzz/images/default/icodefault.png' && !preg_match("/^(http|ftp|https|mms)\:\/\/(.+?)/i", $widget['icon'])){
					$widget['icon']=$_G['setting']['attachurl'].$widget['icon'];
				}
			}
		
	}else{
		
		if($operation=='market'){
			dzz_shownav($lang['menu_widget'],$lang['menu_widget_market']);
		}elseif($operation=='default'){
			dzz_shownav($lang['menu_widget'],$lang['menu_widget_default']);
		}
		
		$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']);
		$type=trim($_GET['type']);
		$perpage = 12;
		$start = ($page-1)*$perpage;
		$gets = array(
				'action'=>$action,
				'operation'=>$operation,
				'username' => $username,
				'day'=>$day,
				'type'=>$type,
				'default'=>$default,
				'classid'=>$classid,
				'subclassid'=>$subclassid,
				'srchtxt'=>trim($_GET['srchtxt'])
			);
		$theurl = ADMINSCRIPT."?".url_implode($gets);
		//获取所有分类
		$appclass=array();
		$class=array();
		$query=DB::query("select * from ".DB::table('dzz_widget_class')." where 1 order by disp ");
		while($value=DB::fetch($query)){
			$appclass[$value['classid']]=$value;
			$class[$value['fupid']][]=$value;
		}
		$wheresql="1";
		
			$time=$_G['timestamp']-$day;
			
			if($operation=='default') $wheresql.=" and `default`!='0'";
			
			//日期选项
			if($day>0) $wheresql.=" and dateline>$time";
			//默认应用里的应用默认位置
			if($default!=0){
				 if($default==-2) $wheresql.=" and `notdelete`>0";
				 else $wheresql.=" and `default`='{$default}'";
			}
			
			//主分类选项
			if($classid) $wheresql.=" and classid='{$classid}'";
			//子分类选项
			if($subclassid){
				$wids=array();
				$query=DB::query("select wid from ".DB::table('dzz_widget_relative')." where classid='{$subclassid}'");
				while($value=DB::fetch($query)){
					$wids[]=$value['wid'];
				}
				if($wids) $wheresql.=" and wid IN (".dimplode($wids).")";
				else $wheresql.=" and wid ='0'";
			}
			//用户选项
			if($username) $wheresql.=" and username='{$username}'";
			$ordersql=" ORDER BY `disp` ,`dateline` DESC";
			//挂件类型
			if($type){
				$wheresql.=" and type ='{$type}'";
			}
			//应用名称模糊搜索
			$srchtxt=trim($_GET['srchtxt']);
			if($srchtxt){
				$wheresql.=" and url LIKE '%".$srchtxt."%'";
			}
			
			//取得所有符合条件的应用列表
			$list=array();
			$count=DB::result_first("SELECT COUNT(*) FROM ".DB::table('dzz_widget_market')." where $wheresql  ");
			if($count){
				$query=DB::query("SELECT * FROM ".DB::table('dzz_widget_market')."  where $wheresql $ordersql   LIMIT $start,$perpage" );
				while($values=dstripslashes(DB::fetch($query))){
					$values['dateline']=dgmdate($values['dateline'],'Y-m-d');
					$values['class_name']=$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['icon']!='' && $values['icon']!='dzz/images/default/widgetdefault.png' && !preg_match("/^(http|ftp|https|mms)\:\/\/(.+?)/i", $values['icon'])){
						$values['icon']=$_G['setting']['attachurl'].str_replace($_G['setting']['attachurl'],'',$values['icon']);
					}
					$values['type']=dzzlang('admin/template','widget_type_'.$values['type']);
					if($values['classname']) $values['classname']=dzzlang('template',$values['classname']);
					else $values['classname']=dzzlang('template','no_border');
				
					$list[$values['wid']]=$values;
				}
			}
			$multi = multi($count, $perpage, $page, $theurl);
			
	}
}
include dzztemplate('admin/dzz_widgets');
dzzfooter();

?>