functions.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  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. if (!function_exists('numBirthday')){
  176. /**
  177. * 生日转年龄
  178. * @author Yuanhang Liu & Xiaoyun Liu
  179. * @param $birthday 2020-10-14 00:48
  180. * @return string
  181. */
  182. function numBirthday($birthday){
  183. if ($birthday){
  184. try {
  185. list($year,$month,$day) = explode("-",$birthday);
  186. $year_diff = (date("Y") - $year)>0?date("Y") - $year.'岁':'';
  187. $month_diff = (date("m") - $month)>0?date("m") - $month.'个月':'';
  188. $day_diff = (date("d") - $day)>0?date("d") - $day.'天':'';
  189. if ($day_diff < 0 || $month_diff < 0)
  190. $year_diff--;
  191. return $year_diff.$month_diff.$day_diff ;
  192. }catch (Exception $e){
  193. return '';
  194. }
  195. }else{
  196. return '';
  197. }
  198. }
  199. }
  200. if (!function_exists('getWeek')){
  201. /**
  202. * 获取当日周几
  203. * @author Yuanhang Liu & Xiaoyun Liu
  204. * @param $birthday 2020-10-14 00:48
  205. * @return string
  206. */
  207. function getWeek($date){
  208. $weekday= "今天是星期" . mb_substr( "日一二三四五六",$date,1,"utf-8" );
  209. return $weekday ;
  210. }
  211. }
  212. //发送短信
  213. if (!function_exists('send_sms')) {
  214. function send_sms($phone, $templateKey, $templateParam = [])
  215. {
  216. $sms_config = config('config.aly_sms');
  217. //是否启用https
  218. $security = false;
  219. $params = [];
  220. $params["PhoneNumbers"] = $phone;
  221. $params["SignName"] = $sms_config['sign_name'];
  222. $params["TemplateCode"] = $sms_config[$templateKey];
  223. $params['TemplateParam'] = $templateParam;
  224. if (is_array($params["TemplateParam"])) {
  225. $params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE);
  226. }
  227. $content = aly_sm_request(
  228. $sms_config['access_key'],
  229. $sms_config['access_secret'],
  230. "dysmsapi.aliyuncs.com",
  231. array_merge($params, array(
  232. "RegionId" => "cn-hangzhou",
  233. "Action" => "SendSms",
  234. "Version" => "2017-05-25",
  235. )),
  236. $security
  237. );
  238. return $content;
  239. }
  240. }
  241. if (!function_exists('aly_sm_request')) {
  242. function aly_sm_request($accessKeyId, $accessKeySecret, $domain, $params, $security = false, $method = 'POST')
  243. {
  244. $apiParams = array_merge(array(
  245. "SignatureMethod" => "HMAC-SHA1",
  246. "SignatureNonce" => uniqid(mt_rand(0, 0xffff), true),
  247. "SignatureVersion" => "1.0",
  248. "AccessKeyId" => $accessKeyId,
  249. "Timestamp" => gmdate("Y-m-d\TH:i:s\Z"),
  250. "Format" => "JSON",
  251. ), $params);
  252. ksort($apiParams);
  253. $sortedQueryStringTmp = "";
  254. foreach ($apiParams as $key => $value) {
  255. $sortedQueryStringTmp .= "&" . aly_sms_encode($key) . "=" . aly_sms_encode($value);
  256. }
  257. $stringToSign = "${method}&%2F&" . aly_sms_encode(substr($sortedQueryStringTmp, 1));
  258. $sign = base64_encode(hash_hmac("sha1", $stringToSign, $accessKeySecret . "&", true));
  259. $signature = aly_sms_encode($sign);
  260. $url = ($security ? 'https' : 'http') . "://{$domain}/";
  261. try {
  262. $content = aly_sms_fetch_content($url, $method, "Signature={$signature}{$sortedQueryStringTmp}");
  263. return json_decode($content, true);
  264. } catch (Exception $e) {
  265. return false;
  266. }
  267. }
  268. }
  269. if (!function_exists('aly_sms_encode')) {
  270. function aly_sms_encode($str)
  271. {
  272. $res = urlencode($str);
  273. $res = preg_replace("/\+/", "%20", $res);
  274. $res = preg_replace("/\*/", "%2A", $res);
  275. $res = preg_replace("/%7E/", "~", $res);
  276. return $res;
  277. }
  278. }
  279. if (!function_exists('aly_sms_fetch_content')) {
  280. function aly_sms_fetch_content($url, $method, $body)
  281. {
  282. $ch = curl_init();
  283. if ($method == 'POST') {
  284. curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
  285. curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
  286. } else {
  287. $url .= '?' . $body;
  288. }
  289. curl_setopt($ch, CURLOPT_URL, $url);
  290. curl_setopt($ch, CURLOPT_TIMEOUT, 5);
  291. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  292. curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  293. "x-sdk-client" => "php/2.0.0"
  294. ));
  295. if (substr($url, 0, 5) == 'https') {
  296. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  297. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  298. }
  299. $rtn = curl_exec($ch);
  300. if ($rtn === false) {
  301. // 大多由设置等原因引起,一般无法保障后续逻辑正常执行,
  302. // 所以这里触发的是E_USER_ERROR,会终止脚本执行,无法被try...catch捕获,需要用户排查环境、网络等故障
  303. trigger_error("[CURL_" . curl_errno($ch) . "]: " . curl_error($ch), E_USER_ERROR);
  304. }
  305. curl_close($ch);
  306. return $rtn;
  307. }
  308. }
  309. //检测重复请求 超过就禁止访问 有用户flag就针对用户flag 没有flag就针对ip地址(ip的话注意反代情况,可能每个用户请求的ip都是反代服务器的ip,当然可以配置一波反代服务器使得业务服务器获取到真实用户ip) 最小只能设置1s一次请求 不支持1s以下 如果开启了redis可以改写支持毫秒级的方法
  310. if (!function_exists('check_repeat_request')) {
  311. function check_repeat_request($time, $limit, $flag = '')
  312. {
  313. $action = request()->getPathInfo();
  314. if (!empty($flag)){
  315. $key = $action.$flag;
  316. }
  317. else {
  318. $ip = request()->ip();
  319. $key = $action.$ip;
  320. }
  321. $time = $time < 1 ? 1 : $time;
  322. $time = round($time);
  323. if (Cache::has($key)){
  324. Cache::increment($key);
  325. $count = Cache::get($key);
  326. if($count > $limit){
  327. exit_out(null, 11003, '操作过于频繁,请稍后重试~');
  328. }
  329. }
  330. else {
  331. Cache::set($key, 1, $time);
  332. }
  333. return true;
  334. }
  335. }
  336. //随机生成验证码
  337. if (!function_exists('generate_code')) {
  338. function generate_code($length = 6)
  339. {
  340. $min = pow(10, ($length - 1));
  341. $max = pow(10, $length) - 1;
  342. return rand($min, $max);
  343. }
  344. }
  345. if (!function_exists('object_array')) {
  346. function object_array($array) {
  347. if(is_object($array)) {
  348. $array = (array)$array;
  349. }
  350. if(is_array($array)) {
  351. foreach($array as $key=>$value) {
  352. $array[$key] = object_array($value);
  353. }
  354. }
  355. return $array;
  356. }
  357. }
  358. if (!function_exists('sechedule_timeperiod')) {
  359. function sechedule_timeperiod()
  360. {
  361. $schedule_config = SystemConfig::get('docter_config');
  362. $times[] = TimePeriod::where('start_time_period','>=',$schedule_config['morning_start'])->where('end_time_period','<=',$schedule_config['morning_end'])->pluck('id')->toArray();
  363. $times[] = TimePeriod::where('start_time_period','>=',$schedule_config['afternoon_start'])->where('end_time_period','<=',$schedule_config['afternoon_end'])->pluck('id')->toArray();
  364. $times[] = TimePeriod::where('start_time_period','>=',$schedule_config['evening_start'])->where('end_time_period','<=',$schedule_config['evening_end'])->pluck('id')->toArray();
  365. return $times;
  366. }
  367. }
  368. if (!function_exists('apiReturn')) {
  369. function apiReturn($code,$msg ='', $data ='') {
  370. return json_encode(['code'=>$code,'msg'=>$msg,'data'=>$data]);
  371. }
  372. }
  373. if (!function_exists('getDateFromList')) {
  374. /**
  375. * 获取指定日期段内每一天的日期
  376. * @param Date $startdate 开始日期
  377. * @param Date $enddate 结束日期
  378. * @return Array
  379. */
  380. function getDateFromList($start,$end){
  381. $stimestamp = strtotime($start);
  382. $etimestamp = strtotime($end);
  383. // 计算日期段内有多少天
  384. $days = ($etimestamp-$stimestamp)/86400+1;
  385. // 保存每天日期
  386. $arr = [];
  387. for($i=0;$i<$days;$i++){
  388. $arr[] = date('Y-m-d',$stimestamp+(86400*$i));
  389. }
  390. return $arr;
  391. }
  392. }
  393. if (!function_exists('numDays')){
  394. /**
  395. * 计算日期到现在多天天
  396. * @param $date
  397. * @return float
  398. */
  399. function numDays($date){
  400. $Date_List_a1=explode("-",date('Y-m-d',time()));
  401. $Date_List_a2=explode("-",$date);
  402. $d1=mktime(0,0,0,$Date_List_a1[1],$Date_List_a1[2],$Date_List_a1[0]);
  403. $d2=mktime(0,0,0,$Date_List_a2[1],$Date_List_a2[2],$Date_List_a2[0]);
  404. $Days=round(($d1-$d2)/3600/24);
  405. return $Days;
  406. }
  407. }