<?php
// 权限管理模型
class ModuleModel extends Model {
	public function save() {
		$info = $_POST['info'];
		$info['id'] = intval($info['id']);
		if (!$info['id']) {
			$info['id'] = $this -> getId('id');
			$isAdd = true;
		} else $isAdd = false;
		// 名称有效性
		$info['title'] = trim($info['title']);
		if (empty($info['title'])) {
			$this -> error = L('NAME_EMPTY');
			return false;
		}
		if ($isAdd) {
			if (empty($info['name'])) {
				$this -> error = L('MODULE_NAME_EMPTY');
				return false;
			}
			$moduleName = $info['name'];
			if ($this -> where('name=' . $info['name']) -> find()) {
				$this -> error = L('MODULE_IS_EXIST');
				return false;
			}
			if ($info['tables']) {
				$tableInDb = $this -> db() -> getTables(C('DB_NAME', 1));
				$tables = explode('|', $info['tables']);
				$exist = array();
				foreach($tables as $table) {
					if (in_array($table, $tableInDb)) $exist[] = $table;
				}
				if (!empty($exist)) show_error(implode(',', $exist) . L('TABLE_IS_EXIST'));
			}
			$dir = trim($info['dir'])?$info['dir'] . '/':'';
			$f = JXCMS_ROOT . $dir . 'Lib/Install/' . $info['name'] . '.sql';
			if (file_exists($f)) {
				M('sql') -> execute(file_get_contents($f));
			}
		} else {
			$data = $this -> find($info['id']);
			$moduleName = $data['name'];
		}
		$info['usecategory'] = empty($info['usecategory'])?0:1;
		$info['iscustomconfig'] = empty($info['iscustomconfig'])?0:1;
		$this -> create($info);
		return $isAdd?$this -> add():$this -> update();
	}
	public function del($id) {
		$id = intval($id);
		$data = $this -> find($id);
		$dir = empty($data['dir'])?'':$data['dir'] . '/';
		$f = JXCMS_ROOT . $dir . 'Lib/Uninstall/' . $data['name'] . '.sql';
		if (file_exists($f)) {
			M('sql') -> execute(file_get_contents($f));
		}
		return $this -> delete($id);
	}
	public function cache() {
		$data = $this -> field(array('id', 'title', 'name', 'dir', 'state', 'usecategory')) -> order(array('orderid', 'id')) -> select();
		if (is_array($data)) {
			$array = $tableInDb = array();
			defined('APP_GROUP') or define('APP_GROUP', 'admin');
			$configObj = M('config');
			foreach($data as $v) {
				if (!isset($tableInDb[$v['dir']])) {
					$tableInDb[$v['dir']] = $this -> setDbConfigDir($v['dir']) -> db() -> getTables(C('DB_NAME', 1, $v['dir']));
				}
				if (in_array(C('DB_PREFIX', 1, $v['dir']) . $v['name'] . '_config', $tableInDb[$v['dir']])) {
					$configObj -> cache($v['name']);
				}
				$array[$v['id']] = $v;
			}
			Cache :: write('module', $array, '', 'data');
		}
	}
}
