<?php
/*-------------------------------------
	版权所有：南京牛昆网络科技有限公司（TEL-15896098989）
	程序版本：1.0
	更新日期：2015-02-09 
-------------------------------------*/
class module
{
	private $db;
	private $table;
	private $membergrade_table;
	private $adminrole_table;

	function __construct()
	{
		global $db;
		$this->db=$db;
		$this->table=LA_PRE.'module';
		$this->adminrole_table=LA_PRE.'adminrole';
	}
	
	function datalist()
	{
		global $page;
		$where=1;
		include SYSTEM_ROOT.'include/datalist.class.php';
		$datalist = new datalist();
		$orderby='issystem DESC ,status DESC ,id ASC';
		$page=max(isset($page)?intval($page):1,1);
		$pagesize=15;
		$result=$datalist->getlist($this->table,$where,$orderby,$page,$pagesize);
		$this->pagestring=$datalist->pagestring;
		return $result;
	}

	function sysmodule()
	{
		return $this->db->fetch_all("SELECT * FROM `$this->table` WHERE `$this->table`.`issystem`=1 AND `$this->table`.`status`=1 ORDER BY `$this->table`.`orderby` ASC,`$this->table`.`id` DESC");
	}

	function usermodule()
	{
		return $this->db->fetch_all("SELECT * FROM `$this->table` WHERE `$this->table`.`issystem`=0 AND `$this->table`.`status`=1 ORDER BY `$this->table`.`orderby` ASC,`$this->table`.`id` DESC");
	}

	function adminmenu($moduleid)
	{
		global $_userid,$_roleid,$admin_founders;
		$menu='';
		$modinfo=$this->get(intval($moduleid));
		$r=string2array($modinfo['adminmenu']);
		foreach($r as $key => $_r)
		{
			$adminrole=explode(',',$_r['role']);
			if((in_array($_roleid,$adminrole) || in_array($_userid,$admin_founders)) && trim($_r['name']))
			{
				$menu.='<li><a href="?mod='.$modinfo['folder'].'&file='.$modinfo['folder'].'&action='.$key.'" target="iframe-wrap">'.$_r['name'].'</a></li>';
			}
		}

		return $menu;
	}

	function uninstalllist()
	{
		$result=$results=$files=$alls=array();
		$alls=glob(SYSTEM_ROOT.'*');
		$files=glob(SYSTEM_ROOT.'*.*');
		$results=array_diff($alls,$files);
		$i=0;

		if($results)foreach($results as $key => $_results)
		{
			if(is_file($_results.'/module.install.php') && !$this->get(basename($_results),'folder'))
			{
				$result[$i]=cache_read('module.install.php',$_results.'/');
				$i++;
			}
		}
		return $result;
	}

	function adminpermission($roleid,$moduleid)
	{
		$modinfo=$this->get(intval($moduleid));
		return in_array($roleid,explode(',',$modinfo['adminrole']));
	}

	function get($id,$byfield='id')
	{
		return $this->db->fetch_one("SELECT * FROM `$this->table` WHERE `$this->table`.`$byfield`='".stripslashes($id)."'");
	}

	function getmoduleid($folder='')
	{
		$r=$this->get($folder,'folder');
		return $r?$r['id']:0;
	}

	function getmodulename($folder='')
	{
		$r=$this->get($folder,'folder');
		return $r?$r['name']:'';
	}

	function disabled($ids=array(),$status=0)
	{
		$ids=is_array($ids)?array_map('intval',$ids):array(intval($ids));
		$status=intval($status);
		foreach($ids as $id)
		{
			$this->db->update($this->table,array('status'=>$status),'id='.$id);
		}
		return true;
	}

	function install($info)
	{
		$info['membergrade']=implode(',',$info['membergrade']);
		$info['membermodel']=implode(',',$info['membermodel']);
		$info['adminrole']=implode(',',$info['adminrole']);

		foreach($info['admin-key'] as $k=>$key)
		{
			if(trim($key) && trim($info['admin-name'][$k]))
			{
				$info['adminmenu'][$key]=array('name'=>$info['admin-name'][$k],'role'=>implode(',',$info['admin-role'][$k]));
			}
		}

		foreach($info['member-key'] as $k=>$key)
		{
			if(trim($key) && trim($info['member-name'][$k]))
			{
				$info['membermenu'][$key]=array('name'=>$info['member-name'][$k],'grade'=>implode(',',$info['member-grade'][$k]));
			}
		}
		$info['adminmenu']=$info['adminmenu']?var_export($info['adminmenu'],true):'';
		$info['membermenu']=$info['membermenu']?var_export($info['membermenu'],true):'';
		return $this->db->insert($this->table,$info);
	}

	function import($folder)
	{
		if(is_file(SYSTEM_ROOT.$folder.'/module.install.php'))
		{
			$info=cache_read('module.install.php',SYSTEM_ROOT.$folder.'/');
		}
		$this->db->insert($this->table,$info);
		$sqlfile=SYSTEM_ROOT.$folder.'/install.sql';

		if(is_file($sqlfile))
		{
			$sqls=file_get_contents($sqlfile);
			if($sqls)
			{
				$sqls=explode(';',trim($sqls));
				foreach($sqls as $sql)
				{
					if(trim($sql))
					{
						$this->db->query(str_replace('la_',LA_PRE,trim($sql)),true);
					}
				}
			}
			@unlink($sqlfile);
		}

		return true;
	}

	function set($id,$info)
	{
		$id=intval($id);
		unset($info['folder'],$info['issystem']);
		$info['membergrade']=implode(',',$info['membergrade']);
		$info['membermodel']=implode(',',$info['membermodel']);
		$info['adminrole']=implode(',',$info['adminrole']);

		foreach($info['admin-key'] as $k=>$key)
		{
			if(trim($key) && trim($info['admin-name'][$k]))
			{
				$info['adminmenu'][$key]=array('name'=>$info['admin-name'][$k],'role'=>implode(',',$info['admin-role'][$k]));
			}
		}

		foreach($info['member-key'] as $k=>$key)
		{
			if(trim($key) && trim($info['member-name'][$k]))
			{
				$info['membermenu'][$key]=array('name'=>$info['member-name'][$k],'grade'=>implode(',',$info['member-grade'][$k]));
			}
		}
		$info['adminmenu']=$info['adminmenu']?var_export($info['adminmenu'],true):'';
		$info['membermenu']=$info['membermenu']?var_export($info['membermenu'],true):'';
		return $this->db->update($this->table,$info,'id='.$id);
	}

	function export($id)
	{
		$id=intval($id);

		/*
			获取模块信息
		*/
		$modinfo=$this->get($id);
		unset($modinfo['id']);
		$modpath=$modinfo['folder'].'/';
		$zipfile=SYSTEM_ROOT.'data/tmp/'.$modinfo['name'].'.zip';

		/*
			获取模块信息并写入文件
		*/
		cache_write('module.install.php',$modinfo,SYSTEM_ROOT.$modinfo['folder'].'/');
		
		/*
			导出数据库安装、卸载文件
		*/
		if(!empty($modinfo['dbtable']))
		{
			$installsql='';
			$uninstallsql='';

			$tables=explode(',',trim($infos['dbtable']));
			if($tables)foreach($tables as $table)
			{
				if(!empty($table))
				{
					$r=$this->db->fetch_one("SHOW CREATE TABLE `{$table}`");
					$installsql.="DROP TABLE IF EXISTS `".str_replace(LA_PRE,'la_',$table)."`;\n";
					$installsql.=str_replace(LA_PRE,'la_',$r['Create Table']).";\n";
					$uninstallsql.="DROP TABLE IF EXISTS `".str_replace(LA_PRE,'la_',$table)."`;\n";
				}
			}

			@file_put_contents(SYSTEM_ROOT.$infos['folder'].'/install.sql',$installsql);
			@file_put_contents(SYSTEM_ROOT.$infos['folder'].'/uninstall.sql',$uninstallsql);
		}

		/*
			导出模块为压缩文件
		*/
		
		include SYSTEM_ROOT.'include/pclzip.lib.php';
		$archive = new PclZip($zipfile);
		if(is_dir(SYSTEM_ROOT.'template/'.TLP_NAME.'/'))
		{
			$result = $archive->create(implode(',',glob($modpath.'*')).','.implode(',',glob('template/'.TPL_NAME.'/'.$infos['folder'])),PCLZIP_OPT_ADD_TEMP_FILE_ON);
		}
		else
		{
			$result = $archive->create(implode(',',glob($modpath.'*')),PCLZIP_OPT_ADD_TEMP_FILE_ON);
		}

        if (!$result) 
		{
			return false;
        }
		else
		{
			/*
				提供下载
			*/
			if(ob_get_length() !== false) @ob_end_clean();
			header('Pragma: public');
			header('Last-Modified: '.gmdate('D, d M Y H:i:s') . ' GMT');
			header('Cache-Control: no-store, no-cache, must-revalidate');
			header('Cache-Control: pre-check=0, post-check=0, max-age=0');
			header('Content-Transfer-Encoding: binary');
			header('Content-Encoding: none');
			header('Content-type: application/x-zip');
			header('Content-Disposition: attachment; filename="'.$modinfo['folder'].'.zip"');
			header('Content-length: '.filesize($zipfile));
			readfile($zipfile);
			@unlink($zipfile);
			exit();
		}
	}

	function upgrade($id)
	{
		$id=intval($id);
		$modinfo=$this->get($id);
		$sqlfile=SYSTEM_ROOT.$modinfo['folder'].'/upgrade.sql';

		if(is_file($sqlfile))
		{
			$sqls=file_get_contents($sqlfile);
			if($sqls)
			{
				$sqls=explode(';',trim($sqls));
				foreach($sqls as $sql)
				{
					if(trim($sql))
					{
						$this->db->query(str_replace('la_',LA_PRE,trim($sql)),true);
					}
				}
			}
			else
			{
				return false;
			}
			@unlink($sqlfile);
		}
		else
		{
			return false;
		}
	}

	function uninstall($id)
	{
		$id=intval($id);
		$modinfo=$this->get($id);
		$sqlfile=SYSTEM_ROOT.$modinfo['folder'].'/uninstall.sql';

		if(is_file($sqlfile))
		{
			$sqls=file_get_contents($sqlfile);
			if($sqls)
			{
				$sqls=explode(';',trim($sqls));
				foreach($sqls as $sql)
				{
					if(trim($sql))
					{
						$this->db->query(str_replace('la_',LA_PRE,trim($sql)),true);
					}
				}
			}
			else
			{
				return false;
			}
		}
		rmdirs(SYSTEM_ROOT.$modinfo['folder']);
		if(is_dir(SYSTEM_ROOT.'template/'.TPL_NAME.'/'.$modinfo['folder']) && preg_match('/^[a-z0-9_]{1,}$/i',$modinfo['folder']))
		{
			rmdirs(SYSTEM_ROOT.'template/'.TPL_NAME.'/'.$modinfo['folder']);
		}
		$this->db->mysql_delete($this->table,$id);
		return true;
	}
	
	function version($module)
	{
		$version=LA_RELEASE;
		$versionfile=SYSTEM_ROOT.'data/module_version/'.$module.'.version.php';
		if(is_file($versionfile))
		{
			$version=file_get_contents($versionfile);
		}

		return date('Y-m-d',strtotime($version));
	}
}
?>
