functions.php 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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. //统一输出格式话的json数据
  11. if (!function_exists('out')) {
  12. function out($data = null, $status = 0, $message = 'success', $exceptionData = false)
  13. {
  14. $out = ['status' => $status, 'message' => $message, 'data' => $data];
  15. if ($exceptionData !== false) {
  16. trace([$message => $exceptionData], 'error');
  17. }
  18. return response()->json($out);
  19. }
  20. }
  21. //统一异常输出格式话的json数据
  22. if (!function_exists('exit_out')) {
  23. function exit_out($data = null, $status = 0, $message = 'success', $exceptionData = false)
  24. {
  25. $out = ['status' => $status, 'message' => $message, 'data' => $data];
  26. if ($exceptionData !== false) {
  27. trace([$message => $exceptionData], 'error');
  28. }
  29. $json = json_encode($out, JSON_UNESCAPED_UNICODE);
  30. throw new ExitOutException($json);
  31. }
  32. }
  33. //日志记录
  34. if (!function_exists('trace')) {
  35. function trace($log = '', $level = 'info')
  36. {
  37. Log::log($level, $log);
  38. }
  39. }
  40. if (!function_exists('upDecimal')) {
  41. /**
  42. * 对价格进行向上取整
  43. * @param $price 价格
  44. * @param $decimal 保留小数位数
  45. */
  46. function upDecimal($price, $decimal = 2){
  47. $data1 = pow(10, $decimal);
  48. $data2 = ceil(bcmul($price, $data1,10));
  49. $data3 = bcdiv($data2, $data1, $decimal);
  50. return $data3;
  51. }
  52. }
  53. //AES加密
  54. if (!function_exists('aes_encrypt')) {
  55. function aes_encrypt($data)
  56. {
  57. if (is_array($data)) {
  58. $data = json_encode($data, JSON_UNESCAPED_UNICODE);
  59. }
  60. $key = config('config.aes_key');
  61. $iv = config('config.aes_iv');
  62. $cipher_text = openssl_encrypt($data, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $iv);
  63. $cipher_text = base64_encode($cipher_text);
  64. return urlencode($cipher_text);
  65. }
  66. }
  67. //AES解密
  68. if (!function_exists('aes_decrypt')) {
  69. function aes_decrypt($encryptData)
  70. {
  71. $encryptData = urldecode($encryptData);
  72. $encryptData = base64_decode($encryptData);
  73. $key = config('config.aes_key');
  74. $iv = config('config.aes_iv');
  75. $original_plaintext = openssl_decrypt($encryptData, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $iv);
  76. return json_decode($original_plaintext, true);
  77. }
  78. }
  79. //获取distance的sql字段
  80. if (!function_exists('get_distance_field')) {
  81. function get_distance_field($latitude, $longitude)
  82. {
  83. if (empty($latitude) || empty($longitude)) {
  84. return '999999999 distance';
  85. }
  86. return 'if(longitude=0 and latitude=0,999999999,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';
  87. }
  88. }
  89. //构建单号
  90. if (!function_exists('build_sn')) {
  91. function build_sn($id, $len = 2, $prefix = '')
  92. {
  93. $idx = 0 - $len;
  94. $suffix = substr($id, $idx);
  95. $suffix = str_pad($suffix, $len, '0', STR_PAD_LEFT);
  96. $sn = $prefix.substr(date('YmdHis'), 2).$suffix;
  97. return $sn;
  98. }
  99. }
  100. if (!function_exists('numBirthday')){
  101. /**
  102. * 生日转年龄
  103. * @author Yuanhang Liu & Xiaoyun Liu
  104. * @param $birthday 2020-10-14 00:48
  105. * @return string
  106. */
  107. function numBirthday($birthday){
  108. if ($birthday){
  109. try {
  110. list($year,$month,$day) = explode("-",$birthday);
  111. $year_diff = (date("Y") - $year)>0?date("Y") - $year.'岁':'';
  112. $month_diff = (date("m") - $month)>0?date("m") - $month.'个月':'';
  113. $day_diff = (date("d") - $day)>0?date("d") - $day.'天':'';
  114. if ($day_diff < 0 || $month_diff < 0)
  115. $year_diff--;
  116. return $year_diff.$month_diff.$day_diff ;
  117. }catch (Exception $e){
  118. return '';
  119. }
  120. }else{
  121. return '';
  122. }
  123. }
  124. }
  125. if (!function_exists('getWeek')){
  126. /**
  127. * 获取当日周几
  128. * @author Yuanhang Liu & Xiaoyun Liu
  129. * @param $birthday 2020-10-14 00:48
  130. * @return string
  131. */
  132. function getWeek($date){
  133. $weekday= "今天是星期" . mb_substr( "日一二三四五六",$date,1,"utf-8" );
  134. return $weekday ;
  135. }
  136. }
  137. //发送短信
  138. if (!function_exists('send_sms')) {
  139. function send_sms($phone, $templateKey, $templateParam = [])
  140. {
  141. $sms_config = config('config.aly_sms');
  142. //是否启用https
  143. $security = false;
  144. $params = [];
  145. $params["PhoneNumbers"] = $phone;
  146. $params["SignName"] = $sms_config['sign_name'];
  147. $params["TemplateCode"] = $sms_config[$templateKey];
  148. $params['TemplateParam'] = $templateParam;
  149. if (is_array($params["TemplateParam"])) {
  150. $params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE);
  151. }
  152. $content = aly_sm_request(
  153. $sms_config['access_key'],
  154. $sms_config['access_secret'],
  155. "dysmsapi.aliyuncs.com",
  156. array_merge($params, array(
  157. "RegionId" => "cn-hangzhou",
  158. "Action" => "SendSms",
  159. "Version" => "2017-05-25",
  160. )),
  161. $security
  162. );
  163. return $content;
  164. }
  165. }
  166. if (!function_exists('aly_sm_request')) {
  167. function aly_sm_request($accessKeyId, $accessKeySecret, $domain, $params, $security = false, $method = 'POST')
  168. {
  169. $apiParams = array_merge(array(
  170. "SignatureMethod" => "HMAC-SHA1",
  171. "SignatureNonce" => uniqid(mt_rand(0, 0xffff), true),
  172. "SignatureVersion" => "1.0",
  173. "AccessKeyId" => $accessKeyId,
  174. "Timestamp" => gmdate("Y-m-d\TH:i:s\Z"),
  175. "Format" => "JSON",
  176. ), $params);
  177. ksort($apiParams);
  178. $sortedQueryStringTmp = "";
  179. foreach ($apiParams as $key => $value) {
  180. $sortedQueryStringTmp .= "&" . aly_sms_encode($key) . "=" . aly_sms_encode($value);
  181. }
  182. $stringToSign = "${method}&%2F&" . aly_sms_encode(substr($sortedQueryStringTmp, 1));
  183. $sign = base64_encode(hash_hmac("sha1", $stringToSign, $accessKeySecret . "&", true));
  184. $signature = aly_sms_encode($sign);
  185. $url = ($security ? 'https' : 'http') . "://{$domain}/";
  186. try {
  187. $content = aly_sms_fetch_content($url, $method, "Signature={$signature}{$sortedQueryStringTmp}");
  188. return json_decode($content);
  189. } catch (\Exception $e) {
  190. return false;
  191. }
  192. }
  193. }
  194. if (!function_exists('aly_sms_encode')) {
  195. function aly_sms_encode($str)
  196. {
  197. $res = urlencode($str);
  198. $res = preg_replace("/\+/", "%20", $res);
  199. $res = preg_replace("/\*/", "%2A", $res);
  200. $res = preg_replace("/%7E/", "~", $res);
  201. return $res;
  202. }
  203. }
  204. if (!function_exists('aly_sms_fetch_content')) {
  205. function aly_sms_fetch_content($url, $method, $body)
  206. {
  207. $ch = curl_init();
  208. if ($method == 'POST') {
  209. curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
  210. curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
  211. } else {
  212. $url .= '?' . $body;
  213. }
  214. curl_setopt($ch, CURLOPT_URL, $url);
  215. curl_setopt($ch, CURLOPT_TIMEOUT, 5);
  216. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  217. curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  218. "x-sdk-client" => "php/2.0.0"
  219. ));
  220. if (substr($url, 0, 5) == 'https') {
  221. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  222. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  223. }
  224. $rtn = curl_exec($ch);
  225. if ($rtn === false) {
  226. // 大多由设置等原因引起,一般无法保障后续逻辑正常执行,
  227. // 所以这里触发的是E_USER_ERROR,会终止脚本执行,无法被try...catch捕获,需要用户排查环境、网络等故障
  228. trigger_error("[CURL_" . curl_errno($ch) . "]: " . curl_error($ch), E_USER_ERROR);
  229. }
  230. curl_close($ch);
  231. return $rtn;
  232. }
  233. if (!function_exists('getDateFromList')) {
  234. /**
  235. * 获取指定日期段内每一天的日期
  236. * @param Date $startdate 开始日期
  237. * @param Date $enddate 结束日期
  238. * @return Array
  239. */
  240. function getDateFromList($start,$end){
  241. $stimestamp = strtotime($start);
  242. $etimestamp = strtotime($end);
  243. // 计算日期段内有多少天
  244. $days = ($etimestamp-$stimestamp)/86400+1;
  245. // 保存每天日期
  246. $arr = [];
  247. for($i=0;$i<$days;$i++){
  248. $arr[] = date('Y-m-d',$stimestamp+(86400*$i));
  249. }
  250. return $arr;
  251. }
  252. }
  253. if (!function_exists('numDays')){
  254. /**
  255. * 计算日期到现在多天天
  256. * @param $date
  257. * @return float
  258. */
  259. function numDays($date){
  260. $Date_List_a1=explode("-",date('Y-m-d',time()));
  261. $Date_List_a2=explode("-",$date);
  262. $d1=mktime(0,0,0,$Date_List_a1[1],$Date_List_a1[2],$Date_List_a1[0]);
  263. $d2=mktime(0,0,0,$Date_List_a2[1],$Date_List_a2[2],$Date_List_a2[0]);
  264. $Days=round(($d1-$d2)/3600/24);
  265. return $Days;
  266. }
  267. }
  268. }