CommonServer.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. <?php
  2. namespace App\Servers;
  3. use AlibabaCloud\Client\AlibabaCloud;
  4. use AlibabaCloud\Ecs\Ecs;
  5. use AlibabaCloud\Green\Green;
  6. use App\Models\Config;
  7. use App\Models\ErrorRecord;
  8. use App\Models\Region;
  9. use Illuminate\Support\Facades\Storage;
  10. use AlibabaCloud\Client\Exception\ClientException;
  11. use AlibabaCloud\Client\Exception\ServerException;
  12. /**
  13. * Redis数据缓存类
  14. */
  15. class CommonServer
  16. {
  17. /**
  18. * 错误信息
  19. * @var string
  20. */
  21. private $errorMsg = '';
  22. static private $server = null;
  23. private function __construct()
  24. {
  25. }
  26. /**
  27. * 创建对象
  28. * @return CommonServer
  29. */
  30. static function creatServer()
  31. {
  32. if (empty(self::$server)) self::$server = new CommonServer();
  33. return self::$server;
  34. }
  35. /**
  36. * 验证手机号码格式
  37. * @param $phone
  38. * @return bool
  39. */
  40. public function verifyPhoneNumber($phone)
  41. {
  42. if (empty($phone)) return false;
  43. if (!preg_match('#^[\d]{11,11}$#', $phone)) {
  44. return false;
  45. }
  46. return true;
  47. }
  48. /**
  49. * 字符串去标签过滤及空格过滤
  50. * @param $str_name
  51. * @param $default
  52. * @return string
  53. */
  54. function filtrationStr($str_name, $default = '')
  55. {
  56. $str = request()->input($str_name, $default);
  57. if (empty($str)) return $str;
  58. if (!is_string($str)) {
  59. $str = json_encode($str);
  60. $str = strip_tags($str);
  61. $str = trim($str);
  62. $str = json_decode($str, true);
  63. } else {
  64. $str = strip_tags($str);
  65. $str = trim($str);
  66. }
  67. return $str;
  68. }
  69. /**
  70. * 获取城市名称
  71. * @param string $province_id
  72. * @param string $city_id
  73. * @param string $area_id
  74. * @return string
  75. */
  76. function getCityName($province_id = '', $city_id = '', $area_id = '')
  77. {
  78. $ids = [$province_id, $city_id, $area_id];
  79. $ids = array_filter($ids);
  80. if (empty($ids)) return '';
  81. $city_name = Region::whereIn('id', $ids)->orderBy('id', 'asc')->pluck('name')->toArray();
  82. $city_name = implode(' ', $city_name);
  83. return $city_name;
  84. }
  85. /**
  86. * 字符串屏蔽
  87. * @param $str
  88. * @param int $start_key 开始位置
  89. * @param int $end_key 尾数开始位置
  90. * @param int $start_num 截取位数
  91. * @param int $end_num 倒数截取位数
  92. * @param int $conceal_num 最大填充数量
  93. * @return string
  94. */
  95. function concealStr($str, $start_key = 0, $end_key = 1, $start_num = 1, $end_num = 1, $conceal_num = 3)
  96. {
  97. $str_len = mb_strlen($str);
  98. $start_str = '';
  99. $end_str = '';
  100. if (($str_len - $start_num - $end_num) < $conceal_num) {
  101. $conceal_num = $str_len - $start_num - $end_num;
  102. }
  103. $conceal_str = $this->getRandChar($conceal_num, '*');
  104. if (empty($conceal_str)) $conceal_str = '*';
  105. if ($str_len >= $start_key) {
  106. $start_str = mb_substr($str, $start_key, $start_num);
  107. }
  108. if ($str_len > $end_key) {
  109. $end_str = mb_substr($str, $end_key * -1, $end_num);
  110. }
  111. return $start_str . $conceal_str . $end_str;
  112. }
  113. /**
  114. * 获取随机字符串
  115. * @param int $length
  116. * @param string $strPol
  117. * @return string|null
  118. */
  119. public function getRandChar($length = 6, $strPol = '')
  120. {
  121. if ($length <= 0) $length = 1;
  122. $str = null;
  123. if (empty($strPol)) $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
  124. $max = strlen($strPol) - 1;
  125. for ($i = 0; $i < $length; $i++) {
  126. $str .= $strPol[rand(0, $max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
  127. }
  128. return $str;
  129. }
  130. /**
  131. * 获取数据库配置信息
  132. * @param $key
  133. * @return mixed
  134. */
  135. function getConfigValue($key)
  136. {
  137. return Config::where('key', $key)->value('value');
  138. }
  139. /**
  140. * 创建文件夹
  141. * @param $dir
  142. * @return bool
  143. */
  144. function creatDir($dir)
  145. {
  146. if ($dir == '') return false;
  147. if (!file_exists(public_path($dir))) {
  148. mkdir(public_path($dir), 0777, true);
  149. chmod(public_path($dir), 0777);
  150. }
  151. return true;
  152. }
  153. /**
  154. * 获取本月1号至月底
  155. * @param $date
  156. * @return array
  157. */
  158. function getNextMonth($date)
  159. {
  160. $first_day = date("Y-m-01 00:00:00", strtotime($date));
  161. $next_day = date("Y-m-d 23:59:59", strtotime("$first_day +1 month -1 day"));
  162. return [$first_day, $next_day];
  163. }
  164. /**
  165. * 获取多少天后的日期
  166. * @param $date
  167. * @param $num
  168. * @return false|string
  169. */
  170. function getManyDate($date, $num)
  171. {
  172. if(!is_numeric($num) || $num==0){
  173. return $date;
  174. }
  175. if($num>0){
  176. $next_day = date("Y-m-d", strtotime("$date +$num day"));
  177. }else{
  178. $next_day = date("Y-m-d", strtotime("$date $num day"));
  179. }
  180. return $next_day;
  181. }
  182. /**
  183. * 验证是否微信浏览器
  184. * @return bool
  185. */
  186. function isWeixin()
  187. {
  188. $http_user_agent = request()->header('user-agent');
  189. if (strpos($http_user_agent, 'MicroMessenger') !== false) {
  190. return true;
  191. }
  192. return false;
  193. }
  194. /**
  195. * 格式化小数位数
  196. * @param $num
  197. * @param int $digit
  198. * @return string
  199. */
  200. function setFloatNum($num, $digit = 4)
  201. {
  202. return sprintf("%.{$digit}f", $num);
  203. }
  204. /**
  205. * 获取真实IP
  206. * @return mixed
  207. */
  208. function getClientIp()
  209. {
  210. $http_x_forwarded_for = request()->header('x-forwarded-for');
  211. if (empty($http_x_forwarded_for)) {
  212. return request()->getClientIp();
  213. } else {
  214. $http_x_forwarded_for = explode(',', $http_x_forwarded_for);
  215. return $http_x_forwarded_for[0];
  216. }
  217. }
  218. function delDir($dir)
  219. {
  220. //先删除目录下的文件:
  221. $dh = opendir($dir);
  222. while ($file = readdir($dh)) {
  223. if ($file != "." && $file != "..") {
  224. $fullpath = $dir . "/" . $file;
  225. if (!is_dir($fullpath)) {
  226. unlink($fullpath);
  227. } else {
  228. $this->deldir($fullpath);
  229. }
  230. }
  231. }
  232. closedir($dh);
  233. //删除当前文件夹:
  234. if (rmdir($dir)) {
  235. return true;
  236. } else {
  237. return false;
  238. }
  239. }
  240. /**
  241. * 图片base64
  242. * @param $image_file
  243. * @return string
  244. */
  245. function base64EncodeImage($image_file)
  246. {
  247. $image_info = getimagesize($image_file);
  248. $image_data = fread(fopen($image_file, 'r'), filesize($image_file));
  249. $base64_image = 'data:' . $image_info['mime'] . ';base64,' . chunk_split(base64_encode($image_data));
  250. return $base64_image;
  251. }
  252. /**
  253. * 图片上传OSS
  254. * @param $img
  255. * @param string $path
  256. * @param $is_compress
  257. * @return string
  258. */
  259. function uploadingImg($img, $path = 'headimgurl',$is_compress=true)
  260. {
  261. $base64_image_content = file_get_contents($img);
  262. $upload_path = "storage" . DIRECTORY_SEPARATOR . $path . DIRECTORY_SEPARATOR . date('Ymd', time()) . DIRECTORY_SEPARATOR;
  263. $img_url = md5(uniqid() . time()) . '.png';
  264. $upload_path1 = public_path($upload_path);
  265. if (!is_dir($upload_path1)) {
  266. mkdir($upload_path1, 0777, true);
  267. }
  268. $oss = Storage::disk('oss');
  269. $pathA = "{$upload_path}{$img_url}";
  270. $update = $oss->put($pathA, $base64_image_content);
  271. if (!$update) { // 如果失败上传本地
  272. file_put_contents($upload_path1 . $img_url, base64_decode($base64_image_content));
  273. }
  274. return $update ? ($oss->url($pathA) . ($is_compress?'?x-oss-process=image/auto-orient,1/quality,q_85':'')) : asset($pathA);
  275. }
  276. /**
  277. * OSS图片压缩
  278. * @param $img
  279. * @param int $resize (3,10,30,50)
  280. * @param int $type 1原比例压缩,2固定高宽比列压缩(300*300)
  281. * @return string|string[]
  282. */
  283. function ossCompress($img, $resize = 10, $type = 1)
  284. {
  285. $old_str=strrchr($img, '?');
  286. if($old_str)$img=str_replace($old_str, '', $img);
  287. if ($type == 1) {
  288. return $img . '?x-oss-process=image/auto-orient,1/resize,p_' . $resize . '/quality,q_90';
  289. } elseif ($type == 2) {
  290. return $img . '?x-oss-process=image/auto-orient,1/resize,m_fill,w_300,h_300/quality,q_90';
  291. } elseif ($type == 3) {
  292. return $img . '?x-oss-process=image/auto-orient,1/resize,m_lfit,w_780/quality,q_100';
  293. }
  294. return $img;
  295. }
  296. /**
  297. * 保留2为小数
  298. * @param $num
  299. * @param int $format_num
  300. * @return float|int
  301. */
  302. function setFormatNum($num,$format_num=2){
  303. // return $num;
  304. $format_num=4;
  305. if(!is_numeric($num)){
  306. return 0;
  307. }
  308. if($format_num<0){
  309. return $num;
  310. }elseif ($format_num==0){
  311. return floor($num);
  312. }else{
  313. $num= sprintf("%.{$format_num}f", $num);
  314. // $multiple=pow(10,$format_num);
  315. // $num = floor($num*$multiple)/$multiple;
  316. }
  317. $num=$num*1;
  318. return $num;
  319. }
  320. /**
  321. * oss图片删除
  322. * @param $path
  323. * @return bool
  324. */
  325. function delImg($path)
  326. {
  327. $path_num = stripos($path, '?');
  328. if ($path_num !== false) {
  329. $path = substr($path, 0, $path_num);
  330. }
  331. $path = str_replace('https://jhnewshop.oss-cn-chengdu.aliyuncs.com', '', $path);
  332. $oss = Storage::disk('oss');
  333. $update = $oss->delete($path);
  334. return $update;
  335. }
  336. /**
  337. * 获取阿里云sts临时权限
  338. */
  339. function getAliSts()
  340. {
  341. $data = RedisDataServer::creatServer()->getData('sts_data');
  342. if ($data) {
  343. $data = json_decode($data, true);
  344. } else {
  345. $accessKeyId = env('ALI_OSS_ACCESS_ID');
  346. $accessSecret = env('ALI_OSS_ACCESS_KEY');
  347. AlibabaCloud::accessKeyClient($accessKeyId, $accessSecret)->regionId('cn-hangzhou')->asDefaultClient();
  348. //设置参数,发起请求。
  349. try {
  350. $result = AlibabaCloud::rpc()
  351. ->product('Sts')
  352. ->scheme('https') // https | http
  353. ->version('2015-04-01')
  354. ->action('AssumeRole')
  355. ->method('POST')
  356. ->host('sts.aliyuncs.com')
  357. ->options([
  358. 'query' => [
  359. 'RegionId' => "cn-chengdu",
  360. 'RoleArn' => "acs:ram::1470797691368660:role/oss-js",
  361. 'RoleSessionName' => "js-oss-serve",
  362. 'DurationSeconds' => 900,
  363. ],
  364. ])
  365. ->request();
  366. $result = $result->toArray();
  367. if (empty($result['Credentials'])) {
  368. return ['code' => 0, 'msg' => '获取token信息失败'];
  369. }
  370. $data = $result['Credentials'];
  371. unset($data['Expiration']);
  372. RedisDataServer::creatServer()->setData('sts_data', $data, 'json', 800);
  373. } catch (ClientException $e) {
  374. return ['code' => 0, 'msg' => $e->getErrorMessage()];
  375. } catch (ServerException $e) {
  376. return ['code' => 0, 'msg' => $e->getErrorMessage()];
  377. }
  378. }
  379. return ['code' => 1, 'msg' => '获取信息成功', 'data' => $data];
  380. }
  381. /**
  382. * 阿里云图片鉴定
  383. * @param $imges
  384. * @return array|bool
  385. * @throws ClientException
  386. * @throws ServerException
  387. */
  388. function sendAliImgAuth($imges)
  389. {
  390. if (is_string($imges)) $imges = [$imges];
  391. $tasks = [];
  392. $auth_status = 1;
  393. foreach ($imges as $key => $img) {
  394. $tasks[] = [
  395. 'dataId' => $key . '-img' . rand(10000000, 99999999) . '-' . time(),
  396. 'url' => $img,
  397. 'status' => 0,
  398. ];
  399. }
  400. $accessKeyId = env('ALI_OSS_ACCESS_ID');
  401. $accessSecret = env('ALI_OSS_ACCESS_KEY');
  402. AlibabaCloud::accessKeyClient($accessKeyId, $accessSecret)->regionId('cn-shanghai')->asDefaultClient();
  403. $request = Green::v20180509()->ImageSyncScan();
  404. $request->method('POST')
  405. ->scheme('https') // https | http
  406. ->body(json_encode([
  407. 'scenes' => ['porn', 'terrorism'],
  408. 'tasks' => $tasks,
  409. ]));
  410. $ret = $request->request();
  411. $ret_data = $ret->toArray();
  412. if (empty($ret_data['code']) || $ret_data['code'] != 200) {
  413. return $auth_status;
  414. } else {
  415. foreach ($ret_data['data'] as $key => $item) {
  416. $status = 1;
  417. if ($auth_status != 1) {
  418. break;
  419. }
  420. foreach ($item['results'] as $value) {
  421. if ($value['suggestion'] == 'review') {
  422. $status = 0;
  423. $auth_status = 0;
  424. break;
  425. } elseif ($value['suggestion'] == 'block') {
  426. $status = 2;
  427. $auth_status = 2;
  428. break;
  429. }
  430. }
  431. $tasks[$key]['status'] = $status;
  432. }
  433. }
  434. return ['auth_status' => $auth_status, 'tasks' => $tasks];
  435. }
  436. /**
  437. * 阿里云视频鉴定
  438. * @param $video 视频地址
  439. * @param int $type 鉴定类型
  440. * @param int $id 任务ID
  441. * @return bool
  442. * @throws ClientException
  443. * @throws ServerException
  444. */
  445. function sendAliVideoAuth($video, $type = 1, $id = 0)
  446. {
  447. $tasks = [
  448. [
  449. 'dataId' => $id . '-video' . rand(10000000, 99999999) . '-' . time(),
  450. 'url' => $video,
  451. 'interval' => 5,
  452. ]
  453. ];
  454. $accessKeyId = env('ALI_OSS_ACCESS_ID');
  455. $accessSecret = env('ALI_OSS_ACCESS_KEY');
  456. AlibabaCloud::accessKeyClient($accessKeyId, $accessSecret)->regionId('cn-shanghai')->asDefaultClient();
  457. $request = Green::v20180509()->videoAsyncScan();
  458. $request->method('POST')
  459. ->scheme('https') // https | http
  460. ->body(json_encode([
  461. 'callback' => route('notify.video-auth', ['type' => $type, 'id' => $id]),
  462. 'seed' => $id . '-video' . rand(10000000, 99999999),
  463. 'scenes' => ['porn', 'terrorism'],
  464. 'tasks' => $tasks,
  465. ]));
  466. $ret = $request->request();
  467. $ret_data = $ret->toArray();
  468. if (empty($ret_data['code']) || $ret_data['code'] != 200) {
  469. ErrorRecord::create(['msg' => '视频鉴定任务提交失败', 'data' => json_encode(compact('id', 'type', 'video'))]);
  470. return false;
  471. }
  472. return true;
  473. }
  474. /**
  475. * 获取文件名
  476. * @param $url
  477. * @return string
  478. */
  479. function getFileName($url)
  480. {
  481. $name = basename($url);
  482. return empty($name) ? '' : $name;
  483. }
  484. }