<?php
/**
 * plugin management
 */

/**
 * @var string $action
 * @var object $CACHE
 */

require_once 'globals.php';

$plugin = Input::getStrVar("plugin");
$filter = Input::getStrVar('filter'); // on or off

if (empty($action) && empty($plugin)) {

    $br = '<a href="./">控制台</a><a><cite>插件管理</cite></a>';

    include View::getAdmView('header');
    require_once(View::getAdmView('plugin'));
    include View::getAdmView('footer');
    View::output();
}

if ($action == 'index') {
    $Plugin_Model = new Plugin_Model();
    $plugins = $Plugin_Model->getPlugins($filter);

    $check = [];
    foreach($plugins as $val){
        $check[] = [
            'name' => $val['Plugin'],
            'version' => $val['Version']
        ];
    }

    $db = Database::getInstance();
    $db_prefix = DB_PREFIX;
    $domain = getDomain();
    $sql = "select * from {$db_prefix}authorization where domain='{$domain}'";
    $res = $db->once_fetch_array($sql);
    $emkey =  empty($res) ? false : $res['emkey'];

    $emcurl = new EmCurl();
    $post_data = [
        'emkey' => $emkey,
        'apps'  => json_encode($check),
    ];

    $emcurl->setPost($post_data);
    $emcurl->request(SERVICE_HOST . '/api/plugin/upgrade');


    $retStatus = $emcurl->getHttpStatus();

    $response = $emcurl->getRespone();


    $ret = json_decode($response, 1);


//d($ret);die;

    foreach($plugins as $key => $val){
        $plugins[$key]['update'] = 0;
        foreach($ret['data'] as $v){
            if($val['Plugin'] == $v['name']){
                $plugins[$key]['update'] = 1;
            }
        }
    }



    output::data($plugins, count($plugins));
}

if($action == 'switch'){
    LoginAuth::checkToken();
    $Plugin_Model = new Plugin_Model();
    $alias = Input::postStrVar('plugin');
    $status = Input::postIntVar('status');
    if($status == 1){
        $res = $Plugin_Model->activePlugin($alias);
    }else{
        if (strpos($alias, 'tpl_options') !== false) {
            output::error('禁止操作该插件');
        }
        $Plugin_Model->inactivePlugin($alias);
        $res = true;
    }
    if($res){
        $CACHE->updateCache('options');
        output::ok('操作成功');
    }else{
        output::error('操作失败');
    }
}


// Load plug-in configuration page
if (empty($action) && $plugin) {
    require_once "../content/plugins/$plugin/{$plugin}_setting.php";
    include View::getAdmView('header');
    plugin_setting_view();
    include View::getAdmView('footer');
}
if($action == 'setting_page'){
    $type = Input::getStrVar('type');
    if($type == 'admin'){
        $br = '<a href="./">控制台</a><a><cite>插件扩展功能</cite></a>';
    }
    require_once "../content/plugins/$plugin/{$plugin}_setting.php";
    include View::getAdmView($type == 'admin' ? 'header' : 'open_head');
    plugin_setting_view();
    include View::getAdmView($type == 'admin' ? 'footer' : 'open_foot');
}

// Save plug-in settings
if ($action == 'setting') {
    if (!empty($_POST)) {
        require_once "../content/plugins/$plugin/{$plugin}_setting.php";
        if (false === plugin_setting()) {
            emDirect("./plugin.php?plugin={$plugin}&error=1");
        } else {
            emDirect("./plugin.php?plugin={$plugin}&setting=1");
        }
    } else {
        emDirect("./plugin.php?plugin={$plugin}&error=1");
    }
}



if ($action == 'del') {
    LoginAuth::checkToken();
    $plugin = Input::postStrVar('plugin');
    $Plugin_Model = new Plugin_Model();
    $Plugin_Model->inactivePlugin($plugin);
    $Plugin_Model->rmCallback($plugin);
    $path = preg_replace("/^([\w-]+)\/[\w-]+\.php$/i", "$1", $plugin);

    if ($path && true === emDeleteFile('../content/plugins/' . $path)) {
        $CACHE->updateCache('options');
        output::ok('删除成功');
    } else {
        output::ok('删除成功');
    }
}

if ($action == 'upload_zip') {
    if (defined('APP_UPLOAD_FORBID') && APP_UPLOAD_FORBID === true) {
        emMsg('系统禁止上传安装应用');
    }
    LoginAuth::checkToken();
    $zipfile = isset($_FILES['pluzip']) ? $_FILES['pluzip'] : '';

    if ($zipfile['error'] == 4) {
        emDirect("./plugin.php?error_d=1");
    }
    if ($zipfile['error'] == 1) {
        emDirect("./plugin.php?error_g=1");
    }
    if (!$zipfile || $zipfile['error'] >= 1 || empty($zipfile['tmp_name'])) {
        emMsg('插件上传失败， 错误码：' . $zipfile['error']);
    }
    if (getFileSuffix($zipfile['name']) != 'zip') {
        emDirect("./plugin.php?error_f=1");
    }

    $ret = emUnZip($zipfile['tmp_name'], '../content/plugins/', 'plugin');
    switch ($ret) {
        case 0:
            emDirect("./plugin.php?activate_install=1");
            break;
        case -1:
            emDirect("./plugin.php?error_e=1");
            break;
        case 1:
        case 2:
            emDirect("./plugin.php?error_b=1");
            break;
        case 3:
            emDirect("./plugin.php?error_c=1");
            break;
    }
}



if ($action === 'upgrade') {
    $alias = Input::postStrVar('alias', '');
    if (!Register::isRegLocal()) {
        output::error('当前程序未授权，无法更新！');
    }

    $temp_file = emFetchFile(SERVICE_HOST . '/api/plugin/down/plugin/' . $alias);
    if (!$temp_file) {
        output::error('无法获取更新文件！');
    }
    $unzip_path = '../content/plugins/';
    $ret = emUnZip($temp_file, $unzip_path, 'plugin');
    @unlink($temp_file);
    switch ($ret) {
        case 0:
            $Plugin_Model = new Plugin_Model();
            $Plugin_Model->upCallback($alias);
            output::ok();
            break;
        case 1:
        case 2:
            output::error('更新失败');
            break;
        case 3:
            output::error('更新失败');
            break;
        default:
            output::error('更新失败');
    }
}
