<?php
// 权限管理模型
class AccessModel 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['name'] = trim($info['name']);
		if (empty($info['name'])) {
			$this -> error = L('NAME_EMPTY');
			return false;
		}
		if (empty($info['control'])) {
			$info['action'] = '';
			$info['module'] = '';
		} else {
			if ($info['name'] == 'sysmenu') {
				$info['action'] = '';
				$info['module'] = '';
			} elseif (empty($info['action'])) $info['action'] = 'defaults';
		}
		$info['roleids'] = isset($info['roleids'])?implode(',', $info['roleids']):'';
		$this -> create($info);
		if($isAdd){
			$rs = $this -> add();
			if ($info['pid']) {
				$this -> where('id=' . $info['pid']) -> create(array('control' => '', 'action' => '')) -> update();
			}
		} else {
			$rs = $this -> update();
			$this -> where('pid=' . $info['id']) -> create(array('roleids' => $info['roleids'])) -> update();
		}
		return $rs;
	}

	public function cache() {
		$data = $this -> order(array('orderid', 'id')) -> select();
		if (is_array($data)) {
			$menu = $access = array();
			// 将父类id相同的菜单合并，产生二维数组$menu
			foreach($data as $r) {
				if (!empty($r['control'])) {
					$key = $r['action'];
					$r['module'] && $key .= '|' . $r['module'];
					$access[$r['control']][] = array('key' => $key, 'roleids' => $r['roleids']);
				}
				if ($r['ismenu']) {
					if ($r['name'] == 'sysmenu') $r['url'] = $r['control'];
					else {
						$r['url'] = empty($r['control'])?'':"?c=$r[control]";
						if (!empty($r['action']) && $r['action'] != 'defaults') $r['url'] .= "&a=$r[action]";
						if (!empty($r['module'])) $r['url'] .= "&m=$r[module]";
					}
					unset($r['control'], $r['action'], $r['module'], $r['description'], $r['ismenu'], $r['orderid']);
					$menu[$r['pid']][$r['id']] = $r;
				}
			}
			Cache :: write('access', $access, '', 'data');
			Cache :: write('menu', $menu, '', 'data');
		}
	}
}
