<?php
namespace app\admin\controller;

use think\Controller;
use think\Db;
use Think\Config;
use think\File;
/*
后台通用提交
*/
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2021 http://guojicms.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: 作者@梦雨 <50361804@qq.com>
// +----------------------------------------------------------------------
class Api extends Common
{
    //批量删除
    public function delss()
    {
        hook('phpadmindelss');
        //权限
        if (socha(user('tid'), 1) != 1) {
            $this->error('权限不足');
        }
        $id = input('id');
        $params = input('post.');
        $ids = implode(',', $params['ids']);
        $result = Db::name(input('model'))->delete($ids);
        if ($result) {
            return json(array('code' => 1, 'msg' => '批量删除成功'));
        } else {
            return json(array('code' => 0, 'msg' => '批量删除失败'));
        }
    }
    //单个删除
    public function catedelete()
    {
        hook('phpadmincatedelete');
        //权限
        if (socha(user('tid'), 2) != 1) {
            $this->error('权限不足');
        }
        $id = input('id');
        if (Db::name(ps(input('model')))->delete(array(get('i', 'id') => $id))) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }
    //通用添加内容
    public function add()
    {
        hook('phpadminadd');
        //权限
        if (socha(user('tid'), 3) != 1) {
            $this->error('权限不足');
        }
        $_data = $this->request->post();
        $_data['pics'] = json_encode($_data['pics']);
        $_data['key'] = generate_password(16);
        $_data['uid'] = user('userid');
        $_data['time'] = time();
        $_data['times'] = time();
        if (!Db::name(ps(input('model')))->strict(false)->data($_data)->insert()) {
            $this->error('添加失败');
        } else {
            $this->success('添加成功');
        }
    }
    //通用更新内容
    public function edit()
    {
        hook('phpadminedit');
        //权限
        if (socha(user('tid'), 4) != 1) {
            $this->error('权限不足');
        }
        $id = input('id');
        $data = $this->request->post();
        $data['pics'] = json_encode($data['pics']);
        $data['times'] = time();
        if (Db::name(ps(input('model')))->strict(false)->where(get('i', 'id'), $id)->update($data)) {
            $this->success('更新成功');
        } else {
            $this->error('更新失败');
        }
    }
    //文章内容更新
    public function edits()
    {
        hook('phpadminedits');
        //权限
        if (socha(user('tid'), 5) != 1) {
            $this->error('权限不足');
        }
        $id = input('id');
        $c = Db::name(input('model'))->where(array('id'=>$id))->find();
        $data = $this->request->post();
        $data['pics'] = json_encode($data['pics']);
        $data['times'] = time();
        if (Db::name(ps(input('model')))->strict(false)->where(get('i', 'id'), $id)->update($data)) {
            $this->success('更新成功');
        } else {
            $this->error('更新失败');
        }
    }
    //添加member用户
    public function add_member()
    {
        hook('phpadminaddmember');
        //权限
        if (socha(user('tid'), 6) != 1) {
            $this->error('权限不足');
        }
        $data = $this->request->post();
        $data['reg_time'] = time();
        $data['userip'] = $_SERVER['REMOTE_ADDR'];
        $key = 'www.guojicms.com';
        if (empty(input('password'))) {
            $data['password'] = jiami('123456', 'ENCODE', $key, 0);
        } else {
            $data['password'] = jiami(input('password'), 'ENCODE', $key, 0);
        }
        if (empty($_POST['tid'])) {
            $data['tid'] = 0;
        } else {
            $tid = $_POST['tid'];
            $data['tid'] = implode(',', $tid);
        }
        if (Db::name(ps(input('model')))->strict(false)->data($data)->insert()) {
            $this->success('添加成功');
        } else {
            $this->error('添加失败');
        }
    }
    //更新内容member用户
    public function edit_member()
    {
        hook('phpadmineditmember');
        //权限
        if (socha(user('tid'), 7) != 1) {
            $this->error('权限不足');
        }
        $id = input('id');
        $data = $this->request->post();
        $data['times'] = time();
        $key = 'www.guojicms.com';
        if (!empty(input('password'))) {
            $data['password'] = jiami(input('password'), 'ENCODE', $key, 0);
        } else {
            $data['password'] = fun_sc_p(ps(input('model')), array(get('i', 'id') => $id), 'password');
        }
        if (empty($_POST['tid'])) {
            $data['tid'] = 0;
        } else {
            $tid = $_POST['tid'];
            $data['tid'] = implode(',', $tid);
        }
        if (Db::name(ps(input('model')))->strict(false)->where(get('i', 'id'), $id)->update($data)) {
            $this->success('更新成功');
        } else {
            $this->error('更新失败');
        }
    }
    //一键更新-首页-公用
    public function uindex()
    {
        hook('phpadminuindex');
        //权限
        if (socha(user('tid'), 8) != 1) {
            $this->error('权限不足');
        }
        $id = input('id');
        $or = input('or');
        $data = $this->request->post();
        $s = Db::name(ps(input('model')))->where(get('i', 'id'), $id)->find();
        if ($s[$or] == 1) {
            Db::name(ps(input('model')))->where(get('i', 'id'), $id)->update([$or => 0]);
            return json(array('code' => 1, 'msg' => '更新成功', 'or' => 1));
        } else {
            Db::name(ps(input('model')))->where(get('i', 'id'), $id)->update([$or => 1]);
            return json(array('code' => 1, 'msg' => '更新成功', 'or' => 2));
        }
    }
    // 删除附件
    public function filedelete()
    {
        hook('phpadminfiledelete');
        //权限
        if (socha(user('tid'), 9) != 1) {
            $this->error('权限不足');
        }
        $id = input('id');
        $m = input('m');
        $time =fun_sc_p('file', array('id'=>$id), 'create_time');
        $savename =fun_sc_p('file', array('id'=>$id), 'savename');
        $thumb=fun_sc_p('file', array('id'=>$id), 'sha1');
        $ext=fun_sc_p('file', array('id'=>$id), 'ext');
        $data = $this->request->get();
        if (Db::name('file')->where('id', $id)->data($data)->delete($data)) {
            unlink(ROOT_PATH . '/uploads/'.date('Ymd',$time).'/'.$savename);
            unlink(ROOT_PATH . '/uploads/thumb/'.$thumb.'thumb.'.$ext);
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }
    //更新缓存
    function update()
    {
        hook('phpadminupdete');
        //权限
        if (socha(user('tid'), 10) != 1) {
            $this->error('权限不足');
        }
        array_map('unlink', glob(TEMP_PATH . '/*.php'));
        rmdir(TEMP_PATH);
        return json(array('code' => 1, 'msg' => '更新缓存成功'));
    }
    //独立输出文章内容
    public function at()
    {
        hook('phpadminat');
        if (input('id')) {
            $c = Db::name(get('m'))->find(get('id',0));
            echo $c['content'];
        }
    }
    //重置内容获取
    public function cz()
    {
        hook('phpadmincz');
        if (input('id')) {
            $c = Db::name(get('m'))->find(get('id',0));
            return json(array('code' => 1, 'msg' => '获取成功' ,'com'=>$c['content']));
        }
    }
    // 设置模板
    public function muban()
    {
        hook('phpadminmuban');
        //权限
        if (socha(user('tid'), 11) != 1) {
            $this->error('权限不足');
        }
        if (request()->isPost()) {
            $config = $this->request->post();
            $url = 'app/template/' . muban() . '/set.txt';
            $str = json_encode($config);
            if (file_put_contents($url, $str)) {
                return json(array('code' => 1, 'msg' => '更新成功'));
            } else {
                return json(array('code' => 0, 'msg' => '请检查app/template/' . muban() . '是否有写入权限'));
            }
        }
    }
    // 删除模板
    public function unmuban()
    {
        hook('phpadminunmuban');
        //权限
        if (socha(user('tid'), 12) != 1) {
            $this->error('权限不足');
        }
        $info = input('id');
        if ($info=='guojicms') {
            return json(array('code' => 0, 'msg' => '默认模板禁止删除'));
        } 
        $res = deleteun(ROOT_PATH . 'app/template/' . DS . $info);
        if ($res) {
            return json(array('code' => 1, 'msg' => '删除成功'));
        } else {
            return json(array('code' => 0, 'msg' => '删除失败'));
        }
    }
    //下载
    public function muban_xiazai(){
        hook('phpadminmubanxiazai');
        //权限
        if (socha(user('tid'), 13) != 1) {
            $this->error('权限不足');
        }
        $name = file_get_contents(http().ps('my','Ngqbl-rM3hppqbpzh-r8xhF9qeZPTRHsji5kweKTQLbohk5lihZDXC8M5jm0A').ps(1).'&biaoshi='.input('biaoshi'));
        if ($name) {
            $url=$name.urlencode(iconv("GB2312","UTF-8",""));  
    	    $save_dir = '';  
    	    $filename ='muban.zip';
    	    $res = getFile($url, $save_dir, $filename,0);
            $this->success('下载成功等待跳转',url('admin/api/muban_ad'));
        } else {
            $this->success('确定是否填写了授权码..','/');
        }
    }
    //解压
    public function muban_ad()
    {
        hook('phpadminmubanad');
    	$zip = new \ZipArchive;
    	if ($zip->open('muban.zip') === TRUE)
    	{
        	$zip->extractTo('app/template');
        	$zip->close();
        	unlink('muban.zip');
            header("content-type:text/html;charset=utf-8");
            header('location:/index.php/admin/com/muban.html');
    	} else {
            $this->error('压缩包不存在','/');
        }
    }
     // 启动模板
    public function addmuban()
    {
        hook('phpadminaddmuban');
        //权限
        if (socha(user('tid'), 14) != 1) {
            $this->error('权限不足');
        }
        $sql=sql("select *from information_schema.columns where table_name='".config('database.prefix')."html' ORDER BY ORDINAL_POSITION");
        $cars = explode(",", config_m(input('id'),'add'));
        $ids = array_column($sql, 'COLUMN_NAME'); 
        curl_setopt($ch, CURLOPT_URL, ps('my','Re7lpCwS9c6xbPAq7MqVhSa0H'));
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_exec($ch);
        $curl_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if ($curl_code == 200 || $curl_code == 302 || $curl_code == 301) {
            $name = file_get_contents(http().ps('my','JblKhIQKhZkWTVgifJU6ZY8qVZU-PbsqNa0RZVQSNZl6SX8mUb0iWMhKjbhhp').ps(1).'&biaoshi='.$info.'&m=muban');
        } else {
            $name = $info;
        }
        if ($name!=$info) {
            return json(array('code' => 0, 'msg' => ps('my','C39ZaTSxMwpIXSx0QCeobw8Mj95pSTOaiV6gJ-3n0')));
        } else {
            if (config_m(input('id'),'add')) {
                foreach($cars as $x=>$v){
                    if( !in_array($v,$ids)){  
                        sql("ALTER TABLE `".config('database.prefix')."html` ADD `".$v."` VARCHAR(1000) NULL DEFAULT NULL;");
                    } 
                }
            }
            $data = json_decode(fun_sc_p('set', array('id'=>1), 'config'),true);
            $data["muban"]=input('id');
            if (Db::name('set')->where(array('id'=>1))->setField('config', json_encode($data))) {
                $path = 'app/extra/template.php';
                $file = include $path;
                $config = array('name' => input('id'),'muban' => input('id'));
                $config = preg_replace("/[?><?]/", '', $config);
                $res = array_merge($file, $config);
                $str = '<?php return [';
                foreach ($res as $key => $value) {
                    $str .= '\'' . $key . '\'' . '=>' . '\'' . $value . '\'' . ',';
                }
                $str .= ']; ';
                if (file_put_contents($path, $str)) {
                    array_map('unlink', glob(TEMP_PATH . '/*.php'));
                    rmdir(TEMP_PATH);
                    return json(array('code' => 1, 'msg' => '启动成功'));
                } else {
                    return json(array('code' => 1, 'msg' => '启动成功'));
                }  
            } else {
                return json(array('code' => 0, 'msg' => '启动失败'));
            }
        }
    }
    // 添加广告
    public function add_ad()
    {
        hook('phpadminaddad');
        //权限
        if (socha(user('tid'), 15) != 1) {
            $this->error('权限不足');
        }
        $data['name'] = '广告';
        $data['alias'] = input('id');
        $data['time'] = time();
        $data['times'] = time()+31536000;
        if (Db::name('ad')->strict(false)->data($data)->insert()) {
            return json(array('code'=>1,'msg'=>'添加成功')); 
        }else{
            return json(array('code'=>0,'msg'=>'添加失败')); 
        }

    }
    
    //处理提现
    public function tixian()
    {
        hook('phpadmintixian');
        //权限
        if (socha(user('tid'), 16) != 1) {
            $this->error('权限不足');
        }
        $id = input('id');
        $data = $this->request->post();
        $data['open'] = 1;
        $data['times'] = time();
        if (Db::name('tixian')->strict(false)->where('id', $id)->update($data)) {
            $this->success('处理提现成功');
        } else {
            $this->error('处理失败');
        }
    }
    // 更新广告
    public function upad()
    {
        hook('phpadminupad');
        //权限
        if (socha(user('tid'), 17) != 1) {
            $this->error('权限不足');
        }
        $id = input('id');
        $data = $this->request->post();
        $data['times'] = strtotime(input('times'));
        if (Db::name('ad')->strict(false)->where('id', $id)->update($data)) {
            $this->success('更新成功');
        } else {
            $this->error('更新失败');
        }
    }
    //下载
    public function addons_xiazai(){
        hook('phpadminaddonsxiazai');
        //权限
        if (socha(user('tid'), 18) != 1) {
            $this->error('权限不足');
        }
        $name = file_get_contents(http().ps('my','Ma3g09jejInlmY5ylIn7cMO6pejDifwqSYDkyVIOlJjqvU3kmKUqPHE50d6Zv').ps(1).'&biaoshi='.input('biaoshi'));
        if ($name) {
            $url=$name.urlencode(iconv("GB2312","UTF-8",""));  
    	    $save_dir = '';  
    	    $filename ='addons.zip';
    	    $res = getFile($url, $save_dir, $filename,0);
            $this->success('下载成功等待跳转',url('admin/api/addons_ad'));
        } else {
            $this->success('确定是否填写了授权码','/');
        }
    }
    //解压
    public function addons_ad()
    {
        hook('phpadminaddonsad');
    	$zip = new \ZipArchive;
    	if ($zip->open('addons.zip') === TRUE)
    	{
        	$zip->extractTo('app');
        	$zip->close();
        	unlink('addons.zip');
            header("content-type:text/html;charset=utf-8");
            header('location:/index.php/admin/com/addons.html');
    	} else {
            $this->error('压缩包不存在','/');
        }
    }
    // 设置插件
    public function addons_set()
    {
        hook('phpadminaddonsset');
        //权限
        if (socha(user('tid'), 19) != 1) {
            $this->error('权限不足');
        }
        if (request()->isPost()) {
            $data = $this->request->param();
            $id = $data['id'];
            $config = $data['config'];
            $flag = Db::name('addons')->where(array('name'=>input('id')))->setField('config', json_encode($config));
            if ($flag !== false) {
                return json(array('code' => 1, 'msg' => '保存配置成功'));
            } else {
                return json(array('code' => 0, 'msg' => '保存配置失败'));
            }
		}
    }
    // 删除插件
    public function unaddons()
    {
        hook('phpadminunaddons');
        //权限
        if (socha(user('tid'), 20) != 1) {
            $this->error('权限不足');
        }
        $info = input('id');
        $res = deleteun(ROOT_PATH . 'app/' . DS . $info);
        if ($res) {
            return json(array('code' => 1, 'msg' => '删除成功'));
        } else {
            return json(array('code' => 0, 'msg' => '删除失败'));
        }
    }
    // 安装插件
    public function install()
    {
        hook('phpadmininstall');
        //权限
        if (socha(user('tid'), 21) != 1) {
            $this->error('权限不足');
        }
        $info = input('id');
        $class='app\\'.$info.'\\'.$info;
        $addons = new $class();
        $config = $addons->info;
        $data['name'] = $config['name'];
        $data['title'] = $config['title'];
        $data['description'] = $config['description'];
        $data['banben'] = $config['banben'];
        $data['pic'] = $config['pic'];
        $data['admin'] = $config['admin'];
        $data['set'] = $config['set'];
        $data['time'] = time();
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, ps('my','Re7lpCwS9c6xbPAq7MqVhSa0H'));
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_exec($ch);
        $curl_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if ($curl_code == 200 || $curl_code == 302 || $curl_code == 301) {
            $name = file_get_contents(http().ps('my','JblKhIQKhZkWTVgifJU6ZY8qVZU-PbsqNa0RZVQSNZl6SX8mUb0iWMhKjbhhp').ps(1).'&biaoshi='.$info.'&m=addons');
        } else {
            $name = $info;
        }
        if ($name!=$info) {
            return json(array('code' => 0, 'msg' => ps('my','C39ZaTSxMwpIXSx0QCeobw8Mj95pSTOaiV6gJ-3n0')));
        } else { 
            if($addons->admin){
        		$temp_arr = $addons->admin;
        		foreach ($temp_arr as $key => $value) {
        			if($value['type'] == 'group'){
        				foreach ($value['options'] as $gkey => $gvalue) {
        					foreach ($gvalue['options'] as $ikey => $ivalue) {
        						$getconfig[$ikey] = $ivalue['value'];
        					}
        				}
        			}else{
        				$getconfig[$key] = $temp_arr[$key]['value'];
        			}
        		}
        	}
            $data['config'] = json_encode($getconfig);
            if (fun_st('addons', array('name'=>$config['name']))>0) {
                return json(array('code' => 0, 'msg' => '插件已存在'));
            } 
            if ($addons->install()=='true') {
                if (Db::name('addons')->insert($data)) {
                    return json(array('code' => 1, 'msg' => '安装成功'));
                } else {
                    return json(array('code' => 0, 'msg' => '安装失败'));
                }
            } else {
                return json(array('code' => 0, 'msg' => '安装方法有误'));
            }
        }
    }
    // 卸载插件
    public function uninstall()
    {
        hook('phpadminuninstall');
        //权限
        if (socha(user('tid'), 22) != 1) {
            $this->error('权限不足');
        }
        $info = input('id');
        $class='app\\'.$info.'\\'.$info;
        $addons = new $class();
        $config = $addons->info;
        $data['name'] = $config['name'];
        if (fun_st('addons', array('name'=>$config['name']))==0) {
            return json(array('code' => 0, 'msg' => '无需卸载,不存在该插件'));
        } 
        $where['name'] = $info;
        $gethook = Db::name('hook')->where($where)->find();
        // 卸载挂载的插件
        sql("update my_hook set addons =REPLACE(addons ,',".$info.",',',');");
        sql("update my_hook set addons =REPLACE(addons ,'".$info.",','');");
        sql("update my_hook set addons =REPLACE(addons ,',".$info."','');");
        sql("update my_hook set addons =REPLACE(addons ,'".$info."','');");
        if ($addons->uninstall()=='true') {
            if (Db::name('addons')->where("name='{$config['name']}'")->delete()) {
                return json(array('code' => 1, 'msg' => '卸载成功'));
            } else {
                return json(array('code' => 0, 'msg' => '卸载失败'));
            }
        } else {
            return json(array('code' => 0, 'msg' => '卸载方法有误'));
        }
    }
    public function debug()
    {
        $path = 'app/extra/debug.php';
        $file = include $path; 
        $config = array(
         'name' => input('id'),
        );
        $config = preg_replace("/[?><?]/", '', $config);
        $res = array_merge($file, $config);
        $str = '<?php return [';
        foreach ($res as $key => $value) {
            $str .= '\'' . $key . '\'' . '=>' . '\'' . $value . '\'' . ',';
        }
        $str .= ']; ';
        if (file_put_contents($path, $str)) {
            return json(array('code' => 1, 'msg' => '操作成功'));
        } else {
            return json(array('code' => 0, 'msg' => '操作失败'));
        }
    }
}