| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537 |
- <?php
- namespace App\Servers;
- use AlibabaCloud\Client\AlibabaCloud;
- use AlibabaCloud\Client\Exception\ClientException;
- use AlibabaCloud\Sts\Sts;
- use App\Models\Config;
- use App\Models\ErrorRecord;
- use App\Models\Region;
- use Illuminate\Support\Facades\Redis;
- use OSS\Core\OssException;
- use OSS\Credentials\EnvironmentVariableCredentialsProvider;
- use OSS\Http\RequestCore_Exception;
- use OSS\OssClient;
- /**
- * 公共服务方法
- */
- class CommonServer
- {
- /**
- * 错误信息
- * @var string
- */
- private $errorMsg = '';
- static private $server = null;
- private function __construct()
- {
- }
- /**
- * 创建对象
- * @return CommonServer
- */
- static function creatServer()
- {
- if (empty(self::$server)) self::$server = new CommonServer();
- return self::$server;
- }
- /**
- * 创建文件夹
- * @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;
- }
- /**
- * redis 滑动窗口节流阀
- * @param $key
- * @param $num //允许的请求次数
- * @param $secs //时间段(秒)
- * @return bool
- */
- function redisThrottler($key ,$num ,$secs){
- try {
- //获取当前时间戳
- $nowTime=time();
- //获取队列长度
- $length=Redis::lLen($key);
- //如果长度没到限制数量就通过
- if($length<$num){
- //当前请求的时间入队
- Redis::lPush($key,$nowTime);
- Redis::expire($key,$secs);
- return true;
- }
- //队列满了,取出最早访问的时间
- $startTime= Redis::lIndex($key,$length-1);
- //计算当前时间和最早一次请求的时间差,如果在规定的时间范围,则不允许通过
- if ($nowTime-$startTime <= $secs) {
- return false;
- } else {
- //如果不在规定的时间范围,证明最早的请求过期,就去掉最早期的再把当前的请求入队
- Redis::rPop($key);
- Redis::lPush($key,$nowTime);
- Redis::expire($key,$secs);
- }
- return true;
- }catch (\Exception $e){
- var_dump($e->getMessage());
- return true;
- }
- }
- /**
- * 指定路由加锁
- * @param $lock_key
- * @param $lock_value
- * @param $routeName
- * @return bool
- */
- function lockSpecifyRoutes($lock_key,$lock_value,$routeName){
- $routeArr= [
- 'withdraw.withdraw',
- ];
- if(in_array($routeName,$routeArr)){
- $lock = RedisDataServer::creatServer()->lockKey($lock_key,$lock_value,1000);
- if(!$lock){//拿不到锁
- return false;
- }
- }
- return true;
- }
- /**
- * 获取数据库配置信息
- * @param $key
- * @return mixed
- */
- function getConfigValue($key)
- {
- return Config::where('key', $key)->value('value');
- }
- /**
- * 生成订单编号
- * @param $prefix
- * @return string
- */
- function createOrderNo($prefix='')
- {
- return $prefix.date('YmdHi').substr(implode('', array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8) . rand(100,999);
- }
- /**
- * 生成唯一码
- * @param $key
- * @return string
- */
- function getOnlyCode($key)
- {
- $total_count = RedisDataServer::creatServer()->getData($key);
- if (empty($total_count)){
- $total_count = rand(100,300);
- // 获取当前时间戳
- $now = time();
- // 获取今天结束的时间戳
- $endOfDay = strtotime("tomorrow") - 1;
- // 计算剩余时间(秒)
- $secondsLeft = bcsub($endOfDay,$now,1);
- RedisDataServer::creatServer()->setData($key,$total_count,'str',$secondsLeft);
- }
- RedisDataServer::creatServer()->setIncr($key);
- return date('md') . $total_count;
- }
- /**
- * @param $str
- * @return array|string|string[]|null
- */
- function utf8_filter($str)
- {
- $pattern = '/[^\x{4e00}-\x{9fa5}\w]/u';
- // 使用正则表达式替换为空字符串
- $data = preg_replace($pattern, '', $str);
- return $data;
- }
- /**
- * 字符串去标签过滤及空格过滤
- * @param $str_name
- * @param $default
- * @return string
- */
- function filtrationStr($str_name, $default = '')
- {
- $str = request()->input($str_name);
- if (empty($str)) {
- return $default;
- };
- if (is_string($str)){
- $str = strip_tags($str);
- $str = trim($str);
- }elseif (is_array($str)){
- $data = [];
- foreach ($str as $value){
- $value = strip_tags($value);
- $data[] = trim($value);
- }
- $str = $data;
- }else{
- $str = json_encode($str);
- $str = strip_tags($str);
- $str = trim($str);
- $str = json_decode($str, true);
- }
- return $str;
- }
- /**
- * 手机号码验证
- * @param $phone
- * @return bool
- */
- function verifyPhone($phone)
- {
- if (empty($phone)) return false;
- if (!preg_match('/^1[3-9]\d{9}$/', $phone)){
- return false;
- }
- return true;
- }
- // /**
- // * 获取阿里云sts临时权限 旧版alibabacloud/sdk包
- // */
- // 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-chengdu')->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::1816998012508375:role/ramosstest",
- // '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()];
- // }
- // }
- // return ['code' => 1, 'msg' => '获取信息成功', 'data' => $data];
- //
- // }
- /**
- * 获取阿里云sts临时权限 alibabacloud/sts包
- */
- function getAliSts()
- {
- $data = RedisDataServer::creatServer()->getData('sts_data');
- if ($data) {
- $data = json_decode($data, true);
- } else {
- // 配置你的AccessKeyId和AccessKeySecret
- $accessKeyId = config('aliyun.oss.access_id');
- $accessKeySecret = config('aliyun.oss.access_key');
- AlibabaCloud::accessKeyClient($accessKeyId,$accessKeySecret)
- ->regionId('cn-chengdu')
- ->asDefaultClient();
- try {
- $request = Sts::v20150401()->assumeRole();
- $result = $request
- ->withRoleArn("acs:ram::1816998012508375:role/ramosstest")
- ->withRoleSessionName("js-oss-serve")
- ->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()];
- }
- }
- return ['code' => 1, 'msg' => '获取信息成功', 'data' => $data];
- }
- /**
- * oss上传
- */
- function uploadAliOss($filePath,$path = 'images')
- {
- // 配置信息
- $accessKeyId = config('aliyun.oss.access_id');
- $accessSecret = config('aliyun.oss.access_key');
- $endpoint = "oss-cn-chengdu.aliyuncs.com"; // 如 oss-cn-hangzhou.aliyuncs.com
- $bucket= config('aliyun.oss.bucket'); // OSS中的存储空间名称
- // 初始化
- try {
- $ossClient = new OssClient($accessKeyId, $accessSecret, $endpoint);
- $upload_path = "files" . DIRECTORY_SEPARATOR . $path . DIRECTORY_SEPARATOR . date('Ymd', time()) . DIRECTORY_SEPARATOR;
- $extension = pathinfo($filePath, PATHINFO_EXTENSION);
- $object = $upload_path . md5(uniqid() . time()) . $extension; // OSS中的文件路径和名称
- // 上传文件
- $ossClient->uploadFile($bucket, $object, $filePath);
- return ['code' => 1, 'msg' => '上传成功','data'=>$object];
- } catch (OssException $e) {
- return ['code' => 0, 'msg' => $e->getMessage()];
- }
- }
- /**
- * 删除oss文件
- * @param $filePath
- * @return bool
- * @throws RequestCore_Exception
- */
- function delAliOss($filePath)
- {
- // 配置信息
- $accessKeyId = config('aliyun.oss.access_id');
- $accessSecret = config('aliyun.oss.access_key');
- $endpoint = "oss-cn-chengdu.aliyuncs.com"; // 如 oss-cn-hangzhou.aliyuncs.com
- $bucket= config('aliyun.oss.bucket'); // OSS中的存储空间名称
- try {
- $ossClient = new OssClient($accessKeyId, $accessSecret, $endpoint);
- // 删除文件
- $ossClient->deleteObject($bucket, urldecode($filePath));
- return true;
- } catch (OssException $e) {
- ErrorRecord::create(['msg' => '阿里云oss删除失败', 'data' => json_encode($filePath,JSON_UNESCAPED_UNICODE)]);
- return false;
- }
- }
- /**
- * 获取城市名称
- * @param $province_id
- * @param $city_id
- * @param $area_id
- * @param $street_id
- * @return string
- */
- function getCityName($province_id = 0, $city_id = 0, $area_id = 0, $street_id = 0)
- {
- $area_arr = [$province_id, $city_id, $area_id, $street_id];
- $area_arr = array_filter($area_arr);
- if ($area_arr) {
- $region = Region::whereIn('id', $area_arr)->orderBy('id', 'asc')->pluck('name')->toArray();
- $city_name = implode(' ', $region);
- } else {
- $city_name = '';
- }
- return $city_name;
- }
- /**
- * 获取两个经纬度直接距离
- * @param $lat1
- * @param $lng1
- * @param $lat2
- * @param $lng2
- * @return float
- */
- 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);
- }
- /**
- * 获取真实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];
- }
- }
- /**
- * 截取字符串
- * @param $string
- * @param $limit
- * @param $suffix
- * @return mixed|string
- */
- function truncateChineseString($string, $limit = 100, $suffix = '...') {
- if (mb_strlen($string, 'UTF-8') <= $limit) {
- // 如果字符串长度没有超过限制,直接返回
- return $string;
- }
- // 截取前 $limit 个汉字
- $truncated = mb_substr($string, 0, $limit, 'UTF-8');
- // 确保截取后的字符串是完整的汉字,不会被截断
- // 如果最后一个字符不是汉字,则需要回溯到上一个汉字的位置
- // $lastChar = mb_substr($truncated, -1, 1, 'UTF-8');
- // if (preg_match('/[^\x{4e00}-\x{9fa5}]/u', $lastChar)) {
- // // 最后一个字符不是汉字,回溯到上一个汉字
- // $truncated = mb_substr($string, 0, mb_strrpos($truncated, mb_substr($string, 0, mb_strlen($truncated, 'UTF-8') - 1, 'UTF-8'), 'UTF-8'), 'UTF-8');
- // }
- // 添加省略号
- return $truncated . $suffix;
- }
- /**
- * 处理图片压缩
- * @param $img
- * @param $str
- * @return string
- */
- function setImageCompress($img,$str)
- {
- //查找链接中?出现的位置
- $find = strrpos($img ,'?');
- if (!$find){//没有就直接拼接
- return $img . '?' . $str;
- }else{
- $url = substr($img,0,$find);
- return $url . '?' . $str;
- }
- }
- /**
- * 获取随机字符串
- * @param int $length
- * @param string $strPol
- * @return string|null
- */
- 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 $num
- * @param $decimals
- * @return string
- */
- function truncateDecimal($num, $decimals = 2) {
- $factor = pow(10, $decimals);
- $truncated = (int)($num * $factor) / $factor;
- return number_format($truncated, $decimals, '.', '');
- }
- /**
- * @param $url
- * @param string $type 请求方式
- * @param string $data 数据 数组格式
- * @return mixed
- */
- function sendRequest($url, $type = 'get', $data = '')
- {
- $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);
- $head = array('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');
- 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);
- return $request;
- }
- }
|