<?php
// 会员管理(含会员模型)控制器
class MemberAction extends BaseAction {
	public function defaults() {
		$page = intval(R('page'));
		$where = array();
		$groupid = intval(R('groupid'));
		$isOwner = $this -> loginInfo['username'] == C('WEB_OWNER', 1);
		if ($groupid > 1 or ($groupid === 1 && $isOwner)) $where[] = "groupid=$groupid";
		elseif (!$isOwner) $where[] = '`groupid`>1 OR `userid`=' . $this -> loginInfo['userid'];
		$username = R('username');
		if ($username) {
			$username = str_replace('*', '%', $username);
			$where[] = R('matching')?"username='$username'":"username LIKE '%$username%'";
		}
		$email = R('email');
		if ($email) {
			$email = str_replace('*', '%', $email);
			$where[] = "email LIKE '%$email%'";
		}
		$lastip = R('lastip');
		if ($lastip) {
			$lastip = str_replace('*', '%', $lastip);
			$where[] = "lastip LIKE '%$lastip%'";
		}
		$regdate = intval(R('regdate'));
		if ($regdate) {
			$sotime = TIME - $regdate;
			$where[] = "regdate < $sotime";
		}
		$lastdate = intval(R('lastdate'));
		if ($lastdate) {
			$sotime = TIME - $lastdate;
			$where[] = "lastdate < $sotime";
		}
		$pageSize = intval(R('perpage'));
		$memberObj = M('member');
		$this -> assign('data', $memberObj -> getList($page, $pageSize, $where, 'lastdate DESC'));
		$this -> assign('pages', $memberObj -> pages());
		$this -> assign('gender', L('MEMBER_GENDER'));
		$this -> assign('group', Cache :: read('group', '', 0, 'Data'));
		$this -> display('member');
	}
	public function add() {
		$memberObj = M('member');
		if ($this -> isSubmit) {
			if ($memberObj -> reg()) $msg = L('OPERATE_SUCCESS');
			else $msg = $memberObj -> error?$memberObj -> error:L('OPERATE_FAIL');
			$this -> showMsg($msg);
		}
		$data = array('userid' => 0, 'username' => '', 'email' => '', 'publicemail' => '', 'groupid' => '', 'question' => '', 'answer' => '', 'qq' => '', 'msn' => '', 'gender' => 2);
		$this -> assign('data', $data);
		$this -> assign('config', C('', 0, 'member'));
		$this -> assign('gender', L('MEMBER_GENDER'));
		$this -> assign('group', Cache :: read('group', '', 0, 'Data'));
		$this -> display('member');
	}
	public function edit() {
		$memberObj = M('member');
		if ($this -> isSubmit) {
			$info = R('info', 'post');
			if ($info['password']) $info['password'] = md5($info['password']);
			else unset($info['password']);
			$memberObj -> create($info);
			if ($memberObj -> update()) {
				$msg = L('OPERATE_SUCCESS');
				$go = $this -> forward;
			} else {
				$msg = $memberObj -> error ? $memberObj -> error : L('OPERATE_FAIL');
				$go = $this -> referer;
			}
			if (strstr($go, '?a=top')) $go = '?a=right';
			$this -> showMsg($msg, $go);
		}
		$this -> assign('data', $memberObj -> find(intval(R('userid'))));
		$this -> assign('config', C('', 0, 'member'));
		$this -> assign('gender', L('MEMBER_GENDER'));
		$this -> assign('group', Cache :: read('group', '', 0, 'Data'));
		$this -> display('member');
	}
	public function view() {
		$memberObj = M('member');
		$userid = intval(R('userid'));
		$this -> assign('data', $memberObj -> find($userid));
		$this -> assign('group', Cache :: read('group', '', 0, 'Data'));
		$this -> assign('role', $memberObj -> getRole($userid));
		$this -> display('member');
	}
	public function del() {
		$selids = R('selids');
		if ($selids) {
			$memberObj = M('member');
			if (strstr($selids, ','))$selids = explode(',', $selids);
			$memberObj -> loginInfo = $this -> loginInfo;
			$msg = $memberObj -> del($selids)?L('OPERATE_SUCCESS'):L('OPERATE_FAIL');
		} else $msg = L('NOPARAM'); //缺少参数
		$this -> showMsg($msg);
	}
	public function search() {
		$this -> display('member');
	}
	public function setRole() {
		$memberObj = M('member');
		$userid = intval(R('userid'));
		$data = $memberObj -> find($userid);
		if ($data) {
			if ($this -> isSubmit) {
				M('role') -> set($userid);
				$this -> showMsg(L('OPERATE_SUCCESS'), $this -> forward);
			}
		} else $this -> showMsg(L('NOPARAM'));
		$roles = $memberObj -> getRole($userid);
		$roleids = array();
		foreach($roles as $role)$roleids[] = $role['roleid'];
		$this -> assign('roleids', $roleids);
		$this -> assign('data', $data);
		$this -> assign('role', Cache :: read('role', '', 0, 'Data'));
		$this -> display('member');
	}
	public function checkUsername() {
		$memberObj = M('member');
		$userName = iconv('utf-8', C('APP_CHARSET', 1), $_POST['info']['username']);
		echo $memberObj -> checkUsername($userName)?'success':iconv(C('APP_CHARSET', 1), 'utf-8', $memberObj -> error);
	}
	// 写入会员模块配置,通行证配置需要特殊处理,所以会员模块配置单独处理
	public function config() {
		$configObj = M('config');
		$configFile = JXCMS_ROOT . 'uc_client/config.php';
		if ($this -> isSubmit) {
			$config = R('info', 'post');
			$config['isreg'] = isset($config['isreg'])?intval($config['isreg']):0;
			$config['ischeck'] = isset($config['ischeck'])?intval($config['ischeck']):0;
			if ($config['enablepassport'] && $config['passportfile'] == 'uc') {
				$ucfounderpw = R('ucfounderpw', 'post');
				$uc = R('uc', 'post');
				if ($ucfounderpw) {
					$uc_api = preg_replace("/\/$/", '', trim(R('uc_api', 'post')));
					if (!defined('UC_API')) define('UC_API', $uc_api);
					if (!@include_once JXCMS_ROOT . 'uc_client/client.php') {
						show_error('uc_client目录不存在，请上传安装包中的 ./upload/uc_client 到程序根目录');
					}
					$uc_ip = trim(R('uc_ip', 'post'));
					$ucinfo = uc_fopen2($uc_api . '/index.php?m=app&a=ucinfo&release=' . UC_CLIENT_RELEASE, 500, '', '', 1, $uc_ip);
					list($status, $ucversion, $ucrelease, $uccharset, $ucdbcharset, $apptypes) = explode('|', $ucinfo);
					$ucdbcharset = strtolower(trim($ucdbcharset ? str_replace('-', '', $ucdbcharset) : $ucdbcharset));
					if ($status != 'UC_STATUS_OK') {
						show_error("UCenter无法正常连接，返回错误 ( $status )，请确认UCenter的IP地址是否正确");
					} elseif (C('DB_CHARSET', 1) && $ucdbcharset && $ucdbcharset != C('DB_CHARSET', 1)) {
						show_error('UCenter 服务端字符集与当前应用的字符集不同，请下载 ' . $ucdbcharset . ' 编码的 精迅CMS 进行安装');
					}
					$postdata = "m=app&a=add&ucfounder=&ucfounderpw=" . urlencode($ucfounderpw) . "&apptype=" . urlencode('OTHER') . "&appname=" . urlencode('精迅CMS') . "&appurl=" . urlencode(substr(APP_URL, 0, -1)) . "&appip=&appcharset=" . C('APP_CHARSET', 1) . '&appdbcharset=' . C('DB_CHARSET', 1) . '&release=' . UC_CLIENT_RELEASE;
					$s = uc_fopen2($uc_api . '/index.php', 500, $postdata, '', 1, $uc_ip);

					if (empty($s)) {
						show_error('UCenter用户中心无法连接');
					} elseif ($s == '-1') {
						show_error('UCenter创始人密码不正确');
					} else {
						$ucs = explode('|', $s);
						if (empty($ucs[0]) || empty($ucs[1])) {
							show_error('UCenter返回的数据出现问题，请参考:<br />' . Func :: shtmlspecialchars($s));
						} else {
							// 处理成功
							$addconfig = '';
							// 验证是否可以直接联接MySQL
							$link = mysql_connect($ucs[2], $ucs[4], $ucs[5], 1);
							$connect = $link && mysql_select_db($ucs[3], $link) ? 'mysql' : '';
							$configcontent = trim(file_get_contents(JXCMS_ROOT . 'uc_client/config.tpl.php'));
							$uc = array('connect' => $connect, 'dbhost' => $ucs[2], 'dbuser' => $ucs[4], 'dbpw' => $ucs[5], 'dbname' => $ucs[3], 'dbcharset' => $ucs[6], 'dbtablepre' => '`' . $ucs[3] . '`.' . $ucs[7], 'key' => $ucs[0], 'api' => $uc_api, 'charset' => $ucs[8], 'ip' => $uc_ip, 'appid' => $ucs[1]);
							foreach ($uc as $k => $v) {
								$upkey = strtoupper($k);
								$configcontent = preg_replace("/define\('UC_{$upkey}'\s*,\s*'.*?'\)/i", "define('UC_{$upkey}', '$v')", $configcontent);
							}
						}
					}
				} elseif (is_array($uc)) {
					$configcontent = trim(file_get_contents($configFile));
					foreach ($uc as $k => $v) {
						$upkey = strtoupper($k);
						$k == 'dbtablepre' && $v = '`' . $uc['dbname'] . '`.' . $v;
						if (($k == 'dbpw' or $k == 'key') && $v == '')continue;
						$configcontent = preg_replace("/define\('UC_{$upkey}'\s*,\s*'.*?'\)/i", "define('UC_{$upkey}', '$v')", $configcontent);
					}
				}
				file_put_contents($configFile, $configcontent);
			}
			if ($configObj -> save($config, 'member')) {
				$this -> showMsg(L('OPERATE_SUCCESS'));
			} else {
				$msg = $configObj -> error ? $configObj -> error : L('OPERATE_FAIL');
				$this -> showMsg($msg);
			}
		}
		if (file_exists($configFile)) {
			include_once $configFile;
			if (defined('UC_DBTABLEPRE')) {
				$uc_dbtablepre = explode('.', UC_DBTABLEPRE);
				$this -> assign('uc_dbtablepre', $uc_dbtablepre[1]);
			}
		}
		$this -> assign('data', $configObj -> get('member'));
		$this -> display('member_config');
	}
	// ---------------------------- 会员模型相关 -----------------------------/
	public function model() {
		// M('MemberModel'),实际不存在这个模型类,数据表的名称去掉前缀以类的命名方式创建对象,就可轻易取得数据
		$this -> assign('data', M('MemberModel') -> getList('', 0, '', 'orderid,id'));
		$this -> display('member_model');
	}
	public function modelAdd() {
		if ($this -> isSubmit) {
			$userObj = M('user');
			$msg = $userObj -> modelSave()?L('OPERATE_SUCCESS'):$userObj -> error;
			$this -> showMsg($msg);
		}
		$data = array('state' => 1, 'name' => '', 'tablename' => '');
		$this -> assign('data', $data);
		$this -> display('member_model');
	}
	public function modelEdit() {
		$userObj = M('user');
		if ($this -> isSubmit) {
			$msg = $userObj -> modelSave()?L('OPERATE_SUCCESS'):$userObj -> error;
			$this -> showMsg($msg, $this -> forward);
		}
		$data = $userObj -> table('member_model') -> find(intval(R('id')));
		$this -> assign('data', $data);
		$this -> display('member_model');
	}
	public function modelDel() {
		$id = intval(R('id'));
		if ($id) {
			$msg = M('user') -> modelDel($id)?L('OPERATE_SUCCESS'):L('OPERATE_FAIL');
		} else $msg = L('NOPARAM'); //缺少参数
		$this -> showMsg($msg);
	}
	// 析构函数
	public function __destruct() {
		M('user') -> cache();
	}
}
