BtRepository.php
17.0 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
<?php
/**
* Created by PhpStorm.
* User: zhl
* Date: 2023/09/18
* Time: 20:56
*/
namespace App\Repositories;
use App\Repositories\Bt\Bt;
use Illuminate\Support\Facades\Log;
/**
* Class BtRepository
* @package App\Repositories
*/
class BtRepository
{
public $instance = [];
/**
* @param $domain
* @return array|bool
*/
public function createBtSite($domain, $rewrite = [], $domain_list = [])
{
$domain_array = parse_url($domain);
$host = $domain_array['host'] ?? $domain_array['path'];
// TODO 验证当前服务器是否已经创建过了
$bt = $this->getBtObject();
$site_list = $bt->WebSiteList($host);
if (!empty($site_list['data'])) {
return ['site_id' => $site_list['data'][0]['id']];
}
// if ($domain_list) {
// $web_name = ['domain' => $host, 'domainlist' => $domain_list, 'count' => 0];
// } else {
// $host_array = explode('.', $host);
// if (FALSE == empty($host_array[0]) && $host_array[0] == 'www')
// unset($host_array[0]);
// $domain_top = implode('.', $host_array);
// if ($domain_top == $host){
// $web_name = ['domain' => $host, 'domainlist' => ['www.'.$domain_top, '*.' . $host], 'count' => 0];
// }else{
// $web_name = ['domain' => $host, 'domainlist' => [$domain_top, '*.' . $domain_top], 'count' => 0];
// }
// }
$web_name = ['domain' => $host, 'domainlist' => $domain_list, 'count' => 0];
$array = [
'webname' => json_encode($web_name),
'path' => '/www/wwwroot/createSite',
'type_id' => 0,
'type' => 'PHP',
'version' => '80',
'port' => '80',
'ps' => $host,
'ftp' => false,
'ftp_username' => '',
'ftp_password' => '',
'sql' => false,
'codeing' => '',
'datauser' => '',
'datapassword' => '',
];
$result = $bt->AddSite($array);
// result 返回信息
// $result = ['siteStatus' => true, 'siteId' => 39, 'ftpStatus' => false, 'databaseStatus' => false,];
if (empty($result) || empty($result['siteId']))
return false;
// 更新站点目录 更新站点运行目录
$bt->SetPath($result['siteId'], public_path());
// 删除 .user.ini
$bt->DeleteFile('/www/wwwroot/c-globalso/public/.user.ini');
$bt->DeleteFile('/www/wwwroot/c-globalso/.user.ini');
// $bt->SetSiteRunPath($result['siteId'], '/');
#---------------------------------------------------------------------------------------------------------------
// 伪静态设置
// $htaccess = $this->rewrite301($rewrite);
// if ($htaccess)
// $bt->SaveFileBody($host, $htaccess);
// 获取配置
// 设置Nginx配置
// $nginx_config = $this->getAfterNginxConfStr($host);
// $bt->SaveFileBody('/www/server/panel/vhost/nginx/' . $host . '.conf', $nginx_config, 'utf-8', 1);
#---------------------------------------------------------------------------------------------------------------
return ['site_id' => $result['siteId']];
}
/**
* 申请免费证书
* @param string $domain
* @param array $rewrite
* @param array $otherDomain
* @param int $is_https
* @return bool
*/
public function applySsl($domain, $rewrite = [], $otherDomain = [], $is_https = 0)
{
$domain_array = parse_url($domain);
$host = $domain_array['host'] ?? $domain_array['path'];
$bt = $this->getBtObject();
$site_list = $bt->WebSiteList($host);
if (empty($site_list['data'])) {
$site = $this->createBtSite($domain,$rewrite,$otherDomain);
$site_id = $site['site_id'];
}else{
$site_id = $site_list['data'][0]['id'];
$host = $site_list['data'][0]['name'];
}
// 获取站点域名
$site_domain = $bt->WebDoaminList($site_id);
$domain_list = [];
foreach ($site_domain as $val) {
if (FALSE === strpos($val['name'], '*')) {
array_push($domain_list, $val['name']);
}
}
//添加站点域名
$this->addDomain($site_id, $host, $otherDomain, $site_domain);
//还原配置
$nginx_config = $this->getBeforeNginxConfStr($host);
$bt->SaveFileBody('/www/server/panel/vhost/nginx/' . $host . '.conf', $nginx_config, 'utf-8', 1);
// 如果已经申请了ssl证书, 并且证书有效期超过3天, 那么就使用已经申请好的证书
$ssl = $bt->GetSSL($host);
$is_set_status = false;//是否需要设置证书
if (FALSE == empty($ssl['cert_data']['notAfter']) && strtotime($ssl['cert_data']['notAfter']) - time() > 259200) {
$key = $ssl['key'];
$cer = $ssl['csr'];
$is_set_status = !$ssl['status'];
} else {
// 申请证书时需要将重写规则情况, 不然会跳转到其他地方
$bt->SaveFileBody($host, '');
// 如果没有证书, 申请证书并设置证书
$rs = $bt->ApplyCert(json_encode($domain_list),$site_id);
if(isset($rs['status']) && $rs['status']){
//申请成功,设置证书
$key = $rs['private_key'];
$cer = $rs['cert'];
$is_set_status = true;
}else{
$key = '';
$cer = '';
}
}
if($key && $cer && $is_set_status){
$bt->SetSSL(1, $host, $key, $cer);
}
$bt->DeleteFile('/www/wwwroot/c-globalso/public/.user.ini');
$bt->DeleteFile('/www/wwwroot/c-globalso/.user.ini');
$htaccess = $this->rewrite301($rewrite,$is_https);
if ($htaccess)
$bt->SaveFileBody($host, $htaccess);
// 更新配置
$nginx_config = $this->getAfterNginxConfStr($host);
$bt->SaveFileBody('/www/server/panel/vhost/nginx/' . $host . '.conf', $nginx_config, 'utf-8', 1);
return true;
}
/**
* 设置ssl证书
* @param string $domain
* @param array $rewrite
* @param array $otherDomain
* @param string $private_key
* @param string $cert
* @param int $is_https
* @return bool
*/
public function setSsl($domain, $rewrite = [], $otherDomain = [], $private_key = '', $cert = '', $is_https = 0)
{
$domain_array = parse_url($domain);
$host = $domain_array['host'] ?? $domain_array['path'];
$bt = $this->getBtObject();
$site_list = $bt->WebSiteList($host);
if (empty($site_list['data'])) {
$site = $this->createBtSite($domain,$rewrite,$otherDomain);
$site_id = $site['site_id'];
}else{
$host = $site_list['data'][0]['name'];
$site_id = $site_list['data'][0]['id'];
}
//添加站点域名
$this->addDomain($site_id, $host, $otherDomain);
// 还原配置
$nginx_config = $this->getBeforeNginxConfStr($host);
$bt->SaveFileBody('/www/server/panel/vhost/nginx/' . $host . '.conf', $nginx_config, 'utf-8', 1);
$bt->SetSSL(1, $host, $private_key, $cert);
$bt->DeleteFile('/www/wwwroot/c-globalso/public/.user.ini');
$bt->DeleteFile('/www/wwwroot/c-globalso/.user.ini');
// 设置301跳转
$htaccess = $this->rewrite301($rewrite,$is_https);
if ($htaccess)
$bt->SaveFileBody($host, $htaccess);
// 更新配置
$nginx_config = $this->getAfterNginxConfStr($host);
$bt->SaveFileBody('/www/server/panel/vhost/nginx/' . $host . '.conf', $nginx_config, 'utf-8', 1);
return true;
}
/**
* 获取bt对象
* @param string $key
* @param string $panel
* @return Bt
*/
public function getBtObject($key = '', $panel = '')
{
$key = $key ?: env('BT_KEY');
$panel = $panel ?: env('BT_PANEL');
$object_key = md5($key . $panel);
if (empty($this->instance[$object_key])) {
$bt = new Bt($panel, $key);
$this->instance[$object_key] = $bt;
}
return $this->instance[$object_key];
}
/**
* 获取配置前的文件内容
* @param $domain
* @return string|string[]
*/
public function getBeforeNginxConfStr($domain)
{
$bt = $this->getBtObject();
$conf = $bt->GetFileBody($domain, 2);
//如果有变量标识,去掉变量标识
if (FALSE !== strpos($conf['data'], 'map $domain_prefix')){
$conf['data'] = str_replace($this->domainPrefixConf(),'',$conf['data']);
//去掉自定义配置
$conf['data'] = str_replace($this->customConf($domain),'root ' . public_path() . ';', $conf['data']);
}
// preg_match('/set \$root[\S\s]+root \$root;/iU', $conf['data'], $matches);
// if (FALSE == empty($matches[0])) {
// $conf['data'] = str_replace($matches[0], 'root ' . public_path() . ';', $conf['data']);
// }
return $conf['data'];
}
/**
* 获取配置后的文件内容
* @param $domain
* @return mixed
*/
public function getAfterNginxConfStr($domain)
{
$bt = $this->getBtObject();
$conf = $bt->GetFileBody($domain, 2);
// $conf['data'] = file_get_contents(storage_path('logs/nginx.conf'));
// 如果没有变量, 添加变量识别
if (FALSE === strpos($conf['data'], 'map $domain_prefix')){
$conf['data'] = $this->domainPrefixConf() . $conf['data'];
// 替换自定义配置
$conf['data'] = str_replace('root ' . public_path() . ';', $this->customConf($domain), $conf['data']);
}
return $conf['data'];
}
/**
* 需要定制修改的配置
* @return string
*/
public function customConf($domain): string
{
$string = ' root '.public_path().'; # 设置根目录
set $domain_prefix "";
if ($host ~* "^(?<domain_prefix>[^.]+)\.") {
set $domain_prefix $1;
}
location / {
root '.public_path().'/'.$domain.'; # 设置根目录
if ($is_prefix_in_string = 1) {
root '.public_path().'/'.$domain.'/$domain_prefix;
}
try_files $uri $uri/ /404/index.html =404;
}
location ~ ^/(api|search) {
root '.public_path().'; # 设置/api /search /.well-known的根目录
try_files $uri $uri/ /index.php?$query_string;
}
location ~ ^/(well-known) {
root '.public_path().';
try_files $uri $uri/ /404/index.html =404;
}
error_page 403 /404/index.html;';
return $string;
}
/**
* 解析301跳转
* @param $rewrite
* @param $is_https
* @return string
*/
public function rewrite301($rewrite,$is_https)
{
$string = '# 屏蔽蜘蛛
if ($http_user_agent ~* "(Knowledge|SiteAuditBot|DotBot|rogerbot|MJ12bot|MegaIndex|Paracrawl|HubSpot|serpstatbot|SemrushBot|DataForSeoBot|BLEXBot|Bytespider|Sogou|Seekport|HubSpot|Barkrowler|PetalBot|Amazonbot|RainBot|test-bot|fidget-spinner-bot)") {
return 444;
}
# 设置跳转
';
if (FALSE == is_array($rewrite))
return $string;
foreach ($rewrite as $val) {
if (empty($val['origin']) || empty($val['target']))
continue;
$origin_tmp = parse_url($val['origin']);
$origin = $origin_tmp['host'] ?? $origin_tmp['path'];
$target_tmp = parse_url($val['target']);
$target = $target_tmp['host'] ?? $target_tmp['path'];
$string .= '
if ($host ~ "^' . $origin . '"){
return 301 $scheme://' . $target . '$request_uri;
}
';
}
if($is_https){
$string .= '
#HTTP_TO_HTTPS_START
if ($server_port !~ 443){
rewrite ^(/.*)$ https://$host$1 permanent;
}
';
}
return $string;
}
/**
* 配置变量
* @return string
*/
public function domainPrefixConf()
{
return 'map $domain_prefix $is_prefix_in_string {
default 0; en 1; zh 1; fr 1; de 1; ko 1; ja 1; es 1; ar 1; pt 1; ru 1; af 1; sq 1;
am 1; hy 1; az 1; eu 1; be 1; bn 1; bs 1; bg 1; ca 1; ceb 1; zh-CN 1; zh-TW 1; co 1;
hr 1; cs 1; da 1; nl 1; eo 1; et 1; fi 1; fy 1; gl 1; ka 1; el 1; gu 1; ht 1; ha 1; haw 1;
iw 1; hi 1; hmn 1; hu 1; is 1; ig 1; id 1; ga 1; it 1; jw 1; kn 1; kk 1; km 1; rw 1;
ku 1; ky 1; lo 1; la 1; lv 1; lt 1; lb 1; mk 1; mg 1; ms 1; ml 1; mt 1; mi 1; mr 1; mn 1;
my 1; ne 1; no 1; ny 1; or 1; ps 1; fa 1; pl 1; pa 1; ro 1; sm 1; gd 1; sr 1; st 1; sn 1;
sd 1; si 1; sk 1; sl 1; so 1; su 1; sw 1; sv 1; tl 1; tg 1; ta 1; tt 1; te 1; th 1; tr 1;
tk 1; uk 1; ur 1; ug 1; uz 1; vi 1; cy 1; xh 1; yi 1; yo 1; zu 1;
}';
}
//添加站点域名
protected function addDomain($site_id, $domain, $otherDomains, $site_domain = [])
{
$bt = $this->getBtObject();
if(!$site_domain){
$site_domain = $bt->WebDoaminList($site_id);
}
$site_domain = array_column($site_domain, 'name');
foreach ($otherDomains as $k => $otherDomain) {
// 如果已经包含, 就不添加
if (in_array($otherDomain, $site_domain)) {
unset($otherDomains[$k]);
}
}
if ($otherDomains) {
$otherDomains = implode(',', $otherDomains);
$res = $bt->WebAddDomain($site_id, $domain, $otherDomains);
if (!$res['status']) {
return false;
}
}
return true;
}
/**
* 创建amp站点
* @param $domain
* @param $key
* @param $cer
* @return array|bool
* @author Akun
* @date 2024/02/18 17:04
*/
public function createBtSiteAmp($domain,$key,$cer)
{
$domain_array = parse_url($domain);
$host = $domain_array['host'] ?? $domain_array['path'];
$host_array = explode('.',$host);
if (count($host_array) <= 2) {
array_unshift($host_array, 'm');
} else {
$host_array[0] = 'm';
}
$host = implode('.',$host_array);
// 验证当前服务器是否已经创建过了
$bt = $this->getBtObject();
$site_list = $bt->WebSiteList($host);
if (!empty($site_list['data'])) {
$site_id = $site_list['data'][0]['id'];
}else{
$web_name = ['domain' => $host, 'domainlist' => [], 'count' => 0];
$array = [
'webname' => json_encode($web_name),
'path' => '/www/wwwroot/createSite',
'type_id' => 0,
'type' => 'PHP',
'version' => '80',
'port' => '80',
'ps' => $host,
'ftp' => false,
'ftp_username' => '',
'ftp_password' => '',
'sql' => false,
'codeing' => '',
'datauser' => '',
'datapassword' => '',
];
$result = $bt->AddSite($array);
if (empty($result) || empty($result['siteId']))
return false;
$site_id = $result['siteId'];
// 更新站点目录 更新站点运行目录
$bt->SetPath($site_id, public_path());
// 删除 .user.ini
$bt->DeleteFile('/www/wwwroot/c-globalso/public/.user.ini');
$bt->DeleteFile('/www/wwwroot/c-globalso/.user.ini');
}
if(empty($key) || empty($cer)){
$ssl = $bt->GetSSL($host);
$is_set_status = false;//是否需要设置证书
if (FALSE == empty($ssl['cert_data']['notAfter']) && strtotime($ssl['cert_data']['notAfter']) - time() > 259200) {
// 如果已经申请了ssl证书, 并且证书有效期超过3天, 那么就使用已经申请好的证书
$key = $ssl['key'];
$cer = $ssl['csr'];
$is_set_status = !$ssl['status'];
} else {
// 如果没有证书, 申请证书并设置证书
$bt->SaveFileBody($host, ''); // 申请证书时需要将重写规则清空, 不然会跳转到其他地方
$rs = $bt->ApplyCert(json_encode([$host]),$site_id);
if(isset($rs['status']) && $rs['status']){
//申请成功,设置证书
$key = $rs['private_key'];
$cer = $rs['cert'];
$is_set_status = true;
}else{
$key = '';
$cer = '';
}
}
}else{
$is_set_status = true;
}
if($key && $cer && $is_set_status){
$bt->SetSSL(1, $host, $key, $cer);
}
// 伪静态设置
$bt->SaveFileBody($host, 'location / {
try_files $uri $uri/ /index.php?$query_string;
}');
return ['site_id' => $site_id];
}
}