functions.php 15 KB

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