| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531 |
- <?php
- namespace App\Servers;
- use AlibabaCloud\Client\AlibabaCloud;
- use AlibabaCloud\Ecs\Ecs;
- use AlibabaCloud\Green\Green;
- use App\Models\Config;
- use App\Models\ErrorRecord;
- use App\Models\Region;
- use Illuminate\Support\Facades\Storage;
- use AlibabaCloud\Client\Exception\ClientException;
- use AlibabaCloud\Client\Exception\ServerException;
- /**
- * Redis数据缓存类
- */
- 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 $phone
- * @return bool
- */
- public function verifyPhoneNumber($phone)
- {
- if (empty($phone)) return false;
- if (!preg_match('#^[\d]{11,11}$#', $phone)) {
- return false;
- }
- return true;
- }
- /**
- * 字符串去标签过滤及空格过滤
- * @param $str_name
- * @param $default
- * @return string
- */
- function filtrationStr($str_name, $default = '')
- {
- $str = request()->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];
- }
- /**
- * 阿里云图片鉴定
- * @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;
- }
- }
|