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

$type     = $_G['GET']['TYPE'];
$tsetpath = 'superadmin:app';
//==========================安装应用======================================
if ('install' == $_G['GET']['ML']) {
    $r = installAT($type, $_G['GET']['T']);
    if (true !== $r) {
        ExitJson($r);
    }
    ExitJson('操作成功', true);
    //==========================卸载应用======================================
} elseif ('uninstall' == $_G['GET']['ML']) {
    $r = uninstallAT($type, $_G['GET']['T']);
    if (true !== $r) {
        ExitJson($r);
    }
    ExitJson('操作成功', true);
} elseif ('table' == $_G['GET']['ML']) {
    $tables = table()->table_names();
    $html   = "<?php
if (!defined('puyuetian')) {
	exit('403');
}

/*
 * 适用于 HadSky 8.3.10 及以后版本
 * 直接Ctrl+A复制全部内容
 * 然后粘贴进" . PK_APP_PATH . "{$_G['GET']['T']}/install.php文件即可
 * 若不存在该文件创建即可
 */

if (user('id') != 1) {
	v8Error('403');
}

";
    foreach ($tables as $table) {
        $perfix = $type . '_' . $_G['GET']['T'] . '_';
        if (strpos($table, $perfix) === 0) {
            $create_php = trim(table($table)->show_create_table());
            $newtable   = substr($create_php, 0, strpos($create_php, ' '));
            $html .= "// {$table}表若不存在则创建\nif (!{$newtable} -> table_exists()) " . $create_php . "\n\n";
        }
    }
    $html .= "v8Success('ok');";
    header('Content-type:text/json');
    exit($html);
} elseif ('json' == $_G['GET']['ML']) {
    //==========================导出模板数据======================================
    $jsonarray = array();
    $perfix    = $type . '_' . $_G['GET']['T'] . '_';
    foreach ($_G['SET'] as $key => $value) {
        if (substr($key, 0, strlen(strtoupper($perfix))) != strtoupper($perfix)) {
            continue;
        }
        $jsonarray[strtolower($key)] = $value;
    }
    header('Content-type:text/json');
    exit(json_encode($jsonarray));
    //==========================加载应用设置======================================
} elseif ('setting' == $_G['GET']['ML']) {
    $tsetpath = "{$_G['SYSTEM']['PATH']}{$type}/{$_G['GET']['T']}/setting.hst";
} elseif ('development' == $_G['GET']['T']) {
    if ($_G['GET']['SUBMIT']) {
        if (!$_POST['logobase64']) {
            ExitJson('请设置logo');
        }
        $array         = array();
        $array['type'] = $_POST['type'];
        if (!InArray('app,template', $array['type'])) {
            ExitJson('应用类型错误');
        }
        $array['title'] = $_POST['title'];
        $array['dir']   = Cstr($_POST['dir'], false, true, 3, 255);
        if (!$array['dir']) {
            ExitJson('目录格式非法');
        }
        $array['version']     = $_POST['version'];
        $array['description'] = $_POST['description'];
        $path                 = $_G['SYSTEM']['PATH'] . $array['type'] . '/' . $array['dir'] . '/';
        if (file_exists($path)) {
            ExitJson('该目录已经存在');
        }
        //创建公有资源
        //创建应用脚本目录
        mkdir($path . 'phpscript/', 0777, true);
        //config.json
        file_put_contents($path . 'config.json', json_encode($array, 320));
        //setting.hst
        $d = file_get_contents(PK_APP_PATH . 'superadmin/template/at-template-setting.hst');
        $d = str_replace(['[AN]', '[TYPE]'], [$array['dir'], $array['type']], $d);
        file_put_contents($path . 'setting.hst', $d);
        //logo.png
        file_put_contents($path . 'logo.png', base64_decode(substr($_POST['logobase64'], 22)));
        // v8
        file_put_contents($path . 'hadsky.v8', '');
        if ('app' == $array['type']) {
            mkdir($path . 'template/phpscript/', 0777, true);
            file_put_contents($path . 'index.php', '<?php
if (!defined(\'puyuetian\'))
	exit(\'403\');

LoadAppScript();');
            file_put_contents($path . 'install.php', '<?php
if (!defined(\'puyuetian\'))
	exit(\'403\');

if (user(\'id\') != 1) {
	v8Error(\'403\');
}

// 应用数据表安装代码

v8Success(\'ok\');');
            file_put_contents($path . 'template/hadsky.v8', '');
            file_put_contents($path . 'template/default.hst', '插件默认页面：' . $path . 'template/default.hst');
            file_put_contents($path . 'phpscript/default.php', '<?php
if (!defined(\'puyuetian\'))
	exit(\'403\');

// 内嵌显示模式
// gConcat(\'template.output\', nt(\'' . $array['dir'] . ':default\'));
// 独立显示模式
g(\'template.body\', \'' . $array['dir'] . ':default\');');
        } else {
            mkdir($path . 'img', 0777);
            mkdir($path . 'css', 0777);
            mkdir($path . 'js', 0777);
        }
        ExitJson($path, true);
    }
    $tsetpath = 'superadmin:app-development';
} elseif ('uploadapp' == $_G['GET']['T']) {
    if ($_G['GET']['SUBMIT']) {
        //原文件名
        $file_name = $_FILES['file']['name'];
        //服务器上临时文件名
        $tmp_name = $_FILES['file']['tmp_name'];
        $suffix   = strtolower(end(explode('.', $_FILES['file']['name'])));
        if (!InArray('hsa,zip', $suffix)) {
            ExitJson('仅允许上传hsa和zip后缀文件');
        }
        $rnd = CreateRandomString(32);
        $lj  = $_G['SYSTEM']['PATH'] . "app/superadmin/appzip/{$rnd}.zip";
        if (!move_uploaded_file($_FILES['file']['tmp_name'], $lj)) {
            ExitJson('上传失败');
        }
        if ('hsa' == $suffix) {
            $content = file_get_contents($lj);
            file_put_contents($lj, base64_decode($content));
        }
        $zip = new ZipArchive;
        $res = $zip->open($lj);
        if (true !== $res) {
            unlink($lj);
            ExitJson('解压失败：' . $res);
        }
        $zip->extractTo($_G['SYSTEM']['PATH']);
        $zip->close();
        unlink($lj);
        ExitJson('上传成功', true);
    }
    $tsetpath = 'superadmin:app-upload';
} else {
    //==========================获取本地插件信息======================================
    $_G['TEMP']['DATA'] = htmlspecialchars(json_encode(getAT($type)), ENT_QUOTES);
}

$contenthtml = template($tsetpath, true);
