<?php
/**
 * @Description TODO 任务监控
 * @Author 1617643@qq.com
 * @Date 2020/2/29 04:00
 */
include '../app/common.php';

$type = trim(strip_tags(daddslashes($_GET['type'])));//任务类型
$key = trim(strip_tags(daddslashes($_GET['key'])));//监控密钥


if ($conf['site_key'] != $key) {
    exit('监控密钥不正确,任务执行失败.');
}

if ($type == 'addDemo') {//使用任务监控搭建演示站
    //创建网站主机
    $cron1 = $DB->query("SELECT * FROM `wcms_demo` WHERE `status` = 1 limit 1")->fetch();
    if ($cron1) {
        $rowProgram = $DB->query("SELECT * FROM `wcms_program` WHERE `code`='{$cron1['code']}' limit 1")->fetch();
        if (!$rowProgram) {
            $DB->exec("UPDATE `wcms_demo` SET `status` ='0',`type` = '项目不存在' WHERE `id`='{$cron1['id']}'"); //任务失败
            exit("项目不存在,本次监控任务结束");
        }
        $rowServer = $DB->query("SELECT * FROM `wcms_server` where `active`= 1 limit 1")->fetch();
        if (!$rowServer) {
            exit("服务器不存在,本次监控任务结束");
        }
        //开始创建主机
        $uid = '10000';
        $usetime = $rowProgram['usetime']; //项目使用时间
        $endtime = (date('Y-m-d H:i:s', strtotime("+$usetime month")));  //过期时间 = 现在的时间 + 使用时间
        $domainRound = substr($cron1['domain'], 0, strpos($cron1['domain'], '.'));
        $defaultDomain = $rowServer['domain'];
        $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'] . "', '" . $uid . "','" . $rowServer['sid'] . "','" . $userDomain . "', '','" . $data['sqlname'] . "','" . $data['sqlpass'] . "','" . $rowProgram['code'] . "','" . $date . "','" . $endtime . "',1,0)");
            $proName = $rowProgram["name"];
            saveLog($uid, "通过监控任务创建项目-$proName ");
            $DB->exec("UPDATE `wcms_demo` SET `status` ='2' WHERE `id`='{$cron1['id']}'"); //创建主机任务完成
            exit("成功创建主机,本次监控任务结束");
        } else {
            $DB->exec("UPDATE `wcms_demo` SET `status` ='0',`type` = '{$result['msg']}' WHERE `id`='{$cron1['id']}'"); //任务失败
            echo($result['msg']);
            exit;
        }
    }

    //给每个主机安装网站程序
    $cron2 = $DB->query("SELECT * FROM `wcms_demo` WHERE `status` = 2 limit 1")->fetch();
    if ($cron2) {
        //$rowServer = $DB->query("SELECT * FROM `wcms_server` where `active`= 1 limit 1")->fetch();
        $rowSite = $DB->query("SELECT * FROM `wcms_site` WHERE `domain`='{$cron2['domain']}' 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`='{$rowSite['sid']}'");
            $DB->exec("UPDATE `wcms_demo` SET `status` ='3' WHERE `id`='{$cron2['id']}'"); //创建主机任务完成
            exit("成功初始化网站,本次监控任务结束");
        } else {
            $DB->exec("UPDATE `wcms_demo` SET `status` ='0',`type` = '网站初始化失败,请手动初始化' WHERE `id`='{$cron2['id']}'"); //任务失败
            exit("网站初始化失败,请手动初始化,本次监控任务结束");
        }
    }

    //将已经搭建成功的网站写入项目数据表的演示站字段
    $cronList = $DB->query("SELECT * FROM `wcms_demo` where `status` !='4'")->fetchAll();
    if ($cronList) {
        foreach ($cronList as $list) {
            $DB->exec("UPDATE `wcms_program` SET `demo` ='{$list['domain']}'  WHERE `code`='{$list['code']}'");
        }
        $DB->exec("UPDATE `wcms_demo` SET `status` ='4' WHERE 1");
        exit("一键搭建演示站任务已完成!");
    } else {
        exit("一键搭建演示站任务已完成!");
    }


} elseif ($type == 'endSiteEmail') {  //监控建议12小时访问一次
    //到期第七天的时候提示 到期还剩一天的时候邮件提示
    //网站过期7天邮件提示
    //如果网站过期7天，还未续费,那么删除网站
    $date = time();
    $rowsites = $DB->query("select * from `wcms_site`")->fetchAll();
    if ($rowsites) {
        foreach ($rowsites as $rowsite) {
            $rest = strtotime($rowsite['endtime']) - $date;//网站的到期时间-现在的时间=剩余时间
            $days = intval($rest / 86400);//将剩余时间戳转换为天数
            if ($days == 7 || $days == 1 || $days < 1) {
                $date = date("Y-m-d H:i:s");
                $row = $DB->query("select u.email,s.domain from `wcms_site` s  inner join `wcms_user` u on  s.uid = u.uid and s.`sid` = '{$rowsite['sid']}'")->fetch();
                if ($row['email'] != null) {
                    $sub = $conf['web_name'] . ' - 网站到期提醒';

                    if ($days < 1) {
                        $DB->exec("update `wcms_site` set `status` = '0' where `sid` = '{$rowsite['sid']}' ");
                        $msg = emailWritting($conf['web_name'], "网站到期提醒", " 域名为 " . $rowsite['domain'] . " 的网站已经到期 " . abs($days) . " 天,网站到期 7 天后没有进行续费将删除网站数据。");
                    } else {
                        $msg = emailWritting($conf['web_name'], "网站到期提醒", " 域名为 " . $rowsite['domain'] . " 的网站离到期时间仅剩 $days 天,网站到期 7 天后没有进行续费将删除网站数据。");
                    }

                    $result = sendEmail($row['email'], $sub, $msg);
                    if ($result === true) {
                        echo "邮件发送成功</br>";
                    } else {
                        echo "邮件发送失败</br>";
                    }
                } else {
                    echo $rowsite['domain'] . "=>用户邮箱为空!</br>";
                }
            } else {
                echo $rowsite['domain'] . "=>还没有到期</br>";
            }
        }
    } else {
        echo "暂时没有获取到网站数据";
    }
} elseif ($type == 'delEndSite') { //删除
    $date = time();
    $rowsite = $DB->query("select * from `wcms_site` where `status` = '0' limit 1")->fetch();

    if ($rowsite) {
        $rest = $date - strtotime($rowsite['endtime']);//网站的到期时间-现在的时间=剩余时间
        $days = intval($rest / 86400);//将剩余时间戳转换为天数

        if ($days >= 7) {
            $date = date("Y-m-d H:i:s");
            $row = $DB->query("select u.email,s.domain from `wcms_site` s  inner join `wcms_user` u on  s.uid = u.uid and s.`sid` = '{$rowsite['sid']}'")->fetch();

            if ($row['email'] != null) {
                //执行删除网站代码
                $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']);
                $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($rowsite['uid'], "网站到期7天自动删除项目-$proName ");
                $domain = $rowsite['domain'];
                $msg = emailWritting($conf['web_name'], "网站删除提醒", " 域名为 $domain 的网站已到期时间仅剩 $days 天,网站数据已删除,感谢您的使用");
                $result = sendEmail($email, $sub, $msg);
                if ($result === true) {
                    echo "邮件发送成功";
                } else {
                    echo "邮件发送失败";
                }
            } else {
                echo "用户邮箱为空!";
            }
        }else{
            echo "不到删除日期";
        }
    } else {
        echo "没有即将到期的网站";
    }

} else {
    exit('任务类型错误,任务执行失败.');
}

