审查视图

application/admin/controller/Addon.php 14.6 KB
Karson authored
1 2 3 4 5
<?php

namespace app\admin\controller;

use app\common\controller\Backend;
6
use fast\Http;
Karson authored
7 8
use think\addons\AddonException;
use think\addons\Service;
9
use think\Cache;
Karson authored
10
use think\Config;
11
use think\Db;
Karson authored
12 13 14 15 16
use think\Exception;

/**
 * 插件管理
 *
17
 * @icon   fa fa-cube
Karson authored
18
 * @remark 可在线安装、卸载、禁用、启用插件,同时支持添加本地插件。FastAdmin已上线插件商店 ,你可以发布你的免费或付费插件:<a href="https://www.fastadmin.net/store.html" target="_blank">https://www.fastadmin.net/store.html</a>
Karson authored
19 20 21 22
 */
class Addon extends Backend
{
    protected $model = null;
23
    protected $noNeedRight = ['get_table_list'];
Karson authored
24 25 26 27

    public function _initialize()
    {
        parent::_initialize();
cxb authored
28 29 30
        if (!$this->auth->isSuperAdmin() && in_array($this->request->action(), ['install', 'uninstall', 'local', 'upgrade'])) {
            $this->error(__('Access is allowed only to the super management group'));
        }
Karson authored
31 32 33 34 35 36 37 38
    }

    /**
     * 查看
     */
    public function index()
    {
        $addons = get_addon_list();
39
        foreach ($addons as $k => &$v) {
Karson authored
40 41
            $config = get_addon_config($v['name']);
            $v['config'] = $config ? 1 : 0;
42
            $v['url'] = str_replace($this->request->server('SCRIPT_NAME'), '', $v['url']);
Karson authored
43
        }
44
        $this->assignconfig(['addons' => $addons, 'api_url' => config('fastadmin.api_url'), 'faversion' => config('fastadmin.version')]);
Karson authored
45 46 47 48 49 50
        return $this->view->fetch();
    }

    /**
     * 配置
     */
51
    public function config($name = null)
Karson authored
52
    {
53
        $name = $name ? $name : $this->request->get("name");
54
        if (!$name) {
55
            $this->error(__('Parameter %s can not be empty', 'name'));
Karson authored
56
        }
57 58 59
        if (!preg_match("/^[a-zA-Z0-9]+$/", $name)) {
            $this->error(__('Addon name incorrect'));
        }
60
        if (!is_dir(ADDON_PATH . $name)) {
Karson authored
61 62 63 64
            $this->error(__('Directory not found'));
        }
        $info = get_addon_info($name);
        $config = get_addon_fullconfig($name);
65
        if (!$info) {
Karson authored
66
            $this->error(__('No Results were found'));
67
        }
68
        if ($this->request->isPost()) {
69
            $params = $this->request->post("row/a", [], 'trim');
70 71 72
            if ($params) {
                foreach ($config as $k => &$v) {
                    if (isset($params[$v['name']])) {
73 74 75 76 77 78
                        if ($v['type'] == 'array') {
                            $params[$v['name']] = is_array($params[$v['name']]) ? $params[$v['name']] : (array)json_decode($params[$v['name']], true);
                            $value = $params[$v['name']];
                        } else {
                            $value = is_array($params[$v['name']]) ? implode(',', $params[$v['name']]) : $params[$v['name']];
                        }
Karson authored
79 80 81
                        $v['value'] = $value;
                    }
                }
82
                try {
Karson authored
83 84
                    //更新配置文件
                    set_addon_fullconfig($name, $config);
85
                    Service::refresh();
Karson authored
86
                    $this->success();
87
                } catch (Exception $e) {
88
                    $this->error(__($e->getMessage()));
Karson authored
89 90 91 92
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
93 94 95 96 97 98 99 100
        $tips = [];
        foreach ($config as $index => &$item) {
            if ($item['name'] == '__tips__') {
                $tips = $item;
                unset($config[$index]);
            }
        }
        $this->view->assign("addon", ['info' => $info, 'config' => $config, 'tips' => $tips]);
101 102 103
        $configFile = ADDON_PATH . $name . DS . 'config.html';
        $viewFile = is_file($configFile) ? $configFile : '';
        return $this->view->fetch($viewFile);
Karson authored
104 105 106 107 108 109 110 111
    }

    /**
     * 安装
     */
    public function install()
    {
        $name = $this->request->post("name");
112 113
        $force = (int)$this->request->post("force");
        if (!$name) {
Karson authored
114 115
            $this->error(__('Parameter %s can not be empty', 'name'));
        }
116 117 118
        if (!preg_match("/^[a-zA-Z0-9]+$/", $name)) {
            $this->error(__('Addon name incorrect'));
        }
119
        try {
Karson authored
120 121
            $uid = $this->request->post("uid");
            $token = $this->request->post("token");
122 123 124 125 126 127 128 129 130
            $version = $this->request->post("version");
            $faversion = $this->request->post("faversion");
            $extend = [
                'uid'       => $uid,
                'token'     => $token,
                'version'   => $version,
                'faversion' => $faversion
            ];
            Service::install($name, $force, $extend);
Karson authored
131 132
            $info = get_addon_info($name);
            $info['config'] = get_addon_config($name) ? 1 : 0;
133
            $info['state'] = 1;
Karson authored
134
            $this->success(__('Install successful'), null, ['addon' => $info]);
135
        } catch (AddonException $e) {
136
            $this->result($e->getData(), $e->getCode(), __($e->getMessage()));
137
        } catch (Exception $e) {
138
            $this->error(__($e->getMessage()), $e->getCode());
Karson authored
139 140 141 142 143 144 145 146 147
        }
    }

    /**
     * 卸载
     */
    public function uninstall()
    {
        $name = $this->request->post("name");
148
        $force = (int)$this->request->post("force");
149
        $droptables = (int)$this->request->post("droptables");
150
        if (!$name) {
Karson authored
151 152
            $this->error(__('Parameter %s can not be empty', 'name'));
        }
153 154 155
        if (!preg_match("/^[a-zA-Z0-9]+$/", $name)) {
            $this->error(__('Addon name incorrect'));
        }
156 157 158 159 160
        //只有开启调试且为超级管理员才允许删除相关数据库
        $tables = [];
        if ($droptables && Config::get("app_debug") && $this->auth->isSuperAdmin()) {
            $tables = get_addon_tables($name);
        }
161
        try {
Karson authored
162
            Service::uninstall($name, $force);
163
            if ($tables) {
164
                $prefix = Config::get('database.prefix');
165 166
                //删除插件关联表
                foreach ($tables as $index => $table) {
167 168 169 170
                    //忽略非插件标识的表名
                    if (!preg_match("/^{$prefix}{$name}/", $table)) {
                        continue;
                    }
171 172 173
                    Db::execute("DROP TABLE IF EXISTS `{$table}`");
                }
            }
Karson authored
174
            $this->success(__('Uninstall successful'));
175
        } catch (AddonException $e) {
176
            $this->result($e->getData(), $e->getCode(), __($e->getMessage()));
177
        } catch (Exception $e) {
178
            $this->error(__($e->getMessage()));
Karson authored
179 180 181 182 183 184 185 186 187 188
        }
    }

    /**
     * 禁用启用
     */
    public function state()
    {
        $name = $this->request->post("name");
        $action = $this->request->post("action");
189 190
        $force = (int)$this->request->post("force");
        if (!$name) {
Karson authored
191 192
            $this->error(__('Parameter %s can not be empty', 'name'));
        }
193 194 195
        if (!preg_match("/^[a-zA-Z0-9]+$/", $name)) {
            $this->error(__('Addon name incorrect'));
        }
196
        try {
Karson authored
197 198 199
            $action = $action == 'enable' ? $action : 'disable';
            //调用启用、禁用的方法
            Service::$action($name, $force);
200
            Cache::rm('__menu__');
Karson authored
201
            $this->success(__('Operate successful'));
202
        } catch (AddonException $e) {
203
            $this->result($e->getData(), $e->getCode(), __($e->getMessage()));
204
        } catch (Exception $e) {
205
            $this->error(__($e->getMessage()));
Karson authored
206 207 208 209 210 211 212 213 214 215 216 217
        }
    }

    /**
     * 本地上传
     */
    public function local()
    {
        Config::set('default_return_type', 'json');

        $file = $this->request->file('file');
        $addonTmpDir = RUNTIME_PATH . 'addons' . DS;
218
        if (!is_dir($addonTmpDir)) {
Karson authored
219 220 221
            @mkdir($addonTmpDir, 0755, true);
        }
        $info = $file->rule('uniqid')->validate(['size' => 10240000, 'ext' => 'zip'])->move($addonTmpDir);
222
        if ($info) {
Karson authored
223 224 225
            $tmpName = substr($info->getFilename(), 0, stripos($info->getFilename(), '.'));
            $tmpAddonDir = ADDON_PATH . $tmpName . DS;
            $tmpFile = $addonTmpDir . $info->getSaveName();
226
            try {
Karson authored
227
                Service::unzip($tmpName);
228
                unset($info);
Karson authored
229 230
                @unlink($tmpFile);
                $infoFile = $tmpAddonDir . 'info.ini';
231
                if (!is_file($infoFile)) {
Karson authored
232 233 234 235 236
                    throw new Exception(__('Addon info file was not found'));
                }

                $config = Config::parse($infoFile, '', $tmpName);
                $name = isset($config['name']) ? $config['name'] : '';
237
                if (!$name) {
Karson authored
238 239
                    throw new Exception(__('Addon info file data incorrect'));
                }
240 241 242
                if (!preg_match("/^[a-zA-Z0-9]+$/", $name)) {
                    throw new Exception(__('Addon name incorrect'));
                }
Karson authored
243 244

                $newAddonDir = ADDON_PATH . $name . DS;
245
                if (is_dir($newAddonDir)) {
Karson authored
246 247 248 249 250
                    throw new Exception(__('Addon already exists'));
                }

                //重命名插件文件夹
                rename($tmpAddonDir, $newAddonDir);
251
                try {
Karson authored
252 253
                    //默认禁用该插件
                    $info = get_addon_info($name);
254
                    if ($info['state']) {
Karson authored
255 256 257 258 259 260
                        $info['state'] = 0;
                        set_addon_info($name, $info);
                    }

                    //执行插件的安装方法
                    $class = get_addon_class($name);
261
                    if (class_exists($class)) {
Karson authored
262 263 264 265 266 267 268 269 270
                        $addon = new $class();
                        $addon->install();
                    }

                    //导入SQL
                    Service::importsql($name);

                    $info['config'] = get_addon_config($name) ? 1 : 0;
                    $this->success(__('Offline installed tips'), null, ['addon' => $info]);
271
                } catch (Exception $e) {
Karson authored
272
                    @rmdirs($newAddonDir);
273
                    throw new Exception(__($e->getMessage()));
Karson authored
274
                }
275
            } catch (Exception $e) {
276
                unset($info);
Karson authored
277 278
                @unlink($tmpFile);
                @rmdirs($tmpAddonDir);
279
                $this->error(__($e->getMessage()));
Karson authored
280
            }
281
        } else {
Karson authored
282
            // 上传失败获取错误信息
283
            $this->error(__($file->getError()));
Karson authored
284 285 286 287
        }
    }

    /**
288 289 290 291 292
     * 更新插件
     */
    public function upgrade()
    {
        $name = $this->request->post("name");
293
        $addonTmpDir = RUNTIME_PATH . 'addons' . DS;
294
        if (!$name) {
295 296
            $this->error(__('Parameter %s can not be empty', 'name'));
        }
297 298 299
        if (!preg_match("/^[a-zA-Z0-9]+$/", $name)) {
            $this->error(__('Addon name incorrect'));
        }
300 301 302
        if (!is_dir($addonTmpDir)) {
            @mkdir($addonTmpDir, 0755, true);
        }
303
        try {
304 305 306 307 308 309 310 311 312 313 314 315
            $uid = $this->request->post("uid");
            $token = $this->request->post("token");
            $version = $this->request->post("version");
            $faversion = $this->request->post("faversion");
            $extend = [
                'uid'       => $uid,
                'token'     => $token,
                'version'   => $version,
                'faversion' => $faversion
            ];
            //调用更新的方法
            Service::upgrade($name, $extend);
316
            Cache::rm('__menu__');
317
            $this->success(__('Operate successful'));
318
        } catch (AddonException $e) {
319
            $this->result($e->getData(), $e->getCode(), __($e->getMessage()));
320
        } catch (Exception $e) {
321
            $this->error(__($e->getMessage()));
Karson authored
322 323 324 325 326 327 328 329
        }
    }

    /**
     * 已装插件
     */
    public function downloaded()
    {
330 331 332
        $offset = (int)$this->request->get("offset");
        $limit = (int)$this->request->get("limit");
        $filter = $this->request->get("filter");
333 334
        $search = $this->request->get("search");
        $search = htmlspecialchars(strip_tags($search));
335
        $onlineaddons = Cache::get("onlineaddons");
336
        if (!is_array($onlineaddons) && config('fastadmin.api_url')) {
337
            $onlineaddons = [];
338 339 340 341
            $result = Http::sendRequest(config('fastadmin.api_url') . '/addon/index', [], 'GET', [
                CURLOPT_HTTPHEADER => ['Accept-Encoding:gzip'],
                CURLOPT_ENCODING   => "gzip"
            ]);
342
            if ($result['ret']) {
343
                $json = (array)json_decode($result['msg'], true);
344 345 346 347 348 349 350 351
                $rows = isset($json['rows']) ? $json['rows'] : [];
                foreach ($rows as $index => $row) {
                    $onlineaddons[$row['name']] = $row;
                }
            }
            Cache::set("onlineaddons", $onlineaddons, 600);
        }
        $filter = (array)json_decode($filter, true);
Karson authored
352 353
        $addons = get_addon_list();
        $list = [];
354
        foreach ($addons as $k => $v) {
355
            if ($search && stripos($v['name'], $search) === false && stripos($v['intro'], $search) === false) {
356
                continue;
357
            }
358
359
            if (isset($onlineaddons[$v['name']])) {
360
                $v = array_merge($v, $onlineaddons[$v['name']]);
361 362 363 364 365 366 367
            } else {
                $v['category_id'] = 0;
                $v['flag'] = '';
                $v['banner'] = '';
                $v['image'] = '';
                $v['donateimage'] = '';
                $v['demourl'] = '';
368
                $v['price'] = __('None');
369 370
                $v['screenshots'] = [];
                $v['releaselist'] = [];
371
            }
372
            $v['url'] = addon_url($v['name']);
373
            $v['url'] = str_replace($this->request->server('SCRIPT_NAME'), '', $v['url']);
374
            $v['createtime'] = filemtime(ADDON_PATH . $v['name']);
375 376 377
            if ($filter && isset($filter['category_id']) && is_numeric($filter['category_id']) && $filter['category_id'] != $v['category_id']) {
                continue;
            }
Karson authored
378 379
            $list[] = $v;
        }
380
        $total = count($list);
381
        if ($limit) {
382 383
            $list = array_slice($list, $offset, $limit);
        }
384
        $result = array("total" => $total, "rows" => $list);
Karson authored
385 386 387 388

        $callback = $this->request->get('callback') ? "jsonp" : "json";
        return $callback($result);
    }
389 390 391 392 393 394 395 396

    /**
     * 获取插件相关表
     */
    public function get_table_list()
    {
        $name = $this->request->post("name");
        $tables = get_addon_tables($name);
397 398 399 400 401 402 403 404
        $prefix = Config::get('database.prefix');
        foreach ($tables as $index => $table) {
            //忽略非插件标识的表名
            if (!preg_match("/^{$prefix}{$name}/", $table)) {
                unset($tables[$index]);
            }
        }
        $tables = array_values($tables);
405 406
        $this->success('', null, ['tables' => $tables]);
    }
Karson authored
407
}