<?php
/**
 * [LJCMS] (C)2012-2099 LJdev,Inc.
 * <E-Mail：aspcms@qq.com>
 * Url http://www.liangjing.org
 *     http://www.8CMS.com
 * Update 2014.04.03
 */
class control extends adminbase
{
    private $plugin_id = NULL;
    private $do = NULL;
    private function _getItems()
    {
        ob_end_clean();
        ob_start();
        $this->plugin_id = XRequest::getArgs('plugin_id');
        $this->do        = XRequest::getArgs('do');
    }
    public function action_run()
    {
        $this->_getItems();
        $model   = parent::model('plugin', 'am');
        $plugins = $model->getPlugins();
        foreach ($plugins as $k => $v) {
            $data               = $model->getPluginsimg($v['pluginname']);
            $plugins[$k]['img'] = "http://www.8cms.cn/" . $data['img'];
            if ($v['pluginname'] == 'oa') {
                $plugins[$k]['url'] = "oa.php";
            } elseif ($v['pluginname'] == 'aplipay') {
                $plugins[$k]['url'] = "admincp.php?c=aplipay";
            } elseif ($v['pluginname'] == 'sale') {
                $plugins[$k]['url'] = "sale.php";
            } else {
                $plugins[$k]['url'] = "admincp.php?c=plugin&a=setting&plugin_id=" . $v['pluginname'];
            }
        }
        unset($model);
        $var_array = array(
            'plugins' => $plugins,
        );
        TPL::assign($var_array);
        TPL::display($this->cptpl . 'plugin.tpl');
    }
    public function action_active()
    {
        $this->_getItems();
        $this->_checkPlugin();
        $model = parent::model('plugin', 'am');
        if ($model->activePlugin($this->plugin_id)) {
            $this->log('plugin', "激活id={$this->plugin_id}", 1);
            XHandle::halt("插件激活成功<script>var leftiframeid = window.parent.document.getElementById('menu-frame');leftiframeid.src='" . $this->cpfile . "?c=frame&a=left&mod=app';</script>", $this->cpfile . '?c=plugin', 0);
        } else {
            $this->log('plugin', "激活id={$this->plugin_id}", 0);
            Xhandle::halt('插件激活失败', '', 1);
        }
        unset($model);
    }
    public function action_shop()
    {
        $this->_getItems();
        $info = $this->checkmemberLogin();
        if (!empty($info)) {
            $check = 1;
        }
        $url = 'https://www.8cms.cn/api.php?a=pluginlist';
        $res = $this->curl_get($url);
        $data = json_decode($res, TRUE);
        $path = "https://www.8cms.cn/";
        foreach ($data['data'] as $k => $v) {
            $data['data'][$k]['img'] = $path . $v['img'];
        }
        $member_id = $info['member_id'];
        $url1      = "https://www.8cms.cn/api.php?a=memberinfo&member_id=$member_id";
        $res1      = $this->curl_get($url1);
        $data1     = json_decode($res1, TRUE);
        $var_array = array(
            'plugin' => $data['data'],
            'check'  => $check,
            'user'   => $data1['data'],
        );
        TPL::assign($var_array);
        TPL::display($this->cptpl . 'pluginlist.tpl');
    }
    public function action_plugin_info()
    {
        $this->_getItems();
        $info = $this->checkmemberLogin();
        if (!empty($info)) {
            $check = 1;
        }
        $burl                = 'http://' . $_SERVER['SERVER_NAME'];
        $plugin_id           = $_REQUEST['id'];
        $model               = parent::model('plugin', 'am');
        $existence           = $model->myplugin($plugin_id);
        $url                 = "https://www.8cms.cn/api.php?a=plugininfo&plugin_id=$plugin_id";
        $res                 = $this->curl_get($url);
        $data                = json_decode($res, TRUE);
        $data['data']['img'] = "https://www.8cms.cn/" . $data['data']['img'];
        $member_id           = $info['member_id'];
        $url1                = "https://www.8cms.cn/api.php?a=memberinfo&member_id=$member_id";
        $res1                = $this->curl_get($url1);
        $data1               = json_decode($res1, TRUE);
        //查看付费插件是否购买
        $is_mai = 0;
        if ($data['data']['type'] == '2') {
            $url2  = "https://www.8cms.cn/api.php?a=is_mai&plugin_id=$plugin_id&user_id=$member_id";
            $res2  = $this->curl_get($url2);
            $data2 = json_decode($res2, TRUE);
            if (!empty($data2['data'])) {
                $is_mai = 1;
            }
        }
        $var_array = array(
            'plugin'    => $data['data'],
            'check'     => $check,
            'existence' => $existence,
            'user'      => $data1['data'],
            'is_mai'    => $is_mai,
            'url'       => $burl
        );
        TPL::assign($var_array);
        TPL::display($this->cptpl . 'plugininfo.tpl');
    }
    public function action_buy()
    {
        $plugin_id = $_REQUEST['plugin_id'];
        $user_id   = $_REQUEST['userid'];
        $url       = "https://www.8cms.cn/api.php?a=buy_pilugin&plugin_id=$plugin_id&user_id=$user_id";
        $res       = $this->curl_get($url);
        $data      = json_decode($res, TRUE);
        $data1     = array(
            'response' => $data['slay'],
            'result'   => $data['msg']
        );
        echo json_encode($data1);
        die;
    }
    public function action_pay()
    {
        $this->_getItems();
        $info = $this->checkmemberLogin();
        if (!empty($info)) {
            $check = 1;
        }
        $member_id = $info['member_id'];
        $url1      = "https://www.8cms.cn/api.php?a=memberinfo&member_id=$member_id";
        $res1      = $this->curl_get($url1);
        $data1     = json_decode($res1, TRUE);
        $var_array = array(
            'check' => $check,
            'user'  => $data1['data'],
        );
        TPL::assign($var_array);
        TPL::display($this->cptpl . 'pay.tpl');
    }
    public function action_ajaxaddorder()
    {
        if ($_POST['price'] == '0') {
            $data = array(
                'response' => 0,
                'result'   => '充值金额不能为0'
            );
            echo json_encode($data);
            die;
        }
        if ($_POST['member_id'] == '0') {
            $data = array(
                'response' => 0,
                'result'   => '参数错误'
            );
            echo json_encode($data);
            die;
        }
        $arr['price']     = $_POST['price'];
        $arr['member_id'] = $_POST['member_id'];
        $data1 = http_build_query($arr);  //把参数转换成URL数据
        $aContext = array('http' => array('method' => 'POST',
                                          'header' => 'Content-type: application/x-www-form-urlencoded',
                                          'content' => $data1));
        $cxContext = stream_context_create($aContext);
        $sUrl = 'https://www.8cms.cn/index.php?c=user&a=ajaxaddorder'; //此处必须为完整路径
        $d = @file_get_contents($sUrl, false, $cxContext);
        echo $d;
    }
    public function action_login()
    {
        $this->_getItems();
        TPL::display($this->cptpl . 'menber_login.tpl');
    }
    public function action_register()
    {
        $this->_getItems();
        TPL::display($this->cptpl . 'menber_register.tpl');
    }
    public function action_ajaxlogin()
    {
        $accountname = $_REQUEST['nickname'];
        $password    = $_REQUEST['password'];
        $url         = "https://www.8cms.cn/api.php?a=member_login&accountname=$accountname&accountpwd=$password";
        $res         = $this->curl_get($url);
        $data        = json_decode($res, TRUE);
        if ($data['slay'] == '1') {
            $arr['member_id'] = $data['data']['adminid'];
            $arr['email']     = $data['data']['email'];
            $arr['phone']     = $data['data']['phone'];
            $arr['time']      = time();
            $model            = parent::model('plugin', 'am');
            $model->doAdd($arr);
        }
        echo $res;
    }
    public function action_install()
    {
        $plugin_id = $_POST['plugin_id'];
        $model     = parent::model('plugin', 'am');
        $data      = $model->checklogin();
        $user_id = $data['member_id'];
        $url     = "https://www.8cms.cn/api.php?a=download_plugin&plugin_id=$plugin_id&user_id=$user_id";
        $res       = $this->curl_get($url);
        $data_back = json_decode($res, TRUE);
        // print_r($data_back['list']);die;
        if (!empty($data_back)) {
            foreach ($data_back['list'] as $k => $v) {
                if ($data_back['filename'] == 'member') {
                    if ($k == 0) {
                        unset($data_back['list'][$k]);
                    }
                    if ($k == 1) {
                        unset($data_back['list'][$k]);
                    }
                }
                if (is_array($v)) {
                    $path = "." . $v['path'];
                    $url  = $v['url'];
                    $name = $v['name'];
                    if ($name == 'oa_config.txt') {
                        $name = 'oa.txt';
                    }
                    if ($name == 'sale_config.txt') {
                        $name = 'sale.txt';
                    }
                    // echo $path.'<br/>';
                    $this->getFile($url, $path, $name, 1);
                }
                //     echo $v['path'].'<br/>';
                //    echo $v['url'].'<br/>';
                //   echo $v['name'].'<br/>';
            }
            // print_r($data_back['list']);
            if ($data_back['filename'] == 'member') {
                $sql  = file_get_contents('./source/plugin/member/member_plugin.sql');
                $sqls = $this->sql_split($sql);
                if (is_array($sqls)) {
                    foreach ($sqls as $sql) {
                        $model = parent::model('plugin', 'am');
                        $res   = $model->insert($sql);
                    }
                }
            }
//            if ($data_back['filename'] == 'oa' || $data_back['filename'] == 'sale') {
//                if ($data_back['filename'] == 'oa') {
//                    $sql = file_get_contents('./source/plugin/oa/ljcms_oa.sql');
//                } elseif ($data_back['filename'] == 'sale') {
//                    $sql = file_get_contents('./source/plugin/sale/ljcms_sale.sql');
//                    $sql = trim($sql, "\xEF\xBB\xBF");
//                }
//                $sqls = $this->sql_split($sql);
//                if (is_array($sqls)) {
//                    foreach ($sqls as $sql) {
//                        $model = parent::model('plugin', 'am');
//                        $res   = $model->insert($sql);
//                    }
//                }
//            }
            $arr['pluginname'] = $data_back['data']['pluginname'];
            $arr['version']    = $data_back['data']['version'];
            $arr['pluginid']   = $data_back['data']['id'];
            $arr['status']     = 1;
            $arr['time']       = time();
            $arr['img']        = $data_back['data']['img'];
            $arr['filename']   = $data_back['data']['Foldername'];
            $result            = $model->addinstalllog($arr);
            if ($result) {
                $model->activePlugin($data_back['filename']);
                if ($data_back['filename'] == 'oa') {
                    $url = "oa.php";
                } else {
                    $url = "admincp.php?c=plugin&a=setting&plugin_id=" . $data_back['filename'];
                }
                $data = array(
                    'response' => 1,
                    'result'   => $url
                );
                echo json_encode($data);
                die;
            }
        } else {
            $data = array(
                'response' => 0,
                'result'   => '非法操作'
            );
            echo json_encode($data);
            die;
        }
    }
    public function action_member_out()
    {
        $model = parent::model('plugin', 'am');
        $data  = $model->memberout();
        if ($data == '1') {
            XHandle::halt("操作成功", $this->cpfile . '?c=plugin&a=shop', 0);
        }
    }
    public function action_inactive()
    {
        $this->_getItems();
        $this->_checkPlugin();
        $model = parent::model('plugin', 'am');
        if ($model->inactivePlugin($this->plugin_id)) {
            $this->log('plugin', "禁用id={$this->plugin_id}", 1);
            XHandle::halt("插件禁用成功<script>var leftiframeid = window.parent.document.getElementById('menu-frame');leftiframeid.src='" . $this->cpfile . "?c=frame&a=left&mod=app';</script>", $this->cpfile . '?c=plugin', 0);
        } else {
            $this->log('plugin', "禁用id={$this->plugin_id}", 0);
            XHandle::halt('插件禁用失败', '', 1);
        }
        unset($model);
    }
    public function action_ajax_inactive()
    {
        $plugin_id = $_REQUEST['plugin_id'];
        $model     = parent::model('plugin', 'am');
        $model->inactivePlugin($plugin_id);
    }
    public function action_del()
    {
        $this->_getItems();
        $this->_checkPlugin();
        $model = parent::model('plugin', 'am');
        $model->inactivePlugin($this->plugin_id);
        $plugin_path = BASE_ROOT . 'source/plugin/' . $this->plugin_id;
        parent::loadUtil('file');
        if (true === XFile::delDir($plugin_path)) {
            $model->delplugin($this->plugin_id);
            if ($this->plugin_id == "member") {
                $model->delcategory();
            }
            $this->log('plugin', "删除id={$this->plugin_id}", 1);
            XHandle::halt("插件删除成功<script>var leftiframeid = window.parent.document.getElementById('menu-frame');leftiframeid.src='" . $this->cpfile . "?c=frame&a=left&mod=app';</script>", $this->cpfile . '?c=plugin', 0);
        } else {
            $this->log('plugin', "删除id={$this->plugin_id}", 0);
            XHandle::halt('插件删除失败', '', 1);
        }
        unset($model);
    }
    public function action_setting()
    {
        $this->_getItems();
        $this->_validPlugin();
        $plugin_path = BASE_ROOT . './source/plugin/' . $this->plugin_id . '/admin.inc.php';
        if (file_exists($plugin_path)) {
            require_once($plugin_path);
            if (empty($this->do)) {
                $this->do = 'setting';
            }
            $function_name = $this->plugin_id . '_plugin_' . $this->do;
            if (function_exists($function_name)) {
                $var_array = array(
                    'plugin_event' => $function_name . '_event',
                    'plugin_name'  => $this->plugin_id,
                );
                TPL::assign($var_array);
                TPL::display($this->cptpl . 'plugin.tpl');
            } else {
                XHandle::halt('对不起，该插件没有' . $this->do . '方法！', '', 1);
            }
        } else {
            XHandle::halt('对不起，载入插件文件失败！', '', 1);
        }
    }
    public function action_save()
    {
        $this->_getItems();
        $this->_validPlugin();
        $plugin_path = BASE_ROOT . './source/plugin/' . $this->plugin_id . '/admin.inc.php';
        if (file_exists($plugin_path)) {
            require_once($plugin_path);
            if (empty($this->do)) {
                $this->do = 'setting';
            }
            $function_name = $this->plugin_id . '_plugin_' . $this->do;
            if (function_exists($function_name)) {
                call_user_func($function_name);
            } else {
                XHandle::halt('对不起，该插件没有' . $this->do . '方法！', '', 1);
            }
        } else {
            XHandle::halt('对不起，载入插件文件失败！', '', 1);
        }
    }
    private function _checkPlugin()
    {
        if (empty($this->plugin_id)) {
            XHandle::halt('对不起，插件名不能为空！', '', 1);
        }
        if (false === XValid::isPlugin($this->plugin_id)) {
            XHandle::halt('对不起，插件名错误或者不存在！', '', 1);
        }
    }
    private function _validPlugin()
    {
        if (empty($this->plugin_id)) {
            XHandle::halt('对不起，插件名不能为空！', '', 1);
        }
        if (false === XValid::isPlugin($this->plugin_id)) {
            XHandle::halt('对不起，插件名错误或者不存在！', '', 1);
        }
        parent::loadLib('option');
        $active_plugins = XOption::get('active_plugins');
        if (!is_array($active_plugins) || !in_array($this->plugin_id, $active_plugins)) {
            XHandle::halt('对不起，该插件不存在或者已禁用。', $this->cpfile . '?c=plugin', 4);
        }
    }
    public function checkmemberLogin()
    {
        $model = parent::model('plugin', 'am');
        $data  = $model->checklogin();
        if (!empty($data)) {
            return $data;
        } else {
            return 0;
        }
    }
    private function getFile($url, $save_dir = '', $filename = '', $type = 0)
    {
        if (trim($url) == '') {
            return false;
        }
        if (trim($save_dir) == '') {
            $save_dir = './';
        }
        if (0 !== strrpos($save_dir, '/')) {
            $save_dir .= '/';
        }
        //创建保存目录
        if (!file_exists($save_dir) && !mkdir($save_dir, 0777, true)) {
            return false;
        }
        //获取远程文件所采用的方法
        if ($type) {
            $ch      = curl_init();
            $timeout = 5;
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
            $content = curl_exec($ch);
            curl_close($ch);
        } else {
            ob_start();
            readfile($url);
            $content = ob_get_contents();
            ob_end_clean();
        }
        $size = strlen($content);
        //文件大小
        $filename = str_replace('txt', 'php', $filename);
        $fp2      = @fopen($save_dir . $filename, 'w');
        fwrite($fp2, $content);
        fclose($fp2);
        unset($content, $url);
        return array(
            'file_name' => $filename,
            'save_path' => $save_dir . $filename
        );
    }
    /**
     * 数据分离
     */
    private function sql_split($sql)
    {
        $sql          = str_replace("\r", "\n", $sql);
        $ret          = array();
        $num          = 0;
        $queriesarray = explode(";\n", trim($sql));
        unset ($sql);
        foreach ($queriesarray as $query) {
            $ret[$num] = '';
            $queries   = explode("\n", trim($query));
            $queries   = array_filter($queries);
            foreach ($queries as $query) {
                $str1 = substr($query, 0, 1);
                if ($str1 != '#' && $str1 != '-')
                    $ret[$num] .= $query;
            }
            $num++;
        }
        return ($ret);
    }
    private function curl_get($url)
    {
        //初始化
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true);  // 从证书中检查SSL加密算法是否存在
        $tmpInfo = curl_exec($curl);     //返回api的json对象
        //关闭URL请求
        curl_close($curl);
        return $tmpInfo;    //返回json对象
    }
    public function action_ajax_get_action()
    {
        $advContrl = get_class_methods('control');
        $html = '';
        foreach ($advContrl as $val) {
            if (strpos($val, 'action') !== false) {
                $html .= "<option value='" . $val . "'>" . $val . "</option>";
            } else {
            }
        }
        exit($html);
    }
}
?>
