<?php
defined('IN_YUNYECMSAdmin') or exit('No permission.');
core::load_admin_class('admin');
class role extends YUNYE_admin
{
	private $lang;  //当前根栏目
	function __construct()
	{
		parent::__construct();
		$this->db = core::load_model('admin_role_model');
		$this->lang = getlangid();
	}
	//加载首页
	public function init()
	{
		$parnav = '<li class=\"breadcrumb-item\"><a href=\"' . url_admin('init', 'user', '') . '\" target=\"maincontent\">管理员</a></li><li><a href=\"' . url_admin('init', 'role', '') . '\" target=\"maincontent\">权限管理</a></li><li class=\"breadcrumb-item active\">权限列表</li>';
		if (!getroot('users', 'role')) {
			messagebox(Lan('no_permission'), 'back', "warn");
		}
		$pagesize = 20;
		$sqlquery = "select `roleid`, `rolename`,`powers` from `#yunyecms_admin_role`  ";
		$where = " where `rolename`<>'' ";
		$sqlcnt = " select count(*) from `#yunyecms_admin_role` ";
		$order = " order by `roleid` asc ";
		if (isset($_POST["searchkey"])) {
			$searchkey = usafestr(trim($_POST["searchkey"]));
			if (empty($searchkey)) {
				messagebox(Lan('search_key_empty'), url_admin('init'), "warn");
				exit;
			} else {
				$where = " where `rolename`  like'%{$searchkey}%' ";
			}
		}
		$pagearr = $this->db->pagelist($sqlcnt, $sqlquery, $where, $order, $pagesize);

		if ($pagearr["count"] != 0) {
			$list = $pagearr["query"];
			$pages = $pagearr["page"];
		}
		require tpl_adm('role_list');
	}
	public function role_add()
	{
		if (!getroot('users', 'role')) {
			messagebox(Lan('no_permission'), 'back', "warn");
		}
		if (!empty($_GET["id"])) {
			$parnav = '<li class=\"breadcrumb-item\"><a href=\"' . url_admin('init', 'user', '') . '\" target=\"maincontent\">管理员</a></li><li><a href=\"' . url_admin('init', 'role', '') . '\" target=\"maincontent\">权限管理</a></li><li class=\"breadcrumb-item active\">权限修改</li>';
			$roleid = trim($_GET["id"]);
			if (!is_numeric($roleid)) {
				messagebox(Lan('id_notnumber'), url_admin('init'), "warn");
			}
			$crole = $this->db->find("select * from `#yunyecms_admin_role` where `roleid`= {$roleid}");
			if (empty($crole)) {
				messagebox(Lan('role_not_exist'), url_admin('role_add', 'role', array('id' => $roleid)), "warn");
			} else {
				$powersarr = array();
				$powers = yunyecms_strrange_decode($crole["powers"], $crole["salt"], $crole["range"]);
				if (!empty($powers)) {
					$powersarr = json_decode($powers, true);
				}
			}
			$yyact = "edit";
		} else {
			$yyact = yyact_get("add");
			$parnav = '<li class=\"breadcrumb-item\"><a href=\"' . url_admin('init', 'user', '') . '\" target=\"maincontent\">管理员</a></li><li><a href=\"' . url_admin('init', 'role', '') . '\" target=\"maincontent\">权限管理</a></li><li class=\"breadcrumb-item active\">增加权限</li>';
		}
		if (isset($_POST["yyact"])) {
			$rolename = $_POST["rolename"];
			if (array_key_exists("powers", $_POST)) {
				$powers = $_POST["powers"];
				if ((yunyecms_getarrayvalue($powers, 'info', 'all') == 1) && (yunyecms_getarrayvalue($powers, 'info', 'self') == 1)) {
					messagebox(Lan('role_info_allself'), 'back', "warn");
					exit;
				}
			} else {
				$powers = NULL;
			}
			if ($_POST["yyact"] == "add") {
				$this->add_admin_role($rolename, $powers);
			}
			if ($_POST["yyact"] == "edit") {
				$id = $_POST["id"];
				$oldrolename = $_POST["oldrolename"];
				$this->edit_admin_role($id, $rolename, $oldrolename, $powers);
			}
		}
		require tpl_adm('role_add');
	}

	public function categoryrole()
	{
		if (!getroot('users', 'role')) {
			messagebox(Lan('no_permission'), 'back', "warn");
		}
		if (!isset($_POST["yyact"])) {
			if (!empty($_GET["id"])) {
				$parnav = '<li class=\"breadcrumb-item\"><a href=\"' . url_admin('init', 'user', '') . '\" target=\"maincontent\">管理员</a></li><li><a href=\"' . url_admin('init', 'role', '') . '\" target=\"maincontent\">权限管理</a></li><li class=\"breadcrumb-item active\">权限修改</li>';
				$roleid = trim($_GET["id"]);
				if (!is_numeric($roleid)) {
					messagebox(Lan('id_notnumber'), url_admin('init'), "warn");
				}
				$crole = $this->db->getbyid($roleid, 'admin_role', 'roleid');;
				if (empty($crole)) {
					messagebox(Lan('role_not_exist'), url_admin('role_add', 'role', array('id' => $roleid)), "warn");
				} else {
					$powercatarr = array();
					if (!empty($crole["powercat"])) {
						$powercat = yunyecms_strdecode($crole["powercat"]);
						$powercatarr = unserialize($powercat);
					}
				}
				$list = $this->db->select("select * from `#yunyecms_category`  where pid=0 and lang={$this->lang}  order by `addtime` desc");
				$yyact = "edit";
			} else {
				messagebox("参数错误", 'back', "warn");
			}
		} else {
			$rolename = $_POST["rolename"];
			if (array_key_exists("powercat", $_POST)) {
				$powercat = $_POST["powercat"];
			} else {
				$powercat = NULL;
			}
			if ($_POST["yyact"] == "edit") {
				$id = $_POST["id"];
				if (!is_numeric($id)) {
					messagebox(Lan('id_notnumber'), url_admin('init'), "warn");
				}
				$crole = $this->db->getbyid($id, 'admin_role', 'roleid');
				if (empty($crole)) {
					messagebox(Lan('role_not_exist'), url_admin('role_add', 'role', array('id' => $id)), "warn");
				} else {
					$powersarr = array();
					if (!empty($crole["powers"])) {
						$powers = yunyecms_strrange_decode($crole["powers"], $crole["salt"], $crole["range"]);
						$powersarr = json_decode($powers, true);
					}
				}
				if (empty($powersarr["info"])) {
					messagebox("请先在权限设置里面配置信息管理权限", url_admin('role_add', 'role', array('id' => $id)), "warn");
				} elseif (empty($powersarr["info"]['browse']) && empty($powersarr["info"]['add']) && empty($powersarr["info"]['edit']) && empty($powersarr["info"]['del'])) {
					messagebox("请先在权限设置里面配置信息管理权限", url_admin('role_add', 'role', array('id' => $id)), "warn");
				}
				if (!empty($powercat)) {
					foreach ($powercat as $key => $var) {
						if (!empty($var['view'])) {
							$checkview[] = $var['view'];
						}
						if (!empty($var['add'])) {
							$checkadd[] = $var['add'];
						}
						if (!empty($var['edit'])) {
							$checkedit[] = $var['edit'];
						}
						if (!empty($var['delete'])) {
							$checkdelete[] = $var['delete'];
						}
					}
					if (empty($powersarr["info"]['view'])) {
						if (!empty($checkview)) {
							messagebox("该用户不能设置栏目内容查看权限，您必须先在权限设置里面为该用户开通信息查看权限", 'back', "warn", '', '', 5000);
						}
					}
					if (empty($powersarr["info"]['add'])) {
						if (!empty($checkadd)) {
							messagebox("该用户不能设置栏目内容添加权限，您必须先在权限设置里面为该用户开通内容添加权限", 'back', "warn", '', '', 5000);
						}
					}
					if (empty($powersarr["info"]['edit'])) {
						if (!empty($checkedit)) {
							messagebox("该用户不能设置栏目内容编辑权限，您必须先在权限设置里面为该用户开通内容编辑权限", 'back', "warn", '', '', 5000);
						}
					}
					if (empty($powersarr["info"]['del'])) {
						if (!empty($checkdelete)) {
							messagebox("该用户不能设置栏目内容删除权限，您必须先在权限设置里面为该用户开通内容删除权限", 'back', "warn", '', '', 5000);
						}
					}
				} else {
					messagebox("您至少应该选择一项栏目内容管理权限");
				}
				$oldrolename = $_POST["oldrolename"];
				$this->edit_admin_categoryrole($id, $rolename, $oldrolename, $powercat);
			}
		}
		require tpl_adm('categoryrole');
	}


	public function role_delete()
	{
		if (!getroot('users', 'role')) {
			messagebox(Lan('no_permission'), 'back', "warn");
		}
		if (!empty($_GET["id"])) {
			$id = trim($_GET["id"]);
			if (!is_numeric($id)) {
				messagebox(Lan('id_notnumber'), url_admin('init'), "warn");
			}
			$crole = $this->db->find("select * from `#yunyecms_admin_role` where `roleid`= {$id}");
			if (empty($crole)) {
				messagebox(Lan('role_not_exist'), url_admin('init'), "warn");
			}
			$query = $this->db->query("delete from `#yunyecms_admin_role` where roleid={$id}");
			if ($query) {
				messagebox(Lan('role_delete_success'), url_admin('init'), "success");
			} else {
				messagebox(Lan('role_delete_error'), url_admin('init'), "warn");
			}
		}
	}

	private function checkrole_exist($rolename)
	{
		$rolename =  usafestr(trim($rolename));
		if (empty($rolename)) {
			return false;
		} else {
			if ($this->db->find("select `rolename` from `#yunyecms_admin_role` where `rolename`= '{$rolename}'")) {
				return true;
			}
		}
	}

	private function add_admin_role($rolename, $powers)
	{
		$rolename = usafestr(trim($rolename));
		$salt = make_rand(20);
		$range['md5']['min'] = mt_rand(0, 10);
		$range['md5']['max'] = mt_rand(1, 22);
		$range['sha1']['min'] = mt_rand(0, 15);
		$range['sha1']['max'] = mt_rand(1, 25);
		$rangearr = yunyecms_json_encode($range);
		$powers = yunyecms_strrange_encode(json_encode($powers), $salt, $rangearr);
		if (empty($rolename)) {
			messagebox(Lan('role_name_empty'), url_admin('role_add', '', ''), "error");
		}
		if (empty($powers)) {
			messagebox(Lan('role_powers_empty'), url_admin('role_add', '', ''), "error");
		}
		if ($this->checkrole_exist($rolename)) {
			messagebox(Lan('role_already_exist'), url_admin('role_add', '', ''), "warn");
		} else {
			$strsql = "insert into `#yunyecms_admin_role`(`rolename`,`powers`,`salt`,`range`) values('$rolename','$powers','$salt','$rangearr')";
			$query = $this->db->query($strsql);
			$roleid = $this->db->insert_id();
			if ($roleid) {
				messagebox(Lan('role_add_success'), url_admin('init'), "success");
			}
		}
	}
	private function edit_admin_role($id, $rolename, $oldrolename, $powers)
	{
		$rolename = usafestr(trim($rolename));
		$oldrolename = usafestr(trim($oldrolename));
		$id = usafestr(intval(trim($id)));
		if (!is_numeric($id)) {
			messagebox(Lan('id_notnumber'), url_admin('role_add', 'role', array('id' => $id)), "warn");
		}
		if (empty($rolename) || empty($id)) {
			messagebox(Lan('role_name_empty'), url_admin('role_add', 'role', array('id' => $id)), "warn");
		}
		if (empty($powers)) {
			messagebox(Lan('role_powers_empty'), url_admin('role_add', 'role', array('id' => $id)), "error");
		}
		$salt = make_rand(20);
		$range['md5']['min'] = mt_rand(0, 10);
		$range['md5']['max'] = mt_rand(1, 22);
		$range['sha1']['min'] = mt_rand(0, 15);
		$range['sha1']['max'] = mt_rand(1, 25);
		$rangearr = yunyecms_json_encode($range);
		$powers = yunyecms_strrange_encode(json_encode($powers), $salt, $rangearr);
		if ($rolename != $oldrolename) {
			$num = $this->db->GetCount("select count(*) as total from `#yunyecms_admin_role` where rolename='$rolename' and roleid<>$id limit 1");
			if ($num) {
				messagebox(Lan('role_already_exist'), url_admin('role_add', '', ''), "warn");
			}
		}
		$strsql = "update `#yunyecms_admin_role`  set `rolename`='$rolename',`powers`='{$powers}',`salt`='{$salt}',`range`='{$rangearr}' where roleid=$id";
		$query = $this->db->query($strsql);
		if ($query) {
			messagebox(Lan('role_edit_success'), url_admin('init'), "success");
		}
	}

	private function edit_admin_categoryrole($id, $rolename, $oldrolename, $powercat)
	{
		$rolename = usafestr(trim($rolename));
		$oldrolename = usafestr(trim($oldrolename));
		$id = usafestr(intval(trim($id)));
		if (!is_numeric($id)) {
			messagebox(Lan('id_notnumber'), url_admin('role_add', 'role', array('id' => $id)), "warn");
		}
		if (empty($rolename) || empty($id)) {
			messagebox(Lan('role_name_empty'), url_admin('role_add', 'role', array('id' => $id)), "warn");
		}
		if (empty($powercat)) {
			messagebox(Lan('role_powers_empty'), url_admin('categoryrole', 'role', array('id' => $id)), "error");
		}
		$powercat = yunyecms_strencode(serialize($powercat));
		if ($rolename != $oldrolename) {
			$num = $this->db->GetCount("select count(*) as total from `#yunyecms_admin_role` where rolename='$rolename' and roleid<>$id limit 1");
			if ($num) {
				messagebox(Lan('role_already_exist'), url_admin('role_add', '', ''), "warn");
			}
		}
		$strsql = "update `#yunyecms_admin_role`  set `rolename`='$rolename',`powercat`='{$powercat}' where roleid=$id";
		$query = $this->db->query($strsql);
		if ($query) {
			messagebox(Lan('role_edit_success'), url_admin('init'), "success");
		}
	}
}
