<?php
 /**
 * Magic CMS 网站管理员组
 * ============================================================================
 * Copyright 2014 大秦科技，并保留所有权利。
 * 网站地址: http://www.qintech.net；
 * ----------------------------------------------------------------------------
 * 未获商业授权之前，不得将Magic CMS用于商业用途（包括但不限于企业网站、经营性网站
 * 以营利为目的或实现盈利的网站）未经官方许可，禁止在Magic CMS的整体或任何部分基础
 * 上以发展任何派生版本、修改版本或第三方版本用于重新分发。如果您未能遵守本协议的
 * 条款，您的授权将被终止，所被许可的权利将被收回，并承担相应法律责任。
 * ============================================================================
 * Date:2014/12/31
**/
class RbacModule extends CommonModule{

	public function index(){
		$rid = Q('get.rid','','intval');
		if(empty($rid)) $this->error('对不起，参数错误');
		$sql = "SELECT n.nid,n.title,n.menu,n.pid,a.rid as access_rid FROM __node__ AS n LEFT JOIN
            			(SELECT * FROM __access__ WHERE rid={$rid}) AS a
                		ON n.nid = a.nid WHERE n.menu>0 AND n.status=1  ORDER BY n.sorter ASC";
        $result = M()->query($sql);

		foreach($result as $k=>$n){
			//当前角色已经有权限或不需要验证的节点
            $checked = $n['access_rid'] ? " checked" : '';
			$result[$k]['checkbox'] = "<input type='checkbox' name='nid[]' value='{$n['nid']}' id='{$n['nid']}' $checked/><label for='{$n['nid']}'> {$n['title']}</label>";
		}

		$node  = Data::channelLevel($result, 0, '-','nid');
		$this->assign('rid', $rid);
		$this->assign('node', $node);
		$this->display('admin/rbac');
	}

	public function save(){
		if (IS_POST){
			$rid  = Q('post.rid');
			$node = Q('post.nid');
			if (empty($rid)){$this->error('参数错误');}
			$db   = M('access');
			$db->where('rid = '.$rid)->del();
			foreach ($node as $v) {
				$data = array("rid" => $rid, "nid" => $v);
				$db->add($data);
			}
			$this->success('保存成功','?r=admin-group-index');
		}else{
			$this->error('非法请求');
		}
	}
}