<?php 
/**
#	Project: PHPDISK File Storage Solution
#	This is NOT a freeware, use is subject to license terms.
#
#	Site: http://www.phpdisk.com
#
#	$Id: users.inc.php 67 2016-08-05 07:26:31Z along $
#
#	Copyright (C) 2008-2016 PHPDisk Team. All Rights Reserved.
#
*/

if(!defined('IN_PHPDISK') || !defined('IN_ADMINCP')) {
	exit('[PHPDisk] Access Denied');
}
$q = $db->query("select gid,group_name,group_type from {$tpf}groups order by gid desc");
$groups = array();
while($rs = $db->fetch_array($q)){
	$rs['txtcolor'] = $rs['group_type'] ? 'txtblue' : '';
	$groups[] = $rs;
}
$db->free($q);
unset($rs);

$q = $db->query("select * from {$tpf}departs order by depart_id asc");
$departs = array();
while($rs = $db->fetch_array($q)){
	$departs[] = $rs;
}
$db->free($q);
unset($rs);

switch($action){

	case 'index':

		if($task =='move'){
			form_auth(gpc('formhash','P',''),formhash());

			$userids = gpc('userids','P',array(''));
			$dest_gid = (int)gpc('dest_gid','P','');

			if($settings['online_demo']){
				$error = true;
				$sysmsg[] = __('online_demo_deny');
			}
			if(!$dest_gid){
				$error = true;
				$sysmsg[] = __('please_select_dest_gid');
			}

			$ids_arr = get_ids_arr($userids,__('please_select_move_users'),1);
			if($ids_arr[0]){
				$error = true;
				$sysmsg[] = $ids_arr[1];
			}else{
				$user_str = $ids_arr[1];
			}

			if(!$error){
				$db->query_unbuffered("update {$tpf}users set gid='$dest_gid' where userid in ($user_str)");
				$sysmsg[] = __('move_user_success');
				redirect(urr(ADMINCP,"item=users&menu=user&action=index"),$sysmsg);
			}else{
				redirect('back',$sysmsg);
			}
		}else{
			$perpage = 50;
			$gid = (int)gpc('gid','G',0);
			$depart_id = (int)gpc('depart_id','G',0);
			$orderby = gpc('orderby','G','');
			$sql_str = "";
			switch($orderby){
				case 'time_desc':
					$sql_orderby = " order by reg_time desc";
					break;
				case 'time_asc':
					$sql_orderby = " order by reg_time asc";
					break;
				case 'is_locked':
					$sql_orderby = $sql_str = " and u.is_locked=1";
					break;
				default:
					$sql_orderby = "";
			}
			if($gid){
				$sql_ext = " and u.gid='$gid'";
			}elseif($depart_id){
				$sql_ext = " and u.depart_id='$depart_id'";
			}else{
				$sql_ext = "";
			}
			if($depart_id){
				$sql_do = " {$tpf}users u,{$tpf}groups g,{$tpf}departs d where u.gid=g.gid and u.depart_id=d.depart_id {$sql_ext}";
			}else{
				$sql_do = " {$tpf}users u,{$tpf}groups g where u.gid=g.gid {$sql_ext}";
			}

			$rs = $db->fetch_one_array("select count(*) as total_num from {$sql_do} {$sql_str}");
			$total_num = $rs['total_num'];
			$start_num = ($pg-1) * $perpage;

			$q = $db->query("select userid,username,email,reg_time,is_locked,reg_ip,group_name,g.gid from {$sql_do} {$sql_orderby} limit $start_num ,$perpage");

			$users = array();
			while($rs = $db->fetch_array($q)){
				$rs['is_admin'] = ($rs['gid']==1) ? 1 : 0;
				$rs['reg_time_s'] = date("Y-m-d",$rs['reg_time']);
				$rs['reg_time'] = date("Y-m-d H:i:s",$rs['reg_time']);
				$rs['status_text'] = $rs['is_locked'] ? '<span class="txtred">'.__('user_open').'</span>' : __('user_locked');
				$rs['a_user_edit'] = urr(ADMINCP,"item=users&menu=$menu&action=user_edit&uid={$rs['userid']}");
				$rs['a_user_lock'] = urr(ADMINCP,"item=users&menu=$menu&action=user_lock&uid={$rs['userid']}");
				$rs['a_user_delete'] = urr(ADMINCP,"item=users&menu=$menu&action=user_delete&uid={$rs['userid']}");
				$rs['a_user_viewfile'] = urr(ADMINCP,"item=files&menu=file&action=index&view=user&uid={$rs['userid']}");
				$users[] = $rs;
			}
			$db->free($q);
			unset($rs);


			$q = $db->query("select gid,group_name,group_type from {$tpf}groups where gid<>1 order by gid asc");
			$mini_groups = array();
			while($rs = $db->fetch_array($q)){
				$rs['txtcolor'] = $rs['group_type'] ? 'txtblue' : '';
				$mini_groups[] = $rs;
			}
			$db->free($q);
			unset($rs);

			$page_nav = multi($total_num, $perpage, $pg, urr(ADMINCP,"item=users&menu=user&action=index&gid=$gid"));

			require_once template_echo($item,$admin_tpl_dir,'',1);
		}
		break;

	case 'search':
		$perpage = 50;
		$word = trim(gpc('word','G',''));
		$word_str = str_replace('　',' ',replace_inject_str($word));
		$arr = explode(' ',$word_str);
		if(count($arr)>1){
			for($i=0;$i<count($arr);$i++){
				if(trim($arr[$i]) <> ''){
					$str .= " u.username like '%{$arr[$i]}%' and";
				}
			}
			$str = substr($str,0,-3);
			$sql_keyword = " and (".$str.")";

		}else{
			$sql_keyword = " and u.username like '%{$word_str}%'";
		}
		$sql_do = " {$tpf}users u,{$tpf}groups g where u.gid=g.gid {$sql_keyword}";

		$rs = $db->fetch_one_array("select count(*) as total_num from {$sql_do}");
		$total_num = $rs['total_num'];
		$start_num = ($pg-1) * $perpage;

		$q = $db->query("select userid,username,email,reg_time,is_locked,credit,reg_ip,g.gid,g.group_type,g.group_name from {$sql_do} limit $start_num,$perpage");
		$users = array();
		while($rs = $db->fetch_array($q)){
			$rs['reg_time_s'] = date("Y-m-d",$rs['reg_time']);
			$rs['reg_time'] = date("Y-m-d H:i:s",$rs['reg_time']);
			$rs['is_admin'] = ($rs['gid']==1) ? 1 : 0;
			$rs['status_text'] = $rs['is_locked'] ? '<span class="txtred">'.__('user_open').'</span>' : __('user_locked');
			$rs['a_user_edit'] = urr(ADMINCP,"item=users&menu=user&action=user_edit&uid={$rs['userid']}");
			$rs['a_user_lock'] = urr(ADMINCP,"item=users&menu=user&action=user_lock&uid={$rs['userid']}");
			$rs['a_user_delete'] = urr(ADMINCP,"item=users&menu=user&action=user_delete&uid={$rs['userid']}");
			$rs['a_user_viewfile'] = urr(ADMINCP,"item=files&action=index&view=user&uid={$rs['userid']}");
			$users[] = $rs;
		}
		$db->free($q);
		unset($rs);


		$q = $db->query("select gid,group_name,group_type from {$tpf}groups where gid<>1 order by gid asc");
		$mini_groups = array();
		while($rs = $db->fetch_array($q)){
			$rs['txtcolor'] = $rs['group_type'] ? 'txtblue' : '';
			$mini_groups[] = $rs;
		}
		$db->free($q);
		unset($rs);

		$page_nav = multi($total_num, $perpage, $pg, urr(ADMINCP,"item=users&menu=user&action=search&word=".rawurlencode($word).""));

		require_once template_echo($item,$admin_tpl_dir,'',1);
		break;
	case 'import_user':
		if($task=='import_user'){
			form_auth(gpc('formhash','P',''),formhash());
			$file = $_FILES['filedata'];

			$file_extension = get_extension($file['name']);

			if(!in_array($file_extension,array('xls','xlsx'))){
				$error = true;
				$sysmsg[] = '请选择Excel文件';
			}

			$file_name = md5(uniqid().$timestamp.$pd_uid).'.'.$file_extension;
			$dest_file = PHPDISK_ROOT.'system/'.$file_name;

			if(!$error){
				if(upload_file($file['tmp_name'],$dest_file)){
					require_once PHPDISK_ROOT.'includes/Classes/PHPExcel.php';
					$PHPExcel = new PHPExcel();
					$PHPExcel = PHPExcel_IOFactory::load('./system/'.$file_name);
					$sheet = $PHPExcel->getSheet(0); // 读取第一個工作表
					$highestRow = $sheet->getHighestRow(); // 取得总行数
					$highestColumm = $sheet->getHighestColumn(); // 取得总列数
					$str = $str2 = '';
					for ($row = 2; $row <= $highestRow; $row++){//行数是以第2行开始
						if($sheet->getCell('A'.$row)->getValue()){
							$username = trim($sheet->getCell('A'.$row)->getValue());
							$pwd_src = trim($sheet->getCell('B'.$row)->getValue());
							$password = md5($pwd_src);
							$group_name = trim($sheet->getCell('C'.$row)->getValue());
							$depart_name = trim($sheet->getCell('D'.$row)->getValue());
							$user_store_space = trim($sheet->getCell('E'.$row)->getValue());
							$user_file_types = trim($sheet->getCell('F'.$row)->getValue());

							$num = @$db->result_first("select count(*) from {$tpf}users where username='$username'");
							if(!$num){
								$gid = (int)@$db->result_first("select gid from {$tpf}groups where group_name='".$db->escape($group_name)."'");
								$depart_id = (int)@$db->result_first("select depart_id from {$tpf}departs where depart_name='".$db->escape($depart_name)."'");
								$ins = array(
								'username' => $username,
								'password' => $password,
								'email' => $username.'@import.user',
								'gid' => $gid,
								'depart_id' => $depart_id,
								'user_store_space' => $user_store_space,
								'user_file_types' => $user_file_types,
								'reg_time' => $timestamp,
								'reg_ip' => $onlineip,
								);

								$db->query("insert into {$tpf}users set ".$db->sql_array($ins).";");
								$rs = $db->fetch_one_array("select count(*) as total from {$tpf}users ");
								if($rs['total']){
									$stats['users_count'] = (int)$rs['total'];
									stats_cache($stats);
								}
								unset($rs);

							}else{
								$sysmsg[] = "用户：$username 已存在,无法重复导入";
							}
						}
					}
					@unlink($dest_file);

					if(count($sysmsg)){
						redirect(urr(ADMINCP,"item=users&menu=user&action=import_user"),$sysmsg);
					}else{
						redirect(urr(ADMINCP,"item=users&menu=user&action=import_user"),'新用户导入成功');
					}
				}
			}else{
				redirect('back',$sysmsg);
			}
			@unlink($file['tmp_name']);
		}else{
			require_once template_echo($item,$admin_tpl_dir,'',1);
		}
		break;
	case 'user_lock':
		if($settings['online_demo']){
			$error = true;
			$sysmsg[] = __('online_demo_deny');
		}
		if(!$error){
			$uid = (int)gpc('uid','G',0);
			$rs = $db->fetch_one_array("select is_locked from {$tpf}users where userid='$uid'");
			$is_locked = $rs['is_locked'] ? 0 : 1;
			unset($rs);
			$db->query_unbuffered("update {$tpf}users set is_locked='$is_locked' where userid='$uid' limit 1");
			redirect($_SERVER['HTTP_REFERER'],'',0);
		}else{
			redirect('back',$sysmsg);
		}
		break;

	case 'user_delete':
		if($settings['online_demo']){
			$error = true;
			$sysmsg[] = __('online_demo_deny');
		}
		$uid = (int)gpc('uid','G',0);
		$num = @$db->result_first("select count(*) from {$tpf}files where userid='$uid'");
		if($num){
			$error = true;
			$sysmsg[] = '此用户空间中存在文件，请先删除用户所有文件，再进行用户帐号删除！';
		}
		if(!$error){
			$db->query_unbuffered("delete from {$tpf}folders where userid='$uid'");
			$db->query_unbuffered("delete from {$tpf}users where userid='$uid'");
			$db->query_unbuffered("update {$tpf}files set is_del=1 where userid='$uid'");
			$db->query_unbuffered("delete from {$tpf}buddys where userid='$uid' or touserid='$uid'");
			$db->query_unbuffered("delete from {$tpf}messages where userid='$uid' or touserid='$uid'");
			
			$my = get_profile($uid);
			if(display_plugin('phpdisk_sso','open_phpdisk_sso_plugin',$settings['open_sso'],0)){
				echo sso_del_user($my[username]);
			}
			
			if(display_plugin('api','open_uc_plugin',$settings['connect_uc'],0)){
				$username = @$db->result_first("select username from {$tpf}users where userid='$uid' limit 1");
				if($settings['connect_uc_type']=='phpwind'){
					$arr = uc_user_get($username,1);
					uc_user_delete($arr['uid']);
				}else{
					$result = uc_user_delete($username);
					if(!$result){
						$sysmsg[] = "UC:".__('delete_user_error');
					}
				}
			}
			$sysmsg[] = __('delete_user_success');
			redirect(urr(ADMINCP,"item=users&menu=user&action=index"),$sysmsg);
		}else{
			redirect('back',$sysmsg);
		}
		break;

	case 'add_user':

		if($task =='add_user'){
			create_new_user(1);
		}else{
			require_once template_echo($item,$admin_tpl_dir,'',1);
		}
		break;

	case 'user_edit':
		$uid = (int)gpc('uid','GP',0);

		if($task =='user_edit'){
			form_auth(gpc('formhash','P',''),formhash());

			$password = trim(gpc('password','P',''));
			$email = trim(gpc('email','P',''));
			$is_locked = (int)gpc('is_locked','P',0);
			$is_activated = (int)gpc('is_activated','P',0);
			$gid = (int)gpc('gid','P',0);
			$depart_id = (int)gpc('depart_id','P',0);
			$user_file_types = trim(gpc('user_file_types','P',''));
			$user_store_space = str_replace('，',',',trim(gpc('user_store_space','P','')));

			if($settings['online_demo']){
				$error = true;
				$sysmsg[] = __('online_demo_deny');
			}
			if($password){
				if(checklength($password,6,20)){
					$error = true;
					$sysmsg[] = __('invalid_password');
				}else{
					$md5_pwd = md5($password);
				}
			}else{
				$rs = $db->fetch_one_array("select password from {$tpf}users where userid='$uid'");
				$md5_pwd = $rs['password'];
			}
			if($gid>1){
				$rs = $db->fetch_one_array("select count(*) as total from {$tpf}users where gid=1 and userid<>'$uid'");
				if(!$rs['total']){
					$error = true;
					$sysmsg[] = __('only_one_admin');
				}
				unset($rs);
			}
			if($settings['reg_use_email']){
				if(!checkemail($email)){
					$error = true;
					$sysmsg[] = __('invalid_email');
				}else{
					$rs = $db->fetch_one_array("select email from {$tpf}users where email='$email' and userid<>'$uid'");
					if($rs){
						if(strcasecmp($email,$rs['email']) ==0){
							$error = true;
							$sysmsg[] = __('email_already_exists');
						}
						unset($rs);
					}
				}
			}
			$user_store_space = $user_store_space ? $user_store_space : 0;
			if($user_file_types && substr($user_file_types,strlen($user_file_types)-1,1) ==','){
				$user_file_types = substr($user_file_types,0,-1);
			}
			if(display_plugin('api','open_uc_plugin',$settings['connect_uc'],0)){
				$old_pwd = $db->result_first("select password from {$tpf}users where userid='$uid'");
				if($settings['connect_uc_type']=='phpwind'){
					uc_user_edit($pd_uid, $pd_username, $pd_username, $password, $email);
				}else{
					$ucresult = uc_user_edit($username, $old_pwd, $password,$email,1);
					if($ucresult < 0) {
						$error = true;
						$sysmsg[] = 'UC:'.__('update_password_error');
					}
				}
			}

			if(!$error){
				$my = get_profile($uid);
				$ins = array(
				'password' => $md5_pwd,
				'email' => $email,
				'is_locked' => $is_locked,
				'gid' => $gid,
				'depart_id' => $depart_id,
				'is_activated' => $is_activated,
				'user_file_types' => $user_file_types,
				'user_store_space' => $user_store_space,
				);
				$db->query_unbuffered("update {$tpf}users set ".$db->sql_array($ins)." where userid='$uid';");
				
				if(display_plugin('phpdisk_sso','open_phpdisk_sso_plugin',$settings['open_sso'],0)){
					echo sso_edit_user($my[username],($password ? $password : $my[password]),$my[email],$my[gid]);
				}
				$sysmsg[] = __('user_edit_success');
				redirect(urr(ADMINCP,"item=users&menu=user&action=index"),$sysmsg);

			}else{
				redirect('back',$sysmsg);
			}

		}else{

			$user = $db->fetch_one_array("select * from {$tpf}users where userid='$uid' limit 1");
			if($user){
				$user['user_store_space'] = $user['user_store_space'] ? $user['user_store_space'] : 0;
				require_once template_echo($item,$admin_tpl_dir,'',1);
			}else{
				exit('Error Operation!');
			}
		}
		break;
	case 'adminlogout':
		$db->query_unbuffered("update {$tpf}adminsession set hashcode='' where userid='$pd_uid'");
		$sysmsg[] = __('system_logout_success');
		redirect('javascript:self.parent.close();',$sysmsg);
		break;

	default:
		redirect(urr(ADMINCP,"item=users&menu=user&action=index"),'',0);
}

?>