CopyTaobao.php 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008
  1. <?php
  2. /**
  3. * Project: 快速复制 淘宝、天猫、1688、京东 商品到CRMEB系统
  4. * Author: 有一片天 <810806442@qq.com> 微信:szktor
  5. * Date: 2019-04-25
  6. */
  7. namespace app\admin\controller\store;
  8. use app\admin\controller\AuthController;
  9. use think\exception\PDOException;
  10. use crmeb\traits\CurdControllerTrait;
  11. use crmeb\services\{CacheService, HttpService, JsonService, UtilService};
  12. use app\admin\model\system\{
  13. SystemAttachment, SystemAttachmentCategory
  14. };
  15. use app\admin\model\store\{
  16. StoreCategory as CategoryModel, StoreDescription, StoreProduct as ProductModel, StoreProductAttr, StoreProductCate
  17. };
  18. use crmeb\services\upload\Upload;
  19. use crmeb\services\product\Product;
  20. /**
  21. * 产品管理
  22. * Class StoreProduct
  23. * @package app\admin\controller\store
  24. */
  25. class CopyTaobao extends AuthController
  26. {
  27. use CurdControllerTrait;
  28. protected $bindModel = ProductModel::class;
  29. //错误信息
  30. protected $errorInfo = true;
  31. //产品默认字段
  32. protected $productInfo = [
  33. 'cate_id' => '',
  34. 'store_name' => '',
  35. 'store_info' => '',
  36. 'unit_name' => '件',
  37. 'price' => 0,
  38. 'keyword' => '',
  39. 'ficti' => 0,
  40. 'ot_price' => 0,
  41. 'give_integral' => 0,
  42. 'postage' => 0,
  43. 'cost' => 0,
  44. 'image' => '',
  45. 'slider_image' => '',
  46. 'add_time' => 0,
  47. 'stock' => 0,
  48. 'description' => '',
  49. 'soure_link' => '',
  50. 'temp_id' => 0
  51. ];
  52. //抓取网站主域名
  53. protected $grabName = [
  54. 'taobao',
  55. '1688',
  56. 'tmall',
  57. 'jd'
  58. ];
  59. //远程下载附件图片分类名称
  60. protected $AttachmentCategoryName = '远程下载';
  61. //cookie 采集前请配置自己的 cookie,获取方式浏览器登录平台,F12或查看元素 network->headers 查看Request Headers 复制cookie 到下面变量中
  62. protected $webcookie = [
  63. //淘宝
  64. 'taobao' => 'cookie: miid=8289590761042824660; thw=cn; cna=bpdDExs9KGgCAXuLszWnEXxS; hng=CN%7Czh-CN%7CCNY%7C156; tracknick=taobaorongyao; _cc_=WqG3DMC9EA%3D%3D; tg=0; enc=WQPStocTopRI3wEBOPpj8VUDkqSw4Ph81ASG9053SgG8xBMzaOuq6yMe8KD4xPBlNfQST7%2Ffsk9M9GDtGmn6iQ%3D%3D; t=4bab065740d964a05ad111f5057078d4; cookie2=1965ea371faf24b163093f31af4120c2; _tb_token_=5d3380e119d6e; v=0; mt=ci%3D-1_1; _m_h5_tk=61bf01c61d46a64c98209a7e50e9e1df_1572349453522; _m_h5_tk_enc=9d9adfcbd7af7e2274c9b331dc9bae9b; l=dBgc_jG4vxuski7DBOCgCuI8aj7TIIRAguPRwN0viOCKUxT9CgCDAJt5v8PWVNKO7t1nNetzvui3udLHRntW6KTK6MK9zd9snxf..; isg=BJWVXJ3FZGyiWUENfGCuywlwpJePOkncAk8hmRc6WoxbbrVg3-Jadf0uODL97mFc',
  65. //阿里巴巴 1688
  66. 'alibaba' => '',
  67. //天猫 可以和淘宝一样
  68. 'tmall' => 'cookie: miid=8289590761042824660; thw=cn; cna=bpdDExs9KGgCAXuLszWnEXxS; hng=CN%7Czh-CN%7CCNY%7C156; tracknick=taobaorongyao; _cc_=WqG3DMC9EA%3D%3D; tg=0; enc=WQPStocTopRI3wEBOPpj8VUDkqSw4Ph81ASG9053SgG8xBMzaOuq6yMe8KD4xPBlNfQST7%2Ffsk9M9GDtGmn6iQ%3D%3D; t=4bab065740d964a05ad111f5057078d4; cookie2=1965ea371faf24b163093f31af4120c2; _tb_token_=5d3380e119d6e; v=0; mt=ci%3D-1_1; _m_h5_tk=61bf01c61d46a64c98209a7e50e9e1df_1572349453522; _m_h5_tk_enc=9d9adfcbd7af7e2274c9b331dc9bae9b; l=dBgc_jG4vxuski7DBOCgCuI8aj7TIIRAguPRwN0viOCKUxT9CgCDAJt5v8PWVNKO7t1nNetzvui3udLHRntW6KTK6MK9zd9snxf..; isg=BJWVXJ3FZGyiWUENfGCuywlwpJePOkncAk8hmRc6WoxbbrVg3-Jadf0uODL97mFc',
  69. //京东 可不用配置
  70. 'jd' => ''
  71. ];
  72. //请求平台名称 taobao alibaba tmall jd
  73. protected $webnname = 'taobao';
  74. /**
  75. * 显示资源
  76. * @return html
  77. */
  78. public function index()
  79. {
  80. $list = CategoryModel::getTierList(null, 1);
  81. $menus = [];
  82. foreach ($list as $menu) {
  83. $menus[] = ['value' => $menu['id'], 'label' => $menu['html'] . $menu['cate_name'], 'disabled' => $menu['pid'] == 0];//,'disabled'=>$menu['pid']== 0];
  84. }
  85. $this->assign('menus', $menus);
  86. $this->assign('is_layui', 1);
  87. return $this->fetch();
  88. }
  89. /**
  90. * 付费采集页面
  91. * @return html
  92. */
  93. public function product()
  94. {
  95. $list = CategoryModel::getTierList(null, 1);
  96. $menus = [];
  97. foreach ($list as $menu) {
  98. $menus[] = ['value' => $menu['id'], 'label' => $menu['html'] . $menu['cate_name'], 'disabled' => $menu['pid'] == 0];//,'disabled'=>$menu['pid']== 0];
  99. }
  100. $this->assign('menus', $menus);
  101. $this->assign('is_layui', 1);
  102. return $this->fetch();
  103. }
  104. /**
  105. * 付费采集请求
  106. */
  107. public function get_product_info()
  108. {
  109. list($link, $type) = UtilService::postMore([
  110. ['link', ''],
  111. ['type', '']
  112. ], $this->request, true);
  113. $cache = app()->make(CacheService::class);
  114. $product = new Product('copy', ['account' => sys_config('sms_account'), 'secret' => sys_config('sms_token')]);
  115. $key = md5($link);
  116. $info = $cache->get($key);
  117. if(!$info){
  118. $info = $product->goods($link);
  119. $cache->set($key,$info,7200);
  120. }
  121. $info = array_merge($this->productInfo,$info);
  122. return JsonService::successful($info);
  123. }
  124. /*
  125. * 设置错误信息
  126. * @param string $msg 错误信息
  127. * */
  128. public function setErrorInfo($msg = '')
  129. {
  130. $this->errorInfo = $msg;
  131. return false;
  132. }
  133. /*
  134. * 设置字符串字符集
  135. * @param string $str 需要设置字符集的字符串
  136. * @return string
  137. * */
  138. public function Utf8String($str)
  139. {
  140. $encode = mb_detect_encoding($str, array("ASCII", 'UTF-8', "GB2312", "GBK", 'BIG5'));
  141. if (strtoupper($encode) == 'UTF-8') {
  142. } else if (strtolower($encode) == 'cp936') {
  143. // $str = iconv('latin1//IGNORE', 'utf-8', $str);
  144. $str = mb_convert_encoding($str, 'utf-8', 'GBK');
  145. } else {
  146. $str = mb_convert_encoding($str, 'utf-8', $encode);
  147. }
  148. return $str;
  149. }
  150. /**
  151. * 获取资源,并解析出对应的商品参数
  152. * @return json
  153. */
  154. public function get_request_contents()
  155. {
  156. list($link) = UtilService::postMore([
  157. ['link', '']
  158. ], $this->request, true);
  159. $url = $this->checkurl($link);
  160. if ($url === false) return JsonService::fail($this->errorInfo);
  161. $this->errorInfo = true;
  162. $html = $this->curl_Get($url, 60);
  163. if (!$html) return JsonService::fail('商品HTML信息获取失败');
  164. $html = $this->Utf8String($html);
  165. preg_match('/<title>([^<>]*)<\/title>/', $html, $title);
  166. //商品标题
  167. $this->productInfo['store_name'] = isset($title['1']) ? str_replace(['-淘宝网', '-tmall.com天猫', ' - 阿里巴巴', ' ', '-', '【图片价格品牌报价】京东', '京东', '【行情报价价格评测】'], '', trim($title['1'])) : '';
  168. $this->productInfo['store_info'] = $this->productInfo['store_name'];
  169. try {
  170. //获取url信息
  171. $pathinfo = pathinfo($url);
  172. if (!isset($pathinfo['dirname'])) return JsonService::fail('解析URL失败');
  173. //提取域名
  174. $parse_url = parse_url($pathinfo['dirname']);
  175. if (!isset($parse_url['host'])) return JsonService::fail('获取域名失败');
  176. //获取第一次.出现的位置
  177. $strLeng = strpos($parse_url['host'], '.') + 1;
  178. //截取域名中的真实域名不带.com后的
  179. $funsuffix = substr($parse_url['host'], $strLeng, strrpos($parse_url['host'], '.') - $strLeng);
  180. if (!in_array($funsuffix, $this->grabName)) return JsonService::fail('您输入的地址不在复制范围内!');
  181. //设拼接设置产品函数
  182. $funName = "setProductInfo" . ucfirst($funsuffix);
  183. //执行方法
  184. if (method_exists($this, $funName))
  185. $this->$funName($html);
  186. else
  187. return JsonService::fail('设置产品函数不存在');
  188. if (!$this->productInfo['slider_image']) return JsonService::fail('未能获取到商品信息,请确保商品信息有效!');
  189. return JsonService::successful($this->productInfo);
  190. } catch (\Exception $e) {
  191. return JsonService::fail('系统错误', ['line' => $e->getLine(), 'meass' => $e->getMessage()]);
  192. }
  193. }
  194. /**
  195. * 淘宝设置产品
  196. * @param $html
  197. */
  198. public function setProductInfoTaobao($html)
  199. {
  200. $this->webnname = 'taobao';
  201. //获取轮播图
  202. $images = $this->getTaobaoImg($html);
  203. $images = array_merge(is_array($images) ? $images : []);
  204. $this->productInfo['slider_image'] = isset($images['gaoqing']) ? $images['gaoqing'] : (array)$images;
  205. $this->productInfo['slider_image'] = array_slice($this->productInfo['slider_image'], 0, 5);
  206. //获取产品详情请求链接
  207. $link = $this->getTaobaoDesc($html);
  208. //获取请求内容
  209. $desc_json = HttpService::getRequest($link);
  210. //转换字符集
  211. $desc_json = $this->Utf8String($desc_json);
  212. //截取掉多余字符
  213. $this->productInfo['test'] = $desc_json;
  214. $desc_json = str_replace('var desc=\'', '', $desc_json);
  215. $desc_json = str_replace(["\n", "\t", "\r"], '', $desc_json);
  216. $content = substr($desc_json, 0, -2);
  217. $this->productInfo['description'] = $content;
  218. //获取详情图
  219. $description_images = $this->decodedesc($this->productInfo['description']);
  220. $this->productInfo['description_images'] = is_array($description_images) ? $description_images : [];
  221. $this->productInfo['image'] = is_array($this->productInfo['slider_image']) && isset($this->productInfo['slider_image'][0]) ? $this->productInfo['slider_image'][0] : '';
  222. }
  223. /**
  224. * 天猫设置产品
  225. * @param $html
  226. */
  227. public function setProductInfoTmall($html)
  228. {
  229. $this->webnname = 'tmall';
  230. //获取轮播图
  231. $images = $this->getTianMaoImg($html);
  232. $images = array_merge(is_array($images) ? $images : []);
  233. $this->productInfo['slider_image'] = $images;
  234. $this->productInfo['slider_image'] = array_slice($this->productInfo['slider_image'], 0, 5);
  235. $this->productInfo['image'] = is_array($this->productInfo['slider_image']) && isset($this->productInfo['slider_image'][0]) ? $this->productInfo['slider_image'][0] : '';
  236. //获取产品详情请求链接
  237. $link = $this->getTianMaoDesc($html);
  238. //获取请求内容
  239. $desc_json = HttpService::getRequest($link);
  240. //转换字符集
  241. $desc_json = $this->Utf8String($desc_json);
  242. //截取掉多余字符
  243. $desc_json = str_replace('var desc=\'', '', $desc_json);
  244. $desc_json = str_replace(["\n", "\t", "\r"], '', $desc_json);
  245. $content = substr($desc_json, 0, -2);
  246. $this->productInfo['description'] = $content;
  247. //获取详情图
  248. $description_images = $this->decodedesc($this->productInfo['description']);
  249. $this->productInfo['description_images'] = is_array($description_images) ? $description_images : [];
  250. }
  251. /**
  252. * 1688设置产品
  253. * @param $html
  254. */
  255. public function setProductInfo1688($html)
  256. {
  257. $this->webnname = 'alibaba';
  258. //获取轮播图
  259. $images = $this->get1688Img($html);
  260. if (isset($images['gaoqing'])) {
  261. $images['gaoqing'] = array_merge($images['gaoqing']);
  262. $this->productInfo['slider_image'] = $images['gaoqing'];
  263. } else
  264. $this->productInfo['slider_image'] = $images;
  265. if (!is_array($this->productInfo['slider_image'])) {
  266. $this->productInfo['slider_image'] = [];
  267. }
  268. $this->productInfo['slider_image'] = array_slice($this->productInfo['slider_image'], 0, 5);
  269. $this->productInfo['image'] = is_array($this->productInfo['slider_image']) && isset($this->productInfo['slider_image'][0]) ? $this->productInfo['slider_image'][0] : '';
  270. //获取产品详情请求链接
  271. $link = $this->get1688Desc($html);
  272. //获取请求内容
  273. $desc_json = HttpService::getRequest($link);
  274. //转换字符集
  275. $desc_json = $this->Utf8String($desc_json);
  276. $this->productInfo['test'] = $desc_json;
  277. //截取掉多余字符
  278. $desc_json = str_replace('var offer_details=', '', $desc_json);
  279. $desc_json = str_replace(["\n", "\t", "\r"], '', $desc_json);
  280. $desc_json = substr($desc_json, 0, -1);
  281. $descArray = json_decode($desc_json, true);
  282. if (!isset($descArray['content'])) $descArray['content'] = '';
  283. $this->productInfo['description'] = $descArray['content'];
  284. //获取详情图
  285. $description_images = $this->decodedesc($this->productInfo['description']);
  286. $this->productInfo['description_images'] = is_array($description_images) ? $description_images : [];
  287. }
  288. /**
  289. * JD设置产品
  290. * @param string $html 网页内容
  291. * */
  292. public function setProductInfoJd($html)
  293. {
  294. $this->webnname = 'jd';
  295. //获取产品详情请求链接
  296. $desc_url = $this->getJdDesc($html);
  297. //获取请求内容
  298. $desc_json = HttpService::getRequest($desc_url);
  299. //转换字符集
  300. $desc_json = $this->Utf8String($desc_json);
  301. //截取掉多余字符
  302. if (substr($desc_json, 0, 8) == 'showdesc') $desc_json = str_replace('showdesc', '', $desc_json);
  303. $desc_json = str_replace('data-lazyload=', 'src=', $desc_json);
  304. $descArray = json_decode($desc_json, true);
  305. if (!$descArray) $descArray = ['content' => ''];
  306. //获取轮播图
  307. $images = $this->getJdImg($html);
  308. $images = array_merge(is_array($images) ? $images : []);
  309. $this->productInfo['slider_image'] = $images;
  310. $this->productInfo['image'] = is_array($this->productInfo['slider_image']) ? ($this->productInfo['slider_image'][0] ?? '') : '';
  311. $this->productInfo['description'] = $descArray['content'];
  312. //获取详情图
  313. $description_images = $this->decodedesc($descArray['content']);
  314. $this->productInfo['description_images'] = is_array($description_images) ? $description_images : [];
  315. }
  316. /**
  317. * 检查淘宝,天猫,1688的商品链接
  318. * @param $link
  319. * @return bool|string
  320. */
  321. public function checkurl($link)
  322. {
  323. $link = strtolower(htmlspecialchars_decode($link));
  324. if (!$link) return $this->setErrorInfo('请输入链接地址');
  325. if (substr($link, 0, 4) != 'http') return $this->setErrorInfo('链接地址必须以http开头');
  326. $arrLine = explode('?', $link);
  327. if (!count($arrLine)) return $this->setErrorInfo('链接地址有误(ERR:1001)');
  328. if (!isset($arrLine[1])) {
  329. if (strpos($link, '1688') !== false && strpos($link, 'offer') !== false) return trim($arrLine[0]);
  330. else if (strpos($link, 'item.jd') !== false) return trim($arrLine[0]);
  331. else return $this->setErrorInfo('链接地址有误(ERR:1002)');
  332. }
  333. if (strpos($link, '1688') !== false && strpos($link, 'offer') !== false) return trim($arrLine[0]);
  334. if (strpos($link, 'item.jd') !== false) return trim($arrLine[0]);
  335. $arrLineValue = explode('&', $arrLine[1]);
  336. if (!is_array($arrLineValue)) return $this->setErrorInfo('链接地址有误(ERR:1003)');
  337. if (!strpos(trim($arrLine[0]), 'item.htm')) $this->setErrorInfo('链接地址有误(ERR:1004)');
  338. //链接参数
  339. $lastStr = '';
  340. foreach ($arrLineValue as $k => $v) {
  341. if (substr(strtolower($v), 0, 3) == 'id=') {
  342. $lastStr = trim($v);
  343. break;
  344. }
  345. }
  346. if (!$lastStr) return $this->setErrorInfo('链接地址有误(ERR:1005)');
  347. return trim($arrLine[0]) . '?' . $lastStr;
  348. }
  349. /*
  350. * 保存图片保存产品信息
  351. * */
  352. public function save_product()
  353. {
  354. $data = UtilService::postMore([
  355. ['cate_id', ''],
  356. ['store_name', ''],
  357. ['store_info', ''],
  358. ['keyword', ''],
  359. ['unit_name', ''],
  360. ['image', ''],
  361. ['slider_image', []],
  362. ['price', ''],
  363. ['ot_price', ''],
  364. ['give_integral', ''],
  365. ['postage', ''],
  366. ['sales', ''],
  367. ['ficti', ''],
  368. ['stock', ''],
  369. ['cost', ''],
  370. ['description_images', []],
  371. ['description', ''],
  372. ['is_show', 0],
  373. ['soure_link', ''],
  374. ['temp_id', 0],
  375. ]);
  376. if (!$data['cate_id']) return JsonService::fail('请选择分类!');
  377. if (!$data['store_name']) return JsonService::fail('请填写产品名称');
  378. if (!$data['unit_name']) return JsonService::fail('请填写产品单位');
  379. if (!$data['image']) return JsonService::fail('商品主图暂无,无法保存商品,您可选择其他链接进行复制产品');
  380. if ($data['price'] == '' || $data['price'] < 0) return JsonService::fail('请输入产品售价');
  381. if ($data['ot_price'] == '' || $data['ot_price'] < 0) return JsonService::fail('请输入产品市场价');
  382. if ($data['stock'] == '' || $data['stock'] < 0) return JsonService::fail('请输入库存');
  383. if (!$data['temp_id']) return JsonService::fail('请选择运费模板');
  384. //查询附件分类
  385. $AttachmentCategory = SystemAttachmentCategory::where('name', $this->AttachmentCategoryName)->find();
  386. //不存在则创建
  387. if (!$AttachmentCategory) $AttachmentCategory = SystemAttachmentCategory::create(['pid' => '0', 'name' => $this->AttachmentCategoryName, 'enname' => '']);
  388. //生成附件目录
  389. try {
  390. if (make_path('attach', 3, true) === '')
  391. return JsonService::fail('无法创建文件夹,请检查您的上传目录权限:' . app()->getRootPath() . 'public' . DS . 'uploads' . DS . 'attach' . DS);
  392. } catch (\Exception $e) {
  393. return JsonService::fail($e->getMessage() . '或无法创建文件夹,请检查您的上传目录权限:' . app()->getRootPath() . 'public' . DS . 'uploads' . DS . 'attach' . DS);
  394. }
  395. ini_set("max_execution_time", 600);
  396. //开始图片下载处理
  397. ProductModel::beginTrans();
  398. try {
  399. //放入主图
  400. $images = [
  401. ['w' => 305, 'h' => 305, 'line' => $data['image'], 'valuename' => 'image']
  402. ];
  403. //放入轮播图
  404. foreach ($data['slider_image'] as $item) {
  405. $value = ['w' => 640, 'h' => 640, 'line' => $item, 'valuename' => 'slider_image', 'isTwoArray' => true];
  406. array_push($images, $value);
  407. }
  408. //执行下载
  409. $res = $this->uploadImage($images, false, 0, $AttachmentCategory['id']);
  410. if (!is_array($res)) return JsonService::fail($this->errorInfo ? $this->errorInfo : '保存图片失败');
  411. if (isset($res['image'])) $data['image'] = $res['image'];
  412. if (isset($res['slider_image'])) $data['slider_image'] = $res['slider_image'];
  413. $data['slider_image'] = count($data['slider_image']) ? json_encode($data['slider_image']) : '';
  414. //替换并下载详情里面的图片默认下载全部图片
  415. $data['description'] = preg_replace('#<style>.*?</style>#is', '', $data['description']);
  416. $data['description'] = $this->uploadImage($data['description_images'], $data['description'], 1, $AttachmentCategory['id']);
  417. unset($data['description_images']);
  418. $description = $data['description'];
  419. unset($data['description']);
  420. $data['add_time'] = time();
  421. $cate_id = explode(',', $data['cate_id']);
  422. //产品存在
  423. if ($productInfo = ProductModel::where('soure_link', $data['soure_link'])->find()) {
  424. $productInfo->slider_image = $data['slider_image'];
  425. $productInfo->image = $data['image'];
  426. $productInfo->store_name = $data['store_name'];
  427. StoreDescription::saveDescription($description, $productInfo->id);
  428. $productInfo->save();
  429. ProductModel::commitTrans();
  430. return JsonService::successful('商品存在,信息已被更新成功');
  431. } else {
  432. //不存在时新增
  433. if ($productId = ProductModel::insertGetId($data)) {
  434. $cateList = [];
  435. foreach ($cate_id as $cid) {
  436. $cateList [] = ['product_id' => $productId, 'cate_id' => $cid, 'add_time' => time()];
  437. }
  438. StoreProductCate::insertAll($cateList);
  439. $attr = [
  440. [
  441. 'value' => '规格',
  442. 'detailValue' => '',
  443. 'attrHidden' => '',
  444. 'detail' => ['默认']
  445. ]
  446. ];
  447. $detail[0]['value1'] = '规格';
  448. $detail[0]['detail'] = ['规格' => '默认'];
  449. $detail[0]['price'] = $data['price'];
  450. $detail[0]['stock'] = $data['stock'];
  451. $detail[0]['cost'] = $data['cost'];
  452. $detail[0]['pic'] = $data['image'];
  453. $detail[0]['ot_price'] = $data['price'];
  454. $attr_res = StoreProductAttr::createProductAttr($attr, $detail, $productId);
  455. if ($attr_res) {
  456. StoreDescription::saveDescription($description, $productId);
  457. ProductModel::commitTrans();
  458. return JsonService::successful('生成产品成功');
  459. } else {
  460. ProductModel::rollbackTrans();
  461. return JsonService::fail(StoreProductAttr::getErrorInfo('生成产品失败'));
  462. }
  463. } else {
  464. ProductModel::rollbackTrans();
  465. return JsonService::fail('生成产品失败');
  466. }
  467. }
  468. } catch (PDOException $e) {
  469. ProductModel::rollbackTrans();
  470. return JsonService::fail('插入数据库错误', ['line' => $e->getLine(), 'messag' => $e->getMessage()]);
  471. } catch (\Exception $e) {
  472. ProductModel::rollbackTrans();
  473. return JsonService::fail('系统错误', ['line' => $e->getLine(), 'messag' => $e->getMessage(), 'file' => $e->getFile()]);
  474. }
  475. }
  476. /*
  477. * 上传图片处理
  478. * @param array $image 图片路径
  479. * @param int $uploadType 上传方式 0=远程下载
  480. * */
  481. public function uploadImage(array $images = [], $html = '', $uploadType = 0, $AttachmentCategoryId = 0)
  482. {
  483. $uploadImage = [];
  484. $siteUrl = sys_config('site_url');
  485. switch ($uploadType) {
  486. case 0:
  487. foreach ($images as $item) {
  488. //下载图片文件
  489. if ($item['w'] && $item['h'])
  490. $uploadValue = $this->downloadImage($item['line'], '', 0, 30, $item['w'], $item['h']);
  491. else
  492. $uploadValue = $this->downloadImage($item['line']);
  493. //下载成功更新数据库
  494. if (is_array($uploadValue)) {
  495. //TODO 拼接图片地址
  496. if ($uploadValue['image_type'] == 1) $imagePath = $siteUrl . $uploadValue['path'];
  497. else $imagePath = $uploadValue['path'];
  498. //写入数据库
  499. if (!$uploadValue['is_exists'] && $AttachmentCategoryId) SystemAttachment::attachmentAdd($uploadValue['name'], $uploadValue['size'], $uploadValue['mime'], $imagePath, $imagePath, $AttachmentCategoryId, $uploadValue['image_type'], time(), 1);
  500. //组装数组
  501. if (isset($item['isTwoArray']) && $item['isTwoArray'])
  502. $uploadImage[$item['valuename']][] = $imagePath;
  503. else
  504. $uploadImage[$item['valuename']] = $imagePath;
  505. }
  506. }
  507. break;
  508. case 1:
  509. preg_match_all('#<img.*?src="([^"]*)"[^>]*>#i', $html, $match);
  510. if (isset($match[1])) {
  511. foreach ($match[1] as $item) {
  512. if (is_int(strpos($item, 'http')))
  513. $arcurl = $item;
  514. else
  515. $arcurl = 'http://' . ltrim($item, '\//');
  516. $uploadValue = $this->downloadImage($arcurl);
  517. //下载成功更新数据库
  518. if (is_array($uploadValue)) {
  519. //TODO 拼接图片地址
  520. if ($uploadValue['image_type'] == 1) $imagePath = $siteUrl . $uploadValue['path'];
  521. else $imagePath = $uploadValue['path'];
  522. //写入数据库
  523. if (!$uploadValue['is_exists'] && $AttachmentCategoryId) SystemAttachment::attachmentAdd($uploadValue['name'], $uploadValue['size'], $uploadValue['mime'], $imagePath, $imagePath, $AttachmentCategoryId, $uploadValue['image_type'], time(), 1);
  524. //替换图片
  525. $html = str_replace($item, $imagePath, $html);
  526. } else {
  527. //替换掉没有下载下来的图片
  528. $html = preg_replace('#<img.*?src="' . $item . '"*>#i', '', $html);
  529. }
  530. }
  531. }
  532. return $html;
  533. break;
  534. default:
  535. return $this->setErrorInfo('上传方式错误');
  536. break;
  537. }
  538. return $uploadImage;
  539. }
  540. //提取商品描述中的所有图片
  541. public function decodedesc($desc = '')
  542. {
  543. $desc = trim($desc);
  544. if (!$desc) return '';
  545. preg_match_all('/<img[^>]*?src="([^"]*?)"[^>]*?>/i', $desc, $match);
  546. if (!isset($match[1]) || count($match[1]) <= 0) {
  547. preg_match_all('/:url(([^"]*?));/i', $desc, $match);
  548. if (!isset($match[1]) || count($match[1]) <= 0) return $desc;
  549. } else {
  550. preg_match_all('/:url(([^"]*?));/i', $desc, $newmatch);
  551. if (isset($newmatch[1]) && count($newmatch[1]) > 0) $match[1] = array_merge($match[1], $newmatch[1]);
  552. }
  553. $match[1] = array_unique($match[1]); //去掉重复
  554. foreach ($match[1] as $k => &$v) {
  555. $_tmp_img = str_replace([')', '(', ';'], '', $v);
  556. $_tmp_img = strpos($_tmp_img, 'http') ? $_tmp_img : 'http:' . $_tmp_img;
  557. if (strpos($v, '?')) {
  558. $_tarr = explode('?', $v);
  559. $_tmp_img = trim($_tarr[0]);
  560. }
  561. $_urls = str_replace(['\'', '"'], '', $_tmp_img);
  562. if ($this->_img_exists($_urls)) $v = $_urls;
  563. }
  564. return $match[1];
  565. }
  566. //获取京东商品组图
  567. public function getJdImg($html = '')
  568. {
  569. //获取图片服务器网址
  570. preg_match('/<img(.*?)id="spec-img"(.*?)data-origin=\"(.*?)\"[^>]*>/', $html, $img);
  571. if (!isset($img[3])) return '';
  572. $info = parse_url(trim($img[3]));
  573. if (!$info['host']) return '';
  574. if (!$info['path']) return '';
  575. $_tmparr = explode('/', trim($info['path']));
  576. $url = 'http://' . $info['host'] . '/' . $_tmparr[1] . '/' . str_replace(['jfs', ' '], '', trim($_tmparr[2]));
  577. preg_match('/imageList:(.*?)"],/is', $html, $img);
  578. if (!isset($img[1])) {
  579. return '';
  580. }
  581. $_arr = explode(',', $img[1]);
  582. foreach ($_arr as $k => &$v) {
  583. $_str = $url . str_replace(['"', '[', ']', ' '], '', trim($v));
  584. if (strpos($_str, '?')) {
  585. $_tarr = explode('?', $_str);
  586. $_str = trim($_tarr[0]);
  587. }
  588. if ($this->_img_exists($_str)) {
  589. $v = $_str;
  590. } else {
  591. unset($_arr[$k]);
  592. }
  593. }
  594. return array_unique($_arr);
  595. }
  596. //获取京东商品描述
  597. public function getJdDesc($html = '')
  598. {
  599. preg_match('/,(.*?)desc:([^<>]*)\',/i', $html, $descarr);
  600. if (!isset($descarr[1]) && !isset($descarr[2])) return '';
  601. $tmpArr = explode(',', $descarr[2]);
  602. if (count($tmpArr) > 0) {
  603. $descarr[2] = trim($tmpArr[0]);
  604. }
  605. $replace_arr = ['\'', '\',', ' ', ',', '/*', '*/'];
  606. if (isset($descarr[2])) {
  607. $d_url = str_replace($replace_arr, '', $descarr[2]);
  608. return $this->formatDescUrl(strpos($d_url, 'http') ? $d_url : 'http:' . $d_url);
  609. }
  610. $d_url = str_replace($replace_arr, '', $descarr[1]);
  611. $d_url = $this->formatDescUrl($d_url);
  612. $d_url = rtrim(rtrim($d_url, "?"), "&");
  613. return substr($d_url, 0, 4) == 'http' ? $d_url : 'http:' . $d_url;
  614. }
  615. //处理下京东商品描述网址
  616. public function formatDescUrl($url = '')
  617. {
  618. if (!$url) return '';
  619. $url = substr($url, 0, 4) == 'http' ? $url : 'http:' . $url;
  620. if (!strpos($url, '&')) {
  621. $_arr = explode('?', $url);
  622. if (!is_array($_arr) || count($_arr) <= 0) return $url;
  623. return trim($_arr[0]);
  624. } else {
  625. $_arr = explode('&', $url);
  626. }
  627. if (!is_array($_arr) || count($_arr) <= 0) return $url;
  628. unset($_arr[count($_arr) - 1]);
  629. $new_url = '';
  630. foreach ($_arr as $k => $v) {
  631. $new_url .= $v . '&';
  632. }
  633. return !$new_url ? $url : $new_url;
  634. }
  635. //获取1688商品组图
  636. public function get1688Img($html = '')
  637. {
  638. preg_match('/<ul class=\"nav nav-tabs fd-clr\">(.*?)<\/ul>/is', $html, $img);
  639. if (!isset($img[0])) {
  640. return '';
  641. }
  642. preg_match_all('/preview":"(.*?)\"\}\'>/is', $img[0], $arrb);
  643. if (!isset($arrb[1]) || count($arrb[1]) <= 0) {
  644. return '';
  645. }
  646. $thumb = [];
  647. $gaoqing = [];
  648. $res = ['thumb' => '', 'gaoqing' => '']; //缩略图片和高清图片
  649. foreach ($arrb[1] as $k => $v) {
  650. $_str = str_replace(['","original":"'], '*', $v);
  651. $_arr = explode('*', $_str);
  652. if (is_array($_arr) && isset($_arr[0]) && isset($_arr[1])) {
  653. if (strpos($_arr[0], '?')) {
  654. $_tarr = explode('?', $_arr[0]);
  655. $_arr[0] = trim($_tarr[0]);
  656. }
  657. if (strpos($_arr[1], '?')) {
  658. $_tarr = explode('?', $_arr[1]);
  659. $_arr[1] = trim($_tarr[0]);
  660. }
  661. if ($this->_img_exists($_arr[0])) $thumb[] = trim($_arr[0]);
  662. if ($this->_img_exists($_arr[1])) $gaoqing[] = trim($_arr[1]);
  663. }
  664. }
  665. $res = ['thumb' => array_unique($thumb), 'gaoqing' => array_unique($gaoqing)]; //缩略图片和高清图片
  666. return $res;
  667. }
  668. //获取1688商品描述
  669. public function get1688Desc($html = '')
  670. {
  671. preg_match('/data-tfs-url="([^<>]*)data-enable="true"/', $html, $descarr);
  672. if (!isset($descarr[1])) return '';
  673. return str_replace(['"', ' '], '', $descarr[1]);
  674. }
  675. //获取天猫商品组图
  676. public function getTianMaoImg($html = '')
  677. {
  678. $pic_size = '430';
  679. preg_match('/<img[^>]*id="J_ImgBooth"[^r]*rc=\"([^"]*)\"[^>]*>/', $html, $img);
  680. if (isset($img[1])) {
  681. $_arr = explode('x', $img[1]);
  682. $filename = $_arr[count($_arr) - 1];
  683. $pic_size = intval(substr($filename, 0, 3));
  684. }
  685. preg_match('|<ul id="J_UlThumb" class="tb-thumb tm-clear">(.*)</ul>|isU', $html, $match);
  686. preg_match_all('/<img src="(.*?)" \//', $match[1], $images);
  687. if (!isset($images[1])) return '';
  688. foreach ($images[1] as $k => &$v) {
  689. $tmp_v = trim($v);
  690. $_arr = explode('x', $tmp_v);
  691. $_fname = $_arr[count($_arr) - 1];
  692. $_size = intval(substr($_fname, 0, 3));
  693. if (strpos($tmp_v, '://')) {
  694. $_arr = explode(':', $tmp_v);
  695. $r_url = trim($_arr[1]);
  696. } else {
  697. $r_url = $tmp_v;
  698. }
  699. $str = str_replace($_size, $pic_size, $r_url);
  700. if (strpos($str, '?')) {
  701. $_tarr = explode('?', $str);
  702. $str = trim($_tarr[0]);
  703. }
  704. $_i_url = strpos($str, 'http') ? $str : 'http:' . $str;
  705. if ($this->_img_exists($_i_url)) {
  706. $v = $_i_url;
  707. } else {
  708. unset($images[1][$k]);
  709. }
  710. }
  711. return array_unique($images[1]);
  712. }
  713. //获取天猫商品描述
  714. public function getTianMaoDesc($html = '')
  715. {
  716. preg_match('/descUrl":"([^<>]*)","httpsDescUrl":"/', $html, $descarr);
  717. if (!isset($descarr[1])) {
  718. preg_match('/httpsDescUrl":"([^<>]*)","fetchDcUrl/', $html, $descarr);
  719. if (!isset($descarr[1])) return '';
  720. }
  721. return strpos($descarr[1], 'http') ? $descarr[1] : 'http:' . $descarr[1];
  722. }
  723. //获取淘宝商品组图
  724. public function getTaobaoImg($html = '')
  725. {
  726. preg_match('/auctionImages([^<>]*)"]/', $html, $imgarr);
  727. if (!isset($imgarr[1])) return '';
  728. $arr = explode(',', $imgarr[1]);
  729. foreach ($arr as $k => &$v) {
  730. $str = trim($v);
  731. $str = str_replace(['"', ' ', '', ':['], '', $str);
  732. if (strpos($str, '?')) {
  733. $_tarr = explode('?', $str);
  734. $str = trim($_tarr[0]);
  735. }
  736. $_i_url = strpos($str, 'http') ? $str : 'http:' . $str;
  737. if ($this->_img_exists($_i_url)) {
  738. $v = $_i_url;
  739. } else {
  740. unset($arr[$k]);
  741. }
  742. }
  743. return array_unique($arr);
  744. }
  745. //获取淘宝商品描述
  746. public function getTaobaoDesc($html = '')
  747. {
  748. preg_match('/descUrl([^<>]*)counterApi/', $html, $descarr);
  749. if (!isset($descarr[1])) return '';
  750. $arr = explode(':', $descarr[1]);
  751. $url = [];
  752. foreach ($arr as $k => $v) {
  753. if (strpos($v, '//')) {
  754. $str = str_replace(['\'', ',', ' ', '?', ':'], '', $v);
  755. $url[] = trim($str);
  756. }
  757. }
  758. if ($url) {
  759. return strpos($url[0], 'http') ? $url[0] : 'http:' . $url[0];
  760. } else {
  761. return '';
  762. }
  763. }
  764. /**
  765. * GET 请求
  766. * @param string $url
  767. */
  768. public function curl_Get($url = '', $time_out = 25)
  769. {
  770. if (!$url) return '';
  771. $ch = curl_init();
  772. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
  773. if (stripos($url, "https://") !== FALSE) {
  774. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); // 从证书中检查SSL加密算法是否存在
  775. }
  776. $headers = ['user-agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36'];
  777. if ($this->webnname) {
  778. $headers[] = $this->webcookie["$this->webnname"];
  779. }
  780. curl_setopt($ch, CURLOPT_URL, $url);
  781. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  782. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  783. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  784. curl_setopt($ch, CURLOPT_TIMEOUT, $time_out);
  785. $response = curl_exec($ch);
  786. if ($error = curl_error($ch)) {
  787. return false;
  788. }
  789. curl_close($ch);
  790. // return mb_convert_encoding($response, 'utf-8', 'auto');
  791. return $response;
  792. }
  793. //检测远程文件是否存在
  794. public function _img_exists($url = '')
  795. {
  796. ini_set("max_execution_time", 0);
  797. $str = @file_get_contents($url, 0, null, 0, 1);
  798. if (strlen($str) <= 0) return false;
  799. if ($str)
  800. return true;
  801. else
  802. return false;
  803. }
  804. //TODO 下载图片
  805. public function downloadImage($url = '', $name = '', $type = 0, $timeout = 30, $w = 0, $h = 0)
  806. {
  807. if (!strlen(trim($url))) return '';
  808. if (!strlen(trim($name))) {
  809. //TODO 获取要下载的文件名称
  810. $downloadImageInfo = $this->getImageExtname($url);
  811. if (!$this->checkExtname($url, $downloadImageInfo['ext_name'])) {
  812. return JsonService::fail('文件后缀不合法');
  813. }
  814. $name = $downloadImageInfo['file_name'];
  815. if (!strlen(trim($name))) return '';
  816. }
  817. //TODO 获取远程文件所采用的方法
  818. if ($type) {
  819. $ch = curl_init();
  820. curl_setopt($ch, CURLOPT_URL, $url);
  821. curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
  822. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
  823. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //TODO 跳过证书检查
  824. if (stripos($url, "https://") !== FALSE) curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); //TODO 从证书中检查SSL加密算法是否存在
  825. curl_setopt($ch, CURLOPT_HTTPHEADER, array('user-agent:' . $_SERVER['HTTP_USER_AGENT']));
  826. if (ini_get('open_basedir') == '' && ini_get('safe_mode' == 'Off')) curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);//TODO 是否采集301、302之后的页面
  827. $content = curl_exec($ch);
  828. curl_close($ch);
  829. } else {
  830. try {
  831. ob_start();
  832. readfile($url);
  833. $content = ob_get_contents();
  834. ob_end_clean();
  835. } catch (\Exception $e) {
  836. return $e->getMessage();
  837. }
  838. }
  839. $size = strlen(trim($content));
  840. if (!$content || $size <= 2) return '图片流获取失败';
  841. $date_dir = date('Y') . DS . date('m') . DS . date('d');
  842. $upload_type = sys_config('upload_type', 1);
  843. $upload = new Upload((int)$upload_type, [
  844. 'accessKey' => sys_config('accessKey'),
  845. 'secretKey' => sys_config('secretKey'),
  846. 'uploadUrl' => sys_config('uploadUrl'),
  847. 'storageName' => sys_config('storage_name'),
  848. 'storageRegion' => sys_config('storage_region'),
  849. ]);
  850. $info = $upload->to('attach/' . $date_dir)->validate()->stream($content, $name);
  851. if ($info === false) {
  852. return $upload->getError();
  853. }
  854. $imageInfo = $upload->getUploadInfo();
  855. $date['path'] = str_replace('\\', '/', $imageInfo['dir']);
  856. $date['name'] = $imageInfo['name'];
  857. $date['size'] = $imageInfo['size'];
  858. $date['mime'] = $imageInfo['type'];
  859. $date['image_type'] = $upload_type;
  860. $date['is_exists'] = false;
  861. return $date;
  862. }
  863. //获取即将要下载的图片扩展名
  864. public function getImageExtname($url = '', $ex = 'jpg')
  865. {
  866. $_empty = ['file_name' => '', 'ext_name' => $ex];
  867. if (!$url) return $_empty;
  868. if (strpos($url, '?')) {
  869. $_tarr = explode('?', $url);
  870. $url = trim($_tarr[0]);
  871. }
  872. $arr = explode('.', $url);
  873. if (!is_array($arr) || count($arr) <= 1) return $_empty;
  874. $ext_name = trim($arr[count($arr) - 1]);
  875. $ext_name = !$ext_name ? $ex : $ext_name;
  876. return ['file_name' => md5($url) . '.' . $ext_name, 'ext_name' => $ext_name];
  877. }
  878. /**
  879. * 验证下载图片文件后缀
  880. * @param string $url
  881. * @param string $ex
  882. * @return bool
  883. */
  884. public function checkExtname($url = '', $ex = 'jpg')
  885. {
  886. if (in_array($ex, ['jpg', 'jpeg', 'gif', 'png', 'swf', 'bmp', 'pcx', 'tif', 'tga', 'exif'])) {
  887. return true;
  888. }
  889. return false;
  890. }
  891. /*
  892. $filepath = 绝对路径,末尾有斜杠 /
  893. $name = 图片文件名
  894. $maxwidth 定义生成图片的最大宽度(单位:像素)
  895. $maxheight 生成图片的最大高度(单位:像素)
  896. $filetype 最终生成的图片类型(.jpg/.png/.gif)
  897. */
  898. public function resizeImage($filepath = '', $name = '', $maxwidth = 0, $maxheight = 0)
  899. {
  900. $pic_file = $filepath . $name; //图片文件
  901. $img_info = getimagesize($pic_file); //索引 2 是图像类型的标记:1 = GIF,2 = JPG,3 = PNG,4 = SWF,5 = PSD,
  902. if ($img_info[2] == 1) {
  903. $im = imagecreatefromgif($pic_file); //打开图片
  904. $filetype = '.gif';
  905. } elseif ($img_info[2] == 2) {
  906. $im = imagecreatefromjpeg($pic_file); //打开图片
  907. $filetype = '.jpg';
  908. } elseif ($img_info[2] == 3) {
  909. $im = imagecreatefrompng($pic_file); //打开图片
  910. $filetype = '.png';
  911. } else {
  912. return ['path' => $filepath, 'file' => $name, 'mime' => ''];
  913. }
  914. $file_name = md5('_tmp_' . microtime() . '_' . rand(0, 10)) . $filetype;
  915. $pic_width = imagesx($im);
  916. $pic_height = imagesy($im);
  917. $resizewidth_tag = false;
  918. $resizeheight_tag = false;
  919. if (($maxwidth && $pic_width > $maxwidth) || ($maxheight && $pic_height > $maxheight)) {
  920. if ($maxwidth && $pic_width > $maxwidth) {
  921. $widthratio = $maxwidth / $pic_width;
  922. $resizewidth_tag = true;
  923. }
  924. if ($maxheight && $pic_height > $maxheight) {
  925. $heightratio = $maxheight / $pic_height;
  926. $resizeheight_tag = true;
  927. }
  928. if ($resizewidth_tag && $resizeheight_tag) {
  929. if ($widthratio < $heightratio)
  930. $ratio = $widthratio;
  931. else
  932. $ratio = $heightratio;
  933. }
  934. if ($resizewidth_tag && !$resizeheight_tag)
  935. $ratio = $widthratio;
  936. if ($resizeheight_tag && !$resizewidth_tag)
  937. $ratio = $heightratio;
  938. $newwidth = $pic_width * $ratio;
  939. $newheight = $pic_height * $ratio;
  940. if (function_exists("imagecopyresampled")) {
  941. $newim = imagecreatetruecolor($newwidth, $newheight);
  942. imagecopyresampled($newim, $im, 0, 0, 0, 0, $newwidth, $newheight, $pic_width, $pic_height);
  943. } else {
  944. $newim = imagecreate($newwidth, $newheight);
  945. imagecopyresized($newim, $im, 0, 0, 0, 0, $newwidth, $newheight, $pic_width, $pic_height);
  946. }
  947. if ($filetype == '.png') {
  948. imagepng($newim, $filepath . $file_name);
  949. } else if ($filetype == '.gif') {
  950. imagegif($newim, $filepath . $file_name);
  951. } else {
  952. imagejpeg($newim, $filepath . $file_name);
  953. }
  954. imagedestroy($newim);
  955. } else {
  956. if ($filetype == '.png') {
  957. imagepng($im, $filepath . $file_name);
  958. } else if ($filetype == '.gif') {
  959. imagegif($im, $filepath . $file_name);
  960. } else {
  961. imagejpeg($im, $filepath . $file_name);
  962. }
  963. imagedestroy($im);
  964. }
  965. @unlink($pic_file);
  966. return ['path' => $filepath, 'file' => $file_name, 'mime' => $img_info['mime']];
  967. }
  968. }