Script: stalker.pl

Record and correlate nick!user@host information.
Author: nils_2 — Version: 1.6.3 — License: GPL3
For WeeChat ≥ 0.3.4, requires: DBD::SQLite.
Tags: irc
Added: 2013-05-01 — Updated: 2021-11-06

Download GitHub Repository

   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
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
#
# Copyright (c) 2013-2018 by Nils Görs <weechatter@arcor.de>
# Copyright (c) 2013-2014 by Stefan Wold <ratler@stderr.eu>
# based on irssi script stalker.pl from Kaitlyn Parkhurst (SymKat) <symkat@symkat.com>
# https://github.com/symkat/Stalker
#
# Records and correlates nick!user@host information
#
# 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 this program.  If not, see <http://www.gnu.org/licenses/>.
#
# History:
#
# version 1.6.3: Sébastien Helleu <flashcode@flashtux.org>
# 2021-11-06: add: compatibility with WeeChat >= 3.4 (new parameters in function hdata_search)
#
# version 1.6.2: Sébastien Helleu <flashcode@flashtux.org>
# 2021-05-06: add: compatibility with WeeChat >= 3.2 (XDG directories)
#
# version 1.6.1: nils_2@freenode.#weechat
# 2018-01-11: fix: wrong variable name
#
# version 1.6: nils_2@freenode.#weechat
# 2018-01-09: add: use hook_process_hashtable() for /WHOIS
#           : imp: use hook_process_hashtable() instead hook_process() for security reasons
#
# version 1.5: nils_2@freenode.#weechat
# 2015-06-15: add: new option del_date
#
# version 1.4: nils_2@freenode.#weechat
# 2014-05-14: fix: perl error under some circumstances (thanks Piotrek)
#
# version 1.3: nils_2@freenode.#weechat
# 2014-04-28: fix: output when loading script twice
#
# version 1.2: nils_2@freenode.#weechat
# 2014-04-13: add: support of customise irc_join messages (weechat >= 0.4.4)
#
# version 1.1: nils_2@freenode.#weechat
# 2013-10-31: add: flood-protection on JOINs
#
# version 1.0: nils_2@freenode.#weechat
# 2013-10-28: add: option 'additional_join_info' (idea by: arch_bcn)
#             add: option 'timeout' time to wait for result of hook_process()
#             add: localvar 'drop_additional_join_info'
#             add: hook_process() to prevent blocking weechat on slower machines (like rpi)
#             add: more DEBUG informations
#
# version 0.9: Ratler@freenode.#weechat
# 2013-08-11: fix: removed trailing whitespaces
#             fix: only add index if it doesn't exist
#             fix: dynamically create or upgrade database based on missing tables or columns
#             fix: allow dynamically creating indices for future tables
#
# version 0.8: Ratler@freenode.#weechat
# 2013-08-09: add: case insensitive nick search
#             add: show "server.nickname" in search results when search_this_network_only is set to off
#             fix: type no longer needed for _ignore_guests()
#
# version 0.7: nils_2@freenode.#weechat
# 2013-08-04: add: support of colors with format "${color:xxx}" (>= WeeChat 0.4.2)
#             add: function "remove_nick_from_host" (patch by FiXato)
#
# version 0.6: nils_2@freenode.#weechat
# 2013-05-27: cleanup code
#
# version 0.5: nils_2@freenode.#weechat
# 2013-05-26: add: function 'count'
#
# version 0.4: nils_2@freenode.#weechat
# 2013-05-18: add: option 'tags'
#
# version 0.3: nils_2@freenode.#weechat
# 2013-05-05: fix: typos in help and description option (thanks FiXato)
#             add: 'ChanServ' to option 'guest_nick_regex'
#
# version 0.2: nils_2@freenode.#weechat
# 2013-05-01: fix: bug with regular expressions using /whois
#             removed: option 'allow_regex_for_search'
#             add: command option '-regex'
#
# version 0.1: nils_2@freenode.#weechat
# 2013-04-23: - initial release -
#
# thanks to firebird and mave_ for testing...
#
# Development is currently hosted at
# https://github.com/weechat/scripts
#
# Requires:
#   DBI
#   DBD::SQLite
#
# How to install DBI:
# with cpan       : install DBI
# with deb-package: sudo apt-get install libdbi-perl
#
# How to install DBD::SQLite:
# with cpan       : install DBD::SQLite
# with deb-package: sudo apt-get install libdbd-sqlite3-perl libdbd-sqlite3 sqlite3-pcre

#use strict;
use warnings;
use File::Spec;
use DBI;

my $SCRIPT_NAME         = "stalker";
my $SCRIPT_VERSION      = "1.6.3";
my $SCRIPT_AUTHOR       = "Nils Görs <weechatter\@arcor.de>";
my $SCRIPT_LICENCE      = "GPL3";
my $SCRIPT_DESC         = "Records and correlates nick!user\@host information";


# internal values
my $weechat_version = "";
my $ptr_hook_timer = "";
my $flood_counter = 0;   # counter to take care of JOINs, e.g. after netsplit

# default values
my %options = ('db_name'                => '%h/nicks.db',
               'debug'                  => 'off',
               'max_recursion'          => '20',
               'recursive_search'       => 'on',
               'ignore_guest_hosts'     => 'off',
               'ignore_guest_nicks'     => 'on',
               'guest_nick_regex'       => '^(guest|weebot|Floodbot|ChanServ).*',
               'guest_host_regex'       => '^webchat',
               'normalize_nicks'        => 'on',
               'search_this_network_only' => 'on',
               'use_localvar'           => 'off',
               'ignore_nickchange'      => 'off',
               'ignore_whois'           => 'off',
               'tags'                   => '',
               'additional_join_info'   => 'off',
               'timeout'                => '1',
               'flood_timer'            => '10',
               'flood_max_nicks'        => '20',
#               '' => '',
);
my %desc_options = ('db_name'           => 'file containing the SQLite database where information is recorded. This database is created on loading of ' . $SCRIPT_NAME . ' if it does not exist. ("%h" will be replaced by WeeChat data directory) (default: %h/nicks.db)',
                    'debug'             => 'Prints debug output to core buffer so you know exactly what is going on. This is far too verbose to be enabled when not actively debugging something. (default: off)',
                    'max_recursion'     => 'For each correlation between nick <-> host that happens, one point of recursion happens. A corrupt database, general evilness, or misfortune can cause the recursion to skyrocket. This is a ceiling number that says if after this many correlation attempts we have not found all nickname and hostname correlations, stop the process and return the list to this point. Use this option with care on slower machines like raspberry pi.',
                    'recursive_search'  => 'When enabled, recursive search causes stalker to function better than a simple hostname to nickname map. Disabling the recursive search in effect turns stalker into a more standard hostname -> nickname map.',
                    'ignore_guest_hosts'=> 'See option guest_host_regex',
                    'guest_host_regex' => 'regex mask to ignore host masks',
                    'ignore_guest_nicks'=> 'See option guest_nick_regex',
                    'guest_nick_regex'  => 'Some networks set default nicknames when a user fails to identify to nickserv, other networks using relay-bots, some irc clients set default nicknames when someone connects and often these change from network to network depending on who is configuring the java irc clients. This allows a regular expression to be entered. When a nickname matches the regular expression and "ignore_guest_nicks" is enabled the nickname is dropped from the search as if it had never been seen. (default: ^(guest|weebot|Floodbot).*)',
                    'normalize_nicks' => 'this option will truncate special chars from username (like: ~) (default: on)',
                    'search_this_network_only' => 'When enabled searches are limited to within the network the window is currently set on. Turning this off is really only useful if multiple networks don\'t encode the hostmask. (default: on)',
                    'use_localvar'      => 'When enabled, only channels with a localvar \'stalker\' will be monitored. This option will not affect /NICK and /WHOIS monitoring. It\'s only for /JOIN messages. (default: off)',
                    'ignore_nickchange' => 'When enabled, /NICK changes won\'t be monitored. (default: off)',
                    'ignore_whois'      => 'When enabled, /WHOIS won\'t be monitored. (default: off)',
                    'tags'              => 'comma separated list of tags used for messages printed by stalker. See documentation for possible tags (e.g. \'no_log\', \'no_highlight\'). This option does not effect DEBUG messages.',
                    'additional_join_info' => 'add a line below the JOIN message that will display alternative nicks (tags: "irc_join", "irc_smart_filter" will be add to additional_join_info). You can use a localvar to drop additional join info for specific buffer(s) "stalker_drop_additional_join_info" (default: off)',
                    'timeout'           => 'timeout in seconds for hook_process_hashtable(), used with option "additional_join_info". On slower machines, like raspberry pi, increase time. (default: 1)',
                    'flood_timer'       => 'Time in seconds for which flood protection is active. Once max_nicks is reached, joins will be ignored for the remaining duration of the timer. (default:10)',
                    'flood_max_nicks'   => 'Maximum number of joins to allow in flood_timer length of time. Once maximum number of joins is reached, joins will be ignored until the timer ends (default:20)',
);

my $count;
my %data;
my $str;
my $DBH;
my $DBH_child;
my $DBH_fork;
my $last_nick = "";
my $last_host = "";

# SQLite table definition
my %tables = (
    'records' => [
        { 'column' => 'nick', 'type' => 'TEXT NOT NULL' },
        { 'column' => 'user', 'type' => 'TEXT NOT NULL' },
        { 'column' => 'host', 'type' => 'TEXT NOT NULL' },
        { 'column' => 'serv', 'type' => 'TEXT NOT NULL' },
        { 'column' => 'added', 'type' => 'DATE NOT NULL DEFAULT CURRENT_TIMESTAMP' },
      ],
  );

# SQLite index definitions
my %indices = (
    'records' => [
        { 'name' => 'index1', 'column' => 'nick' },
        { 'name' => 'index2', 'column' => 'host' },
      ],
  );

# ---------------[ external routines for hook_process_hashtable() ]---------------------
if ($#ARGV == 8 ) # (0-8) nine arguments given?
{
    my $db_filename = $ARGV[0];
    my ($db_user, $db_pass);
    $DBH_fork = DBI->connect(
        'dbi:SQLite:dbname='.$db_filename, $db_user, $db_pass,
        {
            RaiseError => 1,
#           AutoCommit => 1,
            sqlite_use_immediate_transaction => 1,
        }
    );

    exit if (not defined $DBH_fork);

    if ($ARGV[1] eq 'additional_join_info')
    {
        my $nick = $ARGV[2];
        my $user = $ARGV[3];
        my $host = $ARGV[4];
        my $serv = $ARGV[5];
        my $max_recursion = $ARGV[6];
        my $ignore_guest_nicks = $ARGV[7];
        my $guest_nick_regex = $ARGV[8];

        my $nicks_found = join( ", ", (get_nick_records_fork($nick, $serv, $max_recursion, $ignore_guest_nicks, $guest_nick_regex)));

        print "$nicks_found";
        $DBH_fork->disconnect();
        exit;
    }
    elsif ($ARGV[1] eq 'db_add_record')
    {
        my $nick = $ARGV[2];
        my $user = $ARGV[3];
        my $host = $ARGV[4];
        my $serv = $ARGV[5];

#        DEBUG("info", "Adding to DB: nick = $nick, user = $user, host = $host, serv = $serv" );

        # We don't have the record, add it. Test for record is done in add_record()
        $sth = $DBH_fork->prepare("INSERT INTO records (nick,user,host,serv) VALUES( ?, ?, ?, ? )" );
        eval { $sth->execute( $nick, $user, $host, $serv ) };
        $DBH_fork->disconnect();
        if ($@)
        {
            print "error Failed to process record, database said: $@";
            exit;
        }
        print "info Added record for $nick!$user\@$host to $serv";
    }
exit;
}

my $count2;
my %data_fork;
sub get_nick_records_fork
{
    my ( $nick, $serv, $max_recursion, $ignore_guest_nicks, $guest_nick_regex ) = @_;
    my $type = 'nick';
    my @return;
    $count2 = 0; %data_fork = (  );
    @return = _r_search_fork( $serv, $type, $max_recursion, $ignore_guest_nicks, $guest_nick_regex, ({ $type => $nick }) );

    # remove original nick
    @return = grep {$_ ne $nick} @return;
    # case-insensitive sort
    return sort {uc($a) cmp uc($b)} @return;
}

my @nicks_found;
sub _r_search_fork
{
    my ( $serv, $type, $max_recursion, $ignore_guest_nicks, $guest_nick_regex, @input ) = @_;
    return @nicks_found = &del_double(@nicks_found) if $count2 > $max_recursion;

    if ( $type eq 'nick' )
    {
        $count2++;
        for my $row ( @input )
        {
            my $nick = $row->{nick};
            next if exists $data_fork{$nick};

            $data_fork{$nick} = 'nick';
            my @hosts = _get_hosts_from_nick_fork( $nick, $serv, $ignore_guest_nicks, $guest_nick_regex );
            _r_search_fork ( $serv, 'host', $max_recursion, $ignore_guest_nicks, $guest_nick_regex, @hosts );
        }
    }
    elsif ( $type eq 'host' )
    {
        $count2++;
        for my $row ( @input )
        {
            my $host = $row->{host};
            next if exists $data_fork{$host};
            $data_fork{$host} = 'host';

            my @nicks = _get_nicks_from_host_fork ( $host, $serv, $ignore_guest_nicks, $guest_nick_regex );
            next if (scalar(@nicks) <= 0);
            push @nicks_found, map {  $_->{nick} } @nicks;
            # search only current network
#            $output_nicks = join( ", ", map { $_->{nick} } @nicks );

            # use regex only for host search!
            _r_search_fork( $serv, 'nick', $max_recursion, $ignore_guest_nicks, $guest_nick_regex, @nicks );
        }
    }
    return @nicks_found = &del_double(@nicks_found);
#    return %data_fork;
}

sub _get_hosts_from_nick_fork
{
    my ( $nick, $serv, $ignore_guest_nicks, $guest_nick_regex, @return ) = @_;

    my $sth = $DBH_fork->prepare( "SELECT nick, host FROM records WHERE nick = ? COLLATE NOCASE AND serv = ?" );
    $sth->execute( $nick, $serv );

    return _ignore_guests_fork( $sth, $ignore_guest_nicks, $guest_nick_regex );
}

sub _get_nicks_from_host_fork
{
    my ( $host, $serv, $ignore_guest_nicks, $guest_nick_regex, @return ) = @_;
    my $sth = $DBH_fork->prepare( "SELECT nick, host FROM records WHERE host = ? AND serv = ?" );
    $sth->execute( $host, $serv );

    return _ignore_guests_fork( $sth,$ignore_guest_nicks, $guest_nick_regex );
}

sub del_double
{
    my %all=();
    @all{@_}=1;
    return (keys %all);
}

sub _ignore_guests_fork
{
    my ( $sth, $ignore_guest_nicks, $guest_nick_regex ) = @_;
    my @return;

    while ( my $row = $sth->fetchrow_hashref )
    {
        if ( lc($ignore_guest_nicks) eq "on" )
        {
            my $regex = $guest_nick_regex;
            next if( $row->{nick} =~ m/$regex/i );
        }
        push @return, $row;
    }
    return @return;
}

# -----------------------------[ Database ]-----------------------------------
sub open_database
{
    my $db = weechat_dir();

    stat_database( $db );
    my ($db_user, $db_pass);
    # my $db_host = '127.0.0.1';
    # my $db_port = 3306;

    $DBH = DBI->connect(
        'dbi:SQLite:dbname='.$db, $db_user, $db_pass,
        {
            RaiseError => 1,
#            AutoCommit => 1,
            sqlite_use_immediate_transaction => 1,
        }
    );

    # DBI::SQLite and fork() don't mix. Do it anyhow but keep the parent and child DBH separate?
    # Ideally the child should open its own connection.
    $DBH_child = DBI->connect(
        'dbi:SQLite:dbname='.$db, $db_user, $db_pass,
        {
            RaiseError => 1,
#            AutoCommit => 1,
            sqlite_use_immediate_transaction => 1,
        }
    );

    # async data
    my @records_to_add; # Queue of records to add
}

# Automatic Database Creation And Checking
sub stat_database {
    my ( $db_file ) = @_;

    DEBUG('info', 'Stat database');
    if ( ! -e $db_file  ) {
        open my $fh, '>', $db_file
            or die 'Cannot create database file.  Abort.';
        close $fh;
    }
    my $DBH = DBI->connect(
        'dbi:SQLite:dbname='.$db_file, "", "",
        {
            RaiseError => 1,
#            AutoCommit => 1,
            sqlite_use_immediate_transaction => 1,
        }
    );

    create_or_upgrade_database( $DBH );

    index_db( $DBH );
}

sub create_or_upgrade_database {
    my ( $DBH ) = @_;

    # This part will always add missing tables or columns defined in @tables (ie create or upgrade the database)
    DEBUG("info", "Checking database table structure");
    my %col_exists;
    for my $table (keys %tables) {
        for my $col ( @{ $DBH->selectall_arrayref ( "PRAGMA TABLE_INFO($table)" ) } ) {
            $col_exists{$table}{$col->[1]} = 1;
        }
    }
    for my $table (keys %tables) {
        my $upgrade = 0;

        # Create missing tables
        unless ( exists( $col_exists{$table} ) ) {
            create_table( $DBH, $table );
            next;
        }

        # Check for missing columns
        my @cols_not_null;
        for my $col ( @{$tables{$table}} ) {
            unless ( $col_exists{$table}{$col->{column}} ) {
                if ( ($col->{type} =~ /NOT NULL/) and ($col->{type} !~ /DEFAULT/) ) {
                    push @cols_not_null, $col->{column};
                }
                $upgrade = 1;
            }
        }

        # Due to limitations in ALTER TABLE in sqlite this cumbersome method is necessary to alter a table
        if ( $upgrade ) {
            DEBUG("info", "Upgrade required for table '$table', please wait...");
            # Save the old records
            $DBH->do( "ALTER TABLE $table RENAME TO old_$table" );

            # Preserve old column names for copying of data later
            my $old_columns = join( ", ", map { $_->[1] } @{ $DBH->selectall_arrayref( "PRAGMA TABLE_INFO(old_$table)" ) } );

            # Create the new table
            create_table( $DBH, $table );

            # Special care for NOT NULL columns, we set value 1 for all missing columns defined with NOT NULL or the copy will fail
            my $old_select;
            if ( scalar(@cols_not_null) > 0 ) {
                $old_select = $old_columns . ", " . join(", ", map { 1 } @cols_not_null );
                $old_columns .= ", " . join(", ", @cols_not_null);
            } else {
                $old_select = $old_columns;
            }

            # Copy the old records over and drop them
            my @queries = (
                "INSERT INTO $table ($old_columns) SELECT $old_select FROM old_$table",
                "DROP TABLE old_$table",
              );
            for my $query (@queries) {
                my $sth = $DBH->prepare($query) or die "Failed to prepare '$query'. " . $sth->err;
                $sth->execute() or die "Failed to execute '$query'. " . $sth->err;
            }
            DEBUG( "info", "Table '$table' has been successfully upgraded" ) unless ( $DBH->err );
        }
    }
}

# Create table
sub create_table {
    my ( $DBH, $table_name ) = @_;

    my @queries;

    DEBUG("info", "Creating table '$table_name'");
    push @queries, "DROP TABLE IF EXISTS $table_name";
    push @queries, "CREATE TABLE $table_name (" . join(", ", map { "$_->{column} $_->{type}" } @{ $tables{$table_name} }) . ")";

    for my $query (@queries) {
        my $sth = $DBH->prepare($query) or die "Failed to prepare '$query'. " . $sth->err;
        $sth->execute() or die "Failed to execute '$query'. " . $sth->err;
    }
}

# Add indices to the DB.
sub index_db {
    my ( $DBH ) = @_;

    for my $table (keys %indices) {
        my %idx_exists;
        for my $index ( @{ $DBH->selectall_arrayref( "PRAGMA INDEX_LIST($table)" ) } ) {
            $idx_exists{$index->[1]} = 1;
        }

        $DBH->{RaiseError} = 0;
        $DBH->{PrintError} = 0;
        for my $index ( @{$indices{$table}} ) {
            $DBH->do( "CREATE INDEX $index->{name} ON $table ($index->{column})" ) unless ( $idx_exists{$index->{name}} );
        }
        $DBH->{RaiseError} = 1;
        $DBH->{PrintError} = 1;
    }
}

sub normalize
{
    my ( @nicks ) = @_;
    my ( %nicks, %ret ) = map { $_, 1 } @nicks;

    for my $nick ( @nicks )
    {
        (my $base = $nick ) =~ s/[\Q-_~^`\E]//g;
        $ret{ exists $nicks{$base} ? $base : $nick }++;
    }
    return keys %ret;
}

sub add_record
{
    my ( $nick, $user, $host, $serv ) = @_;
    return unless ($nick and $user and $host and $serv);

    # Check if we already have this record, before using a hook_process_hashtable()
    my $sth = $DBH_child->prepare( "SELECT nick FROM records WHERE nick = ? AND user = ? AND host = ? AND serv = ?" );
    $sth->execute( $nick, $user, $host, $serv );
    my $result = $sth->fetchrow_hashref;

    if ( defined $result->{nick} )
    {
        if ( $result->{nick} eq $nick ) {
            DEBUG( "info", "Record for $nick skipped - already exists." );
            return weechat::WEECHAT_RC_OK;
        }
    }

    my $filename = get_script_filename();
    return weechat::WEECHAT_RC_OK if ($filename eq "");

    my $db_filename = weechat_dir();
    DEBUG("info", "Start hook_process(), to add $nick $user\@$host on $serv to database");

    weechat::hook_process_hashtable("perl",
    {
    "arg1"  => $filename,
    "arg2"  => $db_filename,
    "arg3"  => 'db_add_record',
    "arg4"  => $nick,
    "arg5"  => $user,
    "arg6"  => $host,
    "arg7"  => $serv,
    "arg8"  => 'dummy',
    "arg9"  => 'dummy',
    "arg10" => 'dummy',
    }, 1000 * $options{'timeout'},"db_add_record_cb","");


}

# function called when data from child is available, or when child has ended, arguments and return value
sub db_add_record_cb
{
    my ( $data, $command, $return_code, $out, $err ) = @_;
    return weechat::WEECHAT_RC_OK if ( $return_code > 0 or $out eq "");                              # something wrong!

    my ($DEBUG_prefix,$message) = split(/ /,$out,2);
    DEBUG($DEBUG_prefix, $message);
    return weechat::WEECHAT_RC_OK;
}

sub get_host_records {
    # suppress output? yes|no
    # type = host|nick, $query = name, $serv = server, @return = "."
    my ( $suppress, $type, $query, $serv, @return ) = @_;

    $count = 0; %data = (  );
    my %data = _r_search( $suppress, $serv, $type, $query );
    for my $k ( keys %data ) {
        DEBUG( "info", "$type query for records on $query from server $serv returned: $k" );
        push @return, $k if $data{$k} eq 'host';
    }

    # case-insensitive sort
    return sort {uc($a) cmp uc($b)} @return;
}

sub get_nick_records
{
    # type = host|nick, $query = nick, $serv = server, use_regex = 0|1, @return = "."
    my ( $suppress, $type, $query, $serv, $use_regex, @return ) = @_;

    $count = 0; %data = (  );
    my %data = _r_search( $suppress, $serv, $type, $use_regex, ({ $type => $query }) );
    for my $k ( keys %data ) {
        DEBUG( "info", "$type query for database records on $query from server $serv. returned: $k" );
        push @return, $k if $data{$k} eq 'nick';
    }

    if (lc($options{'normalize_nicks'}) eq "on" ) {
        @return = normalize(@return);
    }

    # remove original nick
    @return = grep {$_ ne $query} @return;

    # case-insensitive sort
    return sort {uc($a) cmp uc($b)} @return;
}

sub _r_search
{
    my ( $suppress, $serv, $type, $use_regex, @input ) = @_;

    return %data if $count > 1000;
    return %data if $count > $options{'max_recursion'};
    return %data if $count == 2 and ! $options{'recursive_search'};

    DEBUG( "info", "Recursion Level: $count" );

    if ( $type eq 'nick' )
    {
        $count++;
        for my $row ( @input )
        {
            my $nick = $row->{nick};
            next if exists $data{$nick};

            $data{$nick} = 'nick';
            my @hosts = _get_hosts_from_nick( $nick, $serv, $use_regex );
            # use regex only for nick search!
            $use_regex = 0 if ( $use_regex );
            _r_search( $suppress, $serv, 'host', $use_regex, @hosts );
        }
    } elsif ( $type eq 'host' )
    {
        $count++;
        for my $row ( @input )
        {
            my $host = $row->{host};
            next if exists $data{$host};
            $data{$host} = 'host';
            my @nicks = _get_nicks_from_host( $host, $serv, $use_regex );
            next if (scalar(@nicks) <= 0);

            my $output_nicks;
            if ( lc($options{'search_this_network_only'}) eq "on" )
            {
                $output_nicks = join( ", ", map { $_->{nick} } @nicks );
            }
            else {
                $output_nicks = join( ", ", map { $_->{serv} . "." . $_->{nick} } @nicks );
            }

            if ($suppress eq 'no')
            {
                my $ptr_buffer = weechat::current_buffer();

                my $output = weechat::color('chat_prefix_network').
                            weechat::prefix('network').
                            weechat::color('chat_delimiters').
                            "[".
                            weechat::color('chat_nick').
                            $SCRIPT_NAME.
                            weechat::color('chat_delimiters').
                            "] ".
                            weechat::color('reset').
                            "Found nicks: $output_nicks".
                            " from host $host";

                OUTPUT($ptr_buffer,$output);
            }

            # use regex only for host search!
            $use_regex = 0 if ( $use_regex );
            _r_search( $suppress, $serv, 'nick', $use_regex, @nicks );
        }
    }
    return %data;
}

sub _get_hosts_from_nick {
    my ( $nick, $serv, $use_regex, @return ) = @_;

    my $sth;

    if ( lc($options{'search_this_network_only'}) eq "on" )
    {
        if ( $use_regex )
        {
            $sth = $DBH->prepare( "SELECT nick, host FROM records WHERE nick REGEXP ? AND serv = ?" );
            $sth->execute( $nick, $serv );
        }
        else
        {
            $sth = $DBH->prepare( "SELECT nick, host FROM records WHERE nick = ? COLLATE NOCASE AND serv = ?" );
            $sth->execute( $nick, $serv );
        }
    }
    else
    {
        if ( $use_regex )
        {
            $sth = $DBH->prepare( "SELECT nick, host, serv FROM records WHERE nick REGEXP ?");
        }
        else
        {
            $sth = $DBH->prepare( "SELECT nick, host, serv FROM records WHERE nick = ? COLLATE NOCASE" );
        }
        $sth->execute( $nick );
    }
    # nothing found in database
#    return '' if (not defined $sth->fetchrow_hashref);
    return _ignore_guests( $sth );
}

sub _get_nicks_from_host {
    my ( $host, $serv, $use_regex, @return ) = @_;

    my $sth;
    if ( lc($options{'search_this_network_only'}) eq "on" )
    {
        if ( $use_regex )
        {
            $sth = $DBH->prepare( "SELECT nick, host FROM records WHERE host REGEXP ? AND serv = ?" );
#            $sth->execute( $host, $serv );
        }
        else
        {
            $sth = $DBH->prepare( "SELECT nick, host FROM records WHERE host = ? AND serv = ?" );
        }
        $sth->execute( $host, $serv );
    }
    else
    {
        if ( $use_regex )
        {
            $sth = $DBH->prepare( "SELECT nick, host, serv FROM records WHERE host REGEXP ?" );
        }
        else
        {
            $sth = $DBH->prepare( "SELECT nick, host, serv FROM records WHERE host = ?" );
        }
        $sth->execute( $host );
    }
    # nothing found in database
#    return '' if (not defined $sth->fetchrow_hashref);
    return _ignore_guests( $sth );
}

sub _ignore_guests
{
    my ( $sth ) = @_;
    my @return;

    while ( my $row = $sth->fetchrow_hashref )
    {
        if ( lc($options{'ignore_guest_nicks'}) eq "on" )
        {
            my $regex = $options{'guest_nick_regex'};
            next if( $row->{nick} =~ m/$regex/i );
        }
        if ( lc($options{'ignore_guest_hosts'}) eq "on" )
        {
            my $regex = $options{'guest_host_regex'};
            next if( $row->{host} =~ m/$regex/i );
        }
        push @return, $row;
    }
    return @return;
}

sub _deassociate_nick_from_host
{
    my ( $nick, $host, $serv, $use_regex, @return ) = @_;

    my $sth;
    if ( lc($options{'search_this_network_only'}) eq "on" )
    {
        if ( $use_regex )
        {
            $sth = $DBH->prepare( "DELETE FROM records WHERE host REGEXP ? AND nick REGEXP ? AND serv = ?" );
        }
        else
        {
            $sth = $DBH->prepare( "DELETE FROM records WHERE host = ? AND nick = ? AND serv = ?" );
        }
        $sth->execute( $host, $nick, $serv );
    }
    else
    {
        if ( $use_regex )
        {
            $sth = $DBH->prepare( "DELETE FROM records WHERE host REGEXP ? AND nick REGEXP ?" );
        }
        else
        {
            $sth = $DBH->prepare( "DELETE FROM records WHERE host = ? AND nick = ?" );
        }
        $sth->execute( $host, $nick );
    }
    return $sth->rows;
}

sub delete_older_entries
{
    # $day = yyyy-mm-dd
    my ( $day1, $day2 ) = @_;
    # from date ? to date ?
    $sth = $DBH->prepare( "DELETE FROM records WHERE added >= '" . $day1 . "' AND added < '" . $day2 . "'" );
    $sth->execute();
}

# ------------------------[ OUTPUT with tags ]------------------------------
sub OUTPUT
{
    my ($ptr_buffer,$output) = @_;

    if ( $options{'tags'} ne '' )
    {
        weechat::print_date_tags($ptr_buffer,0,$options{'tags'},$output);
    }
    else
    {
        weechat::print($ptr_buffer,$output);
    }
}
# -----------------------------[ debug ]-----------------------------------
sub DEBUG
{
    my $DEBUG_prefix;
    my $color;

    return if (lc($options{debug}) eq 'off');

    if ( $_[0] eq 'info')
    {
        $DEBUG_prefix = 'info';
        $color = "default";
    }
    elsif ( $_[0] eq 'error')
    {
        $DEBUG_prefix = weechat::config_string(weechat::config_get("weechat.look.prefix_error"));
        $color  = weechat::color(weechat::config_color(weechat::config_get("weechat.color.chat_prefix_error")));
    }
    else
    {
        $DEBUG_prefix = '***';
        $color = 'default';
    }
        weechat::print('', _color_str($color, $DEBUG_prefix) . "\t$SCRIPT_NAME: $_[1]");
}

sub _color_str
{
    my ($color_name, $string) = @_;
    # use eval for colors-codes (${color:red} eg in weechat.look.prefix_error)
    $string = weechat::string_eval_expression($string, {}, {},{}) if ($weechat_version >= 0x00040200);
    weechat::color($color_name) . $string  . weechat::color('reset');
}
# -------------------------------[ subroutines ]-------------------------------------
sub weechat_dir
{
    my $eval_options = { "directory" => "data" };
    return weechat::string_eval_path_home($options{'db_name'}, {}, {}, $eval_options);
}
# -------------------------------[ main ]-------------------------------------
sub stalker_command_cb
{
    my ($data, $buffer, $args) = ($_[0], $_[1], $_[2]);
    my @args_array=split(/ /,$args);
    my $number = @args_array;

    return weechat::WEECHAT_RC_OK if ($number <= 0);

    if (lc($args_array[0]) eq 'count')
    {
#        my $ptr_buffer = weechat::current_buffer();
        my ($count) = $DBH->selectrow_array("SELECT count(*) FROM records");
        my $output = weechat::color('chat_prefix_network').
                     weechat::prefix('network').
                     weechat::color('chat_delimiters').
                     "[".
                     weechat::color('chat_nick').
                     $SCRIPT_NAME.
                     weechat::color('chat_delimiters').
                     "] ".
                     weechat::color('reset').
                     "number of rows: ".
                     $count;

        OUTPUT($buffer,$output);
        return weechat::WEECHAT_RC_OK;
    }
    # get localvar from current buffer
    my $name = weechat::buffer_get_string($buffer,'localvar_name');
    my $server = weechat::buffer_get_string($buffer,'localvar_server');
    my $type = weechat::buffer_get_string($buffer,'localvar_type');

    if ( weechat::buffer_get_string($buffer,'plugin') ne 'irc' and lc($args_array[0]) eq 'scan' )
    {
        command_must_be_executed_on_irc_buffer();
        return weechat::WEECHAT_RC_OK;
    }

    if (lc($args_array[0]) eq 'scan' && $type eq 'channel' && $number == 1)
    {
        channel_scan($buffer);
#        channel_scan_41(weechat::current_buffer());
        return weechat::WEECHAT_RC_OK;
    }

    # at least, we have two arguments
    return weechat::WEECHAT_RC_OK if ($number <= 1);

    my $use_regex = 0;

    if (lc($args_array[0]) eq 'scan' && $args_array[1] ne "")
    {
        $args_array[1] =~ s/\./,/;                      # info_get() needs an "," instead of "."
        my $ptr_buffer = weechat::info_get('irc_buffer',$args_array[1]);
#        channel_scan_41($ptr_buffer) if ( $ptr_buffer ne "");
        channel_scan($ptr_buffer) if ( $ptr_buffer ne "");
    }
    elsif (lc($args_array[0]) eq 'nick' or lc($args_array[0]) eq 'host')
    {
        if ( defined $args_array[2] and $args_array[2] eq "-regex" )
        {
            $use_regex = 1;
        }
        else
        {
            $server = $args_array[2] if ( defined $args_array[2] and $args_array[2] ne "" );
        }

        if ( defined $args_array[3] and $args_array[3] eq "-regex" )
        {
            $use_regex = 1;
        }

        if ( $server eq "" )
        {
            command_must_be_executed_on_irc_buffer();
            return weechat::WEECHAT_RC_OK;
        }
        # $args_array[0]: 'nick' or 'host', $args_array[1]: nick or host name
        # list will be print in subroutine!
        my $nicks_found = join( ", ", (get_nick_records('no', $args_array[0], $args_array[1], $server, $use_regex)));
    }
    elsif (lc($args_array[0]) eq 'remove_nick_from_host')
    {
      $use_regex = 1 if ( grep{ $args_array[$_] eq '-regex' }0..$#args_array );

      my $server = weechat::buffer_get_string($buffer,'localvar_server');

      if ( $server eq "" )
      {
          command_must_be_executed_on_irc_buffer();
          return weechat::WEECHAT_RC_OK;
      }
      my $affected_rows = _deassociate_nick_from_host( $args_array[1], $args_array[2], $server, $use_regex );
      my $color  = weechat::color(weechat::config_color(weechat::config_get('weechat.color.chat_prefix_error')));
      my $DEBUG_prefix = weechat::config_string(weechat::config_get('weechat.look.prefix_error'));
      weechat::print($buffer, _color_str($color, $DEBUG_prefix) . "\t$SCRIPT_NAME: $affected_rows deleted");
    }
    elsif (lc($args_array[0]) eq 'del_date')
    {
        delete_older_entries($args_array[1],$args_array[2]) if ($args_array[1] and $args_array[2]);
    }
    return weechat::WEECHAT_RC_OK;
}

sub command_must_be_executed_on_irc_buffer
{
    my $text = 'command must be executed on irc buffer (server or channel) or a server must be given';
    my $color  = weechat::color(weechat::config_color(weechat::config_get('weechat.color.chat_prefix_error')));
    my $DEBUG_prefix = weechat::config_string(weechat::config_get('weechat.look.prefix_error'));
    weechat::print('', _color_str($color, $DEBUG_prefix) . "\t$SCRIPT_NAME: $text");
}
# hdata_search()
# hdata: hdata pointer
# pointer: pointer to a WeeChat/plugin object
# search: expression to evaluate, default pointer in expression is the name of hdata (and this pointer changes for each element in list); for help on expression, see command /eval in WeeChat User’s guide
# pointers: pointers for evaluated expression
# extra_vars: extra variables for evaluated expression
# options: options for evaluated expression
# move: number of jump(s) to execute after unsuccessful search (negative or positive integer, different from 0)

sub channel_scan_41
{
    my $ptr_buffer = $_[0];

    my $server_name = weechat::buffer_get_string($ptr_buffer, "localvar_server");
    my $channel_name = weechat::buffer_get_string($ptr_buffer, "localvar_channel");
    return if ($server_name eq "" or $channel_name eq "");

#my %hdata = { map { $_ => weechat::hdata_get( "irc_" . $_ ) } qw( server channel nick ) };
    my $hdata_server = weechat::hdata_get("irc_server");
    my $hdata_channel = weechat::hdata_get("irc_channel");
    my $hdata_nick = weechat::hdata_get("irc_nick");

    my $ptr_server;
    if ($weechat_version >= 0x03040000)
    {
        $ptr_server = weechat::hdata_search($hdata_server,
                                            weechat::hdata_get_list($hdata_server, 'irc_servers'),
                                            '${irc_server.name} == ${server_name}',
                                            {},
                                            {'server_name' => $server_name},
                                            {},
                                            1);
    }
    else
    {
        $ptr_server = weechat::hdata_search($hdata_server, weechat::hdata_get_list($hdata_server, 'irc_servers'), '${irc_server.name} == ' . $server_name, 1);
    }
    if ($ptr_server)
    {
        my $ptr_channel;
        if ($weechat_version >= 0x03040000)
        {
            $ptr_channel = weechat::hdata_search($hdata_channel,
                                                 weechat::hdata_pointer($hdata_server, $ptr_server, 'channels'),
                                                 '${irc_channel.name} == ${channel_name}',
                                                 {},
                                                 {'channel_name' => $channel_name},
                                                 {},
                                                 1);
        }
        else
        {
            $ptr_channel = weechat::hdata_search($hdata_channel, weechat::hdata_pointer($hdata_server, $ptr_server, 'channels'), '${irc_channel.name} == ' . $channel_name, 1);
        }

        if ($ptr_channel)
        {
            my $nick = weechat::hdata_pointer($hdata_channel, $ptr_channel, 'nicks');
            while ( $nick )
            {
                my $nick_name = weechat::hdata_string($hdata_nick, $nick, 'name');
                my $host_name = weechat::hdata_string($hdata_nick, $nick, 'host');
                $host_name =~ /(.*)\@/;
                my $user_name = $1;

                add_record( $nick_name, $user_name, $host_name, $server_name);

                $nick = weechat::hdata_move($hdata_nick, $nick, 1);
            }
        }

    }
}

sub channel_scan
{
    my $ptr_buffer = $_[0];
    my $infolist = weechat::infolist_get('nicklist', $ptr_buffer, '');
    # don't stalk yourself
    my $my_nick = weechat::buffer_get_string($ptr_buffer,'localvar_nick');

    my $nick_counter;

    while (weechat::infolist_next($infolist))
    {
        my $nick = weechat::infolist_string($infolist, 'name');
        if ((weechat::infolist_string($infolist, 'type') eq 'nick')
            && ($nick ne $my_nick))
        {
            my $ptr_nick = weechat::nicklist_search_nick($ptr_buffer, '', $nick);
            my $localvar_server = weechat::buffer_get_string($ptr_buffer,'localvar_server');
            my $localvar_channel = weechat::buffer_get_string($ptr_buffer,'localvar_channel');

            my $infolist_nick = weechat::infolist_get('irc_nick','',$localvar_server.','.$localvar_channel.','.$nick);
            weechat::infolist_next($infolist_nick);
            my $host = weechat::infolist_string($infolist_nick,'host');
            weechat::infolist_free($infolist_nick);

            next unless ($nick or $host or $localvar_server);
            $host =~ /(.*)\@/;
            $user = $1;

            add_record( $nick, $user, $host, $localvar_server);

#            $user=~ s/[\Q-_~^`\E]//g;
#            my $hdata = weechat::hdata_get("irc_nick");
#            my $hdata_host = weechat::hdata_string($hdata, $ptr_nick, "host");
#            next if ($host eq $name);

        }
    }
    weechat::infolist_free($infolist);
}

# simple check for last nick/host
# to prevent multiple requests (e.g. "/nick|join nick" for several channels!)
# 0 = failed
# 1 = found
sub check_last_nick_host
{
    my ($nick,$host) = @_;
    my $rc = 0;

    $rc = 1 if ($nick eq $last_nick && $host eq $last_host);

    $last_nick = $nick;
    $last_host = $host;
    return $rc;
}
# -------------------------------[ hooks ]-------------------------------------
# :old_nick!~user@host NICK :new_nick
# /NICK command called
# this is a server command
sub irc_in2_nick_cb
{
    my ($signal, $callback, $callback_data) = @_;
    my ($server,undef) = split(',',$callback);

    return weechat::WEECHAT_RC_OK if ( lc($options{'ignore_nickchange'}) eq "on" );

    DEBUG('info', 'weechat_hook_signal(): NICK change');

    my $hashtable = weechat::info_get_hashtable("irc_message_parse" => + { "message" => $callback_data });

    # $old_nick = $hashtable->{nick}
    my ($old_nick, $host) = split('!', $hashtable->{host});
    my $nick = $hashtable->{arguments};
    $nick =~ s/^.//;                            # remove leading ":"
    my ($user,undef) = split("@",$host);

    return weechat::WEECHAT_RC_OK if check_last_nick_host($nick,$host);

    add_record( $nick, $user, $host, $server);

    return weechat::WEECHAT_RC_OK;
}

sub irc_in2_whois_cb
{
    my ($signal, $callback, $callback_data) = @_;
    my ($server,undef) = split(',',$callback);

    my $ptr_buffer = '';

    my (undef, undef, undef, $nick, $user, $host, undef) = split(' ', $callback_data);
    my $msgbuffer_whois = weechat::config_string(weechat::config_get('irc.msgbuffer.whois'));

    DEBUG('info', 'weechat_hook_signal(): WHOIS');

    # check for nick_regex
    if ( lc($options{'ignore_guest_nicks'}) eq "on" )
    {
        my $regex = $options{'guest_nick_regex'};
        return weechat::WEECHAT_RC_OK if( $nick =~ m/$regex/i );
    }

    my $complete_host = $user."@".$host;

    unless ( check_last_nick_host($nick,$complete_host) or lc($options{'ignore_whois'}) eq "on" )
    {
        add_record( $nick, $user, $complete_host, $server);
    }

    # output for /whois
    if ($msgbuffer_whois eq 'server')
    {
        $ptr_buffer = weechat::info_get('irc_buffer',$server);
#        $ptr_buffer = weechat::buffer_search('irc', 'server.' . $server);
    }
    elsif ($msgbuffer_whois eq 'weechat')
    {
        $ptr_buffer = weechat::buffer_search_main();
    }
    elsif  ($msgbuffer_whois eq 'current')
    {
        $ptr_buffer = weechat::current_buffer();
    }
    elsif ($msgbuffer_whois eq 'private')
    {
        $ptr_buffer = weechat::info_get('irc_buffer',$server.','.$nick);
        if ($ptr_buffer eq '')
        {
            $msgbuffer_whois = weechat::config_string(weechat::config_get('irc.look.msgbuffer_fallback'));
            $ptr_buffer = weechat::info_get('irc_buffer', $server) if ($msgbuffer_whois eq 'server');
        }
    }

    my $use_regex = 0;
    my $filename = get_script_filename();
    return weechat::WEECHAT_RC_OK if ($filename eq "");

    my $db_filename = weechat_dir();
    my $name = weechat::buffer_get_string($ptr_buffer,'localvar_name');
    DEBUG("info", "Start hook_process(), get additional for WHOIS() info from $nick with $user\@$host on $name");

    weechat::hook_process_hashtable("perl",
    {
    "arg1"  => $filename,
    "arg2"  => $db_filename,
    "arg3"  => 'additional_join_info',
    "arg4"  => $nick,
    "arg5"  => $user,
    "arg6"  => $host,
    "arg7"  => $server,
    "arg8"  => $options{'max_recursion'},
    "arg9"  => $options{'ignore_guest_nicks'},
    "arg10" => $options{'guest_nick_regex'},
    }, 1000 * $options{'timeout'},"hook_process_get_nicks_records_cb","$nick $ptr_buffer 'dummy'");

#    my $nicks_found = join( ", ", (get_nick_records('yes', 'nick', $nick, $server, $use_regex)));

    return weechat::WEECHAT_RC_OK;
    # only the given nick is returned?
#    return weechat::WEECHAT_RC_OK if ($nicks_found eq $nick or $nicks_found eq "");

    # more than one nick was returned from sqlite
    my $prefix_network = weechat::prefix('network');
    my $color_chat_delimiter = weechat::color('chat_delimiters');
    my $color_chat_nick = weechat::color('chat_nick');

    my $output = weechat::color('chat_prefix_network').
                  weechat::prefix('network').
                  weechat::color('chat_delimiters').
                  "[".
                  weechat::color('chat_nick').
                  $SCRIPT_NAME.
                  weechat::color('chat_delimiters').
                  "] ".
                  $nicks_found;

    # fallback buffer..
    $ptr_buffer = weechat::buffer_search_main() unless ($ptr_buffer);

    # print /WHOIS with [stalker] line
    OUTPUT($ptr_buffer,$output);

    return weechat::WEECHAT_RC_OK;
}

sub irc_in2_join_cb
{
    my ($data, $buffer, $date, $tags, $displayed, $highlight, $prefix, $message) = @_;

    my ($nick,$user,$host);
    # get nick, user and host.
    if ($weechat_version >= 0x00040400)
    {
        # use tags to avoid problems with customised JOIN messages (v0.4.4)
        $nick = ($tags =~ m/(^|,)nick_([^,]*)/) ? $2 : "";
        ($user,$host) = ($tags =~ m/(^|,)host_(.*)\@([^,]*)/) ? ($2,$3) : ("","");
    }
    else
    {
        # message:   :nick!~user_2@host JOIN #channel
        ($nick,$user,$host) = ($message =~ /(.*) \((.*)\@(.*)\)/);
    }

    return weechat::WEECHAT_RC_OK if (not defined $nick or $nick eq ""
                                      or not defined $user or $user eq ""
                                      or not defined $host or $host eq "");

    my $my_nick = weechat::buffer_get_string($buffer,'localvar_nick');
    my $server = weechat::buffer_get_string($buffer,'localvar_server');
    my $name = weechat::buffer_get_string($buffer,'localvar_name');

    # don't stalk yourself
    return weechat::WEECHAT_RC_OK if ($nick eq $my_nick);

    return weechat::WEECHAT_RC_OK if check_last_nick_host($nick,$host);

    DEBUG('info', 'weechat_hook_signal(): JOIN');

    # check for localvar "stalker"
    if ( lc($options{'use_localvar'}) eq "on" )
    {
        return weechat::WEECHAT_RC_OK if (not weechat::config_string_to_boolean(weechat::buffer_get_string($buffer, 'localvar_stalker')) );
    }

    # check if "flood_timer" is activated
    if ( $options{'flood_timer'} > 0 )
    {
        # reset ptr_hook_timer and flood_counter if hook_timer() does not exists anymore
        if ( $ptr_hook_timer ne "" and search_hook('hook',$ptr_hook_timer) eq 0 )
        {
            $ptr_hook_timer = "";
            $flood_counter = 0;
        }
        # timer still running, add counter
        else
        {
            $flood_counter++;
        }

        if ($ptr_hook_timer eq "")
        {
            # call timer only once
            $ptr_hook_timer = weechat::hook_timer($options{'flood_timer'} * 1000, 0, 1, 'my_hook_timer_cb', '');
        }

        if ( $ptr_hook_timer ne "" and $flood_counter > $options{'flood_max_nicks'} )
        {
            DEBUG("info", "flood protection activated for: $nick with $user\@$host on $server");
            return weechat::WEECHAT_RC_OK;
        }
    }
    # end of flood protection

    add_record( $nick, $user, $host, $server);

    return weechat::WEECHAT_RC_OK if (weechat::config_string_to_boolean(weechat::buffer_get_string($buffer, 'localvar_stalker_drop_additional_join_info')) );

    if ( lc($options{'additional_join_info'}) eq "on" )
    {
        my $filename = get_script_filename();
        return weechat::WEECHAT_RC_OK if ($filename eq "");

        # get tags for stalker output
        my $my_tags = $options{'tags'};
        # add tag 'irc_smart_filter' or 'irc_join' to list of tags, if tag(s) exists in original JOIN message
        $my_tags = $my_tags . ',irc_smart_filter' if (index($tags,'irc_smart_filter') >= 0);
        $my_tags = $my_tags . ',irc_join' if (index($tags,'irc_join') >= 0);

        my $db_filename = weechat_dir();
        DEBUG("info", "Start hook_process(), get additional info from $nick with $user\@$host on $name");

        weechat::hook_process_hashtable("perl",
        {
        "arg1"  => $filename,
        "arg2"  => $db_filename,
        "arg3"  => 'additional_join_info',
        "arg4"  => $nick,
        "arg5"  => $user,
        "arg6"  => $host,
        "arg7"  => $server,
        "arg8"  => $options{'max_recursion'},
        "arg9"  => $options{'ignore_guest_nicks'},
        "arg10" => $options{'guest_nick_regex'},
        }, 1000 * $options{'timeout'},"hook_process_get_nicks_records_cb","$nick $buffer $my_tags");

      }
    return weechat::WEECHAT_RC_OK;
}

# get absolute path of script
sub get_script_filename
{
    my $infolist_ptr = weechat::infolist_get("perl_script","",$SCRIPT_NAME);
    weechat::infolist_next($infolist_ptr);
    my $filename = weechat::infolist_string($infolist_ptr,"filename");
    weechat::infolist_free($infolist_ptr);
    return $filename;
}

sub hook_process_get_nicks_records_cb
{
    my ($data, $command, $return_code, $out, $err) = @_;
    DEBUG("info", "hook_process_get_nicks_records_cb: data=$data command=$command, rc=$return_code out=$out err=$err");

    return weechat::WEECHAT_RC_OK if ( $return_code > 0 or $out eq "");                              # something wrong!

    my ($nick,$buffer_ptr,$tags) = split(/ /,$data);
    my $nicks_found = $out;
    # don't print output if there is no other nick used
    return weechat::WEECHAT_RC_OK if ($nick eq $nicks_found or $nicks_found eq '');

    my $string = weechat::color('chat_prefix_network').
                weechat::prefix('network').
                weechat::color('chat_delimiters').
                "[".
                weechat::color('chat_nick').
                $SCRIPT_NAME.
                weechat::color('chat_delimiters').
                "] ".
                weechat::color('reset').
                $nick.
                " is also known as: ".
                $nicks_found;

    weechat::print_date_tags($buffer_ptr,0,$tags,$string);
    return weechat::WEECHAT_RC_OK;
}

sub search_hook
{
    my ($hook, $ptr_hook) = @_;
    my $hook_found = 0;
    my $infolist = weechat::infolist_get($hook, $ptr_hook, '');
    while ( weechat::infolist_next($infolist) )
    {
        $hook_found = 1 if ( weechat::infolist_pointer($infolist,'pointer') eq $ptr_hook );
    }
    weechat::infolist_free($infolist);

    return $hook_found;
}

sub my_hook_timer_cb
{
    # simply add the flood_counter
    $flood_counter++;
    return weechat::WEECHAT_RC_OK;
}

# -----------------------------[ config ]-----------------------------------
sub init_config
{

    foreach my $option (keys %options){
        if (!weechat::config_is_set_plugin($option)){
            weechat::config_set_plugin($option, $options{$option});
        }
        else{
            $options{$option} = weechat::config_get_plugin($option);
        }
    }
  # set help text for options
  if ( ($weechat_version ne '') && (weechat::info_get('version_number', '') >= 0x00030500) ) {    # v0.3.5
    foreach my $desc_options (keys %desc_options)
    {
      weechat::config_set_desc_plugin($desc_options,$desc_options{$desc_options});
    }
  }

}

sub toggle_config_by_set
{
    my ($pointer, $name, $value) = @_;
    $name = substr($name, length("plugins.var.perl.$SCRIPT_NAME."), length($name));
    $options{$name} = $value;
# insert a refresh here
    return weechat::WEECHAT_RC_OK;
}
# -----------------------------[ shutdown ]-----------------------------------
sub shutdown_cb
{
    # close database
    $DBH->disconnect() if ($DBH);
    $DBH_child->disconnect() if ($DBH_child);
    return weechat::WEECHAT_RC_OK;
}

# -------------------------------[ init ]-------------------------------------
# first function called by a WeeChat-script.
weechat::register($SCRIPT_NAME, $SCRIPT_AUTHOR, $SCRIPT_VERSION,
                  $SCRIPT_LICENCE, $SCRIPT_DESC, 'shutdown_cb', '')  || return;

    $weechat_version = weechat::info_get('version_number', '');

    if ( ($weechat_version ne '') && (weechat::info_get('version_number', '') <= 0x00030400) )
    {
        OUTPUT('',weechat::prefix('error') . 'You need WeeChat >= 0.3.4. Visit: www.weechat.org');
        weechat::command('',"/wait 1ms /perl unload $SCRIPT_NAME");
    }
    else
    {
        init_config();
        open_database();

        weechat::hook_command($SCRIPT_NAME, $SCRIPT_DESC, "host <host> [server] [-regex] || nick <nick> [server] [-regex] || scan [<server.channel>] || count",
                      "                host : look for hostname\n".
                      "                nick : look for nick\n".
                      "                scan : scan a channel (be careful; scanning large channels takes a while!)\n".
                      "                       you should manually /WHO #channel first or use /quote PROTOCTL UHNAMES\n".
                      "                count: display the number of rows in database\n".
                      "             del_date: delete all entries from date1 to date2\n".
                      "remove_nick_from_host: remove a nick from a given host\n".
                      "\n\n".
                      "Stalker will add nick!user\@host to database monitoring JOIN/WHOIS/NICK messages.\n\n".
                      "\n".
                      "Monitor specific channels:\n".
                      "==========================\n".
                      "Set following option:\n".
                      "    /set plugins.var.perl.".$SCRIPT_NAME.".use_localvar \"on\"  (default: off)\n".
                      "Now you'll have to set a localvar for those channels to monitor:\n".
                      "    /buffer set localvar_set_stalker [value]\n".
                      "       values: \"on\", \"true\", \"t\", \"yes\", \"y\", \"1\")\n".
                      "\n".
                      "Display additional information below join message:\n".
                      "=================================================\n".
                      "Example: [stalker] nils_2 is also known as: nils_2_\n".
                      "    /set plugins.var.perl.".$SCRIPT_NAME.".additional_join_info \"on\"  (default: off)\n".
                      "If you want to drop informations for specific channels (especially channels with lot of nicks):\n".
                      "    /buffer set localvar_set_stalker_drop_additional_join_info [value]\n".
                      "       values: \"on\", \"true\", \"t\", \"yes\", \"y\", \"1\")\n".
                      "\n".
                      "Regex:\n".
                      "======\n".
                      "$SCRIPT_NAME performs standard perl regular expression matching with option '-regex'.\n".
                      "Note that regex matching will not use SQLite indices, but will iterate over all rows, so it could be quite costly in terms of performance.\n".
                      "\n".
                      "Tags:\n".
                      "======\n".
                      $SCRIPT_NAME." can use tags to display messages. See documentation for most commonly used tags and add them in following option:\n".
                      "    /set plugins.var.perl.".$SCRIPT_NAME.".tags \"no_log\"\n".
                      "\n".
                      "Examples:\n".
                      "  search for nick 'nils_2'\n".
                      "    /".$SCRIPT_NAME." nick nils_2\n".
                      "  search for nick 'nils_2' on a different server named 'unknown'\n".
                      "    /".$SCRIPT_NAME." nick nils_2 unknown\n".
                      "  search for nicks starting with 'ni'\n".
                      "    /".$SCRIPT_NAME." nick \\bni.* -regex\n".
                      "  search all hosts located in '.de'\n".
                      "    /".$SCRIPT_NAME." host .*\\.de -regex\n".
                      "  remove nick from an association host'\n".
                      "    /".$SCRIPT_NAME." remove_nick_from_host TheNick ~the\@bad.users.host\n".
                      "  remove entries from database in range of given date:'\n".
                      "    /".$SCRIPT_NAME." del_date 2014-01-01 2014-12-31\n".
                      "",
                      "count %-||".
                      "del_date %-||".
                      "host %% %(irc_servers)|-regex %-||".
                      "nick %(nick) %(irc_servers)|-regex -regex %-||".
                      "remove_nick_from_host %(nick) |-regex -regex %-||".
                      "scan %(buffers_names) %-", "stalker_command_cb", "");

        weechat::hook_config("plugins.var.perl.$SCRIPT_NAME.*", "toggle_config_by_set", "");
#        weechat::hook_signal('*,irc_in2_join', 'irc_in2_join_cb', '');
        weechat::hook_print('','irc_join','',1,'irc_in2_join_cb','');
        weechat::hook_signal('*,irc_in2_311', 'irc_in2_whois_cb', '');
        weechat::hook_signal('*,irc_in2_NICK', 'irc_in2_nick_cb', '');
    }