diff --git a/crmeb/app/admin/controller/order/StoreOrder.php b/crmeb/app/admin/controller/order/StoreOrder.php index 32d5d934..16298c4b 100644 --- a/crmeb/app/admin/controller/order/StoreOrder.php +++ b/crmeb/app/admin/controller/order/StoreOrder.php @@ -15,8 +15,6 @@ use crmeb\services\MiniProgramService; use crmeb\services\UtilService; use crmeb\services\WechatService; use crmeb\services\FormBuilder as Form; -use crmeb\services\HookService; -use crmeb\subscribes\OrderSubscribe; use app\admin\model\order\StoreOrderStatus; use app\admin\model\ump\StorePink; use app\admin\model\user\User; diff --git a/crmeb/app/admin/model/wechat/WechatReply.php b/crmeb/app/admin/model/wechat/WechatReply.php index 6d8217ff..79b02387 100644 --- a/crmeb/app/admin/model/wechat/WechatReply.php +++ b/crmeb/app/admin/model/wechat/WechatReply.php @@ -9,7 +9,6 @@ namespace app\admin\model\wechat; use app\admin\model\system\SystemConfig; use crmeb\traits\ModelTrait; use crmeb\basic\BaseModel; -use crmeb\services\HookService; use crmeb\services\UtilService; use crmeb\services\WechatService; use think\facade\Route as Url; diff --git a/crmeb/crmeb/repositories/NoticeRepositories.php b/crmeb/crmeb/repositories/NoticeRepositories.php index 9644e258..8fc1fdca 100644 --- a/crmeb/crmeb/repositories/NoticeRepositories.php +++ b/crmeb/crmeb/repositories/NoticeRepositories.php @@ -4,6 +4,7 @@ * User: xurongyao <763569752@qq.com> * Date: 2019/11/13 4:52 PM */ + namespace crmeb\repositories; use app\models\user\WechatUser; @@ -26,59 +27,60 @@ class NoticeRepositories * @param $order * @param $formId */ - public static function noticeOrderPaySuccess($order,$formId) + public static function noticeOrderPaySuccess($order, $formId) { - $wechatUser = WechatUser::where('uid',$order['uid'])->field('openid','routine_openid')->find(); - if($wechatUser){ + $wechatUser = WechatUser::where('uid', $order['uid'])->field('openid', 'routine_openid')->find(); + if ($wechatUser) { $openid = $wechatUser['openid']; $routineOpenid = $wechatUser['routine_openid']; - try{ - if($openid){//公众号发送模板消息 - WechatTemplateService::sendTemplate($openid,WechatTemplateService::ORDER_PAY_SUCCESS, [ - 'first'=>'亲,您购买的商品已支付成功', - 'keyword1'=>$order['order_id'], - 'keyword2'=>$order['pay_price'], - 'remark'=>'点击查看订单详情' - ],Route::buildUrl('order/detail/'.$order['order_id'])->suffix('')->domain(true)->build()); + try { + if ($openid) {//公众号发送模板消息 + WechatTemplateService::sendTemplate($openid, WechatTemplateService::ORDER_PAY_SUCCESS, [ + 'first' => '亲,您购买的商品已支付成功', + 'keyword1' => $order['order_id'], + 'keyword2' => $order['pay_price'], + 'remark' => '点击查看订单详情' + ], Route::buildUrl('order/detail/' . $order['order_id'])->suffix('')->domain(true)->build()); //订单支付成功后给客服发送模版消息 WechatTemplateService::sendAdminNoticeTemplate([ - 'first'=>"亲,您有一个新订单 \n订单号:{$order['order_id']}", - 'keyword1'=>'新订单', - 'keyword2'=>'已支付', - 'keyword3'=>date('Y/m/d H:i',time()), - 'remark'=>'请及时处理' + 'first' => "亲,您有一个新订单 \n订单号:{$order['order_id']}", + 'keyword1' => '新订单', + 'keyword2' => '已支付', + 'keyword3' => date('Y/m/d H:i', time()), + 'remark' => '请及时处理' ]); //订单支付成功后给客服发送客服消息 CustomerRepository::sendOrderPaySuccessCustomerService($order, 1); - }else if($routineOpenid){//小程序发送模板消息 + } else if ($routineOpenid) {//小程序发送模板消息 RoutineTemplate::sendOrderSuccess($formId, $order['order_id']); //订单支付成功后给客服发送客服消息 CustomerRepository::sendOrderPaySuccessCustomerService($order, 0); } - }catch (\Exception $e){} + } catch (\Exception $e) { + } } //打印小票 - $switch = sysConfig('pay_success_printing_switch') ? true : false ; - if($switch){ - try{ - $order['cart_id'] = is_string($order['cart_id']) ? json_decode($order['cart_id'],true) : $order['cart_id']; - $cartInfo = StoreOrderCartInfo::whereIn('cart_id',$order['cart_id'])->field('cart_info')->select(); + $switch = sysConfig('pay_success_printing_switch') ? true : false; + if ($switch) { + try { + $order['cart_id'] = is_string($order['cart_id']) ? json_decode($order['cart_id'], true) : $order['cart_id']; + $cartInfo = StoreOrderCartInfo::whereIn('cart_id', $order['cart_id'])->field('cart_info')->select(); $cartInfo = count($cartInfo) ? $cartInfo->toArray() : []; - $product = []; - foreach ($cartInfo as $item){ + $product = []; + foreach ($cartInfo as $item) { $value = is_string($item['cart_info']) ? json_decode($item['cart_info']) : $item['cart_info']; $value['productInfo']['store_name'] = $value['productInfo']['store_name'] ?? ""; - $value['productInfo']['store_name'] = StoreOrderCartInfo::getSubstrUTf8($value['productInfo']['store_name'],10,'UTF-8',''); + $value['productInfo']['store_name'] = StoreOrderCartInfo::getSubstrUTf8($value['productInfo']['store_name'], 10, 'UTF-8', ''); $product[] = $value; } - YLYService::getInstance()->setContent(sysConfig('site_name'),is_object($order) ? $order->toArray() : $order,$product)->orderPrinting(); - }catch (\Exception $e){ - Log::error('小票打印出现错误,错误原因:'.$e->getMessage()); + YLYService::instance()->setContent(sysConfig('site_name'), is_object($order) ? $order->toArray() : $order, $product)->orderPrinting(); + } catch (\Exception $e) { + Log::error('小票打印出现错误,错误原因:' . $e->getMessage()); } } //短信通知 下发用户支付成功 下发管理员支付通知 - event('ShortMssageSend',[$order['order_id'],['PaySuccess','AdminPaySuccess']]); + event('ShortMssageSend', [$order['order_id'], ['PaySuccess', 'AdminPaySuccess']]); } } \ No newline at end of file diff --git a/crmeb/crmeb/services/ApiErrorCode.php b/crmeb/crmeb/services/ApiErrorCode.php index cebb94d4..8367e64b 100644 --- a/crmeb/crmeb/services/ApiErrorCode.php +++ b/crmeb/crmeb/services/ApiErrorCode.php @@ -8,7 +8,6 @@ namespace crmeb\services; - /** * 错误码统一存放类 * Class ApiErrorCode @@ -17,10 +16,10 @@ namespace crmeb\services; class ApiErrorCode { - const SUCCESS = [200,'SUCCESS']; - const ERROR = [400,'操作失败']; + const SUCCESS = [200, 'SUCCESS']; + const ERROR = [400, '操作失败']; - const ERR_LOGIN = [40010,'登陆过期']; + const ERR_LOGIN = [40010, '登陆过期']; } \ No newline at end of file diff --git a/crmeb/crmeb/services/CacheService.php b/crmeb/crmeb/services/CacheService.php index a5094193..a42e411a 100644 --- a/crmeb/crmeb/services/CacheService.php +++ b/crmeb/crmeb/services/CacheService.php @@ -29,13 +29,13 @@ class CacheService * @param int $expire 缓存时间,为0读取系统缓存时间 * @return bool */ - public static function set(string $name, $value, int $expire = 0):bool + public static function set(string $name, $value, int $expire = 0): bool { //这里不要去读取缓存配置,会导致死循环 - $expire = $expire ? : SystemConfigService::get('cache_config',null,true); - if(!is_int($expire)) + $expire = $expire ?: SystemConfigService::get('cache_config', null, true); + if (!is_int($expire)) $expire = (int)$expire; - return self::handler()->set($name,$value,$expire); + return self::handler()->set($name, $value, $expire); } /** @@ -44,9 +44,9 @@ class CacheService * @param bool $default * @return mixed */ - public static function get(string $name,$default = false) + public static function get(string $name, $default = false) { - return self::handler()->remember($name,$default); + return self::handler()->remember($name, $default); } /** @@ -56,7 +56,7 @@ class CacheService */ public static function rm(string $name) { - return self::handler()->remember($name,''); + return self::handler()->remember($name, ''); } /** diff --git a/crmeb/crmeb/services/CustomerService.php b/crmeb/crmeb/services/CustomerService.php index 089f83e7..d08cfa8e 100644 --- a/crmeb/crmeb/services/CustomerService.php +++ b/crmeb/crmeb/services/CustomerService.php @@ -1,4 +1,5 @@ &$item){ + if (count($serviceOrderNotice)) { + foreach ($serviceOrderNotice as $key => &$item) { $userInfo = WechatUser::get($item); - if($userInfo){ + if ($userInfo) { $userInfo = $userInfo->toArray(); - if($userInfo['subscribe'] && $userInfo['openid']){ + if ($userInfo['subscribe'] && $userInfo['openid']) { $orderStatus = StoreService::orderServiceStatus($userInfo['uid']); - if($orderStatus){ + if ($orderStatus) { // 统计管理开启 推送图文消息 - $head = '订单提醒 订单号:'.$order['order_id']; - $url = SystemConfigService::get('site_url') . '/customer/orderdetail/'.$order['order_id']; + $head = '订单提醒 订单号:' . $order['order_id']; + $url = SystemConfigService::get('site_url') . '/customer/orderdetail/' . $order['order_id']; $description = ''; $image = SystemConfigService::get('site_logo'); - if(isset($order['seckill_id']) && $order['seckill_id'] > 0){ - $description .= '秒杀产品:'.StoreSeckill::getProductField($order['seckill_id'], 'title'); + if (isset($order['seckill_id']) && $order['seckill_id'] > 0) { + $description .= '秒杀产品:' . StoreSeckill::getProductField($order['seckill_id'], 'title'); $image = StoreSeckill::getProductField($order['seckill_id'], 'image'); - }else if(isset($order['combination_id']) && $order['combination_id'] > 0){ - $description .= '拼团产品:'.StoreCombination::getCombinationField($order['combination_id'], 'title'); + } else if (isset($order['combination_id']) && $order['combination_id'] > 0) { + $description .= '拼团产品:' . StoreCombination::getCombinationField($order['combination_id'], 'title'); $image = StoreCombination::getCombinationField($order['combination_id'], 'image'); - }else if(isset($order['bargain_id']) && $order['bargain_id'] > 0){ - $description .= '砍价产品:'.StoreBargain::getBargainField($order['bargain_id'], 'title'); + } else if (isset($order['bargain_id']) && $order['bargain_id'] > 0) { + $description .= '砍价产品:' . StoreBargain::getBargainField($order['bargain_id'], 'title'); $image = StoreBargain::getBargainField($order['bargain_id'], 'image'); - }else{ + } else { $productIds = StoreCart::getCartIdsProduct((array)$order['cart_id']); $storeProduct = StoreProduct::getProductStoreNameOrImage($productIds); - if(count($storeProduct)){ - foreach ($storeProduct as $value){ - $description .= $value['store_name'].' '; + if (count($storeProduct)) { + foreach ($storeProduct as $value) { + $description .= $value['store_name'] . ' '; $image = $value['image']; } } @@ -65,16 +66,16 @@ class CustomerService } catch (\Exception $e) { Log::error($userInfo['nickname'] . '发送失败' . $e->getMessage()); } - }else{ + } else { // 推送文字消息 $head = "客服提醒:亲,您有一个新订单 \r\n订单单号:{$order['order_id']}\r\n支付金额:¥{$order['pay_price']}\r\n备注信息:{$order['mark']}\r\n订单来源:小程序"; - if($type) $head = "客服提醒:亲,您有一个新订单 \r\n订单单号:{$order['order_id']}\r\n支付金额:¥{$order['pay_price']}\r\n备注信息:{$order['mark']}\r\n订单来源:公众号"; + if ($type) $head = "客服提醒:亲,您有一个新订单 \r\n订单单号:{$order['order_id']}\r\n支付金额:¥{$order['pay_price']}\r\n备注信息:{$order['mark']}\r\n订单来源:公众号"; try { WechatService::staffService()->message($head)->to($userInfo['openid'])->send(); } catch (\Exception $e) { Log::error($userInfo['nickname'] . '发送失败' . $e->getMessage()); } - } + } } } diff --git a/crmeb/crmeb/services/ExportService.php b/crmeb/crmeb/services/ExportService.php index 56143472..53dad136 100644 --- a/crmeb/crmeb/services/ExportService.php +++ b/crmeb/crmeb/services/ExportService.php @@ -10,46 +10,47 @@ namespace crmeb\services; class ExportService { - public static function exportCsv($list,$filename,$header = [],$br = '_'){ - $tableStr = count($header) > 0 ? '"'.implode('","',$header).'"'.PHP_EOL : ''; - $tableStr .= self::tidyCsvStr($list,str_repeat($br,99)); + public static function exportCsv($list, $filename, $header = [], $br = '_') + { + $tableStr = count($header) > 0 ? '"' . implode('","', $header) . '"' . PHP_EOL : ''; + $tableStr .= self::tidyCsvStr($list, str_repeat($br, 99)); ob_end_clean(); ob_start(); header("Content-type:application/vnd.ms-excel"); - header("Content-Disposition:filename=".$filename.".csv"); + header("Content-Disposition:filename=" . $filename . ".csv"); header('Content-Type:application/download'); - exit(iconv('UTF-8',"GB2312//IGNORE",$tableStr)); + exit(iconv('UTF-8', "GB2312//IGNORE", $tableStr)); } - private static function tidyCsvStr($list,$br = '') + private static function tidyCsvStr($list, $br = '') { $tableStr = ''; - foreach ($list as $row){ - if(is_array($row)){ + foreach ($list as $row) { + if (is_array($row)) { $max = 1; - foreach ($row as $k=>$item){ - if(is_array($item)){ - if($max < ($l = count($item))) $max = $l; + foreach ($row as $k => $item) { + if (is_array($item)) { + if ($max < ($l = count($item))) $max = $l; } else $row[$k] = [$item]; } - for($i = 0; $i<=$max; $i++){ + for ($i = 0; $i <= $max; $i++) { $exportRow = []; - if($max == $i){ - if($br == '') + if ($max == $i) { + if ($br == '') continue; else - $exportRow = array_fill(0,count($row),$br); - }else{ - foreach ($row as $item){ + $exportRow = array_fill(0, count($row), $br); + } else { + foreach ($row as $item) { $exportRow[] = isset($item[$i]) && !empty($item[$i]) ? $item[$i] : ' '; } } - $tableStr .= '"'.implode('","',$exportRow).'"," "'.PHP_EOL; + $tableStr .= '"' . implode('","', $exportRow) . '"," "' . PHP_EOL; } - $tableStr = rtrim($tableStr,PHP_EOL); - }else{ - $tableStr .= implode('',['"',$row,'"',',']); + $tableStr = rtrim($tableStr, PHP_EOL); + } else { + $tableStr .= implode('', ['"', $row, '"', ',']); } $tableStr .= PHP_EOL; } diff --git a/crmeb/crmeb/services/FileService.php b/crmeb/crmeb/services/FileService.php index dd20cdb0..c86a56a0 100644 --- a/crmeb/crmeb/services/FileService.php +++ b/crmeb/crmeb/services/FileService.php @@ -506,6 +506,8 @@ class FileService { $handle = @opendir($dir);//打开指定目录 $directory_count = 0; + $total_size = 0; + $file_cout = 0; while (FALSE !== ($file_path = readdir($handle))) { if($file_path != "." && $file_path != "..") diff --git a/crmeb/crmeb/services/FormBuilder.php b/crmeb/crmeb/services/FormBuilder.php index 62ca026d..33d5a68e 100644 --- a/crmeb/crmeb/services/FormBuilder.php +++ b/crmeb/crmeb/services/FormBuilder.php @@ -27,13 +27,14 @@ class FormBuilder extends Form * str 自定义 * @return $this */ - public static function make_post_form($title,array $field,$url,$jscallback = 2){ + public static function make_post_form($title, array $field, $url, $jscallback = 2) + { $form = Form::create($url);//提交地址 $form->setMethod('POST');//提交方式 $form->components($field);//表单字段 $form->setTitle($title);//表单标题 $js = '';//提交成功不执行任何动作 - switch ($jscallback){ + switch ($jscallback) { case 1: $js = 'parent.$(".J_iframe:visible")[0].contentWindow.location.reload();';//提交成功父级页面刷新 break; diff --git a/crmeb/crmeb/services/GroupDataService.php b/crmeb/crmeb/services/GroupDataService.php index 47c7e017..65d58d97 100644 --- a/crmeb/crmeb/services/GroupDataService.php +++ b/crmeb/crmeb/services/GroupDataService.php @@ -21,12 +21,12 @@ class GroupDataService * @param bool $isCaChe 是否读取缓存 * @return array */ - public static function getGroupData(string $config_name, $limit = 0,bool $isCaChe = false):array + public static function getGroupData(string $config_name, $limit = 0, bool $isCaChe = false): array { - try{ + try { $cacheName = $limit ? "group_data_{$config_name}_{$limit}" : "data_{$config_name}"; - $callable = function () use ($config_name,$limit) { + $callable = function () use ($config_name, $limit) { $data = SystemGroupData::getGroupData($config_name, $limit); if (is_object($data)) $data = $data->toArray(); @@ -36,9 +36,9 @@ class GroupDataService if ($isCaChe) return $callable(); - return CacheService::get($cacheName,$callable); + return CacheService::get($cacheName, $callable); - }catch (\Throwable $e){ + } catch (\Throwable $e) { return []; } } @@ -50,24 +50,24 @@ class GroupDataService * @param bool $isCaChe 是否读取缓存 * @return array */ - public static function getData(string $config_name,int $limit = 0,bool $isCaChe = false):array + public static function getData(string $config_name, int $limit = 0, bool $isCaChe = false): array { - try{ + try { $cacheName = $limit ? "data_{$config_name}_{$limit}" : "data_{$config_name}"; - $callable = function () use ($config_name,$limit) { + $callable = function () use ($config_name, $limit) { $data = SystemGroupData::getAllValue($config_name, $limit); - if(is_object($data)) + if (is_object($data)) $data = $data->toArray(); return $data; }; - if($isCaChe) + if ($isCaChe) return $callable(); - return CacheService::get($cacheName,$callable); + return CacheService::get($cacheName, $callable); - }catch (\Throwable $e){ + } catch (\Throwable $e) { return []; } } @@ -78,24 +78,24 @@ class GroupDataService * @param bool $isCaChe 是否读取缓存 * @return array */ - public static function getDataNumber(int $id,bool $isCaChe = false):array + public static function getDataNumber(int $id, bool $isCaChe = false): array { - try{ + try { $cacheName = "data_number_{$id}"; - $callable = function () use ($id) { + $callable = function () use ($id) { $data = SystemGroupData::getDateValue($id); if (is_object($data)) $data = $data->toArray(); return $data; }; - if($isCaChe) + if ($isCaChe) return $callable(); - return CacheService::get($cacheName,$callable); + return CacheService::get($cacheName, $callable); - }catch (\Throwable $e){ + } catch (\Throwable $e) { return []; } } diff --git a/crmeb/crmeb/services/HttpService.php b/crmeb/crmeb/services/HttpService.php index 82b7af5f..804e709c 100644 --- a/crmeb/crmeb/services/HttpService.php +++ b/crmeb/crmeb/services/HttpService.php @@ -4,6 +4,7 @@ * @author: xaboy<365615158@qq.com> * @day: 2017/11/23 */ + namespace crmeb\services; class HttpService diff --git a/crmeb/crmeb/services/JsonService.php b/crmeb/crmeb/services/JsonService.php index 47c16382..ce8bfbc2 100644 --- a/crmeb/crmeb/services/JsonService.php +++ b/crmeb/crmeb/services/JsonService.php @@ -13,57 +13,59 @@ class JsonService private static $FAIL_DEFAULT_MSG = 'no'; - public static function result($code,$msg='',$data=[],$count=0) + public static function result($code, $msg = '', $data = [], $count = 0) { - exit(json_encode(compact('code','msg','data','count'))); - } - public static function successlayui($count=0,$data=[],$msg='') - { - if(is_array($count)){ - if(isset($count['data'])) $data=$count['data']; - if(isset($count['count'])) $count=$count['count']; - } - if(false == is_string($msg)){ - $data = $msg; - $msg = self::$SUCCESSFUL_DEFAULT_MSG; - } - return self::result(0,$msg,$data,$count); - } - public static function successful($msg = 'ok',$data=[],$status=200) - { - if(false == is_string($msg)){ - $data = $msg; - $msg = self::$SUCCESSFUL_DEFAULT_MSG; - } - return self::result($status,$msg,$data); + exit(json_encode(compact('code', 'msg', 'data', 'count'))); } - public static function status($status,$msg,$result = []) + public static function successlayui($count = 0, $data = [], $msg = '') + { + if (is_array($count)) { + if (isset($count['data'])) $data = $count['data']; + if (isset($count['count'])) $count = $count['count']; + } + if (false == is_string($msg)) { + $data = $msg; + $msg = self::$SUCCESSFUL_DEFAULT_MSG; + } + return self::result(0, $msg, $data, $count); + } + + public static function successful($msg = 'ok', $data = [], $status = 200) + { + if (false == is_string($msg)) { + $data = $msg; + $msg = self::$SUCCESSFUL_DEFAULT_MSG; + } + return self::result($status, $msg, $data); + } + + public static function status($status, $msg, $result = []) { $status = strtoupper($status); - if(true == is_array($msg)){ + if (true == is_array($msg)) { $result = $msg; $msg = self::$SUCCESSFUL_DEFAULT_MSG; } - return self::result(200,$msg,compact('status','result')); + return self::result(200, $msg, compact('status', 'result')); } - public static function fail($msg,$data=[],$code=400) + public static function fail($msg, $data = [], $code = 400) { - if(true == is_array($msg)){ + if (true == is_array($msg)) { $data = $msg; $msg = self::$FAIL_DEFAULT_MSG; } - return self::result($code,$msg,$data); + return self::result($code, $msg, $data); } - public static function success($msg,$data=[]) + public static function success($msg, $data = []) { - if(true == is_array($msg)){ + if (true == is_array($msg)) { $data = $msg; $msg = self::$SUCCESSFUL_DEFAULT_MSG; } - return self::result(200,$msg,$data); + return self::result(200, $msg, $data); } /* @@ -73,9 +75,9 @@ class JsonService * @param array $data 返回数据 * @return array * */ - public static function returnData($code,$msg='',$data=[]) + public static function returnData($code, $msg = '', $data = []) { - return compact('code','msg','data'); + return compact('code', 'msg', 'data'); } } \ No newline at end of file diff --git a/crmeb/crmeb/services/MiniProgramService.php b/crmeb/crmeb/services/MiniProgramService.php index 25f682bd..849af566 100644 --- a/crmeb/crmeb/services/MiniProgramService.php +++ b/crmeb/crmeb/services/MiniProgramService.php @@ -11,7 +11,6 @@ use crmeb\repositories\PaymentRepositories; use EasyWeChat\Foundation\Application; use EasyWeChat\Payment\Order; use think\facade\Route as Url; -use crmeb\services\HookService; use crmeb\interfaces\ProviderInterface; use app\models\store\StoreOrder as StoreOrderRoutineModel; use app\models\user\UserRecharge; @@ -324,7 +323,6 @@ class MiniProgramService implements ProviderInterface $staff = self::staffService(); $staff = is_callable($message) ? $staff->message($message()) : $staff->message($message); $res = $staff->to($to)->send(); - HookService::afterListen('wechat_staff_to',compact('to','message'),$res); return $res; } diff --git a/crmeb/crmeb/services/PHPExcelService.php b/crmeb/crmeb/services/PHPExcelService.php index 0235b2a3..8219fb0b 100644 --- a/crmeb/crmeb/services/PHPExcelService.php +++ b/crmeb/crmeb/services/PHPExcelService.php @@ -1,4 +1,5 @@ array('argb' => 'FFFF0000'), ), ), - 'font'=>[ - 'bold'=>true + 'font' => [ + 'bold' => true ], - 'alignment'=>[ - 'horizontal'=>\PHPExcel_Style_Alignment::HORIZONTAL_CENTER, - 'vertical'=>\PHPExcel_Style_Alignment::VERTICAL_CENTER + 'alignment' => [ + 'horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER, + 'vertical' => \PHPExcel_Style_Alignment::VERTICAL_CENTER ] ); + /** *初始化PHPExcel类 - *@param $data array() - *@param $fun function() + * @param $data array() + * @param $fun function() * return */ - private static function initialize($data,$fun){ - self::$PHPExcel= new \PHPExcel(); - if($fun!==null && is_callable($fun)){ - self::$styleArray=$fun(); + private static function initialize($data, $fun) + { + self::$PHPExcel = new \PHPExcel(); + if ($fun !== null && is_callable($fun)) { + self::$styleArray = $fun(); } - if(!is_array($data)) exit(Json::fail('data 为数组')); - self::$data=$data; + if (!is_array($data)) exit(Json::fail('data 为数组')); + self::$data = $data; } + /** *设置字体格式 - *@param $title string 必选 + * @param $title string 必选 * return string */ - public static function setUtf8($title){ + public static function setUtf8($title) + { return iconv('utf-8', 'gb2312', $title); } + /** * * execl数据导出 @@ -81,48 +87,50 @@ class PHPExcelService * * 特殊处理:合并单元格需要先对数据进行处理 */ - public function setExcelContent($list=null) + public function setExcelContent($list = null) { - $sheet=self::$PHPExcel->getActiveSheet(); - foreach(self::$data as $key=>$val){ - $row=self::$cellKey[$key]; - $sheet->getColumnDimension($row)->setWidth(isset($val['w'])?$val['w']:self::$where); - $sheet->setCellValue($row.self::$topNumber,isset($val['name'])?$val['name']:$val); + $sheet = self::$PHPExcel->getActiveSheet(); + foreach (self::$data as $key => $val) { + $row = self::$cellKey[$key]; + $sheet->getColumnDimension($row)->setWidth(isset($val['w']) ? $val['w'] : self::$where); + $sheet->setCellValue($row . self::$topNumber, isset($val['name']) ? $val['name'] : $val); } - $cellkey=array_slice(self::$cellKey,0,self::$count); - if($list!==null && is_array($list)){ - foreach ($cellkey as $k=>$v){ - foreach ($list as $key=>$val){ - if(isset($val[$k]) && !is_array($val[$k])){ - $sheet->setCellValue($v.(self::$topNumber+1+$key),$val[$k]); - }else if(isset($val[$k]) && is_array($val[$k])){ - $str=''; - foreach ($val[$k] as $value){ - $str.=$value.chr(10); + $cellkey = array_slice(self::$cellKey, 0, self::$count); + if ($list !== null && is_array($list)) { + foreach ($cellkey as $k => $v) { + foreach ($list as $key => $val) { + if (isset($val[$k]) && !is_array($val[$k])) { + $sheet->setCellValue($v . (self::$topNumber + 1 + $key), $val[$k]); + } else if (isset($val[$k]) && is_array($val[$k])) { + $str = ''; + foreach ($val[$k] as $value) { + $str .= $value . chr(10); } - $sheet->setCellValue($v.(self::$topNumber+1+$key),$str); + $sheet->setCellValue($v . (self::$topNumber + 1 + $key), $str); } } } $sheet->getDefaultRowDimension()->setRowHeight(self::$height); //设置边框 - $sheet->getStyle('A1:'.self::$cells.(count($list)+self::$topNumber))->applyFromArray(self::$styleArray); + $sheet->getStyle('A1:' . self::$cells . (count($list) + self::$topNumber))->applyFromArray(self::$styleArray); //设置自动换行 - $sheet->getStyle('A4:'.self::$cells.(count($list)+self::$topNumber))->getAlignment()->setWrapText(true); - }else if($list!==null && is_callable($list)){ - $list($sheet,self::$topNumber,$cellkey,self::$cells)->applyFromArray(self::$styleArray); + $sheet->getStyle('A4:' . self::$cells . (count($list) + self::$topNumber))->getAlignment()->setWrapText(true); + } else if ($list !== null && is_callable($list)) { + $list($sheet, self::$topNumber, $cellkey, self::$cells)->applyFromArray(self::$styleArray); } return $this; } + /** * 保存表格数据,并下载 * @param * @return */ - public function ExcelSave(){ - $objWriter=\PHPExcel_IOFactory::createWriter(self::$PHPExcel,'Excel2007'); - $filename=self::$title.'--'.time().'.xlsx'; + public function ExcelSave() + { + $objWriter = \PHPExcel_IOFactory::createWriter(self::$PHPExcel, 'Excel2007'); + $filename = self::$title . '--' . time() . '.xlsx'; ob_end_clean(); header('Content-Type: application/vnd.ms-excel'); header('Content-Type: application/octet-stream'); @@ -138,20 +146,21 @@ class PHPExcelService * @param $fun function() 主要设置边框的粗细 * @return $this */ - public static function setExcelHeader($data,$fun=null) + public static function setExcelHeader($data, $fun = null) { - self::initialize($data,$fun); + self::initialize($data, $fun); - if(self::$count=count(self::$data)){ - if(self::$count>count(self::$cellKey)){ + if (self::$count = count(self::$data)) { + if (self::$count > count(self::$cellKey)) { return Json::fail('表头长度过长'); } - self::$cells=self::$cellKey[self::$count-1]; - }else{ + self::$cells = self::$cellKey[self::$count - 1]; + } else { return Json::fail('data 参数二不能为空'); } return new self; } + /** * 设置标题 * @param $title string || array ['title'=>'','name'=>'','info'=>[]] @@ -160,20 +169,21 @@ class PHPExcelService * @param $funName function($style,$A,$A2) 自定义设置头部样式 * @return $this */ - public function setExcelTile($title='',$Name='',$info=[],$funName=null){ + public function setExcelTile($title = '', $Name = '', $info = [], $funName = null) + { //设置参数 - if(is_array($title)){ - if(isset($title['title'])) $title=$title['title']; - if(isset($title['name'])) $Name=$title['name']; - if(isset($title['info'])) $info=$title['info']; + if (is_array($title)) { + if (isset($title['title'])) $title = $title['title']; + if (isset($title['name'])) $Name = $title['name']; + if (isset($title['info'])) $info = $title['info']; } - if(empty($title)) - $title=self::$title; + if (empty($title)) + $title = self::$title; else - self::$title=$title; - if(empty($Name)) $Name=time(); + self::$title = $title; + if (empty($Name)) $Name = time(); //设置Excel属性 - self::$PHPExcel ->getProperties() + self::$PHPExcel->getProperties() ->setCreator("Neo") ->setLastModifiedBy("Neo") ->setTitle(self::setUtf8($title)) @@ -181,25 +191,25 @@ class PHPExcelService ->setDescription("") ->setKeywords($Name) ->setCategory(""); - self::$PHPExcel ->getActiveSheet()->setCellValue('A1', $title); + self::$PHPExcel->getActiveSheet()->setCellValue('A1', $title); //文字居中 self::$PHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER); self::$PHPExcel->getActiveSheet()->getStyle('A2')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER); self::$PHPExcel->setActiveSheetIndex(0); self::$PHPExcel->getActiveSheet()->setTitle($Name); - self::$PHPExcel->getActiveSheet()->setCellValue('A2',self::setCellInfo($info)); + self::$PHPExcel->getActiveSheet()->setCellValue('A2', self::setCellInfo($info)); //合并表头单元格 - self::$PHPExcel->getActiveSheet()->mergeCells('A1:'.self::$cells.'1'); - self::$PHPExcel->getActiveSheet()->mergeCells('A2:'.self::$cells.'2'); + self::$PHPExcel->getActiveSheet()->mergeCells('A1:' . self::$cells . '1'); + self::$PHPExcel->getActiveSheet()->mergeCells('A2:' . self::$cells . '2'); self::$PHPExcel->getActiveSheet()->getRowDimension(1)->setRowHeight(40); self::$PHPExcel->getActiveSheet()->getRowDimension(2)->setRowHeight(20); //设置表头行高 - if($funName!==null && is_callable($funName)){ - $fontstyle=self::$PHPExcel->getActiveSheet(); - $funName($fontstyle,'A1','A2'); - }else{ + if ($funName !== null && is_callable($funName)) { + $fontstyle = self::$PHPExcel->getActiveSheet(); + $funName($fontstyle, 'A1', 'A2'); + } else { //设置表头字体 self::$PHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setName('黑体'); self::$PHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(20); @@ -207,36 +217,38 @@ class PHPExcelService self::$PHPExcel->getActiveSheet()->getStyle('A2')->getFont()->setName('宋体'); self::$PHPExcel->getActiveSheet()->getStyle('A2')->getFont()->setSize(14); } - self::$PHPExcel->getActiveSheet()->getStyle('A3:'.self::$cells.'3')->getFont()->setBold(true); + self::$PHPExcel->getActiveSheet()->getStyle('A3:' . self::$cells . '3')->getFont()->setBold(true); return $this; } + /** * 设置第二行标题内容 * @param $info array (['name'=>'','site'=>'','phone'=>123] || ['我是表名','我是地址','我是手机号码'] ) || string 自定义 * @return string */ - private static function setCellInfo($info){ - $content=['操作者:','导出日期:'.date('Y-m-d',time()),'地址:','电话:']; - if(is_array($info) && !empty($info)){ - if(isset($info['name'])){ - $content[0].=$info['name']; - }else{ - $content[0].=isset($info[0])?$info[0]:''; + private static function setCellInfo($info) + { + $content = ['操作者:', '导出日期:' . date('Y-m-d', time()), '地址:', '电话:']; + if (is_array($info) && !empty($info)) { + if (isset($info['name'])) { + $content[0] .= $info['name']; + } else { + $content[0] .= isset($info[0]) ? $info[0] : ''; } - if(isset($info['site'])){ - $content[2].=$info['site']; - }else{ - $content[2].=isset($info[1])?$info[1]:''; + if (isset($info['site'])) { + $content[2] .= $info['site']; + } else { + $content[2] .= isset($info[1]) ? $info[1] : ''; } - if(isset($info['phone'])){ - $content[3].=$info['phone']; - }else{ - $content[3].=isset($info[2])?$info[2]:''; + if (isset($info['phone'])) { + $content[3] .= $info['phone']; + } else { + $content[3] .= isset($info[2]) ? $info[2] : ''; } - return implode(' ',$content); - }else if(is_string($info)){ - return empty($info)?implode(' ',$content):$info; + return implode(' ', $content); + } else if (is_string($info)) { + return empty($info) ? implode(' ', $content) : $info; } } } diff --git a/crmeb/crmeb/services/PHPTreeService.php b/crmeb/crmeb/services/PHPTreeService.php index e0b25cd9..7da7921c 100644 --- a/crmeb/crmeb/services/PHPTreeService.php +++ b/crmeb/crmeb/services/PHPTreeService.php @@ -10,21 +10,21 @@ namespace crmeb\services; * @Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) * @updated 2015-08-26 */ -class PHPTreeService{ - +class PHPTreeService +{ protected static $config = array( /* 主键 */ - 'primary_key' => 'id', + 'primary_key' => 'id', /* 父键 */ - 'parent_key' => 'pid', + 'parent_key' => 'pid', /* 展开属性 */ - 'expanded_key' => 'expanded', + 'expanded_key' => 'expanded', /* 叶子节点属性 */ - 'leaf_key' => 'leaf', + 'leaf_key' => 'leaf', /* 孩子节点属性 */ - 'children_key' => 'children', + 'children_key' => 'children', /* 是否展开子节点 */ - 'expanded' => false + 'expanded' => false ); /* 结果集 */ @@ -32,33 +32,37 @@ class PHPTreeService{ /* 层次暂存 */ protected static $level = array(); + /** * @name 生成树形结构 * @param array 二维数组 * @return mixed 多维数组 */ - public static function makeTree($data,$options=array() ){ - $dataset = self::buildData($data,$options); - $r = self::makeTreeCore(0,$dataset,'normal'); + public static function makeTree($data, $options = array()) + { + $dataset = self::buildData($data, $options); + $r = self::makeTreeCore(0, $dataset, 'normal'); return $r; } /* 生成线性结构, 便于HTML输出, 参数同上 */ - public static function makeTreeForHtml($data,$options=array()){ + public static function makeTreeForHtml($data, $options = array()) + { - $dataset = self::buildData($data,$options); - $r = self::makeTreeCore(0,$dataset,'linear'); + $dataset = self::buildData($data, $options); + $r = self::makeTreeCore(0, $dataset, 'linear'); return $r; } /* 格式化数据, 私有方法 */ - private static function buildData($data,$options){ - $config = array_merge(self::$config,$options); + private static function buildData($data, $options) + { + $config = array_merge(self::$config, $options); self::$config = $config; extract($config); $r = array(); - foreach($data as $item){ + foreach ($data as $item) { $id = $item[$primary_key]; $parent_id = $item[$parent_key]; $r[$parent_id][$id] = $item; @@ -68,29 +72,25 @@ class PHPTreeService{ } /* 生成树核心, 私有方法 */ - private static function makeTreeCore($index,$data,$type='linear') + private static function makeTreeCore($index, $data, $type = 'linear') { extract(self::$config); - foreach($data[$index] as $id=>$item) - { - if($type=='normal'){ - if(isset($data[$id])) - { - $item[$expanded_key]= self::$config['expanded']; - $item[$children_key]= self::makeTreeCore($id,$data,$type); - } - else - { - $item[$leaf_key]= true; + foreach ($data[$index] as $id => $item) { + if ($type == 'normal') { + if (isset($data[$id])) { + $item[$expanded_key] = self::$config['expanded']; + $item[$children_key] = self::makeTreeCore($id, $data, $type); + } else { + $item[$leaf_key] = true; } $r[] = $item; - }else if($type=='linear'){ + } else if ($type == 'linear') { $parent_id = $item[$parent_key]; - self::$level[$id] = $index==0?0:self::$level[$parent_id]+1; + self::$level[$id] = $index == 0 ? 0 : self::$level[$parent_id] + 1; $item['level'] = self::$level[$id]; self::$result[] = $item; - if(isset($data[$id])){ - self::makeTreeCore($id,$data,$type); + if (isset($data[$id])) { + self::makeTreeCore($id, $data, $type); } $r = self::$result; diff --git a/crmeb/crmeb/services/QrcodeService.php b/crmeb/crmeb/services/QrcodeService.php index 47536e9b..f4ba74cd 100644 --- a/crmeb/crmeb/services/QrcodeService.php +++ b/crmeb/crmeb/services/QrcodeService.php @@ -15,22 +15,26 @@ class QrcodeService /** * 获取临时二维码 单个 * */ - public static function getTemporaryQrcode($type,$id){ - return QrcodeModel::getTemporaryQrcode($type,$id)->toArray(); - }/** + public static function getTemporaryQrcode($type, $id) + { + return QrcodeModel::getTemporaryQrcode($type, $id)->toArray(); + } + + /** * 获取永久二维码 单个 * */ - public static function getForeverQrcode($type,$id){ - return QrcodeModel::getForeverQrcode($type,$id)->toArray(); - } + public static function getForeverQrcode($type, $id) + { + return QrcodeModel::getForeverQrcode($type, $id)->toArray(); + } - public static function getQrcode($id,$type = 'id') - { - return QrcodeModel::getQrcode($id,$type); - } + public static function getQrcode($id, $type = 'id') + { + return QrcodeModel::getQrcode($id, $type); + } - public static function scanQrcode($id,$type = 'id') - { - return QrcodeModel::scanQrcode($id,$type); - } + public static function scanQrcode($id, $type = 'id') + { + return QrcodeModel::scanQrcode($id, $type); + } } \ No newline at end of file diff --git a/crmeb/crmeb/services/SMSService.php b/crmeb/crmeb/services/SMSService.php index 80ffef2b..1678effb 100644 --- a/crmeb/crmeb/services/SMSService.php +++ b/crmeb/crmeb/services/SMSService.php @@ -1,4 +1,5 @@ ip(); - $to_ken=$request->domain().self::$seperater.$ip.self::$seperater.time().self::$seperater.(time()+$valid_peroid).self::$seperater; - $token=self::enCode($to_ken); + public static function get_token($ip = '', $valid_peroid = 1296000) + { + $request = app('request'); + if (empty($ip)) $ip = $request->ip(); + $to_ken = $request->domain() . self::$seperater . $ip . self::$seperater . time() . self::$seperater . (time() + $valid_peroid) . self::$seperater; + $token = self::enCode($to_ken); return $token; } - private static function getRet($msg,$code=400){ - return ['msg'=>$msg,'code'=>$code]; + + private static function getRet($msg, $code = 400) + { + return ['msg' => $msg, 'code' => $code]; } + /** * * @param string $url * @param array $post_data */ - public static function start(){ - $pach = app()->getRootPath().'version'; + public static function start() + { + $pach = app()->getRootPath() . 'version'; $request = app('request'); - if(!file_exists($pach)) return self::getRet($pach.'升级文件丢失,请联系管理员'); - $version=@file($pach); - if(!isset($version[0])) return self::getRet('获取失败'); - $lv=self::request_post(self::$isNowVersionUrl,['token'=>self::get_token($request->ip())]); - if(isset($lv['code']) && $lv['code']==200) - $version_lv=isset($lv['data']['version']) && $lv['data']['version'] ? $lv['data']['version'] : false; + if (!file_exists($pach)) return self::getRet($pach . '升级文件丢失,请联系管理员'); + $version = @file($pach); + if (!isset($version[0])) return self::getRet('获取失败'); + $lv = self::request_post(self::$isNowVersionUrl, ['token' => self::get_token($request->ip())]); + if (isset($lv['code']) && $lv['code'] == 200) + $version_lv = isset($lv['data']['version']) && $lv['data']['version'] ? $lv['data']['version'] : false; else - return isset($lv['msg'])?self::getRet($lv['msg']):self::getRet('获取失败'); - if($version_lv===false) return self::getRet('获取失败'); - if(strstr($version[0],'=')!==false){ - $version=explode('=',$version[0]); - if($version[1]!=$version_lv){ - return self::getRet($version_lv,200); + return isset($lv['msg']) ? self::getRet($lv['msg']) : self::getRet('获取失败'); + if ($version_lv === false) return self::getRet('获取失败'); + if (strstr($version[0], '=') !== false) { + $version = explode('=', $version[0]); + if ($version[1] != $version_lv) { + return self::getRet($version_lv, 200); } } return self::getRet('获取失败'); } - public static function getVersion(){ - $pach = app()->getRootPath().'.version'; - if(!file_exists($pach)) return self::getRet($pach.'升级文件丢失,请联系管理员'); - $version=@file($pach); - if(!isset($version[0]) && !isset($version[1])) return self::getRet('获取失败'); - $arr=[]; - foreach ($version as $val){ - list($k,$v)=explode('=',$val); - $arr[$k]=$v; + + public static function getVersion() + { + $pach = app()->getRootPath() . '.version'; + if (!file_exists($pach)) return self::getRet($pach . '升级文件丢失,请联系管理员'); + $version = @file($pach); + if (!isset($version[0]) && !isset($version[1])) return self::getRet('获取失败'); + $arr = []; + foreach ($version as $val) { + list($k, $v) = explode('=', $val); + $arr[$k] = $v; } - return self::getRet($arr,200); + return self::getRet($arr, 200); } + /** * 模拟post进行url请求 * @param string $url * @param array $post_data */ - public static function request_post($url = '', $post_data = array()) { - if(strstr($url,'http')===false) $url=self::$domain.$url; - if (empty($url)){ + public static function request_post($url = '', $post_data = array()) + { + if (strstr($url, 'http') === false) $url = self::$domain . $url; + if (empty($url)) { return false; } - if(!isset($post_data['token'])) $post_data['token']=self::get_token(); + if (!isset($post_data['token'])) $post_data['token'] = self::get_token(); $o = ""; - foreach ( $post_data as $k => $v ) - { - $o.= "$k=" . urlencode( $v ). "&" ; + foreach ($post_data as $k => $v) { + $o .= "$k=" . urlencode($v) . "&"; } - $post_data = substr($o,0,-1); + $post_data = substr($o, 0, -1); $postUrl = $url; $curlPost = $post_data; $ch = curl_init();//初始化curl - curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页 + curl_setopt($ch, CURLOPT_URL, $postUrl);//抓取指定网页 curl_setopt($ch, CURLOPT_HEADER, 0);//设置header curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上 curl_setopt($ch, CURLOPT_POST, 1);//post提交方式 curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost); - curl_setopt($ch, CURLOPT_TIMEOUT,20); + curl_setopt($ch, CURLOPT_TIMEOUT, 20); $data = curl_exec($ch);//运行curl curl_close($ch); - if($data){ - $data=json_decode($data,true); + if ($data) { + $data = json_decode($data, true); } return $data; } + /** * 验证远程文件是否存在 以及下载 * @param string $url 文件路径 * @param string $savefile 保存地址 */ - public static function check_remote_file_exists($url,$savefile) + public static function check_remote_file_exists($url, $savefile) { - $url=self::$domain.'public'.DS.'uploads'.DS.'upgrade'.DS.$url; - $url = str_replace('\\','/',$url); + $url = self::$domain . 'public' . DS . 'uploads' . DS . 'upgrade' . DS . $url; + $url = str_replace('\\', '/', $url); $curl = curl_init($url); curl_setopt($curl, CURLOPT_NOBODY, true); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET'); @@ -134,47 +149,49 @@ class UpgradeService extends FileService $result = curl_exec($curl); $found = false; // 如果请求没有发送失败 - if ($result !== false) - { + if ($result !== false) { // 再检查http响应码是否为200 $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE); - if ($statusCode == 200) - { + if ($statusCode == 200) { curl_close($curl); - $fileservice=new self; + $fileservice = new self; //下载文件 - $zip=$fileservice->down_remote_file($url,$savefile); - if($zip['error']>0) return false; - if(!isset($zip['save_path']) && empty($zip['save_path'])) return false; - if(!file_exists($zip['save_path'])) return false; + $zip = $fileservice->down_remote_file($url, $savefile); + if ($zip['error'] > 0) return false; + if (!isset($zip['save_path']) && empty($zip['save_path'])) return false; + if (!file_exists($zip['save_path'])) return false; return $zip['save_path']; } } curl_close($curl); return $found; } + /** * 通用加密 * @param String $string 需要加密的字串 * @param String $skey 加密EKY * @return String */ - private static function enCode($string = '', $skey = 'fb') { + private static function enCode($string = '', $skey = 'fb') + { $skey = array_reverse(str_split($skey)); $strArr = str_split(base64_encode($string)); $strCount = count($strArr); foreach ($skey as $key => $value) { - $key < $strCount && $strArr[$key].=$value; + $key < $strCount && $strArr[$key] .= $value; } return str_replace('=', 'O0O0O', join('', $strArr)); } + /** * 去除回车,去取空格,去除换行,去除tab * @param String $str 需要去除的字串 * @return String */ - public static function replace($str){ - return trim(str_replace(array("\r", "\n", "\t"), '',$str)); + public static function replace($str) + { + return trim(str_replace(array("\r", "\n", "\t"), '', $str)); } } \ No newline at end of file diff --git a/crmeb/crmeb/services/UploadService.php b/crmeb/crmeb/services/UploadService.php index 2d13942c..5e05e0b6 100644 --- a/crmeb/crmeb/services/UploadService.php +++ b/crmeb/crmeb/services/UploadService.php @@ -46,13 +46,13 @@ class UploadService * @var array */ protected $uploadInfo = [ - 'name' => '', - 'size' => 0, - 'type' => 'image/jpeg', - 'dir' => '', - 'thumb_path'=> '', - 'image_type'=> '', - 'time' => 0, + 'name' => '', + 'size' => 0, + 'type' => 'image/jpeg', + 'dir' => '', + 'thumb_path' => '', + 'image_type' => '', + 'time' => 0, ]; /** @@ -83,7 +83,7 @@ class UploadService */ public static function getInstance() { - if(is_null(self::$instance)) self::$instance = new self(); + if (is_null(self::$instance)) self::$instance = new self(); return self::$instance; } @@ -192,8 +192,8 @@ class UploadService */ protected static function uploadDir($path, $root = null) { - if ($root === null) $root = app()->getRootPath() . 'public' . DS ; - return $root . 'uploads' .DS. $path; + if ($root === null) $root = app()->getRootPath() . 'public' . DS; + return $root . 'uploads' . DS . $path; } /** @@ -204,14 +204,14 @@ class UploadService public function image($fileName) { $info = []; - try{ - $uploadType = $this->uploadType ? : sysConfig('upload_type'); + try { + $uploadType = $this->uploadType ?: sysConfig('upload_type'); //TODO 没有选择默认使用本地上传 if (!$uploadType) $uploadType = 1; switch ($uploadType) { case 1 : $info = $this->uploadLocaFile($fileName); - if(is_string($info)) return $info; + if (is_string($info)) return $info; break; case 2 : $keys = Qiniu::uploadImage($fileName); @@ -219,7 +219,7 @@ class UploadService foreach ($keys as $key => &$item) { if (is_array($item)) { $info = Qiniu::imageUrl($item['key']); - $info = $this->setUploadInfo($info['dir'],2,$item['key'],UtilService::setHttpType($info['thumb_path'])); + $info = $this->setUploadInfo($info['dir'], 2, $item['key'], UtilService::setHttpType($info['thumb_path'])); } } } else return $keys; @@ -227,21 +227,21 @@ class UploadService case 3 : $serverImageInfo = OSS::uploadImage($fileName); if (!is_array($serverImageInfo)) return $serverImageInfo; - $info = $this->setUploadInfo(UtilService::setHttpType($serverImageInfo['info']['url']),3,substr(strrchr($serverImageInfo['info']['url'], '/'), 1)); + $info = $this->setUploadInfo(UtilService::setHttpType($serverImageInfo['info']['url']), 3, substr(strrchr($serverImageInfo['info']['url'], '/'), 1)); break; case 4 : - list($imageUrl,$serverImageInfo) = COS::uploadImage($fileName); + list($imageUrl, $serverImageInfo) = COS::uploadImage($fileName); if (!is_array($serverImageInfo) && !is_object($serverImageInfo)) return $serverImageInfo; - $info = $this->setUploadInfo($imageUrl,4,substr(strrchr($imageUrl, '/'), 1)); + $info = $this->setUploadInfo($imageUrl, 4, substr(strrchr($imageUrl, '/'), 1)); break; default: $info = $this->uploadLocaFile($fileName); - if(is_string($info)) return $info; + if (is_string($info)) return $info; break; } $this->uploadPath = ''; $this->autoValidate = true; - }catch (\Exception $e){ + } catch (\Exception $e) { return $e->getMessage(); } return $info; @@ -254,8 +254,9 @@ class UploadService * @param bool $isData 是否真实获取图片信息 * @return array */ - public static function getImageHeaders(string $url,$type = 1,$isData = true){ - stream_context_set_default( [ + public static function getImageHeaders(string $url, $type = 1, $isData = true) + { + stream_context_set_default([ 'ssl' => [ 'verify_peer' => false, 'verify_peer_name' => false, @@ -263,12 +264,12 @@ class UploadService ]); $header['Content-Length'] = 0; $header['Content-Type'] = 'image/jpeg'; - if(!$isData) return $header; - try{ + if (!$isData) return $header; + try { $header = get_headers(str_replace('\\', '/', UtilService::setHttpType($url, $type)), true); - if(!isset($header['Content-Length'])) $header['Content-Length'] = 0; - if(!isset($header['Content-Type'])) $header['Content-Type'] = 'image/jpeg'; - }catch (\Exception $e){ + if (!isset($header['Content-Length'])) $header['Content-Length'] = 0; + if (!isset($header['Content-Type'])) $header['Content-Type'] = 'image/jpeg'; + } catch (\Exception $e) { $header['Content-Length'] = 0; $header['Content-Type'] = 'image/jpeg'; } @@ -284,8 +285,7 @@ class UploadService { $file = request()->file($fileName); if (!$file) return '上传文件不存在!'; - if ($this->autoValidate) - { + if ($this->autoValidate) { try { validate([$fileName => $this->imageValidate])->check([$fileName => $file]); } catch (ValidateException $e) { @@ -297,9 +297,9 @@ class UploadService $filePath = Filesystem::path($fileName); $fileInfo = new File($filePath); $url = '/uploads/' . $fileName; - return $this->setUploadInfo($url,1,$fileInfo->getFilename(),self::thumb('.'.$url),[ - 'Content-Length'=>$fileInfo->getSize(), - 'Content-Type'=>$fileInfo->getMime() + return $this->setUploadInfo($url, 1, $fileInfo->getFilename(), self::thumb('.' . $url), [ + 'Content-Length' => $fileInfo->getSize(), + 'Content-Type' => $fileInfo->getMime() ]); } @@ -310,7 +310,7 @@ class UploadService * @param string $root * @return array|string */ - public function uploadLocalStream($key, $content,$root='') + public function uploadLocalStream($key, $content, $root = '') { $siteUrl = sysConfig('site_url') . '/'; $path = self::uploadDir($this->uploadPath, $root); @@ -321,9 +321,9 @@ class UploadService $name = $path . DS . $key; file_put_contents($name, $content); $path = str_replace('\\', '/', $path); - $headerArray = self::getImageHeaders($siteUrl . $path . '/' .$key); - $url = '/'.$path . '/' .$key; - return $this->setUploadInfo($url,1,$key,$url,$headerArray); + $headerArray = self::getImageHeaders($siteUrl . $path . '/' . $key); + $url = '/' . $path . '/' . $key; + return $this->setUploadInfo($url, 1, $key, $url, $headerArray); } /** @@ -334,7 +334,7 @@ class UploadService * @return array|string * @throws \Exception */ - public function imageStream($key, $content,$root='') + public function imageStream($key, $content, $root = '') { $uploadType = sysConfig('upload_type'); //TODO 没有选择默认使用本地上传 @@ -342,8 +342,8 @@ class UploadService $info = []; switch ($uploadType) { case 1 : - $info = $this->uploadLocalStream($key, $content,$root); - if(is_string($info)) return $info; + $info = $this->uploadLocalStream($key, $content, $root); + if (is_string($info)) return $info; break; case 2 : $keys = Qiniu::uploadImageStream($key, $content); @@ -352,7 +352,7 @@ class UploadService if (is_array($item)) { $info = Qiniu::imageUrl($item['key']); $info['dir'] = UtilService::setHttpType($info['dir']); - $info = $this->setUploadInfo($info['dir'],2,$item['key'],$info['thumb_path']); + $info = $this->setUploadInfo($info['dir'], 2, $item['key'], $info['thumb_path']); } } if (!count($info)) return '七牛云文件上传失败'; @@ -362,16 +362,16 @@ class UploadService $content = COS::resourceStream($content); $serverImageInfo = OSS::uploadImageStream($key, $content); if (!is_array($serverImageInfo)) return $serverImageInfo; - $info = $this->setUploadInfo(UtilService::setHttpType($serverImageInfo['info']['url']),3,substr(strrchr($serverImageInfo['info']['url'], '/'), 1)); + $info = $this->setUploadInfo(UtilService::setHttpType($serverImageInfo['info']['url']), 3, substr(strrchr($serverImageInfo['info']['url'], '/'), 1)); break; case 4 : - list($imageUrl,$serverImageInfo) = COS::uploadImageStream($key, $content); + list($imageUrl, $serverImageInfo) = COS::uploadImageStream($key, $content); if (!is_array($serverImageInfo) && !is_object($serverImageInfo)) return $serverImageInfo; - $info = $this->setUploadInfo($imageUrl,4,substr(strrchr($imageUrl, '/'), 1)); + $info = $this->setUploadInfo($imageUrl, 4, substr(strrchr($imageUrl, '/'), 1)); break; default: - $info = $this->uploadLocalStream($key, $content,$root); - if(is_string($info)) return $info; + $info = $this->uploadLocalStream($key, $content, $root); + if (is_string($info)) return $info; break; } $this->uploadPath = ''; @@ -387,25 +387,25 @@ class UploadService * @param string $thumbPath * @return array */ - protected function setUploadInfo(string $url,int $imageType,string $name = '',string $thumbPath = '',array $headerArray = []) + protected function setUploadInfo(string $url, int $imageType, string $name = '', string $thumbPath = '', array $headerArray = []) { $headerArray = count($headerArray) ? $headerArray : self::getImageHeaders($url); - if(is_array($headerArray['Content-Type']) && count($headerArray['Content-Length']) == 2){ + if (is_array($headerArray['Content-Type']) && count($headerArray['Content-Length']) == 2) { $headerArray['Content-Length'] = $headerArray['Content-Length'][1]; } - if(is_array($headerArray['Content-Type']) && count($headerArray['Content-Type']) == 2){ + if (is_array($headerArray['Content-Type']) && count($headerArray['Content-Type']) == 2) { $headerArray['Content-Type'] = $headerArray['Content-Type'][1]; } $info = [ - 'name' => str_replace('\\','/',$name ? : $url), - 'dir' => str_replace('\\','/',$url), + 'name' => str_replace('\\', '/', $name ?: $url), + 'dir' => str_replace('\\', '/', $url), 'size' => $headerArray['Content-Length'], 'type' => $headerArray['Content-Type'], 'time' => time(), - 'thumb_path' => str_replace('\\','/',$thumbPath ? : $url), + 'thumb_path' => str_replace('\\', '/', $thumbPath ?: $url), 'image_type' => $imageType, ]; - $uploadInfo = array_merge($this->uploadInfo,$info); + $uploadInfo = array_merge($this->uploadInfo, $info); return $uploadInfo; } @@ -421,8 +421,7 @@ class UploadService if (strtolower($extension) == 'php' || !$extension) return self::setError('上传文件非法!'); $file = request()->file($fileName); - if ($this->autoValidate) - { + if ($this->autoValidate) { try { validate([$fileName => $this->imageValidate])->check([$fileName => $file]); } catch (ValidateException $e) { @@ -431,7 +430,7 @@ class UploadService }; $fileName = Filesystem::putFile($this->uploadPath, $file); if (!$fileName) return self::setError('图片上传失败!'); - return self::successful(str_replace('\\','/',$fileName)); + return self::successful(str_replace('\\', '/', $fileName)); } public static function pathToUrl($path) @@ -462,7 +461,7 @@ class UploadService $fileName = basename($filePath); $savePath = $dir . DS . $pre . $fileName; $img->thumb($width, $height)->save($savePath); - if(substr($savePath, 0, 2) == './') return substr($savePath, 1, strlen($savePath)); + if (substr($savePath, 0, 2) == './') return substr($savePath, 1, strlen($savePath)); return DS . $savePath; } diff --git a/crmeb/crmeb/services/UtilService.php b/crmeb/crmeb/services/UtilService.php index cbd14c45..4a7af013 100644 --- a/crmeb/crmeb/services/UtilService.php +++ b/crmeb/crmeb/services/UtilService.php @@ -24,19 +24,19 @@ class UtilService * @param bool $suffix * @return array */ - public static function postMore($params,$request = null,$suffix = false) + public static function postMore($params, $request = null, $suffix = false) { - if($request === null) $request = app('request'); + if ($request === null) $request = app('request'); $p = []; $i = 0; - foreach ($params as $param){ - if(!is_array($param)) { + foreach ($params as $param) { + if (!is_array($param)) { $p[$suffix == true ? $i++ : $param] = $request->param($param); - }else{ - if(!isset($param[1])) $param[1] = null; - if(!isset($param[2])) $param[2] = ''; - $name = is_array($param[1]) ? $param[0].'/a' : $param[0]; - $p[$suffix == true ? $i++ : (isset($param[3]) ? $param[3] : $param[0])] = $request->param($name,$param[1],$param[2]); + } else { + if (!isset($param[1])) $param[1] = null; + if (!isset($param[2])) $param[2] = ''; + $name = is_array($param[1]) ? $param[0] . '/a' : $param[0]; + $p[$suffix == true ? $i++ : (isset($param[3]) ? $param[3] : $param[0])] = $request->param($name, $param[1], $param[2]); } } return $p; @@ -49,25 +49,26 @@ class UtilService * @param bool $suffix * @return array */ - public static function getMore($params,$request=null,$suffix = false) + public static function getMore($params, $request = null, $suffix = false) { - if($request === null) $request = app('request'); + if ($request === null) $request = app('request'); $p = []; $i = 0; - foreach ($params as $param){ - if(!is_array($param)) { + foreach ($params as $param) { + if (!is_array($param)) { $p[$suffix == true ? $i++ : $param] = $request->param($param); - }else{ - if(!isset($param[1])) $param[1] = null; - if(!isset($param[2])) $param[2] = ''; - $name = is_array($param[1]) ? $param[0].'/a' : $param[0]; - $p[$suffix == true ? $i++ : (isset($param[3]) ? $param[3] : $param[0])] = $request->param($name,$param[1],$param[2]); + } else { + if (!isset($param[1])) $param[1] = null; + if (!isset($param[2])) $param[2] = ''; + $name = is_array($param[1]) ? $param[0] . '/a' : $param[0]; + $p[$suffix == true ? $i++ : (isset($param[3]) ? $param[3] : $param[0])] = $request->param($name, $param[1], $param[2]); } } return $p; } - public static function encrypt($string, $operation = false, $key = '', $expiry = 0) { + public static function encrypt($string, $operation = false, $key = '', $expiry = 0) + { // 动态密匙长度,相同的明文会生成不同密文就是依靠动态密匙 $ckey_length = 6; @@ -79,33 +80,33 @@ class UtilService // 密匙b会用来做数据完整性验证 $keyb = md5(substr($key, 16, 16)); // 密匙c用于变化生成的密文 - $keyc = $ckey_length ? ($operation == false ? substr($string, 0, $ckey_length): + $keyc = $ckey_length ? ($operation == false ? substr($string, 0, $ckey_length) : substr(md5(microtime()), -$ckey_length)) : ''; // 参与运算的密匙 - $cryptkey = $keya.md5($keya.$keyc); + $cryptkey = $keya . md5($keya . $keyc); $key_length = strlen($cryptkey); // 明文,前10位用来保存时间戳,解密时验证数据有效性,10到26位用来保存$keyb(密匙b), //解密时会通过这个密匙验证数据完整性 // 如果是解码的话,会从第$ckey_length位开始,因为密文前$ckey_length位保存 动态密匙,以保证解密正确 $string = $operation == false ? base64_decode(substr($string, $ckey_length)) : - sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string; + sprintf('%010d', $expiry ? $expiry + time() : 0) . substr(md5($string . $keyb), 0, 16) . $string; $string_length = strlen($string); $result = ''; $box = range(0, 255); $rndkey = array(); // 产生密匙簿 - for($i = 0; $i <= 255; $i++) { + for ($i = 0; $i <= 255; $i++) { $rndkey[$i] = ord($cryptkey[$i % $key_length]); } // 用固定的算法,打乱密匙簿,增加随机性,好像很复杂,实际上对并不会增加密文的强度 - for($j = $i = 0; $i < 256; $i++) { + for ($j = $i = 0; $i < 256; $i++) { $j = ($j + $box[$i] + $rndkey[$i]) % 256; $tmp = $box[$i]; $box[$i] = $box[$j]; $box[$j] = $tmp; } // 核心加解密部分 - for($a = $j = $i = 0; $i < $string_length; $i++) { + for ($a = $j = $i = 0; $i < $string_length; $i++) { $a = ($a + 1) % 256; $j = ($j + $box[$a]) % 256; $tmp = $box[$a]; @@ -114,10 +115,10 @@ class UtilService // 从密匙簿得出密匙进行异或,再转成字符 $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256])); } - if($operation == false) { + if ($operation == false) { // 验证数据有效性,请看未加密明文的格式 - if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && - substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) { + if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && + substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)) { return substr($result, 26); } else { return ''; @@ -125,7 +126,7 @@ class UtilService } else { // 把动态密匙保存在密文里,这也是为什么同样的明文,生产不同密文后能解密的原因 // 因为加密后的密文可能是一些特殊字符,复制过程可能会丢失,所以用base64编码 - return $keyc.str_replace('=', '', base64_encode($result)); + return $keyc . str_replace('=', '', base64_encode($result)); } } @@ -137,7 +138,7 @@ class UtilService */ public static function pathToUrl($path) { - return trim(str_replace(DS, '/', $path),'.'); + return trim(str_replace(DS, '/', $path), '.'); } /** @@ -147,10 +148,10 @@ class UtilService */ public static function urlToPath($url) { - $path = trim(str_replace('/',DS,$url),DS); - if(0 !== strripos($path, 'public')) + $path = trim(str_replace('/', DS, $url), DS); + if (0 !== strripos($path, 'public')) $path = 'public' . DS . $path; - return app()->getRootPath().$path; + return app()->getRootPath() . $path; } /** @@ -202,6 +203,7 @@ class UtilService } return $list; } + /** * 分级返回多维数组 * @param $data @@ -227,6 +229,7 @@ class UtilService } + /**分级返回下级所有分类ID * @param $data * @param string $children @@ -234,12 +237,12 @@ class UtilService * @param string $pk * @return string */ - public static function getChildrenPid($data,$pid, $field = 'pid', $pk = 'id') + public static function getChildrenPid($data, $pid, $field = 'pid', $pk = 'id') { static $pids = ''; foreach ($data as $k => $res) { if ($res[$field] == $pid) { - $pids .= ','.$res[$pk]; + $pids .= ',' . $res[$pk]; self::getChildrenPid($data, $res[$pk], $field, $pk); } } @@ -252,13 +255,13 @@ class UtilService * @param $url * @return \StdClass */ - public static function rmPublicResource($url,$isPath = false) + public static function rmPublicResource($url, $isPath = false) { $path = $isPath ? $url : realpath(self::urlToPath($url)); - if(!$path) return JsonService::fail('删除文件不存在!'); - if(!file_exists($path)) return JsonService::fail('删除路径不合法!'); + if (!$path) return JsonService::fail('删除文件不存在!'); + if (!file_exists($path)) return JsonService::fail('删除路径不合法!'); // if(0 !== strpos($path,app()->getRootPath().'public/uploads/')) return JsonService::fail('删除路径不合法!'); - if(!unlink($path)) return JsonService::fail('删除文件失败!'); + if (!unlink($path)) return JsonService::fail('删除文件失败!'); return JsonService::successful(); } @@ -278,14 +281,14 @@ class UtilService */ public static function anonymity($name) { - $strLen = mb_strlen($name,'UTF-8'); + $strLen = mb_strlen($name, 'UTF-8'); $min = 3; - if($strLen <= 1) + if ($strLen <= 1) return '*'; - if($strLen<= $min) - return mb_substr($name,0,1,'UTF-8').str_repeat('*',$min-1); + if ($strLen <= $min) + return mb_substr($name, 0, 1, 'UTF-8') . str_repeat('*', $min - 1); else - return mb_substr($name,0,1,'UTF-8').str_repeat('*',$strLen-1).mb_substr($name,-1,1,'UTF-8'); + return mb_substr($name, 0, 1, 'UTF-8') . str_repeat('*', $strLen - 1) . mb_substr($name, -1, 1, 'UTF-8'); } /** @@ -293,45 +296,45 @@ class UtilService * @param $card * @return bool */ - public static function setCard($card){ - $city = [11=>"北京",12=>"天津",13=>"河北",14=>"山西",15=>"内蒙古",21=>"辽宁",22=>"吉林",23=>"黑龙江 ",31=>"上海",32=>"江苏",33=>"浙江",34=>"安徽",35=>"福建",36=>"江西",37=>"山东",41=>"河南",42=>"湖北 ",43=>"湖南",44=>"广东",45=>"广西",46=>"海南",50=>"重庆",51=>"四川",52=>"贵州",53=>"云南",54=>"西藏 ",61=>"陕西",62=>"甘肃",63=>"青海",64=>"宁夏",65=>"新疆",71=>"台湾",81=>"香港",82=>"澳门",91=>"国外 "]; + public static function setCard($card) + { + $city = [11 => "北京", 12 => "天津", 13 => "河北", 14 => "山西", 15 => "内蒙古", 21 => "辽宁", 22 => "吉林", 23 => "黑龙江 ", 31 => "上海", 32 => "江苏", 33 => "浙江", 34 => "安徽", 35 => "福建", 36 => "江西", 37 => "山东", 41 => "河南", 42 => "湖北 ", 43 => "湖南", 44 => "广东", 45 => "广西", 46 => "海南", 50 => "重庆", 51 => "四川", 52 => "贵州", 53 => "云南", 54 => "西藏 ", 61 => "陕西", 62 => "甘肃", 63 => "青海", 64 => "宁夏", 65 => "新疆", 71 => "台湾", 81 => "香港", 82 => "澳门", 91 => "国外 "]; $tip = ""; $match = "/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/"; - $pass= true; - if(!$card || !preg_match($match,$card)){ + $pass = true; + if (!$card || !preg_match($match, $card)) { //身份证格式错误 $pass = false; - }else if(!$city[substr($card,0,2)]){ + } else if (!$city[substr($card, 0, 2)]) { //地址错误 $pass = false; - }else{ + } else { //18位身份证需要验证最后一位校验位 - if(strlen($card) == 18){ + if (strlen($card) == 18) { $card = str_split($card); //∑(ai×Wi)(mod 11) //加权因子 - $factor = [ 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 ]; + $factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]; //校验位 - $parity = [ 1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2 ]; + $parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2]; $sum = 0; $ai = 0; $wi = 0; - for ($i = 0; $i < 17; $i++) - { + for ($i = 0; $i < 17; $i++) { $ai = $card[$i]; $wi = $factor[$i]; $sum += $ai * $wi; } $last = $parity[$sum % 11]; - if($parity[$sum % 11] != $card[17]){ + if ($parity[$sum % 11] != $card[17]) { // $tip = "校验位错误"; - $pass =false; + $pass = false; } - }else{ - $pass =false; + } else { + $pass = false; } } - if(!$pass) return false;/* 身份证格式错误*/ + if (!$pass) return false;/* 身份证格式错误*/ return true;/* 身份证格式正确*/ } @@ -342,96 +345,97 @@ class UtilService * @return array|bool|string * @throws \Exception */ - public static function setShareMarketingPoster($data = array(), $path){ + public static function setShareMarketingPoster($data = array(), $path) + { $config = array( - 'text'=>array( + 'text' => array( array( - 'text'=>$data['price'],//TODO 价格 - 'left'=>116, - 'top'=>200, - 'fontPath'=>app()->getRootPath().'public/static/font/Alibaba-PuHuiTi-Regular.otf', //字体文件 - 'fontSize'=>50, //字号 - 'fontColor'=>'255,0,0', //字体颜色 - 'angle'=>0, + 'text' => $data['price'],//TODO 价格 + 'left' => 116, + 'top' => 200, + 'fontPath' => app()->getRootPath() . 'public/static/font/Alibaba-PuHuiTi-Regular.otf', //字体文件 + 'fontSize' => 50, //字号 + 'fontColor' => '255,0,0', //字体颜色 + 'angle' => 0, ), array( - 'text'=>$data['label'],//TODO 标签 - 'left'=>394, - 'top'=>190, - 'fontPath'=>app()->getRootPath().'public/static/font/Alibaba-PuHuiTi-Regular.otf', //字体文件 - 'fontSize'=>24, //字号 - 'fontColor'=>'255,255,255', //字体颜色 - 'angle'=>0, + 'text' => $data['label'],//TODO 标签 + 'left' => 394, + 'top' => 190, + 'fontPath' => app()->getRootPath() . 'public/static/font/Alibaba-PuHuiTi-Regular.otf', //字体文件 + 'fontSize' => 24, //字号 + 'fontColor' => '255,255,255', //字体颜色 + 'angle' => 0, ), array( - 'text'=>$data['msg'],//TODO 简述 - 'left'=>80, - 'top'=>270, - 'fontPath'=>app()->getRootPath().'public/static/font/Alibaba-PuHuiTi-Regular.otf', //字体文件 - 'fontSize'=>22, //字号 - 'fontColor'=>'40,40,40', //字体颜色 - 'angle'=>0, + 'text' => $data['msg'],//TODO 简述 + 'left' => 80, + 'top' => 270, + 'fontPath' => app()->getRootPath() . 'public/static/font/Alibaba-PuHuiTi-Regular.otf', //字体文件 + 'fontSize' => 22, //字号 + 'fontColor' => '40,40,40', //字体颜色 + 'angle' => 0, ) ), - 'image'=>array( + 'image' => array( array( - 'url'=>$data['image'], //图片 - 'stream'=>0, - 'left'=>120, - 'top'=>340, - 'right'=>0, - 'bottom'=>0, - 'width'=>450, - 'height'=>450, - 'opacity'=>100 + 'url' => $data['image'], //图片 + 'stream' => 0, + 'left' => 120, + 'top' => 340, + 'right' => 0, + 'bottom' => 0, + 'width' => 450, + 'height' => 450, + 'opacity' => 100 ), array( - 'url'=>$data['url'], //二维码资源 - 'stream'=>0, - 'left'=>260, - 'top'=>890, - 'right'=>0, - 'bottom'=>0, - 'width'=>160, - 'height'=>160, - 'opacity'=>100 + 'url' => $data['url'], //二维码资源 + 'stream' => 0, + 'left' => 260, + 'top' => 890, + 'right' => 0, + 'bottom' => 0, + 'width' => 160, + 'height' => 160, + 'opacity' => 100 ) ), - 'background'=>app()->getRootPath().'/public/static/poster/poster.jpg' + 'background' => app()->getRootPath() . '/public/static/poster/poster.jpg' ); - if(!file_exists($config['background'])) exception('缺少系统预设背景图片'); - if(strlen($data['title']) < 36){ + if (!file_exists($config['background'])) exception('缺少系统预设背景图片'); + if (strlen($data['title']) < 36) { $text = array( - 'text'=>$data['title'],//TODO 标题 - 'left'=>76, - 'top'=>100, - 'fontPath'=>app()->getRootPath().'public/static/font/Alibaba-PuHuiTi-Regular.otf', //字体文件 - 'fontSize'=>32, //字号 - 'fontColor'=>'0,0,0', //字体颜色 - 'angle'=>0, + 'text' => $data['title'],//TODO 标题 + 'left' => 76, + 'top' => 100, + 'fontPath' => app()->getRootPath() . 'public/static/font/Alibaba-PuHuiTi-Regular.otf', //字体文件 + 'fontSize' => 32, //字号 + 'fontColor' => '0,0,0', //字体颜色 + 'angle' => 0, ); - array_push($config['text'],$text); - }else{ + array_push($config['text'], $text); + } else { $titleOne = array( - 'text'=>mb_substr($data['title'], 0, 12),//TODO 标题 - 'left'=>76, - 'top'=>70, - 'fontPath'=>app()->getRootPath().'public/static/font/Alibaba-PuHuiTi-Regular.otf', //字体文件 - 'fontSize'=>32, //字号 - 'fontColor'=>'0,0,0', //字体颜色 - 'angle'=>0, + 'text' => mb_substr($data['title'], 0, 12),//TODO 标题 + 'left' => 76, + 'top' => 70, + 'fontPath' => app()->getRootPath() . 'public/static/font/Alibaba-PuHuiTi-Regular.otf', //字体文件 + 'fontSize' => 32, //字号 + 'fontColor' => '0,0,0', //字体颜色 + 'angle' => 0, ); $titleTwo = array( - 'text'=> mb_substr($data['title'], 12, 12),//TODO 标题 - 'left'=>76, - 'top'=>120, - 'fontPath'=>app()->getRootPath().'public/static/font/Alibaba-PuHuiTi-Regular.otf', //字体文件 - 'fontSize'=>32, //字号 - 'fontColor'=>'0,0,0', //字体颜色 - 'angle'=>0, + 'text' => mb_substr($data['title'], 12, 12),//TODO 标题 + 'left' => 76, + 'top' => 120, + 'fontPath' => app()->getRootPath() . 'public/static/font/Alibaba-PuHuiTi-Regular.otf', //字体文件 + 'fontSize' => 32, //字号 + 'fontColor' => '0,0,0', //字体颜色 + 'angle' => 0, ); - array_push($config['text'],$titleOne); - array_push($config['text'],$titleTwo); + array_push($config['text'], $titleOne); + array_push($config['text'], $titleTwo); } return self::setSharePoster($config, $path); } @@ -443,70 +447,71 @@ class UtilService * @return array|bool|string * @throws \Exception */ - public static function setSharePoster($config = array(), $path){ + public static function setSharePoster($config = array(), $path) + { $imageDefault = array( - 'left'=>0, - 'top'=>0, - 'right'=>0, - 'bottom'=>0, - 'width'=>100, - 'height'=>100, - 'opacity'=>100 + 'left' => 0, + 'top' => 0, + 'right' => 0, + 'bottom' => 0, + 'width' => 100, + 'height' => 100, + 'opacity' => 100 ); $textDefault = array( - 'text'=>'', - 'left'=>0, - 'top'=>0, - 'fontSize'=>32, //字号 - 'fontColor'=>'255,255,255', //字体颜色 - 'angle'=>0, + 'text' => '', + 'left' => 0, + 'top' => 0, + 'fontSize' => 32, //字号 + 'fontColor' => '255,255,255', //字体颜色 + 'angle' => 0, ); $background = $config['background'];//海报最底层得背景 $backgroundInfo = getimagesize($background); $background = imagecreatefromstring(file_get_contents($background)); $backgroundWidth = $backgroundInfo[0]; //背景宽度 $backgroundHeight = $backgroundInfo[1]; //背景高度 - $imageRes = imageCreatetruecolor($backgroundWidth,$backgroundHeight); + $imageRes = imageCreatetruecolor($backgroundWidth, $backgroundHeight); $color = imagecolorallocate($imageRes, 0, 0, 0); imagefill($imageRes, 0, 0, $color); - imagecopyresampled($imageRes,$background,0,0,0,0,imagesx($background),imagesy($background),imagesx($background),imagesy($background)); - if(!empty($config['image'])){ + imagecopyresampled($imageRes, $background, 0, 0, 0, 0, imagesx($background), imagesy($background), imagesx($background), imagesy($background)); + if (!empty($config['image'])) { foreach ($config['image'] as $key => $val) { - $val = array_merge($imageDefault,$val); + $val = array_merge($imageDefault, $val); $info = getimagesize($val['url']); - $function = 'imagecreatefrom'.image_type_to_extension($info[2], false); - if($val['stream']){ + $function = 'imagecreatefrom' . image_type_to_extension($info[2], false); + if ($val['stream']) { $info = getimagesizefromstring($val['url']); $function = 'imagecreatefromstring'; } $res = $function($val['url']); $resWidth = $info[0]; $resHeight = $info[1]; - $canvas=imagecreatetruecolor($val['width'], $val['height']); + $canvas = imagecreatetruecolor($val['width'], $val['height']); imagefill($canvas, 0, 0, $color); - imagecopyresampled($canvas, $res, 0, 0, 0, 0, $val['width'], $val['height'],$resWidth,$resHeight); - $val['left'] = $val['left']<0?$backgroundWidth- abs($val['left']) - $val['width']:$val['left']; - $val['top'] = $val['top']<0?$backgroundHeight- abs($val['top']) - $val['height']:$val['top']; - imagecopymerge($imageRes,$canvas, $val['left'],$val['top'],$val['right'],$val['bottom'],$val['width'],$val['height'],$val['opacity']);//左,上,右,下,宽度,高度,透明度 + imagecopyresampled($canvas, $res, 0, 0, 0, 0, $val['width'], $val['height'], $resWidth, $resHeight); + $val['left'] = $val['left'] < 0 ? $backgroundWidth - abs($val['left']) - $val['width'] : $val['left']; + $val['top'] = $val['top'] < 0 ? $backgroundHeight - abs($val['top']) - $val['height'] : $val['top']; + imagecopymerge($imageRes, $canvas, $val['left'], $val['top'], $val['right'], $val['bottom'], $val['width'], $val['height'], $val['opacity']);//左,上,右,下,宽度,高度,透明度 } } - if(isset($config['text']) && !empty($config['text'])){ + if (isset($config['text']) && !empty($config['text'])) { foreach ($config['text'] as $key => $val) { - $val = array_merge($textDefault,$val); - list($R,$G,$B) = explode(',', $val['fontColor']); + $val = array_merge($textDefault, $val); + list($R, $G, $B) = explode(',', $val['fontColor']); $fontColor = imagecolorallocate($imageRes, $R, $G, $B); - $val['left'] = $val['left']<0?$backgroundWidth- abs($val['left']):$val['left']; - $val['top'] = $val['top']<0?$backgroundHeight- abs($val['top']):$val['top']; - imagettftext($imageRes,$val['fontSize'],$val['angle'],$val['left'],$val['top'],$fontColor,$val['fontPath'],$val['text']); + $val['left'] = $val['left'] < 0 ? $backgroundWidth - abs($val['left']) : $val['left']; + $val['top'] = $val['top'] < 0 ? $backgroundHeight - abs($val['top']) : $val['top']; + imagettftext($imageRes, $val['fontSize'], $val['angle'], $val['left'], $val['top'], $fontColor, $val['fontPath'], $val['text']); } } ob_start(); - imagejpeg ($imageRes); + imagejpeg($imageRes); imagedestroy($imageRes); $res = ob_get_contents(); ob_end_clean(); - $key = substr(md5(rand(0, 9999)) , 0, 5). date('YmdHis') . rand(0, 999999) . '.jpg'; - return UploadService::getInstance()->setUploadPath($path)->imageStream($key,$res); + $key = substr(md5(rand(0, 9999)), 0, 5) . date('YmdHis') . rand(0, 999999) . '.jpg'; + return UploadService::getInstance()->setUploadPath($path)->imageStream($key, $res); } /* @@ -516,7 +521,7 @@ class UtilService * */ public static function getCurrentController() { - return strtolower(app('http')->getName().'/'.request()->controller().'/'.request()->action()); + return strtolower(app('http')->getName() . '/' . request()->controller() . '/' . request()->action()); } /** @@ -530,32 +535,35 @@ class UtilService curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); $result = curl_exec($curl); - $result = json_decode($result,true); - if(is_array($result)) return ['status'=>false,'msg'=>$result['errcode'].'---'.$result['errmsg']]; - return ['status'=>true]; + $result = json_decode($result, true); + if (is_array($result)) return ['status' => false, 'msg' => $result['errcode'] . '---' . $result['errmsg']]; + return ['status' => true]; } /** * TODO 修改 https 和 http * @param $url $url 域名 - * @param int $type 0 返回https 1 返回 http + * @param int $type 0 返回https 1 返回 http * @return string */ public static function setHttpType($url, $type = 0) { - $domainTop = substr($url,0,5); - if($type){ if($domainTop == 'https') $url = 'http'.substr($url,5,strlen($url)); } - else{ if($domainTop != 'https') $url = 'https:'.substr($url,5,strlen($url)); } + $domainTop = substr($url, 0, 5); + if ($type) { + if ($domainTop == 'https') $url = 'http' . substr($url, 5, strlen($url)); + } else { + if ($domainTop != 'https') $url = 'https:' . substr($url, 5, strlen($url)); + } return $url; } public static function setSiteUrl($image, $siteUrl = '') { - if(!strlen(trim($siteUrl))) $siteUrl = sysConfig('site_url'); - $domainTop = substr($image,0,4); - if($domainTop == 'http') return $image; + if (!strlen(trim($siteUrl))) $siteUrl = sysConfig('site_url'); + $domainTop = substr($image, 0, 4); + if ($domainTop == 'http') return $image; $image = str_replace('\\', '/', $image); - return $siteUrl.$image; + return $siteUrl . $image; } /** @@ -566,16 +574,16 @@ class UtilService public static function CurlFileExist($url) { $ch = curl_init(); - try{ - curl_setopt ($ch, CURLOPT_URL, $url); + try { + curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HEADER, 1); - curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); - curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 10); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); $contents = curl_exec($ch); if (preg_match("/404/", $contents)) return false; if (preg_match("/403/", $contents)) return false; return true; - }catch (\Exception $e){ + } catch (\Exception $e) { return false; } } @@ -588,26 +596,26 @@ class UtilService */ public static function getQRCodePath($url, $name) { - if(!strlen(trim($url)) || !strlen(trim($name))) return false; - try{ + if (!strlen(trim($url)) || !strlen(trim($name))) return false; + try { $uploadType = sysConfig('upload_type'); //TODO 没有选择默认使用本地上传 if (!$uploadType) $uploadType = 1; $siteUrl = sysConfig('site_url'); - if(!$siteUrl) return '请前往后台设置->系统设置->网站域名 填写您的域名格式为:http://域名'; + if (!$siteUrl) return '请前往后台设置->系统设置->网站域名 填写您的域名格式为:http://域名'; $info = []; $outfile = Config::get('qrcode.cache_dir'); $code = new QRcode(); - $wapCodePath = $code->png($url, $outfile.'/'.$name)->getPath(); //获取二维码生成的地址 - $content = file_get_contents('.'.$wapCodePath); + $wapCodePath = $code->png($url, $outfile . '/' . $name)->getPath(); //获取二维码生成的地址 + $content = file_get_contents('.' . $wapCodePath); switch ($uploadType) { case 1 : $info["code"] = 200; $info["name"] = $name; $info["dir"] = $wapCodePath; $info["time"] = time(); - $headerArray=UploadService::getImageHeaders($siteUrl.$info['dir'],1,false); + $headerArray = UploadService::getImageHeaders($siteUrl . $info['dir'], 1, false); $info['size'] = $headerArray['Content-Length']; $info['type'] = $headerArray['Content-Type']; $info["image_type"] = 1; @@ -620,7 +628,7 @@ class UtilService if (is_array($item)) { $info = Qiniu::imageUrl($item['key']); $info['dir'] = UtilService::setHttpType($info['dir']); - $headerArray = UploadService::getImageHeaders( $info['dir']); + $headerArray = UploadService::getImageHeaders($info['dir']); $info['size'] = $headerArray['Content-Length']; $info['type'] = $headerArray['Content-Type']; $info['image_type'] = 2; @@ -638,14 +646,14 @@ class UtilService $serverImageInfo['info']['url'] = UtilService::setHttpType($serverImageInfo['info']['url']); $info['dir'] = $serverImageInfo['info']['url']; $info['thumb_path'] = $serverImageInfo['info']['url']; - $headerArray = UploadService::getImageHeaders($serverImageInfo['info']['url'],1,true); + $headerArray = UploadService::getImageHeaders($serverImageInfo['info']['url'], 1, true); $info['size'] = $headerArray['Content-Length']; $info['type'] = $headerArray['Content-Type']; $info['time'] = time(); $info['image_type'] = 3; break; case 4 : - list($imageUrl,$serverImageInfo) = COS::uploadImageStream($name, $content); + list($imageUrl, $serverImageInfo) = COS::uploadImageStream($name, $content); if (!is_array($serverImageInfo) && !is_object($serverImageInfo)) return $serverImageInfo; if (is_object($serverImageInfo)) $serverImageInfo = $serverImageInfo->toArray(); $serverImageInfo['ObjectURL'] = $imageUrl; @@ -653,7 +661,7 @@ class UtilService $info['name'] = substr(strrchr($serverImageInfo['ObjectURL'], '/'), 1); $info['dir'] = $serverImageInfo['ObjectURL']; $info['thumb_path'] = $serverImageInfo['ObjectURL']; - $headerArray = UploadService::getImageHeaders( $serverImageInfo['ObjectURL'],true); + $headerArray = UploadService::getImageHeaders($serverImageInfo['ObjectURL'], true); $info['size'] = $headerArray['Content-Length']; $info['type'] = $headerArray['Content-Type']; $info['time'] = time(); @@ -663,7 +671,7 @@ class UtilService return '上传类型错误,请先选择文件上传类型'; } return $info; - }catch (\Exception $e){ + } catch (\Exception $e) { return $e->getMessage(); } } @@ -673,19 +681,20 @@ class UtilService * @param string $avatar * @return bool|string */ - public static function setImageBase64($avatar = '',$timeout=9){ - try{ - $url=parse_url($avatar); - $url=$url['host']; + public static function setImageBase64($avatar = '', $timeout = 9) + { + try { + $url = parse_url($avatar); + $url = $url['host']; $header = [ 'User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:45.0) Gecko/20100101 Firefox/45.0', 'Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3', 'Accept-Encoding: gzip, deflate', - 'Host:'.$url + 'Host:' . $url ]; - $dir= pathinfo($url); + $dir = pathinfo($url); $host = $dir['dirname']; - $refer= $host.'/'; + $refer = $host . '/'; $curl = curl_init(); curl_setopt($curl, CURLOPT_REFERER, $refer); curl_setopt($curl, CURLOPT_URL, $avatar); @@ -697,9 +706,9 @@ class UtilService $data = curl_exec($curl); $code = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); - if ($code == 200) return "data:image/jpeg;base64," . base64_encode($data); + if ($code == 200) return "data:image/jpeg;base64," . base64_encode($data); else return false; - }catch (\Exception $e){ + } catch (\Exception $e) { return false; } } diff --git a/crmeb/crmeb/services/WechatService.php b/crmeb/crmeb/services/WechatService.php index 3ebbe834..8e76eff7 100644 --- a/crmeb/crmeb/services/WechatService.php +++ b/crmeb/crmeb/services/WechatService.php @@ -593,7 +593,6 @@ class WechatService $staff = self::staffService(); $staff = is_callable($message) ? $staff->message($message()) : $staff->message($message); $res = $staff->to($to)->send(); - HookService::afterListen('wechat_staff_to',compact('to','message'),$res); return $res; } diff --git a/crmeb/crmeb/services/WechatTemplateService.php b/crmeb/crmeb/services/WechatTemplateService.php index 74dbe750..fe5ad2cc 100644 --- a/crmeb/crmeb/services/WechatTemplateService.php +++ b/crmeb/crmeb/services/WechatTemplateService.php @@ -50,7 +50,7 @@ class WechatTemplateService implements ProviderInterface const ORDER_USER_GROUPS_SUCCESS = 'OPENTM407456411'; //拼团失败通知 - const ORDER_USER_GROUPS_LOSE = 'OPENTM401113750'; + const ORDER_USER_GROUPS_LOSE = 'OPENTM401113750'; //开团成功 const OPEN_PINK_SUCCESS = 'OPENTM414349441'; @@ -58,10 +58,11 @@ class WechatTemplateService implements ProviderInterface //砍价成功 const BARGAIN_SUCCESS = 'OPENTM410292733'; - public static function getConstants($code='') { + public static function getConstants($code = '') + { $oClass = new \ReflectionClass(__CLASS__); - $stants=$oClass->getConstants(); - if($code) return isset($stants[$code]) ? $stants[$code] : ''; + $stants = $oClass->getConstants(); + if ($code) return isset($stants[$code]) ? $stants[$code] : ''; else return $stants; } @@ -79,13 +80,13 @@ class WechatTemplateService implements ProviderInterface * @param string $defaultColor * @return bool */ - public static function sendTemplate($openid,$templateId,array $data,$url = null,$defaultColor = '') + public static function sendTemplate($openid, $templateId, array $data, $url = null, $defaultColor = '') { - $tempid = WechatTemplateModel::where('tempkey',$templateId)->where('status',1)->value('tempid'); - if(!$tempid) return false; - try{ - return WechatService::sendTemplate($openid,$tempid,$data,$url,$defaultColor); - }catch (\Exception $e){ + $tempid = WechatTemplateModel::where('tempkey', $templateId)->where('status', 1)->value('tempid'); + if (!$tempid) return false; + try { + return WechatService::sendTemplate($openid, $tempid, $data, $url, $defaultColor); + } catch (\Exception $e) { dump($e->getMessage()); return false; } @@ -97,24 +98,24 @@ class WechatTemplateService implements ProviderInterface * @param string $defaultColor * @return bool */ - public static function sendAdminNoticeTemplate(array $data,$url = null,$defaultColor = '') + public static function sendAdminNoticeTemplate(array $data, $url = null, $defaultColor = '') { - $adminIds = explode(',',trim(sysConfig('site_store_admin_uids'))); - $kefuIds = ServiceModel::where('notify',1)->column('uid','uid'); - if(empty($adminIds[0])){ + $adminIds = explode(',', trim(sysConfig('site_store_admin_uids'))); + $kefuIds = ServiceModel::where('notify', 1)->column('uid', 'uid'); + if (empty($adminIds[0])) { $adminList = array_unique($kefuIds); - }else{ - $adminList = array_unique(array_merge($adminIds,$kefuIds)); + } else { + $adminList = array_unique(array_merge($adminIds, $kefuIds)); } - if(!is_array($adminList) || empty($adminList)) return false; - foreach ($adminList as $uid){ - try{ + if (!is_array($adminList) || empty($adminList)) return false; + foreach ($adminList as $uid) { + try { $openid = WechatUser::uidToOpenid($uid, 'openid'); - if(!$openid) continue; - }catch (\Exception $e){ + if (!$openid) continue; + } catch (\Exception $e) { continue; } - self::sendTemplate($openid,self::ADMIN_NOTICE,$data,$url,$defaultColor); + self::sendTemplate($openid, self::ADMIN_NOTICE, $data, $url, $defaultColor); } } @@ -129,48 +130,48 @@ class WechatTemplateService implements ProviderInterface /** * 修改账号所属行业 - * 主行业 副行业 代码 - * IT科技 互联网/电子商务 1 - * IT科技 IT软件与服务 2 - * IT科技 IT硬件与设备 3 - * IT科技 电子技术 4 - * IT科技 通信与运营商 5 - * IT科技 网络游戏 6 - * 金融业 银行 7 - * 金融业 基金|理财|信托 8 - * 金融业 保险 9 - * 餐饮 餐饮 10 - * 酒店旅游 酒店 11 - * 酒店旅游 旅游 12 - * 运输与仓储 快递 13 - * 运输与仓储 物流 14 - * 运输与仓储 仓储 15 - * 教育 培训 16 - * 教育 院校 17 - * 政府与公共事业 学术科研 18 - * 政府与公共事业 交警 19 - * 政府与公共事业 博物馆 20 - * 政府与公共事业 公共事业|非盈利机构 21 - * 医药护理 医药医疗 22 - * 医药护理 护理美容 23 - * 医药护理 保健与卫生 24 - * 交通工具 汽车相关 25 - * 交通工具 摩托车相关 26 - * 交通工具 火车相关 27 - * 交通工具 飞机相关 28 - * 房地产 建筑 29 - * 房地产 物业 30 - * 消费品 消费品 31 - * 商业服务 法律 32 - * 商业服务 会展 33 - * 商业服务 中介服务 34 - * 商业服务 认证 35 - * 商业服务 审计 36 - * 文体娱乐 传媒 37 - * 文体娱乐 体育 38 - * 文体娱乐 娱乐休闲 39 - * 印刷 印刷 40 - * 其它 其它 41 + * 主行业 副行业 代码 + * IT科技 互联网/电子商务 1 + * IT科技 IT软件与服务 2 + * IT科技 IT硬件与设备 3 + * IT科技 电子技术 4 + * IT科技 通信与运营商 5 + * IT科技 网络游戏 6 + * 金融业 银行 7 + * 金融业 基金|理财|信托 8 + * 金融业 保险 9 + * 餐饮 餐饮 10 + * 酒店旅游 酒店 11 + * 酒店旅游 旅游 12 + * 运输与仓储 快递 13 + * 运输与仓储 物流 14 + * 运输与仓储 仓储 15 + * 教育 培训 16 + * 教育 院校 17 + * 政府与公共事业 学术科研 18 + * 政府与公共事业 交警 19 + * 政府与公共事业 博物馆 20 + * 政府与公共事业 公共事业|非盈利机构 21 + * 医药护理 医药医疗 22 + * 医药护理 护理美容 23 + * 医药护理 保健与卫生 24 + * 交通工具 汽车相关 25 + * 交通工具 摩托车相关 26 + * 交通工具 火车相关 27 + * 交通工具 飞机相关 28 + * 房地产 建筑 29 + * 房地产 物业 30 + * 消费品 消费品 31 + * 商业服务 法律 32 + * 商业服务 会展 33 + * 商业服务 中介服务 34 + * 商业服务 认证 35 + * 商业服务 审计 36 + * 文体娱乐 传媒 37 + * 文体娱乐 体育 38 + * 文体娱乐 娱乐休闲 39 + * 印刷 印刷 40 + * 其它 其它 41 * @param $industryId1 * @param $industryId2 * @return \EasyWeChat\Support\Collection diff --git a/crmeb/crmeb/services/YLYService.php b/crmeb/crmeb/services/YLYService.php index 2531c116..bc7ea348 100644 --- a/crmeb/crmeb/services/YLYService.php +++ b/crmeb/crmeb/services/YLYService.php @@ -3,48 +3,52 @@ namespace crmeb\services; use app\models\system\Cache as CacheModel; +use crmeb\interfaces\ProviderInterface; +use crmeb\traits\LogicTrait; /** * Class YLYService * @package crmeb\services */ -class YLYService extends HttpService +class YLYService extends HttpService implements ProviderInterface { + use LogicTrait; + /** * 开发者创建的应用的应用ID * @var string */ - protected $client_id; + protected $client_id; /** * 开发者创建的应用的秘钥 * @var string */ - protected $apiKey; + protected $apiKey; /** * 开发者id * @var string */ - protected $partner; + protected $partner; /** * 易联云token * @var null */ - protected $access_token=null; + protected $access_token = null; /** * 订单编号 * @var null */ - protected $order_id=null; + protected $order_id = null; /** * 终端号码 * @var string */ - protected $terminal; + protected $terminal; /** * 打印内容 @@ -56,57 +60,48 @@ class YLYService extends HttpService * 请求地址 * @var string */ - protected $apiUrl = 'https://open-api.10ss.net/'; + protected $apiUrl = 'https://open-api.10ss.net/'; - /** - * 本类实例化句柄 - * @var - */ - protected static $instance; + + public function register($congig = []) + { + + } /** * YLYService constructor. */ protected function __construct() { - $system = SystemConfigService::more(['develop_id','printing_api_key','printing_client_id','terminal_number']); - $this->partner = $system['develop_id'] ?? ''; - $this->apiKey = $system['printing_api_key'] ?? ''; + $system = SystemConfigService::more(['develop_id', 'printing_api_key', 'printing_client_id', 'terminal_number']); + $this->partner = $system['develop_id'] ?? ''; + $this->apiKey = $system['printing_api_key'] ?? ''; $this->client_id = $system['printing_client_id'] ?? ''; - $this->terminal = $system['terminal_number'] ?? ''; + $this->terminal = $system['terminal_number'] ?? ''; $this->getAccessToken(); } - /** - * 实例化本类 - * @return YLYService - */ - public static function getInstance() - { - if(is_null(self::$instance)) self::$instance = new self(); - return self::$instance; - } - /** * 获取AccessToken * */ - protected function getAccessToken(){ + protected function getAccessToken() + { $token = CacheModel::getDbCache('YLY_access_token'); - if(!$token){ - $request = self::postRequest($this->apiUrl.'oauth/oauth',[ + if (!$token) { + $request = self::postRequest($this->apiUrl . 'oauth/oauth', [ 'client_id' => $this->client_id, - 'grant_type'=> 'client_credentials', - 'sign' => strtolower(md5($this->client_id.time().$this->apiKey)), - 'scope' => 'all', + 'grant_type' => 'client_credentials', + 'sign' => strtolower(md5($this->client_id . time() . $this->apiKey)), + 'scope' => 'all', 'timestamp' => time(), - 'id' => $this->createUuid(), + 'id' => $this->createUuid(), ]); - $request = json_decode($request,true); - $request['error'] = $request['error'] ?? 0; + $request = json_decode($request, true); + $request['error'] = $request['error'] ?? 0; $request['error_description'] = $request['error_description'] ?? ''; - if($request['error'] == 0 && $request['error_description'] == 'success'){ + if ($request['error'] == 0 && $request['error_description'] == 'success') { $token = $request['body']['access_token'] ?? ''; - CacheModel::setDbCache('YLY_access_token',$token); + CacheModel::setDbCache('YLY_access_token', $token); } } $this->access_token = $token; @@ -116,9 +111,10 @@ class YLYService extends HttpService * 生成UUID4 * @return string */ - protected function createUuid() { - return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',mt_rand( 0, 0xffff ),mt_rand( 0, 0xffff ),mt_rand( 0, 0xffff ), - mt_rand( 0, 0x0fff )|0x4000,mt_rand( 0, 0x3fff )|0x8000,mt_rand( 0, 0xffff ),mt_rand( 0, 0xffff ),mt_rand( 0, 0xffff )); + protected function createUuid() + { + return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x', mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff), + mt_rand(0, 0x0fff) | 0x4000, mt_rand(0, 0x3fff) | 0x8000, mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)); } /** @@ -129,18 +125,18 @@ class YLYService extends HttpService */ public function orderPrinting(string $order_id = '') { - $request=self::postRequest($this->apiUrl.'print/index',[ - 'client_id' => $this->client_id, - 'access_token' => $this->access_token, - 'machine_code' => $this->terminal, - 'content' => $this->content, - 'origin_id' => $order_id ? $order_id : $this->order_id, - 'sign' => strtolower(md5($this->client_id.time().$this->apiKey)), - 'id' => $this->createUuid(), - 'timestamp' => time() + $request = self::postRequest($this->apiUrl . 'print/index', [ + 'client_id' => $this->client_id, + 'access_token' => $this->access_token, + 'machine_code' => $this->terminal, + 'content' => $this->content, + 'origin_id' => $order_id ? $order_id : $this->order_id, + 'sign' => strtolower(md5($this->client_id . time() . $this->apiKey)), + 'id' => $this->createUuid(), + 'timestamp' => time() ]); - if($request === false) return false; - return json_decode($request,true); + if ($request === false) return false; + return json_decode($request, true); } /** @@ -150,16 +146,16 @@ class YLYService extends HttpService */ public function deletePrinter($machine_code) { - $request = self::postRequest($this->apiUrl.'printer/deleteprinter',[ - 'client_id' => $this->client_id, - 'access_token' => $this->access_token, - 'machine_code' => $machine_code, - 'sign' => strtolower(md5($this->client_id.time().$this->apiKey)), - 'id' => $this->createUuid(), - 'timestamp' => time(), + $request = self::postRequest($this->apiUrl . 'printer/deleteprinter', [ + 'client_id' => $this->client_id, + 'access_token' => $this->access_token, + 'machine_code' => $machine_code, + 'sign' => strtolower(md5($this->client_id . time() . $this->apiKey)), + 'id' => $this->createUuid(), + 'timestamp' => time(), ]); - if($request === false) return false; - return json_decode($request,true); + if ($request === false) return false; + return json_decode($request, true); } /** @@ -169,18 +165,19 @@ class YLYService extends HttpService * @param array $product 订单详情 * @return $this */ - public function setContent(string $name,array $orderInfo,array $product){ - $timeYmd = date('Y-m-d',time()); - $timeHis = date('H:i:s',time()); + public function setContent(string $name, array $orderInfo, array $product) + { + $timeYmd = date('Y-m-d', time()); + $timeHis = date('H:i:s', time()); $goodsStr = '
| 商品名称 | 数量 | 单价 | 金额 |
| {$item['productInfo']['store_name']} | {$item['cart_num']} | {$item['productInfo']['price']} | {$item['truePrice']} | "; - $goodsStr.='
| {$item['productInfo']['store_name']} | {$item['cart_num']} | {$item['productInfo']['price']} | {$item['truePrice']} | "; + $goodsStr .= '