input($str_name, $default); if (empty($str)) return $str; if (!is_string($str)) { $str = json_encode($str); $str = strip_tags($str); $str = trim($str); $str = json_decode($str, true); } else { $str = strip_tags($str); $str = trim($str); } return $str; } /** * 获取城市名称 * @param string $province_id * @param string $city_id * @param string $area_id * @return string */ function getCityName($province_id = '', $city_id = '', $area_id = '') { $ids = [$province_id, $city_id, $area_id]; $ids = array_filter($ids); if (empty($ids)) return ''; $city_name = Region::whereIn('id', $ids)->orderBy('id', 'asc')->pluck('name')->toArray(); $city_name = implode(' ', $city_name); return $city_name; } /** * 字符串屏蔽 * @param $str * @param int $start_key 开始位置 * @param int $end_key 尾数开始位置 * @param int $start_num 截取位数 * @param int $end_num 倒数截取位数 * @param int $conceal_num 最大填充数量 * @return string */ function concealStr($str, $start_key = 0, $end_key = 1, $start_num = 1, $end_num = 1, $conceal_num = 3) { $str_len = mb_strlen($str); $start_str = ''; $end_str = ''; if (($str_len - $start_num - $end_num) < $conceal_num) { $conceal_num = $str_len - $start_num - $end_num; } $conceal_str = $this->getRandChar($conceal_num, '*'); if (empty($conceal_str)) $conceal_str = '*'; if ($str_len >= $start_key) { $start_str = mb_substr($str, $start_key, $start_num); } if ($str_len > $end_key) { $end_str = mb_substr($str, $end_key * -1, $end_num); } return $start_str . $conceal_str . $end_str; } /** * 获取随机字符串 * @param int $length * @param string $strPol * @return string|null */ public function getRandChar($length = 6, $strPol = '') { if ($length <= 0) $length = 1; $str = null; if (empty($strPol)) $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz"; $max = strlen($strPol) - 1; for ($i = 0; $i < $length; $i++) { $str .= $strPol[rand(0, $max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数 } return $str; } /** * 获取数据库配置信息 * @param $key * @return mixed */ function getConfigValue($key) { return Config::where('key', $key)->value('value'); } /** * 创建文件夹 * @param $dir * @return bool */ function creatDir($dir) { if ($dir == '') return false; if (!file_exists(public_path($dir))) { mkdir(public_path($dir), 0777, true); chmod(public_path($dir), 0777); } return true; } /** * 获取本月1号至月底 * @param $date * @return array */ function getNextMonth($date) { $first_day = date("Y-m-01 00:00:00", strtotime($date)); $next_day = date("Y-m-d 23:59:59", strtotime("$first_day +1 month -1 day")); return [$first_day, $next_day]; } /** * 获取多少天后的日期 * @param $date * @param $num * @return false|string */ function getManyDate($date, $num) { if(!is_numeric($num) || $num==0){ return $date; } if($num>0){ $next_day = date("Y-m-d", strtotime("$date +$num day")); }else{ $next_day = date("Y-m-d", strtotime("$date $num day")); } return $next_day; } /** * 验证是否微信浏览器 * @return bool */ function isWeixin() { $http_user_agent = request()->header('user-agent'); if (strpos($http_user_agent, 'MicroMessenger') !== false) { return true; } return false; } /** * 格式化小数位数 * @param $num * @param int $digit * @return string */ function setFloatNum($num, $digit = 4) { return sprintf("%.{$digit}f", $num); } /** * 获取真实IP * @return mixed */ function getClientIp() { $http_x_forwarded_for = request()->header('x-forwarded-for'); if (empty($http_x_forwarded_for)) { return request()->getClientIp(); } else { $http_x_forwarded_for = explode(',', $http_x_forwarded_for); return $http_x_forwarded_for[0]; } } function delDir($dir) { //先删除目录下的文件: $dh = opendir($dir); while ($file = readdir($dh)) { if ($file != "." && $file != "..") { $fullpath = $dir . "/" . $file; if (!is_dir($fullpath)) { unlink($fullpath); } else { $this->deldir($fullpath); } } } closedir($dh); //删除当前文件夹: if (rmdir($dir)) { return true; } else { return false; } } /** * 图片base64 * @param $image_file * @return string */ function base64EncodeImage($image_file) { $image_info = getimagesize($image_file); $image_data = fread(fopen($image_file, 'r'), filesize($image_file)); $base64_image = 'data:' . $image_info['mime'] . ';base64,' . chunk_split(base64_encode($image_data)); return $base64_image; } /** * 图片上传OSS * @param $img * @param string $path * @param $is_compress * @return string */ function uploadingImg($img, $path = 'headimgurl',$is_compress=true) { $base64_image_content = file_get_contents($img); $upload_path = "storage" . DIRECTORY_SEPARATOR . $path . DIRECTORY_SEPARATOR . date('Ymd', time()) . DIRECTORY_SEPARATOR; $img_url = md5(uniqid() . time()) . '.png'; $upload_path1 = public_path($upload_path); if (!is_dir($upload_path1)) { mkdir($upload_path1, 0777, true); } $oss = Storage::disk('oss'); $pathA = "{$upload_path}{$img_url}"; $update = $oss->put($pathA, $base64_image_content); if (!$update) { // 如果失败上传本地 file_put_contents($upload_path1 . $img_url, base64_decode($base64_image_content)); } return $update ? ($oss->url($pathA) . ($is_compress?'?x-oss-process=image/auto-orient,1/quality,q_85':'')) : asset($pathA); } /** * OSS图片压缩 * @param $img * @param int $resize (3,10,30,50) * @param int $type 1原比例压缩,2固定高宽比列压缩(300*300) * @return string|string[] */ function ossCompress($img, $resize = 10, $type = 1) { $old_str=strrchr($img, '?'); if($old_str)$img=str_replace($old_str, '', $img); if ($type == 1) { return $img . '?x-oss-process=image/auto-orient,1/resize,p_' . $resize . '/quality,q_90'; } elseif ($type == 2) { return $img . '?x-oss-process=image/auto-orient,1/resize,m_fill,w_300,h_300/quality,q_90'; } elseif ($type == 3) { return $img . '?x-oss-process=image/auto-orient,1/resize,m_lfit,w_780/quality,q_100'; } return $img; } /** * 保留2为小数 * @param $num * @param int $format_num * @return float|int */ function setFormatNum($num,$format_num=2){ // return $num; $format_num=4; if(!is_numeric($num)){ return 0; } if($format_num<0){ return $num; }elseif ($format_num==0){ return floor($num); }else{ $num= sprintf("%.{$format_num}f", $num); // $multiple=pow(10,$format_num); // $num = floor($num*$multiple)/$multiple; } $num=$num*1; return $num; } /** * oss图片删除 * @param $path * @return bool */ function delImg($path) { $path_num = stripos($path, '?'); if ($path_num !== false) { $path = substr($path, 0, $path_num); } $path = str_replace('https://jhnewshop.oss-cn-chengdu.aliyuncs.com', '', $path); $oss = Storage::disk('oss'); $update = $oss->delete($path); return $update; } /** * 获取阿里云sts临时权限 */ function getAliSts() { $data = RedisDataServer::creatServer()->getData('sts_data'); if ($data) { $data = json_decode($data, true); } else { $accessKeyId = env('ALI_OSS_ACCESS_ID'); $accessSecret = env('ALI_OSS_ACCESS_KEY'); AlibabaCloud::accessKeyClient($accessKeyId, $accessSecret)->regionId('cn-hangzhou')->asDefaultClient(); //设置参数,发起请求。 try { $result = AlibabaCloud::rpc() ->product('Sts') ->scheme('https') // https | http ->version('2015-04-01') ->action('AssumeRole') ->method('POST') ->host('sts.aliyuncs.com') ->options([ 'query' => [ 'RegionId' => "cn-chengdu", 'RoleArn' => "acs:ram::1470797691368660:role/oss-js", 'RoleSessionName' => "js-oss-serve", 'DurationSeconds' => 900, ], ]) ->request(); $result = $result->toArray(); if (empty($result['Credentials'])) { return ['code' => 0, 'msg' => '获取token信息失败']; } $data = $result['Credentials']; unset($data['Expiration']); RedisDataServer::creatServer()->setData('sts_data', $data, 'json', 800); } catch (ClientException $e) { return ['code' => 0, 'msg' => $e->getErrorMessage()]; } catch (ServerException $e) { return ['code' => 0, 'msg' => $e->getErrorMessage()]; } } return ['code' => 1, 'msg' => '获取信息成功', 'data' => $data]; } function getTxySts(){ $data = RedisDataServer::creatServer()->getData('txy_sts_data'); if ($data ) { $data = json_decode($data, true); } else { $sts = new Sts(); $accessKeyId = env('TXY_OSS_ACCESS_ID'); $accessSecret = env('TXY_OSS_ACCESS_KEY'); $config = array( 'url' => 'https://sts.tencentcloudapi.com/', // url和domain保持一致 'domain' => 'sts.tencentcloudapi.com', // 域名,非必须,默认为 sts.tencentcloudapi.com 'proxy' => '', 'secretId' => $accessKeyId, // 固定密钥,若为明文密钥,请直接以'xxx'形式填入,不要填写到getenv()函数中 'secretKey' => $accessSecret, // 固定密钥,若为明文密钥,请直接以'xxx'形式填入,不要填写到getenv()函数中 'bucket' => 'wealfavor-1257406827', // 换成你的 bucket 'region' => 'ap-beijing', // 换成 bucket 所在园区 'durationSeconds' => 1800, // 密钥有效期 'allowPrefix' => 'app-serve/*', // 这里改成允许的路径前缀,可以根据自己网站的用户登录态判断允许上传的具体路径,例子: a.jpg 或者 a/* 或者 * (使用通配符*存在重大安全风险, 请谨慎评估使用) // 密钥的权限列表。简单上传和分片需要以下的权限,其他权限列表请看 https://cloud.tencent.com/document/product/436/31923 'allowActions' => array ( // 简单上传 'name/cos:PutObject', 'name/cos:PostObject', // 分片上传 'name/cos:InitiateMultipartUpload', 'name/cos:ListMultipartUploads', 'name/cos:ListParts', 'name/cos:UploadPart', 'name/cos:CompleteMultipartUpload' ) ); // dd($config); try { $result = $sts->getTempKeys($config); if(empty($result['credentials'])){ return ['code' => 0, 'msg' => '权限生成失败']; } $data = $result['credentials']; $data['StartTime']=time(); $data['ExpiredTime']=time()+1700; RedisDataServer::creatServer()->setData('txy_sts_data', $data, 'json', 800); } catch (\Exception $e) { return ['code' => 0, 'msg' => $e->getMessage()]; } } return ['code' => 1, 'msg' => '获取信息成功', 'data' => $data]; } /** * 阿里云图片鉴定 * @param $imges * @return array|bool * @throws ClientException * @throws ServerException */ function sendAliImgAuth($imges) { if (is_string($imges)) $imges = [$imges]; $tasks = []; $auth_status = 1; foreach ($imges as $key => $img) { $tasks[] = [ 'dataId' => $key . '-img' . rand(10000000, 99999999) . '-' . time(), 'url' => $img, 'status' => 0, ]; } $accessKeyId = env('ALI_OSS_ACCESS_ID'); $accessSecret = env('ALI_OSS_ACCESS_KEY'); AlibabaCloud::accessKeyClient($accessKeyId, $accessSecret)->regionId('cn-shanghai')->asDefaultClient(); $request = Green::v20180509()->ImageSyncScan(); $request->method('POST') ->scheme('https') // https | http ->body(json_encode([ 'scenes' => ['porn', 'terrorism'], 'tasks' => $tasks, ])); $ret = $request->request(); $ret_data = $ret->toArray(); if (empty($ret_data['code']) || $ret_data['code'] != 200) { return $auth_status; } else { foreach ($ret_data['data'] as $key => $item) { $status = 1; if ($auth_status != 1) { break; } foreach ($item['results'] as $value) { if ($value['suggestion'] == 'review') { $status = 0; $auth_status = 0; break; } elseif ($value['suggestion'] == 'block') { $status = 2; $auth_status = 2; break; } } $tasks[$key]['status'] = $status; } } return ['auth_status' => $auth_status, 'tasks' => $tasks]; } /** * 阿里云视频鉴定 * @param $video 视频地址 * @param int $type 鉴定类型 * @param int $id 任务ID * @return bool * @throws ClientException * @throws ServerException */ function sendAliVideoAuth($video, $type = 1, $id = 0) { $tasks = [ [ 'dataId' => $id . '-video' . rand(10000000, 99999999) . '-' . time(), 'url' => $video, 'interval' => 5, ] ]; $accessKeyId = env('ALI_OSS_ACCESS_ID'); $accessSecret = env('ALI_OSS_ACCESS_KEY'); AlibabaCloud::accessKeyClient($accessKeyId, $accessSecret)->regionId('cn-shanghai')->asDefaultClient(); $request = Green::v20180509()->videoAsyncScan(); $request->method('POST') ->scheme('https') // https | http ->body(json_encode([ 'callback' => route('notify.video-auth', ['type' => $type, 'id' => $id]), 'seed' => $id . '-video' . rand(10000000, 99999999), 'scenes' => ['porn', 'terrorism'], 'tasks' => $tasks, ])); $ret = $request->request(); $ret_data = $ret->toArray(); if (empty($ret_data['code']) || $ret_data['code'] != 200) { ErrorRecord::create(['msg' => '视频鉴定任务提交失败', 'data' => json_encode(compact('id', 'type', 'video'))]); return false; } return true; } /** * 获取文件名 * @param $url * @return string */ function getFileName($url) { $name = basename($url); return empty($name) ? '' : $name; } function lockCapitalRoutes($mId,$routeName,$type){ $routeArr= [ 'rush.session-pay', 'rush.order-pay', 'rush.putaway-goods', 'change.save',//划转 'dealOrder.create',//转赠 'member.set_wallet',//修改钱包地址 'order.create',//商城购买 'order.pay',//商城支付 'recharge.save',//充值提交 'withdraw.withdraw',//提现 ]; if(in_array($routeName,$routeArr)){ $redisName=$mId.'lockCapital'; if($type){ $row= RedisDataServer::creatServer()->getData($redisName); $isOutput= RedisDataServer::creatServer()->getData('dateOutput'); if($row || $isOutput){ return false; } RedisDataServer::creatServer()->setData($redisName,time(),'str',3,false); }else{ RedisDataServer::creatServer()->delData($redisName); } } return true; } //两个经纬度直接距离 function getDistance($lat1, $lng1, $lat2, $lng2){ $lat1 = ($lat1 * pi() ) / 180; $lng1 = ($lng1 * pi() ) / 180; $lat2 = ($lat2 * pi() ) / 180; $lng2 = ($lng2 * pi() ) / 180; $calcLongitude = $lng2 - $lng1; $calcLatitude = $lat2 - $lat1; $dist = 2 * asin(sqrt(pow(sin($calcLatitude/2),2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude/2),2))); $dist = $dist * 6378.137; return round($dist, 2); } function utf8_filter($str) { $pattern = '/[^\x{4e00}-\x{9fa5}\w]/u'; // 使用正则表达式替换为空字符串 $data = preg_replace($pattern, '', $str); return $data; } static function writeLog($text,$path='comm') { if(is_array($text) || is_object($text)){ $text = json_encode($text,JSON_UNESCAPED_SLASHES); } $logDir = public_path('/storage/log/'.$path.'/'.date('Ymd').'/') ; if(!is_dir($logDir)){ mkdir($logDir,0777,true); } file_put_contents ( $logDir.$path.date("Y-m-d").".log", date("Y-m-d H:i:s") . " Log" . $text . "\r\n", FILE_APPEND ); } /** * @param $url * @param string $type 请求方式 * @param string $data 数据 数组格式 * @param $head * @param $retType * @return mixed */ function sendRequest($url, $data = '', $type = 'get',$head=[],$retType='json') { $ch = curl_init(); if ($type == 'get' && $data) { $url = $url . '?' . http_build_query($data); } curl_setopt($ch, CURLOPT_URL, $url); //设置访问路径 curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); //设置可以返回字符串 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); if(empty($head)){ $head = [ 'User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36', 'Content-Type: application/json' ]; } curl_setopt($ch, CURLOPT_HTTPHEADER, $head); if ($type == 'post') { curl_setopt($ch, CURLOPT_POST, TRUE);//post请求 $data = json_encode($data, JSON_UNESCAPED_UNICODE); curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//设置传递的参数 } $request = curl_exec($ch); curl_close($ch); if($request){ if($retType=='gzip'){ $request=gzdecode($request); } $request=json_decode($request,true); } return $request; } }