From a3589dab7dcc51f6e435a52b68bf79213ed24e6c Mon Sep 17 00:00:00 2001 From: admin Date: Mon, 20 Nov 2023 20:18:51 +0800 Subject: [PATCH] =?UTF-8?q?edit=E4=BF=AE=E6=94=B9=E7=9B=B8=E9=97=9C?= =?UTF-8?q?=E5=85=A7=E5=AE=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- controllers/SiteController.php | 78 +- models/Dev.php | 59 + modules/api/controllers/UserController.php | 29 +- modules/api/models/LoginByWxoaForm.php | 294 +-- modules/api/models/LoginForm.php | 48 +- modules/api/models/ReportEditForm.php | 79 + modules/api/models/UserModifyForm.php | 9 +- modules/api/models/WxmpAuthMobileForm.php | 316 +-- modules/file/controllers/UploadController.php | 1751 +++++++++-------- modules/store/controllers/DevController.php | 104 + .../store/controllers/ReportController.php | 181 +- modules/store/models/Menu.php | 289 +-- modules/store/models/dev/DevActionForm.php | 178 ++ modules/store/models/dev/DevEditForm.php | 89 + modules/store/models/dev/DevtListForm.php | 95 + .../store/models/report/ReportListForm.php | 254 +-- modules/store/views/dev/edit.php | 129 ++ modules/store/views/dev/index.php | 488 +++++ modules/store/views/passport/login.php | 300 +-- modules/store/views/report/index.php | 9 +- 20 files changed, 3040 insertions(+), 1739 deletions(-) create mode 100644 models/Dev.php create mode 100644 modules/api/models/ReportEditForm.php create mode 100644 modules/store/controllers/DevController.php create mode 100644 modules/store/models/dev/DevActionForm.php create mode 100644 modules/store/models/dev/DevEditForm.php create mode 100644 modules/store/models/dev/DevtListForm.php create mode 100644 modules/store/views/dev/edit.php create mode 100644 modules/store/views/dev/index.php diff --git a/controllers/SiteController.php b/controllers/SiteController.php index 246759a..429b65c 100644 --- a/controllers/SiteController.php +++ b/controllers/SiteController.php @@ -1,38 +1,40 @@ - [ - 'class' => 'yii\web\ErrorAction', - ], - ]; - } - - /** - * Displays homepage. - * - * @return string - */ - public function actionIndex() - { - $code = $this->request->get('code'); - echo($code); - exit(); - return $this->render('index'); - } - -} + [ + 'class' => 'yii\web\ErrorAction', + ], + ]; + } + + /** + * Displays homepage. + * + * @return string + */ + public function actionIndex() + { + $code = $this->request->get('code'); + $url = "https://app.3dxh.h5.dev.1nww.com/#/White?code={$code}"; + return $this->redirect($url); + echo($code); + exit(); + return $this->render('index'); + } + +} diff --git a/models/Dev.php b/models/Dev.php new file mode 100644 index 0000000..f8773fc --- /dev/null +++ b/models/Dev.php @@ -0,0 +1,59 @@ + 50], + ]; + } + + /** + * {@inheritdoc} + */ + public function attributeLabels() + { + return [ + 'id' => 'ID', + 'store_id' => 'Store ID', + 'name' => 'Name', + 'dev_number' => 'Dev Number', + 'status' => 'Status', + 'created_at' => 'Created At', + 'updated_at' => 'Updated At', + 'is_delete' => 'Is Delete', + 'deleted_at' => 'Deleted At', + ]; + } +} diff --git a/modules/api/controllers/UserController.php b/modules/api/controllers/UserController.php index 44bcd49..1e5ef47 100644 --- a/modules/api/controllers/UserController.php +++ b/modules/api/controllers/UserController.php @@ -25,6 +25,8 @@ use app\modules\api\models\CommentForm; use app\modules\api\models\LoginForm; use app\modules\api\models\UserBasicInfoForm; use app\modules\api\models\UserModifyForm; +use app\modules\api\models\ReportEditForm; + class UserController extends Controller { @@ -56,10 +58,12 @@ class UserController extends Controller $post = \Yii::$app->request->post(); // attributes 转成键值对形式 key=> value $user_outh = UserOauth::findOne(['openid' => $post['code']]); if ($user_outh == null) { - return ['code' => 1, 'msg' => '授权失败,请重新进行微信公众号授权',]; + $data = ['code' => 1, 'msg' => '授权失败,请重新进行微信公众号授权',]; + return $this->responseHandler($data); } if ($user_outh->user_id == 0) { - return ['code' => 1, 'msg' => '暂未填写信息',]; + $data = ['code' => 1, 'msg' => '暂未填写信息',]; + return $this->responseHandler($data); } // 查用户信息 @@ -98,4 +102,25 @@ class UserController extends Controller $data = $form->modify_user(); return $this->responseHandler($data); } + + + /** + * showdoc + * @catalog 会员注册 + * @method post + * @url /api/user/user-create + * @return {"code":0,"msg":"ok","data":{}} + * @remark + */ + public function actionUserCreate() + { + $post = \Yii::$app->request->post(); // attributes 转成键值对形式 key=> value + $form = new ReportEditForm(); +// $form->cx_mch_id = $this->cx_mch_id; //商户ID 没看到传参赋值 默认给0 + $form->attributes = $post; + $form->user_id = \Yii::$app->user->identity->id; //获取用户登陆ID + $data = $form->edit(); + + return $this->responseHandler($data); + } } \ No newline at end of file diff --git a/modules/api/models/LoginByWxoaForm.php b/modules/api/models/LoginByWxoaForm.php index ff3af16..8a27e66 100644 --- a/modules/api/models/LoginByWxoaForm.php +++ b/modules/api/models/LoginByWxoaForm.php @@ -1,148 +1,148 @@ -validate()) { - return $this->getModelError(); - } - $res = FlashStorage::getCache("m{$this->cx_mch_id}_c{$this->code}"); - if ($this->code_expires == 1 || $res === false) { - $res = $this->code2session($this->code); - if ($res['code'] != 0) - return $res; - FlashStorage::setCache("m{$this->cx_mch_id}_c{$this->code}", $res, 864000); - } - - if ($res['code'] != 0) { - return $res; - } - - $access_token = $res['data']['access_token']; - $openid = $res['data']['openid']; - - //用户是否存在 - $user_oauth = null; - if ($openid != 0) { - //优选使用unionid - $user_oauth = UserOauth::findOne([ - 'cx_mch_id' => $this->cx_mch_id, - 'is_delete' => 0, - 'openid' => $openid - ]); - } - if ($user_oauth == null) { - $user_oauth = new UserOauth(); - $user_oauth->cx_mch_id = 0; - $user_oauth->type = 'wxoa'; - $user_oauth->openid = $openid; - $user_oauth->created_at = time(); - $res = $user_oauth->save(); - if ($res['code'] != 0) { - return ['code' => 1, 'msg' => '登陆失败']; - } - } - $data = ['code' => 1, 'msg' => '登陆成功', 'data' => $openid]; - return $data; - } - - - /*** - * 用户数据解密 - */ - private function curl_wechat_user($access_token, $openid) - { - - $api = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $access_token . "&openid=" . $openid . "&lang=zh_CN"; - $this->wechat_mp->curl->get($api); - - if ($this->wechat_mp->curl->error_code != 0) { - return [ - 'code' => 1, - 'msg' => "err_code:{$this->wechat_mp->curl->error_code}err_msg:{$this->wechat_mp->curl->error_msg}" - ]; - } - - $resp = $this->wechat_mp->curl->response; - $res = json_decode($resp, true); - if (!isset($res['nickname']) || !isset($res['headimgurl'])) { - return [ - 'code' => 1, - 'msg' => isset($res['errmsg']) ? $res['errmsg'] : 'error' - ]; - } - return [ - 'code' => 0, - 'msg' => 'ok', - 'data' => $res - ]; - - } - - private function code2session($code) - { - $api = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->wechat_mp->appId}&secret={$this->wechat_mp->appSecret}&code=" . $code . "&grant_type=authorization_code"; - $this->wechat_mp->curl->get($api); - if ($this->wechat_mp->curl->error_code != 0) { - return [ - 'code' => 1, - 'msg' => "err_code:{$this->wechat_mp->curl->error_code}err_msg:{$this->wechat_mp->curl->error_msg}" - ]; - } - $resp = $this->wechat_mp->curl->response; - $res = json_decode($resp, true); - if (!isset($res['access_token']) || !isset($res['openid'])) { - return [ - 'code' => 1, - 'msg' => isset($res['errmsg']) ? $res['errmsg'] : 'error' - ]; - } - return [ - 'code' => 0, - 'msg' => 'ok', - 'data' => $res - ]; - } +validate()) { + return $this->getModelError(); + } + $res = FlashStorage::getCache("m{$this->cx_mch_id}_c{$this->code}"); + if ($this->code_expires == 1 || $res === false) { + $res = $this->code2session($this->code); + if ($res['code'] != 0) + return $res; + FlashStorage::setCache("m{$this->cx_mch_id}_c{$this->code}", $res, 864000); + } + + if ($res['code'] != 0) { + return $res; + } + + $access_token = $res['data']['access_token']; + $openid = $res['data']['openid']; + + //用户是否存在 + $user_oauth = null; + if ($openid != 0) { + //优选使用unionid + $user_oauth = UserOauth::findOne([ + 'cx_mch_id' => $this->cx_mch_id, + 'is_delete' => 0, + 'openid' => $openid + ]); + } + if ($user_oauth == null) { + $user_oauth = new UserOauth(); + $user_oauth->cx_mch_id = 0; + $user_oauth->type = 'wxoa'; + $user_oauth->openid = $openid; + $user_oauth->created_at = time(); + $res = $user_oauth->save(); + if ($res['code'] != 0) { + return ['code' => 1, 'msg' => '登陆失败']; + } + } + $data = ['code' => 0, 'msg' => '登陆成功', 'data' => $openid]; + return $data; + } + + + /*** + * 用户数据解密 + */ + private function curl_wechat_user($access_token, $openid) + { + + $api = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $access_token . "&openid=" . $openid . "&lang=zh_CN"; + $this->wechat_mp->curl->get($api); + + if ($this->wechat_mp->curl->error_code != 0) { + return [ + 'code' => 1, + 'msg' => "err_code:{$this->wechat_mp->curl->error_code}err_msg:{$this->wechat_mp->curl->error_msg}" + ]; + } + + $resp = $this->wechat_mp->curl->response; + $res = json_decode($resp, true); + if (!isset($res['nickname']) || !isset($res['headimgurl'])) { + return [ + 'code' => 1, + 'msg' => isset($res['errmsg']) ? $res['errmsg'] : 'error' + ]; + } + return [ + 'code' => 0, + 'msg' => 'ok', + 'data' => $res + ]; + + } + + private function code2session($code) + { + $api = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->wechat_mp->appId}&secret={$this->wechat_mp->appSecret}&code=" . $code . "&grant_type=authorization_code"; + $this->wechat_mp->curl->get($api); + if ($this->wechat_mp->curl->error_code != 0) { + return [ + 'code' => 1, + 'msg' => "err_code:{$this->wechat_mp->curl->error_code}err_msg:{$this->wechat_mp->curl->error_msg}" + ]; + } + $resp = $this->wechat_mp->curl->response; + $res = json_decode($resp, true); + if (!isset($res['access_token']) || !isset($res['openid'])) { + return [ + 'code' => 1, + 'msg' => isset($res['errmsg']) ? $res['errmsg'] : 'error' + ]; + } + return [ + 'code' => 0, + 'msg' => 'ok', + 'data' => $res + ]; + } } \ No newline at end of file diff --git a/modules/api/models/LoginForm.php b/modules/api/models/LoginForm.php index fc8c54a..7856c5f 100644 --- a/modules/api/models/LoginForm.php +++ b/modules/api/models/LoginForm.php @@ -45,32 +45,36 @@ class LoginForm extends ApiModel ]; } - public function login() + public function login($user=null) { + $this->cx_mch_id = 0; if(!$this->validate()){ return $this->getModelError(); } - $mobile_phone = EncryptHelper::encryptMobilePhone($this->username); - $mobile_phone = $mobile_phone ? $mobile_phone : $this->username; - $user = User::find() - ->where([ - 'cx_mch_id' => $this->cx_mch_id, - 'is_delete' => 0, - 'status' => User::STATUS_NORMAL - ]) - ->andWhere([ - 'OR', - ['username' => $this->username], - ['mobile_phone' => $mobile_phone], - ]) - ->one(); - if($user == null){ - return [ - 'code' => 1, - 'msg' => '用户名或者密码错误' - ]; + if(empty($user)){ + $mobile_phone = EncryptHelper::encryptMobilePhone($this->username); + $mobile_phone = $mobile_phone ? $mobile_phone : $this->username; + $user = User::find() + ->where([ + 'cx_mch_id' => $this->cx_mch_id, + 'is_delete' => 0, + 'status' => User::STATUS_NORMAL + ]) + ->andWhere([ + 'OR', + ['username' => $this->username], + ['mobile_phone' => $mobile_phone], + ]) + ->one(); + if($user == null){ + return [ + 'code' => 1, + 'msg' => '用户名或者密码错误1' + ]; + } } - if(!$user->validatePassword($this->password)){ + + /*if(!$user->validatePassword($this->password)){ $err_msg = "密码错误"; User::lastLogin($user->id, 0, $err_msg, $this->cx_mch_id); @@ -78,7 +82,7 @@ class LoginForm extends ApiModel 'code' => 1, 'msg' => '用户名或者密码错误' ]; - } + } */ if(\Yii::$app->user->login($user,\Yii::$app->params['loginAuthExpireTime'])){ $args = []; $args['cx_mch_id'] = $this->cx_mch_id; diff --git a/modules/api/models/ReportEditForm.php b/modules/api/models/ReportEditForm.php new file mode 100644 index 0000000..6803d99 --- /dev/null +++ b/modules/api/models/ReportEditForm.php @@ -0,0 +1,79 @@ + $this->dev_id]); + + if ($dev == null) { + return ['code' => 1, 'msg' => '无效设备,请联系管理员']; + } + + + $model = new Report(); + $model->user_id = $this->user_id; + $model->model_number = $dev->dev_number; + $model->store_id = $this->store_id; + $model->created_at = time(); + if (!$model->save()) { + return Model::getModelErrorInfo($model); + } + return ['code' => 0, 'msg' => '成功']; + + } + + +} \ No newline at end of file diff --git a/modules/api/models/UserModifyForm.php b/modules/api/models/UserModifyForm.php index 668f9d6..244bc8d 100644 --- a/modules/api/models/UserModifyForm.php +++ b/modules/api/models/UserModifyForm.php @@ -82,7 +82,7 @@ class UserModifyForm extends ApiModel $form->username = $user->username; $form->password = '123456'; $form->token_type = 3; - return $form->login(); + return $form->login($user); } //没有信息 去绑定 @@ -134,13 +134,18 @@ class UserModifyForm extends ApiModel $form->username = $username; $form->password = $password; $form->token_type = 3; - $data = $form->login(); + $data = $form->login($user); return $data; } catch (\Exception $e) { $t->rollBack(); return [ 'code' => 1, 'msg' => '失败', + 'data' => [ + 'msg' => $e->getMessage(), + 'line' => $e->getLine(), + 'file' => $e->getFile(), + ], ]; } } diff --git a/modules/api/models/WxmpAuthMobileForm.php b/modules/api/models/WxmpAuthMobileForm.php index f0efa83..bb3a4b4 100644 --- a/modules/api/models/WxmpAuthMobileForm.php +++ b/modules/api/models/WxmpAuthMobileForm.php @@ -1,157 +1,159 @@ -code2session($this->code); - if($res['code'] != 0) - return $res; - $session_key = $res['data']['session_key']; - $res = $this->decrypted_data($session_key); - if($res['code'] != 0){ - return $res; - } - $res['data'] = json_decode($res['data'],true); - if(!isset($res['data']['purePhoneNumber'])){ - return [ - 'code' => 1, - 'msg' => '数据解析失败', - 'data' => $res['data'] - ]; - } - $mobile = $res['data']['purePhoneNumber'];//不带区号的手机号 - $mobile_prefix = $res['data']['countryCode']; - $data = [ - 'code' => 0, - 'msg' => 'ok', - 'data' => [ - 'mobile' => $mobile, - 'mobile_prefix' => $mobile_prefix - ] - ]; - return $data; - } - - - /*** - * 用户数据解密 - */ - private function decrypted_data($session_key){ - $pc = new WxBizDataCrypt($this->wechat_mp->appId, $session_key); - $errCode = $pc->decryptData($this->encrypted_data, $this->iv, $data ); - if ($errCode == 0) { - return [ - 'code' => 0, - 'msg' => 'success', - 'data' => $data - ]; - } else { - return [ - 'code' => 1, - 'msg' => $errCode, - ]; - } - } - - private function code2session($code) - { - $api = "https://api.weixin.qq.com/sns/jscode2session?appid={$this->wechat_mp->appId}&secret={$this->wechat_mp->appSecret}&js_code={$code}&grant_type=authorization_code"; - $this->wechat_mp->curl->get($api); - if($this->wechat_mp->curl->error_code != 0){ - return [ - 'code' => 1, - 'msg' => "err_code:{$this->wechat_mp->curl->error_code}err_msg:{$this->wechat_mp->curl->error_msg}" - ]; - } - $resp = $this->wechat_mp->curl->response; - $res = json_decode($resp, true); - if(!isset($res['openid'])){ - return [ - 'code' => 1, - 'msg' => isset($res['errmsg']) ? $res['errmsg'] : 'error' - ]; - } - return [ - 'code' => 0, - 'msg' => 'ok', - 'data' => $res - ]; - } - - /** - * @ 获取js-sdk前端所需参数 - */ - public function actionGetJssdk(){ - $redis_name = "api:{$this->wechat_mp->appId}:actionGetJssdk_1"; - $get = \Yii::$app->redis->get($redis_name); - if(empty($get)){ - $accessToken = $this->wechat_mp->getAccessToken(); - // $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken"; - $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=".$accessToken; - $this->wechat_mp->curl->get($url); - $res = json_decode($this->wechat_mp->curl->response); - $get = $res->ticket; - \Yii::$app->redis->setex($redis_name,6800,$get); - } - $uniq = uniqid(); - $time = time(); - $str = "jsapi_ticket={$get}&noncestr={$uniq}×tamp={$time}&url={$this->url}"; - $sign = sha1($str); - $return = [ - 'appId' => $this->wechat_mp->appId, - 'timestamp' => $time, - 'nonceStr' => $uniq, - 'signature' => $sign, - 'jsApiList' => [ - 'scanQRCode', - ], - ]; - return $this->apiReturnSuccess('ok',$return); - } -} - +code2session($this->code); + if($res['code'] != 0) + return $res; + $session_key = $res['data']['session_key']; + $res = $this->decrypted_data($session_key); + if($res['code'] != 0){ + return $res; + } + $res['data'] = json_decode($res['data'],true); + if(!isset($res['data']['purePhoneNumber'])){ + return [ + 'code' => 1, + 'msg' => '数据解析失败', + 'data' => $res['data'] + ]; + } + $mobile = $res['data']['purePhoneNumber'];//不带区号的手机号 + $mobile_prefix = $res['data']['countryCode']; + $data = [ + 'code' => 0, + 'msg' => 'ok', + 'data' => [ + 'mobile' => $mobile, + 'mobile_prefix' => $mobile_prefix + ] + ]; + return $data; + } + + + /*** + * 用户数据解密 + */ + private function decrypted_data($session_key){ + $pc = new WxBizDataCrypt($this->wechat_mp->appId, $session_key); + $errCode = $pc->decryptData($this->encrypted_data, $this->iv, $data ); + if ($errCode == 0) { + return [ + 'code' => 0, + 'msg' => 'success', + 'data' => $data + ]; + } else { + return [ + 'code' => 1, + 'msg' => $errCode, + ]; + } + } + + private function code2session($code) + { + $api = "https://api.weixin.qq.com/sns/jscode2session?appid={$this->wechat_mp->appId}&secret={$this->wechat_mp->appSecret}&js_code={$code}&grant_type=authorization_code"; + $this->wechat_mp->curl->get($api); + if($this->wechat_mp->curl->error_code != 0){ + return [ + 'code' => 1, + 'msg' => "err_code:{$this->wechat_mp->curl->error_code}err_msg:{$this->wechat_mp->curl->error_msg}" + ]; + } + $resp = $this->wechat_mp->curl->response; + $res = json_decode($resp, true); + if(!isset($res['openid'])){ + return [ + 'code' => 1, + 'msg' => isset($res['errmsg']) ? $res['errmsg'] : 'error' + ]; + } + return [ + 'code' => 0, + 'msg' => 'ok', + 'data' => $res + ]; + } + + /** + * @ 获取js-sdk前端所需参数 + */ + public function actionGetJssdk(){ + $redis_name = "api:{$this->wechat_mp->appId}:actionGetJssdk_1"; + $get = \Yii::$app->redis->get($redis_name); + if(empty($get)){ + $accessToken = $this->wechat_mp->getAccessToken(); + // $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken"; + $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=".$accessToken; + $this->wechat_mp->curl->get($url); + $res = json_decode($this->wechat_mp->curl->response); + $get = $res->ticket; + \Yii::$app->redis->setex($redis_name,6800,$get); + } + $uniq = uniqid(); + $time = time(); + $this->url = urldecode($this->url); + $str = "jsapi_ticket={$get}&noncestr={$uniq}×tamp={$time}&url={$this->url}"; + $sign = sha1($str); + $return = [ + 'appId' => $this->wechat_mp->appId, + 'timestamp' => $time, + 'nonceStr' => $uniq, + 'signature' => $sign, + 'jsApiList' => [ + 'scanQRCode', + ], + 'url' => $this->url, + ]; + return $this->apiReturnSuccess('ok',$return); + } +} + diff --git a/modules/file/controllers/UploadController.php b/modules/file/controllers/UploadController.php index 2cb2e86..9483ea1 100644 --- a/modules/file/controllers/UploadController.php +++ b/modules/file/controllers/UploadController.php @@ -1,876 +1,877 @@ - [ - /* 文件上传的根目录 */ - //'rootPath' => $_SERVER['DOCUMENT_ROOT'], - /* 上传图片配置项 */ - "imageActionName" => "uploadimage", - /* 执行上传图片的action名称 */ - "imageFieldName" => "file", - /* 提交的图片表单名称 */ - "imageMaxSize" => 20480000, - /* 银联文件上传大小限制,单位B */ - "imageMaxSize_union" => 2097152, - /* 上传大小限制,单位B */ - "imageAllowFiles" => [ - ".png", - ".jpg", - ".jpeg", - ".gif", - ".ico", - ".bmp" - ], - /* 上传图片格式显示 */ - "imageCompressEnable" => true, - /* 是否压缩图片,默认是true */ - "imageCompressBorder" => 800, - /* 图片压缩最长边限制 */ - "imageInsertAlign" => "none", - /* 插入的图片浮动方式 */ - "imageUrlPrefix" => "", - /* 图片访问路径前缀 */ - "imagePathFormat" => "/upload/image/{yyyy}/{mm}{dd}/{time}{rand:6}", - /* 上传保存路径,可以自定义保存路径和文件名格式 */ - /* {filename} 会替换成原文件名,配置这项需要注意中文乱码问题 */ - /* {rand:6} 会替换成随机数,后面的数字是随机数的位数 */ - /* {time} 会替换成时间戳 */ - /* {yyyy} 会替换成四位年份 */ - /* {yy} 会替换成两位年份 */ - /* {mm} 会替换成两位月份 */ - /* {dd} 会替换成两位日期 */ - /* {hh} 会替换成两位小时 */ - /* {ii} 会替换成两位分钟 */ - /* {ss} 会替换成两位秒 */ - /* 非法字符 \ => * ? " < > | */ - /* 具请体看线上文档=> fex.baidu.com/ueditor/#use-format_upload_filename */ - - /* 涂鸦图片上传配置项 */ - "scrawlActionName" => "uploadscrawl", - /* 执行上传涂鸦的action名称 */ - "scrawlFieldName" => "file", - /* 提交的图片表单名称 */ - "scrawlPathFormat" => "/upload/image/{yyyy}/{mm}{dd}/{time}{rand:6}", - /* 上传保存路径,可以自定义保存路径和文件名格式 */ - "scrawlMaxSize" => 2048000, - /* 上传大小限制,单位B */ - "scrawlUrlPrefix" => "", - /* 图片访问路径前缀 */ - "scrawlInsertAlign" => "none", - /* 截图工具上传 */ - "snapscreenActionName" => "uploadimage", - /* 执行上传截图的action名称 */ - "snapscreenPathFormat" => "/upload/image/{yyyy}/{mm}{dd}/{time}{rand:6}", - /* 上传保存路径,可以自定义保存路径和文件名格式 */ - "snapscreenUrlPrefix" => "", - /* 图片访问路径前缀 */ - "snapscreenInsertAlign" => "none", - /* 插入的图片浮动方式 */ - - /* 抓取远程图片配置 */ - "catcherLocalDomain" => [ - "127.0.0.1", - "localhost", - "img.baidu.com" - ], - "catcherActionName" => "catchimage", - /* 执行抓取远程图片的action名称 */ - "catcherFieldName" => "source", - /* 提交的图片列表表单名称 */ - "catcherPathFormat" => "/upload/image/{yyyy}/{mm}{dd}/{time}{rand:6}", - /* 上传保存路径,可以自定义保存路径和文件名格式 */ - "catcherUrlPrefix" => "", - /* 图片访问路径前缀 */ - "catcherMaxSize" => 2048000, - /* 上传大小限制,单位B */ - "catcherAllowFiles" => [ - ".png", - ".jpg", - ".jpeg", - ".gif", - ".ico", - ".bmp" - ], - /* 抓取图片格式显示 */ - - /* 上传视频配置 */ - "videoActionName" => "uploadvideo", - /* 执行上传视频的action名称 */ - "videoFieldName" => "file", - /* 提交的视频表单名称 */ - "videoPathFormat" => "/upload/video/{yyyy}/{mm}{dd}/{time}{rand:6}", - /* 上传保存路径,可以自定义保存路径和文件名格式 */ - "videoUrlPrefix" => "", - /* 视频访问路径前缀 */ - // "videoMaxSize" => 5120000, - "videoMaxSize" => 52428800, - /* 上传大小限制,单位B,默认100MB */ - "videoAllowFiles" => [ - ".flv", -// ".swf", -// ".mkv", -// ".avi", -// ".rm", - ".rmvb", - ".mpeg", - ".mpg", -// ".ogg", -// ".ogv", -// ".mov", - ".wmv", - ".mp4", -// ".webm", - ".mp3", - ".wav", -// ".mid" - ], - /* 上传视频格式显示 */ - - /* 上传文件配置 */ - "fileActionName" => "uploadfile", - /* controller里,执行上传视频的action名称 */ - "fileFieldName" => "file", - /* 提交的文件表单名称 */ - "filePathFormat" => "/upload/file/{yyyy}/{mm}{dd}/{time}{rand:6}", - /* 上传保存路径,可以自定义保存路径和文件名格式 */ - "fileUrlPrefix" => "", - /* 文件访问路径前缀 */ - "fileMaxSize" => 51200000, - /* 上传大小限制,单位B,默认50MB */ - "fileAllowFiles" => [ - ".png", - ".jpg", - ".jpeg", - ".gif", - ".ico", - ".bmp", - ".flv", - //".swf", - //".mkv", - ".avi", - //".rm", - ".rmvb", - //".mpeg", - //".mpg", - ".ogg", - //".ogv", - //".mov", - ".wmv", - ".mp4", - //".webm", - ".mp3", - ".wav", - //".mid", - ".rar", - ".zip", - //".tar", - //".gz", - //".7z", - //".bz2", - //".cab", - //".iso", - ".doc", - ".docx", - ".xls", - ".xlsx", - ".ppt", - ".pptx", - ".pdf", - ".txt", - ".md", - ".xml" - ], - /* 上传文件格式显示 */ - - /* 列出指定目录下的图片 */ - "imageManagerActionName" => "listimage", - /* 执行图片管理的action名称 */ - "imageManagerListPath" => "/upload/image/", - /* 指定要列出图片的目录 */ - "imageManagerListSize" => 20, - /* 每次列出文件数量 */ - "imageManagerUrlPrefix" => "", - /* 图片访问路径前缀 */ - "imageManagerInsertAlign" => "none", - /* 插入的图片浮动方式 */ - "imageManagerAllowFiles" => [ - ".png", - ".jpg", - ".jpeg", - ".gif", - ".ico", - ".bmp" - ], - /* 列出的文件类型 */ - - /* 列出指定目录下的文件 */ - "fileManagerActionName" => "listfile", - /* 执行文件管理的action名称 */ - "fileManagerListPath" => "/upload/file/", - /* 指定要列出文件的目录 */ - "fileManagerUrlPrefix" => "", - /* 文件访问路径前缀 */ - "fileManagerListSize" => 20, - /* 每次列出文件数量 */ - "fileManagerAllowFiles" => [ - ".png", - ".jpg", - ".jpeg", - ".gif", - ".ico", - ".bmp", - ".flv", - ".swf", - ".mkv", - ".avi", - ".rm", - ".rmvb", - ".mpeg", - ".mpg", - ".ogg", - ".ogv", - ".mov", - ".wmv", - ".mp4", - ".webm", - ".mp3", - ".wav", - ".mid", - ".rar", - ".zip", - ".tar", - ".gz", - ".7z", - ".bz2", - ".cab", - ".iso", - ".doc", - ".docx", - ".xls", - ".xlsx", - ".ppt", - ".pptx", - ".pdf", - ".txt", - ".md", - ".xml" - ] - /* 列出的文件类型 */ - ] - ]; - - public function actionIndex() - { - //设置允许的跨域header - header('Access-Control-Allow-Headers: X-Requested-With,X_Requested_With'); - $action = Yii::$app->request->get("action"); - $action = htmlspecialchars($action); - switch ($action) { - case 'config': - $result = json_encode($this->uploadConfig['uploadFile']); - break; - /* 上传图片 */ - case 'uploadimage': - /* 上传涂鸦 */ - case 'uploadscrawl': - /* 上传视频 */ - case 'uploadvideo': - /* 上传文件 */ - case 'uploadfile': - if(isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] == "OPTIONS"){ - //判断实际发送的请求是否安全 - $result = ""; - } else { - if(Yii::$app->request->isPost && !empty($_FILES)){ - //上传 - $currentFileInfo = $this->uploadFile($action); - $result = json_encode($currentFileInfo); - } else { - $result = ""; - } - } - break; - - /* 列出图片 */ - case 'listimage': - if(isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] == "OPTIONS"){ - $result = ""; - } else { - //返回结果 - $result = $this->getFileList($action); - } - break; - /* 列出文件 */ - case 'listfile': - if(isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] == "OPTIONS"){ - $result = ""; - } else { - //返回结果 - $result = $this->getFileList($action); - } - break; - - /* 抓取远程文件 */ - case 'catchimage': - if(isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] == "OPTIONS"){ - $result = ""; - } else { - //返回结果 - $result = $this->crawlerImage($action); - } - break; - - default: - $result = json_encode(array( - 'state'=> '请求地址出错' - )); - break; - } - - /* 输出结果 */ - if (isset($_GET["callback"])) { - if (preg_match("/^[\w_]+$/", $_GET["callback"])) { - echo htmlspecialchars($_GET["callback"]) . '(' . $result . ')'; - } else { - echo json_encode(array( - 'state'=> 'callback参数不合法' - )); - } - } else { - echo $result; - } - } - - //上传图片 - public function actionImage() - { - if(!\Yii::$app->request->isPost){ - $data = [ - 'code' => 1, - 'msg' => "Invalid Request" - ]; - return $this->responseHandler($data); - } - $action = "uploadimage"; - $fileInfo = $this->uploadFile($action); - if($fileInfo["state"] == "SUCCESS"){ - $data = [ - 'code' => 0, - 'msg' => 'success', - 'data' => [ - 'url' => $fileInfo['url'], - 'extension' => $fileInfo["type"], - 'size' => $fileInfo["size"], - 'type' => $this->getFileType(trim($fileInfo['type'],".")) - ] - ]; - } else { - $data = [ - 'code' => 1, - 'msg' => $fileInfo["state"] - ]; - } - return $this->responseHandler($data); - } - - //上传文件 - public function actionFile() - { - try { - if(!\Yii::$app->request->isPost){ - $data = [ - 'code' => 1, - 'msg' => "Invalid Request" - ]; - return $this->responseHandler($data); - } - $action = "uploadfile"; - $fileInfo = $this->uploadFile($action); - if($fileInfo["state"] == "SUCCESS"){ - $data = [ - 'code' => 0, - 'msg' => 'success', - 'data' => [ - 'url' => $fileInfo['url'], - 'extension' => $fileInfo["type"], - 'size' => $fileInfo["size"], - 'type' => $this->getFileType(trim($fileInfo['type'],".")) - ] - ]; - } else { - $data = [ - 'code' => 1, - 'msg' => $fileInfo["state"] - ]; - } - - }catch (\Exception $e){ - $data = [ - 'code' => 1, - 'msg' => $e->getMessage() - ]; - } - return $this->responseHandler($data); - } - - //上传视频 - public function actionVideoFile() - { - if(!\Yii::$app->request->isPost){ - $data = [ - 'code' => 1, - 'msg' => "Invalid Request" - ]; - } - $action = "uploadvideo"; - $fileInfo = $this->uploadFile($action); - if($fileInfo["state"] == "SUCCESS"){ - $data = [ - 'code' => 0, - 'msg' => 'success', - 'data' => [ - 'url' => $fileInfo['url'], - 'extension' => $fileInfo["type"], - 'size' => $fileInfo["size"], - 'type' => $this->getFileType(trim($fileInfo['type'],".")) - ] - ]; - } else { - $data = [ - 'code' => 1, - 'msg' => $fileInfo["state"] - ]; - } - return $this->responseHandler($data); - } - - - /** - * @TODO 扩展上传至第三方存储 - * 文件上传 - */ - private function uploadFile($action){ - //获取上传配置 - $uploadConfig = $this->getUploadConfig($action); - $path = $uploadConfig["path"]; - $_config = $uploadConfig["config"]; - - /* 上传配置 */ - $base64 = "upload"; - switch ($action) { - case 'uploadimage': - $_config['imagePathFormat'] = $path . $_config['imagePathFormat']; - $config = array( - "pathFormat" => $_config['imagePathFormat'], - "maxSize" => $_config['imageMaxSize'], - "allowFiles" => $_config['imageAllowFiles'] - ); - $fieldName = $_config['imageFieldName']; - break; - case 'uploadscrawl': - $_config['scrawlPathFormat'] = $path . $_config['scrawlPathFormat']; - $config = array( - "pathFormat" => $_config['scrawlPathFormat'], - "maxSize" => $_config['scrawlMaxSize'], - "allowFiles" => $_config['scrawlAllowFiles'], - "oriName" => "scrawl.png" - ); - $fieldName = $_config['scrawlFieldName']; - $base64 = "base64"; - break; - case 'uploadvideo': - $_config['videoPathFormat'] = $path . $_config['videoPathFormat']; - $config = array( - "pathFormat" => $_config['videoPathFormat'], - "maxSize" => $_config['videoMaxSize'], - "allowFiles" => $_config['videoAllowFiles'] - ); - $fieldName = $_config['videoFieldName']; - break; - case 'uploadimageUnion': - #########2022/06/10##################### - $_config['imagePathFormat'] = $path . $_config['imagePathFormat']; - $config = array( - "pathFormat" => $_config['imagePathFormat'], - "maxSize" => $_config['imageMaxSize_union'], - "allowFiles" => $_config['imageAllowFiles'] - ); - $fieldName = $_config['imageFieldName']; - break; - case 'uploadfile': - default: - $_config['filePathFormat'] = $path . $_config['filePathFormat']; - $config = array( - "pathFormat" => $_config['filePathFormat'], - "maxSize" => $_config['fileMaxSize'], - "allowFiles" => $_config['fileAllowFiles'] - ); - $fieldName = $_config['fileFieldName']; - break; - } - - /* 生成上传实例对象并完成上传 */ - $up = new Uploader($fieldName, $config, $base64); - /** - * 得到上传文件所对应的各个参数,数组结构 - * array( - * "state" => "", //上传状态,上传成功时必须返回"SUCCESS" - * "url" => "", //返回的地址 - * "title" => "", //新文件名 - * "original" => "", //原始文件名 - * "type" => "" //文件类型 - * "size" => "", //文件大小 - * ) - */ - - /* 返回数据 */ - $fileInfo = $up->getFileInfo(); - if($fileInfo["state"] == "SUCCESS"){ - $this->imageCompress($fileInfo); - $model = new UploadFile(); - $model->cx_mch_id = $this->cx_mch_id; - $model->user_id = Model::getUserId(); - $model->file_url = $fileInfo["url"]; - $model->extension = trim($fileInfo["type"],"."); - $model->type = $this->getFileType($model->extension); - $model->size = $fileInfo["size"]; - $model->group_id = \Yii::$app->request->get("group_id"); - $model->group_id = $model->group_id ? $model->group_id : 0; - $model->save(); - } - return $fileInfo; - } - - private function imageCompress(&$fileInfo) - { - $filetype = $this->getFileType(trim($fileInfo["type"],".")); - if($filetype != "image") - return; - $imageCompressConfig = $this->getImageCompressConfig(); - $filename = trim($fileInfo["url"],'/'); - if($imageCompressConfig['imageCompressEnable'] && file_exists($filename)){ - try{ - $gumletImagic = new ImageResize($filename); - $gumletImagic->resizeToLongSide($imageCompressConfig['imageCompressBorder']); - $gumletImagic->save($filename); - clearstatcache(); - } catch (ImageResizeException $ex){ - } - } - $fileInfo["size"] = filesize($filename); - } - - private function mkDir($dir, $mode = 0777) - { - return is_dir($dir) or $this->mkDir(dirname($dir), $mode) and mkdir($dir, $mode); - } - - private function getImageCompressConfig() - { - $config = []; - $imageCompressEnable = \Yii::$app->request->get('imageCompressEnable'); - if($imageCompressEnable !== null){ - $config['imageCompressEnable'] = $imageCompressEnable == 1 ? true : false; - } else { - $config['imageCompressEnable'] = $this->uploadConfig['uploadFile']['imageCompressEnable']; - } - - $imageCompressBorder = \Yii::$app->request->get('imageCompressBorder'); - if($imageCompressBorder !== null && is_numeric($imageCompressBorder)){ - $imageCompressBorder = (int)$imageCompressBorder; - $config['imageCompressBorder'] = $imageCompressBorder; - } else { - $config['imageCompressBorder'] = $this->uploadConfig['uploadFile']['imageCompressBorder']; - } - return $config; - } - - private function getFileType($extension) - { - $type_list = [ - 'image' => ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'ico'], - 'video' => ['mp4', 'flv', 'ogg', 'mov',], - ]; - foreach ($type_list as $type => $exs) { - if (in_array($extension, $exs)) { - return $type; - } - } - return ''; - } - - /** - * 获取已经上传的文件列表 - */ - private function getFileList($action){ - //获取上传配置 - $uploadConfig = $this->getUploadConfig($action); - $_path = $uploadConfig["path"]; - $_config = $uploadConfig["config"]; - - /* 判断类型 */ - switch ($action) { - /* 列出文件 */ - case 'listfile': - $_config['fileManagerListPath'] = $_path .$_config['fileManagerListPath']; - $allowFiles = $_config['fileManagerAllowFiles']; - $listSize = $_config['fileManagerListSize']; - $path = $_config['fileManagerListPath']; - break; - /* 列出图片 */ - case 'listimage': - default: - $_config['imageManagerListPath'] = $_path . $_config['imageManagerListPath']; - $allowFiles = $_config['imageManagerAllowFiles']; - $listSize = $_config['imageManagerListSize']; - $path = $_config['imageManagerListPath']; - } - $allowFiles = substr(str_replace(".", "|", join("", $allowFiles)), 1); - - /* 获取参数 */ - $size = isset($_GET['size']) ? htmlspecialchars($_GET['size']) : $listSize; - $start = isset($_GET['start']) ? htmlspecialchars($_GET['start']) : 0; - $end = $start + $size; - - /* 获取文件列表 */ - $path = $_SERVER['DOCUMENT_ROOT'] . (substr($path, 0, 1) == "/" ? "":"/") . $path; - $files = $this->getfiles($path, $allowFiles); - if (!count($files)) { - return json_encode(array( - "state" => "no match file", - "list" => array(), - "start" => $start, - "total" => count($files) - )); - } - - /* 获取指定范围的列表 */ - $len = count($files); - for ($i = min($end, $len) - 1, $list = array(); $i < $len && $i >= 0 && $i >= $start; $i--){ - $list[] = $files[$i]; - } - //倒序 - //for ($i = $end, $list = array(); $i < $len && $i < $end; $i++){ - // $list[] = $files[$i]; - //} - - /* 返回数据 */ - $result = json_encode(array( - "state" => "SUCCESS", - "list" => $list, - "start" => $start, - "total" => count($files) - )); - - return $result; - } - - /** - * 遍历获取目录下的指定类型的文件 - * @param $path - * @param array $files - * @return array - */ - private function getfiles($path, $allowFiles, &$files = array()) - { - if (!is_dir($path)) return null; - if(substr($path, strlen($path) - 1) != '/') $path .= '/'; - $handle = opendir($path); - while (false !== ($file = readdir($handle))) { - if ($file != '.' && $file != '..') { - $path2 = $path . $file; - if (is_dir($path2)) { - $this->getfiles($path2, $allowFiles, $files); - } else { - if (preg_match("/\.(".$allowFiles.")$/i", $file)) { - $files[] = array( - 'url'=> substr($path2, strlen($_SERVER['DOCUMENT_ROOT'])), - 'mtime'=> filemtime($path2) - ); - } - } - } - } - return $files; - } - - /** - * 获取上传路径前缀,及配置信息 - */ - private function getUploadConfig($action){ - - $path = UploadHelper::getUploadPath($this->cx_mch_id); - $config = $this->uploadConfig['uploadFile']; - - return array( - "path" => $path, - "config" => $config - ); - } - - /** - * 抓取远程图片 - */ - private function crawlerImage($action) { - set_time_limit(0); - //获取上传配置 - $uploadConfig = $this->getUploadConfig($action); - $_path = $uploadConfig["path"]; - $_config = $uploadConfig["config"]; - /* 上传配置 */ - $_config['catcherPathFormat'] = $_path . $_config['catcherPathFormat']; - $config = array( - "pathFormat" => $_config['catcherPathFormat'], - "maxSize" => $_config['catcherMaxSize'], - "allowFiles" => $_config['catcherAllowFiles'], - "oriName" => "remote.png" - ); - $fieldName = $_config['catcherFieldName']; - - /* 抓取远程图片 */ - $list = array(); - if (isset($_POST[$fieldName])) { - $source = $_POST[$fieldName]; - } else { - $source = $_GET[$fieldName]; - } - foreach ($source as $imgUrl) { - $item = new Uploader($imgUrl, $config, "remote"); - $info = $item->getFileInfo(); - array_push($list, array( - "state" => $info["state"], - "url" => $info["url"], - "size" => $info["size"], - "title" => htmlspecialchars($info["title"]), - "original" => htmlspecialchars($info["original"]), - "source" => htmlspecialchars($imgUrl) - )); - } - - /* 返回抓取数据 */ - return json_encode(array( - 'state'=> count($list) ? 'SUCCESS': 'ERROR', - 'list'=> $list - )); - } - - public function actionVideo() - { - set_time_limit (0); - $params = \Yii::$app->request->post(); - $tempDir = './temp/upload/video/chunks/'.date('Ymd',time()) . '/' . md5($params['name']); - if(!file_exists($tempDir)) - $this->mk_dir($tempDir); - if(!isset($params['chunk'])){ - $params['chunk'] = 0; - } - if(!isset($params['chunks'])){ - $params['chunks'] = 1; - } - //获取上传配置 - $action = 'uploadvideo'; - $uploadConfig = $this->getUploadConfig($action); - $config = array( - "pathFormat" => $tempDir . '/' .$params['chunk'], - "maxSize" => $uploadConfig['config']['videoMaxSize'], - "allowFiles" => $uploadConfig['config']['videoAllowFiles'] - ); - $base64 = "upload"; - /* 生成上传实例对象并完成上传 */ - $up = new Uploader('file', $config, $base64); - $fileInfo = $up->getFileInfo(); - $chunk = strval($params['chunk']); - $chunkCount = strval($params['chunks']); - if($chunk + 1 == $chunkCount){ - //合并 - $targetDir = './upload/video/'.date('Ymd',time()). '/' . md5($params['name']); - if(!file_exists($targetDir)) - $this->mk_dir($targetDir); - $finalName = $targetDir . $fileInfo['type']; - if(file_exists($finalName)) - unlink($finalName); - $file = fopen($finalName, 'wb'); - for($index = 0; $index < $chunkCount; $index++){ - $tmpFile = $tempDir . '/'. $index . $fileInfo['type']; - $chunkFile = fopen($tmpFile, 'rb'); - $content = fread($chunkFile, filesize($tmpFile)); - fclose($chunkFile); - fwrite($file, $content); - - //删除chunk文件 - unlink($tmpFile); - } - fclose($file); - //删除chunk文件夹 - rmdir($targetDir); - $fileInfo['url'] = $finalName; - } - /* 返回数据 */ - \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; - return $fileInfo; - } - - private function mk_dir($dir,$mode = 0777) - { - return is_dir($dir) or $this->mk_dir(dirname($dir),$mode) and mkdir($dir,$mode); - } - - //上传图片 - public function actionUnionImage() - { - if(!\Yii::$app->request->isPost){ - $data = [ - 'code' => 1, - 'msg' => "Invalid Request" - ]; - return $this->responseHandler($data); - } - $action = "uploadimageUnion"; - $fileInfo = $this->uploadFile($action); - if($fileInfo["state"] == "SUCCESS"){ - $data = [ - 'code' => 0, - 'msg' => 'success', - 'data' => [ - 'url' => $fileInfo['url'], - 'extension' => $fileInfo["type"], - 'size' => $fileInfo["size"], - 'type' => $this->getFileType(trim($fileInfo['type'],".")) - ] - ]; - } else { - $data = [ - 'code' => 1, - 'msg' => $fileInfo["state"] - ]; - } - return $this->responseHandler($data); - } + [ + /* 文件上传的根目录 */ + //'rootPath' => $_SERVER['DOCUMENT_ROOT'], + /* 上传图片配置项 */ + "imageActionName" => "uploadimage", + /* 执行上传图片的action名称 */ + "imageFieldName" => "file", + /* 提交的图片表单名称 */ + "imageMaxSize" => 20480000, + /* 银联文件上传大小限制,单位B */ + "imageMaxSize_union" => 2097152, + /* 上传大小限制,单位B */ + "imageAllowFiles" => [ + ".png", + ".jpg", + ".jpeg", + ".gif", + ".ico", + ".bmp" + ], + /* 上传图片格式显示 */ + "imageCompressEnable" => true, + /* 是否压缩图片,默认是true */ + "imageCompressBorder" => 800, + /* 图片压缩最长边限制 */ + "imageInsertAlign" => "none", + /* 插入的图片浮动方式 */ + "imageUrlPrefix" => "", + /* 图片访问路径前缀 */ + "imagePathFormat" => "/upload/image/{yyyy}/{mm}{dd}/{time}{rand:6}", + /* 上传保存路径,可以自定义保存路径和文件名格式 */ + /* {filename} 会替换成原文件名,配置这项需要注意中文乱码问题 */ + /* {rand:6} 会替换成随机数,后面的数字是随机数的位数 */ + /* {time} 会替换成时间戳 */ + /* {yyyy} 会替换成四位年份 */ + /* {yy} 会替换成两位年份 */ + /* {mm} 会替换成两位月份 */ + /* {dd} 会替换成两位日期 */ + /* {hh} 会替换成两位小时 */ + /* {ii} 会替换成两位分钟 */ + /* {ss} 会替换成两位秒 */ + /* 非法字符 \ => * ? " < > | */ + /* 具请体看线上文档=> fex.baidu.com/ueditor/#use-format_upload_filename */ + + /* 涂鸦图片上传配置项 */ + "scrawlActionName" => "uploadscrawl", + /* 执行上传涂鸦的action名称 */ + "scrawlFieldName" => "file", + /* 提交的图片表单名称 */ + "scrawlPathFormat" => "/upload/image/{yyyy}/{mm}{dd}/{time}{rand:6}", + /* 上传保存路径,可以自定义保存路径和文件名格式 */ + "scrawlMaxSize" => 2048000, + /* 上传大小限制,单位B */ + "scrawlUrlPrefix" => "", + /* 图片访问路径前缀 */ + "scrawlInsertAlign" => "none", + /* 截图工具上传 */ + "snapscreenActionName" => "uploadimage", + /* 执行上传截图的action名称 */ + "snapscreenPathFormat" => "/upload/image/{yyyy}/{mm}{dd}/{time}{rand:6}", + /* 上传保存路径,可以自定义保存路径和文件名格式 */ + "snapscreenUrlPrefix" => "", + /* 图片访问路径前缀 */ + "snapscreenInsertAlign" => "none", + /* 插入的图片浮动方式 */ + + /* 抓取远程图片配置 */ + "catcherLocalDomain" => [ + "127.0.0.1", + "localhost", + "img.baidu.com" + ], + "catcherActionName" => "catchimage", + /* 执行抓取远程图片的action名称 */ + "catcherFieldName" => "source", + /* 提交的图片列表表单名称 */ + "catcherPathFormat" => "/upload/image/{yyyy}/{mm}{dd}/{time}{rand:6}", + /* 上传保存路径,可以自定义保存路径和文件名格式 */ + "catcherUrlPrefix" => "", + /* 图片访问路径前缀 */ + "catcherMaxSize" => 2048000, + /* 上传大小限制,单位B */ + "catcherAllowFiles" => [ + ".png", + ".jpg", + ".jpeg", + ".gif", + ".ico", + ".bmp" + ], + /* 抓取图片格式显示 */ + + /* 上传视频配置 */ + "videoActionName" => "uploadvideo", + /* 执行上传视频的action名称 */ + "videoFieldName" => "file", + /* 提交的视频表单名称 */ + "videoPathFormat" => "/upload/video/{yyyy}/{mm}{dd}/{time}{rand:6}", + /* 上传保存路径,可以自定义保存路径和文件名格式 */ + "videoUrlPrefix" => "", + /* 视频访问路径前缀 */ + // "videoMaxSize" => 5120000, + "videoMaxSize" => 52428800, + /* 上传大小限制,单位B,默认100MB */ + "videoAllowFiles" => [ + ".flv", +// ".swf", +// ".mkv", +// ".avi", +// ".rm", + ".rmvb", + ".mpeg", + ".mpg", +// ".ogg", +// ".ogv", +// ".mov", + ".wmv", + ".mp4", +// ".webm", + ".mp3", + ".wav", +// ".mid" + ], + /* 上传视频格式显示 */ + + /* 上传文件配置 */ + "fileActionName" => "uploadfile", + /* controller里,执行上传视频的action名称 */ + "fileFieldName" => "file", + /* 提交的文件表单名称 */ + "filePathFormat" => "/upload/file/{yyyy}/{mm}{dd}/{time}{rand:6}", + /* 上传保存路径,可以自定义保存路径和文件名格式 */ + "fileUrlPrefix" => "", + /* 文件访问路径前缀 */ + "fileMaxSize" => 51200000, + /* 上传大小限制,单位B,默认50MB */ + "fileAllowFiles" => [ + ".png", + ".jpg", + ".jpeg", + ".gif", + ".ico", + ".bmp", + ".flv", + //".swf", + //".mkv", + ".avi", + //".rm", + ".rmvb", + //".mpeg", + //".mpg", + ".ogg", + //".ogv", + //".mov", + ".wmv", + ".mp4", + //".webm", + ".mp3", + ".wav", + //".mid", + ".rar", + ".zip", + //".tar", + //".gz", + //".7z", + //".bz2", + //".cab", + //".iso", + ".doc", + ".docx", + ".xls", + ".xlsx", + ".ppt", + ".pptx", + ".pdf", + ".txt", + ".md", + ".ply", + ".xml" + ], + /* 上传文件格式显示 */ + + /* 列出指定目录下的图片 */ + "imageManagerActionName" => "listimage", + /* 执行图片管理的action名称 */ + "imageManagerListPath" => "/upload/image/", + /* 指定要列出图片的目录 */ + "imageManagerListSize" => 20, + /* 每次列出文件数量 */ + "imageManagerUrlPrefix" => "", + /* 图片访问路径前缀 */ + "imageManagerInsertAlign" => "none", + /* 插入的图片浮动方式 */ + "imageManagerAllowFiles" => [ + ".png", + ".jpg", + ".jpeg", + ".gif", + ".ico", + ".bmp" + ], + /* 列出的文件类型 */ + + /* 列出指定目录下的文件 */ + "fileManagerActionName" => "listfile", + /* 执行文件管理的action名称 */ + "fileManagerListPath" => "/upload/file/", + /* 指定要列出文件的目录 */ + "fileManagerUrlPrefix" => "", + /* 文件访问路径前缀 */ + "fileManagerListSize" => 20, + /* 每次列出文件数量 */ + "fileManagerAllowFiles" => [ + ".png", + ".jpg", + ".jpeg", + ".gif", + ".ico", + ".bmp", + ".flv", + ".swf", + ".mkv", + ".avi", + ".rm", + ".rmvb", + ".mpeg", + ".mpg", + ".ogg", + ".ogv", + ".mov", + ".wmv", + ".mp4", + ".webm", + ".mp3", + ".wav", + ".mid", + ".rar", + ".zip", + ".tar", + ".gz", + ".7z", + ".bz2", + ".cab", + ".iso", + ".doc", + ".docx", + ".xls", + ".xlsx", + ".ppt", + ".pptx", + ".pdf", + ".txt", + ".md", + ".xml" + ] + /* 列出的文件类型 */ + ] + ]; + + public function actionIndex() + { + //设置允许的跨域header + header('Access-Control-Allow-Headers: X-Requested-With,X_Requested_With'); + $action = Yii::$app->request->get("action"); + $action = htmlspecialchars($action); + switch ($action) { + case 'config': + $result = json_encode($this->uploadConfig['uploadFile']); + break; + /* 上传图片 */ + case 'uploadimage': + /* 上传涂鸦 */ + case 'uploadscrawl': + /* 上传视频 */ + case 'uploadvideo': + /* 上传文件 */ + case 'uploadfile': + if(isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] == "OPTIONS"){ + //判断实际发送的请求是否安全 + $result = ""; + } else { + if(Yii::$app->request->isPost && !empty($_FILES)){ + //上传 + $currentFileInfo = $this->uploadFile($action); + $result = json_encode($currentFileInfo); + } else { + $result = ""; + } + } + break; + + /* 列出图片 */ + case 'listimage': + if(isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] == "OPTIONS"){ + $result = ""; + } else { + //返回结果 + $result = $this->getFileList($action); + } + break; + /* 列出文件 */ + case 'listfile': + if(isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] == "OPTIONS"){ + $result = ""; + } else { + //返回结果 + $result = $this->getFileList($action); + } + break; + + /* 抓取远程文件 */ + case 'catchimage': + if(isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] == "OPTIONS"){ + $result = ""; + } else { + //返回结果 + $result = $this->crawlerImage($action); + } + break; + + default: + $result = json_encode(array( + 'state'=> '请求地址出错' + )); + break; + } + + /* 输出结果 */ + if (isset($_GET["callback"])) { + if (preg_match("/^[\w_]+$/", $_GET["callback"])) { + echo htmlspecialchars($_GET["callback"]) . '(' . $result . ')'; + } else { + echo json_encode(array( + 'state'=> 'callback参数不合法' + )); + } + } else { + echo $result; + } + } + + //上传图片 + public function actionImage() + { + if(!\Yii::$app->request->isPost){ + $data = [ + 'code' => 1, + 'msg' => "Invalid Request" + ]; + return $this->responseHandler($data); + } + $action = "uploadimage"; + $fileInfo = $this->uploadFile($action); + if($fileInfo["state"] == "SUCCESS"){ + $data = [ + 'code' => 0, + 'msg' => 'success', + 'data' => [ + 'url' => $fileInfo['url'], + 'extension' => $fileInfo["type"], + 'size' => $fileInfo["size"], + 'type' => $this->getFileType(trim($fileInfo['type'],".")) + ] + ]; + } else { + $data = [ + 'code' => 1, + 'msg' => $fileInfo["state"] + ]; + } + return $this->responseHandler($data); + } + + //上传文件 + public function actionFile() + { + try { + if(!\Yii::$app->request->isPost){ + $data = [ + 'code' => 1, + 'msg' => "Invalid Request" + ]; + return $this->responseHandler($data); + } + $action = "uploadfile"; + $fileInfo = $this->uploadFile($action); + if($fileInfo["state"] == "SUCCESS"){ + $data = [ + 'code' => 0, + 'msg' => 'success', + 'data' => [ + 'url' => $fileInfo['url'], + 'extension' => $fileInfo["type"], + 'size' => $fileInfo["size"], + 'type' => $this->getFileType(trim($fileInfo['type'],".")) + ] + ]; + } else { + $data = [ + 'code' => 1, + 'msg' => $fileInfo["state"] + ]; + } + + }catch (\Exception $e){ + $data = [ + 'code' => 1, + 'msg' => $e->getMessage() + ]; + } + return $this->responseHandler($data); + } + + //上传视频 + public function actionVideoFile() + { + if(!\Yii::$app->request->isPost){ + $data = [ + 'code' => 1, + 'msg' => "Invalid Request" + ]; + } + $action = "uploadvideo"; + $fileInfo = $this->uploadFile($action); + if($fileInfo["state"] == "SUCCESS"){ + $data = [ + 'code' => 0, + 'msg' => 'success', + 'data' => [ + 'url' => $fileInfo['url'], + 'extension' => $fileInfo["type"], + 'size' => $fileInfo["size"], + 'type' => $this->getFileType(trim($fileInfo['type'],".")) + ] + ]; + } else { + $data = [ + 'code' => 1, + 'msg' => $fileInfo["state"] + ]; + } + return $this->responseHandler($data); + } + + + /** + * @TODO 扩展上传至第三方存储 + * 文件上传 + */ + private function uploadFile($action){ + //获取上传配置 + $uploadConfig = $this->getUploadConfig($action); + $path = $uploadConfig["path"]; + $_config = $uploadConfig["config"]; + + /* 上传配置 */ + $base64 = "upload"; + switch ($action) { + case 'uploadimage': + $_config['imagePathFormat'] = $path . $_config['imagePathFormat']; + $config = array( + "pathFormat" => $_config['imagePathFormat'], + "maxSize" => $_config['imageMaxSize'], + "allowFiles" => $_config['imageAllowFiles'] + ); + $fieldName = $_config['imageFieldName']; + break; + case 'uploadscrawl': + $_config['scrawlPathFormat'] = $path . $_config['scrawlPathFormat']; + $config = array( + "pathFormat" => $_config['scrawlPathFormat'], + "maxSize" => $_config['scrawlMaxSize'], + "allowFiles" => $_config['scrawlAllowFiles'], + "oriName" => "scrawl.png" + ); + $fieldName = $_config['scrawlFieldName']; + $base64 = "base64"; + break; + case 'uploadvideo': + $_config['videoPathFormat'] = $path . $_config['videoPathFormat']; + $config = array( + "pathFormat" => $_config['videoPathFormat'], + "maxSize" => $_config['videoMaxSize'], + "allowFiles" => $_config['videoAllowFiles'] + ); + $fieldName = $_config['videoFieldName']; + break; + case 'uploadimageUnion': + #########2022/06/10##################### + $_config['imagePathFormat'] = $path . $_config['imagePathFormat']; + $config = array( + "pathFormat" => $_config['imagePathFormat'], + "maxSize" => $_config['imageMaxSize_union'], + "allowFiles" => $_config['imageAllowFiles'] + ); + $fieldName = $_config['imageFieldName']; + break; + case 'uploadfile': + default: + $_config['filePathFormat'] = $path . $_config['filePathFormat']; + $config = array( + "pathFormat" => $_config['filePathFormat'], + "maxSize" => $_config['fileMaxSize'], + "allowFiles" => $_config['fileAllowFiles'] + ); + $fieldName = $_config['fileFieldName']; + break; + } + + /* 生成上传实例对象并完成上传 */ + $up = new Uploader($fieldName, $config, $base64); + /** + * 得到上传文件所对应的各个参数,数组结构 + * array( + * "state" => "", //上传状态,上传成功时必须返回"SUCCESS" + * "url" => "", //返回的地址 + * "title" => "", //新文件名 + * "original" => "", //原始文件名 + * "type" => "" //文件类型 + * "size" => "", //文件大小 + * ) + */ + + /* 返回数据 */ + $fileInfo = $up->getFileInfo(); + if($fileInfo["state"] == "SUCCESS"){ + $this->imageCompress($fileInfo); + $model = new UploadFile(); + $model->cx_mch_id = $this->cx_mch_id; + $model->user_id = Model::getUserId(); + $model->file_url = $fileInfo["url"]; + $model->extension = trim($fileInfo["type"],"."); + $model->type = $this->getFileType($model->extension); + $model->size = $fileInfo["size"]; + $model->group_id = \Yii::$app->request->get("group_id"); + $model->group_id = $model->group_id ? $model->group_id : 0; + $model->save(); + } + return $fileInfo; + } + + private function imageCompress(&$fileInfo) + { + $filetype = $this->getFileType(trim($fileInfo["type"],".")); + if($filetype != "image") + return; + $imageCompressConfig = $this->getImageCompressConfig(); + $filename = trim($fileInfo["url"],'/'); + if($imageCompressConfig['imageCompressEnable'] && file_exists($filename)){ + try{ + $gumletImagic = new ImageResize($filename); + $gumletImagic->resizeToLongSide($imageCompressConfig['imageCompressBorder']); + $gumletImagic->save($filename); + clearstatcache(); + } catch (ImageResizeException $ex){ + } + } + $fileInfo["size"] = filesize($filename); + } + + private function mkDir($dir, $mode = 0777) + { + return is_dir($dir) or $this->mkDir(dirname($dir), $mode) and mkdir($dir, $mode); + } + + private function getImageCompressConfig() + { + $config = []; + $imageCompressEnable = \Yii::$app->request->get('imageCompressEnable'); + if($imageCompressEnable !== null){ + $config['imageCompressEnable'] = $imageCompressEnable == 1 ? true : false; + } else { + $config['imageCompressEnable'] = $this->uploadConfig['uploadFile']['imageCompressEnable']; + } + + $imageCompressBorder = \Yii::$app->request->get('imageCompressBorder'); + if($imageCompressBorder !== null && is_numeric($imageCompressBorder)){ + $imageCompressBorder = (int)$imageCompressBorder; + $config['imageCompressBorder'] = $imageCompressBorder; + } else { + $config['imageCompressBorder'] = $this->uploadConfig['uploadFile']['imageCompressBorder']; + } + return $config; + } + + private function getFileType($extension) + { + $type_list = [ + 'image' => ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'ico'], + 'video' => ['mp4', 'flv', 'ogg', 'mov',], + ]; + foreach ($type_list as $type => $exs) { + if (in_array($extension, $exs)) { + return $type; + } + } + return ''; + } + + /** + * 获取已经上传的文件列表 + */ + private function getFileList($action){ + //获取上传配置 + $uploadConfig = $this->getUploadConfig($action); + $_path = $uploadConfig["path"]; + $_config = $uploadConfig["config"]; + + /* 判断类型 */ + switch ($action) { + /* 列出文件 */ + case 'listfile': + $_config['fileManagerListPath'] = $_path .$_config['fileManagerListPath']; + $allowFiles = $_config['fileManagerAllowFiles']; + $listSize = $_config['fileManagerListSize']; + $path = $_config['fileManagerListPath']; + break; + /* 列出图片 */ + case 'listimage': + default: + $_config['imageManagerListPath'] = $_path . $_config['imageManagerListPath']; + $allowFiles = $_config['imageManagerAllowFiles']; + $listSize = $_config['imageManagerListSize']; + $path = $_config['imageManagerListPath']; + } + $allowFiles = substr(str_replace(".", "|", join("", $allowFiles)), 1); + + /* 获取参数 */ + $size = isset($_GET['size']) ? htmlspecialchars($_GET['size']) : $listSize; + $start = isset($_GET['start']) ? htmlspecialchars($_GET['start']) : 0; + $end = $start + $size; + + /* 获取文件列表 */ + $path = $_SERVER['DOCUMENT_ROOT'] . (substr($path, 0, 1) == "/" ? "":"/") . $path; + $files = $this->getfiles($path, $allowFiles); + if (!count($files)) { + return json_encode(array( + "state" => "no match file", + "list" => array(), + "start" => $start, + "total" => count($files) + )); + } + + /* 获取指定范围的列表 */ + $len = count($files); + for ($i = min($end, $len) - 1, $list = array(); $i < $len && $i >= 0 && $i >= $start; $i--){ + $list[] = $files[$i]; + } + //倒序 + //for ($i = $end, $list = array(); $i < $len && $i < $end; $i++){ + // $list[] = $files[$i]; + //} + + /* 返回数据 */ + $result = json_encode(array( + "state" => "SUCCESS", + "list" => $list, + "start" => $start, + "total" => count($files) + )); + + return $result; + } + + /** + * 遍历获取目录下的指定类型的文件 + * @param $path + * @param array $files + * @return array + */ + private function getfiles($path, $allowFiles, &$files = array()) + { + if (!is_dir($path)) return null; + if(substr($path, strlen($path) - 1) != '/') $path .= '/'; + $handle = opendir($path); + while (false !== ($file = readdir($handle))) { + if ($file != '.' && $file != '..') { + $path2 = $path . $file; + if (is_dir($path2)) { + $this->getfiles($path2, $allowFiles, $files); + } else { + if (preg_match("/\.(".$allowFiles.")$/i", $file)) { + $files[] = array( + 'url'=> substr($path2, strlen($_SERVER['DOCUMENT_ROOT'])), + 'mtime'=> filemtime($path2) + ); + } + } + } + } + return $files; + } + + /** + * 获取上传路径前缀,及配置信息 + */ + private function getUploadConfig($action){ + + $path = UploadHelper::getUploadPath($this->cx_mch_id); + $config = $this->uploadConfig['uploadFile']; + + return array( + "path" => $path, + "config" => $config + ); + } + + /** + * 抓取远程图片 + */ + private function crawlerImage($action) { + set_time_limit(0); + //获取上传配置 + $uploadConfig = $this->getUploadConfig($action); + $_path = $uploadConfig["path"]; + $_config = $uploadConfig["config"]; + /* 上传配置 */ + $_config['catcherPathFormat'] = $_path . $_config['catcherPathFormat']; + $config = array( + "pathFormat" => $_config['catcherPathFormat'], + "maxSize" => $_config['catcherMaxSize'], + "allowFiles" => $_config['catcherAllowFiles'], + "oriName" => "remote.png" + ); + $fieldName = $_config['catcherFieldName']; + + /* 抓取远程图片 */ + $list = array(); + if (isset($_POST[$fieldName])) { + $source = $_POST[$fieldName]; + } else { + $source = $_GET[$fieldName]; + } + foreach ($source as $imgUrl) { + $item = new Uploader($imgUrl, $config, "remote"); + $info = $item->getFileInfo(); + array_push($list, array( + "state" => $info["state"], + "url" => $info["url"], + "size" => $info["size"], + "title" => htmlspecialchars($info["title"]), + "original" => htmlspecialchars($info["original"]), + "source" => htmlspecialchars($imgUrl) + )); + } + + /* 返回抓取数据 */ + return json_encode(array( + 'state'=> count($list) ? 'SUCCESS': 'ERROR', + 'list'=> $list + )); + } + + public function actionVideo() + { + set_time_limit (0); + $params = \Yii::$app->request->post(); + $tempDir = './temp/upload/video/chunks/'.date('Ymd',time()) . '/' . md5($params['name']); + if(!file_exists($tempDir)) + $this->mk_dir($tempDir); + if(!isset($params['chunk'])){ + $params['chunk'] = 0; + } + if(!isset($params['chunks'])){ + $params['chunks'] = 1; + } + //获取上传配置 + $action = 'uploadvideo'; + $uploadConfig = $this->getUploadConfig($action); + $config = array( + "pathFormat" => $tempDir . '/' .$params['chunk'], + "maxSize" => $uploadConfig['config']['videoMaxSize'], + "allowFiles" => $uploadConfig['config']['videoAllowFiles'] + ); + $base64 = "upload"; + /* 生成上传实例对象并完成上传 */ + $up = new Uploader('file', $config, $base64); + $fileInfo = $up->getFileInfo(); + $chunk = strval($params['chunk']); + $chunkCount = strval($params['chunks']); + if($chunk + 1 == $chunkCount){ + //合并 + $targetDir = './upload/video/'.date('Ymd',time()). '/' . md5($params['name']); + if(!file_exists($targetDir)) + $this->mk_dir($targetDir); + $finalName = $targetDir . $fileInfo['type']; + if(file_exists($finalName)) + unlink($finalName); + $file = fopen($finalName, 'wb'); + for($index = 0; $index < $chunkCount; $index++){ + $tmpFile = $tempDir . '/'. $index . $fileInfo['type']; + $chunkFile = fopen($tmpFile, 'rb'); + $content = fread($chunkFile, filesize($tmpFile)); + fclose($chunkFile); + fwrite($file, $content); + + //删除chunk文件 + unlink($tmpFile); + } + fclose($file); + //删除chunk文件夹 + rmdir($targetDir); + $fileInfo['url'] = $finalName; + } + /* 返回数据 */ + \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; + return $fileInfo; + } + + private function mk_dir($dir,$mode = 0777) + { + return is_dir($dir) or $this->mk_dir(dirname($dir),$mode) and mkdir($dir,$mode); + } + + //上传图片 + public function actionUnionImage() + { + if(!\Yii::$app->request->isPost){ + $data = [ + 'code' => 1, + 'msg' => "Invalid Request" + ]; + return $this->responseHandler($data); + } + $action = "uploadimageUnion"; + $fileInfo = $this->uploadFile($action); + if($fileInfo["state"] == "SUCCESS"){ + $data = [ + 'code' => 0, + 'msg' => 'success', + 'data' => [ + 'url' => $fileInfo['url'], + 'extension' => $fileInfo["type"], + 'size' => $fileInfo["size"], + 'type' => $this->getFileType(trim($fileInfo['type'],".")) + ] + ]; + } else { + $data = [ + 'code' => 1, + 'msg' => $fileInfo["state"] + ]; + } + return $this->responseHandler($data); + } } \ No newline at end of file diff --git a/modules/store/controllers/DevController.php b/modules/store/controllers/DevController.php new file mode 100644 index 0000000..216888b --- /dev/null +++ b/modules/store/controllers/DevController.php @@ -0,0 +1,104 @@ + [ + 'class' => LoginBehavior::className(), + ], + ]); + } + + //设备列表 + public function actionIndex() + { + if (\Yii::$app->request->isAjax) { + $form = new DevtListForm(); + $form->store_id = \Yii::$app->store->identity->store_id; + $form->attributes = \Yii::$app->request->get(); + $data = $form->search(); + return $this->responseHandler($data); + } + return $this->render('index', []); + + } + + + //添加设备 + public function actionEdit($id = 0) + { + $model = Dev::findOne([ + 'id' => $id, + ]); + if ($model == null) + $model = new Dev(); + + + if (\Yii::$app->request->isAjax) { + $form = new DevEditForm(); + $form->store_id = \Yii::$app->store->identity->store_id; + $form->model = $model; + $form->attributes = \Yii::$app->request->post(); + + $data = $form->edit(); + return $this->responseHandler($data); + } + + $return_url = \Yii::$app->request->referrer; + return $this->render("edit", [ + 'model' => $model, + 'return_url' => $return_url, + ]); + } + + + //设备二维码 + public function actionQrcode($id = 0) + { + if (!\Yii::$app->request->isPost) { + $data = $this->invaildRequest(); + return $this->responseHandler($data); + } + $form = new DevActionForm(); + $form->attributes = \Yii::$app->request->post(); + $data = $form->getBallQrcode(); + return $this->responseHandler($data); + } + + public function actionBatchQrcode() + { + $form = new DevActionForm(); + $data = $form->BatchQrcode(); + return $this->responseHandler($data); + } + +} \ No newline at end of file diff --git a/modules/store/controllers/ReportController.php b/modules/store/controllers/ReportController.php index 5858a7d..ece861f 100644 --- a/modules/store/controllers/ReportController.php +++ b/modules/store/controllers/ReportController.php @@ -1,91 +1,92 @@ - [ - 'class' => LoginBehavior::className(), - ], - ]); - } - - //报告列表 - public function actionIndex() - { - if (\Yii::$app->request->isAjax) { - $form = new ReportListForm(); - $form->store_id = \Yii::$app->store->identity->store_id; - $form->attributes = \Yii::$app->request->get(); - $data = $form->search(); - return $this->responseHandler($data); - } - return $this->render('index', []); - - } - - - public function actionEdit($id = 0) - { - $model = Report::findOne([ - 'id' => $id, - ]); - if ($model == null) - $model = new Report(); - - - $store_user_id = \Yii::$app->store->identity->user_id; - $storeUser = StoreUser::findOne(['user_id' => $store_user_id]); - - if (\Yii::$app->request->isAjax) { - $form = new ReportEditForm(); - $form->store_id = \Yii::$app->store->identity->store_id; - $form->model = $model; - $form->user_type = $storeUser->user_type; - $form->attributes = \Yii::$app->request->post(); - - $data = $form->edit(); - return $this->responseHandler($data); - } - - if ($model != null) { - $user = User::findOne(['id' => $model->user_id]); - } - - - $report_name = $storeUser->user_type == 1 ? '初始模型' : '最终模型'; - - $return_url = \Yii::$app->request->referrer; - - return $this->render("edit", [ - 'model' => $model, - 'return_url' => $return_url, - 'user' => $user, - 'storeUser' => $storeUser, - 'report_name' => $report_name - ]); - } + [ + 'class' => LoginBehavior::className(), + ], + ]); + } + + //报告列表 + public function actionIndex() + { + if (\Yii::$app->request->isAjax) { + $form = new ReportListForm(); + $form->store_id = \Yii::$app->store->identity->store_id; + $form->user_id = \Yii::$app->store->identity->user_id; + $form->attributes = \Yii::$app->request->get(); + $data = $form->search(); + return $this->responseHandler($data); + } + return $this->render('index', []); + + } + + + public function actionEdit($id = 0) + { + $model = Report::findOne([ + 'id' => $id, + ]); + if ($model == null) + $model = new Report(); + + + $store_user_id = \Yii::$app->store->identity->user_id; + $storeUser = StoreUser::findOne(['user_id' => $store_user_id]); + + if (\Yii::$app->request->isAjax) { + $form = new ReportEditForm(); + $form->store_id = \Yii::$app->store->identity->store_id; + $form->model = $model; + $form->user_type = $storeUser->user_type; + $form->attributes = \Yii::$app->request->post(); + + $data = $form->edit(); + return $this->responseHandler($data); + } + + if ($model != null) { + $user = User::findOne(['id' => $model->user_id]); + } + + + $report_name = $storeUser->user_type == 1 ? '初始模型' : '最终模型'; + + $return_url = \Yii::$app->request->referrer; + + return $this->render("edit", [ + 'model' => $model, + 'return_url' => $return_url, + 'user' => $user, + 'storeUser' => $storeUser, + 'report_name' => $report_name + ]); + } } \ No newline at end of file diff --git a/modules/store/models/Menu.php b/modules/store/models/Menu.php index b431c2e..c9c5d87 100644 --- a/modules/store/models/Menu.php +++ b/modules/store/models/Menu.php @@ -1,133 +1,156 @@ - '主页', - 'is_menu' => true, - 'is_show' => true, - 'route' => "store/default/index", - 'icon' => 'layui-icon-home', - 'children' => [ - ], - ], - /*[ - 'name' => '人员管理', - 'is_menu' => true, - 'is_show' => true, - 'route' => null, - 'icon' => 'layui-icon-user', - 'children' => [ - [ - 'name' => '人员列表', - 'is_menu' => true, - 'is_show' => true, - 'route' => 'store/store/store-user', - ], - [ - 'name' => '创建/编辑人员', - 'is_menu' => true, - 'is_show' => true, - 'route' => 'store/store/store-user-edit', - ], - ], - ],*/ - - [ - 'name' => '报告管理', - 'is_menu' => true, - 'is_show' => true, - 'route' => null, - 'icon' => 'layui-icon-list', - 'children' => [ - [ - 'name' => '报告列表', - 'is_menu' => true, - 'is_show' => true, - 'route' => 'store/report/index', - ], - [ - 'name' => '上传报告', - 'is_menu' => true, - 'is_show' => false, - 'route' => 'store/report/edit', - ], - ], - ], -// [ -// 'name' => '财务管理', -// 'is_menu' => true, -// 'is_show' => true, -// 'route' => null, -// 'icon' => 'layui-icon-rmb', -// 'children' => [ -// /** -// * [ -// * 'name' => '提现管理', -// * 'is_menu' => true, -// * 'is_show' => true, -// * 'route' => null, -// * 'children' => [ -// * [ -// * 'name' => '提现列表', -// * 'is_menu' => true, -// * 'is_show' => true, -// * 'route' => 'store/cash/index', -// * ], -// * [ -// * 'name' => '提现设置', -// * 'is_menu' => true, -// * 'is_show' => true, -// * 'route' => 'store/cash/setting', -// * ], -// * ], -// * ], -// * */ -// [ -// 'name' => '门店收益', -// 'is_menu' => true, -// 'is_show' => true, -// 'route' => 'store/store/store-earings', -// ], -// [ -// 'name' => '数据图表', -// 'is_menu' => true, -// 'is_show' => true, -// 'route' => 'store/store/bind', -// ], -// -// ], -// ], - [ - 'name' => '设置', - 'is_menu' => true, - 'is_show' => true, - 'route' => null, - 'icon' => 'layui-icon-set', - 'children' => [ - [ - 'name' => '密码修改', - 'is_menu' => true, - 'is_show' => true, - 'route' => 'store/setting/password', - ], - ] - ], - ]; - } -} + '主页', + 'is_menu' => true, + 'is_show' => true, + 'route' => "store/default/index", + 'icon' => 'layui-icon-home', + 'children' => [ + ], + ], + /*[ + 'name' => '人员管理', + 'is_menu' => true, + 'is_show' => true, + 'route' => null, + 'icon' => 'layui-icon-user', + 'children' => [ + [ + 'name' => '人员列表', + 'is_menu' => true, + 'is_show' => true, + 'route' => 'store/store/store-user', + ], + [ + 'name' => '创建/编辑人员', + 'is_menu' => true, + 'is_show' => true, + 'route' => 'store/store/store-user-edit', + ], + ], + ],*/ + + [ + 'name' => '报告管理', + 'is_menu' => true, + 'is_show' => true, + 'route' => null, + 'icon' => 'layui-icon-list', + 'children' => [ + [ + 'name' => '报告列表', + 'is_menu' => true, + 'is_show' => true, + 'route' => 'store/report/index', + ], + [ + 'name' => '上传报告', + 'is_menu' => true, + 'is_show' => false, + 'route' => 'store/report/edit', + ], + ], + ], + [ + 'name' => '设备管理', + 'is_menu' => true, + 'is_show' => true, + 'route' => null, + 'icon' => 'layui-icon-list', + 'children' => [ + [ + 'name' => '设备列表', + 'is_menu' => true, + 'is_show' => true, + 'route' => 'store/dev/index', + ], + [ + 'name' => '添加/编辑设备', + 'is_menu' => true, + 'is_show' => true, + 'route' => 'store/dev/edit', + ], + ], + ], + + +// [ +// 'name' => '财务管理', +// 'is_menu' => true, +// 'is_show' => true, +// 'route' => null, +// 'icon' => 'layui-icon-rmb', +// 'children' => [ +// /** +// * [ +// * 'name' => '提现管理', +// * 'is_menu' => true, +// * 'is_show' => true, +// * 'route' => null, +// * 'children' => [ +// * [ +// * 'name' => '提现列表', +// * 'is_menu' => true, +// * 'is_show' => true, +// * 'route' => 'store/cash/index', +// * ], +// * [ +// * 'name' => '提现设置', +// * 'is_menu' => true, +// * 'is_show' => true, +// * 'route' => 'store/cash/setting', +// * ], +// * ], +// * ], +// * */ +// [ +// 'name' => '门店收益', +// 'is_menu' => true, +// 'is_show' => true, +// 'route' => 'store/store/store-earings', +// ], +// [ +// 'name' => '数据图表', +// 'is_menu' => true, +// 'is_show' => true, +// 'route' => 'store/store/bind', +// ], +// +// ], +// ], + [ + 'name' => '设置', + 'is_menu' => true, + 'is_show' => true, + 'route' => null, + 'icon' => 'layui-icon-set', + 'children' => [ + [ + 'name' => '密码修改', + 'is_menu' => true, + 'is_show' => true, + 'route' => 'store/setting/password', + ], + ] + ], + ]; + } +} diff --git a/modules/store/models/dev/DevActionForm.php b/modules/store/models/dev/DevActionForm.php new file mode 100644 index 0000000..a8f0110 --- /dev/null +++ b/modules/store/models/dev/DevActionForm.php @@ -0,0 +1,178 @@ + '选择项', + ]; + } + + + public function getBallQrcode() + { + $ball = Dev::findOne($this->ids); + if ($ball == null) { + return ['code' => 1, 'msg' => '该设备不存在']; + } + $store = Store::findOne($ball->store_id); + if ($store == null) { + return ['code' => 1, 'msg' => '该设备所在门店不存在']; + } + + return $this->getQrcode($store, $ball); + } + + + /** + * @param $store + * @param $ball + * @return array + */ + public function getQrcode($store, $ball) + { + + $path = 'qrcode/'; + if (!is_dir($path)) { + mkdir($path, 0777, true); + } + + $hostname = $this->url; + $filename = 'qrcode/' . $ball->dev_number . '.png'; + + + if (!file_exists($filename)) { + + + $qr_data = $hostname . "?dev_id={$ball->id}&store_id={$ball->store_id}&time={$ball->created_at}&path=basicsInfo"; + $errorCorrectionLevel = 'L'; //容错级别 + $matrixPointSize = 5; //生成图片大小 + + + + QRcode::png($qr_data, $filename, $errorCorrectionLevel, $matrixPointSize, 2, true); + + $url = \Yii::$app->request->getHostInfo() . '/' . $filename; + if (!file_exists($filename)) { + return ['code' => 1, 'msg' => '生成二维码失败']; + } else { + return ['code' => 0, 'msg' => 'ok', 'data' => $url]; + } + // if (!file_exists($filename)) { + // return [ + // 'code' => 1, + // 'msg' => 'Failed to generate QR code.' + // ]; + // } else { + + + // $url = $hostname . '/' . $filename; + + // $file = fopen($filename, "w");//打开文件准备写入 + // fwrite($file, $url);//写入,$res为图片二进制内容 + // fclose($file);//关闭 + + + // //图片是否存在 + // if (!file_exists($filename)) { + // return ['code' => 1, 'msg' => '生成二维码失败']; + // } else { + // return ['code' => 0, 'msg' => 'ok', 'data' => $url]; + // } + // } + } else { + return ['code' => 0, 'msg' => 'ok', 'data' => \Yii::$app->request->getHostInfo() . '/' . $filename]; + } + } + + //获取小程序二维码 + public function wxmpQrcode($body) + { + $plugin = new \app\models\common\PluginService(); + $wxmpService = $plugin->getWxmpService(0); + $accessToken = $wxmpService->getAccessToken(); + if (empty($accessToken)) { + $accessToken = $wxmpService->getAccessToken(true); + } + $body = json_encode($body); + return $wxmpService->Qrcode->getWxappQrcode($accessToken, $body); + } + + public function BatchQrcode() + { + $ball = Dev::find()->select('id,store_id,name,dev_number,created_at')->where(['is_delete' => 0])->all(); + if ($ball == null) { + return ['code' => 1, 'msg' => '该设备不存在']; + } + + $path = 'qrcode/dev_qrcode_zip'; + if (!is_dir($path)) { + mkdir($path, 0777, true); + } + $paths = []; + foreach ($ball as $value) { + $store = Store::findOne($value->store_id); + if ($store == null) { + return $value->dev_number . '编号设备所在门店不存在'; + } + $r = $this->getQrcode($store, $value); + if ($r['code'] != 0) { + return $r['msg']; + } + $name = $store->name . '_' . $value->dev_number . '.png'; + array_push($paths, ['name' => $name, 'path' => $r['data']]); + } + if (empty($paths)) { + return '无下载数据'; + } + $zipName = '设备二维码_' . date('Y年m月d日') . '下载' . '.zip'; // 压缩包文件名 + return (new ZipFile())->downloadZipImg($zipName, $path, $paths); + } + +} \ No newline at end of file diff --git a/modules/store/models/dev/DevEditForm.php b/modules/store/models/dev/DevEditForm.php new file mode 100644 index 0000000..2db8230 --- /dev/null +++ b/modules/store/models/dev/DevEditForm.php @@ -0,0 +1,89 @@ + '设备名称', + 'dev_number' => '设备编号', + ]; + } + + + public function edit() + { + if (!$this->validate()) { + return $this->getModelError(); + } + + + if ($this->model->isNewRecord) { + $this->model->created_at = time(); + + + $exists = Dev::find()->where(['dev_number' => $this->dev_number, 'is_delete' => 0])->exists(); + if ($exists) { + return $this->apiReturnError('设备编号已存在'); + } + + } + + $this->model->name = $this->name; + $this->model->dev_number = $this->dev_number; + $this->model->store_id = $this->store_id; + $this->model->updated_at = time(); + + if (!$this->model->save()) { + return $this->getModelError($this->model); + } + return $this->apiReturnSuccess('保存成功'); + } + + +} \ No newline at end of file diff --git a/modules/store/models/dev/DevtListForm.php b/modules/store/models/dev/DevtListForm.php new file mode 100644 index 0000000..7e25134 --- /dev/null +++ b/modules/store/models/dev/DevtListForm.php @@ -0,0 +1,95 @@ + 1], + [['limit'], 'default', 'value' => 20], + ]; + } + + public function search() + { + if (!$this->validate()) { + return $this->getModelError(); + } + + $where = ['o.store_id' => $this->store_id]; + if (!empty($this->times)) { + $explode = explode(' - ', $this->times); + $where = [ + 'and', + ['>=', 'o.created_at', strtotime($explode[0])], + ['<=', 'o.created_at', strtotime($explode[1])], + ]; + } + + $query = Dev::find()->alias('o') + ->select('o.id,o.name,o.dev_number,o.created_at,o.status,s.name as store_name') + ->leftJoin(['s' => Store::tableName()], 'o.store_id=s.id') + ->where([ + + ])->andWhere($where) + ->andFilterWhere([ + 'OR', + ['like', 'o.name', $this->keywords], + ['like', 'o.dev_numbe', $this->keywords], + ]); + + + $count = $query->count(); + $pagination = new Pagination(['totalCount' => $count, 'pageSize' => $this->limit]); + $list = $query->offset($pagination->offset)->limit($pagination->limit)->orderBy(['o.created_at' => SORT_DESC])->asArray()->all(); + foreach ($list as $index => $item) { + $item['created_at_cn'] = date("Y-m-d H:i", $item['created_at']); + $list[$index] = $item; + } + $data = []; + $data['code'] = 0; + $data['msg'] = 'ok'; + $data['data'] = $list; + $data['count'] = $count; + return $data; + + } + + +} \ No newline at end of file diff --git a/modules/store/models/report/ReportListForm.php b/modules/store/models/report/ReportListForm.php index f848cdf..377cd4a 100644 --- a/modules/store/models/report/ReportListForm.php +++ b/modules/store/models/report/ReportListForm.php @@ -1,123 +1,133 @@ - 1], - [['limit'], 'default', 'value' => 20], - ]; - } - - public function search() - { - if (!$this->validate()) { - return $this->getModelError(); - } - - $where = ['o.store_id' => $this->store_id]; - if (!empty($this->times)) { - $explode = explode(' - ', $this->times); - $where = [ - 'and', - ['>=', 'o.created_at', strtotime($explode[0])], - ['<=', 'o.created_at', strtotime($explode[1])], - ]; - } - - $query = Report::find()->alias('o') - ->select('o.id,o.model_number,o.initial_path,o.final_path,o.pdf_path,o.step,u.real_name,u.mobile_phone,s.name as store_name,o.created_at') - ->leftJoin(['u' => User::tableName()], 'o.user_id=u.id') - ->leftJoin(['s' => Store::tableName()], 'o.store_id=s.id') - ->where([ - - ])->andWhere($where) - ->andFilterWhere([ - 'OR', - ['like', 'u.mobile_phone', $this->keywords], - ['like', 'u.nickname', $this->keywords], - ['like', 'u.real_name', $this->keywords], - ]); - - - $count = $query->count(); - $pagination = new Pagination(['totalCount' => $count, 'pageSize' => $this->limit]); - $list = $query->offset($pagination->offset)->limit($pagination->limit)->orderBy(['o.created_at' => SORT_DESC])->asArray()->all(); - foreach ($list as $index => $item) { - $item['created_at_cn'] = date("Y-m-d H:i", $item['created_at']); - - $item['initial_path_ext'] = ""; - $item['initial_name'] = ''; - if (!empty($item['initial_path'])) { - $item['initial_name'] = $item['model_number'] . '初始报告'; - $explode = explode('.', $item['initial_path']); - $item['initial_path_ext'] = end($explode); - } - - $item['final_path_ext'] = ''; - $item['final_name'] = ''; - if (!empty($item['final_path'])) { - $item['final_name'] = $item['model_number'] . '最终报告'; - $explode = explode('.', $item['final_path']); - $item['final_path_ext'] = end($explode); - } - - - $item['pdf_path_ext'] = ""; - $item['pdf_name'] = ''; - if (!empty($item['pdf_path'])) { - $item['pdf_name'] = $item['model_number'] . 'PDF报告'; - $explode = explode('.', $item['pdf_path']); - $item['pdf_path_ext'] = end($explode); - } - - - $list[$index] = $item; - } - $data = []; - $data['code'] = 0; - $data['msg'] = 'ok'; - $data['data'] = $list; - $data['count'] = $count; - return $data; - - } - - + 1], + [['limit'], 'default', 'value' => 20], + ]; + } + + public function search() + { + if (!$this->validate()) { + return $this->getModelError(); + } + + $where = ['o.store_id' => $this->store_id]; + if (!empty($this->times)) { + $explode = explode(' - ', $this->times); + $where = [ + 'and', + ['>=', 'o.created_at', strtotime($explode[0])], + ['<=', 'o.created_at', strtotime($explode[1])], + ]; + } + + $query = Report::find()->alias('o') + ->select('o.id,o.model_number,o.initial_path,o.final_path,o.pdf_path,o.step,u.real_name,u.mobile_phone,s.name as store_name,o.created_at') + ->leftJoin(['u' => User::tableName()], 'o.user_id=u.id') + ->leftJoin(['s' => Store::tableName()], 'o.store_id=s.id') + ->where([ + + ])->andWhere($where) + ->andFilterWhere([ + 'OR', + ['like', 'u.mobile_phone', $this->keywords], + ['like', 'u.nickname', $this->keywords], + ['like', 'u.real_name', $this->keywords], + ]); + + + $count = $query->count(); + $pagination = new Pagination(['totalCount' => $count, 'pageSize' => $this->limit]); + $list = $query->offset($pagination->offset)->limit($pagination->limit)->orderBy(['o.created_at' => SORT_DESC])->asArray()->all(); + + $storeUser = StoreUser::findOne(['user_id' => $this->user_id]); + + + foreach ($list as $index => $item) { + + $item['user_type'] = $storeUser->user_type; + + + $item['created_at_cn'] = date("Y-m-d H:i", $item['created_at']); + + $item['initial_path_ext'] = ""; + $item['initial_name'] = ''; + if (!empty($item['initial_path'])) { + $item['initial_name'] = $item['model_number'] . '初始模型'; + $explode = explode('.', $item['initial_path']); + $item['initial_path_ext'] = end($explode); + } + + $item['final_path_ext'] = ''; + $item['final_name'] = ''; + if (!empty($item['final_path'])) { + $item['final_name'] = $item['model_number'] . '最终模型'; + $explode = explode('.', $item['final_path']); + $item['final_path_ext'] = end($explode); + } + + + $item['pdf_path_ext'] = ""; + $item['pdf_name'] = ''; + if (!empty($item['pdf_path'])) { + $item['pdf_name'] = $item['model_number'] . 'PDF报告'; + $explode = explode('.', $item['pdf_path']); + $item['pdf_path_ext'] = end($explode); + } + + + $list[$index] = $item; + } + $data = []; + $data['code'] = 0; + $data['msg'] = 'ok'; + $data['data'] = $list; + $data['count'] = $count; + return $data; + + } + + } \ No newline at end of file diff --git a/modules/store/views/dev/edit.php b/modules/store/views/dev/edit.php new file mode 100644 index 0000000..5e1c03c --- /dev/null +++ b/modules/store/views/dev/edit.php @@ -0,0 +1,129 @@ +registerJsFile($layui_js_file, ['depends' => 'app\modules\admin\assets\AppAsset']); + +$this->title = '添加/编辑设备'; +$this->params['breadcrumbs'][] = $this->title; +?> +
+
+
title ?>
+
+
+ + +
+ +
+ +
+
+
+ + +
+ +
+ +
+
+
+ + +
+
+
+ +
+
+
+
+
+
+
+ +registerJs($this->blocks['js_script_wrap'], \yii\web\View::POS_END); ?> diff --git a/modules/store/views/dev/index.php b/modules/store/views/dev/index.php new file mode 100644 index 0000000..e06165f --- /dev/null +++ b/modules/store/views/dev/index.php @@ -0,0 +1,488 @@ +title = '设备列表'; +$this->params['breadcrumbs'][] = $this->title; + + +?> + +
+
+
+ title ?> +
+
+
+
+ +
+
+ + + + + + $val):?> + + + + + + +
+ +
+ "> +
+
+
+ +
+
+
+
+
+
+
+
+
+ + + + + + + + + + + + +registerJs($this->blocks['js_script_wrap'], \yii\web\View::POS_END); ?> + diff --git a/modules/store/views/passport/login.php b/modules/store/views/passport/login.php index 2a1ad6a..94cce29 100644 --- a/modules/store/views/passport/login.php +++ b/modules/store/views/passport/login.php @@ -1,151 +1,151 @@ -title = '登录'; - -use app\components\SiteHelper; - -?> - - - +title = '登录'; + +use app\components\SiteHelper; + +?> + + + registerJs($this->blocks['js_script_wrap'], \yii\web\View::POS_END); ?> \ No newline at end of file diff --git a/modules/store/views/report/index.php b/modules/store/views/report/index.php index f0687cb..171f47f 100644 --- a/modules/store/views/report/index.php +++ b/modules/store/views/report/index.php @@ -79,7 +79,14 @@ $this->params['breadcrumbs'][] = $this->title;