<?php
abstract class BaseAction extends Action {
	protected function _initialize() {
		session_start();
		$loginInfo = empty($_SESSION[C('DB_PREFIX', 1) . 'loginInfo'])?'':$_SESSION[C('DB_PREFIX', 1) . 'loginInfo'];
		if ($this -> action != 'login' && empty($loginInfo)) $this -> showMsg(L('LOGIN_FIRST'), '?a=login');
		if ($loginInfo) {
			if ($this -> action == 'login')$this -> showMsg(L('ALREADY_LOGIN'), '?a=defaults');
			$loginInfo = unserialize($loginInfo);
			$userid = get_cookie('userid');
			$username = get_cookie('username');
			if (empty($userid) or empty($username)) {
				$cookieTime = 86400;
				set_cookie('userid', $loginInfo['userid'], $cookieTime);
				set_cookie('username', $loginInfo['username'], $cookieTime);
				set_cookie('groupid', $loginInfo['groupid'], $cookieTime);
				set_cookie('email', $loginInfo['email'], $cookieTime);
				set_cookie('lastdate', $loginInfo['lastdate'], $cookieTime);
			}
			$this -> loginInfo = $loginInfo;
			$this -> assign('loginInfo', $loginInfo);
			$this -> _initializeMore();
			// 后台访问权限验证
			$c = strtolower(substr(get_class($this), 0, -6));
			$userRoleids = array();
			foreach($loginInfo['role'] as $role) {
				$userRoleids[] = $role['roleid'];
			}
			$access = Cache :: read('access', '', 0, 'data');
			if (!empty($access[$c]) && $c != 'content') {
				foreach($access[$c] as $k => $v) {
					if ($this -> action == $v['key']) {
						if ($this -> access($userRoleids, $v['roleids'])) {
							break;
						} else $this -> showMsg(L('NO_PERMISSION'));
					}
				}
			}
		}
	}
	// 回调函数，完成进一步初始化
	protected function _initializeMore() {
	}
	// 后台权限校验 $userRoleids 用户对应的角色ID, $roleids 具备权限的角色ID
	public function access($userRoleids, $roleids) {
		if ($this -> loginInfo['username'] == C('WEB_OWNER', 1) || empty($roleids)) return true;
		if (empty($userRoleids)) return false;
		$roleids = explode(',', $roleids);
		foreach($userRoleids as $userRoleid) {
			if (in_array($userRoleid, $roleids)) return true;
		}
		return false;
	}
}
