functions.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: zilongs
  5. * Date: 20-9-23
  6. * Time: 上午10:56
  7. */
  8. use Illuminate\Support\Facades\Log;
  9. use App\Exceptions\ExitOutException;
  10. use App\Models\SystemConfig;
  11. use App\Models\TimePeriod;
  12. //统一输出格式话的json数据
  13. if (!function_exists('out')) {
  14. function out($data = null, $status = 0, $message = 'success', $exceptionData = false)
  15. {
  16. $out = ['status' => $status, 'message' => $message, 'data' => $data];
  17. if ($exceptionData !== false) {
  18. trace([$message => $exceptionData], 'error');
  19. }
  20. return response()->json($out);
  21. }
  22. }
  23. //统一异常输出格式话的json数据
  24. if (!function_exists('exit_out')) {
  25. function exit_out($data = null, $status = 0, $message = 'success', $exceptionData = false)
  26. {
  27. $out = ['status' => $status, 'message' => $message, 'data' => $data];
  28. if ($exceptionData !== false) {
  29. trace([$message => $exceptionData], 'error');
  30. }
  31. $json = json_encode($out, JSON_UNESCAPED_UNICODE);
  32. throw new ExitOutException($json);
  33. }
  34. }
  35. //日志记录
  36. if (!function_exists('trace')) {
  37. function trace($log = '', $level = 'info')
  38. {
  39. Log::log($level, $log);
  40. }
  41. }
  42. if (!function_exists('upDecimal')) {
  43. /**
  44. * 对价格进行向上取整
  45. * @param $price 价格
  46. * @param $decimal 保留小数位数
  47. */
  48. function upDecimal($price, $decimal = 2){
  49. $data1 = pow(10, $decimal);
  50. $data2 = ceil(bcmul($price, $data1,10));
  51. $data3 = bcdiv($data2, $data1, $decimal);
  52. return $data3;
  53. }
  54. }
  55. //AES加密
  56. if (!function_exists('aes_encrypt')) {
  57. function aes_encrypt($data)
  58. {
  59. if (is_array($data)) {
  60. $data = json_encode($data, JSON_UNESCAPED_UNICODE);
  61. }
  62. $key = config('config.aes_key');
  63. $iv = config('config.aes_iv');
  64. $cipher_text = openssl_encrypt($data, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $iv);
  65. $cipher_text = base64_encode($cipher_text);
  66. return urlencode($cipher_text);
  67. }
  68. }
  69. //AES解密
  70. if (!function_exists('aes_decrypt')) {
  71. function aes_decrypt($encryptData)
  72. {
  73. $encryptData = urldecode($encryptData);
  74. $encryptData = base64_decode($encryptData);
  75. $key = config('config.aes_key');
  76. $iv = config('config.aes_iv');
  77. $original_plaintext = openssl_decrypt($encryptData, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $iv);
  78. return json_decode($original_plaintext, true);
  79. }
  80. }
  81. //获取distance的sql字段
  82. if (!function_exists('get_distance_field')) {
  83. function get_distance_field($latitude, $longitude)
  84. {
  85. if (empty($latitude) || empty($longitude)) {
  86. return '未知 distance';
  87. }
  88. return 'if(longitude=0 and latitude=0,未知,round(6378.138*2*asin(sqrt(pow(sin( (' . $latitude . '*pi()/180-latitude*pi()/180)/2),2)+cos(' . $latitude . '*pi()/180)*cos(latitude*pi()/180)* pow(sin((' . $longitude . '*pi()/180-longitude*pi()/180)/2),2)))*1000)) distance';
  89. }
  90. }
  91. //获取用户的distance的sql字段
  92. if (!function_exists('get_user_distance_field')) {
  93. function get_user_distance_field($user)
  94. {
  95. $coordinate = get_user_coordinate($user);
  96. $latitude = $coordinate['latitude'];
  97. $longitude = $coordinate['longitude'];
  98. if (empty($latitude) || empty($longitude)) {
  99. return '"未知" distance';
  100. }
  101. return 'if(longitude=0 and latitude=0,"未知",round(6378.138*2*asin(sqrt(pow(sin( (' . $latitude . '*pi()/180-latitude*pi()/180)/2),2)+cos(' . $latitude . '*pi()/180)*cos(latitude*pi()/180)* pow(sin((' . $longitude . '*pi()/180-longitude*pi()/180)/2),2)))*1000)) distance';
  102. }
  103. }
  104. //构建单号
  105. if (!function_exists('build_sn')) {
  106. function build_sn($id, $len = 2, $prefix = '')
  107. {
  108. $idx = 0 - $len;
  109. $suffix = substr($id, $idx);
  110. $suffix = str_pad($suffix, $len, '0', STR_PAD_LEFT);
  111. $sn = $prefix.substr(date('YmdHis'), 2).$suffix;
  112. return $sn;
  113. }
  114. }
  115. //生日转年龄
  116. if (!function_exists('birthday_to_age')){
  117. function birthday_to_age($birthday)
  118. {
  119. if($birthday==null)
  120. {
  121. return "0岁";
  122. }
  123. list($year, $month, $day) = explode("-", $birthday);
  124. $year_diff = (date("Y") - $year) > 0 ? date("Y") - $year.'岁':'';
  125. $month_diff = (date("m") - $month) > 0 ? date("m") - $month.'个月':'';
  126. $day_diff = (date("d") - $day) > 0 ? date("d") - $day.'天':'';
  127. if ($day_diff < 0 || $month_diff < 0) {
  128. $year_diff--;
  129. }
  130. return $year_diff.$month_diff.$day_diff ;
  131. }
  132. }
  133. //计算经纬度两点之间距离(返回为米)
  134. if (!function_exists('get_distance')) {
  135. function get_distance($lat1, $lng1, $lat2, $lng2)
  136. {
  137. if (empty($lat1) || empty($lng1) || empty($lat2) || empty($lng2)) {
  138. return '未知';
  139. }
  140. $earthRadius = 6378138;
  141. $lat1 = ($lat1 * pi()) / 180;
  142. $lng1 = ($lng1 * pi()) / 180;
  143. $lat2 = ($lat2 * pi()) / 180;
  144. $lng2 = ($lng2 * pi()) / 180;
  145. $calcLongitude = $lng2 - $lng1;
  146. $calcLatitude = $lat2 - $lat1;
  147. $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
  148. $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
  149. $calculatedDistance = $earthRadius * $stepTwo;
  150. return number_format($calculatedDistance, 2, '.', '');
  151. }
  152. }
  153. //获取用户坐标
  154. if (!function_exists('get_user_coordinate')) {
  155. function get_user_coordinate($user)
  156. {
  157. $req = request()->post();
  158. if (empty($req['latitude']) || empty($req['longitude'])) {
  159. $latitude = $user['latitude'] ?? 0;
  160. $longitude = $user['longitude'] ?? 0;
  161. }
  162. else {
  163. $latitude = $req['latitude'];
  164. $longitude = $req['longitude'];
  165. }
  166. return ['latitude' => $latitude, 'longitude' => $longitude];
  167. }
  168. }
  169. //获取用户距离
  170. if (!function_exists('get_user_distance')) {
  171. function get_user_distance($user, $lat, $lng)
  172. {
  173. $coordinate = get_user_coordinate($user);
  174. $data = get_distance($coordinate['latitude'], $coordinate['longitude'], $lat, $lng);
  175. return $data;
  176. }
  177. }
  178. if (!function_exists('numBirthday')){
  179. /**
  180. * 生日转年龄
  181. * @author Yuanhang Liu & Xiaoyun Liu
  182. * @param $birthday 2020-10-14 00:48
  183. * @return string
  184. */
  185. function numBirthday($birthday){
  186. if ($birthday){
  187. try {
  188. list($year,$month,$day) = explode("-",$birthday);
  189. $year_diff = (date("Y") - $year)>0?date("Y") - $year.'岁':'';
  190. $month_diff = (date("m") - $month)>0?date("m") - $month.'个月':'';
  191. $day_diff = (date("d") - $day)>0?date("d") - $day.'天':'';
  192. if ($day_diff < 0 || $month_diff < 0)
  193. $year_diff--;
  194. return $year_diff.$month_diff.$day_diff ;
  195. }catch (Exception $e){
  196. return '';
  197. }
  198. }else{
  199. return '';
  200. }
  201. }
  202. }
  203. if (!function_exists('getWeek')){
  204. /**
  205. * 获取当日周几
  206. * @author Yuanhang Liu & Xiaoyun Liu
  207. * @param $birthday 2020-10-14 00:48
  208. * @return string
  209. */
  210. function getWeek($date){
  211. $weekarray=array("周日","周一","周二","周三","周四","周五","周六");
  212. $weekday['week'] = $weekarray[date("w",strtotime($date))];
  213. $weekday['flag'] = date("w",strtotime($date));
  214. return $weekday ;
  215. }
  216. }
  217. //发送短信
  218. if (!function_exists('send_sms')) {
  219. function send_sms($phone, $templateKey, $templateParam = [])
  220. {
  221. $sms_config = config('config.aly_sms');
  222. //是否启用https
  223. $security = false;
  224. $params = [];
  225. $params["PhoneNumbers"] = $phone;
  226. $params["SignName"] = $sms_config['sign_name'];
  227. $params["TemplateCode"] = $sms_config[$templateKey];
  228. $params['TemplateParam'] = $templateParam;
  229. if (is_array($params["TemplateParam"])) {
  230. $params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE);
  231. }
  232. $content = aly_sm_request(
  233. $sms_config['access_key'],
  234. $sms_config['access_secret'],
  235. "dysmsapi.aliyuncs.com",
  236. array_merge($params, array(
  237. "RegionId" => "cn-hangzhou",
  238. "Action" => "SendSms",
  239. "Version" => "2017-05-25",
  240. )),
  241. $security
  242. );
  243. return $content;
  244. }
  245. }
  246. if (!function_exists('aly_sm_request')) {
  247. function aly_sm_request($accessKeyId, $accessKeySecret, $domain, $params, $security = false, $method = 'POST')
  248. {
  249. $apiParams = array_merge(array(
  250. "SignatureMethod" => "HMAC-SHA1",
  251. "SignatureNonce" => uniqid(mt_rand(0, 0xffff), true),
  252. "SignatureVersion" => "1.0",
  253. "AccessKeyId" => $accessKeyId,
  254. "Timestamp" => gmdate("Y-m-d\TH:i:s\Z"),
  255. "Format" => "JSON",
  256. ), $params);
  257. ksort($apiParams);
  258. $sortedQueryStringTmp = "";
  259. foreach ($apiParams as $key => $value) {
  260. $sortedQueryStringTmp .= "&" . aly_sms_encode($key) . "=" . aly_sms_encode($value);
  261. }
  262. $stringToSign = "${method}&%2F&" . aly_sms_encode(substr($sortedQueryStringTmp, 1));
  263. $sign = base64_encode(hash_hmac("sha1", $stringToSign, $accessKeySecret . "&", true));
  264. $signature = aly_sms_encode($sign);
  265. $url = ($security ? 'https' : 'http') . "://{$domain}/";
  266. try {
  267. $content = aly_sms_fetch_content($url, $method, "Signature={$signature}{$sortedQueryStringTmp}");
  268. return json_decode($content, true);
  269. } catch (Exception $e) {
  270. return false;
  271. }
  272. }
  273. }
  274. if (!function_exists('aly_sms_encode')) {
  275. function aly_sms_encode($str)
  276. {
  277. $res = urlencode($str);
  278. $res = preg_replace("/\+/", "%20", $res);
  279. $res = preg_replace("/\*/", "%2A", $res);
  280. $res = preg_replace("/%7E/", "~", $res);
  281. return $res;
  282. }
  283. }
  284. if (!function_exists('aly_sms_fetch_content')) {
  285. function aly_sms_fetch_content($url, $method, $body)
  286. {
  287. $ch = curl_init();
  288. if ($method == 'POST') {
  289. curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
  290. curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
  291. } else {
  292. $url .= '?' . $body;
  293. }
  294. curl_setopt($ch, CURLOPT_URL, $url);
  295. curl_setopt($ch, CURLOPT_TIMEOUT, 5);
  296. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  297. curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  298. "x-sdk-client" => "php/2.0.0"
  299. ));
  300. if (substr($url, 0, 5) == 'https') {
  301. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  302. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  303. }
  304. $rtn = curl_exec($ch);
  305. if ($rtn === false) {
  306. // 大多由设置等原因引起,一般无法保障后续逻辑正常执行,
  307. // 所以这里触发的是E_USER_ERROR,会终止脚本执行,无法被try...catch捕获,需要用户排查环境、网络等故障
  308. trigger_error("[CURL_" . curl_errno($ch) . "]: " . curl_error($ch), E_USER_ERROR);
  309. }
  310. curl_close($ch);
  311. return $rtn;
  312. }
  313. }
  314. if (!function_exists('getDateFromList')) {
  315. /**
  316. * 获取指定日期段内每一天的日期
  317. * @param Date $startdate 开始日期
  318. * @param Date $enddate 结束日期
  319. * @return Array
  320. */
  321. function getDateFromList($start,$end){
  322. $stimestamp = strtotime($start);
  323. $etimestamp = strtotime($end);
  324. // 计算日期段内有多少天
  325. $days = ($etimestamp-$stimestamp)/86400+1;
  326. // 保存每天日期
  327. $arr = [];
  328. for($i=0;$i<$days;$i++){
  329. $arr[] = date('Y-m-d',$stimestamp+(86400*$i));
  330. }
  331. return $arr;
  332. }
  333. }
  334. if (!function_exists('numDays')){
  335. /**
  336. * 计算日期到现在多天天
  337. * @param $date
  338. * @return float
  339. */
  340. function numDays($date){
  341. $Date_List_a1=explode("-",date('Y-m-d',time()));
  342. $Date_List_a2=explode("-",$date);
  343. $d1=mktime(0,0,0,$Date_List_a1[1],$Date_List_a1[2],$Date_List_a1[0]);
  344. $d2=mktime(0,0,0,$Date_List_a2[1],$Date_List_a2[2],$Date_List_a2[0]);
  345. $Days=round(($d1-$d2)/3600/24);
  346. return $Days;
  347. }
  348. }
  349. //检测重复请求 超过就禁止访问 有用户flag就针对用户flag 没有flag就针对ip地址(ip的话注意反代情况,可能每个用户请求的ip都是反代服务器的ip,当然可以配置一波反代服务器使得业务服务器获取到真实用户ip) 最小只能设置1s一次请求 不支持1s以下 如果开启了redis可以改写支持毫秒级的方法
  350. if (!function_exists('check_repeat_request')) {
  351. function check_repeat_request($time, $limit, $flag = '')
  352. {
  353. $action = request()->getPathInfo();
  354. if (!empty($flag)){
  355. $key = $action.$flag;
  356. }
  357. else {
  358. $ip = request()->ip();
  359. $key = $action.$ip;
  360. }
  361. $time = $time < 1 ? 1 : $time;
  362. $time = round($time);
  363. if (Cache::has($key)){
  364. Cache::increment($key);
  365. $count = Cache::get($key);
  366. if($count > $limit){
  367. exit_out(null, 11003, '操作过于频繁,请稍后重试~');
  368. }
  369. }
  370. else {
  371. Cache::set($key, 1, $time);
  372. }
  373. return true;
  374. }
  375. }
  376. //随机生成验证码
  377. if (!function_exists('generate_code')) {
  378. function generate_code($length = 6)
  379. {
  380. $min = pow(10, ($length - 1));
  381. $max = pow(10, $length) - 1;
  382. return rand($min, $max);
  383. }
  384. }
  385. if (!function_exists('object_array')) {
  386. function object_array($array) {
  387. if(is_object($array)) {
  388. $array = (array)$array;
  389. }
  390. if(is_array($array)) {
  391. foreach($array as $key=>$value) {
  392. $array[$key] = object_array($value);
  393. }
  394. }
  395. return $array;
  396. }
  397. }
  398. if (!function_exists('sechedule_timeperiod')) {
  399. function sechedule_timeperiod()
  400. {
  401. $schedule_config = SystemConfig::get('docter_config');
  402. $times[] = TimePeriod::where('start_time_period','>=',$schedule_config['morning_start'])->where('end_time_period','<=',$schedule_config['morning_end'])->pluck('id')->toArray();
  403. $times[] = TimePeriod::where('start_time_period','>=',$schedule_config['afternoon_start'])->where('end_time_period','<=',$schedule_config['afternoon_end'])->pluck('id')->toArray();
  404. $times[] = TimePeriod::where('start_time_period','>=',$schedule_config['evening_start'])->where('end_time_period','<=',$schedule_config['evening_end'])->pluck('id')->toArray();
  405. return $times;
  406. }
  407. }
  408. if (!function_exists('apiReturn')) {
  409. function apiReturn($code,$msg ='', $data ='') {
  410. return json_encode(['code'=>$code,'msg'=>$msg,'data'=>$data]);
  411. }
  412. }
  413. if (!function_exists('getDateFromList')) {
  414. /**
  415. * 获取指定日期段内每一天的日期
  416. * @param Date $startdate 开始日期
  417. * @param Date $enddate 结束日期
  418. * @return Array
  419. */
  420. function getDateFromList($start,$end){
  421. $stimestamp = strtotime($start);
  422. $etimestamp = strtotime($end);
  423. // 计算日期段内有多少天
  424. $days = ($etimestamp-$stimestamp)/86400+1;
  425. // 保存每天日期
  426. $arr = [];
  427. for($i=0;$i<$days;$i++){
  428. $arr[] = date('Y-m-d',$stimestamp+(86400*$i));
  429. }
  430. return $arr;
  431. }
  432. }
  433. if (!function_exists('numDays')){
  434. /**
  435. * 计算日期到现在多天天
  436. * @param $date
  437. * @return float
  438. */
  439. function numDays($date){
  440. $Date_List_a1=explode("-",date('Y-m-d',time()));
  441. $Date_List_a2=explode("-",$date);
  442. $d1=mktime(0,0,0,$Date_List_a1[1],$Date_List_a1[2],$Date_List_a1[0]);
  443. $d2=mktime(0,0,0,$Date_List_a2[1],$Date_List_a2[2],$Date_List_a2[0]);
  444. $Days=round(($d1-$d2)/3600/24);
  445. return $Days;
  446. }
  447. }