文件
chengduzhongchuliang/application/common/controller/GranaryBackend.php

70 行
3.4 KiB
PHP

<?php
namespace app\common\controller;
use app\common\library\GranarySite;
use think\Db;
/** Apply site authorization to every grain-management read and write route. */
class GranaryBackend extends Backend
{
protected $granarySites = [];
protected $filterSites = [];
public function _initialize()
{
parent::_initialize();
$this->initializeGranarySiteAccess();
}
protected function initializeGranarySiteAccess()
{
$this->granarySites = GranarySite::allowed($this->auth);
$site = $this->request->get('site', '');
if ($site !== '' && (!GranarySite::valid($site) || !in_array($site, $this->granarySites, true))) {
$this->error('无权访问此库区');
}
$this->filterSites = $site === '' ? $this->granarySites : [$site];
$this->assignconfig('granarySites', GranarySite::options($this->granarySites));
$controller = strtolower($this->request->controller());
$action = strtolower($this->request->action());
$actions = [
'granary' => ['index', 'add', 'detail', 'dell'],
'testing' => ['index', 'add', 'sort', 'dell'],
'content' => ['index', 'add', 'status', 'getcontent', 'dell'],
'forecast' => ['index', 'detail', 'add', 'retry', 'actual'],
];
if (!isset($actions[$controller]) || !in_array($action, $actions[$controller], true)) $this->error('不支持此操作');
$table = $controller === 'forecast' ? 'grain_forecast' : $controller;
$id = $this->request->post('id', $this->request->get('id', ''));
if ($action === 'actual') {
$id = Db::name('grain_forecast_point')->where('id', $this->request->post('point_id/d', 0))->value('forecast_id');
if (!$id) $this->error('预测周期不存在');
}
if ($id !== '' && $id !== null && $id !== 0 && $id !== '0') {
if (!is_scalar($id) || !preg_match('/^\d+(,\d+)*$/D', (string)$id)) $this->error('记录编号不正确');
foreach (explode(',', (string)$id) as $recordId) {
$gid = $controller === 'granary' ? $recordId : Db::name($table)->where('id', $recordId)->value('gid');
if (!GranarySite::permits($gid, $this->granarySites)) $this->error('记录不存在或无权访问所属库区');
}
}
$gid = $this->request->post('gid', $this->request->get('gid', 0));
if ($gid && !GranarySite::permits($gid, $this->granarySites)) $this->error('无权访问此仓库');
if ($controller !== 'granary' && $action === 'add' && $this->request->isPost() && !$gid) $this->error('请选择所属仓库');
if ($controller === 'content' && $action === 'index') {
$rid = $this->request->get('rid/d', 0);
if ($rid && !GranarySite::permits($rid, $this->granarySites)) $this->error('无权访问此仓库');
}
if ($controller === 'forecast' && $action === 'add' && $this->request->isPost()) {
$existingGid = Db::name('grain_forecast')->where('request_key', $this->request->post('request_key', ''))->value('gid');
if ($existingGid && !GranarySite::permits($existingGid, $this->granarySites)) $this->error('无权访问原预测记录');
}
}
protected function scopeRecords($query)
{
$ids = array_column(GranarySite::granaries($this->filterSites), 'id');
return $query->where('gid', 'in', $ids ?: [0]);
}
}