/
LVPIpManager.php
727 lines (610 loc) · 19.1 KB
/
LVPIpManager.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
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
<?php
/**
* LVPEchoHandler module for Nuwani v2
*
* @author Dik Grapendaal <dik@sa-mp.nl>
*/
class LVPIpManager implements LVPCommandRegistrar {
/**
* These constants are used to differentiate between nicknames and IPs
* in the command handler of this class.
*
* @var integer
*/
const TYPE_IP = 1;
const TYPE_RANGED_IP = 2;
const TYPE_NICKNAME = 3;
/**
* @var LVPDatabase
*/
private $Database;
/**
* @var LVPPlayerManager
*/
private $PlayerService;
/**
*
*/
public function __construct(LVPDatabase $database, LVPPlayerManager $playerService) {
$this->Database = $database;
$this->PlayerService = $playerService;
}
/**
* This method will register all the commands handled by this class to
* the LVPCommandHandler.
*/
public function registerCommands(LVPCommandHandler $commandService) {
$aCommands = array(
'!ipinfo' => LVP::LEVEL_ADMINISTRATOR,
'!ipinfoname' => LVP::LEVEL_ADMINISTRATOR,
'!iplocation' => LVP::LEVEL_ADMINISTRATOR,
'!iploc' => LVP::LEVEL_ADMINISTRATOR,
'!namelocation' => LVP::LEVEL_ADMINISTRATOR,
'!nameloc' => LVP::LEVEL_ADMINISTRATOR,
'!idlocation' => LVP::LEVEL_ADMINISTRATOR,
'!idloc' => LVP::LEVEL_ADMINISTRATOR,
'!hidename' => LVP::LEVEL_MANAGEMENT,
'!hideip' => LVP::LEVEL_MANAGEMENT
);
foreach ($aCommands as $sTrigger => $nLevel) {
$commandService->register(new LVPCommand(
$sTrigger,
$nLevel,
array($this, 'handleCommands')
));
}
}
/**
* This method provides us with a work around so that we always get a
* signed integer.
*
* @param string $ip The IP address in dotted format.
* @return integer
*/
public function ip2long($ip) {
list(, $longIp) = unpack('l', pack('l', ip2long($ip)));
return $longIp;
}
/**
* This method returns true when the given ID is numeric and between 0
* and 199. These are valid IDs within SA-MP.
*
* @param integer $id The ID to check for validness.
* @return boolean
*/
public function isValidId($id) {
return is_numeric($id) && $id >= 0 && $id <= 199;
}
/**
* This method checks if the given input string is a valid IP statement.
* What's so special about this method however, is that it incorporates
* ranged inputs, like 255.255.*.*, but *.*.*.* is not accepted. It also
* checks if every octet is between 0 and 255, if it's not a wildcard.
*
* @param string $ip The input string we want to check.
* @return boolean
*/
public function isRangedIp($ip) {
$matches = array ();
if (preg_match('/^(\d{1,3})\.(\d{1,3}|\*)\.(\d{1,3}|\*)\.\*$/', $ip, $matches) == 0) {
return false;
}
unset($matches[0]);
foreach ($matches as $octet) {
if ($octet == '*') {
continue;
}
if ($octet < 0 || $octet > 255) {
return false;
}
}
return true;
}
/**
* This method checks if the given string is a valid IP. Wildcards are
* not considered valid by this method.
*
* @param string $ip The input string to check.
* @return boolean
*/
public function isValidIp($ip) {
return ip2long($ip) !== false;
}
/**
* This method will simply check if the given IP address is an IPv6
* address or not.
*
* @param string $ip The IP string to check.
* @return boolean
*/
public function isValidIpV6($ip) {
return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false;
}
/**
* This method deals with processing the command input from IRC. It
* determines what needs to be done according to the trigger and the
* given parameters. It then uses the methods in this class to gather
* the requested information and outputs a message understandable for
* human beings with the information they need.
*
* @param integer $mode The mode the command is executing in.
* @param integer $level The level we're operating at.
* @param string $channel The channel we'll be sending our output to.
* @param string $nickname The nickname who triggered the command.
* @param string $trigger The trigger that set this in motion.
* @param string $params All of the text following the trigger.
* @param array $splitParams Same as above, except split into an array.
* @return string
*/
public function handleCommands($mode, $level, $channel, $nickname, $trigger, $params, $splitParams) {
switch ($trigger) {
case '!ipinfo':
case '!ipinfoname':
return $this->handleIpInfo($level, $trigger, $params, $splitParams);
case '!iplocation':
case '!iploc':
return $this->handleIpLocation($trigger, $params, $splitParams);
case '!namelocation':
case '!nameloc':
case '!idlocation':
case '!idloc':
return $this->handleNameLocation($trigger, $params, $splitParams);
case '!hideip':
case '!hidename':
return $this->handleHideFake($trigger, $params, $splitParams);
default:
echo 'This command has not been implemented.';
return LVPCommand::OUTPUT_ERROR;
}
}
/**
* For the hypocrites on LVP, I've especially built a hiding feature for
* both names as well as IPs. This method provides the code that will
* allow the management to set a fake string that's shown instead of the
* real information.
*
* @param string $sTrigger The trigger that set this in motion.
* @param string $sParams All of the text following the trigger.
* @param array $aParams Same as above, except split into an array.
* @return string
*/
private function handleHideFake($sTrigger, $sParams, $aParams) {
if ($sParams == null || count ($aParams) == 0) {
echo $sTrigger . ' ';
switch ($sTrigger) {
case '!hideip':
echo 'IP';
break;
case '!hidename':
echo 'Name';
break;
}
echo ' [FakeMessage]';
return LVPCommand::OUTPUT_USAGE;
}
$sSubject = Util::stripFormat(array_shift($aParams));
$sOrigSubject = $sSubject;
$sFakeString = empty ($aParams) ? null : implode (' ', $aParams);
if ($this->isValidIpV6($sSubject)) {
echo 'No IPv6 support.';
return LVPCommand::OUTPUT_ERROR;
}
else if ($this->isRangedIp($sSubject)) {
echo 'It\'s not possible to hide a complete range.';
return LVPCommand::OUTPUT_ERROR;
}
if ($this->isValidIp($sSubject)) {
$sTable = 'samp_address_hide_ip';
$sField = 'ip_address';
$sBindParam = 'i';
$sSubject = $this->ip2long($sSubject);
} else {
$sTable = 'samp_address_hide_nickname';
$sField = 'nickname';
$sBindParam = 's';
}
$sQuery =
'SELECT
display_string
FROM
' . $sTable . '
WHERE
' . $sField . ' = ?';
$pStatement = $this->Database->prepare($sQuery);
if ($pStatement === false) {
echo 'There seems to be a problem with the database. Try again later.';
return LVPCommand::OUTPUT_ERROR;
}
$pStatement->bind_param($sBindParam, $sSubject);
$pStatement->bind_result($sOldFakeString);
if (!$pStatement->execute()) {
echo 'Database error: ' . $pStatement -> error;
return LVPCommand::OUTPUT_ERROR;
}
$pStatement->close();
$sQuery =
'INSERT INTO ' . $sTable . ' (
' . $sField . ', display_string
) VALUES (
?, ?
) ON DUPLICATE KEY UPDATE display_string = ?';
$pStatement = $this->Database->prepare($sQuery);
if ($pStatement === false) {
echo 'There seems to be a problem with the database. Try again later.';
return LVPCommand::OUTPUT_ERROR;
}
$pStatement->bind_param($sBindParam . 'ss', $sSubject, $sFakeString, $sFakeString);
if ($pStatement->execute()) {
echo '"' . $sOrigSubject . '" is now hidden.';
return LVPCommand::OUTPUT_SUCCESS;
} else {
echo 'Database error: ' . $pStatement->error;
return LVPCommand::OUTPUT_ERROR;
}
}
/**
* This method will handle the !iplocation command. It takes an IP
* address or hostname as a parameter, and will report the found
* locations using the GeoIP database.
*
* @param string $sTrigger The trigger that set this in motion.
* @param string $sParams All of the text following the trigger.
* @param array $aParams Same as above, except split into an array.
* @return string
*/
private function handleIpLocation($sTrigger, $sParams, $aParams) {
if ($sParams !== null) {
$sParams = Util::stripFormat($sParams);
}
if ($sParams === null || $sParams === '') {
echo $sTrigger . ' IP // ' . $sTrigger . ' Hostname';
return LVPCommand::OUTPUT_USAGE;
}
if ($this->isValidIpV6($sParams)) {
echo 'No IPv6 support.';
return LVPCommand::OUTPUT_ERROR;
}
else if ($this->isRangedIp($sParams)) {
echo 'It\'s not possible to determine the location from a range.';
return LVPCommand::OUTPUT_ERROR;
}
$pLocation = new Location();
if ($this->isValidIp($sParams)) {
echo ModuleBase::COLOUR_TEAL . '* ';
echo 'Location info for IP "' . $sParams . '"' . ModuleBase::CLEAR . ': ';
$aInfo = $pLocation->lookup($sParams);
$bFirst = true;
foreach ($aInfo as $sKey => $sValue) {
if ($sKey == 'country_2') continue;
if ($sValue != '--') {
if ($bFirst) $bFirst = false;
else echo ', ';
echo ucfirst($sKey) . ': ' . $sValue;
}
}
return LVPCommand::OUTPUT_NORMAL;
} else {
// Hostname, resolve it and show the countries.
$aIps = gethostbynamel($sParams);
if ($aIps === false) {
echo 'Could not resolve the hostname.';
return LVPCommand::OUTPUT_ERROR;
}
echo ModuleBase::COLOUR_TEAL . '* ';
echo 'Location info for hostname "' . $sParams . '"' . ModuleBase::CLEAR . ': ';
$bFirst = true;
foreach ($aIps as $sIp) {
$aInfo = $pLocation->lookup($sIp);
if ($bFirst) $bFirst = false;
else echo ', ';
echo $sIp . ' - ' . $aInfo ['country'];
}
return LVPCommand::OUTPUT_NORMAL;
}
}
/**
* The !namelocation command is handled in this method. It takes only a
* nickname as a parameter and will lookup all IPs with this nickname
* in the database. After that, all locations will be looked up and
* processed for uniqueness.
*
* @param string $sTrigger The trigger that set this in motion.
* @param string $sParams All of the text following the trigger.
* @param array $aParams Same as above, except split into an array.
* @return string
*/
private function handleNameLocation($sTrigger, $sParams, $aParams) {
if ($sParams !== null) {
$sParams = Util::stripFormat($sParams);
}
if ($sParams === null || $sParams === '') {
echo $sTrigger . ' Name // ' . $sTrigger . ' ID';
return LVPCommand::OUTPUT_USAGE;
}
if ($this->isValidId($sParams)) {
$pPlayer = $this->PlayerService->getPlayer($sParams);
if ($pPlayer == null) {
echo 'ID not found.';
return LVPCommand::OUTPUT_ERROR;
}
$sParams = $pPlayer['Nickname'];
}
$pStatement = $this->Database->prepare(
'SELECT
ip_address,
COUNT(ip_address) num_ip
FROM
lvp_mainserver.sessions
WHERE
nickname = ?
GROUP BY
ip_address
ORDER BY
num_ip DESC
LIMIT 15'
);
if ($pStatement === false) {
echo 'There seems to be a problem with the database. Try again later.';
return LVPCommand::OUTPUT_ERROR;
}
$pStatement->bind_param('s', $sParams);
$pStatement->bind_result($nLongIp, $nNumIps);
if ($pStatement->execute()) {
$pLocation = new Location();
$aCountries = array();
while ($pStatement->fetch()) {
$aInfo = $pLocation->lookup(long2ip($nLongIp));
if ($aInfo['country'] == 'Unknown') continue;
if (!isset($aCountries[$aInfo['country']])) {
$aCountries[$aInfo['country']] = array(
'Num' => 0,
'City' => array()
);
}
$aCountries[$aInfo['country']]['Num'] += $nNumIps;
if ($aInfo['city'] == '' || $aInfo['city'] == '--') continue;
if (!isset ($aCountries[$aInfo['country']]['City'][$aInfo ['city']])) {
$aCountries[$aInfo['country']]['City'][$aInfo ['city']] = 0;
}
$aCountries[$aInfo['country']]['City'][$aInfo ['city']]++;
}
echo ModuleBase::COLOUR_TEAL . '* Location info for "' . $sParams . '"';
echo ModuleBase::CLEAR . ': ';
$bFirst = true;
foreach ($aCountries as $sCountry => $aInfo) {
if ($bFirst) $bFirst = false;
else echo ', ';
echo $sCountry . ModuleBase::COLOUR_DARKGREY . ' (';
$bFirst = true;
foreach ($aInfo['City'] as $sCity => $nNum) {
if ($bFirst) $bFirst = false;
else echo ', ';
echo $sCity;
if ($nNum > 1) {
echo ' x' . $nNum;
}
}
$bFirst = false;
echo ')' . ModuleBase::CLEAR;
}
return LVPCommand::OUTPUT_NORMAL;
} else {
echo 'Error with the database: ' . $pStatement -> error;
return LVPCommand::OUTPUT_ERROR;
}
}
/**
* Probably one of the most and most important commands of the whole bot
* is handled in this quite large method. This command will determine
* what kind of information is requested first. If given an IP or an IP
* range, the command will return all nicknames found with that IP or in
* that IP range. If given a nickname, it will simply return all the IPs
* found with that nickname. Some additional parsing and adjustments in
* the query make the output easily readable and understandable.
*
* Note to reader: this method is ugly. Sorry.
*
* @param integer $nLevel The level we're operating at.
* @param string $sTrigger The trigger that set this in motion.
* @param string $sParams All of the text following the trigger.
* @param array $aParams Same as above, except split into an array.
* @return string
*/
private function handleIpInfo($nLevel, $sTrigger, $sParams, $aParams) {
if ($sParams !== null) {
$sParams = Util::stripFormat($sParams);
}
if ($sParams === null || $sParams === '' || count($aParams) > 1) {
echo $sTrigger . ' IP // ' .
$sTrigger . ' Name // ' .
$sTrigger . ' ID';
return LVPCommand::OUTPUT_USAGE;
}
$bForceName = false;
if (strpos($sTrigger, 'name') !== false) {
$bForceName = true;
}
if ($this->isValidId($sParams)) {
$pPlayer = $this->PlayerService->getPlayer($sParams);
if ($pPlayer == null) {
echo 'ID not found.';
return LVPCommand::OUTPUT_ERROR;
}
$sParams = $pPlayer['Nickname'];
}
$sOrigParams = $sParams;
$nType = self::TYPE_NICKNAME;
if (!$bForceName) {
if ($this->isValidIpV6($sParams)) {
echo 'Sorry, no IPv6 support.';
return LVPCommand::OUTPUT_ERROR;
}
else if ($this->isValidIp($sParams)) {
$nType = self::TYPE_IP;
}
else if ($this->isRangedIp($sParams)) {
$nType = self::TYPE_RANGED_IP;
}
}
if ($nLevel < LVP::LEVEL_MANAGEMENT && ($nType == self::TYPE_NICKNAME || $nType == self::TYPE_IP)) {
if ($nType == self::TYPE_NICKNAME) {
$sTable = 'samp_address_hide_nickname';
$sField = 'nickname';
$sBindParam = 's';
$sQueryParam = $sParams;
}
else if ($nType == self::TYPE_IP) {
$sTable = 'samp_address_hide_ip';
$sField = 'ip_address';
$sBindParam = 'i';
$sQueryParam = $this->ip2long($sParams);
}
else {
echo 'Unknown error occurred.';
return LVPCommand::OUTPUT_ERROR;
}
$pStatement = $this->Database->prepare(
'SELECT
display_string
FROM
' . $sTable . '
WHERE
' . $sField . ' = ?'
);
if ($pStatement === false) {
echo 'There seems to be a problem with the database. Try again later.';
return LVPCommand::OUTPUT_ERROR;
}
$pStatement->bind_param($sBindParam, $sQueryParam);
$pStatement->bind_result($sFakeString);
$pStatement->execute();
$pStatement->store_result();
if ($pStatement->num_rows != 0) {
$pStatement->fetch();
// Hide it.
if ($sFakeString == null) {
echo ModuleBase::COLOUR_TEAL . '* No results found.';
return LVPCommand::OUTPUT_NORMAL;
} else {
echo ModuleBase::COLOUR_TEAL . '* Result with "' . $sParams . '"';
echo ModuleBase::CLEAR . ': ' . $sFakeString;
return LVPCommand::OUTPUT_NORMAL;
}
}
$pStatement->close();
}
$pDatabase = $this->Database;
$sQuery =
'SELECT
nickname,
GROUP_CONCAT(DISTINCT ip_address) ip_address,
COUNT(*) num,
MAX(session_date) session_date,
GROUP_CONCAT(DISTINCT user_id) user_id
FROM
lvp_mainserver.sessions
WHERE ';
switch ($nType) {
case self::TYPE_IP:
$sQuery .= 'ip_address = ' . $this->ip2long($sParams);
break;
case self::TYPE_RANGED_IP:
$nMinIp = $this->ip2long(str_replace('*', '0', $sParams));
$nMaxIp = $this->ip2long(str_replace('*', '255', $sParams));
$sQuery .= 'ip_address >= ' . $nMinIp . ' AND ip_address <= ' . $nMaxIp;
break;
case self::TYPE_NICKNAME:
$sQuery .= 'nickname = "' . $pDatabase->escape($sParams) . '"';
break;
}
if ($nLevel < LVP::LEVEL_MANAGEMENT && ($nType == self::TYPE_NICKNAME || $nType == self::TYPE_IP)) {
if ($nType == self::TYPE_NICKNAME) {
$sTable = 'lvp_website.samp_address_hide_ip';
$sField = 'ip_address';
} else if ($nType == self::TYPE_IP) {
$sTable = 'lvp_website.samp_address_hide_nickname';
$sField = 'nickname';
}
$sQuery .= ' AND ' . $sField . ' NOT IN(
SELECT ' . $sField . '
FROM ' . $sTable . '
)';
}
$sQuery .= ' GROUP BY ';
switch ($nType) {
case self::TYPE_IP:
case self::TYPE_RANGED_IP:
$sQuery .= 'nickname';
break;
case self::TYPE_NICKNAME:
$sQuery .= 'ip_address';
break;
}
$sQuery .=
' ORDER BY
session_date DESC
LIMIT 15';
$pResult = $pDatabase->query($sQuery);
if ($pResult === false) {
echo 'There seems to be a problem with the database. Try again later.';
return LVPCommand::OUTPUT_ERROR;
}
if ($pResult->num_rows == 0) {
echo ModuleBase::COLOUR_TEAL . '* No results found.';
return LVPCommand::OUTPUT_NORMAL;
}
echo ModuleBase::COLOUR_TEAL . '* ';
switch ($nType) {
case self::TYPE_IP:
echo 'Names from IP';
break;
case self::TYPE_RANGED_IP:
echo 'Names in IP range';
break;
case self::TYPE_NICKNAME:
echo 'IPs with name';
break;
}
echo ' "' . $sOrigParams . '"' . ModuleBase::CLEAR . ': ';
$nUnderlineDiff = 86400 * 3;
$nTime = time ();
$bFirst = true;
$pLocation = new Location();
while (($aRow = $pResult->fetch_assoc()) !== null) {
if ($bFirst) $bFirst = false;
else echo ', ';
$bUnderline = false;
if ($nTime - strtotime($aRow['session_date']) <= $nUnderlineDiff) {
$bUnderline = true;
echo ModuleBase::UNDERLINE;
}
switch ($nType) {
case self::TYPE_NICKNAME:
echo long2ip($aRow['ip_address']);
break;
case self::TYPE_IP:
case self::TYPE_RANGED_IP:
echo $aRow['nickname'];
break;
}
if ($bUnderline) {
// Reset
echo ModuleBase::UNDERLINE;
}
$aInfo = $pLocation->lookup(long2ip(explode(',', $aRow['ip_address'])[0]));
$aRow['country'] = $aInfo['country_2'];
if ($aRow['num'] > 1 || ($aRow['country'] != '--' && $aRow['country'] != '')) {
// Darker color so that other information stays readable.
echo ModuleBase::COLOUR_DARKGREY;
if ($aRow ['num'] > 1) {
echo ' (x' . $aRow['num'] . ')';
}
if ($aRow['country'] != '--' && $aRow['country'] != '') {
echo ' (' . $aRow['country'] . ')';
}
echo ModuleBase::CLEAR;
}
}
return LVPCommand::OUTPUT_NORMAL;
}
}