-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCore.php
More file actions
813 lines (743 loc) · 27 KB
/
Core.php
File metadata and controls
813 lines (743 loc) · 27 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
<?php
namespace TypechoPlugin\Access;
use Redis;
use Typecho\Cookie;
use Typecho\Db;
use Typecho\I18n;
use Typecho\Plugin\Exception as PluginException;
use Typecho\Request;
use Typecho\Response;
use Utils\Helper;
use Widget\Options;
use Widget\User;
if (!defined('__TYPECHO_ROOT_DIR__')) {
exit;
}
class Core
{
protected Db $db;
protected Request $request;
protected Response $response;
/** Redis 缓存实例,未启用时为 null */
protected ?Redis $redis = null;
/** Redis 缓存键前缀 */
private const CACHE_PREFIX = 'typecho_access:';
public UA $ua;
public $config;
public string $action;
public string $title;
public array $logs = [];
public array $overview = [];
public array $referer = [];
/**
* 构造函数,根据不同类型的请求,计算不同的数据并渲染输出
*
* @access public
*/
public function __construct()
{
# Load language pack
if (I18n::getLang() !== 'zh_CN') {
$file = __TYPECHO_ROOT_DIR__ . __TYPECHO_PLUGIN_DIR__ .
'/Access/lang/' . I18n::getLang() . '.mo';
file_exists($file) && I18n::addLang($file);
}
# Init variables
$this->db = Db::get();
$this->config = Options::alloc()->plugin('Access');
$this->request = Request::getInstance();
$this->response = Response::getInstance();
if ($this->config->pageSize == null || $this->config->isDrop == null) {
throw new PluginException(_t('请先设置插件!'));
}
$this->ua = new UA($this->request->getAgent());
$this->initRedis();
switch ($this->request->get('action')) {
case 'overview':
$this->action = 'overview';
$this->title = _t('访问概览');
break;
case 'logs':
default:
$this->action = 'logs';
$this->title = _t('访问日志');
break;
}
}
/**
* 获取概览页全部数据(供 AJAX 接口调用)
*
* @access public
* @return array
*/
public function getOverviewData(): array
{
$this->parseOverview();
$this->parseReferer();
return [
'overview' => [
'today' => $this->overview['today'],
'yesterday' => $this->overview['yesterday'],
'total' => $this->overview['total'],
],
'referer' => $this->referer,
'chart_data' => json_decode($this->overview['chart_data'], true),
];
}
/**
* 获取日志页全部数据(供 AJAX 接口调用)
*
* @access public
* @param int $page 页码
* @param int $type 类型 1=人类 2=爬虫 3=全部
* @param string $filter 筛选类型 all/ip/post/path
* @param string $filterValue 筛选值
* @return array
*/
public function getLogsData(int $page, int $type, string $filter, string $filterValue): array
{
$offset = (max($page, 1) - 1) * $this->config->pageSize;
$query = $this->db->select()->from('table.access')
->order('time', Db::SORT_DESC)
->offset($offset)->limit($this->config->pageSize);
$qcount = $this->db->select('count(1) AS count')->from('table.access');
switch ($type) {
case 1:
$query->where('robot = ?', 0);
$qcount->where('robot = ?', 0);
break;
case 2:
$query->where('robot = ?', 1);
$qcount->where('robot = ?', 1);
break;
}
switch ($filter) {
case 'ip':
$ip = bindec(decbin(ip2long($filterValue)));
$query->where('ip = ?', $ip);
$qcount->where('ip = ?', $ip);
break;
case 'post':
$query->where('content_id = ?', $filterValue);
$qcount->where('content_id = ?', $filterValue);
break;
case 'path':
$query->where('path = ?', $filterValue);
$qcount->where('path = ?', $filterValue);
break;
}
$list = $this->db->fetchAll($query);
foreach ($list as &$row) {
if (!empty($row['robot']) && $row['robot'] == 1) {
$name = $row['robot_id'] ?? '';
$version = $row['robot_version'] ?? '';
} else {
$name = $row['browser_id'] ?? '';
$version = $row['browser_version'] ?? '';
}
if ($name === '' && !empty($row['ua'])) {
$ua = new UA($row['ua']);
if ($ua->isRobot()) {
$name = $ua->getRobotID();
$version = $ua->getRobotVersion();
} else {
$name = $ua->getBrowserName();
$version = $ua->getBrowserVersion();
}
}
if ($name == '') {
$row['display_name'] = _t('Unknown');
} elseif ($version == '') {
$row['display_name'] = $name;
} else {
$row['display_name'] = $name . ' / ' . $version;
}
// 转换 IP 以便前端直接使用
$row['ip_display'] = $this->long2ip($row['ip']);
}
$list = $this->htmlEncode($this->urlDecode($list));
$rows = (int)$this->db->fetchAll($qcount)[0]['count'];
$filterArr = ['filter' => $filter];
if ($filter !== 'all') {
$filterArr[$filter] = $filterValue;
}
$pageObj = new Page($this->config->pageSize, $rows, $page, 10, array_merge($filterArr, [
'panel' => Plugin::$panel,
'action' => 'logs',
'type' => $type,
]));
$cidList = $this->db->fetchAll($this->db->select('DISTINCT content_id as cid, COUNT(1) as count, table.contents.title as title')
->from('table.access')
->join('table.contents', 'table.access.content_id = table.contents.cid')
->where('table.access.content_id IS NOT NULL')
->where('table.contents.type = ?', 'post')
->group('table.access.content_id')
->group('table.contents.title')
->order('count', Db::SORT_DESC));
return [
'list' => $list,
'rows' => $rows,
'page' => $pageObj->show(),
'cidList' => $cidList,
];
}
/**
* 初始化 Redis 连接
*
* @access protected
* @return void
*/
protected function initRedis(): void
{
if (!extension_loaded('redis')) {
return;
}
if (!isset($this->config->redisCache) || $this->config->redisCache != '1') {
return;
}
try {
$redis = new Redis();
$host = $this->config->redisHost ?: '127.0.0.1';
$port = (int)($this->config->redisPort ?: 6379);
if (!$redis->connect($host, $port, 3)) {
return;
}
$password = $this->config->redisAuth ?? '';
if ($password !== '') {
$redis->auth($password);
}
$redis->ping();
$this->redis = $redis;
} catch (\Exception $e) {
$this->redis = null;
}
}
/**
* 从 Redis 获取缓存数据
*
* @access protected
* @param string $key 缓存键名
* @return array|null 缓存数据,未命中返回 null
*/
protected function getCache(string $key): ?array
{
if ($this->redis === null) {
return null;
}
try {
$data = $this->redis->get(self::CACHE_PREFIX . $key);
if ($data === false) {
return null;
}
$decoded = json_decode($data, true);
return is_array($decoded) ? $decoded : null;
} catch (\Exception $e) {
return null;
}
}
/**
* 写入 Redis 缓存
* TTL 统一为距明天 0 点的剩余秒数(86400 - 当天已过去的秒数)
*
* @access protected
* @param string $key 缓存键名
* @param array $data 缓存数据
* @return void
*/
protected function setCache(string $key, array $data): void
{
if ($this->redis === null) {
return;
}
try {
$ttl = 86400 - (time() - strtotime(date("Y-m-d 00:00:00")));
$this->redis->setex(
self::CACHE_PREFIX . $key,
max($ttl, 1),
json_encode($data, JSON_UNESCAPED_UNICODE)
);
} catch (\Exception $e) {
// 写入失败静默忽略,不影响主流程
}
}
/**
* 生成来源统计数据,提供给页面渲染使用
* 优先从 Redis 缓存读取,缓存未命中时查询数据库并回填缓存
*
* @access protected
* @return void
*/
protected function parseReferer()
{
// ── 来源 URL ──
$cachedUrl = $this->getCache('referer:url');
if ($cachedUrl !== null) {
$this->referer['url'] = $cachedUrl;
} else {
$this->referer['url'] = $this->db->fetchAll($this->db->select('DISTINCT entrypoint AS value, COUNT(1) as count')
->from('table.access')->where("entrypoint <> ''")->group('entrypoint')
->order('count', Db::SORT_DESC)->limit($this->config->pageSize));
$this->referer['url'] = $this->htmlEncode($this->urlDecode($this->referer['url']));
$this->setCache('referer:url', $this->referer['url']);
}
// ── 来源域名 ──
$cachedDomain = $this->getCache('referer:domain');
if ($cachedDomain !== null) {
$this->referer['domain'] = $cachedDomain;
} else {
$this->referer['domain'] = $this->db->fetchAll($this->db->select('DISTINCT entrypoint_domain AS value, COUNT(1) as count')
->from('table.access')->where("entrypoint_domain <> ''")->group('entrypoint_domain')
->order('count', Db::SORT_DESC)->limit($this->config->pageSize));
$this->referer['domain'] = $this->htmlEncode($this->urlDecode($this->referer['domain']));
$this->setCache('referer:domain', $this->referer['domain']);
}
}
/**
* 生成用于图标的 JSON 数据
*
* @access protected
* @return string
*/
protected function makeChartJson(): string
{
$chart = [];
foreach ($this->overview as $type => $val) {
$val['sub_title'] = 'Generate By AccessPlugin';
if ($type == 'today' || $type == 'yesterday') {
$val['xAxis'] = range(0, count($val['ip']['detail']));
$val['title'] = _t('%s 统计', $val['time']);
} elseif ($type == 'month') {
$val['xAxis'] = range(1, count($val['ip']['detail']));
$val['title'] = _t('%s 月统计', $val['time']);
}
$chart[$type] = $val;
}
return json_encode($chart, JSON_UNESCAPED_UNICODE);
}
/**
* 生成总览数据,提供给页面渲染使用
* "昨日"、"总计"、"当月" 优先从 Redis 缓存读取;"今日" 始终实时查询
*
* @access protected
* @return void
*/
protected function parseOverview(): void
{
// ── 今日数据:始终实时查询,保证准确性 ──
$this->overview['today'] = $this->queryDayOverview(date("Y-m-d"));
// ── 昨日数据:缓存键包含日期,跨天自动失效 ──
$yesterdayDate = date("Y-m-d", strtotime('-1 day'));
$yesterdayCacheKey = 'overview:yesterday:' . $yesterdayDate;
$cached = $this->getCache($yesterdayCacheKey);
if ($cached !== null) {
$this->overview['yesterday'] = $cached;
} else {
$this->overview['yesterday'] = $this->queryDayOverview($yesterdayDate);
$this->setCache($yesterdayCacheKey, $this->overview['yesterday']);
}
// ── 当月数据:按 TTL 缓存 ──
$monthCacheKey = 'overview:month:' . date('Y-m');
$cached = $this->getCache($monthCacheKey);
if ($cached !== null) {
$this->overview['month'] = $cached;
} else {
$this->overview['month'] = $this->queryMonthOverview();
$this->setCache($monthCacheKey, $this->overview['month']);
}
// ── 总计数据:按 TTL 缓存 ──
$totalCacheKey = 'overview:total';
$cached = $this->getCache($totalCacheKey);
if ($cached !== null) {
$this->overview['total'] = $cached;
} else {
$this->overview['total'] = $this->queryTotalOverview();
$this->setCache($totalCacheKey, $this->overview['total']);
}
# 输出用于图表的Json
$this->overview['chart_data'] = $this->makeChartJson();
}
/**
* 查询某一天的访问概览(按小时维度 + 当日汇总)
*
* @access protected
* @param string $date 日期,格式 Y-m-d
* @return array
*/
protected function queryDayOverview(string $date): array
{
$result = ['time' => $date];
$dayStart = strtotime("{$date} 00:00:00");
$dayEnd = strtotime("{$date} 23:59:59");
# 按小时统计明细
for ($hour = 0; $hour < 24; $hour++) {
$start = strtotime("{$date} {$hour}:00:00");
$end = strtotime("{$date} {$hour}:59:59");
$subQuery = $this->db->select('DISTINCT ip')->from('table.access')
->where("time >= ? AND time <= ?", $start, $end);
if (method_exists($subQuery, 'prepare')) {
$subQuery = $subQuery->prepare($subQuery);
}
$result['ip']['detail'][$hour] = (int)$this->db->fetchAll($this->db->select('COUNT(1) AS count')
->from('(' . $subQuery . ') AS tmp'))[0]['count'];
$subQuery = $this->db->select('DISTINCT ip,ua')->from('table.access')
->where("time >= ? AND time <= ?", $start, $end);
if (method_exists($subQuery, 'prepare')) {
$subQuery = $subQuery->prepare($subQuery);
}
$result['uv']['detail'][$hour] = (int)$this->db->fetchAll($this->db->select('COUNT(1) AS count')
->from('(' . $subQuery . ') AS tmp'))[0]['count'];
$result['pv']['detail'][$hour] = (int)$this->db->fetchAll($this->db->select('COUNT(1) AS count')
->from('table.access')->where('time >= ? AND time <= ?', $start, $end))[0]['count'];
}
# 当日汇总
$subQuery = $this->db->select('DISTINCT ip')->from('table.access')
->where("time >= ? AND time <= ?", $dayStart, $dayEnd);
if (method_exists($subQuery, 'prepare')) {
$subQuery = $subQuery->prepare($subQuery);
}
$result['ip']['count'] = (int)$this->db->fetchAll($this->db->select('COUNT(1) AS count')
->from('(' . $subQuery . ') AS tmp'))[0]['count'];
$subQuery = $this->db->select('DISTINCT ip,ua')->from('table.access')
->where("time >= ? AND time <= ?", $dayStart, $dayEnd);
if (method_exists($subQuery, 'prepare')) {
$subQuery = $subQuery->prepare($subQuery);
}
$result['uv']['count'] = (int)$this->db->fetchAll($this->db->select('COUNT(1) AS count')
->from('(' . $subQuery . ') AS tmp'))[0]['count'];
$result['pv']['count'] = (int)$this->db->fetchAll($this->db->select('COUNT(1) AS count')
->from('table.access')
->where("time >= ? AND time <= ?", $dayStart, $dayEnd)
)[0]['count'];
return $result;
}
/**
* 查询当月访问概览(按天维度)
*
* @access protected
* @return array
*/
protected function queryMonthOverview(): array
{
$year = date('Y');
$month = date('m');
$monthDays = cal_days_in_month(CAL_GREGORIAN, (int)$month, (int)$year);
$result = ['time' => $month];
for ($day = 1; $day <= $monthDays; $day++) {
$start = strtotime("{$year}-{$month}-{$day} 00:00:00");
$end = strtotime("{$year}-{$month}-{$day} 23:59:59");
$subQuery = $this->db->select('DISTINCT ip')->from('table.access')
->where('time >= ? AND time <= ?', $start, $end);
if (method_exists($subQuery, 'prepare')) {
$subQuery = $subQuery->prepare($subQuery);
}
$result['ip']['detail'][$day - 1] = (int)$this->db->fetchAll($this->db->select('COUNT(1) AS count')
->from('(' . $subQuery . ') AS tmp'))[0]['count'];
$subQuery = $this->db->select('DISTINCT ip,ua')->from('table.access')
->where('time >= ? AND time <= ?', $start, $end);
if (method_exists($subQuery, 'prepare')) {
$subQuery = $subQuery->prepare($subQuery);
}
$result['uv']['detail'][$day - 1] = (int)$this->db->fetchAll($this->db->select('COUNT(1) AS count')
->from('(' . $subQuery . ') AS tmp'))[0]['count'];
$result['pv']['detail'][$day - 1] = (int)$this->db->fetchAll($this->db->select('COUNT(1) AS count')
->from('table.access')->where('time >= ? AND time <= ?', $start, $end))[0]['count'];
}
return $result;
}
/**
* 查询总计访问概览
*
* @access protected
* @return array
*/
protected function queryTotalOverview(): array
{
$result = [];
$result['ip'] = (int)$this->db->fetchAll($this->db->select('COUNT(1) AS count')
->from('(' . $this->db->select('DISTINCT ip')->from('table.access') . ') AS tmp'))[0]['count'];
$result['uv'] = (int)$this->db->fetchAll($this->db->select('COUNT(1) AS count')
->from('(' . $this->db->select('DISTINCT ip,ua')->from('table.access') . ') AS tmp'))[0]['count'];
$result['pv'] = (int)$this->db->fetchAll($this->db->select('COUNT(1) AS count')
->from('table.access'))[0]['count'];
return $result;
}
/**
* 编码数组中的字符串为 HTML 实体
*
* @param array|string $data 将要被编码的数据
* @param bool $valuesOnly 是否只编码数组数值
* @param string $charset 字符串编码方式
* @return array|string 编码后的数据
*/
protected function htmlEncode($data, bool $valuesOnly = true, string $charset = 'UTF-8')
{
if (is_array($data)) {
$d = [];
foreach ($data as $key => $value) {
if (!$valuesOnly) {
$key = $this->htmlEncode($key, $valuesOnly, $charset);
}
$d[$key] = $this->htmlEncode($value, $valuesOnly, $charset);
}
$data = $d;
} elseif (is_string($data)) {
$data = htmlspecialchars($data, ENT_QUOTES | ENT_SUBSTITUTE, $charset);
}
return $data;
}
/**
* 解析所有 URL 编码过的字符
*
* @param array|string $data 将要被解码的数据
* @param bool $valuesOnly 是否只解码数组数值
* @return array|string 解码后的数据
*/
protected function urlDecode($data, bool $valuesOnly = true)
{
if (is_array($data)) {
$d = [];
foreach ($data as $key => $value) {
if (!$valuesOnly) {
$key = $this->urlDecode($key, $valuesOnly);
}
$d[$key] = $this->urlDecode($value, $valuesOnly);
}
$data = $d;
} elseif (is_string($data)) {
$data = urldecode($data);
}
return $data;
}
/**
* 判断是否是管理员登录状态
*
* @access public
* @return bool
*/
public function isAdmin(): bool
{
$hasLogin = User::alloc()->hasLogin();
if (!$hasLogin) {
return false;
}
return User::alloc()->pass('administrator', true);
}
/**
* 删除记录
*
* @access public
* @param array $ids
* @return void
*/
public function deleteLogs(array $ids)
{
foreach ($ids as $id) {
$this->db->query($this->db->delete('table.access')
->where('id = ?', $id)
);
}
}
/**
* 获取首次进入网站时的来源
*
* @access public
* @return string
*/
public function getEntryPoint(): string
{
$entrypoint = $this->request->getReferer();
if ($entrypoint == null) {
$entrypoint = Cookie::get('__typecho_access_entrypoint') ?: '';
}
if (parse_url($entrypoint, PHP_URL_HOST) == parse_url(Helper::options()->siteUrl, PHP_URL_HOST)) {
$entrypoint = '';
}
if ($entrypoint != null) {
Cookie::set('__typecho_access_entrypoint', $entrypoint);
}
return $entrypoint;
}
/**
* IPv6 地址转长字符串
*
* @param string $ipv6
* @return string
*/
public function ip62long(string $ipv6): string
{
$ip_n = inet_pton($ipv6);
$bits = 15;
$ipv6long = '';
while ($bits >= 0) {
$bin = sprintf("%08b", (ord($ip_n[$bits])));
$ipv6long = $bin . $ipv6long;
$bits--;
}
return gmp_strval(gmp_init($ipv6long, 2), 10);
}
/**
* 长字符还原 IPv6
*
* @param string $ipv6long
* @return false|string
*/
public function long2ip6(string $ipv6long)
{
$bin = gmp_strval(gmp_init($ipv6long, 10), 2);
if (strlen($bin) < 128) {
$pad = 128 - strlen($bin);
for ($i = 1; $i <= $pad; $i++) {
$bin = "0" . $bin;
}
}
$ipv6 = '';
$bits = 0;
while ($bits <= 7) {
$bin_part = substr($bin, ($bits * 16), 16);
$ipv6 .= dechex(bindec($bin_part)) . ":";
$bits++;
}
return inet_ntop(inet_pton(substr($ipv6, 0, -1)));
}
/**
* 记录当前访问(管理员登录不会记录)
*
* @access public
* @return void
*/
public function writeLogs($archive = null, $url = null, $content_id = null, $meta_id = null)
{
if ($this->isAdmin()) {
return;
}
if ($url == null) {
$url = $this->request->getServer('REQUEST_URI');
}
$ip = $this->request->getIp();
if ($ip == null) {
$ip = '0.0.0.0';
}
// 判断 IP 类型
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
$ip = bindec(decbin(ip2long($ip)));
} else if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
$ip = $this->ip62long($ip);
}
$entrypoint = $this->getEntryPoint();
$referer = $this->request->getReferer();
if (empty($referer)) {
$referer = '';
}
$time = Helper::options()->gmtTime + (Helper::options()->timezone - Helper::options()->serverTimezone);
if ($archive != null) {
$parsedArchive = $this->parseArchive($archive);
$content_id = $parsedArchive['content_id'];
$meta_id = $parsedArchive['meta_id'];
} else {
$content_id = is_numeric($content_id) ? $content_id : null;
$meta_id = is_numeric($meta_id) ? $meta_id : null;
}
$rows = [
'ua' => $this->ua->getUA(),
'browser_id' => $this->ua->getBrowserID(),
'browser_version' => $this->ua->getBrowserVersion(),
'os_id' => $this->ua->getOSID(),
'os_version' => $this->ua->getOSVersion(),
'url' => $url,
'path' => parse_url($url, PHP_URL_PATH),
'query_string' => parse_url($url, PHP_URL_QUERY),
'ip' => $ip,
'referer' => $referer,
'referer_domain' => parse_url($referer, PHP_URL_HOST),
'entrypoint' => $entrypoint,
'entrypoint_domain' => parse_url($entrypoint, PHP_URL_HOST),
'time' => $time,
'content_id' => $content_id,
'meta_id' => $meta_id,
'robot' => $this->ua->isRobot() ? 1 : 0,
'robot_id' => $this->ua->getRobotID(),
'robot_version' => $this->ua->getRobotVersion(),
];
try {
$this->db->query($this->db->insert('table.access')->rows($rows));
} catch (\Exception $e) {
}
}
/**
* 重新刷数据库,当遇到一些算法变更时可能需要用到
*
* @access public
* @return void
* @throws PluginException
*/
public static function rewriteLogs()
{
$db = Db::get();
$rows = $db->fetchAll($db->select()->from('table.access'));
foreach ($rows as $row) {
$ua = new UA($row['ua']);
$row['browser_id'] = $ua->getBrowserID();
$row['browser_version'] = $ua->getBrowserVersion();
$row['os_id'] = $ua->getOSID();
$row['os_version'] = $ua->getOSVersion();
$row['robot'] = $ua->isRobot() ? 1 : 0;
$row['robot_id'] = $ua->getRobotID();
$row['robot_version'] = $ua->getRobotVersion();
try {
$db->query($db->update('table.access')->rows($row)->where('id = ?', $row['id']));
} catch (Db\Exception $e) {
throw new PluginException(_t('刷新数据库失败:%s。', $e->getMessage()));
}
}
}
/**
* 解析archive对象
*
* @access public
* @param $archive
* @return array
*/
public function parseArchive($archive): array
{
$content_id = null;
$meta_id = null;
if ($archive->is('index')) {
$meta_id = 0;
} elseif ($archive->is('post') || $archive->is('page')) {
$content_id = $archive->cid;
} elseif ($archive->is('tag')) {
if (is_array($archive->tags) && !empty($archive->tags)) {
$meta_id = $archive->tags[0]['mid'];
}
} elseif ($archive->is('category')) {
if (is_array($archive->categories) && !empty($archive->categories)) {
$meta_id = $archive->categories[0]['mid'];
}
}
return [
'content_id' => $content_id,
'meta_id' => $meta_id,
];
}
/**
* 长整型转 IP 地址
*
* @param string $long
* @return false|string
*/
public function long2ip($long)
{
$len = trim(strlen($long));
if ($len == 38) {
return $this->long2ip6($long);
}
if ($long < 0 || $long > 4294967295) return false;
$ip = "";
for ($i = 3; $i >= 0; $i--) {
$ip .= (int)($long / pow(256, $i));
$long -= (int)($long / pow(256, $i)) * pow(256, $i);
if ($i > 0) $ip .= ".";
}
return $ip;
}
}