<?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 $_comeurl = NUll;
    private $_urlitem = NULL;

    private $tid = NULL;

    private $scatid = NULL;

    private $stitle = NULL;

    private $modtitle = NULL;

    private $modalias = NULL;



    public function action_run() {
        $model = parent::model('language', 'am');
        list($total, $data) = $model->getList(array('page'=>$this->page, 'pagesize'=>$this->pagesize, 'searchsql'=>''));
        $url = XRequest::getPhpSelf();
        $url .= '?c=language&'.$this->_urlitem;
      //  print_r($data);
        $var_array = array(
            'page'=>$this->page,
            'nextpage'=>$this->page+1,
            'prepage'=>$this->page-1,
            'pagecount'=>ceil($total/$this->pagesize),
            'pagesize'=>$this->pagesize,
            'total'=>$total,
            'showpage'=>XPage::admin($total, $this->pagesize, $this->page, $url, 10),
            'data'=>$data,
        );
        unset($model);
        TPL::assign($var_array);
        TPL::display($this->cptpl.'language.tpl');
    }


    public function action_add() {
        $url = 'https://www.8cms.cn/api.php?a=lang_list';
        $res = $this->curl_get($url);
        $data = json_decode($res, TRUE);
        $var_array = array(
            'data'=>$data['data']
        );
        TPL::assign($var_array);
        TPL::display($this->cptpl.'language.tpl');
    }
    public function action_ajaxinfo(){
        $id= $_REQUEST['id'];
        $url = 'https://www.8cms.cn/api.php?a=lang_info&lang_id='.$id;
        $res = $this->curl_get($url);
        $data = json_decode($res, TRUE);
        $arr['response']=$data['slay'];
        $arr['result']=$data['msg'];
        $arr['data']=$data['data'];
        echo json_encode($arr);die;
    }
    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_edit() {
        $id = XRequest::getInt('id');
        $this->_validID($id);
        $model = parent::model('language', 'am');
        $data = $model->getData($id);
        if (empty($data)) {
            XHandle::halt('对不起，读取数据不存在！', '', 1);
        }
        else {

            $var_array = array(
                'data'=>$data,
                'id'=>$id,
                'page'=>$this->page,
                'comeurl'=>$this->_comeurl,
                'modtitle'=>$this->modtitle,
                'tid'=>$this->tid,
                'timeline'=>time(),
            );
            TPL::assign($var_array);
            TPL::display($this->cptpl.'language.tpl');
        }
        unset($model);
    }


    public function action_saveadd() {
        list($args, $attrs) = $this->_validAdd();
        $arr['name']=$args['lang_name'];
        $arr['lang']=$args['lang_sign'];
        $arr['fileurl']=$args['fileurl'];
        $arr['sort']=$args['sort'];
        $model = parent::model('language', 'am');
        $result = $model->doAdd($arr, $attrs);
        unset($model);
        if (true === $result) {
            $url='https://8cms.com/'.$arr['fileurl'];
            $path='data/attachment/language';
            $name='language_'.$arr['lang'].'.txt';
            $this->getFile($url, $path, $name, 1);
            $this->log('language_add', '', 1);
            XHandle::halt('添加成功', $this->cpfile.'?c=language', 0);
        }
        else {
            $this->log('language_add', '', 0);
            XHandle::halt('添加失败', '', 1);
        }
    }
    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', 'ini', $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
        );
    }

    public function action_saveedit() {
        list($id, $args, $attrs) = $this->_validEdit();
        $model = parent::model('language', 'am');
    //    print_r($args);die;
        $result = $model->doEdit($id, $args, $attrs);
        unset($model);
        if (true === $result) {
            $this->log('language_edit', "id={$id}", 1);
            XHandle::halt('编辑成功', $this->cpfile.'?c=language', 0);
        }
        else {
            $this->log('language_edit', "id={$id}", 0);
            XHandle::halt('编辑失败', '', 1);
        }
    }


    public function action_del() {
        $array_id = XRequest::getArray('id');
        $this->_validID($array_id);
        $model = parent::model('language', 'am');
        for($ii=0; $ii<count($array_id); $ii++){
            $id = intval($array_id[$ii]);
            $result = $model->doDel($id);
        }
        unset($model);
        if (true === $result) {
            $this->log('language_del', "id={$array_id}", 1);
            XHandle::halt('删除成功', $this->cpfile.'?c=language', 0);
        }
        else {
            $this->log('language_del', "id={$array_id}", 0);
            XHandle::halt('删除失败', '', 1);
        }

    }


    public function action_update() {
        $this->checkAuth('hr_edit');
        $args = XRequest::getGpc(array('id', 'type'));
        $model = parent::model('hr', 'am');
        $model->doUpdate(intval($args['id']), trim($args['type']));
        unset($model);
    }


    private function _validAdd() {
        $args = XRequest::getGpc(array(
            'lang_name','lang_sign','sort','fileurl'

        ));
        if (empty($args['lang_name'])) {
            XHandle::halt('请填写语言名称', '', 1);
        }
        if (empty($args['lang_sign'])) {
            XHandle::halt('请填写语言标识', '', 1);
        }

        return array($args, $this->_getAttrValue());
    }


    private function _validEdit() {
        $id = XRequest::getInt('id');
        $args = XRequest::getGpc(array(
            'lang_name','lang_sign','sort','flag','fileurl'
        ));
        if ($id<1) {
            XHandle::halt('ID丢失', '', 1);
        }
        if (empty($args['lang_name'])) {
            XHandle::halt('请填写语言名称', '', 1);
        }
        if (empty($args['lang_sign'])) {
            XHandle::halt('请填写语言标识', '', 1);
        }
        return array($id, $args, $this->_getAttrValue());
    }

    private function _validID($id) {
        if (empty($id)) {
            XHandle::halt('ID丢失，请选择要操作的ID', '', 1);
        }
    }


    private function _getAttrValue() {
        $array = array();

        $m = parent::model('modattr', 'am');
        $attrdata = $m->getAttrList($this->modalias, $this->tid);
        unset($m);
        foreach($attrdata as $key=>$value) {

            if ($value['inputtype'] == 'checkbox') {
                $arr = XRequest::getArray('attr_'.$value['aid']);
                $array_val = '';
                for($ii=0; $ii<count($arr); $ii++){
                    $array_val .= trim($arr[$ii]).',';
                }
                if (!empty($array_val)) {
                    $array_val = substr($array_val, 0, (strlen($array_val)-1));
                }
                $array[] = array(
                    'aid'=>$value['aid'],
                    'extvalue'=>$array_val,
                );
            }
            else {
                $array[] = array(
                    'aid'=>$value['aid'],
                    'extvalue'=>XRequest::getArgs('attr_'.$value['aid']),
                );
            }
        }
        return $array;
    }
}
?>
