<?php
define('IN_ECS', true);

require(dirname(__FILE__) . '/includes/init.php');

include_once (ROOT_PATH . '/includes/cls_image.php');
$image = new cls_image($_CFG['bgcolor']);

$exc = new exchange($ecs->table('users'), $db, 'user_id', 'user_name');

/*------------------------------------------------------ */
//-- 用户帐号列表
/*------------------------------------------------------ */

if ($_REQUEST['act'] == 'list')
{
    /* 检查权限 */
    admin_priv('users_manage');
    
    $smarty->assign('ur_here',      $_LANG['03_users_list']);
    $smarty->assign('action_link',  array('text' => '新增客戶', 'href'=>'users.php?act=add'));
    
    $user_list = user_list();

    $smarty->assign('user_list',    $user_list['user_list']);
    $smarty->assign('filter',       $user_list['filter']);
    $smarty->assign('record_count', $user_list['record_count']);
    $smarty->assign('page_count',   $user_list['page_count']);
    $smarty->assign('full_page',    1);
    $smarty->assign('sort_user_id', '<img src="images/sort_desc.gif">');

    assign_query_info();
    $smarty->display('users_list.htm');
}

/*------------------------------------------------------ */
//-- ajax返回用户列表
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'query')
{
    $user_list = user_list();

    $smarty->assign('user_list',    $user_list['user_list']);
    $smarty->assign('filter',       $user_list['filter']);
    $smarty->assign('record_count', $user_list['record_count']);
    $smarty->assign('page_count',   $user_list['page_count']);

    $sort_flag  = sort_flag($user_list['filter']);
    $smarty->assign($sort_flag['tag'], $sort_flag['img']);

    make_json_result($smarty->fetch('users_list.htm'), '', array('filter' => $user_list['filter'], 'page_count' => $user_list['page_count']));
}

/*------------------------------------------------------ */
//-- 添加会员帐号
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'add')
{
    /* 检查权限 */
    admin_priv('users_manage');

    /* 取出注册扩展字段 */
    $smarty->assign('ur_here',          $_LANG['04_users_add']);
    $smarty->assign('action_link',      array('text' => $_LANG['03_users_list'], 'href'=>'users.php?act=list'));
    $smarty->assign('form_action',      'insert');
    $smarty->assign('user',             $user);

    assign_query_info();
    $smarty->display('user_info.htm');
}

/*------------------------------------------------------ */
//-- 添加会员帐号
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'insert')
{
    /* 检查权限 */
//    admin_priv('users_manage');
    $username = empty($_POST['username']) ? '' : trim($_POST['username']);
    $password = empty($_POST['password']) ? '' : trim($_POST['password']);
	$status = $_POST['status'];

    $users = init_users();

    if (!$users->add_user($username, $password))
    {
        /* 插入会员数据失败 */
        if ($users->error == ERR_INVALID_USERNAME)
        {
            $msg = $_LANG['username_invalid'];
        }
        elseif ($users->error == ERR_USERNAME_NOT_ALLOW)
        {
            $msg = $_LANG['username_not_allow'];
        }
        elseif ($users->error == ERR_USERNAME_EXISTS)
        {
            $msg = $_LANG['username_exists'];
        }
        else
        {
            //die('Error:'.$users->error_msg());
        }
        sys_msg($msg, 1);
    }

    /* 更新会员的其它信息 */
    $other =  array();
    $other['name'] = $_POST['name'];
    $other['tel'] = $_POST['tel'];
    $other['email'] = $_POST['email'];
    $other['address'] = $_POST['address'];
    $other['reg_time'] = local_strtotime(local_date('Y-m-d H:i:s'));
    $other['last_time']   = date('Y-m-d H:i:s');
    $other['note'] = $_POST['note'];
    $other['status'] = 0;
    $other['enable'] = 0;

    $db->autoExecute($ecs->table('users'), $other, 'UPDATE', "user_name = '$username'");

	$uid=$db->getOne("SELECT user_id FROM ".$ecs->table('users')." WHERE user_name='$username'");
	/*建立web*/
	$sql="INSERT INTO ".$ecs->table('hs_web')." (hs_id,cname,tel,email,address) VALUES ('$uid','$_POST[name]','$_POST[tel]','$_POST[email]','$_POST[address]') ";
	$db->query($sql);
	
    /* 记录管理员操作 */
    admin_log($_POST['username'], 'add', 'users');

    /* 提示信息 */
    $link[] = array('text' => $_LANG['go_back'], 'href'=>'users.php?act=list');
    sys_msg(sprintf($_LANG['add_success'], htmlspecialchars(stripslashes($_POST['username']))), 0, $link);

}

/*------------------------------------------------------ */
//-- 编辑用户帐号
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'edit')
{
    /* 检查权限 */
//    admin_priv('users_manage');

    $sql = "SELECT * ".
        " FROM " .$ecs->table('users'). "  WHERE user_id='$_GET[id]'";

    $row = $db->GetRow($sql);

    if ($row)
    {
		$user=$row;
    }
    else
    {
          $link[] = array('text' => $_LANG['go_back'], 'href'=>'users.php?act=list');
          sys_msg($_LANG['username_invalid'], 0, $links);
     }

    assign_query_info();
    $smarty->assign('ur_here',          $_LANG['users_edit']);
    $smarty->assign('action_link',      array('text' => $_LANG['03_users_list'], 'href'=>'users.php?act=list&' . list_link_postfix()));
    $smarty->assign('user',             $user);
    $smarty->assign('form_action',      'update');
    $smarty->display('user_info.htm');
}

/*------------------------------------------------------ */
//-- 更新用户帐号
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'update')
{
    /* 检查权限 */
//    admin_priv('users_manage');
    $username = empty($_POST['username']) ? '' : trim($_POST['username']);
    $password = empty($_POST['password']) ? '' : trim($_POST['password']);
	$user_id 	= $_POST['id'];
	$status 	= $_POST['status'];
	$note 		= $_POST['note'];
	$enable 	= $_POST['enable'];

    $users  = init_users();

    if (!$users->edit_user(array('username'=>$username, 'password'=>$password,'status'=>$status), 1))
    {
        if ($users->error == ERR_MOBILE_EXISTS)
        {
            $msg = $_LANG['mobile_exists'];
        }
        else
        {
            $msg = $_LANG['edit_user_failed'];
        }
        sys_msg($msg, 1);
    }
    
    if(!empty($password))
    {
			$sql="UPDATE ".$ecs->table('users'). "SET `ec_salt`='0' WHERE user_name= '".$username."'";
			$db->query($sql);
	}

    /* 更新会员的其它信息 */
    $other =  array();
    $other['name'] = $_POST['name'];
    $other['tel'] = $_POST['tel'];
    $other['email'] = $_POST['email'];
    $other['address'] = $_POST['address'];
    $other['last_time']   = date('Y-m-d H:i:s');
    $other['note'] = $_POST['note'];
    $other['status'] = $_POST['status'];
    $other['enable'] = 0;

    $db->autoExecute($ecs->table('users'), $other, 'UPDATE', "user_name = '$username'");

    /* 记录管理员操作 */
    admin_log($username, 'edit', 'users');

    /* 提示信息 */
    $links[0]['text']    = $_LANG['goto_list'];
    $links[0]['href']    = 'users.php?act=list&' . list_link_postfix();
    $links[1]['text']    = $_LANG['go_back'];
    $links[1]['href']    = 'javascript:history.back()';

    sys_msg($_LANG['update_success'], 0, $links);

}

/*------------------------------------------------------ */
//-- 添加会员帐号
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'user_ad')
{
    /* 检查权限 */
//    admin_priv('users_manage');
    /* 取出注册扩展字段 */
	$sql="SELECT * FROM ".$ecs->table('portal')." WHERE 1 ";
	$portals=$db->getAll($sql);
	$i=0;
	for($i;$i<count($portals);$i++){
		$row=$db->getRow("SELECT block,dstamp FROM ".$ecs->table('user_ad')." WHERE pt_id=".$portals[$i]['id']." AND user_id=".$_REQUEST['id']);
		$portals[$i]['block']=$row['block'];
		$portals[$i]['dstamp']=$row['dstamp'];		
	}

    $smarty->assign('ur_here',          '廣告管理');
    $smarty->assign('action_link',      array('text' => $_LANG['03_users_list'], 'href'=>'users.php?act=list'));
    $smarty->assign('form_action',      'ad_update');
    $smarty->assign('id',          $_REQUEST['id']);
    $smarty->assign('portals',             $portals);

//	$sql="SELECT * FROM ".$ecs->table('users')." WHERE user_id= ".$_REQUEST['id'];
//	$user=$db->getRow($sql);
//	$have_ad=$db->getOne("SELECT count(*) FROM ".$ecs->table('user_ad')."WHERE user_id=".$_REQUEST['id']);
//	if($have_ad){
//		$user['expire']=date('Y-m-d',$user['expire']);		
//	}else{
//		$user['expire']=date('Y-m-d');
//	}

//    $smarty->assign('user',$user);

	$sql="SELECT * FROM ".$ecs->table('hs_web')." WHERE hs_id= ".$_REQUEST['id'];
	$web=$db->getRow($sql);
    $smarty->assign('web',$web);


    assign_query_info();
    $smarty->display('user_ad.htm');
}

/*------------------------------------------------------ */
//-- 添加会员帐号
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'ad_update')
{
    /* 检查权限 */
//    admin_priv('users_manage');
	if(isset($_FILES['image1']) && $_FILES['image1']['tmp_name'] != '')
	{
		$image1 = $image->upload_image($_FILES['image1']);
		if($image1 === false)
		{
			sys_msg($image->error_msg(), 1, array(), false);
		}
	}
	if(isset($_FILES['image2']) && $_FILES['image2']['tmp_name'] != '')
	{
		$image2 = $image->upload_image($_FILES['image2']);
		if($image2 === false)
		{
			sys_msg($image->error_msg(), 1, array(), false);
		}
	}
	if(isset($_FILES['image3']) && $_FILES['image3']['tmp_name'] != '')
	{
		$image3 = $image->upload_image($_FILES['image3']);
		if($image3 === false)
		{
			sys_msg($image->error_msg(), 1, array(), false);
		}
	}
	if(isset($_FILES['image4']) && $_FILES['image4']['tmp_name'] != '')
	{
		$image4 = $image->upload_image($_FILES['image4']);
		if($image4 === false)
		{
			sys_msg($image->error_msg(), 1, array(), false);
		}
	}

			$sql = "update " . $ecs->table('hs_web') . " set  ";
			$sql .= " ad_text2 = '$_REQUEST[ad_text2]' ";

			if(@$image1 != '')
			{
				$sql .= " ,image1 = '$image1' ";
			}
			if(@$image2 != '')
			{
				$sql .= " ,image2 = '$image2' ";
			}
			if(@$image3 != '')
			{
				$sql .= " ,image3 = '$image3' ";
			}
			if(@$image4 != '')
			{
				$sql .= " ,image4 = '$image4' ";
			}
			$sql .= " where hs_id = '" .$_POST['id'] . "'";
			$db->query($sql);			


	$sql="DELETE FROM ".$ecs->table('user_ad')." WHERE user_id=".$_POST['id'];
	$db->query($sql);

	if(is_array($_POST['ad'])){
	foreach($_POST['ad'] as $key => $vals){
		$block=0;
		foreach($vals as $val){
			$block+=$val;
		}
		$sql="INSERT INTO ".$ecs->table('user_ad')."(user_id,pt_id,block,dstamp) VALUES ('$_POST[id]','$key','$block','".$_POST['expire'][$key]."')";
		$db->query($sql);
	}		
	}

    /* 记录管理员操作 */
    admin_log($_POST['id'], 'ad_update', 'users');

    /* 提示信息 */
    $link[] = array('text' => $_LANG['go_back'], 'href'=>'users.php?act=user_ad&id='.$_POST['id']);
    sys_msg('設定完成', 0, $link);

}

/*------------------------------------------------------ */
//-- 删除会员帐号
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'remove')
{
    /* 检查权限 */
    admin_priv('users_drop');

    $sql = "SELECT * FROM " . $ecs->table('users') . " WHERE user_id = '" . $_GET['id'] . "'";
    $username = $db->getOne($sql);

    $sql = "SELECT domain,cf_iden FROM " . $ecs->table('hs_web') . " WHERE hs_id = '" . $_GET['id'] . "'";
    $web = $db->getRow($sql);

    /* 通过插件来删除用户 */
	$sql=" DELETE FROM ".$ecs->table('users') . " WHERE user_id = '" . $_GET['id'] . "'";
	$db->query($sql);

	$sql=" DELETE FROM ".$ecs->table('hs_web') . " WHERE hs_id = '" . $_GET['id'] . "'";
	$db->query($sql);

	$sql=" DELETE FROM ".$ecs->table('hs_news') . " WHERE hs_id = '" . $_GET['id'] . "'";
	$db->query($sql);

	$sql=" DELETE FROM ".$ecs->table('hs_room') . " WHERE hs_id = '" . $_GET['id'] . "'";
	$db->query($sql);

	$sql=" DELETE FROM ".$ecs->table('hs_gallery') . " WHERE hs_id = '" . $_GET['id'] . "'";
	$db->query($sql);

	if(strlen($web['domain'])){
		if(preg_match("/".$_CFG['cf_domain']."$/",$web['domain'])){ 
			include_once(ROOT_PATH . 'admin/includes/cls_cloudflare.php');
			$cf_obj = new cloudflare;
			$cf_obj->del_domain(trim($web['cf_iden']));
		}	
	}


    /* 记录管理员操作 */
    admin_log(addslashes($username), 'remove', 'users');

    /* 提示信息 */
    $link[] = array('text' => $_LANG['go_back'], 'href'=>'users.php?act=list');
    sys_msg(sprintf($_LANG['remove_success'], $username), 0, $link);
}

/*------------------------------------------------------ */
//-- 脱离推荐关系
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'remove_parent')
{
    /* 检查权限 */
    admin_priv('users_manage');

    $sql = "UPDATE " . $ecs->table('users') . " SET parent_id = 0 WHERE user_id = '" . $_GET['id'] . "'";
    $db->query($sql);

    /* 记录管理员操作 */
    $sql = "SELECT user_name FROM " . $ecs->table('users') . " WHERE user_id = '" . $_GET['id'] . "'";
    $username = $db->getOne($sql);
    admin_log(addslashes($username), 'edit', 'users');

    /* 提示信息 */
    $link[] = array('text' => $_LANG['go_back'], 'href'=>'users.php?act=list');
    sys_msg(sprintf($_LANG['update_success'], $username), 0, $link);
}

/*------------------------------------------------------ */
//-- 修改上架状态
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'toggle_status')
{
//    check_authz_json('room_manage');

    $id       = intval($_POST['id']);
    $val      = intval($_POST['val']);

    if ($exc->edit("status = '$val'", $id))
    {
        clear_cache_files();
        make_json_result($val);
    }
}


/**
 *  返回用户列表数据
 *
 * @access  public
 * @param
 *
 * @return void
 */
function user_list()
{
    $result = get_filter();
    
    if ($result === false)
    {
        /* 过滤条件 */
        $filter['keywords'] = empty($_REQUEST['keywords']) ? '' : trim($_REQUEST['keywords']);
        if (isset($_REQUEST['is_ajax']) && $_REQUEST['is_ajax'] == 1)
        {
            $filter['keywords'] = json_str_iconv($filter['keywords']);
        }
        $filter['status'] = !strlen($_REQUEST['status']) ? -1 : trim($_REQUEST['status']);		
        $filter['sort_by']    = empty($_REQUEST['sort_by'])    ? 'user_id' : trim($_REQUEST['sort_by']);
        $filter['sort_order'] = empty($_REQUEST['sort_order']) ? 'DESC'     : trim($_REQUEST['sort_order']);

        $ex_where = ' WHERE 1 ';

        if ($filter['keywords'])
        {
        	/* keyword判斷行動電話或帳號 */
            $ex_where .= " AND (user_name LIKE '%" . mysql_like_quote($filter['keywords']) . "%' or name LIKE '%" . mysql_like_quote($filter['keywords']) . "%' or tel like  '%" . mysql_like_quote($filter['keywords']) . "%' )";
        }

		if ($filter['status']>=0)
        {
            $ex_where .=" AND status = '$filter[status]' ";
        }
		
		$filter['record_count'] = $GLOBALS['db']->getOne("SELECT COUNT(*) FROM " . $GLOBALS['ecs']->table('users') . $ex_where);

        /* 分页大小 */
        $filter = page_and_size($filter);

//互亿无线代码
        $sql = "SELECT * ".
                " FROM " . $GLOBALS['ecs']->table('users') .
				$ex_where .
                " ORDER by " . $filter['sort_by'] . ' ' . $filter['sort_order'] .
                " LIMIT " . $filter['start'] . ',' . $filter['page_size'];
//互亿无线代码

        $filter['keywords'] = stripslashes($filter['keywords']);
        set_filter($filter, $sql);
    }
    else
    {
        $sql    = $result['sql'];
        $filter = $result['filter'];
    }

    $user_list = $GLOBALS['db']->getAll($sql);

    $count = count($user_list);
    for ($i=0; $i<$count; $i++)
    {
        $user_list[$i]['reg_time'] = local_date($GLOBALS['_CFG']['date_format'], $user_list[$i]['reg_time']);
        $user_list[$i]['web'] = $GLOBALS['db']->getOne("SELECT domain FROM ".$GLOBALS['ecs']->table('hs_web')." WHERE hs_id=".$user_list[$i]['user_id']);
	}

    $arr = array('user_list' => $user_list, 'filter' => $filter,
        'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);

    return $arr;
}

?>