<?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');
}
require_once dzz_libfile('function/plugin');
$refer=dreferer();
dzz_cpheader();

$pluginid = !empty($_GET['pluginid']) ? intval($_GET['pluginid']) : 0;
$anchor = !empty($_GET['gp_anchor']) ? $_GET['anchor'] : '';
if(!empty($_GET['dir']) && !ispluginkey($_GET['dir'])) {
	unset($_GET['dir']);
}
if($operation == 'import'){
	dzz_shownav($lang['menu_plugin'],$lang['menu_plugins_import']);
	if(!submitcheck('importsubmit') && !isset($_GET['dir'])) {
		

		$query = DB::query("SELECT * FROM ".DB::table('dzz_plugin')." ORDER BY available DESC, pluginid DESC");
		$installsdir = array();
		while($plugin = DB::fetch($query)) {
			$installsdir[] = $plugin['directory'];
		}

		$plugindir = DISCUZ_ROOT.'./dzz/plugin';
		$pluginsdir = dir($plugindir);
		$newplugins = array();
		while($entry = $pluginsdir->read()) {
			if(!in_array($entry, array('.', '..')) && is_dir($plugindir.'/'.$entry) && !in_array($entry.'/', $installsdir)) {
				$entrydir = DISCUZ_ROOT.'./dzz/plugin/'.$entry;
				$d = dir($entrydir);
				$filemtime = filemtime($entrydir);
				
				while($f = $d->read()) {
					if(preg_match('/^dzz\_plugin\_'.$entry.'(\_\w+)?\.xml$/', $f)) {
						$entrytitle = $entry;
						$newplugins[$entry]['entrytitle']=$entry;
						$newplugins[$entry]['new']=$filemtime > TIMESTAMP - 86400;
						$entryversion = $entrycopyright = '';
						if(file_exists($entrydir.'/dzz_plugin_'.$entry.'.xml')) {
							$importtxt = @implode('', file($entrydir.'/dzz_plugin_'.$entry.'.xml'));
							$pluginarray = getimportdata('Dzz! Plugin', 1, 1);
							if(!empty($pluginarray['plugin']['name'])) {
								$newplugins[$entry]['entrytitle'] = dhtmlspecialchars($pluginarray['plugin']['name']);
								$newplugins[$entry]['entryversion']= dhtmlspecialchars($pluginarray['plugin']['version']);
								$newplugins[$entry]['entrycopyright'] = dhtmlspecialchars($pluginarray['plugin']['copyright']);
							}
						}
						
						break;
					}
				}
			}
		}
	} else {

		if(!isset($_GET['dir'])) {
			$pluginarray = getimportdata('Dzz! Plugin');
		} elseif(!isset($_GET['installtype'])) {
			$pdir = DISCUZ_ROOT.'./dzz/plugin/'.$_GET['dir'];
			$d = dir($pdir);
			$xmls = '';$count = 0;
			$referer = dreferer();
			while($f = $d->read()) {
				if(preg_match('/^dzz\_plugin_'.$_GET['dir'].'(\_\w+)?\.xml$/', $f, $a)) {
					$extratxt = $extra = substr($a[1], 1);
					if(preg_match('/^SC\_GBK$/i', $extra)) {
						$extratxt = '&#31616;&#20307;&#20013;&#25991;&#29256;';
					} elseif(preg_match('/^SC\_UTF8$/i', $extra)) {
						$extratxt = '&#31616;&#20307;&#20013;&#25991;&#85;&#84;&#70;&#56;&#29256;';
					} elseif(preg_match('/^TC\_BIG5$/i', $extra)) {
						$extratxt = '&#32321;&#39636;&#20013;&#25991;&#29256;';
					} elseif(preg_match('/^TC\_UTF8$/i', $extra)) {
						$extratxt = '&#32321;&#39636;&#20013;&#25991;&#85;&#84;&#70;&#56;&#29256;';
					}
					$url = ADMINSCRIPT.'?action=plugins&operation=import&dir='.$_GET['dir'].'&installtype='.rawurlencode($extra).(!empty($referer) ? '&referer='.rawurlencode($referer) : '');
					$xmls .= '&nbsp;<input type="button" class="btn" onclick="location.href=\''.$url.'\'" value="'.($extra ? $extratxt : $lang['plugins_import_default']).'">&nbsp;';
					$count++;
				}
			}
			$xmls .= '<br /><br /><input class="btn" onclick="location.href=\''.ADMINSCRIPT.'?action=plugins&operation=import\'" type="button" value="'.$lang['cancel_setup'].'"/>';
			//cpmsg($xmls.'===='+$count);
			if($count == 1) {
				dheader('location: '.$url);
			}
			echo '<div class="infobox"><h4 class="infotitle2">'.$lang['plugins_import_installtype_1'].' '.$_GET['dir'].' '.$lang['plugins_import_installtype_2'].' '.$count.' '.$lang['plugins_import_installtype_3'].'</h4>'.$xmls.'</div>';
			
			exit;
		} else {
			$installtype = $_GET['installtype'];
			$dir = $_GET['dir'];
			$license = $_GET['license'];
			$extra = $installtype ? '_'.$installtype : '';
			
			$importfile = DISCUZ_ROOT.'./dzz/plugin/'.$dir.'/dzz_plugin_'.$dir.$extra.'.xml';
			$importtxt = @implode('', file($importfile));
			$pluginarray = getimportdata('Dzz! Plugin');
			if(empty($license) && $pluginarray['license']) {
				require_once libfile('function/discuzcode');
				$pluginarray['license'] = discuzcode(dstripslashes(strip_tags($pluginarray['license'])), 1, 0);
				echo '<div class="infobox"><h4 class="infotitle2">'.$pluginarray['plugin']['name'].' '.$pluginarray['plugin']['version'].' '.$lang['plugins_import_license'].'</h4><div style="text-align:left;line-height:25px;">'.$pluginarray['license'].'</div><br /><br /><center>'.
					'<button onclick="location.href=\''.ADMINSCRIPT.'?action=plugins&operation=import&dir='.$dir.'&installtype='.$installtype.'&license=yes\'">'.$lang['plugins_import_agree'].'</button>&nbsp;&nbsp;'.
					'<button onclick="location.href=\''.ADMINSCRIPT.'?action=plugins\'">'.$lang['plugins_import_pass'].'</button></center></div>';
				exit;
			}
		}

		if(!ispluginkey($pluginarray['plugin']['identifier'])) {
			cpmsg($lang['plugins_edit_identifier_invalid'], '', 'error');
		}
		
		

		$plugin = DB::fetch_first("SELECT name, pluginid FROM ".DB::table('dzz_plugin')." WHERE identifier='{$pluginarray[plugin][identifier]}' LIMIT 1");
		if($plugin) {
			cpmsg(dzzlang('admin/template','plugins_import_identifier_duplicated', array('plugin_name' => $plugin['name'])), '', 'error');
		}

		if(!empty($pluginarray['checkfile']) && preg_match('/^[\w\.]+$/', $pluginarray['checkfile'])) {
			$filename = DISCUZ_ROOT.'./dzz/plugin/'.$_GET['dir'].'/'.$pluginarray['checkfile'];
			if(file_exists($filename)) {
				@include $filename;
			}
		}

		if(empty($_GET['ignoreversion']) && strip_tags($pluginarray['version']) != strip_tags(DZZ_VERSION)) {
			if(isset($dir)) {
				cpmsg(dzzlang('admin/template','plugins_import_version_invalid_confirm',array('cur_version' => $pluginarray['version'], 'set_version' => DZZ_VERSION)), 'action=plugins&operation=import&ignoreversion=yes&dir='.$dir.'&installtype='.$installtype.'&license='.$license, 'form');
			} else {
				cpmsg(dzzlang('admin/template','plugins_import_version_invalid',array('cur_version' => $pluginarray['version'], 'set_version' => DZZ_VERSION)), '', 'error');
			}
		}

		plugininstall($pluginarray, $installtype);
		updatemenu_plugin();
		//updatemenu('plugin');

		if(!empty($dir) && !empty($pluginarray['installfile']) && preg_match('/^[\w\.]+$/', $pluginarray['installfile'])) {
			//showmessage(ADMINSCRIPT.'?action=plugins&operation=plugininstall&dir='.$dir.'&installtype='.$installtype);
			dheader('location: '.ADMINSCRIPT.'?action=plugins&operation=plugininstall&dir='.$dir.'&installtype='.$installtype);
		}

		//pluginstat('install', $pluginarray['plugin']);
		if(!empty($dir)) {
			cpmsg($lang['plugins_install_succeed'], 'action=plugins', 'succeed');
		} else {
			cpmsg($lang['plugins_import_succeed'], 'action=plugins', 'succeed');
		}

	}
} elseif($operation == 'plugininstall' || $operation == 'pluginuninstall' || $operation == 'pluginupgrade') {

	$finish = FALSE;
	$dir = $_GET['dir'];
	$installtype = str_replace('/', '', $_GET['installtype']);
	$extra = $installtype ? '_'.$installtype : '';
	$xmlfile = 'dzz_plugin_'.$dir.$extra.'.xml';
	$importfile = DISCUZ_ROOT.'./dzz/plugin/'.$dir.'/'.$xmlfile;
	if(!file_exists($importfile)) {
		cpmsg($lang['plugin_file_error'], '', 'error');
	}
	$importtxt = @implode('', file($importfile));
	$pluginarray = getimportdata('Dzz! Plugin');
	if($operation == 'plugininstall') {
		$filename = $pluginarray['installfile'];
	} elseif($operation == 'pluginuninstall') {
		$filename = $pluginarray['uninstallfile'];
	} else {
		$filename = $pluginarray['upgradefile'];
		$toversion = $pluginarray['plugin']['version'];
	}
	if(!empty($filename) && preg_match('/^[\w\.]+$/', $filename)) {
		$filename = DISCUZ_ROOT.'./dzz/plugin/'.$dir.'/'.$filename;
		if(file_exists($filename)) {
			@include_once $filename;
		} else {
			$finish = TRUE;
		}
	} else {
		$finish = TRUE;
	}

	if($finish) {
		updatemenu_plugin();
		//updatecache('setting');
		//updatemenu('plugin');
		if($operation == 'plugininstall') {
			//pluginstat('install', $pluginarray['plugin']);
			cpmsg($lang['plugins_install_succeed'], "action=plugins", 'succeed');
		} if($operation == 'pluginuninstall') {
			//pluginstat('uninstall', $pluginarray['plugin']);
			cpmsg($lang['plugins_delete_succeed'], "action=plugins", 'succeed');
		} else {
			//pluginstat('upgrade', $pluginarray['plugin']);
			cpmsg($lang['plugins_upgrade_succeed'], "action=plugins", 'succeed', array('toversion' => $toversion));
		}
	}

}elseif($operation=='design'){
	dzz_shownav($lang['menu_plugin'],$lang['menu_plugins_design']);
	if(!submitcheck('addsubmit')) {
		
	}else{
		$namenew	= dhtmlspecialchars(trim($_POST['namenew']));
		$versionnew	= strip_tags(trim($_POST['versionnew']));
		$identifiernew	= trim($_POST['identifiernew']);
		$copyrightnew	= dhtmlspecialchars($_POST['copyrightnew']);
	
		if(!$namenew) {
			cpmsg($lang['plugins_edit_name_invalid'], '', 'error');
		} else {
			$query = DB::query("SELECT pluginid FROM ".DB::table('dzz_plugin')." WHERE identifier='$identifiernew' LIMIT 1");
			if(DB::num_rows($query) || !ispluginkey($identifiernew)) {
				cpmsg($lang['plugins_edit_identifier_invalid'], '', 'error');
			}
		}
		$data = array(
			'name' => $namenew,
			'version' => $versionnew,
			'identifier' => $identifiernew,
			'directory' => $identifiernew.'/',
			'available' => 0,
			'copyright' => $copyrightnew,
		);
		$pluginid = DB::insert('dzz_plugin', $data, 1);
		//updatecache(array('plugin', 'setting', 'styles'));
		cpmsg($lang['plugins_edit_succeed'], "action=plugins&operation=edit&pluginid=$pluginid", 'succeed');
	}

} elseif($operation == 'enable' || $operation == 'disable') {
	if($operation == 'enable') {
		$plugin = DB::fetch_first("SELECT * FROM ".DB::table('dzz_plugin')." WHERE pluginid='$_GET[pluginid]'");
		if(!$plugin) {
			cpmsg($lang['plugin_not_found'], '', 'error');
		}
		if(!is_file(DISCUZ_ROOT.'dzz/plugin/'.$plugin['directory'].($plugin['indexfile']?$plugin['indexfile']:'index.php'))){
			cpmsg($lang['plugin_file_error'],'action=plugins', 'succeed');
		}
	}else{
		$plugin = DB::fetch_first("SELECT * FROM ".DB::table('dzz_plugin')." WHERE pluginid='$_GET[pluginid]'");
		if(!$plugin) {
			cpmsg($lang['plugin_not_found'], '', 'error');
		}
		/*if($plugin['appid']){
			DB::delete('dzz_apps',"appid='{$plugin[appid]}'");
			set_ico_position($plugin['appid'],'app');
		}
		if($plugin['wid']){
			DB::delete('dzz_widget_market',"wid='{$plugin[wid]}'");
			set_ico_position($plugin['wid'],'widget');
		}
		DB::update('dzz_plugin',array('wid'=>0,'appid'=>0),"pluginid='$_GET[pluginid]'");*/
		
	}
	$available = $operation == 'enable' ? 1 : 0;
	
	DB::query("UPDATE ".DB::table('dzz_plugin')." SET available='$available' WHERE pluginid='$_GET[pluginid]'");
	updatemenu_plugin();
	if($operation == 'enable') {
		cpmsg($lang['plugins_enable_succeed'], 'action=plugins', 'succeed');
	} else {
		cpmsg($lang['plugins_disable_succeed'], 'action=plugins', 'succeed');
	}
} elseif($operation == 'export' && $pluginid) {
	dzz_shownav($lang['menu_plugin'],$lang['menu_plugins_export']);

	$plugin = DB::fetch_first("SELECT * FROM ".DB::table('dzz_plugin')." WHERE pluginid='$pluginid'");
	if(!$plugin) {
		cpheader();
		cpmsg($lang['plugin_not_found'], '', 'error');
	}

	unset($plugin['pluginid']);
	unset($plugin['appid']);
	$pluginarray = array();
	$pluginarray['plugin'] = $plugin;
	$pluginarray['version'] = strip_tags(DZZ_VERSION);

	$plugindir = DISCUZ_ROOT.'./dzz/plugin/'.$pluginarray['plugin']['directory'];
	if(file_exists($plugindir.'/install.php')) {
		$pluginarray['installfile'] = 'install.php';
	}
	if(file_exists($plugindir.'/uninstall.php')) {
		$pluginarray['uninstallfile'] = 'uninstall.php';
	}
	if(file_exists($plugindir.'/upgrade.php')) {
		$pluginarray['upgradefile'] = 'upgrade.php';
	}
	if(file_exists($plugindir.'/check.php')) {
		$pluginarray['checkfile'] = 'check.php';
	}
	if(file_exists($plugindir.'/index.php')) {
		$pluginarray['indexfile'] = 'index.php';
	}
	if(file_exists($plugindir.'/admin.php')) {
		$pluginarray['adminfile'] = 'admin.php';
	}
	exportdata('Dzz! Plugin', $plugin['identifier'], $pluginarray);
} elseif($operation == 'upgrade') {

	$plugin = DB::fetch_first("SELECT name, identifier, directory,  version FROM ".DB::table('dzz_plugin')." WHERE pluginid='$pluginid'");
	$dir = substr($plugin['directory'], 0, -1);

	if(!$_GET['confirmed']) {

		$file = DISCUZ_ROOT.'./dzz/plugin/'.$dir.'/dzz_plugin_'.$dir.($plugin['installtype'] ? '_'.$plugin['installtype'] : '').'.xml';
		$upgrade = false;
		if(file_exists($file)) {
			$importtxt = @implode('', file($file));
			$pluginarray = getimportdata('Dzz! Plugin');
			$newver = !empty($pluginarray['plugin']['version']) ? $pluginarray['plugin']['version'] : 0;
			$upgrade = $newver > $plugin['version'] ? true : false;
		}
		$entrydir = DISCUZ_ROOT.'./dzz/plugin/'.$dir;
		$upgradestr = '';
		if(file_exists($entrydir)) {
			$d = dir($entrydir);
			while($f = $d->read()) {
				if(preg_match('/^dzz\_plugin\_'.$plugin['identifier'].'(\_\w+)?\.xml$/', $f, $a)) {
					$extratxt = $extra = substr($a[1], 1);
					if(preg_match('/^SC\_GBK$/i', $extra)) {
						$extratxt = '&#31616;&#20307;&#20013;&#25991;&#29256;';
					} elseif(preg_match('/^SC\_UTF8$/i', $extra)) {
						$extratxt = '&#31616;&#20307;&#20013;&#25991;&#85;&#84;&#70;&#56;&#29256;';
					} elseif(preg_match('/^TC\_BIG5$/i', $extra)) {
						$extratxt = '&#32321;&#39636;&#20013;&#25991;&#29256;';
					} elseif(preg_match('/^TC\_UTF8$/i', $extra)) {
						$extratxt = '&#32321;&#39636;&#20013;&#25991;&#85;&#84;&#70;&#56;&#29256;';
					}
					if($plugin['installtype'] == $extratxt) {
						continue;
					}
					$importtxt = @implode('', file($entrydir.'/'.$f));
					$pluginarray = getimportdata('Dzz! Plugin');
					$newverother = !empty($pluginarray['plugin']['version']) ? $pluginarray['plugin']['version'] : 0;
					$upgradestr .= $newverother > $plugin['version'] ? '<input class="btn" onclick="location.href=\''.ADMINSCRIPT.'?action=plugins&operation=upgrade&pluginid='.$pluginid.'&confirmed=yes&installtype='.rawurlencode($extra).'\'" type="button" value="'.($extra ? $extratxt : $lang['plugins_import_default']).' '.$newverother.'" />&nbsp;&nbsp;&nbsp;' : '';
				}
			}
		}
		if(!empty($pluginarray['checkfile']) && preg_match('/^[\w\.]+$/', $pluginarray['checkfile'])) {
			$filename = DISCUZ_ROOT.'./source/plugin/'.$plugin['identifier'].'/'.$pluginarray['checkfile'];
			if(file_exists($filename)) {
				loadcache('pluginlanguage_install');
				$installlang = $_G['cache']['pluginlanguage_install'][$plugin['identifier']];
				@include $filename;
			}
		}

		if($upgrade) {

			cpmsg(dzzlang('admin/template','plugins_config_upgrade_confirm',array('pluginname' => $plugin['name'], 'version' => $plugin['version'], 'toversion' => $newver)), 'action=plugins&operation=upgrade&pluginid='.$pluginid.'&confirm=yes', 'form');

		} elseif($upgradestr) {

			echo '<h3>'.cplang('discuz_message').'</h3><div class="infobox"><h4 class="marginbot normal">'.cplang('plugins_config_upgrade_other', array('pluginname' => $plugin['name'], 'version' => $plugin['version'])).'</h4><br /><p class="margintop">'.$upgradestr.
				'<input class="btn" onclick="location.href=\''.ADMINSCRIPT.'?action=plugins\'" type="button" value="'.$lang['cancel'].'"/></div></div>';

		} else {

			cpmsg($lang['plugins_config_upgrade_missed'],'','error');

		}

	} else {

		$installtype = !isset($_GET['installtype']) ? $plugin['installtype'] : (preg_match('/^\w+$/', $_GET['installtype']) ? $_GET['installtype'] : '');
		$importfile = DISCUZ_ROOT.'./dzz/plugin/'.$dir.'/dzz_plugin_'.$dir.($installtype ? '_'.$installtype : '').'.xml';
		if(!file_exists($importfile)) {
			cpmsg($lang['plugin_file_error'], '', 'error');
		}
		$importtxt = @implode('', file($importfile));
		$pluginarray = getimportdata('Dzz! Plugin');

		if(!ispluginkey($pluginarray['plugin']['identifier']) || $pluginarray['plugin']['identifier'] != $plugin['identifier']) {
			cpmsg($lang['plugins_edit_identifier_invalid'], '', 'error');
		}
		

		if(!empty($pluginarray['checkfile']) && preg_match('/^[\w\.]+$/', $pluginarray['checkfile'])) {
			if(!empty($pluginarray['language'])) {
				$installlang[$pluginarray['plugin']['identifier']] = dstripslashes($pluginarray['language']['installlang']);
			}
			$filename = DISCUZ_ROOT.'./dzz/plugin/'.$plugin['directory'].$pluginarray['checkfile'];
			if(file_exists($filename)) {
				loadcache('pluginlanguage_install');
				$installlang = $_G['cache']['pluginlanguage_install'][$plugin['identifier']];
				@include $filename;
			}
		}

		pluginupgrade($pluginarray, $installtype);

		if(!empty($plugin['directory']) && !empty($pluginarray['upgradefile']) && preg_match('/^[\w\.]+$/', $pluginarray['upgradefile'])) {
			dheader('location: '.ADMINSCRIPT.'?action=plugins&operation=pluginupgrade&dir='.$dir.'&installtype='.$plugin['installtype'].'&fromversion='.$plugin['version']);
		}
		$toversion = $pluginarray['plugin']['version'];

		//pluginstat('upgrade', $pluginarray['plugin']);
		cpmsg(dzzlang('admin/template','plugins_upgrade_succeed',array('toversion' => $toversion)), "action=plugins", 'succeed');

	}


} elseif($operation == 'delete') {

	$plugin = DB::fetch_first("SELECT * FROM ".DB::table('dzz_plugin')." WHERE pluginid='$pluginid'");
	$dir = substr($plugin['directory'], 0, -1);

	if(!$_GET['confirmed']) {

		if(!empty($pluginarray['checkfile']) && preg_match('/^[\w\.]+$/', $pluginarray['checkfile'])) {
			$filename = DISCUZ_ROOT.'./dzz/plugin/'.$plugin['identifier'].'/'.$pluginarray['checkfile'];
			if(file_exists($filename)) {
				@include $filename;
			}
		}

		cpmsg(dzzlang('admin/template','plugins_delete_confirm'), 'action=plugins&operation=delete&pluginid='.$pluginid.'&confirmed=yes', 'form', array('pluginname' => $plugin['name'], 'toversion' => $plugin['version']));

	} else {

		$identifier = $plugin['identifier'];
		DB::query("DELETE FROM ".DB::table('dzz_plugin')." WHERE pluginid=$pluginid");
		if($plugin['appid']){
			 	$picids=array();
				$query=DB::query("select picid from ".DB::table('dzz_pic')." where id = '{$plugin[appid]}'");
				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 = '{$plugin[appid]}' and type='app'");
				while($value=DB::fetch($query)){
					dzz_delete_ico($value['icoid']);
				}
				DB::delete('dzz_icos',"oid  = '{$plugin[appid]}' and type='app'");
			 	DB::delete('dzz_apps',"appid  = '{$plugin[appid]}'");
				
		}
		if($plugin['wid']){
			$widget=DB::query("select * from ".DB::table('dzz_widget_market')." where wid ='{$plugin[wid]}'");
				
			if($widget['icon']!='' && $widget['icon']!='dzz/images/default/widgetdefault.png' && !preg_match("/^(http|ftp|https|mms)\:\/\/(.+?)/i", $widget['icon'])){
				@unlink($_G['setting']['attachdir'].$widget['icon']);//删除图标;
			}
			DB::delete('dzz_widget_market',"wid='{$plugin[wid]}'");
			$query=DB::query("select gid from ".DB::table('dzz_widget')." where oid='{$plugin[wid]}'");
			while($value=DB::fetch($query)){
				dzz_delete_widget($value['gid']);
			}
			
		}

		updatemenu_plugin();

		if($dir) {
			$file = DISCUZ_ROOT.'./dzz/plugin/'.$dir.'/dzz_plugin_'.$dir.($installtype ? '_'.$installtype : '').'.xml';
			if(file_exists($file)) {
				$importtxt = @implode('', file($file));
				$pluginarray = getimportdata('Dzz! Plugin');
				if(!empty($pluginarray['uninstallfile']) && preg_match('/^[\w\.]+$/', $pluginarray['uninstallfile'])) {
					dheader('location: '.ADMINSCRIPT.'?action=plugins&operation=pluginuninstall&dir='.$dir.'&installtype='.$modules['extra']['installtype']);
				}
			}
		}

		//pluginstat('uninstall', $pluginarray['plugin']);
		cpmsg($lang['plugins_delete_succeed'], "action=plugins", 'succeed');
	}

	
} elseif($operation == 'edit' && $pluginid) {
		$plugin = DB::fetch_first("SELECT * FROM ".DB::table('dzz_plugin')." WHERE pluginid='$pluginid'");
		if(!$plugin) {
			cpmsg($lang['plugin_not_found'], '', 'error');
		}

	if(!submitcheck('editsubmit')) {
		dzz_shownav($lang['menu_plugin'],$lang['menu_plugins_edit']);
		$plugin['titlebuttons']=explode(',',$plugin['titlebuttons']);
	} else {
		$namenew	= dhtmlspecialchars(trim($_POST['name']));
		$versionnew	= strip_tags(trim($_POST['version']));
		$directorynew	= dhtmlspecialchars($_POST['directory']);
		$identifiernew	= trim($_POST['identifier']);
		$descriptionnew	= dhtmlspecialchars($_POST['description']);
		$copyrightnew	= $plugin['copyright'] ? addslashes($plugin['copyright']) : dhtmlspecialchars($_POST['copyright']);
		
		if(!$namenew) {
			cpmsg($lang['plugins_edit_name_invalid'], '', 'error');
		} elseif(!isplugindir($directorynew)) {
			cpmsg($lang['plugins_edit_directory_invalid'], '', 'error');
		} elseif($identifiernew != $plugin['identifier']) {
			$query = DB::query("SELECT pluginid FROM ".DB::table('dzz_plugin')." WHERE identifier='$identifiernew' LIMIT 1");
			if(DB::num_rows($query) || !ispluginkey($identifiernew)) {
				cpmsg($lang['plugins_edit_identifier_invalid'], '', 'error');
			}
		}
		$setarr=array(  'name'=>$namenew,
						'version'=>$versionnew,
						'directory'=>$directorynew,
						'description'=>$descriptionnew,
						'copyright'=>$copyrightnew,
						'identifier'=>$identifiernew,
						'acceptdata'=>intval($_POST['acceptdata']),
						'datatype'=>trim($_POST['datatype']),
						'titlebuttons'=>implode(',',$_POST['titlebuttons']),
						'open'=>trim($_POST['open']),
						'wwidth'=>intval($_POST['wwidth']),
						'wheight'=>intval($_POST['wheight']),
						'isshow'=>intval($_POST['isshow']),
						'havetask'=>intval($_POST['havetask']),
						'icon'=>trim($_POST['icon']),
						'indexfile'=>trim($_POST['indexfile']),
						'adminfile'=>trim($_POST['adminfile']),
						);
		DB::update('dzz_plugin', daddslashes($setarr)," pluginid='{$pluginid}'");
		/*if($plugin['appid']){
			$updatearr=array('open'=>trim($_POST['open']),
							'width'=>intval($_POST['wwidth']),
							'height'=>intval($_POST['wheight']),
							'isshow'=>intval($_POST['isshow']),
							'havetask'=>intval($_POST['havetask']),
							'titlebuttons'=>implode(',',$_POST['titlebuttons']),
							);
			DB::update('dzz_apps', daddslashes($updatearr)," appid='{$plugin[appid]}'");			
		}*/
		cpmsg($lang['plugins_edit_succeed'], "action=plugins&operation=edit&pluginid=$pluginid&anchor=$anchor", 'succeed');
	}
} elseif($operation == 'pushto' && $pluginid) {
	$target=trim($_GET['target']);
	if(!$plugin=DB::fetch_first("select * from ".DB::table('dzz_plugin')." where pluginid='{$pluginid}'")){
		cpmsg($lang['plugin_not_found'], '', 'error');
	}
	switch($target){
		case 'appmarket':
			if($appid=DB::result_first("select appid from ".DB::table('dzz_apps')." where idtype='pluginid' and typeid='{$pluginid}'")){
				DB::update('dzz_plugin',array('appid'=>$appid),"pluginid='{$pluginid}'");
			}else{
				$apparr=array(
								'appname'=>$plugin['name'],
								'appurl'=>'{DZZSCRIPT}?mod=plugin:'.trim($plugin['directory'],'/').'&op='.($plugin['indexfile']?$plugin['indexfile']:'index.php').'&uid={uid}',
								'appico'=>$plugin['icon']?$plugin['icon']:$_G['siteurl'].'dzz/plugin/'.$plugin['directory'].'images/logo.png',
								'appdesc'=>$plugin['description'],
								'vendor'=>$plugin['copyright'],
								'width'=>$plugin['wwidth'],
								'height'=>$plugin['wheight'],
								'titlebuttons'=>$plugin['titlebuttons'],
								'open'=>$plugin['open'],
								'ismarket'=>1,
								'uid'=>$_G['uid'],
								'idtype'=>'pluginid',
								'typeid'=>$plugin['pluginid'],
								'isshow'=>intval($plugin['isshow']),
								'havetask'=>intval($plugin['havetask']),
								'dateline'=>$_G['timestamp']
								);
				
				if($appid1=DB::insert('dzz_apps',daddslashes($apparr),1)){
					DB::update('dzz_plugin',array('appid'=>$appid1),"pluginid='{$pluginid}'");
				}
			}
			break;
		case 'widgetmarket':
			if($wid=DB::result_first("select wid from ".DB::table('dzz_widget_market')." where idtype='pluginid' and typeid='{$pluginid}'")){
				DB::update('dzz_plugin',array('wid'=>$wid),"pluginid='{$pluginid}'");
			}else{
				$setarr=array(
					'name'=>$plugin['name'],
					'url'=>'{DZZSCRIPT}?mod=plugin:'.trim($plugin['directory'],'/').'&op='.($plugin['indexfile']?$plugin['indexfile']:'index.php').'&uid={uid}',
					'width'=>$plugin['wwidth'],
					'height'=>$plugin['wwidth'],
					'default'=>0,
					'type'=>'link',
					'icon'=>$plugin['icon']?$plugin['icon']:$_G['siteurl'].'dzz/plugin/'.$plugin['directory'].'images/logo.png',
					'idtype'=>'pluginid',
					'typeid'=>$plugin['pluginid'],
					'dateline'=>$_G['timestamp']
				);
				if($wid1=DB::insert('dzz_widget_market',daddslashes($setarr),1)){
					DB::update('dzz_plugin',array('wid'=>$wid1),"pluginid='{$pluginid}'");
				}
			}
			break;
	}
	cpmsg(dzzlang('admin/template','plugins_pushto_succeed_'.$target), 'action=plugins', 'succeed');
}else{
	if(!submitcheck('submit')) {
		dzz_shownav($lang['menu_plugin']);
		$query = DB::query("SELECT * FROM ".DB::table('dzz_plugin')." ORDER BY available DESC, disp DESC");
		$plugins=array();
		
		while($value = DB::fetch($query)) {
			$modfile='./dzz/plugin/'.$value['identifier'].'/'.($value['adminfile']?$value['adminfile']:'admin.php');
			if(file_exists(DISCUZ_ROOT.$modfile)){
				$value['haveadmin']=1;
				$value['action']='plugin:'.$value['identifier'];
			}
			if($value['wid'] && DB::result_first("select COUNT(*) from ".DB::table('dzz_widget_market')." where wid='{$value[wid]}'")){
				
			}else{
				$value['wid']=0;
			}
			if($value['appid'] && DB::result_first("select COUNT(*) from ".DB::table('dzz_apps')." where appid='{$value[appid]}' ")){
				
			}else{
				$value['appid']=0;
			}
			$plugins[]=$value;
		}
//		print_r($plugins);
		
	} else {
		$pluginids=$_POST['pluginid'];
		if($pluginids){
			foreach($pluginids as $pluginid){
				$disp=intval($_POST['displayordernew'][$pluginid]);
				DB::query("UPDATE ".DB::table('dzz_plugin')." SET disp='".$disp."' WHERE pluginid='{$pluginid}'");
			}
		}
		cpmsg($lang['plugins_edit_succeed'], 'action=plugins', 'succeed');
	}
	
}
include dzztemplate('admin/dzz_plugin');
dzzfooter();
?>