functions.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  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. //AES加密
  42. if (!function_exists('aes_encrypt')) {
  43. function aes_encrypt($data)
  44. {
  45. if (is_array($data)) {
  46. $data = json_encode($data, JSON_UNESCAPED_UNICODE);
  47. }
  48. $key = config('config.aes_key');
  49. $iv = config('config.aes_iv');
  50. $cipher_text = openssl_encrypt($data, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $iv);
  51. $cipher_text = base64_encode($cipher_text);
  52. return urlencode($cipher_text);
  53. }
  54. }
  55. //AES解密
  56. if (!function_exists('aes_decrypt')) {
  57. function aes_decrypt($encryptData)
  58. {
  59. $encryptData = urldecode($encryptData);
  60. $encryptData = base64_decode($encryptData);
  61. $key = config('config.aes_key');
  62. $iv = config('config.aes_iv');
  63. $original_plaintext = openssl_decrypt($encryptData, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $iv);
  64. return json_decode($original_plaintext, true);
  65. }
  66. }
  67. //获取distance的sql字段
  68. if (!function_exists('get_distance_field')) {
  69. function get_distance_field($latitude, $longitude)
  70. {
  71. if (empty($latitude) || empty($longitude)) {
  72. return '未知 distance';
  73. }
  74. 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';
  75. }
  76. }
  77. //获取用户的distance的sql字段
  78. if (!function_exists('get_user_distance_field')) {
  79. function get_user_distance_field($user)
  80. {
  81. $coordinate = get_user_coordinate($user);
  82. $latitude = $coordinate['latitude'];
  83. $longitude = $coordinate['longitude'];
  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. //构建单号
  91. if (!function_exists('build_sn')) {
  92. function build_sn($id, $len = 2, $prefix = '')
  93. {
  94. $idx = 0 - $len;
  95. $suffix = substr($id, $idx);
  96. $suffix = str_pad($suffix, $len, '0', STR_PAD_LEFT);
  97. $sn = $prefix.substr(date('YmdHis'), 2).$suffix;
  98. return $sn;
  99. }
  100. }
  101. //生日转年龄
  102. if (!function_exists('birthday_to_age')){
  103. function birthday_to_age($birthday)
  104. {
  105. if($birthday==null)
  106. {
  107. return "0岁";
  108. }
  109. list($year, $month, $day) = explode("-", $birthday);
  110. $year_diff = (date("Y") - $year) > 0 ? date("Y") - $year.'岁':'';
  111. $month_diff = (date("m") - $month) > 0 ? date("m") - $month.'个月':'';
  112. $day_diff = (date("d") - $day) > 0 ? date("d") - $day.'天':'';
  113. if ($day_diff < 0 || $month_diff < 0) {
  114. $year_diff--;
  115. }
  116. return $year_diff.$month_diff.$day_diff ;
  117. }
  118. }
  119. //计算经纬度两点之间距离(返回为米)
  120. if (!function_exists('get_distance')) {
  121. function get_distance($lat1, $lng1, $lat2, $lng2)
  122. {
  123. if (empty($lat1) || empty($lng1) || empty($lat2) || empty($lng2)) {
  124. return '未知';
  125. }
  126. $earthRadius = 6378138;
  127. $lat1 = ($lat1 * pi()) / 180;
  128. $lng1 = ($lng1 * pi()) / 180;
  129. $lat2 = ($lat2 * pi()) / 180;
  130. $lng2 = ($lng2 * pi()) / 180;
  131. $calcLongitude = $lng2 - $lng1;
  132. $calcLatitude = $lat2 - $lat1;
  133. $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
  134. $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
  135. $calculatedDistance = $earthRadius * $stepTwo;
  136. return number_format($calculatedDistance, 2, '.', '');
  137. }
  138. }
  139. //获取用户坐标
  140. if (!function_exists('get_user_coordinate')) {
  141. function get_user_coordinate($user)
  142. {
  143. $req = request()->post();
  144. if (empty($req['latitude']) || empty($req['longitude'])) {
  145. $latitude = $user['latitude'] ?? 0;
  146. $longitude = $user['longitude'] ?? 0;
  147. }
  148. else {
  149. $latitude = $req['latitude'];
  150. $longitude = $req['longitude'];
  151. }
  152. return ['latitude' => $latitude, 'longitude' => $longitude];
  153. }
  154. }
  155. //获取用户距离
  156. if (!function_exists('get_user_distance')) {
  157. function get_user_distance($user, $lat, $lng)
  158. {
  159. $coordinate = get_user_coordinate($user);
  160. $data = get_distance($coordinate['latitude'], $coordinate['longitude'], $lat, $lng);
  161. return $data;
  162. }
  163. }
  164. //发送短信
  165. if (!function_exists('send_sms')) {
  166. function send_sms($phone, $templateKey, $templateParam = [])
  167. {
  168. $sms_config = config('config.aly_sms');
  169. //是否启用https
  170. $security = false;
  171. $params = [];
  172. $params["PhoneNumbers"] = $phone;
  173. $params["SignName"] = $sms_config['sign_name'];
  174. $params["TemplateCode"] = $sms_config[$templateKey];
  175. $params['TemplateParam'] = $templateParam;
  176. if (is_array($params["TemplateParam"])) {
  177. $params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE);
  178. }
  179. $content = aly_sm_request(
  180. $sms_config['access_key'],
  181. $sms_config['access_secret'],
  182. "dysmsapi.aliyuncs.com",
  183. array_merge($params, array(
  184. "RegionId" => "cn-hangzhou",
  185. "Action" => "SendSms",
  186. "Version" => "2017-05-25",
  187. )),
  188. $security
  189. );
  190. return $content;
  191. }
  192. }
  193. if (!function_exists('aly_sm_request')) {
  194. function aly_sm_request($accessKeyId, $accessKeySecret, $domain, $params, $security = false, $method = 'POST')
  195. {
  196. $apiParams = array_merge(array(
  197. "SignatureMethod" => "HMAC-SHA1",
  198. "SignatureNonce" => uniqid(mt_rand(0, 0xffff), true),
  199. "SignatureVersion" => "1.0",
  200. "AccessKeyId" => $accessKeyId,
  201. "Timestamp" => gmdate("Y-m-d\TH:i:s\Z"),
  202. "Format" => "JSON",
  203. ), $params);
  204. ksort($apiParams);
  205. $sortedQueryStringTmp = "";
  206. foreach ($apiParams as $key => $value) {
  207. $sortedQueryStringTmp .= "&" . aly_sms_encode($key) . "=" . aly_sms_encode($value);
  208. }
  209. $stringToSign = "${method}&%2F&" . aly_sms_encode(substr($sortedQueryStringTmp, 1));
  210. $sign = base64_encode(hash_hmac("sha1", $stringToSign, $accessKeySecret . "&", true));
  211. $signature = aly_sms_encode($sign);
  212. $url = ($security ? 'https' : 'http') . "://{$domain}/";
  213. try {
  214. $content = aly_sms_fetch_content($url, $method, "Signature={$signature}{$sortedQueryStringTmp}");
  215. return json_decode($content, true);
  216. } catch (Exception $e) {
  217. return false;
  218. }
  219. }
  220. }
  221. if (!function_exists('aly_sms_encode')) {
  222. function aly_sms_encode($str)
  223. {
  224. $res = urlencode($str);
  225. $res = preg_replace("/\+/", "%20", $res);
  226. $res = preg_replace("/\*/", "%2A", $res);
  227. $res = preg_replace("/%7E/", "~", $res);
  228. return $res;
  229. }
  230. }
  231. if (!function_exists('aly_sms_fetch_content')) {
  232. function aly_sms_fetch_content($url, $method, $body)
  233. {
  234. $ch = curl_init();
  235. if ($method == 'POST') {
  236. curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
  237. curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
  238. } else {
  239. $url .= '?' . $body;
  240. }
  241. curl_setopt($ch, CURLOPT_URL, $url);
  242. curl_setopt($ch, CURLOPT_TIMEOUT, 5);
  243. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  244. curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  245. "x-sdk-client" => "php/2.0.0"
  246. ));
  247. if (substr($url, 0, 5) == 'https') {
  248. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  249. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  250. }
  251. $rtn = curl_exec($ch);
  252. if ($rtn === false) {
  253. // 大多由设置等原因引起,一般无法保障后续逻辑正常执行,
  254. // 所以这里触发的是E_USER_ERROR,会终止脚本执行,无法被try...catch捕获,需要用户排查环境、网络等故障
  255. trigger_error("[CURL_" . curl_errno($ch) . "]: " . curl_error($ch), E_USER_ERROR);
  256. }
  257. curl_close($ch);
  258. return $rtn;
  259. }
  260. }
  261. //检测重复请求 超过就禁止访问 有用户flag就针对用户flag 没有flag就针对ip地址(ip的话注意反代情况,可能每个用户请求的ip都是反代服务器的ip,当然可以配置一波反代服务器使得业务服务器获取到真实用户ip) 最小只能设置1s一次请求 不支持1s以下 如果开启了redis可以改写支持毫秒级的方法
  262. if (!function_exists('check_repeat_request')) {
  263. function check_repeat_request($time, $limit, $flag = '')
  264. {
  265. $action = request()->getPathInfo();
  266. if (!empty($flag)){
  267. $key = $action.$flag;
  268. }
  269. else {
  270. $ip = request()->ip();
  271. $key = $action.$ip;
  272. }
  273. $time = $time < 1 ? 1 : $time;
  274. $time = round($time);
  275. if (Cache::has($key)){
  276. Cache::increment($key);
  277. $count = Cache::get($key);
  278. if($count > $limit){
  279. exit_out(null, 11003, '操作过于频繁,请稍后重试~');
  280. }
  281. }
  282. else {
  283. Cache::set($key, 1, $time);
  284. }
  285. return true;
  286. }
  287. }
  288. //随机生成验证码
  289. if (!function_exists('generate_code')) {
  290. function generate_code($length = 6)
  291. {
  292. $min = pow(10, ($length - 1));
  293. $max = pow(10, $length) - 1;
  294. return rand($min, $max);
  295. }
  296. }
  297. if (!function_exists('object_array')) {
  298. function object_array($array) {
  299. if(is_object($array)) {
  300. $array = (array)$array;
  301. }
  302. if(is_array($array)) {
  303. foreach($array as $key=>$value) {
  304. $array[$key] = object_array($value);
  305. }
  306. }
  307. return $array;
  308. }
  309. }
  310. if (!function_exists('sechedule_timeperiod')) {
  311. function sechedule_timeperiod()
  312. {
  313. $schedule_config = SystemConfig::get('docter_config');
  314. $times[] = TimePeriod::where('start_time_period','>=',$schedule_config['morning_start'])->where('end_time_period','<=',$schedule_config['morning_end'])->pluck('id')->toArray();
  315. $times[] = TimePeriod::where('start_time_period','>=',$schedule_config['afternoon_start'])->where('end_time_period','<=',$schedule_config['afternoon_end'])->pluck('id')->toArray();
  316. $times[] = TimePeriod::where('start_time_period','>=',$schedule_config['evening_start'])->where('end_time_period','<=',$schedule_config['evening_end'])->pluck('id')->toArray();
  317. return $times;
  318. }
  319. }
  320. if (!function_exists('apiReturn')) {
  321. function apiReturn($code,$msg ='', $data ='') {
  322. return json_encode(['code'=>$code,'msg'=>$msg,'data'=>$data]);
  323. }
  324. }