-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathAccess_Core.php
593 lines (553 loc) · 22.6 KB
/
Access_Core.php
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
<?php
if (!defined('__ACCESS_PLUGIN_ROOT__')) {
throw new RuntimeException('Bootstrap File Not Found');
}
class Access_Core
{
protected $db;
protected $request;
protected $response;
public $ua;
public $config;
public $action;
public $title;
public $logs = array();
public $overview = array();
public $referer = array();
/**
* 构造函数,根据不同类型的请求,计算不同的数据并渲染输出
*
* @access public
* @return void
*/
public function __construct()
{
# Load language pack
if (Typecho_I18n::getLang() !== 'zh_CN') {
$file = __TYPECHO_ROOT_DIR__ . __TYPECHO_PLUGIN_DIR__ .
'/Access/lang/' . Typecho_I18n::getLang() . '.mo';
file_exists($file) && Typecho_I18n::addLang($file);
}
# Init variables
$this->db = Typecho_Db::get();
$this->config = Typecho_Widget::widget('Widget_Options')->plugin('Access');
$this->request = Typecho_Request::getInstance();
$this->response = Typecho_Response::getInstance();
if ($this->config->pageSize == null || $this->config->isDrop == null) {
throw new Typecho_Plugin_Exception(_t('请先设置插件!'));
}
$this->ua = new Access_UA($this->request->getAgent());
switch ($this->request->get('action')) {
case 'overview':
$this->action = 'overview';
$this->title = _t('访问概览');
$this->parseOverview();
$this->parseReferer();
break;
case 'logs':
default:
$this->action = 'logs';
$this->title = _t('访问日志');
$this->parseLogs();
break;
}
}
/**
* 生成详细访问日志数据,提供给页面渲染使用
*
* @access public
* @return void
*/
protected function parseLogs()
{
$type = $this->request->get('type', 1);
$filter = $this->request->get('filter', 'all');
$pagenum = $this->request->get('page', 1);
$offset = (max((int)$pagenum, 1) - 1) * $this->config->pageSize;
$query = $this->db->select()->from('table.access')
->order('time', Typecho_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;
default:
break;
}
switch ($filter) {
case 'ip':
$ip = $this->request->get('ip', '');
$ip = bindec(decbin(ip2long($ip)));
$query->where('ip = ?', $ip);
$qcount->where('ip = ?', $ip);
break;
case 'post':
$cid = $this->request->get('cid', '');
$query->where('content_id = ?', $cid);
$qcount->where('content_id = ?', $cid);
break;
case 'path':
$path = $this->request->get('path', '');
$query->where('path = ?', $path);
$qcount->where('path = ?', $path);
break;
}
$list = $this->db->fetchAll($query);
foreach ($list as &$row) {
$ua = new Access_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;
}
}
$this->logs['list'] = $this->htmlEncode($this->urlDecode($list));
$this->logs['rows'] = $this->db->fetchAll($qcount)[0]['count'];
$filter = $this->request->get('filter', 'all');
$filterOptions = $this->request->get($filter);
$filterArr = array(
'filter' => $filter,
$filter => $filterOptions
);
$page = new Access_Page($this->config->pageSize, $this->logs['rows'], $pagenum, 10, array_merge($filterArr, array(
'panel' => Access_Plugin::$panel,
'action' => 'logs',
'type' => $type,
)));
$this->logs['page'] = $page->show();
$this->logs['cidList'] = $this->db->fetchAll($this->db->select('DISTINCT content_id as cid, COUNT(1) as count, table.contents.title')
->from('table.access')
->join('table.contents', 'table.access.content_id = table.contents.cid')
->where('table.access.content_id <> ?', null)
->group('table.access.content_id')
->order('count', Typecho_Db::SORT_DESC));
}
/**
* 生成来源统计数据,提供给页面渲染使用
*
* @access public
* @return void
*/
protected function parseReferer()
{
$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', Typecho_Db::SORT_DESC)->limit($this->config->pageSize));
$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', Typecho_Db::SORT_DESC)->limit($this->config->pageSize));
$this->referer = $this->htmlEncode($this->urlDecode($this->referer));
}
/**
* 生成用于图标的 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);
}
/**
* 生成总览数据,提供给页面渲染使用
*
* @access protected
* @return void
*/
protected function parseOverview(): void
{
$types = ['today', 'yesterday', 'month'];
# 分类分时段统计数据
foreach($types as $type) {
if($type == 'today' || $type == 'yesterday') {
if($type == 'today')
$time = date("Y-m-d");
else
$time = date("Y-m-d", strtotime('-1 day'));
$this->overview[$type]['time'] = $time;
# 按小时统计数据
for($hour = 0; $hour < 24; $hour++) {
$start = strtotime(date("{$time} {$hour}:00:00"));
$end = strtotime(date("{$time} {$hour}:59:59"));
// "SELECT DISTINCT ip FROM {$this->table} {$where} AND `time` BETWEEN {$start} AND {$end}"));
$subQuery = $this->db->select('DISTINCT ip')->from('table.access')
->where("time >= ? AND time <= ?", $start, $end);
if (method_exists($subQuery, 'prepare')) {
$subQuery = $subQuery->prepare($subQuery);
}
$this->overview[$type]['ip']['detail'][$hour] = (int)$this->db->fetchAll($this->db->select('COUNT(1) AS count')
->from('(' . $subQuery . ') AS tmp'))[0]['count'];
// "SELECT DISTINCT ip,ua FROM {$this->table} {$where} AND `time` BETWEEN {$start} AND {$end}"));
$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);
}
$this->overview[$type]['uv']['detail'][$hour] = (int)$this->db->fetchAll($this->db->select('COUNT(1) AS count')
->from('(' . $subQuery . ') AS tmp'))[0]['count'];
// "SELECT ip FROM {$this->table} {$where} AND `time` BETWEEN {$start} AND {$end}"));
$this->overview[$type]['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'];
}
# 统计当天总数据
$start = strtotime(date("{$time} 00:00:00"));
$end = strtotime(date("{$time} 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);
}
$this->overview[$type]['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 <= ?", $start, $end);
if (method_exists($subQuery, 'prepare')) {
$subQuery = $subQuery->prepare($subQuery);
}
$this->overview[$type]['uv']['count'] = (int)$this->db->fetchAll($this->db->select('COUNT(1) AS count')->from('(' . $subQuery . ') AS tmp'))[0]['count'];
$this->overview[$type]['pv']['count'] = (int)$this->db->fetchAll($this->db->select('COUNT(1) AS count')
->from('table.access')
->where("time >= ? AND time <= ?", $start, $end)
)[0]['count'];
} elseif($type == 'month') {
$year = date('Y');
$month = date("m");
$monthDays = cal_days_in_month(CAL_GREGORIAN, (int)$month, (int)$year); # 计算当月天数
$this->overview[$type]['time'] = $month;
# 按天统计数据
for($day = 1; $day <= $monthDays; $day++) {
$start = strtotime(date("{$year}-{$month}-{$day} 00:00:00"));
$end = strtotime(date("{$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);
}
$this->overview[$type]['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);
}
$this->overview[$type]['uv']['detail'][$day-1] = (int)$this->db->fetchAll($this->db->select('COUNT(1) AS count')
->from('(' . $subQuery . ') AS tmp'))[0]['count'];
$this->overview[$type]['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'];
}
}
}
# 统计总计数据
// "SELECT DISTINCT ip FROM {$this->table} {$where}"));
$this->overview['total']['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'];
// "SELECT DISTINCT ip,ua FROM {$this->table} {$where}"));
$this->overview['total']['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'];
// "SELECT ip FROM {$this->table} {$where}"));
$this->overview['total']['pv'] = (int)$this->db->fetchAll($this->db->select('COUNT(1) AS count')
->from('table.access'))[0]['count'];
# 输出用于图表的Json
$this->overview['chart_data'] = $this->makeChartJson();
}
/**
* 编码数组中的字符串为 HTML 实体
* 默认只有数组的值被编码,下标不被编码
* 如果数据类型是数组,那么它的所有子元素都将被递归编码
* 只有字符串类型才会被编码
* @param array $data 将要被编码的数据
* @param bool $valuesOnly 是否只编码数组数值,如果为 false 那么所有下标和值都将被编码
* @param string $charset 字符串编码方式,默认为 UTF-8
* @return array 编码后的数据
* @see http://www.php.net/manual/en/function.htmlspecialchars.php
*/
protected function htmlEncode($data, bool $valuesOnly = true, string $charset = 'UTF-8')
{
if (is_array($data)) {
$d = array();
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 $data 将要被解码的数据
* @param bool $valuesOnly 是否只解码数组数值,如果为 false 那么所有下标和值都将被解码
* @return array 解码后的数据
* @see http://www.php.net/manual/en/function.urldecode.php
*/
protected function urlDecode($data, bool $valuesOnly = true)
{
if (is_array($data)) {
$d = array();
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 = Typecho_Widget::widget('Widget_User')->hasLogin();
if (!$hasLogin) {
return false;
}
$isAdmin = Typecho_Widget::widget('Widget_User')->pass('administrator', true);
return $isAdmin;
}
/**
* 删除记录
*
* @access public
* @return void
*/
public function deleteLogs($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 = Typecho_Cookie::get('__typecho_access_entrypoint')?:'';
}
if (parse_url($entrypoint, PHP_URL_HOST) == parse_url(Helper::options()->siteUrl, PHP_URL_HOST)) {
$entrypoint = '';
}
if ($entrypoint != null) {
Typecho_Cookie::set('__typecho_access_entrypoint', $entrypoint);
}
return $entrypoint;
}
/**
* IPv6 地址转长字符串
*
* @param $ipv6
* @return string
*/
function ip62long($ipv6): string
{
$ip_n = inet_pton($ipv6);
$bits = 15; // 16 x 8 bit = 128bit
$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 $ipv6long
* @return false|string
*/
function long2ip6($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;
}
}
$bits = 0;
while ($bits <= 7) {
$bin_part = substr($bin, ($bits*16), 16);
$ipv6 .= dechex(bindec($bin_part)).":";
$bits++;
}
// compress
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 = array(
'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) {} catch (Typecho_Db_Query_Exception $e) {}
}
/**
* 重新刷数据库,当遇到一些算法变更时可能需要用到
*
* @access public
* @return void
* @throws Typecho_Plugin_Exception
*/
public static function rewriteLogs()
{
$db = Typecho_Db::get();
$rows = $db->fetchAll($db->select()->from('table.access'));
foreach ($rows as $row) {
$ua = new Access_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 (Typecho_Db_Exception $e) {
throw new Typecho_Plugin_Exception(_t('刷新数据库失败:%s。', $e->getMessage()));
}
}
}
/**
* 解析archive对象
*
* @access public
* @param $archive
* @return array
*/
public function parseArchive($archive): array
{
// 暂定首页的meta_id为0
$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')) {
$meta_id = $archive->tags[0]['mid'];
} elseif ($archive->is('category')) {
$meta_id = $archive->categories[0]['mid'];
} elseif ($archive->is('archive', 404)) {}
return array(
'content_id' => $content_id,
'meta_id' => $meta_id,
);
}
public function long2ip($long) {
// 判断是否为 IPv6 地址
$len = trim(strlen($long));
if($len ==38){
return $this->long2ip6($long);
}
// 判断是否为无效 IPv4 地址
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;
}
}