<?php
// +----------------------------------------------------------------------
// | Quotes [未来可期]
// +----------------------------------------------------------------------
// +----------------------------------------------------------------------
// | Author: 自助建站系统 https://www.kancloud.cn/btwcms-com/btwcms/2265967 作者QQ：1617643
// +----------------------------------------------------------------------
// | Date: 2020年2月5日
// +----------------------------------------------------------------------


include '../app/common.php';


$act = isset($_GET['act']) ? daddslashes($_GET['act']) : null;

@header('Content-Type: application/json; charset=UTF-8');

if (!$userrow['uid']) {
    exit('{"code":-1,"msg":"登录信息失效"}');
}

switch ($act) {

    /**
     * author: 1617643@qq.com
     * time:2020/05/10 23:23
     * description:TODO 获取登陆记录填充到chart图
     */
    case 'getLogRecord':
        $list=$DB->query("SELECT substring(date, 1, 10) as date, COUNT(0) as count FROM `wcms_log`  WHERE `uid`={$userrow['uid']} GROUP BY substring(date, 1, 10)")->fetchAll();
        $result = array("code" => 1, "msg" => "获取成功","data"=>$list);
        exit(json_encode($result));
        break;


    /**
     * author: 1617643@qq.com
     * time:2020/2/12 23:23
     * description:TODO 保存用户资料
     */
    case 'saveMyInfo':
        $nickname = trim(strip_tags(daddslashes($_POST['nickname']))); //用户昵称
        $email = trim(strip_tags(daddslashes($_POST['email'])));//用户邮箱
        $phone = trim(strip_tags(daddslashes($_POST['phone'])));//用户手机号
        //对用户输入的信息进行判断
        if (!$email || !$nickname || !$phone) {
            exit('{"code":-1,"msg":"请补充完整"}');
        }
        if (!preg_match('/^[\x7f-\xff]+$/', $nickname)) {
            exit('{"code":-1,"msg":"昵称只能为汉字！"}');
        }
        //对用户名敏感词检测
        if (strlen($phone) != 11 && strpos($phone, '@') == false) {
            exit('{"code":-1,"msg":"请填写正确的手机账号！"}');
        }
        if (!preg_match('/^[A-z0-9._-]+@[A-z0-9._-]+\.[A-z0-9._-]+$/', $email)) {
            exit('{"code":-1,"msg":"邮箱格式不正确"}');
        }
        $exitphone = $DB->query("SELECT * FROM wcms_user WHERE phone='{$phone}' and uid!={$userrow['uid']} limit 1")->fetch();
        $exitemail = $DB->query("SELECT * FROM wcms_user WHERE email='{$email}' and uid!={$userrow['uid']} limit 1")->fetch();
        if ($exitphone) {
            exit('{"code":-1,"msg":"手机号:' . $phone . '已存在,请重新设置"}');
        }
        if ($exitemail) {
            exit('{"code":-1,"msg":"邮箱:' . $email . '已存在,请重新设置"}');
        }
        //没有修改的情况
        if ($nickname == $userrow['nickname'] && $email == $userrow['email'] && $phone == $userrow['phone']) {
            exit('{"code":1,"msg":"修改成功"}');
        }
        $sql = $DB->exec("UPDATE `wcms_user` SET `phone` ='{$phone}',`email` ='{$email}',`nickname` ='{$nickname}' WHERE `uid`='{$userrow['uid']}'");
        if ($sql) {
            exit('{"code":1,"msg":"修改成功"}');
        } else {
            exit('{"code":-1,"msg":"修改失败,请稍后再试"}');
        }
        break;

    /**
     * author: 1617643@qq.com
     * time:2020/2/12 23:23
     * description:TODO 用户邮箱设置
     */
    case 'emailSet':
        $email = trim(strip_tags(daddslashes($_POST['email'])));
        if (!preg_match('/^[A-z0-9._-]+@[A-z0-9._-]+\.[A-z0-9._-]+$/', $email)) {
            exit('{"code":-1,"msg":"邮箱格式不正确"}');
        }
        $email = strtolower($email);
        $exitemail = $DB->query("SELECT * FROM m_user WHERE email='{$email}'  and id!='{$userrow['id']}' limit 1")->fetch();
        if ($exitemail) {
            exit('{"code":-1,"msg":"邮箱已存在,请重新设置"}');
        }
        if ($email == $userrow['email']) {
            exit('{"code":1,"msg":"修改成功"}');
        }
        //正常修改
        $sql = $DB->exec("UPDATE `m_user` SET `email` ='{$email}' WHERE `id`='{$userrow['id']}'");
        if ($sql) {
            saveLog($userrow['uid'], "修改邮箱");
            exit('{"code":1,"msg":"修改成功"}');
        } else {
            exit('{"code":-1,"msg":"修改失败啦"}');
        }

        break;

    /**
     * author: 1617643@qq.com
     * time:2020/2/12 23:23
     * description:TODO 用户密码设置
     */
    case 'passSet':
        $newpassword = trim(strip_tags(daddslashes($_POST['newpassword'])));
        $password = trim(strip_tags(daddslashes($_POST['password'])));
        //对用户输入的信息进行判断
        if (!$newpassword || !$password) {
            $result = array("code" => -1, "msg" => "所有项不得为空,请补充完整");
            exit(json_encode($result));
        } elseif (strlen($newpassword) < 6) {
            $result = array("code" => -1, "msg" => "新密码不能低于6位");
            exit(json_encode($result));
        }
        $password = md5($password); //原密码
        $userrow = $DB->query("SELECT * FROM wcms_user WHERE password='{$password}' limit 1")->fetch();
        if (!$userrow) {
            $result = array("code" => -1, "msg" => "原密码输入错误");
            exit(json_encode($result));
        }

        $newpassword = md5($newpassword); //原密码

        //没有修改的情况下
        if ($newpassword == $password) {
            $result = array("code" => 1, "msg" => "修改成功");
            exit(json_encode($result));
        }

        //正常修改
        $sql = $DB->exec("UPDATE `wcms_user` SET `password` ='{$newpassword}' WHERE `uid`='{$userrow['uid']}'");
        if ($sql) {
            saveLog($userrow['uid'], "修改登录密码");
            $result = array("code" => 1, "msg" => "修改成功");
            exit(json_encode($result));
        } else {
            $result = array("code" => -1, "msg" => "修改失败啦");
            exit(json_encode($result));
        }


        break;

    /**
     * author: 1617643@qq.com
     * time:2020/2/12 23:23
     * description:TODO 用户购买会员
     */
    case 'buyMember':
        $mid = trim(strip_tags(daddslashes($_POST['mid'])));
        $rowMember = $DB->query("SELECT * FROM `wcms_member` WHERE mid='{$mid}' limit 1")->fetch();
        if (!$rowMember) {
            $result = array("code" => -1, "msg" => "会员分类不存在");
            exit(json_encode($result));
        } else {
            if ($userrow['mcode'] > $rowMember['mcode'] || $userrow['mcode'] == $rowMember['mcode']) {
                $result = array("code" => -1, "msg" => "您已拥有此身份");
                exit(json_encode($result));
            }
            //判断现在身份,是否补差价
            $rowNowMember = $DB->query("SELECT * FROM `wcms_member` WHERE mcode='{$userrow['mcode']}' limit 1")->fetch();
            //用户现在会员身份的价格
            //购买会员的价格=要购买的会员的价格-用户现在身份的价格
            $rowMember['mprice'] = $rowMember['mprice'] - $rowNowMember['mprice'];
            //判断余额
            if ($userrow['money'] < $rowMember['mprice']) {
                $result = array("code" => -1, "msg" => "余额不足");
                exit(json_encode($result));
            } else {
                $userrow['money'] = $userrow['money'] - $rowMember['mprice'];
                $DB->exec("UPDATE `wcms_user` SET `money` ='{$userrow['money']}',`mcode`='{$rowMember['mcode']}' WHERE `uid`='{$userrow['uid']}'");
                $memName = $rowMember["mname"];
                saveLog($userrow['uid'], "升级身份-$memName ");
                $code = $rowMember['mcode'];
                $result = array("code" => 1, "msg" => "购买成功", "url" => "info.php");
                exit(json_encode($result));
            }
        }
        break;

    /**
     * author: 1617643@qq.com
     * time:2020/2/12 23:23
     * description:TODO 用户支付
     */
    case 'pay':
        $account = trim(strip_tags(daddslashes($_POST['account'])));
        $type = trim(strip_tags(daddslashes($_POST['type'])));
        $order_no = date("YmdHis") . rand(111, 999);
        if (!is_numeric($account)) {
            $result = array("code" => -1, "msg" => "提交参数错误");
            exit(json_encode($result));
        }
        if ($account > 1000 || $account < 1) {
            exit('{"code":-1,"msg":"充值金额不能小于1且不能超过1000！"}');
        }
        $name = '用户' . $userrow['uid'] . '-在线充值' . $account . '元余额';
        $sitename = $conf['web_name'];
        $sql = $DB->exec("INSERT INTO `wcms_order` (`order_no`,  `name`,`uid`, `money`, `date`, `type`, `status`)VALUES ('{$order_no}', '{$name}', '{$userrow['uid']}',  '{$account}', '{$date}','{$type}', '0')");
        if ($sql) {
            exit('{"code":1,"msg":"提交订单成功！","url":"../pay/submit.php?type=' . $type . '&orderid=' . $order_no . '"}');
        } else {
            $result = array("code" => -1, "msg" => "提交订单失败");
            exit(json_encode($result));
        }


        break;

    /**
     * author: 1617643@qq.com
     * time:2020/2/12 23:23
     * description:TODO 用户搭建网站
     */
    case 'build':
        $pid = trim(strip_tags(daddslashes($_POST['pid'])));
        $serverId = trim(strip_tags(daddslashes($_POST['serverid'])));
        $rowProgram = $DB->query("SELECT * FROM `wcms_program` WHERE `pid`='{$pid}' limit 1")->fetch();//判断项目是否存在
        $rowServer = $DB->query("SELECT * FROM `wcms_server` WHERE `sid`='{$serverId}' limit 1")->fetch();//判断服务器是否存在

        if (!$rowProgram) {
            $result = array("code" => -1, "msg" => "项目不存在");
            exit(json_encode($result));
        }
        if (!$rowServer) {
            $result = array("code" => -1, "msg" => "服务器不存在");
            exit(json_encode($result));
        }
        if ($rowProgram['status'] != 1) {
            $result = array("code" => -1, "msg" => "该项目未上架");
            exit(json_encode($result));
        }
        $rowMemberConf = $DB->query("SELECT * FROM `wcms_member` WHERE `mcode`='{$userrow['mcode']}' limit 1")->fetch();//判断服务器是否存在
        if ($rowProgram['discount'] == 1) { //开启优惠
            $newPrice = $rowProgram['price'] * $rowMemberConf['mpercent']; //商品新价格 = 原价 * 会员折扣
        } else {
            $newPrice = $rowProgram['price'];
        }
        $userMoney = $userrow['money'];
        if ($userMoney < $newPrice) {
            $result = array("code" => -1, "msg" => "账户余额不足,余额: ￥ $userMoney ,项目价格:￥ $newPrice ");
            exit(json_encode($result));
        }
        $uid = $userrow['uid'];
        //生成默认域名
        $domainRound = getRandStr(); //域名前缀
        $defaultDomain = $rowServer['domain'];//服务器设置的泛绑定域名
        $usetime = $rowProgram['usetime']; //项目使用时间
        $endtime = (date('Y-m-d H:i:s', strtotime("+$usetime month")));  //过期时间 = 现在的时间 + 使用时间

        $result = \app\Site::build("http://" . $rowServer['api'], $rowServer['pass'], $domainRound, $defaultDomain, $rowServer['sitepath'], $rowProgram['phpversion'], $uid, $rowProgram['name'], $endtime);
        if ($result['code'] == 1) {
            $data = $result['data'];
            $userDomain = $domainRound . '.' . $defaultDomain;
            if ($rowProgram['isrewrite'] == 1) { //开启伪静态
                $sitePath = $userDomain;
                $reWriteData = $reWiteConfig[$rowProgram['rewrite']];
                //配置伪静态[win系统与linux系统有区别]
                if($GLOBALS['serverType'] == 0){
                    \app\Site::reWrite($rowServer['api'], $rowServer['pass'], $sitePath, $reWriteData); //linux系统
                }else{
                    \app\Site::SetSiteRewrite($rowServer['api'], $rowServer['pass'], $sitePath, $reWriteData); //win系统
                }

            }
            //mod 由于配置运行目录后导致无法初始化，因此 此处不再进行配置，修改为初始化完成后配置 2021.04.11 start
            //运行目录配置
            //\app\Site::SetSiteRunPath($rowServer['api'], $rowServer['pass'],$data['bid'],$rowProgram['site_path']);
            //mod 由于配置运行目录后导致无法初始化，因此 此处不再进行配置，修改为初始化完成后配置 2021.04.11 end
            $sql = $DB->exec("INSERT INTO `wcms_site` (`bid`,`uid`,`serverid`,`domain`,`userdomain`,`sqlname`,`sqlpass`,`code`,`addtime`,`endtime`,`status`,`isinstall`)VALUES('" . $data['bid'] . "', '" . $userrow['uid'] . "','" . $rowServer['sid'] . "','" . $userDomain . "', '','" . $data['sqlname'] . "','" . $data['sqlpass'] . "','" . $rowProgram['code'] . "','" . $date . "','" . $endtime . "',1,0)");
            $newMoney = $userrow['money'] - $newPrice; //减掉用户余额
            $sql = $DB->exec("UPDATE `wcms_user` SET `money` ='{$newMoney}' WHERE `uid`='{$userrow['uid']}'");
            $proName = $rowProgram["name"];
            saveLog($userrow['uid'], "购买项目-$proName ");
            //发送邮件提醒
            if ($userrow['email'] != null && ($conf['mail_pwd'] != null || $conf['sms_appkey'] != null)) {
                $sub = $conf['web_name'] . ' - 搭建网站提醒';
                $msg = emailWritting($conf['web_name'], "搭建网站", " 您成功搭建: $proName <br/>你的网站域名：$userDomain<br/>搭建时间为：$date");
                sendEmail($userrow['email'], $sub, $msg);
            }
            $result = array("code" => 1, "msg" => "购买成功", "url" => "mySite.php");
            exit(json_encode($result));
        } else {
            exit(json_encode($result));
        }
        break;


    /**
     * author: 1617643@qq.com
     * time:2020/2/12 23:23
     * description:TODO 获取单个网站信息
     */
    case 'getMyOneSite':
        $sid = trim(strip_tags(daddslashes($_POST['sid'])));
        $site = $DB->query("SELECT * FROM `wcms_site` WHERE `uid`='{$userrow['uid']}' and `sid`='{$sid}' limit 1")->fetch();
        $pro = $DB->query("SELECT * FROM `wcms_program` WHERE `code`='{$site['code']}'limit 1")->fetch();
        if ($site && $pro) {
            $result = array('code' => 1, 'site' => $site, 'pro' => $pro);
        } else {
            $result = array('code' => -1, 'msg' => '获取数据失败');
        }

        exit(json_encode($result));
        break;

    /**
     * author: 1617643@qq.com
     * time:2020/2/12 23:23
     * description:TODO 安装网站
     */
    case 'install':
        $sid = trim(strip_tags(daddslashes($_POST['sid'])));

        //执行安装
        $rowSite = $DB->query("SELECT * FROM `wcms_site` WHERE `uid`='{$userrow['uid']}' and `sid`='{$sid}' limit 1")->fetch();
        $sqlname = $rowSite['sqlname'];
        $sqlpass = $rowSite['sqlpass'];
        $rowProgram = $DB->query("SELECT * FROM `wcms_program` WHERE `code`='{$rowSite['code']}' limit 1")->fetch();//根据网站唯一程序code查询 项目的信息

        $username = "admin"; //网站用户名
        $password = "123456";//网站密码
        $result = \app\Site::install($rowSite['domain'], $rowProgram['path'], $rowProgram['install'], $sqlname, $sqlpass, $conf['site_key'], $username, $password);
        if ($result['code'] == 1) { //安装成功
            $DB->exec("UPDATE `wcms_site` SET `isinstall` ='1' WHERE `sid`='{$sid}'");
            //由于有些sql文件无法通过php导入数据库 ，此处可执行 直接导入数据库文件的命令[不通过php导入] 2021.04.11 start
            /**逻辑
             * 1.获取到网站的根目录 找到sql文件
             * 2.执行方法，导入该sql文件
             * 具体业务待完成
             */
            //或者将sql文件中不是句末的;去掉
            //由于有些sql文件无法通过php导入数据库 ，此处可执行 直接导入数据库文件的命令[不通过php导入] 2021.04.11 end

            //mod 由于配置运行目录后导致无法初始化，因此初始化完成后配置 2021.04.11 start
            //运行目录配置
            $rowServer = $DB->query("SELECT * FROM `wcms_server` WHERE `sid`='{$rowSite['serverid']}' limit 1")->fetch();
            $api = 'http://' . $rowServer['api'] . '';
            $pass = $rowServer['pass'];
            \app\Site::SetSiteRunPath($rowServer['api'], $rowServer['pass'],$rowSite['bid'],$rowProgram['site_path']);
            //mod 由于配置运行目录后导致无法初始化，，因此初始化完成后配置 2021.04.11 end

            $result = array("code" => 1, "msg" => "网站初始化成功", "url" => 'mySite.php');
        } else {
            //初始化失败了
            $result = array("code" => -1, "msg" => $result['msg']);
        }
        exit(json_encode($result));
        break;

    /**
     * author: 1617643@qq.com
     * time:2020/2/12 23:23
     * description:TODO 用户删除网站
     */
    case 'delSite':
        $sid = trim(strip_tags(daddslashes($_POST['sid'])));
        //判断当前站点是否在数据库中
        $rowSite = $DB->query("SELECT * FROM `wcms_site` WHERE `uid`='{$userrow['uid']}' and `sid`='{$sid}' limit 1")->fetch();
        if (!$rowSite) {
            $result = array("code" => -1, "msg" => "删除失败,当前项目不在数据库中");
            exit(json_encode($result));
        }
        //获得对应的服务器信息

        $rowServer = $DB->query("SELECT * FROM `wcms_server` WHERE `sid`='{$rowSite['serverid']}' limit 1")->fetch();
        $api = 'http://' . $rowServer['api'] . '';
        $pass = $rowServer['pass'];

        $delSite = \app\Site::delSite($api, $pass, $rowSite['bid'], $rowSite['domain']);//执行删除宝塔网站api  //删除路径  ftp  数据库

        if ($delSite['code'] == -1) {
            $result = array("code" => -1, "msg" => $delSite['msg']);
            exit(json_encode($result));
        } else {
            $DB->exec("DELETE FROM `wcms_site` WHERE `bid`='{$rowSite['bid']}'");
            $rowProgram = $DB->query("SELECT * FROM `wcms_program` WHERE `code`='{$rowSite['code']}' limit 1")->fetch();//根据网站唯一程序code 查询 项目的信息
            $proName = $rowProgram["name"];
            saveLog($userrow['uid'], "删除项目-$proName ");
            //发送邮件提醒
            if ($userrow['email'] != null && ($conf['mail_pwd'] != null || $conf['sms_appkey'] != null)) {
                $sub = $conf['web_name'] . ' - 删除网站提醒';
                $domain = $rowSite['domain'];
                $msg = emailWritting($conf['web_name'], "删除网站", " 您成功删除: $proName <br/>删除网站域名：$domain<br/>删除时间为：$date");
                sendEmail($userrow['email'], $sub, $msg);
            }
            $result = array("code" => 1, "msg" => "删除成功", "url" => 'mySite.php');
            exit(json_encode($result));
        }
        break;

    /**
     * author: 1617643@qq.com
     * time:2020/2/12 23:23
     * description:TODO 用户续费网站
     */
    case 'rePay':
        $sid = trim(strip_tags(daddslashes($_POST['sid'])));

        //根据宝塔ID获得数据库中对应的站点的信息
        $rowSite = $DB->query("SELECT * FROM `wcms_site` WHERE `uid`='{$userrow['uid']}' and `sid`='{$sid}' limit 1")->fetch();

        //获得对应的项目信息
        $rowProgram = $DB->query("SELECT * FROM `wcms_program` WHERE `code`='{$rowSite['code']}'  limit 1")->fetch();//根据网站唯一程序code查询 项目的信息
        //获得对应的服务器信息
        $rowServer = $DB->query("SELECT * FROM `wcms_server` WHERE `sid`='{$rowSite['serverid']}'  limit 1")->fetch();
        $rowMemberConf = $DB->query("SELECT * FROM `wcms_member` WHERE `mcode`='{$userrow['mcode']}'  limit 1")->fetch();

        if ($rowProgram['discount'] == 1) { //开启优惠
            $newPrice = $rowProgram['reprice'] * $rowMemberConf['mpercent']; //商品新价格 = 续费价格 * 会员折扣
        } else {
            $newPrice = $rowProgram['reprice'];
        }
        $userMoney = $userrow['money'];
        if ($newPrice > $userMoney) {
            $result = array("code" => -1, "msg" => "账户余额不足,余额: ￥ $userMoney ,项目价格:￥ $newPrice ");
            exit(json_encode($result));
        }
        if ($rowSite['uid'] != $userrow['uid']) {
            $result = array("code" => -1, "msg" => "疑似非法操作");
            exit(json_encode($result));
        }

        //$rowProgram['usetime']  //续费使用
        // $rowSite['endtime'] 	//剩余时间
        //新到期时间 = 剩余时间 + 续费时间
        $endtime = date('Y-m-d H:i:s', strtotime("{$rowSite['endtime']} + {$rowProgram['usetime']} months"));
        $endtime = date('Y-m-d', strtotime($endtime)); //将年月日时分秒转成年月日
        $api = 'http://' . $rowServer['api'] . '';
        $pass = $rowServer['pass'];
        $timeSet = \app\Site::rePay($api, $pass, $rowSite['bid'], $endtime);
        if ($timeSet['code'] == -1) {
            $result = array("code" => -1, "msg" => $timeSet['msg']);
            exit(json_encode($result));
        } else {
            $DB->exec("UPDATE `wcms_site` SET `endtime` ='{$endtime}' WHERE `sid`='{$sid}'");
            //对用户进行扣款，这里执行折扣操作
            $userrow['money'] = $userrow['money'] - $newPrice;
            $DB->exec("UPDATE `wcms_user` SET `money` ='{$userrow['money']}' WHERE `uid`='{$userrow['uid']}'");
            $proName = $rowProgram["name"];
            saveLog($userrow['uid'], "续费项目-$proName ");
            if ($userrow['email'] != null && ($conf['mail_pwd'] != null || $conf['sms_appkey'] != null)) {
                $sub = $conf['web_name'] . ' - 续费网站提醒';
                $domain = $rowSite['domain'];
                $money = $userrow['money'];
                $msg = emailWritting($conf['web_name'], "续费网站", " 您成功续费: $proName <br/>续费网站域名：$domain<br/>账户余额：$money<br/>续费时间为：$date");
                sendEmail($userrow['email'], $sub, $msg);
            }
            $result = array("code" => 1, "msg" => "续费成功", "url" => 'mySite.php');
            exit(json_encode($result));
        }
        break;

    /**
     * author: 1617643@qq.com
     * time:2020/2/12 23:23
     * description:TODO 用户重装网站
     */
    case 'reInstall':
        $sid = trim(strip_tags(daddslashes($_POST['sid'])));
        $rowSite = $DB->query("SELECT * FROM `wcms_site` WHERE `sid`='{$sid}'  limit 1")->fetch();//根据网站ID查询网站
        $sqlname = $rowSite['sqlname'];
        $sqlpass = $rowSite['sqlpass'];
        $rowProgram = $DB->query("SELECT * FROM `wcms_program` WHERE `code`='{$rowSite['code']}'  limit 1")->fetch();//根据网站唯一程序code 查询 项目的信息
        $username = "admin";
        $password = "123456";
        $result = \app\Site::install($rowSite['domain'], $rowProgram['path'], $rowProgram['install'], $sqlname, $sqlpass, $conf['site_key'], $username, $password);
        if ($result['code'] == 1) { //安装成功
            $DB->exec("UPDATE `wcms_site` SET `isinstall` ='1' WHERE `uid`='{$rowSite['bid']}'");
            $proName = $rowProgram["name"];
            saveLog($userrow['uid'], "重装项目-$proName ");
            $result = array("code" => 1, "msg" => "网站重装成功", "url" => 'mySite.php');
        } else {
            //重装失败了
            $result = array("code" => -1, "msg" => $result['msg']);
        }
        exit(json_encode($result));
        break;


    /**
     * author: 1617643@qq.com
     * time:2020/2/12 23:23
     * description:TODO 获取单个网站域名
     */
    case 'getMyDomain':
        $sid = trim(strip_tags(daddslashes($_POST['sid'])));
        $myPro = $DB->query("SELECT * FROM `wcms_site` WHERE `sid`='{$sid}' and `uid`='{$userrow['uid']}' limit 1")->fetch();//根据网站ID查询网站
        $domainlist = $myPro['userdomain']; //用户自定义域名
        if (!$domainlist) {
            $domainlist = array();
        } else {
            if (strstr($domainlist, ",")) {
                $domainlist = explode(',', $domainlist);
            } else {
                $domainlist = array($myPro['userdomain']);
            }
        }
        $result = array('code' => 1, 'myDomain' => $domainlist, "domain" => $myPro['domain']);
        exit(json_encode($result));

        break;

    /**
     * author: 1617643@qq.com
     * time:2020/2/12 23:23
     * description:TODO 绑定自定义域名
     */
    case 'addDomain':
        $sid = trim(strip_tags(daddslashes($_POST['sid'])));
        $domain = trim(strip_tags(daddslashes($_POST['domain'])));

        $rowSite = $DB->query("SELECT * FROM `wcms_site` WHERE `sid`='{$sid}' and `uid`='{$userrow['uid']}' limit 1")->fetch();//根据网站ID查询网站
        $userdomain = $rowSite['userdomain'];
        $userdomain_arr = explode(",", $userdomain);
        foreach ($userdomain_arr as $k => $v) {
            if ($v == $domain) {
                $result = array("code" => -1, "msg" => "自定义绑定域名已经存在");
                exit(json_encode($result));
            }
        }
        $userdomain_arr[] = $domain;
        $rowServer = $DB->query("SELECT * FROM `wcms_server` WHERE `sid`='{$rowSite['serverid']}' limit 1")->fetch();//根据网站ID查询网站
        if($rowServer['ok_domain'] == 0){
            if(strpos($domain,$rowServer['domain']) !==false){
                $result = array("code" => -1, "msg" => "请绑定您自己的域名");
                exit(json_encode($result));
            }
        }

        $api = 'http://' . $rowServer['api'] . '';
        $pass = $rowServer['pass'];
        $bid = $rowSite['bid'];
        $addDomain = \app\Site::addDomain($api, $pass, $bid, $rowSite['domain'], $domain);

        if ($addDomain['code'] == -1) {
            exit(json_encode($addDomain));
        } else {
            if ($rowSite['userdomain'] == null) { //第一次绑定自定义域名
                $DB->exec("UPDATE `wcms_site` SET `userdomain` ='{$domain}' WHERE `bid`='{$bid}'");
            } else {
                $sql = "UPDATE `wcms_site` SET `userdomain`=:userdomain WHERE `bid`=:bid";
                $stmt = $DB->prepare($sql);
                $stmt->execute(array(':userdomain' => implode(',', $userdomain_arr), ':bid' => $bid));
            }
            $result = array("code" => 1, "msg" => " $domain 绑定成功");
            exit(json_encode($result));
        }
        break;

    /**
     * author: 1617643@qq.com
     * time:2020/2/12 23:23
     * description:TODO 删除自定义域名
     */
    case 'delDomain':
        $sid = trim(strip_tags(daddslashes($_POST['sid'])));
        $domain = trim(strip_tags(daddslashes($_POST['domain'])));
        $rowSite = $DB->query("SELECT * FROM `wcms_site` WHERE `sid`='{$sid}' and `uid`='{$userrow['uid']}' limit 1")->fetch();//根据网站ID查询网站
        $rowServer = $DB->query("SELECT * FROM `wcms_server` WHERE `sid`='{$rowSite['serverid']}' limit 1")->fetch();//根据网站ID查询网站
        $api = 'http://' . $rowServer['api'] . '';
        $pass = $rowServer['pass'];
        $bid = $rowSite['bid'];
        $delDomain = \app\Site::delDomain($api, $pass, $bid, $rowSite['domain'], $domain);
        $userdomain = $rowSite['userdomain'];
        $userdomain_arr = explode(",", $userdomain);
        foreach ($userdomain_arr as $k => $v) {
            if ($v == $domain) {
                unset($userdomain_arr[$k]);
            }
        }
        if ($delDomain['code'] == -1) {
            exit(json_encode($delDomain));
        } else {
            $sql = "UPDATE `wcms_site` SET `userdomain`=:userdomain WHERE `bid`=:bid";
            $stmt = $DB->prepare($sql);
            $stmt->execute(array(':userdomain' => implode(',', $userdomain_arr), ':bid' => $bid));
            $result = array("code" => 1, "msg" => " $domain 删除成功");
            exit(json_encode($result));
        }
        break;


    /**
     * author: 1617643@qq.com
     * time:2020/2/29 00:52
     * description:TODO 发起工单
     */
    case 'addWorkOrder':
        $title = trim(strip_tags(daddslashes($_POST['title'])));
        $content = trim(strip_tags(daddslashes($_POST['content'])));
        $domain = trim(strip_tags(daddslashes($_POST['domain'])));
        if ($title == null || $content == null) {
            $result = array("code" => -1, "msg" => "所有项不得为空,请补充完整");
            exit(json_encode($result));
        }
        if (strlen($content) < '10' || strlen($content) > '100') {
            $result = array("code" => -1, "msg" => "工单内容不能小于10个字符且不能大于100字符");
            exit(json_encode($result));
        }
        $code = substr(md5(uniqid() . rand(1, 10000)), 16);
        $num = time();
        $content = $domain."-".$content;

        $sql = $DB->exec("INSERT INTO `wcms_workorder` (`code`, `num`, `uid`, `user`, `title`,`content`, `date`, `userreply`, `state`) VALUES('{$code}','{$num}','{$userrow['uid']}','{$userrow['nickname']}','{$title}','{$content}','{$date}','{$date}','0')");
        if ($sql) {
            $manage = $DB->query("SELECT * FROM `wcms_user` WHERE `uid`='10000' limit 1")->fetch();
            if ($manage['email'] != null && ($conf['mail_pwd'] != null || $conf['sms_appkey'] != null)) {
                $sub = $conf['web_name'] . ' - 新工单提醒';
                $msg = emailWritting($conf['web_name'], "新工单提醒", " 您的网站有新的工单提醒请及时查看<br/>工单提交时间为：$date");
                sendEmail($manage['email'], $sub, $msg);
            }
            saveLog($userrow['uid'], "发起工单");
            $result = array("code" => 1, "msg" => "工单提交成功", "url" => "workOrder.php");
            exit(json_encode($result));
        } else {
            $result = array("code" => -1, "msg" => "工单提交失败,请稍后再试");
            exit(json_encode($result));
        }
        break;

    /**
     * author: 1617643@qq.com
     * time:2020/2/29 02:23
     * description:TODO 删除单个工单
     */
    case 'delWorkOrder':
        $id = trim(strip_tags(daddslashes($_POST['id'])));
        $row = $DB->query("SELECT * from `wcms_workorder` WHERE `id`='{$id}' and `uid`='{$userrow['uid']}' limit 1")->fetch();
        if (!$row) {
            $result = array("code" => -1, "msg" => "账号异常,请重新登录");
            exit(json_encode($result));
        }
        $DB->exec("DELETE FROM `wcms_workorder` WHERE `code` = '{$row['code']}'");
        $result = array("code" => 1, "msg" => "删除成功", "url" => 'workOrder.php');
        exit(json_encode($result));
        break;

    /**
     * author: 1617643@qq.com
     * time:2020/2/29 02:23
     * description:TODO 改变工单状态
     */
    case 'changeWorkOrder':
        $id = trim(strip_tags(daddslashes($_POST['id'])));
        $row = $DB->query("SELECT * from `wcms_workorder` WHERE `id`='{$id}' and `uid`='{$userrow['uid']}' limit 1")->fetch();
        if (!$row) {
            $result = array("code" => -1, "msg" => "账号异常,请重新登录");
            exit(json_encode($result));
        }
        $state = 0;
        if ($row['state'] == 0) {
            $state = 1;
        }
        $DB->exec("UPDATE `wcms_workorder` SET  `state`='{$state}'  WHERE `code`='{$row['code']}'");
        $result = array("code" => 1, "msg" => "修改成功", "url" => 'workOrder.php');
        exit(json_encode($result));
        break;


    /**
     * author: 1617643@qq.com
     * time:2020/2/28 22:22
     * description:TODO 回复工单
     */
    case 'replyWorkOrder':
        $code = trim(strip_tags(daddslashes($_POST['code'])));
        $content = trim(strip_tags(daddslashes($_POST['content'])));
        $row = $DB->query("SELECT * from `wcms_workorder` WHERE `code`='{$code}' and `uid`='{$userrow['uid']}'  limit 1")->fetch();//f03a84cb7482f59e
        if (!$row) {
            $result = array("code" => -1, "msg" => "账号异常,请重新登录");
            exit(json_encode($result));
        }
        $date = $row['date'];
        $title = $row['title'];
        $adminreply = '0001-01-01 00:00:00';
        $userreply = date("Y-m-d H:i:s");
        $num = time();
        $date = date("Y-m-d H:i:s");
        $state = 0;
        $DB->exec("UPDATE `wcms_workorder` SET `adminreply` ='{$adminreply}' WHERE `code`='{$code}'");
        $sql = $DB->exec("INSERT INTO `wcms_workorder` (`code`,`uid`,`num`, `user`, `title`,`content`,`userreply`, `state`,`date`,`adminreply`) VALUES ('{$code}','{$userrow['uid']}','{$num}','{$userrow['nickname']}','{$title}','{$content}','{$userreply}','{$state}','{$date}','{$adminreply}')");
        $DB->exec("UPDATE `wcms_workorder` SET  `state`=0  WHERE `code`='{$code}'");
        $DB->exec("UPDATE `wcms_workorder` SET  `userreply`='{$userreply}'  WHERE `code`='{$code}'");
        $manage = $DB->query("SELECT * FROM `wcms_user` WHERE `uid`='10000' limit 1")->fetch();
        if ($manage['email'] != null && ($conf['mail_pwd'] != null || $conf['sms_appkey'] != null)) {
            $sub = $conf['web_name'] . ' - 新工单提醒';
            $msg = emailWritting($conf['web_name'], "新工单提醒", " 您的网站有新的工单提醒请及时查看<br/>工单提交时间为：$date");
            sendEmail($manage['email'], $sub, $msg);
        }
        $result = array("code" => 1, "msg" => "回复成功", "url" => 'workOrder.php');
        exit(json_encode($result));
        break;

    /**
     * author: 1617643@qq.com
     * time:2020/2/29 07:00
     * description:TODO 网站push
     */
    case 'push':
        $sid = trim(strip_tags(daddslashes($_POST['sid'])));
        $username = trim(strip_tags(daddslashes($_POST['username'])));
        $rowSite = $DB->query("SELECT * FROM `wcms_site` WHERE `uid`='{$userrow['uid']}' and `sid`='{$sid}' limit 1")->fetch();
        $rowUser = $DB->query("SELECT * FROM `wcms_user` WHERE `username`='{$username}' limit 1")->fetch();
        if(!$rowSite){
            $result = array("code" => -1, "msg" => "没有指定push网站");
            exit(json_encode($result));
        }
        if(!$rowUser){
            $result = array("code" => -1, "msg" => "push用户账号错误");
            exit(json_encode($result));
        }

        //push价格
        if($conf['push_toll'] == 1){
            if($conf['push_price'] > $userrow['money']){
                $result = array("code" => -1, "msg" => "余额不足,不可push");
                exit(json_encode($result));
            }else{
                $money = $userrow['money'] - $conf['push_price'];
                $DB->exec("UPDATE `wcms_user` SET `money`='{$money}' WHERE `uid`='{$userrow['uid']}'");
                $money = $row['money'];
                saveLog($userrow['uid'], "push网站,花费 $money 元");
            }
        }
        $DB->exec("UPDATE `wcms_site` SET `uid` ='{$rowUser['uid']}' WHERE `sid`='{$sid}'");
        $result = array("code" => 1, "msg" => "push成功","url" =>"push.php");
        exit(json_encode($result));
        break;


    /**
     * author: 1617643@qq.com
     * time:2020/2/29 15:33
     * description:TODO 卡密支付
     */
    case 'cardPay':
        $card = trim(strip_tags(daddslashes($_POST['card'])));
        $row = $DB->query("SELECT * from `wcms_card` WHERE `card`='{$card}' and `type`='0' and `active`='0' limit 1")->fetch();//f03a84cb7482f59e
        if (!$row) {
            $result = array("code" => -1, "msg" => "卡密输入错误");
            exit(json_encode($result));
        }
        $DB->exec("UPDATE `wcms_card` SET `active` ='1',`endtime`='{$date}',`uid`='{$userrow['uid']}' WHERE `card`='{$row['card']}'");
        $money = $userrow['money'] + $row['money'];
        $DB->exec("UPDATE `wcms_user` SET `money`='{$money}' WHERE `uid`='{$userrow['uid']}'");
        $money = $row['money'];
        $order_no = date("YmdHis") . rand(111, 999);
        $name = '用户' . $userrow['uid'] . '-卡密充值' . $money . '元余额';
        $type = 'cardPay';
        $DB->exec("INSERT INTO `wcms_order` (`order_no`,  `name`,`uid`, `money`, `date`, `type`, `status`)VALUES ('{$order_no}', '{$name}', '{$userrow['uid']}',  '{$money}', '{$date}','{$type}', '1')");
        saveLog($userrow['uid'], "卡密充值 $money 元");
        $result = array("code" => 1, "msg" => "充值 $money 元 成功", "url" => "info.php");
        exit(json_encode($result));
        break;


    default:

        break;


}

?>