-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathhelpers.php
More file actions
1442 lines (1215 loc) · 47.3 KB
/
Copy pathhelpers.php
File metadata and controls
1442 lines (1215 loc) · 47.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
use QuarkCMS\QuarkAdmin\Models\Picture;
use QuarkCMS\QuarkAdmin\Models\File;
use App\Models\Category;
use App\Models\Sms;
use App\Models\Printer;
use App\User;
use Modules\Wechat\Models\WechatConfig;
use App\Excels\Export;
use App\Excels\Import;
use Flc\Alidayu\Client;
use Flc\Alidayu\App;
use Flc\Alidayu\Requests\AlibabaAliqinFcSmsNumSend;
use Endroid\QrCode\QrCode;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use OSS\OssClient;
use OSS\Core\OssException;
use GuzzleHttp\Client as HttpClient;
/**
* 判断当前url是否被选中
* @author tangtanglove <dai_hang_love@126.com>
*/
if(!function_exists('get_url_activated')) {
function get_url_activated($url,$activated = 'active')
{
$urlActiveStatus = '';
if (!empty($url)) {
$host = $_SERVER['HTTP_HOST'];
$requestUri = $_SERVER['REQUEST_URI'];
// https状态 todo
$httpsStatus = web_config('SSL_OPEN');
$httpsStatus == 1 ? $baseUrl = 'https://' : $baseUrl = 'http://';
$getUrl = $baseUrl.$host.$requestUri;
if($requestUri =='/' && $url == '/index/index') {
$urlActiveStatus = $activated;
} else {
if(strpos($getUrl, $url) !== false) {
$urlActiveStatus = $activated;
}
}
}
return $urlActiveStatus;
}
}
/**
* Sioo希奥发送手机短信接口
* @return string
*/
if(!function_exists('sioo_send_sms')) {
function sioo_send_sms($phone,$content) {
if(!preg_match("/^1[345789]\d{9}$/", $phone)) {
return error('手机号错误!');
}
$uid = web_config('SIOO_UID');
$password = web_config('SIOO_PASSWORD');
if(empty($uid) || empty($password)) {
return error('接口配置错误!');
}
// 接口url
$url = "https://submit.10690221.com/send/ordinarykv?uid="
.$uid
."&password=".md5($password)
."&mobile=".$phone
."&msg=".$content;
$client = new HttpClient();
$response = $client->request('GET', $url);
$body = $response->getBody()->getContents();
$result = json_decode($body,true);
if ($result['code'] == 0) {
return success('发送成功!');
} else {
return error($result['msg']);
}
}
}
/**
* sms_post Alidayu发送手机短信接口
* string $config = ['app_key' => '*****','app_secret' => '************',// 'sandbox' => true, // 是否为沙箱环境,默认false;
* string $signName = '积木云'
* string $templateCode = 'SMS_70450333'
* string $phone = '15076569633'
* string $smsParam = [ 'number' => rand(100000, 999999)]
*/
if(!function_exists('alidayu_send_sms')) {
function alidayu_send_sms($templateCode,$phone,$smsParam) {
if(!preg_match("/^1[345789]\d{9}$/", $phone)) {
return error('手机号错误!');
}
$config['app_key'] = web_config('ALIDAYU_APP_KEY');
$config['app_secret'] = web_config('ALIDAYU_APP_SECRET');
$signName = web_config('ALIDAYU_APP_SIGNNAME');
if(empty($config['app_key']) || empty($config['app_secret']) || empty($signName)) {
return error('接口配置错误!');
}
if(empty($templateCode)) {
return error('模板代码不能为空!');
}
if(empty($smsParam)) {
return error('短信参数不能为空!');
}
//执行发短信
$client = new Client(new App($config));
$request = new AlibabaAliqinFcSmsNumSend;
$request->setRecNum($phone)
->setSmsParam($smsParam)
->setSmsFreeSignName($signName)
->setSmsTemplateCode($templateCode);
$result = $client->execute($request);
if ($result) {
return success('发送成功!');
} else {
return error('发送失败!');
}
}
}
/**
* 生成缩略图
* @author tangtanglove
* @param string $imagePath 图片路径
* @param string $thumbPath 缩略图路径
*/
if(!function_exists('make_thumb')) {
function make_thumb($imagePath,$thumbPath,$width,$height,$thumbType = 1)
{
if (empty($imagePath)) {
return error('图片路径不能为空!');
}
if (empty($thumbPath)) {
//如果不定义缩略图路径,则以thumb_+原图片名命名
$list = explode('/', $imagePath);
$key = count($list)-1;
//定义缩略图名称
$thumb_name = 'thumb_'.$width.'_'.$height.'_'.$list[$key];
$thumbPath = str_replace($list[$key],'',$imagePath).$thumb_name;
}
if (is_file($imagePath)) {
//不存在缩略图则创建
if (!is_file($thumbPath)) {
$image = \think\Image::open($imagePath);
$image->thumb($width, $height,$thumbType)->save($thumbPath);
}
return $thumbPath;
} else {
return $imagePath;
}
}
}
/**
* 适应手机页面
* @author tangtanglove <dai_hang_love@126.com>
*/
if(!function_exists('mobile_adaptor')) {
function mobile_adaptor($objects)
{
if($objects) {
foreach ($objects as $key => $object) {
if(isset($object['content'])) {
$preg_str = "/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png]))[\'|\"].*?[\/]?>/";
preg_match_all($preg_str,$object['content'],$match);
foreach ($match[1] as $key1 => $value) {
if(!strstr($value,"v.qq.com")) {
if(strpos($value,'../') !== false) {
$objects[$key]['cover_path'.$key1] = 'http://'.$_SERVER['HTTP_HOST'].'/'.str_replace('../','',$value);
if(web_config('SSL_OPEN') == 1) {
$objects[$key]['cover_path'.$key1] = 'https://'.$_SERVER['HTTP_HOST'].'/'.str_replace('../','',$value);
}
} else {
$objects[$key]['cover_path'.$key1] = $value;
}
}
}
$preg_str1 = "/<[video|VIDEO|embed|EMBED|source|SOURCE].*?src=[\'|\"](.*?)[\'|\"].*?[\/]?>/";
preg_match_all($preg_str1,$object['content'],$match1);
foreach ($match1[1] as $key2 => $value2) {
if(strstr($value2,"v.qq.com")) {
$objects[$key]['video_path'.$key2] = $value2;
}
}
}
// 封面图
if (isset($object['cover_id'])) {
// 获取文件url,用于外部访问
$objects[$key]['cover_path'] = get_picture($object['cover_id']);
}
// 多封面
if (isset($object['cover_ids'])) {
// 获取文件url,用于外部访问
if(count(explode('[',$object['cover_ids']))>1) {
$coverIds = json_decode($object['cover_ids'], true);
foreach($coverIds as $coverKey => $coverId) {
$objects[$key]['cover_path'.$coverKey] = get_picture($coverId);
}
}
}
}
// 生成手机图
if (isset($objects['content'])) {
$preg_str = "/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png]))[\'|\"].*?[\/]?>/";
preg_match_all($preg_str,$objects['content'],$match);
if($match[1]) {
foreach ($match[1] as $key => $value) {
if(strpos($value,'../') !== false) {
$objects['content'] = str_replace($value,'http://'.$_SERVER['HTTP_HOST'].'/'.str_replace('../','',$value),$objects['content']);
if(web_config('SSL_OPEN') == 1) {
$objects['content'] = str_replace($value,'https://'.$_SERVER['HTTP_HOST'].'/'.str_replace('../','',$value),$objects['content']);
}
}
}
}
$preg_str1 = "/<[video|VIDEO|embed|EMBED|source|SOURCE].*?src=[\'|\"](.*?)[\'|\"].*?[\/]?>/";
preg_match_all($preg_str1,$objects['content'],$match1);
foreach ($match1[1] as $key2 => $value2) {
$objects['video_path'.$key2] = $value2;
}
}
// 多封面
if (isset($objects['cover_ids']) && !empty($objects['cover_ids'])) {
// 获取文件url,用于外部访问
if(count(explode('[',$objects['cover_ids']))>1) {
$coverIds = json_decode($objects['cover_ids'], true);
}
if($coverIds) {
foreach($coverIds as $coverKey => $coverId) {
$url = get_picture($coverId);
$objects['cover_path'.$coverKey] = $url;
}
}
}
// 单图
if (isset($objects['cover_id']) && !empty($objects['cover_id'])) {
// 获取文件url,用于外部访问
$objects['cover_path'] = get_picture($objects['cover_id']);
}
}
return $objects;
}
}
/**
* 获取文章内视频
* @author tangtanglove <dai_hang_love@126.com>
*/
if(!function_exists('get_content_video')) {
function get_content_video($content)
{
preg_match_all('/<[iframe|video|embed]*\s+src="([^"]*)"[^>]*>/is',$content,$match);
return $match[1][0];
}
}
/**
* 获取文章内图片url
* @author tangtanglove <dai_hang_love@126.com>
*/
if(!function_exists('get_content_picture')) {
function get_content_picture($content)
{
preg_match_all("/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png]))[\'|\"].*?[\/]?>/",$content,$match);
$result = [];
foreach ($match[1] as $key => $value) {
if(strpos($value,'../') !== false) {
$baseUrl = 'http://';
if (web_config('SSL_OPEN') == 1) {
$baseUrl = 'https://';
}
$result[$key] = $baseUrl.$_SERVER['HTTP_HOST'].'/'.str_replace('../','',$value);
} else {
$result[$key] = $value;
}
}
return $result;
}
}
/**
* 获取分类名称
* @author tangtanglove <dai_hang_love@126.com>
*/
if(!function_exists('get_category')) {
function get_category($id)
{
$category = Category::find($id);
if(!empty($category)) {
return $category->title;
}
}
}
/**
* 字符串截取,支持中文和其他编码
* static
* access public
* @param string $str 需要转换的字符串
* @param string $start 开始位置
* @param string $length 截取长度
* @param string $charset 编码格式
* @param string $suffix 截断显示字符
* return string
*/
if(!function_exists('msubstr')) {
function msubstr($str, $start, $length, $charset="utf-8")
{
if(function_exists("mb_substr")) {
$slice = mb_substr($str, $start, $length, $charset);
} elseif(function_exists('iconv_substr')) {
$slice = iconv_substr($str,$start,$length,$charset);
if(false === $slice) {
$slice = '';
}
} else {
$re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
$re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
$re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
$re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
preg_match_all($re[$charset], $str, $match);
$slice = join("",array_slice($match[0], $start, $length));
}
$strlen=mb_strlen($str);
if($strlen>$length) {
$slice = $slice.'...';
}
return $slice;
}
}
/**
* 过滤Emoji
* @author tangtanglove <dai_hang_love@126.com>
*/
if(!function_exists('filter_emoji')) {
function filter_emoji($str)
{
$str = preg_replace_callback('/./u',function (array $match) {
return strlen($match[0]) >= 4 ? '' : $match[0];
},$str);
return $str;
}
}
/**
* 获取微信配置信息
* @author tangtanglove <dai_hang_love@126.com>
*/
if(!function_exists('get_wechat_config')) {
function get_wechat_config($name) {
$config = WechatConfig::where('name',$name)->first();
$value = '';
if(!empty($config)) {
$value = $config->value;
}
return $value;
}
}
/**
* 返回公众号配置
* @author tangtanglove <dai_hang_love@126.com>
*/
if(!function_exists('wechat_config')) {
function wechat_config($type = 'fwh')
{
switch (strtolower($type)) {
case 'dyh':
// 订阅号
$appid = get_wechat_config('WECHAT_DYH_APPID');
$secret = get_wechat_config('WECHAT_DYH_APPSECRET');
$token = get_wechat_config('WECHAT_DYH_TOKEN');
$aesKey = get_wechat_config('WECHAT_DYH_ENCODINGAESKEY');
break;
case 'fwh':
// 服务号
$appid = get_wechat_config('WECHAT_FWH_APPID');
$secret = get_wechat_config('WECHAT_FWH_APPSECRET');
$token = get_wechat_config('WECHAT_FWH_TOKEN');
$aesKey = get_wechat_config('WECHAT_FWH_ENCODINGAESKEY');
break;
case 'mp':
// 小程序
$appid = get_wechat_config('WECHAT_MP_APPID');
$secret = get_wechat_config('WECHAT_MP_APPSECRET');
$token = get_wechat_config('WECHAT_MP_TOKEN');
$aesKey = get_wechat_config('WECHAT_MP_ENCODINGAESKEY');
break;
default:
return false;
break;
}
$config = false;
if(!empty($appid) && !empty($secret)) {
$config = [
'debug' => true,
'app_id' => $appid,
'secret' => $secret,
'token' => $token,
'aes_key' => $aesKey,
'oauth' => [
'scopes' => ['snsapi_userinfo'],
'callback' => url('wechat/callback'),
],
'log' => [
'level' => 'debug',
'file' => storage_path('/logs/easywechat/easywechat_'.date('Ymd').'.log'),
]
];
}
return $config;
}
}
/**
* 返回公众号配置
* @author tangtanglove <dai_hang_love@126.com>
*/
if(!function_exists('wechat_pay_config')) {
function wechat_pay_config()
{
$getApiclientCertPath = '';
$getApiclientKeyPath = '';
$getApiclientCert = get_wechat_config('WECHAT_PAY_APICLIENT_CERT');
$getApiclientKey = get_wechat_config('WECHAT_PAY_APICLIENT_KEY');
if(!empty($getApiclientCert) && !empty($getApiclientKey)) {
$apiclientCertInfo = File::where('id',$getApiclientCert)->first();
$apiclientKeyInfo = File::where('id',$getApiclientKey)->first();
$getApiclientCertPath = str_replace("\\","/",storage_path('app\\'.$apiclientCertInfo['path']));
$getApiclientKeyPath = str_replace("\\","/",storage_path('app\\'.$apiclientKeyInfo['path']));
}
$config = [
'debug' => true,
'app_id' => get_wechat_config('WECHAT_PAY_APP_ID'),
'log' => [
'level' => 'debug',
'file' => storage_path('/logs/easywechat/easywechat_'.date('Ymd').'.log'),
],
'mch_id' => get_wechat_config('WECHAT_PAY_MERCHANTID'),
'key' => get_wechat_config('WECHAT_PAY_KEY'),
'cert_path' => $getApiclientCertPath, // XXX: 绝对路径!!!!
'key_path' => $getApiclientKeyPath // XXX: 绝对路径!!!!
];
return $config;
}
}
/**
* 返回微信app支付配置
* @author tangtanglove <dai_hang_love@126.com>
*/
if(!function_exists('wechat_app_pay_config')) {
function wechat_app_pay_config()
{
$getApiclientCertPath = '';
$getApiclientKeyPath = '';
$getApiclientCert = get_wechat_config('WECHAT_APP_PAY_APICLIENT_CERT');
$getApiclientKey = get_wechat_config('WECHAT_APP_PAY_APICLIENT_KEY');
if(!empty($getApiclientCert) && !empty($getApiclientKey)) {
$apiclientCertInfo = File::where('id',$getApiclientCert)->first();
$apiclientKeyInfo = File::where('id',$getApiclientKey)->first();
$getApiclientCertPath = str_replace("\\","/",storage_path('app\\'.$apiclientCertInfo['path']));
$getApiclientKeyPath = str_replace("\\","/",storage_path('app\\'.$apiclientKeyInfo['path']));
}
$config = [
'debug' => true,
'app_id' => get_wechat_config('WECHAT_APP_PAY_APP_ID'),
'log' => [
'level' => 'debug',
'file' => storage_path('/logs/easywechat/easywechat_'.date('Ymd').'.log'),
],
'mch_id' => get_wechat_config('WECHAT_APP_PAY_MERCHANTID'),
'key' => get_wechat_config('WECHAT_APP_PAY_KEY'),
'cert_path' => $getApiclientCertPath, // XXX: 绝对路径!!!!
'key_path' => $getApiclientKeyPath // XXX: 绝对路径!!!!
];
return $config;
}
}
/**
* 返回微信小程序支付配置
* @author tangtanglove <dai_hang_love@126.com>
*/
if(!function_exists('wechat_mp_pay_config')) {
function wechat_mp_pay_config()
{
$getApiclientCertPath = '';
$getApiclientKeyPath = '';
$getApiclientCert = get_wechat_config('WECHAT_MINIPROGRAMPAY_APICLIENT_CERT');
$getApiclientKey = get_wechat_config('WECHAT_MINIPROGRAMPAY_APICLIENT_KEY');
if(!empty($getApiclientCert) && !empty($getApiclientKey)) {
$apiclientCertInfo = File::where('id',$getApiclientCert)->first();
$apiclientKeyInfo = File::where('id',$getApiclientKey)->first();
$getApiclientCertPath = str_replace("\\","/",storage_path('app\\'.$apiclientCertInfo['path']));
$getApiclientKeyPath = str_replace("\\","/",storage_path('app\\'.$apiclientKeyInfo['path']));
}
$config = [
'debug' => true,
'app_id' => get_wechat_config('WECHAT_MINIPROGRAMPAY_APP_ID'),
'log' => [
'level' => 'debug',
'file' => storage_path('/logs/easywechat/easywechat_'.date('Ymd').'.log'),
],
'mch_id' => get_wechat_config('WECHAT_MINIPROGRAMPAY_MERCHANTID'),
'key' => get_wechat_config('WECHAT_MINIPROGRAMPAY_KEY'),
'secret' => get_wechat_config('WECHAT_MINIPROGRAMPAY_SECRET'),
'cert_path' => $getApiclientCertPath, // XXX: 绝对路径!!!!
'key_path' => $getApiclientKeyPath // XXX: 绝对路径!!!!
];
return $config;
}
}
/**
* 创建订单号
* @author tangtanglove <dai_hang_love@126.com>
*/
if(!function_exists('create_order_no')) {
function create_order_no()
{
return date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
}
}
/**
* 判断是否为手机端
* @author tangtanglove <dai_hang_love@126.com>
*/
if(!function_exists('is_mobile')) {
function is_mobile()
{
if (isset ($_SERVER['HTTP_USER_AGENT'])) {
$clientkeywords = array ('nokia', 'sony','ericsson','mot',
'samsung','htc','sgh','lg','sharp',
'sie-','philips','panasonic','alcatel',
'lenovo','iphone','ipod','blackberry',
'meizu','android','netfront','symbian',
'ucweb','windowsce','palm','operamini',
'operamobi','openwave','nexusone','cldc',
'midp','wap','mobile'
);
// 从HTTP_USER_AGENT中查找手机浏览器的关键字
if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
$result = true;
} else {
$result = false;
}
} else {
$result = false;
}
return $result;
}
}
/**
* @param $url 请求网址
* @param bool $params 请求参数
* @param int $ispost 请求方式
* @param bool $headers 请求头部
* @param int $https https协议
* @return bool|mixed
*/
if(!function_exists('curl')) {
function curl($url, $params = false, $method = 'get', $headers = false, $https = 0)
{
$httpInfo = array();
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36');
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if($headers) {
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}
if ($https) {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // 对认证证书来源的检查
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); // 从证书中检查SSL加密算法是否存在
}
if ($method == 'post') {
curl_setopt($ch, CURLOPT_POST, true);
if (is_array($params)) {
$params = http_build_query($params);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
}
curl_setopt($ch, CURLOPT_URL, $url);
} else {
if ($params) {
if (is_array($params)) {
$params = http_build_query($params);
}
curl_setopt($ch, CURLOPT_URL, $url . '?' . $params);
} else {
curl_setopt($ch, CURLOPT_URL, $url);
}
}
$response = curl_exec($ch);
if ($response === FALSE) {
return false;
}
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$httpInfo = array_merge($httpInfo, curl_getinfo($ch));
curl_close($ch);
return $response;
}
}
/**
* 获取用户名
* @author tangtanglove <dai_hang_love@126.com>
*/
if(!function_exists('user')) {
function user($uid = '',$field = 'username')
{
$result = '';
if(empty($uid)) {
$user = auth('web')->user();
} else {
$user = User::where('id',$uid)->first();
}
if(isset($user[$field])) {
$result = $user[$field];
}
return $result;
}
}
/**
* 生成二维码
* @author tangtanglove <dai_hang_love@126.com>
*/
if(!function_exists('qrcode')) {
function qrcode($text)
{
$qrCode = new QrCode($text);
header('Content-Type: '.$qrCode->getContentType());
echo $qrCode->writeString();
exit;
}
}
/**
* 发送邮件
* @author tangtanglove <dai_hang_love@126.com>
*/
if(!function_exists('send_email')) {
function send_email($subject,$toEmail,$content)
{
config([
'mail.mailers.smtp.host' => web_config('EMAIL_HOST'),
'mail.mailers.smtp.port' => web_config('EMAIL_PORT'),
'mail.mailers.smtp.encryption' => web_config('MAIL_ENCRYPTION'),
'mail.mailers.smtp.from' => ['address' => web_config('EMAIL_USERNAME'),'name' => web_config('WEB_SITE_NAME')],
'mail.mailers.smtp.username' => web_config('EMAIL_USERNAME'),
'mail.mailers.smtp.password' => web_config('EMAIL_PASSWORD')
]);
\Mail::raw($content, function ($message) use($toEmail, $subject) {
$message ->to($toEmail)->subject($subject);
});
if(count(\Mail::failures()) < 1){
return true;
}else{
return false;
}
}
}
/**
* 是否微信浏览器
* @author tangtanglove <dai_hang_love@126.com>
*/
if(!function_exists('is_wechat')) {
function is_wechat()
{
// 微信中登录认证
if(isset($_SERVER['HTTP_USER_AGENT'])) {
if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
return true;
} else {
return false;
}
}
}
}
/**
* 导出Excel
* @author tangtanglove <dai_hang_love@126.com>
*/
if(!function_exists('export')) {
function export($fileName,$titles,$lists,$columnFormats = [])
{
$getTitles = [];
$getLists = [];
if (!(count($titles) == count($titles, 1))) { // 标题为二维数组
foreach ($titles as $key => $value) {
$getTitles[] = $value['title'];
$fileds[] = $value['filed'];
}
foreach ($lists as $key1 => $value1) {
foreach ($fileds as $key2 => $value2) {
$rows[$value2] = $value1[$value2];
}
$getLists[$key1] = $rows;
}
} else {
$getTitles = $titles;
$getLists = $lists;
}
$export = new Export($getLists,$getTitles,$columnFormats);
return \Excel::download($export,$fileName.'_'.date('YmdHis').'.xlsx');
}
}
/**
* 导入Excel
* @author tangtanglove <dai_hang_love@126.com>
*/
if(!function_exists('import')) {
function import($fileId)
{
$file = File::where('id',$fileId)->first();
$importData = \Excel::toArray(new Import, storage_path('app/').$file['path']);
$results = $importData[0];
return $results;
}
}
/**
* 获取当前地理位置
* @author tangtanglove <dai_hang_love@126.com>
*/
if(!function_exists('get_address')) {
function get_address($ip='', $latitude='', $longitude='') {
$getAddress = [];
if(!empty($ip)) {
// 根据ip获取地理位置
$address = curl('http://ip.taobao.com/service/getIpInfo.php?ip='.$ip);
$address = json_decode($address,true);
if($address === false) {
$getAddress = '';
} else {
$getAddress['country'] = $address['data']['country'];
$getAddress['province'] = $address['data']['region'];
$getAddress['city'] = $address['data']['city'];
$getAddress['district'] = $address['data']['county'];
}
} elseif(!empty($latitude) && !empty($longitude)) {
// 根据经纬度获取地理位置
$address = curl('http://apis.map.qq.com/jsapi?qt=rgeoc&lnglat='.$longitude.'%2C'.$latitude);
$address = mb_convert_encoding($address, "utf-8", "gb18030");
$address = json_decode($address,true);
if($address === false) {
$getAddress = '';
} else {
$getAddress['country'] = $address['detail']['results'][0]['n'];
$getAddress['province'] = $address['detail']['results'][0]['p'];
$getAddress['city'] = $address['detail']['results'][0]['c'];
$getAddress['district'] = $address['detail']['results'][1]['address_name'];
}
}
return $getAddress;
}
}
/**
* 验证短信验证码是否合法
* @author tangtanglove <dai_hang_love@126.com>
*/
if(!function_exists('validate_sms_code')) {
function validate_sms_code($phone,$code) {
if(empty($phone)) {
return error('请先获取手机验证码!');
}
if(empty($code)) {
return error('手机验证码不能为空!');
}
$sms = Sms::where('phone',$phone)->orderBy('id','desc')->first();
// 判断验证码是否正确
if($sms['code'] != $code) {
// 更新错误次数
Sms::where('id',$sms['id'])->increment('error_times');
return error('手机验证码错误!');
}
// 验证码有效时间6分钟,最多允许6次错误
if(((time() - strtotime($sms['created_at'])) > 3600) || ($sms['error_times'])>6) {
return error('手机验证码已经失效,请重新获取!');
}
return success('验证成功!');
}
}
/**
* 获取易联云打印机Token
* @param $grantType
* @param $scope
* @param $timesTamp
* @param null $code
* @return mixed
*/
if(!function_exists('get_printer_token')) {
function get_printer_token($clientId,$clientSecret,$grantType, $scope, $timesTamp, $code = null)
{
$requestAll = [
'client_id' => $clientId,
'sign' => md5($clientId.$timesTamp.$clientSecret),
'id' => Str::uuid(),
'grant_type' => $grantType,
'scope' => $scope,
'code' => $code,
'timestamp' => $timesTamp,
];
$url = 'https://open-api.10ss.net/oauth/oauth';
$params = http_build_query($requestAll);
return curl($url, $params, 'post',0, 0);
}
}
/**
* 打印机
* @param $printerId 打印机id
* @param $originId 可以为订单号的id
* @param $content 打印内容
* @return mixed
*/
if(!function_exists('printer')) {
function printer($printerId,$originId,$content)
{
$printer = Printer::where('id',$printerId)->first();
if(empty($printer)) {
return error('无此打印机配置信息!');
}
$machineCode = $printer['machine_code'];
$clientId = $printer['client_id'];
$clientSecret = $printer['client_secret'];
$accessToken = $printer['access_token'];
$refreshToken = $printer['refresh_token'];
$grantType = 'client_credentials'; //自有模式(client_credentials) || 开放模式(authorization_code)
$scope = 'all'; //权限
$timesTamp = time(); //当前服务器时间戳(10位)
$getYlyAccessToken = Cache::get('yly_access_token');
if(empty($getYlyAccessToken)) {
// 获取access_token
$tokenInfo = get_printer_token($clientId,$clientSecret,$grantType,$scope,$timesTamp);
$tokenInfo = json_decode($tokenInfo,true);
$data['access_token'] = $tokenInfo['body']['access_token'];
$data['refresh_token'] = $tokenInfo['body']['refresh_token'];
// 储存到缓存
Cache::put('yly_access_token', $data, $tokenInfo['body']['expires_in']/60);
// 赋值
$accessToken = $tokenInfo['body']['access_token'];
} else {
// 赋值
$accessToken = $getYlyAccessToken['access_token'];
}
$url = 'https://open-api.10ss.net/print/index';
$requestAll = [
'client_id' => $clientId,
'sign' => md5($clientId.$timesTamp.$clientSecret),
'id' => Str::uuid(),
'machine_code' => $machineCode,
'access_token' => $accessToken,
'content' => $content,
'origin_id' => $originId,
'timestamp' => $timesTamp,
];
$params = http_build_query($requestAll);
$getResult = curl($url, $params, 'post',0, 0);
$result = json_decode($getResult,true);
if ($result['error'] == 0) {
return success('操作成功!');
} else {
return error('操作失败!');
}
}
}
/**
* 将一个字符串部分字符用*替代隐藏
* @param string $string 待转换的字符串
* @param int $bengin 起始位置,从0开始计数,当$type=4时,表示左侧保留长度
* @param int $len 需要转换成*的字符个数,当$type=4时,表示右侧保留长度
* @param int $type 转换类型:0,从左向右隐藏;1,从右向左隐藏;2,从指定字符位置分割前由右向左隐藏;3,从指定字符位置分割后由左向右隐藏;4,保留首末指定字符串
* @param string $glue 分割符