<?php
if (!defined('puyuetian')) {
    exit('403');
}

function chkinstall($as, $at)
{
    return true;
    global $_G;
    $getjson = json_decode(GetPostData("https://www.hadsky.com/index.php?c=app&a=zhanzhang:index6&s=appinstall&at={$at}&domain={$_G['SYSTEM']['DOMAIN']}&sitekey=" . md5($_G['SET']['APP_HADSKYCLOUDSERVER_SITEKEY']) . "&rnd={$_G['RND']}", '', 10), true);
    if (!$getjson) {
        header('Location:index.php?c=app&a=superadmin:index&s=' . $as . '&alert=' . urlencode('暂时无法安装请稍后再试') . '&pkalert=show&rnd=' . $_G['RND']);
        exit('<script>top.location.href="index.php?c=app&a=superadmin:index"</script>');
    }

    if ('ok' != $getjson['state']) {
        header('Location:index.php?c=app&a=superadmin:index&s=' . $as . '&alert=' . urlencode($getjson['datas']['msg']) . '&pkalert=show&rnd=' . $_G['RND']);
        exit('<script>top.location.href="index.php?c=app&a=superadmin:index"</script>');
    }
}

function apiData($s, $return = false)
{
    global $_G;
    $url = 'https://www.hadsky.com/index.php?c=app&a=zhanzhang:index6&s=' . $s;
    $url .= '&domain=' . $_G['SYSTEM']['DOMAIN'] . '&sitekey=' . md5($_G['SET']['APP_HADSKYCLOUDSERVER_SITEKEY']);
    $url .= '&version=' . HADSKY_VERSION;
    if ($return) {
        return $url;
    }
    $data = GetPostData($url, '', 10);
    $json = json_decode($data, true);
    if (InArray('ok,no', $json['state'])) {
        return $json;
    } else {
        return array('state' => 'no', 'datas' => array('msg' => '请求失败或返回数据非法：' . $data));
    }
}

function getAT($type)
{
    global $_G;
    $array   = array();
    $tpath   = $_G['SYSTEM']['PATH'] . $type;
    $appnavs = '';
    $scan    = scandir($tpath);
    foreach ($scan as $name) {
        $fn = $tpath . '/' . $name;
        if ('.' == $name || '..' == $name || filetype($fn) != 'dir') {
            continue;
        }
        if (!file_exists($fn . '/config.json')) {
            continue;
        }
        $iarray            = json_decode(file_get_contents($fn . '/config.json'), true);
        $iarray['install'] = file_exists($fn . '/install.json') ? true : false;
        $iarray['setting'] = file_exists($fn . '/setting.hst') ? true : false;
        $iarray['running'] = $_G['SET'][strtoupper($type) . '_' . strtoupper($name) . '_' . 'LOAD'] ? true : false;
        if ($iarray['install']) {
            $iarray['status'] = '已下载';
        } else {
            $iarray['status'] = '已安装';
        }
        if ($iarray['running']) {
            $iarray['status'] = '已开启';
        }
        $array[$name] = $iarray;
    }
    return $array;
}

function installAT($type, $t)
{
    global $_G;
    $fpath = "{$_G['SYSTEM']['PATH']}{$type}/{$t}/install.json";
    if (!file_exists($fpath)) {
        return '安装失败，未找到安装数据';
    }
    // 8.2.0添加版本是否支持
    $config = file_get_contents("{$_G['SYSTEM']['PATH']}{$type}/{$t}/config.json");
    $config = json_decode($config, true);
    if (!$config) {
        return '缺少配置信息';
    }
    // 判断系统版本是否支持
    if ($config['hs_mv'] && version_compare($config['hs_mv'], HADSKY_VERSION, '>')) {
        return '当前系统版本：' . HADSKY_VERSION . "，最低要求版本：{$config['hs_mv']}，请升级系统后再安装";
    }
    // 判断是否有依赖 rely on
    if ($config['am_ro'] && !file_exists(PK_WWWROOT . "{$config['am_ro']}")) {
        return '当前应用依赖于应用：<a target="_blank" class="pk-text-primary pk-hover-underline" href="https://www.hadsky.com/appstore.html?type=' . str_replace('/', '&dir=', $config['am_ro']) . '&auto=1">' . $config['am_ro'] . '</a>，请先下载安装相关应用后再安装';
    }
    $jsondata = json_decode(file_get_contents($fpath), true);
    if (!$jsondata) {
        return '安装数据解析出错';
    }
    if (!rename($fpath, "{$_G['SYSTEM']['PATH']}{$type}/{$t}/uninstall.json")) {
        return '安装或升级失败，无写入权限';
    }
    $prefix = $type . '_' . $t . '_';
    foreach ($jsondata as $key => $value) {
        //数据校验
        if (substr($key, 0, strlen($prefix)) != $prefix) {
            continue;
        }
        if (table('set')->where('setname', $key)->mustNoCache()->find()) {
            // 该值存在，说明安装过
            continue;
        }
        table('set')->insert([
            'setname'  => $key,
            'setvalue' => $value,
        ]);
    }
    return true;
}

function uninstallAT($type, $t)
{
    global $_G;
    $sysapps = 'default,superadmin,verifycode,systememail,puyuetianeditor,hadskycloudserver,filesmanager,mysqlmanager,puyuetian_search,v8';
    if (InArray($sysapps, strtolower($_G['GET']['T']))) {
        return '不可卸载系统应用';
    }
    $fpath = "{$_G['SYSTEM']['PATH']}{$type}/{$t}/uninstall.json";
    if (!file_exists($fpath)) {
        return '卸载失败，未找到卸载数据';
    }
    $jsondata = json_decode(file_get_contents($fpath), true);
    if (!$jsondata) {
        return '卸载数据解析出错';
    }
    if (!rename($fpath, "{$_G['SYSTEM']['PATH']}{$type}/{$t}/install.json")) {
        return '卸载失败，无写入权限';
    }
    $prefix = $type . '_' . $t . '_';
    $iarray = array();
    foreach ($jsondata as $key => $value) {
        //数据校验
        if (substr($key, 0, strlen($prefix)) != $prefix) {
            continue;
        }
        $_G['TABLE']['SET']->delData('setname', $key);
    }
    return true;
}
