diff --git a/components/Oss.php b/components/Oss.php
index 578667e..3f41fd5 100644
--- a/components/Oss.php
+++ b/components/Oss.php
@@ -1,67 +1,67 @@
-accessKeyId = 'LTAI5tShVduri66gPQj1arLQ';
- $this->accessKeySecret = 'R9pzKpWbfcudFO7VrWSz3BZst62ayX';
- $this->bucket = 'cxgyc';
- $this->endpoint = 'https://oss-cn-guangzhou.aliyuncs.com';
-
- try {
- if (!isset($this->client)) {
- $this->client = $ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint, false);
- }
- } catch (OssException $e) {
- return $e->getMessage();
- }
- }
-
-
- /**
- * 上传文件到oss并删除本地文件
- * @param $file
- * @return bool|string
- */
- public function upload($file)
- {
- $ext = explode('.', $file);
- $ext = end($ext);
- $date = date('Ymd');
- $file_name = md5(time() . uniqid());
- $oss_path = "upload/{$date}/{$file_name}.{$ext}";
-// $file = \Yii::$app->basePath . '/web' . $file;
- if (file_exists($file)) {
- try {
- $oss_client = $this->client->uploadFile($this->bucket, $oss_path, $file);
- } catch (OssException $e) {
- return $e->getMessage();
- }
- if (isset($oss_client['info']['url'])) {
- // 自动删除本地的文件
- unlink($file);
- return $oss_client['info']['url'];
- } else {
- return $oss_client;
- }
- }
- return false;
- }
-
+accessKeyId = 'LTAI5tMaDbEbWyQWpwmxp24y';
+ $this->accessKeySecret = '3bjqbBFC08YIub3c8ry9Elz05UF1J7';
+ $this->bucket = 'cxgjyz';
+ $this->endpoint = 'https://oss-cn-beijing.aliyuncs.com';
+
+ try {
+ if (!isset($this->client)) {
+ $this->client = $ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint, false);
+ }
+ } catch (OssException $e) {
+ return $e->getMessage();
+ }
+ }
+
+
+ /**
+ * 上传文件到oss并删除本地文件
+ * @param $file
+ * @return bool|string
+ */
+ public function upload($file)
+ {
+ $ext = explode('.', $file);
+ $ext = end($ext);
+ $date = date('Ymd');
+ $file_name = md5(time() . uniqid());
+ $oss_path = "upload/{$date}/{$file_name}.{$ext}";
+// $file = \Yii::$app->basePath . '/web' . $file;
+ if (file_exists($file)) {
+ try {
+ $oss_client = $this->client->uploadFile($this->bucket, $oss_path, $file);
+ } catch (OssException $e) {
+ return $e->getMessage();
+ }
+ if (isset($oss_client['info']['url'])) {
+ // 自动删除本地的文件
+ unlink($file);
+ return $oss_client['info']['url'];
+ } else {
+ return $oss_client;
+ }
+ }
+ return false;
+ }
+
}
\ No newline at end of file
diff --git a/models/Box.php b/models/Box.php
index 04d980e..dca2850 100644
--- a/models/Box.php
+++ b/models/Box.php
@@ -17,6 +17,7 @@ use Yii;
* @property int $is_delete 是否删除,0=否,1=是
* @property int $deleted_at 删除时间
* @property string $notice 包厢公告
+ *
*/
class Box extends \yii\db\ActiveRecord
{
@@ -35,7 +36,7 @@ class Box extends \yii\db\ActiveRecord
{
return [
[['goods_id', 'bj_id', 'notice', 'status', 'created_at'], 'required'],
- [['goods_id', 'bj_id', 'status', 'created_at', 'updated_at', 'is_delete', 'deleted_at'], 'integer'],
+ [['goods_id', 'bj_id', 'status', 'created_at', 'updated_at', 'is_delete', 'deleted_at','sort'], 'integer'],
[['notice', 'cover_pic'], 'string'],
];
}
diff --git a/models/GoodsHub.php b/models/GoodsHub.php
index c976d3c..4bf38a2 100644
--- a/models/GoodsHub.php
+++ b/models/GoodsHub.php
@@ -1,104 +1,104 @@
- 255],
- ];
- }
-
- /**
- * {@inheritdoc}
- */
- public function attributeLabels()
- {
- return [
- 'id' => 'ID',
- 'cx_mch_id' => '平台商户ID',
- 'name' => '商品名称',
- 'subtitle' => '副标题',
- 'original_price' => '原价',
- 'cost_price' => '成本价',
- 'detail' => '商品详情,图文',
- 'cover_pic' => '商品缩略图',
- 'pic_urls' => '商品轮播图',
- 'video_url' => '商品视频',
- 'unit' => '单位',
- 'created_at' => '添加时间',
- 'updated_at' => '更新时间',
- 'deleted_at' => '删除时间',
- 'is_delete' => '是否删除,0=否,1=是',
- 'type' => '商品类型:0=实体商品 ',
- ];
- }
-
-
- public function beforeSave($insert) {
- if(parent::beforeSave($insert)){
- if($this->isNewRecord){
- $this->created_at = time();
- }
- $this->updated_at = time();
- if($this->is_delete == 1)
- $this->deleted_at = time();
- $this->htmlTagFilter();
- return true;
- } else {
- return false;
- }
- }
-
- public function htmlTagFilter()
- {
- $this->name = Model::htmlTagFilter($this->name);
- $this->subtitle = Model::htmlTagFilter($this->subtitle);
- $this->detail = Model::htmlTagFilter($this->detail);
- $this->cover_pic = Model::htmlTagFilter($this->cover_pic);
- $this->video_url = Model::htmlTagFilter($this->video_url);
- $this->unit = Model::htmlTagFilter($this->unit);
- }
-
-}
+ 255],
+ ];
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function attributeLabels()
+ {
+ return [
+ 'id' => 'ID',
+ 'cx_mch_id' => '平台商户ID',
+ 'name' => '商品名称',
+ 'subtitle' => '副标题',
+ 'original_price' => '原价',
+ 'cost_price' => '成本价',
+ 'detail' => '商品详情,图文',
+ 'cover_pic' => '商品缩略图',
+ 'pic_urls' => '商品轮播图',
+ 'video_url' => '商品视频',
+ 'unit' => '单位',
+ 'created_at' => '添加时间',
+ 'updated_at' => '更新时间',
+ 'deleted_at' => '删除时间',
+ 'is_delete' => '是否删除,0=否,1=是',
+ 'type' => '商品类型:0=实体商品 ',
+ ];
+ }
+
+
+ public function beforeSave($insert) {
+ if(parent::beforeSave($insert)){
+ if($this->isNewRecord){
+ $this->created_at = time();
+ }
+ $this->updated_at = time();
+ if($this->is_delete == 1)
+ $this->deleted_at = time();
+ $this->htmlTagFilter();
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ public function htmlTagFilter()
+ {
+ $this->name = Model::htmlTagFilter($this->name);
+ $this->subtitle = Model::htmlTagFilter($this->subtitle);
+ $this->detail = Model::htmlTagFilter($this->detail);
+ $this->cover_pic = Model::htmlTagFilter($this->cover_pic);
+ $this->video_url = Model::htmlTagFilter($this->video_url);
+ $this->unit = Model::htmlTagFilter($this->unit);
+ }
+
+}
diff --git a/models/common/CommonGoodsEditForm.php b/models/common/CommonGoodsEditForm.php
index af5775a..e531c32 100644
--- a/models/common/CommonGoodsEditForm.php
+++ b/models/common/CommonGoodsEditForm.php
@@ -1,435 +1,435 @@
- 0],
- [['cost_price', 'original_price', 'price'], 'number', 'max' => 9999999],
- [['sort', 'virtual_sales', 'freight_id'], 'default', 'value' => 100],
- [['confine_count', 'use_attr'], 'default', 'value' => 0],
- [['name', 'price', 'cover_pic', 'type', 'plugin_sign', 'banner_urls', 'model', 'cx_mch_id'], 'required'],
- ];
- }
-
- public function attributeLabels()
- {
- return [
- 'name' => '商品名称',
- 'subtitle' => '副标题',
- 'original_price' => '原价',
- 'cost_price' => '成本价',
- 'detail' => '商品详情,图文',
- 'cover_pic' => '商品缩略图',
- 'pic_urls' => '商品轮播图',
- 'video_url' => '商品视频',
- 'unit' => '单位',
- 'type' => '商品类型:0=实体商品 ',
- 'status' => '上架状态:0=下架,1=上架',
- 'price' => '售价',
- 'use_attr' => '是否使用规格:0=不使用,1=使用',
- 'attr' => '商品规格',
- 'goods_stock' => '商品库存',
- 'virtual_sales' => '已出售量',
- 'confine_count' => '购物数量限制,0=不限制',
- 'freight_id' => '运费模板ID',
- 'plugin_sign' => '商品标示用于区分商品属于什么模块',
- 'sort' => '排序',
- ];
- }
-
- public function save()
- {
- if (!$this->validate()) {
- return $this->getModelError();
- }
- $t = \Yii::$app->db->beginTransaction();
- if ($this->model->isNewRecord) {
- $this->model->cx_mch_id = $this->cx_mch_id;
- $this->model->plugin_sign = $this->plugin_sign;
- }
- $this->model->price = $this->price;
- $this->model->goods_stock = empty($this->goods_stock) ? 9999 : $this->goods_stock; // 商品库存
- $this->model->virtual_sales = $this->virtual_sales;
- $this->model->confine_count = $this->confine_count;
- $this->model->freight_id = $this->freight_id;
- $this->model->sort = 100;
- $this->model->status = 1;
-// $this->handleAttrGroups();
-// $this->model->attr_groups = json_encode($this->attrGroups,JSON_UNESCAPED_UNICODE);
- $this->model->attr_groups = 1; //商品规格组 用不到看表 0 不需要规格组
-
- $this->model->date = strtotime($this->date);
-
-
- //保存商品基础信息
- $res = $this->saveGoodsHub();
-
- //保存商品基础信息
- $res1 = $this->saveGoodsCat();
-
-
- if ($res['code'] != 0 || $res1['code'] != 0) {
- $t->rollBack();
- return $res;
- }
-
-
- if (!$this->model->save()) {
- $t->rollBack();
- return $this->getModelError($this->model);
- }
-
- $t->commit();
- return $this->apiReturnSuccess('保存成功');
- }
-
- //扩展其他
- protected function saveExtra()
- {
- return $this->apiReturnSuccess();
- }
-
- private function saveGoodsHub()
- {
- $goods_hub_id = $this->model->isNewRecord ? 0 : $this->model->goods_hub_id;
- $goods_hub = GoodsHub::findOne(['id' => $goods_hub_id, 'is_delete' => 0, 'cx_mch_id' => $this->cx_mch_id]);
- if ($goods_hub == null) {
- $goods_hub = new GoodsHub();
- $goods_hub->cx_mch_id = $this->cx_mch_id;
- }
- $goods_hub->name = $this->name;
- $goods_hub->subtitle = $this->subtitle;
- $goods_hub->original_price = $this->original_price ? $this->original_price : $this->price;
- $goods_hub->cost_price = $this->cost_price ? $this->cost_price : $this->price;
- $goods_hub->detail = $this->detail;
- $goods_hub->cover_pic = $this->cover_pic;
-
- $goods_hub->banner_urls = $this->banner_urls;
-
-
- $video_banner_urls = is_string($this->video_banner_urls) ? $this->video_banner_urls : json_encode($this->video_banner_urls);
- $goods_hub->video_banner_urls = $video_banner_urls;
-
-
- $pic_urls = is_string($this->pic_urls) ? $this->pic_urls : json_encode($this->pic_urls);
- $goods_hub->pic_urls = $pic_urls;
- $video_urls = is_string($this->video_url) ? $this->video_url : json_encode($this->video_url);
-
-
- $goods_hub->video_url = $video_urls;
- $goods_hub->unit = $this->unit;
- $goods_hub->type = $this->type;
- if (!$goods_hub->save()) {
- return $this->getModelError($goods_hub);
- }
- $this->model->goods_hub_id = $goods_hub->id;
- return $this->apiReturnSuccess();
- }
-
- //保存商品规格
- private function saveGoodsAttr()
- {
- if ((int)$this->use_attr === 0) {
- $this->model->use_attr = 0;
- // 未使用规格就添加默认规格
- $res = $this->setDefaultAttr();
- if ($res['code'] != 0)
- return $res;
- $attrPicList = [];
- } else {
- $this->handleAttr();
- // 多规格数据处理
- $this->newAttrs = $this->attr;
- $attrPicList = array_column($this->attrGroups[0]['attr_list'], 'cover_pic', 'attr_id');
- }
-
- $oldAttr = GoodsAttr::find()
- ->where(['is_delete' => 0, 'goods_id' => $this->model->id])
- ->select('id')
- ->asArray()
- ->all();
-
- // 是否为新增
- if (!$this->model->isNewRecord) {
- GoodsAttr::updateAll(['is_delete' => 1,], ['goods_id' => $this->model->id, 'is_delete' => 0]);
- }
-
- // 旧规格ID
- $oldAttrIds = [];
- $newAttrIds = [];
- foreach ($oldAttr as $oldItem) {
- $oldAttrIds[] = $oldItem['id'];
- }
-
- $goodsStock = 0;
- foreach ($this->newAttrs as $newAttr) {
- $goodsStock += $newAttr['stock'];
-
- // 记录规格ID数组
- $signIds = '';
- foreach ($newAttr['attr_list'] as $aLItem) {
- $signIds .= $signIds ? ':' . (int)$aLItem['attr_id'] : (int)$aLItem['attr_id'];
- }
-
- // TODO 待修改
- // 判断规格是需要新增还是更新
- $goodsAttr = null;
- if ($this->model->id) {
- $goodsAttr = GoodsAttr::findOne([
- 'id' => isset($newAttr['id']) ? $newAttr['id'] : 0,
- 'goods_id' => $this->model->id
- ]);
- if ($goodsAttr == null && count($this->newAttrs) == 1) {
- $goodsAttr = GoodsAttr::findOne([
- 'sign_id' => $signIds,
- 'goods_id' => $this->model->id
- ]);
- }
- }
- if ($goodsAttr) {
- $goodsAttr->is_delete = 0;
- } else {
- $goodsAttr = new GoodsAttr();
- }
- if ($newAttr['stock'] > 9999999) {
- return $this->apiReturnError('商品总库存不能大于9999999');
- }
- $goodsAttr->goods_id = $this->model->id;
- $goodsAttr->sign_id = $signIds;
- $goodsAttr->stock = $newAttr['stock'];
- $goodsAttr->price = $newAttr['price'];
- $goodsAttr->serial_no = $newAttr['serial_no'];
- $goodsAttr->weight = $newAttr['weight'] ?: 0;
- $key = strstr($signIds, ':', true) ?: $signIds;
- $goodsAttr->cover_pic = !empty($newAttr['cover_pic']) ? $newAttr['cover_pic'] : $this->cover_pic;
-
- $res = $goodsAttr->save();
- if (!$res) {
- return $this->getModelError($goodsAttr);
- }
- $newAttrIds[] = $goodsAttr->id;
-
- }
- if ($goodsStock > 9999999) {
- return $this->apiReturnError('商品总库存不能大于9999999');
- }
- $this->model->goods_stock = $goodsStock;
- $res = $this->model->save();
- if (!$res) {
- return $this->getModelError($this->model);
- }
- return $this->apiReturnSuccess();
- }
-
- private function handleAttrGroups()
- {
- $this->attrGroups = $this->addAttrGroupsId($this->attrGroups);
- }
-
- private function handleAttr()
- {
- foreach ($this->attr as &$item) {
- foreach ($item['attr_list'] as &$alItem) {
- $alItem['attr_group_id'] = $this->newAttrGroupList[$alItem['attr_group_name']];
- $alItem['attr_id'] = $this->newAttrList[$alItem['attr_name']];
- }
- unset($alItem);
- }
- unset($item);
- }
-
- private $newAttrGroupList = [];
- private $newAttrList = [];
- private $signArr = [];
-
- private function addAttrGroupsId($list, &$id = 1)
- {
- $newId = 1;
- foreach ($list as $key => $item) {
- if (isset($item['attr_list'])) {
- $this->newAttrGroupList[$item['attr_group_name']] = $newId;
- $list[$key]['attr_group_id'] = $newId++;
- $newItemList = $this->addAttrGroupsId($item['attr_list'], $id);
- $list[$key]['attr_list'] = $newItemList;
- } else {
- if (isset($this->signArr[$item['attr_name']])) {
- $this->newAttrList[$item['attr_name']] = $this->signArr[$item['attr_name']];
- $list[$key]['attr_id'] = $this->signArr[$item['attr_name']];
- } else {
- $this->signArr[$item['attr_name']] = $id;
- $this->newAttrList[$item['attr_name']] = $id;
- $list[$key]['attr_id'] = $id++;
- }
- }
- }
- return $list;
- }
-
- /**
- * 添加默认规格
- */
- private function setDefaultAttr()
- {
- $attrList = [
- [
-
- 'attr_group_name' => '规格',
- 'attr_group_id' => 1,
- 'attr_id' => 1,
- 'attr_name' => '默认',
- ]
- ];
- $count = 1;
- $attrGroups = [];
- foreach ($attrList as &$item) {
- $item['attr_group_id'] = $count;
- $count++;
- $item['attr_id'] = $count;
- $count++;
- $newItem = [
- 'attr_group_id' => $item['attr_group_id'],
- 'attr_group_name' => $item['attr_group_name'],
- 'attr_list' => [
- [
- 'attr_id' => $item['attr_id'],
- 'attr_name' => $item['attr_name']
- ]
- ]
- ];
- $attrGroups[] = $newItem;
- }
- unset($item);
- // 未使用规格 就添加一条默认规格
- $newAttrs = [
- [
- 'attr_list' => $attrList,
- 'stock' => $this->goods_stock,
- 'price' => $this->price,
- 'serial_no' => $this->goods_no ? $this->goods_no : '',
- 'weight' => $this->goods_weight ? $this->goods_weight : 0,
- 'cover_pic' => $this->cover_pic,
- ]
- ];
-
- // 未使用规格情况下,要把上一次的规格ID 存回去,不然规格记录会重复添加
- if (count($this->attr) === 1 && isset($this->attr[0]['id'])) {
- $newAttrs[0]['id'] = $this->attr[0]['id'];
- }
-
- $this->model->attr_groups = (new Serializer)->encode($attrGroups);
- $res = $this->model->save();
- if (!$res) {
- return $this->getModelError($this->model);
- }
-
- $this->newAttrs = $newAttrs;
- return $this->apiReturnSuccess();
- }
-
-
- //保存商品分类
- protected function saveGoodsCat()
- {
- $type = Cat::TYPE_GOODS;
- $goods_hub_id = $this->model->goods_hub_id;
-
- $goods_cat = GoodsCat::findOne(['goods_hub_id' => $goods_hub_id, 'is_delete' => 0]);
-
- if ($goods_cat == null) {
- $goods_cat = new GoodsCat();
- }
-
- $goods_cat->goods_hub_id = $goods_hub_id;
-
- $goods_cat->cat_id = $this->cat_id;
- $goods_cat->cat1_id = $this->cat1_id;
- $goods_cat->cat2_id = $this->cat2_id;
- $goods_cat->cat3_id = $this->cat3_id;
- $goods_cat->cat4_id = $this->cat4_id;
-
- $goods_cat->is_delete = 0;
- $res = $goods_cat->save();
- if (!$res) {
- return $this->getModelError($goods_cat);
- }
-
- return $this->apiReturnSuccess();
- }
-}
-
+ 0],
+ [['cost_price', 'original_price', 'price'], 'number', 'max' => 9999999],
+ [['sort', 'virtual_sales', 'freight_id'], 'default', 'value' => 100],
+ [['confine_count', 'use_attr'], 'default', 'value' => 0],
+ [['name', 'price', 'cover_pic', 'type', 'plugin_sign', 'banner_urls', 'model', 'cx_mch_id'], 'required'],
+ ];
+ }
+
+ public function attributeLabels()
+ {
+ return [
+ 'name' => '商品名称',
+ 'subtitle' => '副标题',
+ 'original_price' => '原价',
+ 'cost_price' => '成本价',
+ 'detail' => '商品详情,图文',
+ 'cover_pic' => '商品缩略图',
+ 'pic_urls' => '商品轮播图',
+ 'video_url' => '商品视频',
+ 'unit' => '单位',
+ 'type' => '商品类型:0=实体商品 ',
+ 'status' => '上架状态:0=下架,1=上架',
+ 'price' => '售价',
+ 'use_attr' => '是否使用规格:0=不使用,1=使用',
+ 'attr' => '商品规格',
+ 'goods_stock' => '商品库存',
+ 'virtual_sales' => '已出售量',
+ 'confine_count' => '购物数量限制,0=不限制',
+ 'freight_id' => '运费模板ID',
+ 'plugin_sign' => '商品标示用于区分商品属于什么模块',
+ 'sort' => '排序',
+ ];
+ }
+
+ public function save()
+ {
+ if (!$this->validate()) {
+ return $this->getModelError();
+ }
+ $t = \Yii::$app->db->beginTransaction();
+ if ($this->model->isNewRecord) {
+ $this->model->cx_mch_id = $this->cx_mch_id;
+ $this->model->plugin_sign = $this->plugin_sign;
+ }
+ $this->model->price = $this->price;
+ $this->model->goods_stock = empty($this->goods_stock) ? 9999 : $this->goods_stock; // 商品库存
+ $this->model->virtual_sales = $this->virtual_sales;
+ $this->model->confine_count = $this->confine_count;
+ $this->model->freight_id = $this->freight_id;
+ $this->model->sort = $this->sort;
+ $this->model->status = 1;
+// $this->handleAttrGroups();
+// $this->model->attr_groups = json_encode($this->attrGroups,JSON_UNESCAPED_UNICODE);
+ $this->model->attr_groups = 1; //商品规格组 用不到看表 0 不需要规格组
+
+ $this->model->date = (int)strtotime($this->date."-01-01");
+
+
+ //保存商品基础信息
+ $res = $this->saveGoodsHub();
+
+ //保存商品基础信息
+ $res1 = $this->saveGoodsCat();
+
+
+ if ($res['code'] != 0 || $res1['code'] != 0) {
+ $t->rollBack();
+ return $res;
+ }
+
+
+ if (!$this->model->save()) {
+ $t->rollBack();
+ return $this->getModelError($this->model);
+ }
+
+ $t->commit();
+ return $this->apiReturnSuccess('保存成功');
+ }
+
+ //扩展其他
+ protected function saveExtra()
+ {
+ return $this->apiReturnSuccess();
+ }
+
+ private function saveGoodsHub()
+ {
+ $goods_hub_id = $this->model->isNewRecord ? 0 : $this->model->goods_hub_id;
+ $goods_hub = GoodsHub::findOne(['id' => $goods_hub_id, 'is_delete' => 0, 'cx_mch_id' => $this->cx_mch_id]);
+ if ($goods_hub == null) {
+ $goods_hub = new GoodsHub();
+ $goods_hub->cx_mch_id = $this->cx_mch_id;
+ }
+ $goods_hub->name = $this->name;
+ $goods_hub->subtitle = $this->subtitle;
+ $goods_hub->original_price = $this->original_price ? $this->original_price : $this->price;
+ $goods_hub->cost_price = $this->cost_price ? $this->cost_price : $this->price;
+ $goods_hub->detail = $this->detail;
+ $goods_hub->cover_pic = $this->cover_pic;
+
+ $goods_hub->banner_urls = $this->banner_urls;
+
+
+ $video_banner_urls = is_string($this->video_banner_urls) ? $this->video_banner_urls : json_encode($this->video_banner_urls);
+ $goods_hub->video_banner_urls = $video_banner_urls;
+
+
+ $pic_urls = is_string($this->pic_urls) ? $this->pic_urls : json_encode($this->pic_urls);
+ $goods_hub->pic_urls = $pic_urls;
+ $video_urls = is_string($this->video_url) ? $this->video_url : json_encode($this->video_url);
+
+
+ $goods_hub->video_url = $video_urls;
+ $goods_hub->unit = $this->unit;
+ $goods_hub->type = $this->type;
+ if (!$goods_hub->save()) {
+ return $this->getModelError($goods_hub);
+ }
+ $this->model->goods_hub_id = $goods_hub->id;
+ return $this->apiReturnSuccess();
+ }
+
+ //保存商品规格
+ private function saveGoodsAttr()
+ {
+ if ((int)$this->use_attr === 0) {
+ $this->model->use_attr = 0;
+ // 未使用规格就添加默认规格
+ $res = $this->setDefaultAttr();
+ if ($res['code'] != 0)
+ return $res;
+ $attrPicList = [];
+ } else {
+ $this->handleAttr();
+ // 多规格数据处理
+ $this->newAttrs = $this->attr;
+ $attrPicList = array_column($this->attrGroups[0]['attr_list'], 'cover_pic', 'attr_id');
+ }
+
+ $oldAttr = GoodsAttr::find()
+ ->where(['is_delete' => 0, 'goods_id' => $this->model->id])
+ ->select('id')
+ ->asArray()
+ ->all();
+
+ // 是否为新增
+ if (!$this->model->isNewRecord) {
+ GoodsAttr::updateAll(['is_delete' => 1,], ['goods_id' => $this->model->id, 'is_delete' => 0]);
+ }
+
+ // 旧规格ID
+ $oldAttrIds = [];
+ $newAttrIds = [];
+ foreach ($oldAttr as $oldItem) {
+ $oldAttrIds[] = $oldItem['id'];
+ }
+
+ $goodsStock = 0;
+ foreach ($this->newAttrs as $newAttr) {
+ $goodsStock += $newAttr['stock'];
+
+ // 记录规格ID数组
+ $signIds = '';
+ foreach ($newAttr['attr_list'] as $aLItem) {
+ $signIds .= $signIds ? ':' . (int)$aLItem['attr_id'] : (int)$aLItem['attr_id'];
+ }
+
+ // TODO 待修改
+ // 判断规格是需要新增还是更新
+ $goodsAttr = null;
+ if ($this->model->id) {
+ $goodsAttr = GoodsAttr::findOne([
+ 'id' => isset($newAttr['id']) ? $newAttr['id'] : 0,
+ 'goods_id' => $this->model->id
+ ]);
+ if ($goodsAttr == null && count($this->newAttrs) == 1) {
+ $goodsAttr = GoodsAttr::findOne([
+ 'sign_id' => $signIds,
+ 'goods_id' => $this->model->id
+ ]);
+ }
+ }
+ if ($goodsAttr) {
+ $goodsAttr->is_delete = 0;
+ } else {
+ $goodsAttr = new GoodsAttr();
+ }
+ if ($newAttr['stock'] > 9999999) {
+ return $this->apiReturnError('商品总库存不能大于9999999');
+ }
+ $goodsAttr->goods_id = $this->model->id;
+ $goodsAttr->sign_id = $signIds;
+ $goodsAttr->stock = $newAttr['stock'];
+ $goodsAttr->price = $newAttr['price'];
+ $goodsAttr->serial_no = $newAttr['serial_no'];
+ $goodsAttr->weight = $newAttr['weight'] ?: 0;
+ $key = strstr($signIds, ':', true) ?: $signIds;
+ $goodsAttr->cover_pic = !empty($newAttr['cover_pic']) ? $newAttr['cover_pic'] : $this->cover_pic;
+
+ $res = $goodsAttr->save();
+ if (!$res) {
+ return $this->getModelError($goodsAttr);
+ }
+ $newAttrIds[] = $goodsAttr->id;
+
+ }
+ if ($goodsStock > 9999999) {
+ return $this->apiReturnError('商品总库存不能大于9999999');
+ }
+ $this->model->goods_stock = $goodsStock;
+ $res = $this->model->save();
+ if (!$res) {
+ return $this->getModelError($this->model);
+ }
+ return $this->apiReturnSuccess();
+ }
+
+ private function handleAttrGroups()
+ {
+ $this->attrGroups = $this->addAttrGroupsId($this->attrGroups);
+ }
+
+ private function handleAttr()
+ {
+ foreach ($this->attr as &$item) {
+ foreach ($item['attr_list'] as &$alItem) {
+ $alItem['attr_group_id'] = $this->newAttrGroupList[$alItem['attr_group_name']];
+ $alItem['attr_id'] = $this->newAttrList[$alItem['attr_name']];
+ }
+ unset($alItem);
+ }
+ unset($item);
+ }
+
+ private $newAttrGroupList = [];
+ private $newAttrList = [];
+ private $signArr = [];
+
+ private function addAttrGroupsId($list, &$id = 1)
+ {
+ $newId = 1;
+ foreach ($list as $key => $item) {
+ if (isset($item['attr_list'])) {
+ $this->newAttrGroupList[$item['attr_group_name']] = $newId;
+ $list[$key]['attr_group_id'] = $newId++;
+ $newItemList = $this->addAttrGroupsId($item['attr_list'], $id);
+ $list[$key]['attr_list'] = $newItemList;
+ } else {
+ if (isset($this->signArr[$item['attr_name']])) {
+ $this->newAttrList[$item['attr_name']] = $this->signArr[$item['attr_name']];
+ $list[$key]['attr_id'] = $this->signArr[$item['attr_name']];
+ } else {
+ $this->signArr[$item['attr_name']] = $id;
+ $this->newAttrList[$item['attr_name']] = $id;
+ $list[$key]['attr_id'] = $id++;
+ }
+ }
+ }
+ return $list;
+ }
+
+ /**
+ * 添加默认规格
+ */
+ private function setDefaultAttr()
+ {
+ $attrList = [
+ [
+
+ 'attr_group_name' => '规格',
+ 'attr_group_id' => 1,
+ 'attr_id' => 1,
+ 'attr_name' => '默认',
+ ]
+ ];
+ $count = 1;
+ $attrGroups = [];
+ foreach ($attrList as &$item) {
+ $item['attr_group_id'] = $count;
+ $count++;
+ $item['attr_id'] = $count;
+ $count++;
+ $newItem = [
+ 'attr_group_id' => $item['attr_group_id'],
+ 'attr_group_name' => $item['attr_group_name'],
+ 'attr_list' => [
+ [
+ 'attr_id' => $item['attr_id'],
+ 'attr_name' => $item['attr_name']
+ ]
+ ]
+ ];
+ $attrGroups[] = $newItem;
+ }
+ unset($item);
+ // 未使用规格 就添加一条默认规格
+ $newAttrs = [
+ [
+ 'attr_list' => $attrList,
+ 'stock' => $this->goods_stock,
+ 'price' => $this->price,
+ 'serial_no' => $this->goods_no ? $this->goods_no : '',
+ 'weight' => $this->goods_weight ? $this->goods_weight : 0,
+ 'cover_pic' => $this->cover_pic,
+ ]
+ ];
+
+ // 未使用规格情况下,要把上一次的规格ID 存回去,不然规格记录会重复添加
+ if (count($this->attr) === 1 && isset($this->attr[0]['id'])) {
+ $newAttrs[0]['id'] = $this->attr[0]['id'];
+ }
+
+ $this->model->attr_groups = (new Serializer)->encode($attrGroups);
+ $res = $this->model->save();
+ if (!$res) {
+ return $this->getModelError($this->model);
+ }
+
+ $this->newAttrs = $newAttrs;
+ return $this->apiReturnSuccess();
+ }
+
+
+ //保存商品分类
+ protected function saveGoodsCat()
+ {
+ $type = Cat::TYPE_GOODS;
+ $goods_hub_id = $this->model->goods_hub_id;
+
+ $goods_cat = GoodsCat::findOne(['goods_hub_id' => $goods_hub_id, 'is_delete' => 0]);
+
+ if ($goods_cat == null) {
+ $goods_cat = new GoodsCat();
+ }
+
+ $goods_cat->goods_hub_id = $goods_hub_id;
+
+ $goods_cat->cat_id = $this->cat_id;
+ $goods_cat->cat1_id = $this->cat1_id;
+ $goods_cat->cat2_id = $this->cat2_id;
+ $goods_cat->cat3_id = $this->cat3_id;
+ $goods_cat->cat4_id = $this->cat4_id;
+
+ $goods_cat->is_delete = 0;
+ $res = $goods_cat->save();
+ if (!$res) {
+ return $this->getModelError($goods_cat);
+ }
+
+ return $this->apiReturnSuccess();
+ }
+}
+
diff --git a/models/common/CommonGoodsListForm.php b/models/common/CommonGoodsListForm.php
index 5abd5fe..09b85d9 100644
--- a/models/common/CommonGoodsListForm.php
+++ b/models/common/CommonGoodsListForm.php
@@ -1,317 +1,317 @@
- 1],
- [['limit'], 'default', 'value' => 20],
- [['status'], 'in', 'range' => [0, 1, 2]],
- [['cx_mch_id'], 'required'],
- [['start_time', 'end_time',], 'safe'],
- [['goods_id'], 'required', 'on' => 'detail'],
- ];
- }
-
- public function search()
- {
- if (!$this->validate()) {
- return $this->getModelError();
- }
- $cat_query = GoodsCat::find()
- ->where([
- 'is_delete' => 0,
- ])
- ->select('goods_hub_id,cat_id,cat1_id,cat2_id,cat3_id,cat4_id');
- $query = $this->getQuery($cat_query);
- $query = $query->where([
- 'g.cx_mch_id' => $this->cx_mch_id,
- // 'g.is_delete' => 0,
- // 'gh.is_delete' => 0,
-// 'g.plugin_sign' => $this->plugin_sign,
- ])
- ->andFilterWhere([
- 'OR',
- ['LIKE', 'gh.name', $this->keywords],
-// ['LIKE', 'gh.subtitle', $this->keywords],
- ])
- ->andFilterWhere([
- 'g.id' => $this->goods_id,
- 'gc.cat_id' => $this->cat_id,
- 'gc.cat1_id' => $this->cat1_id,
- 'gc.cat2_id' => $this->cat2_id,
- 'gc.cat3_id' => $this->cat3_id,
- 'gc.cat4_id' => $this->cat4_id,
- ]);
- if ($this->status == 2) {
- $query = $query->andWhere(['g.goods_stock' => 0]);//售罄
- } else {
- $query = $query->andFilterWhere(['g.status' => $this->status]);
- }
- $query = $this->switchTime($query);
- $query = $this->getFields($query);
- $count_query = clone $query;
- $count = $count_query->count();
- $pagination = new Pagination(['pageSize' => $this->limit, 'totalCount' => $count, 'page' => $this->page - 1]);
- $list = $query->offset($pagination->offset)->limit($pagination->limit)->orderBy(['g.sort' => SORT_ASC, 'g.created_at' => SORT_DESC])->asArray()->all();
-
-
- $list = $this->handleList($list);
- //是否已经全部加载
- $end_flag = $this->page > $pagination->pageCount ? true : false;
- return [
- 'code' => 0,
- 'msg' => 'ok',
- 'data' => $list,
- 'count' => $count,
- 'page_size' => $this->limit,
- 'page_count' => $pagination->pageCount,
- 'page_no' => $this->page,
- 'end_flag' => $end_flag
- ];
- }
-
- protected function getQuery($cat_query)
- {
- $query = Goods::find()->alias('g')
- ->leftJoin(['gh' => GoodsHub::tableName()], 'gh.id=g.goods_hub_id')
- ->leftJoin(['gc' => $cat_query], 'gc.goods_hub_id=gh.id');
- return $query;
- }
-
- public function setFields($fields)
- {
- $this->fields = $fields;
- }
-
- protected function getFields($query)
- {
- $fields = is_array($this->fields) ? implode(',', $this->fields) : $this->fields;
- return $query->select($fields);
- }
-
- protected function handleList($list)
- {
- foreach ($list as $index => $item) {
- $item['status_cn'] = $item['status'] == Goods::STATUS_ONLINE ? '正常' : '隐藏';
- $item['created_at_cn'] = date('Y-m-d H:i:s', $item['created_at']);
- $item['date_at_cn'] = date('Y-m-d', $item['date']);
-
- $item['cat_list'] = $this->getCatList($item['goods_hub_id']);
-
- $item['cat1_list'] = $this->getCat1List($item['goods_hub_id']);
- $item['cat2_list'] = $this->getCat2List($item['goods_hub_id']);
- $item['cat3_list'] = $this->getCat3List($item['goods_hub_id']);
- $item['cat4_list'] = $this->getCat4List($item['goods_hub_id']);
-
-
- $item['cover_pic'] = SiteHelper::getFullUrl($item['cover_pic']);
- if ($this->scenario == 'detail') {
- $item['detail'] = SiteHelper::repairContent($item['detail']);
- $item['pic_urls'] = $this->fixPicUrls($item['pic_urls']);
- $item['video_url'] = SiteHelper::getFullUrl($item['video_url']);
- $item['goods_sales'] = $item['virtaul_sales'] + $item['sales'];
- $item['attr_groups'] = empty($item['attr_groups']) ? [] : json_decode($item['attr_groups'], true);
- $item['attr'] = $this->getAttr($item['id']);
- }
- $list[$index] = $item;
- }
- return $list;
- }
-
-
- protected function switchTime($query)
- {
- if (!empty($this->start_time)) {
- $query = $query->andWhere([
- '>',
- 'g.created_at',
- strtotime($this->start_time)
- ]);
- }
- if (!empty($this->end_time)) {
- $query = $query->andWhere([
- '<',
- 'g.created_at',
- strtotime($this->end_time)
- ]);
- }
- return $query;
- }
-
- protected function getCatList($goods_hub_id)
- {
- switch ($this->plugin_sign) {
- case SysConst::$cxPluginSceneMall:
- $type = Cat::TYPE_GOODS;
- break;
- case SysConst::$cxPluginSceneIntegralMall:
- $type = Cat::TYPE_INTEGRAL_GOODS;
- break;
- //@TODO 其他
- default:
- $type = Cat::TYPE_GOODS;
- }
- $list = GoodsCat::find()->alias('gc')
- ->leftJoin(['c' => Cat::tableName()], 'c.id=gc.cat_id')
- ->where([
- 'gc.is_delete' => 0,
- 'gc.goods_hub_id' => $goods_hub_id,
- 'c.is_delete' => 0,
- 'c.type' => $type,
- ])
- ->select('c.name,c.id as cat_id')->asArray()->all();
- return $list;
- }
-
- protected function getCat1List($goods_hub_id)
- {
- $list = GoodsCat::find()->alias('gc')
- ->leftJoin(['c' => Cat1::tableName()], 'c.id=gc.cat1_id')
- ->where([
- 'gc.is_delete' => 0,
- 'gc.goods_hub_id' => $goods_hub_id,
- 'c.is_delete' => 0,
- ])
- ->select('c.name,c.id as cat_id')->asArray()->all();
- return $list;
- }
-
-
- protected function getCat2List($goods_hub_id)
- {
-
- $list = GoodsCat::find()->alias('gc')
- ->leftJoin(['c' => Cat2::tableName()], 'c.id=gc.cat2_id')
- ->where([
- 'gc.is_delete' => 0,
- 'gc.goods_hub_id' => $goods_hub_id,
- 'c.is_delete' => 0,
- ])
- ->select('c.name,c.id as cat_id')->asArray()->all();
- return $list;
- }
-
- protected function getCat3List($goods_hub_id)
- {
-
- $list = GoodsCat::find()->alias('gc')
- ->leftJoin(['c' => Cat3::tableName()], 'c.id=gc.cat3_id')
- ->where([
- 'gc.is_delete' => 0,
- 'gc.goods_hub_id' => $goods_hub_id,
- 'c.is_delete' => 0,
- ])
- ->select('c.name,c.id as cat_id')->asArray()->all();
- return $list;
- }
-
-
- protected function getCat4List($goods_hub_id)
- {
-
- $list = GoodsCat::find()->alias('gc')
- ->leftJoin(['c' => Cat4::tableName()], 'c.id=gc.cat4_id')
- ->where([
- 'gc.is_delete' => 0,
- 'gc.goods_hub_id' => $goods_hub_id,
- 'c.is_delete' => 0,
- ])
- ->select('c.name,c.id as cat_id')->asArray()->all();
- return $list;
- }
-
-
- protected function fixPicUrls($pic_urls)
- {
- $pic_urls = is_string($pic_urls) && !empty($pic_urls) ? json_decode($pic_urls, true) : $pic_urls;
- foreach ($pic_urls as $index => $item) {
- $item = SiteHelper::getFullUrl($item);
- $pic_urls[$index] = $item;
- }
- return $pic_urls;
- }
-
- //获取商品规格
- private function getAttr($goods_id)
- {
- $attr = GoodsAttr::find()->alias('gr')
- ->where([
- 'gr.goods_id' => $goods_id,
- 'gr.is_delete' => 0
- ])
- ->select('gr.id,gr.goods_id,gr.price,gr.sign_id,gr.stock,gr.serial_no,gr.weight,gr.cover_pic')
- ->asArray()->all();
- foreach ($attr as $index => $item) {
- $item['cover_pic'] = SiteHelper::getFullUrl($item['cover_pic']);
- $attr[$index] = $item;
- }
- return $attr;
-
- }
-}
-
-
-
-
-
-
-
+ 1],
+ [['limit'], 'default', 'value' => 20],
+ [['status'], 'in', 'range' => [0, 1, 2]],
+ [['cx_mch_id'], 'required'],
+ [['start_time', 'end_time',], 'safe'],
+ [['goods_id'], 'required', 'on' => 'detail'],
+ ];
+ }
+
+ public function search()
+ {
+ if (!$this->validate()) {
+ return $this->getModelError();
+ }
+ $cat_query = GoodsCat::find()
+ ->where([
+ 'is_delete' => 0,
+ ])
+ ->select('goods_hub_id,cat_id,cat1_id,cat2_id,cat3_id,cat4_id');
+ $query = $this->getQuery($cat_query);
+ $query = $query->where([
+ 'g.cx_mch_id' => $this->cx_mch_id,
+ 'g.is_delete' => 0,
+ // 'gh.is_delete' => 0,
+// 'g.plugin_sign' => $this->plugin_sign,
+ ])
+ ->andFilterWhere([
+ 'OR',
+ ['LIKE', 'gh.name', $this->keywords],
+// ['LIKE', 'gh.subtitle', $this->keywords],
+ ])
+ ->andFilterWhere([
+ 'g.id' => $this->goods_id,
+ 'gc.cat_id' => $this->cat_id,
+ 'gc.cat1_id' => $this->cat1_id,
+ 'gc.cat2_id' => $this->cat2_id,
+ 'gc.cat3_id' => $this->cat3_id,
+ 'gc.cat4_id' => $this->cat4_id,
+ ]);
+ if ($this->status == 2) {
+ $query = $query->andWhere(['g.goods_stock' => 0]);//售罄
+ } else {
+ $query = $query->andFilterWhere(['g.status' => $this->status]);
+ }
+ $query = $this->switchTime($query);
+ $query = $this->getFields($query);
+ $count_query = clone $query;
+ $count = $count_query->count();
+ $pagination = new Pagination(['pageSize' => $this->limit, 'totalCount' => $count, 'page' => $this->page - 1]);
+ $list = $query->offset($pagination->offset)->limit($pagination->limit)->orderBy(['g.sort' => SORT_DESC, 'g.created_at' => SORT_DESC])->asArray()->all();
+
+
+ $list = $this->handleList($list);
+ //是否已经全部加载
+ $end_flag = $this->page > $pagination->pageCount ? true : false;
+ return [
+ 'code' => 0,
+ 'msg' => 'ok',
+ 'data' => $list,
+ 'count' => $count,
+ 'page_size' => $this->limit,
+ 'page_count' => $pagination->pageCount,
+ 'page_no' => $this->page,
+ 'end_flag' => $end_flag
+ ];
+ }
+
+ protected function getQuery($cat_query)
+ {
+ $query = Goods::find()->alias('g')
+ ->leftJoin(['gh' => GoodsHub::tableName()], 'gh.id=g.goods_hub_id')
+ ->leftJoin(['gc' => $cat_query], 'gc.goods_hub_id=gh.id');
+ return $query;
+ }
+
+ public function setFields($fields)
+ {
+ $this->fields = $fields;
+ }
+
+ protected function getFields($query)
+ {
+ $fields = is_array($this->fields) ? implode(',', $this->fields) : $this->fields;
+ return $query->select($fields);
+ }
+
+ protected function handleList($list)
+ {
+ foreach ($list as $index => $item) {
+ $item['status_cn'] = $item['status'] == Goods::STATUS_ONLINE ? '正常' : '隐藏';
+ $item['created_at_cn'] = date('Y-m-d H:i:s', $item['created_at']);
+ $item['date_at_cn'] = date('Y-m-d', $item['date']);
+
+ $item['cat_list'] = $this->getCatList($item['goods_hub_id']);
+
+ $item['cat1_list'] = $this->getCat1List($item['goods_hub_id']);
+ $item['cat2_list'] = $this->getCat2List($item['goods_hub_id']);
+ $item['cat3_list'] = $this->getCat3List($item['goods_hub_id']);
+ $item['cat4_list'] = $this->getCat4List($item['goods_hub_id']);
+
+
+ $item['cover_pic'] = SiteHelper::getFullUrl($item['cover_pic']);
+ if ($this->scenario == 'detail') {
+ $item['detail'] = SiteHelper::repairContent($item['detail']);
+ $item['pic_urls'] = $this->fixPicUrls($item['pic_urls']);
+ $item['video_url'] = SiteHelper::getFullUrl($item['video_url']);
+ $item['goods_sales'] = $item['virtaul_sales'] + $item['sales'];
+ $item['attr_groups'] = empty($item['attr_groups']) ? [] : json_decode($item['attr_groups'], true);
+ $item['attr'] = $this->getAttr($item['id']);
+ }
+ $list[$index] = $item;
+ }
+ return $list;
+ }
+
+
+ protected function switchTime($query)
+ {
+ if (!empty($this->start_time)) {
+ $query = $query->andWhere([
+ '>',
+ 'g.created_at',
+ strtotime($this->start_time)
+ ]);
+ }
+ if (!empty($this->end_time)) {
+ $query = $query->andWhere([
+ '<',
+ 'g.created_at',
+ strtotime($this->end_time)
+ ]);
+ }
+ return $query;
+ }
+
+ protected function getCatList($goods_hub_id)
+ {
+ switch ($this->plugin_sign) {
+ case SysConst::$cxPluginSceneMall:
+ $type = Cat::TYPE_GOODS;
+ break;
+ case SysConst::$cxPluginSceneIntegralMall:
+ $type = Cat::TYPE_INTEGRAL_GOODS;
+ break;
+ //@TODO 其他
+ default:
+ $type = Cat::TYPE_GOODS;
+ }
+ $list = GoodsCat::find()->alias('gc')
+ ->leftJoin(['c' => Cat::tableName()], 'c.id=gc.cat_id')
+ ->where([
+ 'gc.is_delete' => 0,
+ 'gc.goods_hub_id' => $goods_hub_id,
+ 'c.is_delete' => 0,
+ 'c.type' => $type,
+ ])
+ ->select('c.name,c.id as cat_id')->asArray()->all();
+ return $list;
+ }
+
+ protected function getCat1List($goods_hub_id)
+ {
+ $list = GoodsCat::find()->alias('gc')
+ ->leftJoin(['c' => Cat1::tableName()], 'c.id=gc.cat1_id')
+ ->where([
+ 'gc.is_delete' => 0,
+ 'gc.goods_hub_id' => $goods_hub_id,
+ 'c.is_delete' => 0,
+ ])
+ ->select('c.name,c.id as cat_id')->asArray()->all();
+ return $list;
+ }
+
+
+ protected function getCat2List($goods_hub_id)
+ {
+
+ $list = GoodsCat::find()->alias('gc')
+ ->leftJoin(['c' => Cat2::tableName()], 'c.id=gc.cat2_id')
+ ->where([
+ 'gc.is_delete' => 0,
+ 'gc.goods_hub_id' => $goods_hub_id,
+ 'c.is_delete' => 0,
+ ])
+ ->select('c.name,c.id as cat_id')->asArray()->all();
+ return $list;
+ }
+
+ protected function getCat3List($goods_hub_id)
+ {
+
+ $list = GoodsCat::find()->alias('gc')
+ ->leftJoin(['c' => Cat3::tableName()], 'c.id=gc.cat3_id')
+ ->where([
+ 'gc.is_delete' => 0,
+ 'gc.goods_hub_id' => $goods_hub_id,
+ 'c.is_delete' => 0,
+ ])
+ ->select('c.name,c.id as cat_id')->asArray()->all();
+ return $list;
+ }
+
+
+ protected function getCat4List($goods_hub_id)
+ {
+
+ $list = GoodsCat::find()->alias('gc')
+ ->leftJoin(['c' => Cat4::tableName()], 'c.id=gc.cat4_id')
+ ->where([
+ 'gc.is_delete' => 0,
+ 'gc.goods_hub_id' => $goods_hub_id,
+ 'c.is_delete' => 0,
+ ])
+ ->select('c.name,c.id as cat_id')->asArray()->all();
+ return $list;
+ }
+
+
+ protected function fixPicUrls($pic_urls)
+ {
+ $pic_urls = is_string($pic_urls) && !empty($pic_urls) ? json_decode($pic_urls, true) : $pic_urls;
+ foreach ($pic_urls as $index => $item) {
+ $item = SiteHelper::getFullUrl($item);
+ $pic_urls[$index] = $item;
+ }
+ return $pic_urls;
+ }
+
+ //获取商品规格
+ private function getAttr($goods_id)
+ {
+ $attr = GoodsAttr::find()->alias('gr')
+ ->where([
+ 'gr.goods_id' => $goods_id,
+ 'gr.is_delete' => 0
+ ])
+ ->select('gr.id,gr.goods_id,gr.price,gr.sign_id,gr.stock,gr.serial_no,gr.weight,gr.cover_pic')
+ ->asArray()->all();
+ foreach ($attr as $index => $item) {
+ $item['cover_pic'] = SiteHelper::getFullUrl($item['cover_pic']);
+ $attr[$index] = $item;
+ }
+ return $attr;
+
+ }
+}
+
+
+
+
+
+
+
diff --git a/modules/admin/controllers/mall/GoodsController.php b/modules/admin/controllers/mall/GoodsController.php
index dd8c14b..f7cefc2 100644
--- a/modules/admin/controllers/mall/GoodsController.php
+++ b/modules/admin/controllers/mall/GoodsController.php
@@ -194,7 +194,7 @@ class GoodsController extends Controller
$return_url = \Yii::$app->request->referrer;
- $model->date = date('Y-m-d', $model->date);
+ $model->date = date('Y', $model->date);
// var_dump($model->goodsHub->video_url);
// var_dump($model->goodsHub->video_banner_urls);
diff --git a/modules/admin/models/store/BoxEditForm.php b/modules/admin/models/store/BoxEditForm.php
index 860c7b4..9f4b16c 100644
--- a/modules/admin/models/store/BoxEditForm.php
+++ b/modules/admin/models/store/BoxEditForm.php
@@ -40,13 +40,14 @@ class BoxEditForm extends AdminModel
public $updated_at;
public $is_delete;
public $deleted_at;
+ public $sort;
public function rules()
{
return [
- [['status', 'created_at', 'updated_at', 'is_delete', 'deleted_at', 'goods_id', 'bj_id'], 'integer'],
+ [['status', 'created_at', 'updated_at', 'is_delete', 'deleted_at', 'goods_id', 'bj_id','sort'], 'integer'],
[['model'], 'safe'],
[['notice', 'cover_pic'], 'string'],
[['goods_id', 'bj_id', 'notice', 'cover_pic'], 'required'],
@@ -87,6 +88,7 @@ class BoxEditForm extends AdminModel
$this->model->cover_pic = $this->cover_pic;
$this->model->status = $this->status;
$this->model->notice = $this->notice;
+ $this->model->sort = $this->sort;
if (!$this->model->save()) {
return $this->getModelError($this->model);
diff --git a/modules/admin/models/store/BoxListForm.php b/modules/admin/models/store/BoxListForm.php
index 1f94d70..f22bca2 100644
--- a/modules/admin/models/store/BoxListForm.php
+++ b/modules/admin/models/store/BoxListForm.php
@@ -56,7 +56,7 @@ class BoxListForm extends AdminModel
->leftJoin(['goods' => Goods::tableName()], 'b.goods_id=goods.id')
->leftJoin(['goodHub' => GoodsHub::tableName()], 'goods.goods_hub_id=goodHub.id')
->leftJoin(['storeBj' => StoreBj::tableName()], 'b.bj_id=storeBj.id')
- ->select('b.id,b.created_at,b.status,goodHub.name as goods_name,storeBj.name as bj_name')
+ ->select('b.id,b.created_at,b.status,goodHub.name as goods_name,storeBj.name as bj_name,b.sort')
->where([
'b.is_delete' => 0
])
@@ -65,7 +65,7 @@ class BoxListForm extends AdminModel
$count = $query->count();
$pagination = new Pagination(['totalCount' => $count, 'pageSize' => $this->limit]);
- $list = $query->offset($pagination->offset)->limit($pagination->limit)->orderBy(['b.created_at' => SORT_DESC])->asArray()->all();
+ $list = $query->offset($pagination->offset)->limit($pagination->limit)->orderBy(['b.sort'=>SORT_DESC,'b.id' => SORT_DESC])->asArray()->all();
foreach ($list as $index => $item) {
// $item['business'] = $item['begin_time'] . '-' . $item['end_time'];
$item['created_at_cn'] = date("Y-m-d H:i", $item['created_at']);
diff --git a/modules/admin/views/mall/goods/edit.php b/modules/admin/views/mall/goods/edit.php
index 7381d28..f7d8c5b 100644
--- a/modules/admin/views/mall/goods/edit.php
+++ b/modules/admin/views/mall/goods/edit.php
@@ -1,329 +1,344 @@
-title = $model->isNewRecord ? '添加冠军' : '编辑冠军';
-$this->params['breadcrumbs'][] = ['label' => '冠军', 'url' => [\Yii::$app->urlManager->createUrl(["admin/mall/goods/index"])]];
-$this->params['breadcrumbs'][] = $this->title;
-?>
-
-
-
-
-
-
-
-
-
-
-
-
- = PickFile::widget([
- 'accept' => 'images',
- 'id' => 'cover_pic',
- 'name' => 'cover_pic',
- 'label' => '封面',
- 'value' => $model->goodsHub ? $model->goodsHub->cover_pic : '',
- 'tip' => '图片大小750×750',
- 'required' => true,
- 'imageCompressEnable' => 1,
- 'imageCompressBorder' => 750,
- ]) ?>
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- = PickFile::widget([
- 'multiple' => true,
- 'accept' => 'images',
- 'id' => 'pic_urls',
- 'name' => 'pic_urls',
- 'label' => '冠军轮播图(多张)',
- 'value' => $model->goodsHub ? $model->goodsHub->pic_urls : '',
- 'tip' => '图片大小750×750',
- 'required' => true,
-// 'imageCompressEnable' => 1,
-// 'imageCompressBorder' => 750,
- ]) ?>
-
-
- = PickFile::widget([
- 'accept' => 'images',
- 'id' => 'banner_urls',
- 'name' => 'banner_urls',
- 'label' => '冠军详情图',
- 'value' => $model->goodsHub ? $model->goodsHub->banner_urls : '',
-// 'tip' => '图片大小750×750',
- 'required' => true,
- 'imageCompressEnable' => 1,
- 'imageCompressBorder' => 750,
- ]) ?>
-
-
-
-
- goodsHub->video_url)) {
- $json_de = json_decode($model->goodsHub->video_url, true);
- $temp_arr = [];
- foreach ($json_de as $key => $val) {
- $explode = explode('/', $val);
- $end = end($explode);
- //
- $temp_arr[] = [
- 'name' => $end,
- 'url' => $val,
- ];
- }
- $model->goodsHub->video_url = json_encode($temp_arr, JSON_UNESCAPED_UNICODE);
- }
- ?>
-
-
- = PickFile::widget([
- 'accept' => 'file',
- 'multiple' => true,
- 'id' => 'video_url',
- 'name' => 'video_url',
- 'label' => '冠军视频',
- 'value' => $model->goodsHub ? $model->goodsHub->video_url : '',
- 'tip' => '视频最大50M',
- 'required' => false
- ]) ?>
-
-
- = PickFile::widget([
- 'multiple' => true,
- 'accept' => 'images',
- 'id' => 'video_banner_urls',
- 'name' => 'video_banner_urls',
- 'label' => '冠军视频封面图',
- 'value' => $model->goodsHub ? $model->goodsHub->video_banner_urls : '',
- 'tip' => '图片大小750×750',
- 'required' => true,
-// 'imageCompressEnable' => 1,
-// 'imageCompressBorder' => 750,
- ]) ?>
-
-
-
-
-
-
-
-
-
-
-
-registerJs($this->blocks['js_script_wrap'], \yii\web\View::POS_END); ?>
-
-
-
+title = $model->isNewRecord ? '添加冠军' : '编辑冠军';
+$this->params['breadcrumbs'][] = ['label' => '冠军', 'url' => [\Yii::$app->urlManager->createUrl(["admin/mall/goods/index"])]];
+$this->params['breadcrumbs'][] = $this->title;
+?>
+
+
+
+
+
+
+
+
+
+
+
+
+ = PickFile::widget([
+ 'accept' => 'images',
+ 'id' => 'cover_pic',
+ 'name' => 'cover_pic',
+ 'label' => '封面',
+ 'value' => $model->goodsHub ? $model->goodsHub->cover_pic : '',
+ 'tip' => '图片大小750×750',
+ 'required' => true,
+ 'imageCompressEnable' => 1,
+ 'imageCompressBorder' => 750,
+ ]) ?>
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ = PickFile::widget([
+ 'multiple' => true,
+ 'accept' => 'images',
+ 'id' => 'pic_urls',
+ 'name' => 'pic_urls',
+ 'label' => '冠军轮播图(多张)',
+ 'value' => $model->goodsHub ? $model->goodsHub->pic_urls : '',
+ 'tip' => '图片大小750×750',
+ 'required' => true,
+// 'imageCompressEnable' => 1,
+// 'imageCompressBorder' => 750,
+ ]) ?>
+
+
+ = PickFile::widget([
+ 'accept' => 'images',
+ 'id' => 'banner_urls',
+ 'name' => 'banner_urls',
+ 'label' => '冠军详情图',
+ 'value' => $model->goodsHub ? $model->goodsHub->banner_urls : '',
+// 'tip' => '图片大小750×750',
+ 'required' => true,
+ 'imageCompressEnable' => 1,
+ 'imageCompressBorder' => 750,
+ ]) ?>
+
+
+
+
+ goodsHub->video_url)) {
+ $json_de = json_decode($model->goodsHub->video_url, true);
+ $temp_arr = [];
+ foreach ($json_de as $key => $val) {
+ $explode = explode('/', $val);
+ $end = end($explode);
+ //
+ $temp_arr[] = [
+ 'name' => $end,
+ 'url' => $val,
+ ];
+ }
+ $model->goodsHub->video_url = json_encode($temp_arr, JSON_UNESCAPED_UNICODE);
+ }
+ ?>
+
+
+ = PickFile::widget([
+ 'accept' => 'file',
+ 'multiple' => true,
+ 'id' => 'video_url',
+ 'name' => 'video_url',
+ 'label' => '冠军视频',
+ 'value' => $model->goodsHub ? $model->goodsHub->video_url : '',
+ 'tip' => '视频最大50M',
+ 'required' => false
+ ]) ?>
+
+
+ = PickFile::widget([
+ 'multiple' => true,
+ 'accept' => 'images',
+ 'id' => 'video_banner_urls',
+ 'name' => 'video_banner_urls',
+ 'label' => '冠军视频封面图',
+ 'value' => $model->goodsHub ? $model->goodsHub->video_banner_urls : '',
+ 'tip' => '图片大小750×750',
+ 'required' => true,
+// 'imageCompressEnable' => 1,
+// 'imageCompressBorder' => 750,
+ ]) ?>
+
+
+
+
+
+
+
+
+
+
+
+registerJs($this->blocks['js_script_wrap'], \yii\web\View::POS_END); ?>
+
+
+
diff --git a/modules/admin/views/mall/goods/index.php b/modules/admin/views/mall/goods/index.php
index e0dfc07..72a0c15 100644
--- a/modules/admin/views/mall/goods/index.php
+++ b/modules/admin/views/mall/goods/index.php
@@ -1,503 +1,504 @@
-title = '冠军列表';
-$this->params['breadcrumbs'][] = $this->title;
-
-$status_labels = [
- '0' => '已隐藏',
- '1' => '已启用',
-];
-$status = \Yii::$app->request->get('status');
-$cat_id = \Yii::$app->request->get('cat_id');
-?>
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-registerJs($this->blocks['js_script_wrap'], \yii\web\View::POS_END); ?>
-
+title = '冠军列表';
+$this->params['breadcrumbs'][] = $this->title;
+
+$status_labels = [
+ '0' => '已隐藏',
+ '1' => '已启用',
+];
+$status = \Yii::$app->request->get('status');
+$cat_id = \Yii::$app->request->get('cat_id');
+?>
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+registerJs($this->blocks['js_script_wrap'], \yii\web\View::POS_END); ?>
+
diff --git a/modules/admin/views/store/store-user-edit.php b/modules/admin/views/store/store-user-edit.php
index 9e73b26..576b4f4 100644
--- a/modules/admin/views/store/store-user-edit.php
+++ b/modules/admin/views/store/store-user-edit.php
@@ -75,6 +75,13 @@ $this->params['breadcrumbs'][] = $this->title;
+
+
diff --git a/modules/admin/views/store/store-user.php b/modules/admin/views/store/store-user.php
index 2a7e737..24ab09a 100644
--- a/modules/admin/views/store/store-user.php
+++ b/modules/admin/views/store/store-user.php
@@ -143,11 +143,11 @@ $user_type = \Yii::$app->request->get('user_type');
, {field: 'id', title: 'ID', width: 80}
, {field: 'goods_name', title: '冠军名称'}
, {field: 'bj_name', title: '所属分类'}
- // , {field: 'money', title: '案例金额'}
// , {field: 'device', title: '案例设备'}
// , {field: 'business', title: '营业时间', width: 110}
, {field: 'status', title: '状态', templet: '#statusTpl', width: 80}
, {field: 'created_at_cn', title: '创建时间', width: 150}
+ , {field: 'sort', title: '案例排序'}
, {title: '操作', fixed: 'right', toolbar: '#rowBarTpl', width: 200}
]
]
diff --git a/modules/api/controllers/mall/integral/GoodsController.php b/modules/api/controllers/mall/integral/GoodsController.php
index a6c1d99..d134cd3 100644
--- a/modules/api/controllers/mall/integral/GoodsController.php
+++ b/modules/api/controllers/mall/integral/GoodsController.php
@@ -78,7 +78,7 @@ class GoodsController extends Controller
$data = $form->search();
foreach ($data['data'] as $key => $value) {
- $data['data'][$key]['date'] = date('Y-m-d', $value['date']);
+ $data['data'][$key]['date'] = date('Y', $value['date']);
// $data['data'][$key]['video_url'] = SiteHelper::getFullUrl($value['video_url']);
$data['data'][$key]['pic_arr'] = [];
if ($value['pic_urls'] != null) {
@@ -141,7 +141,7 @@ class GoodsController extends Controller
$data = $form->search();
foreach ($data['data'] as $key => $value) {
- $data['data'][$key]['date'] = date('Y-m-d', $value['date']);
+ $data['data'][$key]['date'] = date('Y', $value['date']);
$data['data'][$key]['pic_arr'] = [];
if ($value['pic_urls'] != null) {
$pic_arr = json_decode($value['pic_urls'], true);
diff --git a/modules/api/models/BoxForm.php b/modules/api/models/BoxForm.php
index 08f2b8e..c4aaf37 100644
--- a/modules/api/models/BoxForm.php
+++ b/modules/api/models/BoxForm.php
@@ -71,7 +71,7 @@ class BoxForm extends ApiModel
$count = $query->count();
$pagination = new Pagination(['totalCount' => $count, 'pageSize' => $this->limit]);
- $list = $query->offset($pagination->offset)->limit($pagination->limit)->orderBy(['b.created_at' => SORT_DESC])->asArray()->all();
+ $list = $query->offset($pagination->offset)->limit($pagination->limit)->orderBy(['b.sort'=>SORT_DESC,'b.id' => SORT_DESC])->asArray()->all();
foreach ($list as $index => $item) {
// $item['business'] = $item['begin_time'] . '-' . $item['end_time'];
$list[$index]['created_at_cn'] = date("Y-m-d H:i", $item['created_at']);
diff --git a/modules/file/controllers/UploadController.php b/modules/file/controllers/UploadController.php
index 81eeb30..5860ba3 100644
--- a/modules/file/controllers/UploadController.php
+++ b/modules/file/controllers/UploadController.php
@@ -1,997 +1,997 @@
- [
- /* 文件上传的根目录 */
- //'rootPath' => $_SERVER['DOCUMENT_ROOT'],
- /* 上传图片配置项 */
- "imageActionName" => "uploadimage",
- /* 执行上传图片的action名称 */
- "imageFieldName" => "file",
- /* 提交的图片表单名称 */
- "imageMaxSize" => 20480000,
- /* 上传大小限制,单位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,
- /* 上传大小限制,单位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($rfmt = 'default')
-// {
-// if(!\Yii::$app->request->isPost){
-// $data = [
-// 'code' => 1,
-// 'msg' => "Invalid Request"
-// ];
-// return $this->responseHandler($data);
-// }
-// $action = "uploadimage";
-// $fileInfo = $this->uploadFile($action);
-// if($rfmt == 'default'){
-// 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"]
-// ];
-// }
-// } else if($rfmt == 'wangeditor'){
-// if($fileInfo["state"] == "SUCCESS"){
-// $data = [
-// 'errno' => 0,
-// 'message' => 'success',
-// 'data' => [
-// 'url' => $fileInfo['url'],
-// 'alt' => '',
-// 'href' => '',
-// 'extension' => $fileInfo["type"],
-// 'size' => $fileInfo["size"],
-// 'type' => $this->getFileType(trim($fileInfo['type'],"."))
-// ]
-// ];
-// } else {
-// $data = [
-// 'errno' => 1,
-// 'message' => $fileInfo["state"]
-// ];
-// }
-// }
-// return $this->responseHandler($data);
-// }
-
-
- //上传图片到OSS
- public function actionImage()
- {
- if (!\Yii::$app->request->isPost) {
- $data = [
- 'code' => 1,
- 'msg' => "Invalid Request"
- ];
- return $this->responseHandler($data);
- }
-
- if (empty($_FILES['file']['name'])) {
- $data = [
- 'code' => 1,
- 'msg' => "请选择要上传的文件"
- ];
- return $this->responseHandler($data);
- }
-
-
- // 上传文件的目录
- $upload_dir = \Yii::$app->basePath . "/web/upload/1/";
-
- if (!is_dir($upload_dir)) {
- mkdir(\Yii::$app->basePath . '/web/upload/1', 0777, true);
- }
- $file = md5($_FILES['file']['name']);
- // 上传文件的全名
- $upload_file = \Yii::$app->basePath . '/web/upload/1/' . $file . '.png';
- // 将上传的文件从临时目录移动到指定目录
- if (!move_uploaded_file($_FILES['file']['tmp_name'], $upload_file)) {
- $data = [
- 'code' => 1,
- 'msg' => "文件上传失败"
- ];
- } else {
- $oss = new Oss();
- $file = '/web/upload/1/' . $file . '.png';
- //上传文件目录
- $oss_data = $oss->upload($upload_file, $file);
- if ($oss == false) {
- $data = [
- 'code' => 1,
- 'msg' => "文件上传失败"
- ];
- } else {
- $data = [
- 'code' => 0,
- 'msg' => 'success',
- 'data' => [
- 'url' => $oss_data,
- ]
- ];
- }
- }
- return $this->responseHandler($data);
- }
-
-
- //上传文件
- public function actionFile($rfmt = 'default')
- {
- if (!\Yii::$app->request->isPost) {
- $data = [
- 'code' => 1,
- 'msg' => "Invalid Request"
- ];
- return $this->responseHandler($data);
- }
-
-
- if (empty($_FILES['file']['name'])) {
- $data = [
- 'code' => 1,
- 'msg' => "请选择要上传的文件"
- ];
- return $this->responseHandler($data);
- }
- $type = $_FILES['file']['type'];
- $explode = explode('/', $type);
- $type = end($explode);
-
- // 上传文件的目录
- $upload_dir = \Yii::$app->basePath . "/web/uploads/file/";
-
- if (!is_dir($upload_dir)) {
- mkdir(\Yii::$app->basePath . '/web/uploads/file', 0777, true);
- }
- $file = md5($_FILES['file']['name']);
- // 上传文件的全名
- $upload_file = \Yii::$app->basePath . '/web/uploads/file/' . $file . '.' . $type;
- // 将上传的文件从临时目录移动到指定目录
- if (!move_uploaded_file($_FILES['file']['tmp_name'], $upload_file)) {
- $data = [
- 'code' => 1,
- 'msg' => "文件上传失败"
- ];
- } else {
- $oss = new Oss();
- //上传文件目录
- $oss_data = $oss->upload($upload_file);
- if ($oss == false) {
- $data = [
- 'code' => 1,
- 'msg' => "文件上传失败"
- ];
- } else {
- $data = [
- 'code' => 0,
- 'msg' => 'success',
- 'data' => [
- 'url' => $oss_data,
- ]
- ];
- }
- }
- return $this->responseHandler($data);
- }
-
-
-
-// //上传文件
-// public function actionFile($rfmt = 'default')
-// {
-// if (!\Yii::$app->request->isPost) {
-// $data = [
-// 'code' => 1,
-// 'msg' => "Invalid Request"
-// ];
-// return $this->responseHandler($data);
-// }
-//
-//
-// $action = "uploadfile";
-// $fileInfo = $this->uploadFile($action);
-// if ($rfmt == 'default') {
-// 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"]
-// ];
-// }
-// } else if ($rfmt == 'wangeditor') {
-// if ($fileInfo["state"] == "SUCCESS") {
-// $data = [
-// 'errno' => 0,
-// 'message' => 'success',
-// 'data' => [
-// 'url' => $fileInfo['url'],
-// 'alt' => '',
-// 'href' => '',
-// 'extension' => $fileInfo["type"],
-// 'size' => $fileInfo["size"],
-// 'type' => $this->getFileType(trim($fileInfo['type'], "."))
-// ]
-// ];
-// } else {
-// $data = [
-// 'errno' => 1,
-// 'message' => $fileInfo["state"]
-// ];
-// }
-// }
-// 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 '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->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();
- $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);
- }
+ [
+ /* 文件上传的根目录 */
+ //'rootPath' => $_SERVER['DOCUMENT_ROOT'],
+ /* 上传图片配置项 */
+ "imageActionName" => "uploadimage",
+ /* 执行上传图片的action名称 */
+ "imageFieldName" => "file",
+ /* 提交的图片表单名称 */
+ "imageMaxSize" => 20480000,
+ /* 上传大小限制,单位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,
+ /* 上传大小限制,单位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($rfmt = 'default')
+// {
+// if(!\Yii::$app->request->isPost){
+// $data = [
+// 'code' => 1,
+// 'msg' => "Invalid Request"
+// ];
+// return $this->responseHandler($data);
+// }
+// $action = "uploadimage";
+// $fileInfo = $this->uploadFile($action);
+// if($rfmt == 'default'){
+// 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"]
+// ];
+// }
+// } else if($rfmt == 'wangeditor'){
+// if($fileInfo["state"] == "SUCCESS"){
+// $data = [
+// 'errno' => 0,
+// 'message' => 'success',
+// 'data' => [
+// 'url' => $fileInfo['url'],
+// 'alt' => '',
+// 'href' => '',
+// 'extension' => $fileInfo["type"],
+// 'size' => $fileInfo["size"],
+// 'type' => $this->getFileType(trim($fileInfo['type'],"."))
+// ]
+// ];
+// } else {
+// $data = [
+// 'errno' => 1,
+// 'message' => $fileInfo["state"]
+// ];
+// }
+// }
+// return $this->responseHandler($data);
+// }
+
+
+ //上传图片到OSS
+ public function actionImage()
+ {
+ if (!\Yii::$app->request->isPost) {
+ $data = [
+ 'code' => 1,
+ 'msg' => "Invalid Request"
+ ];
+ return $this->responseHandler($data);
+ }
+
+ if (empty($_FILES['file']['name'])) {
+ $data = [
+ 'code' => 1,
+ 'msg' => "请选择要上传的文件"
+ ];
+ return $this->responseHandler($data);
+ }
+
+
+ // 上传文件的目录
+ $upload_dir = \Yii::$app->basePath . "/web/upload/1/";
+
+ if (!is_dir($upload_dir)) {
+ mkdir(\Yii::$app->basePath . '/web/upload/1', 0777, true);
+ }
+ $file = md5($_FILES['file']['name']);
+ // 上传文件的全名
+ $upload_file = \Yii::$app->basePath . '/web/upload/1/' . $file . '.png';
+ // 将上传的文件从临时目录移动到指定目录
+ if (!move_uploaded_file($_FILES['file']['tmp_name'], $upload_file)) {
+ $data = [
+ 'code' => 1,
+ 'msg' => "文件上传失败"
+ ];
+ } else {
+ $oss = new Oss();
+ $file = '/web/upload/1/' . $file . '.png';
+ //上传文件目录
+ $oss_data = $oss->upload($upload_file, $file);
+ if ($oss == false) {
+ $data = [
+ 'code' => 1,
+ 'msg' => "文件上传失败"
+ ];
+ } else {
+ $data = [
+ 'code' => 0,
+ 'msg' => 'success',
+ 'data' => [
+ 'url' => $oss_data,
+ ]
+ ];
+ }
+ }
+ return $this->responseHandler($data);
+ }
+
+
+ //上传文件
+ public function actionFile($rfmt = 'default')
+ {
+ if (!\Yii::$app->request->isPost) {
+ $data = [
+ 'code' => 1,
+ 'msg' => "Invalid Request"
+ ];
+ return $this->responseHandler($data);
+ }
+
+
+ if (empty($_FILES['file']['name'])) {
+ $data = [
+ 'code' => 1,
+ 'msg' => "请选择要上传的文件"
+ ];
+ return $this->responseHandler($data);
+ }
+ $type = $_FILES['file']['type'];
+ $explode = explode('/', $type);
+ $type = end($explode);
+
+ // 上传文件的目录
+ $upload_dir = \Yii::$app->basePath . "/web/uploads/file/";
+
+ if (!is_dir($upload_dir)) {
+ mkdir(\Yii::$app->basePath . '/web/uploads/file', 0777, true);
+ }
+ $file = md5($_FILES['file']['name']);
+ // 上传文件的全名
+ $upload_file = \Yii::$app->basePath . '/web/uploads/file/' . $file . '.' . $type;
+ // 将上传的文件从临时目录移动到指定目录
+ if (!move_uploaded_file($_FILES['file']['tmp_name'], $upload_file)) {
+ $data = [
+ 'code' => 1,
+ 'msg' => "文件上传失败"
+ ];
+ } else {
+ $oss = new Oss();
+ //上传文件目录
+ $oss_data = $oss->upload($upload_file);
+ if ($oss == false) {
+ $data = [
+ 'code' => 1,
+ 'msg' => "文件上传失败"
+ ];
+ } else {
+ $data = [
+ 'code' => 0,
+ 'msg' => 'success',
+ 'data' => [
+ 'url' => $oss_data,
+ ]
+ ];
+ }
+ }
+ return $this->responseHandler($data);
+ }
+
+
+
+// //上传文件
+// public function actionFile($rfmt = 'default')
+// {
+// if (!\Yii::$app->request->isPost) {
+// $data = [
+// 'code' => 1,
+// 'msg' => "Invalid Request"
+// ];
+// return $this->responseHandler($data);
+// }
+//
+//
+// $action = "uploadfile";
+// $fileInfo = $this->uploadFile($action);
+// if ($rfmt == 'default') {
+// 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"]
+// ];
+// }
+// } else if ($rfmt == 'wangeditor') {
+// if ($fileInfo["state"] == "SUCCESS") {
+// $data = [
+// 'errno' => 0,
+// 'message' => 'success',
+// 'data' => [
+// 'url' => $fileInfo['url'],
+// 'alt' => '',
+// 'href' => '',
+// 'extension' => $fileInfo["type"],
+// 'size' => $fileInfo["size"],
+// 'type' => $this->getFileType(trim($fileInfo['type'], "."))
+// ]
+// ];
+// } else {
+// $data = [
+// 'errno' => 1,
+// 'message' => $fileInfo["state"]
+// ];
+// }
+// }
+// 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 '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->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();
+ $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);
+ }
}
\ No newline at end of file
diff --git a/vendor.rar b/vendor.rar
deleted file mode 100644
index 0021a61..0000000
Binary files a/vendor.rar and /dev/null differ