-
Notifications
You must be signed in to change notification settings - Fork 12
/
lastlogin.php
510 lines (447 loc) · 14.2 KB
/
lastlogin.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
<?php
/**
* Roundcube Plugin Lastlogin.
*
* Roundcube plugin to provide information (IP, DNS, Geo) about the user last logins.
*
* @author Diana Soares <diana.soares@gmail.com>
* @license GPL-3.0+
* @requires geolocation
* @version 1.3.0
*
* Copyright (C) Diana Soares
*
* This program is a Roundcube (http://www.roundcube.net) plugin.
* For more information see README.md.
* For configuration see config.inc.php.dist.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Roundcube. If not, see http://www.gnu.org/licenses/.
*/
class lastlogin extends rcube_plugin
{
public $task = 'login|mail|settings';
private $log_table = 'userlogins';
private $rc;
/**
* Plugin initialization.
*/
public function init()
{
$this->load_config('config.inc.php.dist');
$this->load_config();
$this->add_texts('localization/');
$this->rc = rcmail::get_instance();
if ($this->rc->config->get('lastlogin_geolocation')) {
$this->require_plugin('geolocation');
}
// add hooks
if (!$this->get_flag() && $this->rc->task == 'login' && $this->rc->action == 'login') {
$this->add_hook('login_after', [$this, 'login_after']);
$this->add_hook('login_after', [$this, 'write_log']);
} elseif ($this->get_flag() && $this->rc->task == 'mail') {
$this->add_hook('render_page', [$this, 'render_page']);
} elseif ($this->rc->task == 'settings') {
$this->add_hook('preferences_list', [$this, 'preferences_list']);
$this->add_hook('preferences_save', [$this, 'preferences_save']);
$this->add_hook('settings_actions', [$this, 'settings_actions']);
$this->register_action('plugin.lastlogin', [$this, 'show_more']);
}
}
/**
* Render page hook.
*/
public function render_page($args)
{
$this->show_info();
$this->save_info();
$this->unset_flag();
return $args;
}
/**
* Login after hook.
*/
public function login_after($args)
{
$this->set_flag();
return $args;
}
/**
* Show last login information.
*/
public function show_info()
{
$vars = $this->get_info();
if (!empty($vars['from']) && !empty($vars['date']) && $vars['timeout'] > 0) {
$this->api->output->show_message('lastlogin.lastlogin_info', 'notice', $vars, false, $vars['timeout']);
}
}
/**
* Get last login information.
*/
public function get_info()
{
$info = $this->rc->config->get('lastlogin', []);
if (!isset($info['timeout'])) {
$info['timeout'] = intval($this->rc->config->get('lastlogin_timeout'));
}
$info['more'] = $this->rc->url(['_task'=>'settings', '_action'=>'plugin.lastlogin']);
$info['date'] = $this->_format_date($info['date']);
$info['dns'] = $this->get_dns($info['from']);
if ($info['dns'] != '') {
$info['dns'] = " (".$info['dns'].") ";
}
if ($info['geo'] != '') {
$info['geo'] = " (".$info['geo'].") ";
}
return $info;
}
/**
* Save last login information.
*/
public function save_info()
{
$ip = $this->remote_ip('single');
$info = $this->rc->config->get('lastlogin', []);
$info = [
'from' => $ip,
'date' => date('U'),
'geo' => $this->get_geo($ip),
'timeout' => (isset($info['timeout'])
? $info['timeout']
: intval($this->rc->config->get('lastlogin_timeout')))
];
$this->rc->user->save_prefs(['lastlogin'=>$info]);
}
/**
* Insert login information into database on a successful login
*/
public function write_log($args)
{
$username = $this->rc->user->get_username('local');
$user_id = $this->rc->user->ID;
// in a failed login, do nothing
if ($user_id <= 0) {
return $args;
}
$sess_id = session_id();
$ips = $this->remote_ip();
$ip = $this->remote_ip('single');
$geo = $this->get_geo($ip);
$dns = $this->get_dns($ip);
$tor = $this->is_tor($ip);
$ua = ($this->rc->config->get('lastlogin_useragent', false) ? $_SERVER['HTTP_USER_AGENT'] : '');
$sql = "INSERT INTO " . $this->table_name() .
"(user_id, username, sess_id, ip, real_ip, hostname, geoloc, ua".($tor ? ", tor" : "").")".
" VALUES (?, ?, ?, ?, ?, ?, ?, ?".($tor ? ", TRUE" : "").")";
$ret = $this->rc->db->query(
$sql,
$user_id,
$username,
$sess_id,
$ips['ip'],
$ips['forwarded_ip'],
$dns,
$geo,
$ua
);
if ($ret) {
$args['abort'] = false;
}
return $args;
}
/**
* Load current user log.
*/
public function load_log()
{
$sth = $this->rc->db->limitquery(
"SELECT hostname, geoloc, ua"
.", CASE WHEN real_ip<>'' THEN real_ip ELSE ip END AS `from`"
.", " . $this->unixtimestamp('timestamp') . " AS `date`"
." FROM " . $this->table_name()
." WHERE user_id = ? "
." ORDER BY id DESC ",
0,
intval($this->rc->config->get('lastlogin_lastrecords')),
$this->rc->user->ID
);
$rows = [];
while ($res = $this->rc->db->fetch_assoc($sth)) {
$rows[] = $res;
}
return $rows;
}
/**
* Get session flag.
*/
private function get_flag()
{
return $_SESSION['plugin.lastlogin.show_info'];
}
/**
* Set session flag to show last login information.
*/
private function set_flag()
{
$_SESSION['plugin.lastlogin.show_info'] = true;
}
/**
* Unset session flag.
*/
private function unset_flag()
{
$_SESSION['plugin.lastlogin.show_info'] = false;
}
/**
* Add a tab to Settings.
*/
public function settings_actions($args)
{
$args['actions'][] = [
'action' => 'plugin.lastlogin',
'class' => 'lastlogin',
'label' => 'lastlogin',
'domain' => 'lastlogin',
];
return $args;
}
/**
* Lastlogin settings tab/menu entry.
*/
public function show_more()
{
$this->register_handler('plugin.body', [$this, 'infohtml']);
$this->rc->output->set_pagetitle($this->gettext('lastlogin'));
$this->rc->output->send('plugin');
}
/**
* Settings tab content.
*/
public function infohtml()
{
$this->include_stylesheet($this->local_skin_path()."/lastlogin.css");
$html = html::tag(
'fieldset',
'',
html::tag('legend', null, $this->gettext('recentactivity'))
. $this->recentlogins()
. html::tag('p', 'license', $this->gettext('geoip_license'))
);
return html::div(
['class' => 'box formcontent lastlogin'],
html::div(['class' => 'boxtitle'], $this->gettext('lastlogin')) .
html::div(['class' => 'boxcontent propform'], $html)
);
}
/**
* Display lastlogin preferences tab.
*/
public function preferences_list($args)
{
if ($args['section'] == 'general'
&& !in_array('lastlogin_timeout', (array)$this->rc->config->get('dont_override'))
) {
$this->include_stylesheet($this->local_skin_path()."/lastlogin.css");
$field_id = 'rcmfd_lastlogin_timeout';
$info = $this->get_info();
$value = intval($info['timeout']);
$input = new html_select(['name' => '_lastlogin_timeout', 'id' => $field_id]);
$input->add($this->gettext('never'), '0');
foreach ([5, 10, 15, 20] as $sec) {
$input->add($this->gettext(['name'=>'fornseconds', 'vars'=>['n'=>$sec]]), $sec);
}
$args['blocks']['main']['options']['timeout'] = [
'title' => html::label($field_id, $this->gettext('timeout')),
'content' => $input->show($value),
];
}
return $args;
}
/**
* Save preferences.
*/
public function preferences_save($args)
{
if ($args['section'] == 'general') {
$config = $this->rc->config->get('lastlogin', []);
$dont_override = (array) $this->rc->config->get('dont_override');
if (!in_array('lastlogin_timeout', $dont_override)) {
$config['timeout'] = intval(
rcube_utils::get_input_value(
'_lastlogin_timeout',
rcube_utils::INPUT_POST
)
);
}
$args['prefs']['lastlogin'] = $config;
}
return $args;
}
/**
* HTML table with recent user logins.
*/
public function recentlogins()
{
$table = new html_table(
['cols'=>5, 'class'=>'uibox records-table',
'border'=>1, 'cellspacing'=>0, 'cellpadding'=>4]
);
foreach (['timestamp', 'ip', 'hostname', 'location', 'ua'] as $key) {
$key = rcube::Q($this->gettext($key));
$table->add_header(['title' => $key], $key);
}
$logs = $this->load_log();
foreach ($logs as $log) {
$date = $this->_format_date($log['date']);
$geo = $log['geoloc'];
$dns = $log['hostname'];
$ua = $log['ua'];
$from = (
$this->rc->config->get('lastlogin_mask_ip', false)
? preg_replace('/\.[0-9]{0,3}\.[0-9]{0,3}\./', '.*.*.', $log['from'])
: $log['from']
);
$table->add([], rcube::Q($date));
$table->add([], rcube::Q($from));
$table->add([], rcube::Q($dns));
$table->add([], rcube::Q($geo));
$table->add(['title' => rcube::Q($ua)], rcube::Q($ua));
}
return $table->show();
}
/**
* Returns remote IP address and forwarded addresses if found.
* Based on roundcube rcube_utils::remote_ip().
*
* @param string $mode mode=(multiple|single)
*
* @return array
*/
private function remote_ip($mode='multiple')
{
$ips = [
'ip' => $_SERVER['REMOTE_ADDR'],
'real_ip' => '',
'forwarded_ip' => ''
];
// append the NGINX X-Real-IP header, if set
if (!empty($_SERVER['HTTP_X_REAL_IP'])) {
$ips['real_ip'] = $_SERVER['HTTP_X_REAL_IP'];
}
// append the X-Forwarded-For header, if set
if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ips['forwarded_ip'] = $_SERVER['HTTP_X_FORWARDED_FOR'];
}
// if mode is single, return only one IP
if ($mode == 'single') {
foreach (['forwarded_ip', 'real_ip'] as $k) {
if ($ips[$k] != '') {
return $ips[$k];
}
}
return $ips['ip'];
}
return $ips;
}
/**
* DNS name.
*/
private function get_dns($ip)
{
if ($this->rc->config->get('lastlogin_dns')) {
$dns = (intval($ip) ? gethostbyaddr($ip) : '');
if ($dns != $ip) {
return $dns;
}
}
return '';
}
/**
* Geolocation info.
*/
private function get_geo($ip)
{
if (! $this->rc->config->get('lastlogin_geolocation')) {
return '';
}
$geo = geolocation::get_instance()->get_geolocation($ip);
if (is_array($geo)) {
$geo = array_map('trim', $geo);
$geo = array_filter($geo);
$geo = implode(', ', $geo);
}
return $geo;
}
/**
* Check if IP is a TOR-network exit point.
*/
private function is_tor($ip)
{
if ($this->rc->config->get('lastlogin_tor')) {
$ip = $this->reverse_ip_octets($ip).
".".$_SERVER['SERVER_PORT'].
".".$this->reverse_ip_octets($_SERVER['SERVER_ADDR']).
$this->rc->config->get('lastlogin_tor_suffix');
$tor_ip = $this->rc->config->get('lastlogin_tor_ip');
return (gethostbyname($ip) == $tor_ip);
}
return false;
}
/**
* Reverse the octets of an IP.
*/
private function reverse_ip_octets($ip)
{
return implode('.', array_reverse(explode('.', $ip)));
}
/**
* Return SQL statement to convert a field value into a unix timestamp.
*/
private function unixtimestamp($field)
{
switch ($this->rc->db->db_provider) {
case 'sqlite':
$ts = ($field === 'NOW()') ? "strftime('%s', 'now')" : $field;
break;
case 'pgsql':
case 'postgres':
$ts = "EXTRACT (EPOCH FROM $field)";
break;
default:
$ts = "UNIX_TIMESTAMP($field)";
}
return $ts;
}
/**
* Format date.
*/
private function _format_date($date)
{
if ($date >= strtotime("today")) {
$wday = preg_replace("//", "\\", ucfirst($this->gettext('today')));
} elseif ($date >= strtotime("yesterday")) {
$wday = preg_replace("//", "\\", ucfirst($this->gettext('yesterday')));
} else {
$wday = 'l';
}
return $this->rc->format_date($date, "$wday, d F Y, H:i");
}
/**
* Get table name.
*/
private function table_name()
{
return $this->rc->db->table_name($this->log_table, true);
}
}