functions.php 15 KB

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