审查视图

application/admin/library/traits/Backend.php 16.2 KB
Karson authored
1 2 3 4
<?php

namespace app\admin\library\traits;
5 6 7 8 9
use app\admin\library\Auth;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
10
use think\Db;
11
use think\Exception;
12 13
use think\exception\PDOException;
use think\exception\ValidateException;
14
Karson authored
15 16 17 18
trait Backend
{

    /**
19 20 21 22
     * 排除前台提交过来的字段
     * @param $params
     * @return array
     */
23
    protected function preExcludeFields($params)
24 25 26
    {
        if (is_array($this->excludeFields)) {
            foreach ($this->excludeFields as $field) {
27
                if (key_exists($field, $params)) {
28 29 30 31
                    unset($params[$field]);
                }
            }
        } else {
32
            if (key_exists($this->excludeFields, $params)) {
33 34 35 36 37 38 39 40
                unset($params[$this->excludeFields]);
            }
        }
        return $params;
    }


    /**
Karson authored
41 42 43 44 45 46
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
47
        if ($this->request->isAjax()) {
Karson authored
48
            //如果发送的来源是Selectpage,则转发到Selectpage
49
            if ($this->request->request('keyField')) {
Karson authored
50 51 52 53
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
54 55 56
                ->where($where)
                ->order($sort, $order)
                ->count();
Karson authored
57 58

            $list = $this->model
59 60 61 62
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
Karson authored
63
Karson authored
64
            $list = collection($list)->toArray();
Karson authored
65 66 67 68 69 70 71 72 73 74 75 76 77 78
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 回收站
     */
    public function recyclebin()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
79
        if ($this->request->isAjax()) {
Karson authored
80 81
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
82 83 84 85
                ->onlyTrashed()
                ->where($where)
                ->order($sort, $order)
                ->count();
Karson authored
86 87

            $list = $this->model
88 89 90 91 92
                ->onlyTrashed()
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
Karson authored
93 94 95 96 97 98 99 100 101 102 103 104 105

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
106
        if ($this->request->isPost()) {
Karson authored
107
            $params = $this->request->post("row/a");
108
            if ($params) {
109 110
                $params = $this->preExcludeFields($params);
111
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
Karson authored
112 113
                    $params[$this->dataLimitField] = $this->auth->id;
                }
114 115
                $result = false;
                Db::startTrans();
116
                try {
Karson authored
117
                    //是否采用模型验证
118
                    if ($this->modelValidate) {
119
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
120
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
Karson authored
121 122 123
                        $this->model->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
124 125 126 127 128 129
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
Karson authored
130
                    $this->error($e->getMessage());
131 132
                } catch (Exception $e) {
                    Db::rollback();
133
                    $this->error($e->getMessage());
Karson authored
134
                }
135 136 137 138 139
                if ($result) {
                    $this->success();
                } else {
                    $this->error();
                }
Karson authored
140 141 142 143 144 145 146 147 148
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
149
    public function edit($ids = null)
Karson authored
150 151
    {
        $row = $this->model->get($ids);
152
        if (!$row) {
Karson authored
153
            $this->error(__('No Results were found'));
154
        }
Karson authored
155
        $adminIds = $this->getDataLimitAdminIds();
156 157
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
Karson authored
158 159 160
                $this->error(__('You have no permission'));
            }
        }
161
        if ($this->request->isPost()) {
Karson authored
162
            $params = $this->request->post("row/a");
163
            if ($params) {
164
                $params = $this->preExcludeFields($params);
165 166
                $result = false;
                Db::startTrans();
167
                try {
Karson authored
168
                    //是否采用模型验证
169
                    if ($this->modelValidate) {
170 171
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
Karson authored
172 173 174
                        $row->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
175 176 177 178 179 180
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
Karson authored
181
                    $this->error($e->getMessage());
182 183
                } catch (Exception $e) {
                    Db::rollback();
184
                    $this->error($e->getMessage());
Karson authored
185
                }
186 187 188 189 190
                if ($result) {
                    $this->success();
                } else {
                    $this->error();
                }
Karson authored
191 192 193 194 195 196 197 198 199 200 201 202
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
203
        if ($ids) {
Karson authored
204 205
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
206
            if (is_array($adminIds)) {
207
                $this->model->where($this->dataLimitField, 'in', $adminIds);
Karson authored
208 209
            }
            $list = $this->model->where($pk, 'in', $ids)->select();
210
Karson authored
211
            $count = 0;
212 213 214 215 216 217 218 219 220 221 222 223
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
Karson authored
224
            }
225
            if ($count) {
Karson authored
226
                $this->success();
227
            } else {
Karson authored
228 229 230 231 232 233 234 235 236 237 238 239 240
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 真实删除
     */
    public function destroy($ids = "")
    {
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
241
        if (is_array($adminIds)) {
242
            $this->model->where($this->dataLimitField, 'in', $adminIds);
Karson authored
243
        }
244
        if ($ids) {
Karson authored
245 246 247
            $this->model->where($pk, 'in', $ids);
        }
        $count = 0;
248 249 250 251 252 253 254 255 256 257 258 259 260
        Db::startTrans();
        try {
            $list = $this->model->onlyTrashed()->select();
            foreach ($list as $k => $v) {
                $count += $v->delete(true);
            }
            Db::commit();
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
Karson authored
261
        }
262
        if ($count) {
Karson authored
263
            $this->success();
264
        } else {
Karson authored
265 266 267 268 269 270 271 272 273 274 275 276
            $this->error(__('No rows were deleted'));
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 还原
     */
    public function restore($ids = "")
    {
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
277
        if (is_array($adminIds)) {
Karson authored
278 279
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
280
        if ($ids) {
Karson authored
281 282
            $this->model->where($pk, 'in', $ids);
        }
283
        $count = 0;
284 285 286 287 288 289 290 291 292 293 294 295 296
        Db::startTrans();
        try {
            $list = $this->model->onlyTrashed()->select();
            foreach ($list as $index => $item) {
                $count += $item->restore();
            }
            Db::commit();
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
297 298
        }
        if ($count) {
Karson authored
299 300 301 302 303 304 305 306 307 308 309
            $this->success();
        }
        $this->error(__('No rows were updated'));
    }

    /**
     * 批量更新
     */
    public function multi($ids = "")
    {
        $ids = $ids ? $ids : $this->request->param("ids");
310 311
        if ($ids) {
            if ($this->request->has('params')) {
Karson authored
312
                parse_str($this->request->post("params"), $values);
313 314
                $values = array_intersect_key($values, array_flip(is_array($this->multiFields) ? $this->multiFields : explode(',', $this->multiFields)));
                if ($values || $this->auth->isSuperAdmin()) {
Karson authored
315
                    $adminIds = $this->getDataLimitAdminIds();
316
                    if (is_array($adminIds)) {
Karson authored
317 318
                        $this->model->where($this->dataLimitField, 'in', $adminIds);
                    }
319
                    $count = 0;
320 321 322 323 324 325 326 327 328 329 330 331 332
                    Db::startTrans();
                    try {
                        $list = $this->model->where($this->model->getPk(), 'in', $ids)->select();
                        foreach ($list as $index => $item) {
                            $count += $item->allowField(true)->isUpdate(true)->save($values);
                        }
                        Db::commit();
                    } catch (PDOException $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    } catch (Exception $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
Karson authored
333
                    }
334 335 336
                    if ($count) {
                        $this->success();
                    } else {
Karson authored
337 338
                        $this->error(__('No rows were updated'));
                    }
339
                } else {
Karson authored
340 341 342 343 344 345 346 347 348 349 350 351 352
                    $this->error(__('You have no permission'));
                }
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 导入
     */
    protected function import()
    {
        $file = $this->request->request('file');
353
        if (!$file) {
Karson authored
354 355 356
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
357
        if (!is_file($filePath)) {
Karson authored
358 359
            $this->error(__('No results were found'));
        }
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, "w");
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding != 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
Karson authored
380
                }
381
                $n++;
Karson authored
382
            }
383 384 385 386 387 388 389
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
Karson authored
390 391
        }
392 393 394
        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';
Karson authored
395 396 397 398
        $table = $this->model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
399 400
        foreach ($list as $k => $v) {
            if ($importHeadType == 'comment') {
401
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
402
            } else {
403 404
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
Karson authored
405 406
        }
407
        //加载文件
Karson authored
408
        $insert = [];
409 410 411
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
Karson authored
412
            }
413 414 415 416 417 418 419 420 421
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields = [];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[] = $val;
Karson authored
422 423
                }
            }
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440

            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : $val;
                }
                $row = [];
                $temp = array_combine($fields, $values);
                foreach ($temp as $k => $v) {
                    if (isset($fieldArr[$k]) && $k !== '') {
                        $row[$fieldArr[$k]] = $v;
                    }
                }
                if ($row) {
                    $insert[] = $row;
                }
Karson authored
441
            }
442 443
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
Karson authored
444
        }
445
        if (!$insert) {
Karson authored
446 447
            $this->error(__('No rows were updated'));
        }
448
449
        try {
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
            //是否包含admin_id字段
            $has_admin_id = false;
            foreach ($fieldArr as $name => $key) {
                if ($key == 'admin_id') {
                    $has_admin_id = true;
                    break;
                }
            }
            if ($has_admin_id) {
                $auth = Auth::instance();
                foreach ($insert as &$val) {
                    if (!isset($val['admin_id']) || empty($val['admin_id'])) {
                        $val['admin_id'] = $auth->isLogin() ? $auth->id : 0;
                    }
                }
            }
Karson authored
466
            $this->model->saveAll($insert);
467
        } catch (PDOException $exception) {
468 469 470 471 472
            $msg = $exception->getMessage();
            if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
                $msg = "导入失败,包含【{$matches[1]}】的记录已存在";
            };
            $this->error($msg);
473 474
        } catch (\Exception $e) {
            $this->error($e->getMessage());
Karson authored
475 476 477 478 479
        }

        $this->success();
    }
}