<?php
/**
 * @Description TODO API调用接口
 * @Author 1617643@qq.com
 * @Date 2020/03/06 04:00
 */
include '../app/common.php';


$act = isset($_GET['act']) ? daddslashes($_GET['act']) : null;
$api_user = isset($_GET['api_user']) ? daddslashes($_GET['api_user']) : null;
$api_key = isset($_GET['api_key']) ? daddslashes($_GET['api_key']) : null;
@header('Content-Type: application/json; charset=UTF-8');

if($conf['api_status'] != 1){
    $result = array("code" => -1, "msg" => "站点未开启API接口权限");
    exit(json_encode($result));
}

if($conf['api_user'] !=  $api_user || $conf['api_key'] != $api_key){
    $result = array("code" => -1, "msg" => "API接口账号或密钥错误,请在建站系统后台设置");
    exit(json_encode($result));
}

switch ($act) {
    /**
     * author: 1617643@qq.com
     * time:2020/03/05 22:22
     * description:TODO 获取所有项目
     */
    case 'getAllProgram':
        $list = $DB->query("SELECT * FROM `wcms_program` WHERE 1 order by `pid` asc")->fetchAll();
        $result = array("code" => 1, "msg" => "获取成功", "data" => $list);
        exit(json_encode($result));
        break;

    /**
     * author: 1617643@qq.com
     * time:2020/03/05 22:22
     * description:TODO 获取一个项目
     */
    case 'getOneProgram':
        $pid=intval($_GET['pid']);
        $row = $DB->query("SELECT * from `wcms_program` WHERE `pid`={$pid} limit 1")->fetch();
        if ($row) {
            $result = array("code" => 1, "msg" => "获取成功", "data" => $row);
            exit(json_encode($result));
        } else {
            $result = array("code" => -1, "msg" => "获取数据失败");
            exit(json_encode($result));
        }
        break;


    /**
     * author: 1617643@qq.com
     * time:2020/03/05 22:22
     * description:TODO 获取所有服务器信息
     */
    case 'getAllServer':
        $list=$DB->query("SELECT * FROM `wcms_server` WHERE 1 order by `sid` asc")->fetchAll();
        $result = array("code" => 1, "msg" => "获取成功", "data" => $list);
        exit(json_encode($result));
        break;

    /**
     * author: 1617643@qq.com
     ** time:2020/03/05 22:22
     * description:TODO 获取一个服务器信息
     */
    case 'getOneServer':
        $sid=intval($_GET['sid']);
        $row = $DB->query("SELECT * from `wcms_server` WHERE `sid`={$sid} limit 1")->fetch();
        if ($row) {
            $result = array("code" => 1, "msg" => "获取成功", "data" => $row);
            exit(json_encode($result));
        } else {
            $result = array("code" => -1, "msg" => "获取数据失败");
            exit(json_encode($result));
        }
        break;

    /**
     * author: 1617643@qq.com
     * time:2020/03/05 22:22
     * description:TODO 获取所有用户信息
     */
    case 'getAllUser':
        $list = $DB->query("SELECT * FROM `wcms_user` WHERE 1 order by `uid` asc ")->fetchAll();
        $result = array("code" => 1, "msg" => "获取成功", "data" => $list);
        exit(json_encode($result));
        break;

    /**
     * author: 1617643@qq.com
     * time:2020/03/05 22:22
     * description:TODO 获取一个用户信息
     */
    case 'getOneUser':
        $uid=intval($_GET['uid']);
        $row = $DB->query("SELECT * from `wcms_user` WHERE `uid`='{$uid}' limit 1")->fetch();
        if ($row) {
            $result = array("code" => 1, "msg" => "获取成功", "data" => $row);
            exit(json_encode($result));
        } else {
            $result = array("code" => -1, "msg" => "获取数据失败");
            exit(json_encode($result));
        }
        break;

    /**
     * author: 1617643@qq.com
     * time:2020/03/05 22:22
     * description:TODO 搭建网站
     */
    case 'buildSite':
        $pid=intval($_GET['pid']);
        $serverId=intval($_GET['sid']);
        $uid=intval($_GET['uid']);
        $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();//判断服务器是否存在
        $userrow = $DB->query("SELECT * from `wcms_user` WHERE `uid`='{$uid}' 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));
        }
        if(!$userrow){
            $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系统
                }
            }
            //运行目录配置
            \app\Site::SetSiteRunPath($rowServer['api'], $rowServer['pass'],$data['bid'], $rowProgram['site_path']);
            $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/03/05 22:22
     * description:TODO 安装网站
     */
    case 'install':
        $sid=intval($_GET['sid']);
        $uid=intval($_GET['uid']);
        $userrow = $DB->query("SELECT * from `wcms_user` WHERE `uid`='{$uid}' limit 1")->fetch(); //判断用户是否存在
        if(!$userrow){
            $result = array("code" => -1, "msg" => "用户不存在");
            exit(json_encode($result));
        }
        //执行安装
        $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}'");
            $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/03/05 22:22
     * description:TODO 用户删除网站
     */
    case 'delSite':
        $sid=intval($_GET['sid']);
        $uid=intval($_GET['uid']);
        $userrow = $DB->query("SELECT * from `wcms_user` WHERE `uid`='{$uid}' limit 1")->fetch(); //判断用户是否存在
        if(!$userrow){
            $result = array("code" => -1, "msg" => "用户不存在");
            exit(json_encode($result));
        }
        //判断当前站点是否在数据库中
        $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  数据库
        //$site = new Site();
        //$delSite = $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/03/05 22:22
     * description:TODO 用户续费网站
     */
    case 'rePay':
        $sid=intval($_GET['sid']);
        $uid=intval($_GET['uid']);
        $userrow = $DB->query("SELECT * from `wcms_user` WHERE `uid`='{$uid}' limit 1")->fetch(); //判断用户是否存在
        if(!$userrow){
            $result = array("code" => -1, "msg" => "用户不存在");
            exit(json_encode($result));
        }
        //根据宝塔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/03/05 22:22
     * description:TODO 用户重装网站
     */
    case 'reInstall':
        $sid=intval($_GET['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/03/05 22:22
     * description:TODO 获取单个网站域名
     */
    case 'getMyDomain':
        $sid=intval($_GET['sid']);
        $uid=intval($_GET['uid']);
        $userrow = $DB->query("SELECT * from `wcms_user` WHERE `uid`='{$uid}' limit 1")->fetch(); //判断用户是否存在
        if(!$userrow){
            $result = array("code" => -1, "msg" => "用户不存在");
            exit(json_encode($result));
        }
        $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/03/05 22:22
     * description:TODO 绑定自定义域名
     */
    case 'addDomain':
        $sid=intval($_GET['sid']);
        $domain = trim(strip_tags(daddslashes($_GET['domain'])));
        $uid=intval($_GET['uid']);
        $userrow = $DB->query("SELECT * from `wcms_user` WHERE `uid`='{$uid}' limit 1")->fetch(); //判断用户是否存在
        if(!$userrow){
            $result = array("code" => -1, "msg" => "用户不存在");
            exit(json_encode($result));
        }
        $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查询网站
        $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/03/05 22:22
     * description:TODO 删除自定义域名
     */
    case 'delDomain':
        $sid=intval($_GET['sid']);
        $domain = trim(strip_tags(daddslashes($_GET['domain'])));
        $uid=intval($_GET['uid']);
        $userrow = $DB->query("SELECT * from `wcms_user` WHERE `uid`='{$uid}' limit 1")->fetch(); //判断用户是否存在
        if(!$userrow){
            $result = array("code" => -1, "msg" => "用户不存在");
            exit(json_encode($result));
        }
        $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;







    default:
        $result = array("code" => -1, "msg" => "操作类型错误");
        exit(json_encode($result));
        break;

}

