query_blocker.pl 36.8 KB
Newer Older
1 2 3 4 5
# -----------------------------------------------------------------------------
#
# query_blocker.pl - Simple blocker for private messages (i.e. spam).
#
# -----------------------------------------------------------------------------
6
# Copyright (c) 2009-2014 by rettub <rettub@gmx.net>
7
# Copyright (c) 2011-2018 by nils_2 <weechatter@arcor.de>
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
#
# 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/>.
#
# -----------------------------------------------------------------------------
#
# Simple IRC query blocker.
25
# - requires WeeChat 0.4.2 or newer
26 27 28 29 30 31 32 33 34 35
# - suggests perl script newsbar
#
# Got inspiration from (xchat script):
# GodOfGTA's Query-Blocker (eng) 1.2.3
#   http://home.arcor.de/godofgta/xchat/queryblocker-eng.pl
#
#
# Newest version available at:
#   git://github.com/rettub/weechat-plugins.git
#
36 37 38
## Development is currently hosted at
# https://github.com/weechatter/weechat-scripts
#
39 40
# -----------------------------------------------------------------------------
# History:
41 42 43 44 45 46 47
# 2018-07-30, usefulz & nils_2:
#     version 1.2:
#     FIX: undefine subroutine
#     ADD: eval_expression() for options
#     FIX: Warnung: Use of uninitialized value using highmon as a bar
#     FIX: Warnung: Use of uninitialized value using newsbar
#
48 49
# 2017-04-14, nils_2:
#     version 1.1:
50
#       ADD: function to ignore server (https://github.com/weechat/scripts/issues/79)
51 52
#
# 2016-12-11, mumixam:
53
#     version 1.0:
54
#     FIX: message starting with color not caught
55
#
56 57 58 59
# 2014-05-22, nils_2:
#     version 0.9:
#     IMPROVED: use NOTICE instead of PRIVMSG for auto-response (suggested by Mkaysi)
#
60 61 62 63
# 2013-05-01, nils_2:
#     version 0.8:
#     ADD: option ignore_auto_message (suggested by bpeak)
#
64 65 66 67 68 69 70 71
# 2013-02-24, nils_2:
#     version 0.7:
#     FIX: case insensitive comparison for "nickserv" and "chanserv"
#     ADD: option 'show_first_message_only' (suggested by gry)
#
# 2012-08-16, nils_2:
#     version 0.6.1:
#     IMPROVED: help text to allow a temporary query
72
#
73 74 75 76 77 78 79
# 2012-06-12, nils_2:
#     version 0.6:
#     FIX: allow own queries without 'mynick' in query whitelist
#     ADD: option 'temporary_mode'.
#     ADD: whitelist is now using format: server.nickname (please update your qb-whitelist!)
#     ADD: tab completion for all commands
#
80 81 82 83 84 85 86 87 88 89 90
# 2012-05-03, nils_2:
#     version 0.5:
#     FIX: invalid pointer for function infolist_get()
#     FIX: problem with case-sensitive nicks
#     FIX: work-around for [bug #27936] removed. (weechat ≥ 0.3.2)
#     ADD: option msgbuffer (idea by pmo)
#     ADD: option open_on_startup (idea by pmo)
#     ADD: option show_nick_only and show_deny_message
#     ADD: nick completion for add/del
#
# 2011-09-17, nils_2:
91 92 93
#     version 0.4:
#     FIX:         infolist() not freed
#
94
# 2010-12-20, nils_2:
95 96
#     version 0.3:
#     FIX:         find_color_nick(), now using API function weechat::info_get("irc_nick_color")
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
#
# 2010-01-10, rettub:
#     version 0.2:
#     new options: quiet, show_hint
#                  auto_message, auto_message_prefix
#
# 2009-11-03, rettub:
#     version 0.1: initial release
#
# -----------------------------------------------------------------------------
# TODO
#   - make Auto-Messages configurable

use Data::Dumper;
use warnings;
use strict;

my $SCRIPT      = 'query_blocker';
my $AUTHOR      = 'rettub <rettub@gmx.net>';
116
my $VERSION     = '1.2';
117 118 119 120
my $LICENSE     = 'GPL3';
my $DESCRIPTION = 'Simple blocker for private message (i.e. spam)';
my $COMMAND     = "query_blocker";             # new command name
my $ARGS_HELP   = "<on> | <off> | <status> | <list [last]> | <add [nick_1 [... [nick_n]]]> | <del nick_1 [... [nick_n]]> | <reload> | <blocked [clear]>";
121 122 123 124 125
my %help_desc = ( "block_queries"       => "to enable or disable $COMMAND (default: 'off')",
                  "quiet"               => "will send auto reply about blocking, but don't send any notice to you. (default: 'off')",
                  "show_deny_message"   => "show you the deny message, sent to user. (default: 'off')",
                  "show_hint"           => "show hint how to allow queries for nick. (default: 'on')",
                  "show_nick_only"      => "only show nick and server. (default: 'off')",
126
                  "show_first_message_only"=> "Show only first message sent by blocked queries (default: 'on')",
127
                  "whitelist"           => "path/file-name to store/read nicks not to be blocked (default: qb-whitelist.txt)",
128 129 130
                  "auto_message"        => "messages to inform user that you don't like to get private messages without asking first. '%N' will be replaced with users nick (note: content is evaluated, see /help eval).",
                  "auto_message_prefix" => "Prefix for auto message, may not be empty! (note: content is evaluated, see /help eval)",
                  "msgbuffer"           => "buffer used to display $SCRIPT messages (current = current buffer, private = private buffer, weechat = weechat core buffer, server = server buffer, buffer = $SCRIPT buffer, highmon = highmon buffer, newsbar = newsbar-bar)",
131
                  "logger"              => "logger status for $SCRIPT buffer (default: 'off')",
132
                  "hotlist_show"        => "$SCRIPT buffer appear in hotlists (status bar/buflist) (default: 'off')",
133
                  "open_on_startup"     => "open $SCRIPT buffer on startup. option msgbuffer has to be set to 'buffer' (default: 'off')",
134 135
                  "temporary_mode"      => "if 'on' you have to manually add a nick to whitelist. otherwise a conversation will be temporary only and after closing query buffer the nick will be discard (default: 'off')",
                  "ignore_auto_message" => "path/file-name to store/read nicks to not send an auto message (default: qb-ignore_auto_message.txt)",
136 137
);

138 139 140 141 142
my $CMD_HELP    = <<EO_HELP;
If a not allowed (blocked) nick sends you a private message, you will see a notice about nick, server and the message, but no buffer will be created. Then the nick gets a 'blocked' state, which will prevent you from seeing his queries again till you restart WeeChat, reload the script or you put the nick into the whitelist (if newsbar.pl is running notices will be printed there). In addition the user will be informed about blocking by an auto responce message when he gains the blocked state. So he can ask you in the public channel to allow his private messages.
If you send a private message to a user, his nick will be added to the whitelist.

Arguments:
143 144 145 146 147 148 149
              on/off: toggle blocking of queries.
              status: show blocking status.
         list [last]: show whitelist, use last to show the nick blocked last.
     add/del [nicks]: add/delete nick(s) to/from whitelist. (if no nick is given, 'add' will use the last blocked one).
                      ('nicks' is a list of nicks seperated by spaces).
              reload: reload whitelist (useful if you changed the file-location i.e. to use a common file).
     blocked [clear]: list blocked nicks. If arg 'clear' is given all blocked nicks will be removed.
150 151

Script Options:
152
 ignore_auto_message: $help_desc{ignore_auto_message}
153 154 155 156 157 158 159 160 161 162 163 164
           whitelist: $help_desc{whitelist}
       block_queries: $help_desc{block_queries}
        auto_message: $help_desc{auto_message}
 auto_message_prefix: $help_desc{auto_message_prefix}
               quiet: $help_desc{quiet}
   show_deny_message: $help_desc{show_deny_message}
           show_hint: $help_desc{show_hint}
      show_nick_only: $help_desc{show_nick_only}
           msgbuffer: $help_desc{msgbuffer}
              logger: $help_desc{logger}
        hotlist_show: $help_desc{hotlist_show}
     open_on_startup: $help_desc{open_on_startup}
165
      temporary_mode: $help_desc{temporary_mode}
166 167 168

By default all private messages (/query, /msg) from nicks not in the whitelist will be blocked.
 - to allow all private message, $SCRIPT can be disabled, type '/$COMMAND off'.
169
 - to allow private messages from certain nicks, put them into the whitelist, type '/$COMMAND add nick' (you can use nick-completion).
170
   if you start a query, the nick will be added as a temporary nick. the nick will be removed when you close query
171
 - to remove a nick from the whitelist, type '/$COMMAND del nick' (you can use nick-completion).
172
 - you can add a localvar for a specific server to disable $COMMAND for this server: /buffer set localvar_set_query_blocker 1
173 174 175 176

NOTE: If you load $SCRIPT the first time, blocking of private messages is disabled, you have to enable blocking, type '/$COMMAND on'.
EO_HELP

177 178 179 180 181 182 183 184
my $COMPLETITION  = "on %-".
                    "||off %-".
                    "||status %-".
                    "||list last %-".
                    "||add %(perl_query_blocker_add)| %(nick)|%*".
                    "||del %(perl_query_blocker_del)| %(nick)|%*".
                    "||reload %-".
                    "||blocked clear %-";
185 186
my $CALLBACK      = $COMMAND;
my $CALLBACK_DATA = undef;
187
my $weechat_version;
188 189 190 191

# script options
my %SETTINGS = (
    "block_queries" => "off",
192 193 194 195
    "quiet"         => "off",
    "show_deny_message" => "off",
    "show_hint"     => "on",
    "show_nick_only"=> "off",
196
    "show_first_message_only" => "on",
197
    "whitelist"     => "qb-whitelist.txt",
198
    "auto_message"  => "I'm using a query blocking script, please wait while i whitelist you!",
199
    "auto_message_prefix" => "Auto-Message: ",
200 201 202 203
    "msgbuffer"     => "server", # current, private, weechat, buffer, highmon
    "logger"        => "off",
    "hotlist_show"  => "off",
    "open_on_startup"  => "off",
204
    "temporary_mode" => "off",
205
    "ignore_auto_message" => "qb-ignore_auto_message.txt",
206 207 208 209 210 211 212 213 214 215 216
);

my $Last_query_nick = undef;

sub DEBUG {weechat::print('', "***\t" . $_[0]);}

# {{{ helpers
# 
# irc_nick_find_color: find a color for a nick (according to nick letters)
sub irc_nick_find_color
{
217 218
    my $nick_name = $_[0];
    return weechat::info_get("irc_nick_color", $nick_name);
219 220 221 222 223
}
# }}}

my %Blocked = ();
my %Allowed = ();
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
my %ignore_auto_message = ();

sub check_ignore_auto_message { return exists $ignore_auto_message{ $_[0] }; }

sub ignore_auto_message_read {
    my $whitelist = weechat::config_get_plugin( "ignore_auto_message" );
    return unless -e $whitelist;
    open (WL, "<", $whitelist) || DEBUG("$whitelist: $!");
        while (<WL>) {
                chomp;
                my ( $server, $nick ) = split /\./,$_;           # servername.nickname
                if (not defined $nick){
                    close WL;
                    weechat::print("",weechat::prefix("error")."$SCRIPT: $whitelist wrong format for entry: $_ (new format: servername.nickname).");
                    return 1;
                }
                $ignore_auto_message{$_} = 1  if length $_;
        }
        close WL;
        return 0;
}
245

246
sub nick_allowed { return exists $Allowed{ $_[0] }; }
247 248 249 250 251 252 253

sub whitelist_read {
    my $whitelist = weechat::config_get_plugin( "whitelist" );
    return unless -e $whitelist;
    open (WL, "<", $whitelist) || DEBUG("$whitelist: $!");
	while (<WL>) {
		chomp;
254 255 256 257 258 259 260
                my ( $server, $nick ) = split /\./,$_;           # servername.nickname
                if (not defined $nick){
                    close WL;
                    weechat::print("",weechat::prefix("error")."$SCRIPT: $whitelist wrong format for entry: $_ (new format: servername.nickname).");
                    return 1;
                }
                $Allowed{$_} = 1  if length $_;
261 262
	}
	close WL;
263
	return 0;
264 265 266 267 268
}

sub whitelist_save {
    my $whitelist = weechat::config_get_plugin( "whitelist" );
    open (WL, ">", $whitelist) || DEBUG("write whitelist: $!");
269 270 271
    foreach ( sort { "\L$a" cmp "\L$b" } keys %Allowed ){
        print WL "$_\n" if ($Allowed{$_} == 1);
    }
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
    close WL;
}

# newsbar api staff {{{
sub info2newsbar {
    my ( $color, $category, $server, $nick, $message ) = @_;
    weechat::command( '',
            "/newsbar  add --color $color $category\t"
          . irc_nick_find_color($nick)
          . $nick
          . weechat::color('reset') . '@'
          . irc_nick_find_color($server)
          . $server
          . weechat::color('reset')
          . weechat::color('bold')
          . " tries to start a query: "
          . weechat::color('reset')
          . $message );
    weechat::command( '',
            "/newsbar  add --color $color $category\t"
          . "To allow the query, type: "
          . "/$COMMAND add $nick" ) unless (weechat::config_get_plugin('show_hint') eq 'off');
}

sub newsbar {
297
    my $info_list = weechat::infolist_get( "perl_script", "", "newsbar" );
298
    weechat::infolist_next($info_list);
299 300 301
    my $newsbar = weechat::infolist_string( $info_list, "name" ) eq 'newsbar';
    weechat::infolist_free($info_list);
    return $newsbar if (defined $newsbar);
302 303 304
}
#}}}

305 306 307 308
sub print_info {
    my ( $buffer, $server, $my_nick, $nick, $message ) = @_;
    my $prefix_network = weechat::config_string( weechat::config_get("weechat.look.prefix_network"));
    my $buf_pointer = "";
309
    my $bar_pointer = "";
310
    my $orig_message = $message;
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328

    if     ( $buffer eq "current" ){
        $buf_pointer = weechat::current_buffer();
    }elsif ( $buffer eq "weechat" ){
        $buf_pointer = weechat::buffer_search("core","weechat");
    }elsif ( $buffer eq "server" ){
        $buf_pointer = weechat::buffer_search("irc","server".".".$server);
    }elsif ( $buffer eq "private" ){
        $buf_pointer = weechat::buffer_search("irc",$server.".".$my_nick);
    }elsif ( $buffer eq "buffer" ){
        $buf_pointer = weechat::buffer_search("perl",$SCRIPT);
        $buf_pointer = query_blocker_buffer_open() if ( $buf_pointer eq "" );
    }elsif ( $buffer eq "highmon" ){
        $buf_pointer = weechat::buffer_search("perl","highmon");
    }else{
        $buf_pointer = weechat::buffer_search("",$buffer);
        $server = weechat::buffer_get_string($buf_pointer, "localvar_server");
    }
329

330
    # no buffer found, use weechat fallback buffer
331
    if ( $buf_pointer eq "" or not defined $buf_pointer ){
332 333 334
        if ( $server eq "" ){
            $buf_pointer = weechat::buffer_search_main();
        }else{
335
            $buf_pointer = fallback_buffer($server);
336 337 338 339
        }
    }
    return $buf_pointer if (lc(weechat::config_get_plugin('quiet') eq "on"));

340
    if (lc(weechat::config_get_plugin('show_nick_only') eq 'off')) {
341 342 343 344
        $message = ": $message";
    }else{
        $message = "";
    }
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
    unless ( exists $Blocked{$server.".".$nick} and lc(weechat::config_get_plugin('show_first_message_only') eq 'off') ) {
        weechat::print($buf_pointer,"$prefix_network\t"
                                    .irc_nick_find_color($nick).$nick
                                    .weechat::color('reset')
                                    ." tries to start a query on "
                                    .irc_nick_find_color($server).$server
                                    .weechat::color('reset')
                                    .$message );
        weechat::print($buf_pointer,"$prefix_network\t"
                                    ."to allow query: /$COMMAND add "
                                    .irc_nick_find_color($server).$server
                                    .weechat::color('reset')
                                    ."."
                                    .irc_nick_find_color($nick).$nick
                                    .weechat::color('reset')."\n"
                                    ."or to allow temporary query: /query -server "
                                    .irc_nick_find_color($server).$server
                                    .weechat::color('reset')
                                    ." "
                                    .irc_nick_find_color($nick).$nick
                                    .weechat::color('reset')) unless (weechat::config_get_plugin('show_hint') eq 'off');
    }else{
        weechat::print($buf_pointer,irc_nick_find_color($server).$server."."
                                    .irc_nick_find_color($nick).$nick."\t"
                                    .weechat::color('reset')
                                    .$orig_message );
    }
372 373 374
    return $buf_pointer;
}

375 376 377 378 379 380
sub eval_expression{
    my ($string) = @_;
    return weechat::string_eval_expression($string, {}, {},{});
}

# get value from msgbuffer_fallback option
381
sub fallback_buffer{
382
    my ($server) = @_;
383 384
    my $fallback = weechat::config_string( weechat::config_get("irc.look.msgbuffer_fallback") );
    my $buf_pointer;
385 386
    $buf_pointer = weechat::current_buffer() if ( $fallback eq "current" );
    $buf_pointer = weechat::buffer_search("irc","server".".".$server) if ( $fallback eq "server" );
387
    return $buf_pointer;
388 389 390 391 392 393
}

sub modifier_irc_in_privmsg {
    my ( $data, $signal, $server, $arg ) = @_;
    my $my_nick = weechat::info_get( 'irc_nick', $server );

394 395 396
    # by default, blocking is enabled for all server. except the one with a localvar
    return $arg if (weechat::buffer_get_string(weechat::buffer_search("irc", "server.".$server), 'localvar_query_blocker'));

397
    # check for query message
398
    if ( $arg =~ m/:(.+?)!.+? PRIVMSG $my_nick :(.*)/i ) {
399 400 401
        my $query_nick = $1;
        my $query_msg  = $2;

402 403 404
        # always allow own queries
        return $arg if ($query_nick eq $my_nick);

405
        # if nick is allowed to send queries, let WeeChat handle the query
406
        return $arg if nick_allowed($server . "." . $query_nick);
407

408 409 410
        # if nick is in ignore_auto_message list, ignore it.
        return '' if check_ignore_auto_message($server . "." . $query_nick);

411
        $Last_query_nick = $server . "." . $query_nick;
412
        my $buf_pointer;
413 414 415 416
        unless ( exists $Blocked{$server.".".$query_nick} and lc(weechat::config_get_plugin('show_first_message_only') eq 'on') )
        {
            unless (lc(weechat::config_get_plugin('quiet') eq 'on'))
            {
417 418
                # print messages to.... newsbar, current, private, server, weechat, buffer, highmon
                if ( newsbar() eq "1" and lc(weechat::config_get_plugin('msgbuffer')) eq 'newsbar' ) {
419
                    info2newsbar( 'lightred', '[QUERY-WARN]', $server, $query_nick, $query_msg );
420 421 422 423 424 425 426 427 428 429 430 431
                } elsif ( lc(weechat::config_get_plugin('msgbuffer')) eq 'current' ) {
                    $buf_pointer = print_info("current", $server, $my_nick, $query_nick, $query_msg);
                } elsif ( lc(weechat::config_get_plugin('msgbuffer')) eq 'server' ) {
                    $buf_pointer = print_info("server", $server, $my_nick, $query_nick, $query_msg);
                } elsif ( lc(weechat::config_get_plugin('msgbuffer')) eq 'private' ) {
                    $buf_pointer = print_info("private", $server, $my_nick, $query_nick, $query_msg);
                } elsif ( lc(weechat::config_get_plugin('msgbuffer')) eq 'weechat' ) {
                    $buf_pointer = print_info("weechat", $server, $my_nick, $query_nick, $query_msg);
                } elsif ( lc(weechat::config_get_plugin('msgbuffer')) eq 'buffer' ) {
                    $buf_pointer = print_info("buffer", $server, $my_nick, $query_nick, $query_msg);
                } elsif ( lc(weechat::config_get_plugin('msgbuffer')) eq 'highmon' ) {
                    $buf_pointer = print_info("highmon", $server, $my_nick, $query_nick, $query_msg);
432
                } else {
433
                    $buf_pointer = print_info(weechat::config_get_plugin('msgbuffer'), $server, $my_nick, $query_nick, $query_msg);
434 435
                }
            }
436 437 438 439 440 441
            #elsif (lc(weechat::config_get_plugin('quiet') eq 'on')){
            #    $buf_pointer = print_info(lc(weechat::config_get_plugin('msgbuffer')), $server, $my_nick, $query_nick, $query_msg);
            #}

            # auto responce msg to query_nick (deny_message)
            my $msg = weechat::config_get_plugin('auto_message_prefix') . weechat::config_get_plugin('auto_message');
442 443
            $msg =~ s/%N/$query_nick/g;     # keep this for historical reasons
            $msg = eval_expression($msg);
444

445 446
            if (lc(weechat::config_get_plugin('show_deny_message')) eq 'off' or lc(weechat::config_get_plugin('quiet') eq 'on'))
            {
447 448 449
                # According to the RFC 1459, automatic messages must not be sent as response to NOTICEs and currently it might be possible to get in loop of automatic away messages or something similar.
#                weechat::command( '', "/mute -all /msg -server $server $query_nick $msg " );
                weechat::command( '', "/mute -all /notice -server $server $query_nick $msg " );
450
            }
451
            else        # show deny message!
452
            {
453 454
#                weechat::command( '', "/mute -all /msg -server $server $query_nick $msg " );
                weechat::command( '', "/mute -all /notice -server $server $query_nick $msg " );
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
                if ( newsbar() eq "1" and lc(weechat::config_get_plugin('msgbuffer')) eq 'newsbar' ) {
                    weechat::command( '',
                    "/newsbar  add --color lightred [QUERY-WARN]\t"     # $color $category
                    . irc_nick_find_color($query_nick)
                    . $query_nick
                    . weechat::color('reset') . '@'
                    . irc_nick_find_color($server)
                    . $server
                    . weechat::color('reset')
                    . ": "
                    . weechat::color('bold')
                    . "$msg");
                }
                else {
                    weechat::print($buf_pointer,"$SCRIPT\t"."$query_nick"."@"."$server: $msg");
                }
471
            }
472 473
            # counter for how many blocked messages
            $Blocked{$server.".".$query_nick} = 0;
474
        }
475
            $Blocked{$server.".".$query_nick}++;
476 477 478
    }
    else
    {
479 480 481 482 483 484 485
        return $arg;
    }

    # return empty string - don't create a new buffer
    return '';
}

486
# add nick to whitelist
487 488
sub _add {
    my $arg = shift;
489 490
    my $temporary_mode = shift;
    my $temporary_txt = "";
491 492 493

    if ( defined $arg ) {
        foreach ( split( / +/, $arg ) ) {
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
            my ($server,$nick);
            ($server,$nick) = split(/\./,$_);
            if (not defined $nick){
                $nick = $server;
                $server = weechat::buffer_get_string(weechat::current_buffer(),"localvar_server");
                if ($server eq ""){
                    weechat::print( '', "Server missing for: '".
                                        irc_nick_find_color($nick).
                                        $nick . weechat::color('reset') . "'");
                    return;
                }
            }
            $Last_query_nick = undef if ( defined $Last_query_nick and $server.".".$nick eq $Last_query_nick );
            $Allowed{$server.".".$nick} = $temporary_mode;
            delete $Blocked{$server.".".$nick};
            $temporary_txt = " (temporary)" if ($temporary_mode == 2);
            weechat::print( '', "Allow" . $temporary_txt ." queries for: '".
                                weechat::color(weechat::config_color(weechat::config_get("weechat.color.chat_server"))).$server .
                                weechat::color('reset') . "." .
                                irc_nick_find_color($nick).
                                $nick . weechat::color('reset') . "'");
515 516 517
        }
        whitelist_save();
    } elsif ( defined $Last_query_nick and not exists $Allowed{$Last_query_nick} ) {
518 519
        $Allowed{$Last_query_nick} = $temporary_mode;
        my ($server,$nick) = split(/\./,$Last_query_nick);
520
        delete $Blocked{$Last_query_nick};
521 522 523 524 525
        weechat::print( '', "Allow" . $temporary_txt . " queries for: '".
                            weechat::color(weechat::config_color(weechat::config_get("weechat.color.chat_server"))).$server .
                            weechat::color('reset') . "." .
                            irc_nick_find_color($nick).
                            $nick . weechat::color('reset') . "'");
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
        $Last_query_nick = undef;
        whitelist_save();
        # FIXME: open query window
    } else {
        weechat::print( '', "There is no nick to be added to the whitelist");
    }
}

# handle hooks {{{
{
my %Hooks;

sub qb_hooked { %Hooks };

sub qb_hook {
    return 1 if qb_hooked();

543 544 545
    $Hooks{query}          = weechat::hook_command_run( '/query *', 'qb_query', "" );
    $Hooks{msg}            = weechat::hook_command_run( '/msg *',   'qb_msg',   "" );
    $Hooks{modifier_in}    = weechat::hook_modifier( "irc_in_privmsg", "modifier_irc_in_privmsg", "" );
546 547
    $Hooks{completion_del} = weechat::hook_completion("perl_query_blocker_del", "query blocker completion_del", "query_blocker_completion_del_cb", "");
    $Hooks{completion_add} = weechat::hook_completion("perl_query_blocker_add", "query blocker completion_add", "query_blocker_completion_add_cb", "");
548 549

    # FIXME handle hook errors (hook_ returns NULL := '')
550 551 552 553
    DEBUG("cant hook completion for del argument")      if $Hooks{completion_del}    eq '';
    DEBUG("cant hook completion for add argument")      if $Hooks{completion_add}    eq '';
    DEBUG("cant hook command '/query'")                 if $Hooks{query}    eq '';
    DEBUG("cant hook command '/msg'")                   if $Hooks{msg}      eq '';
554
    DEBUG("cant hook modifier 'irc_in_privmsg'")        if $Hooks{modifier_in} eq '';
555 556 557 558 559 560 561 562 563 564

    return 0;
}

sub qb_unhook {
    return 1 unless qb_hooked();

    # FIXME handle hook errors (hook_ returns NULL := '')
    weechat::unhook( $Hooks{query} );
    weechat::unhook( $Hooks{msg} );
565
    weechat::unhook( $Hooks{modifier_in} );
566 567
    weechat::unhook( $Hooks{completion_del} );
    weechat::unhook( $Hooks{completion_add} );
568 569 570 571 572 573
    undef %Hooks;

    return 0;
}
} # }}}

574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
sub query_blocker_completion_del_cb{
    my ($data, $completion_item, $buffer, $completion) = @_;
    foreach ( sort { "\L$a" cmp "\L$b" } keys %Allowed ) {
        weechat::hook_completion_list_add($completion, $_,1, weechat::WEECHAT_LIST_POS_SORT);
    }
return weechat::WEECHAT_RC_OK;
}
sub query_blocker_completion_add_cb{
    my ($data, $completion_item, $buffer, $completion) = @_;
    foreach (reverse keys %Blocked) {
        weechat::hook_completion_list_add($completion, $_,1, weechat::WEECHAT_LIST_POS_SORT);
    }
return weechat::WEECHAT_RC_OK;
}


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
sub toggled_by_set {
    my ( $script, $option, $value ) = @_;

    if ( $value ne 'on' ) { # all values different to 'on' will disable blocking
        if ( $value ne 'off' ) {
            weechat::config_set_plugin( $option, "off" );
            DEBUG("wrong value for option '$option', falling back to 'off'");
        }
        if ( qb_hooked() ) {    # enabled?
            qb_unhook();
            weechat::print( '', "$COMMAND: disabled" );
        } else {
            weechat::print( '', "$COMMAND: already disabled" );
        }
    } else {    # enable blocking
        unless ( qb_hooked() ) {
            qb_hook();
            weechat::print( '', "$COMMAND: private messages will be blocked" );
        } else {
            weechat::print( '', "$COMMAND: private messages already blocked" );
        }
    }

    return weechat::WEECHAT_RC_OK;
}

sub query_blocker {
    my ( $data, $buffer, $args ) = ( $_[0], $_[1], $_[2] );

    if ( $args =~ /^o(n|ff)$/ ) {
        weechat::config_set_plugin( 'block_queries', $args );
    } elsif ( $args eq 'status' ) {
        if ( weechat::config_get_plugin( 'block_queries') eq 'on' ) {
            weechat::print( '', "$COMMAND: private messages will be blocked");
        } else {
            weechat::print( '', "$COMMAND: disabled");
        }
    } elsif ( $args eq 'reload' ) {
        whitelist_read();
    } else {
        my ( $cmd, $arg ) = ( $args =~ /(.*?)\s+(.*)/ );
        $cmd = $args unless $cmd;
        if ( $cmd eq 'list' ) {
            if ( defined $arg and $arg eq 'last' ) {
                if (defined $Last_query_nick) {
635 636 637 638 639 640
                    my ($server,$nick) = split(/\./,$Last_query_nick);
                    weechat::print( '', "Last blocked nick: '".
                                        weechat::color(weechat::config_color(weechat::config_get("weechat.color.chat_server"))).$server .
                                        weechat::color('reset') . "." .
                                        irc_nick_find_color($nick).
                                        $nick . weechat::color('reset') . "'");
641 642 643 644 645 646 647
                } else {
                    weechat::print( '', "No blocked nicks");
                }
            } else {
                my $n = keys %Allowed;
                weechat::print( '', "Allowed nicks for queries ($n):" );
                foreach ( sort { "\L$a" cmp "\L$b" } keys %Allowed ) {
648 649 650 651 652 653 654 655 656
                    my ($server,$nick) = split(/\./,$_);
                    my $temporary_txt = "";
                    $temporary_txt = "  (temporary)" if ( $Allowed{$server.".".$nick} == 2);
                    weechat::print( '', "   ".
                                        weechat::color(weechat::config_color(weechat::config_get("weechat.color.chat_server"))).$server .
                                        weechat::color('reset') . "." .
                                        irc_nick_find_color($nick).
                                        $nick . weechat::color('reset').
                                        $temporary_txt);
657 658 659 660 661
                }
            }
        } elsif ( $cmd eq 'blocked' ) {
            if ( keys %Blocked ) {
                if ( defined $arg and $arg eq 'clear' ) {
662
                    weechat::print( '', "Removing blocked state from:");
663
                    foreach ( sort { "\L$a" cmp "\L$b" } keys %Blocked ) {
664 665 666 667 668 669
                        my ($server,$nick) = split(/\./,$_);
                        weechat::print( '', "   " .
                                            weechat::color(weechat::config_color(weechat::config_get("weechat.color.chat_server"))).$server .
                                            weechat::color('reset') . "." .
                                            irc_nick_find_color($nick) . $nick .
                                            weechat::color('reset') . " (#$Blocked{$_})");
670 671 672 673 674
                        delete $Blocked{$_};
                    }
                } else {
                    weechat::print( '', "Queries of this nicks have been blocked:" );
                    foreach ( sort { "\L$a" cmp "\L$b" } keys %Blocked ) {
675 676 677 678 679 680
                        my ($server,$nick) = split(/\./,$_);
                        weechat::print( '', "   " .
                                            weechat::color(weechat::config_color(weechat::config_get("weechat.color.chat_server"))).$server .
                                            weechat::color('reset') . "." .
                                            irc_nick_find_color($nick) . $nick .
                                            weechat::color('reset') . " (#$Blocked{$_})");
681 682 683 684 685 686
                    }
                }
            } else {
                weechat::print( '', "No nicks have been blocked" );
            }
        } elsif ( $cmd eq 'add' ) {
687
            _add($arg,1);
688 689 690 691
        }elsif ( $cmd eq 'del' and defined $arg ) {
            foreach ( split( / +/, $arg ) ) {
                if (exists $Allowed{$_} ) {
                    delete $Allowed{$_};
692 693 694 695 696 697
                    my ($server,$nick) = split(/\./,$_);
                    weechat::print( '', "Nick removed from whitelist: '".
                                        weechat::color(weechat::config_color(weechat::config_get("weechat.color.chat_server"))).$server .
                                        weechat::color('reset') . "." .
                                        irc_nick_find_color($nick) . $nick .
                                        weechat::color('reset') . "'");
698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720
                } else {
                    weechat::print( '', "Can't remove nick, not in whitelist: '" . irc_nick_find_color($_) . $_ . weechat::color('reset') . "'");
                }
            }
            whitelist_save();
        }
    }
    return weechat::WEECHAT_RC_OK;
}

sub _get_nick {
    my ($l) = shift;
    $l =~ s/\/(query|msg) +//;

    if ($l =~ /-server/ ) {
        $l =~ s/-server \w+ //;
    }
    
    $l =~ s/ .*$//;

    return $l;
}

721
# /query
722
sub qb_query {
723 724 725 726 727 728 729 730 731
    my ($data, $buffer, $command) = @_;
    my $server = weechat::buffer_get_string($buffer,"localvar_server");
    return weechat::WEECHAT_RC_OK if ($server eq "");

    my $n = _get_nick($command);
    return weechat::WEECHAT_RC_OK if (lc($n) eq "nickserv" or lc($n) eq "chanserv");
    my $temporary_mode = 1;
    $temporary_mode = 2 if (weechat::config_get_plugin('temporary_mode') eq "on");
    _add($server.".".$n,$temporary_mode) unless nick_allowed($server.".".$n);
732 733 734 735 736 737

    return weechat::WEECHAT_RC_OK;
}

# add nick as allowed if responce isn't auto reply
sub qb_msg {
738 739 740 741 742
    my ($data, $buffer, $command) = @_;
    my $server = weechat::buffer_get_string($buffer,"localvar_server");
    return weechat::WEECHAT_RC_OK if ($server eq "");

    my ($msg) = $command =~ /^\/msg -server .*?\s.*?\s(.*)/;
743
    return weechat::WEECHAT_RC_OK if (not defined $msg);
744
    my $n = _get_nick($_[2]);
745
    return weechat::WEECHAT_RC_OK if (lc($n) eq "nickserv" or lc($n) eq "chanserv");
746 747
    my $prefix = weechat::config_get_plugin('auto_message_prefix');

748 749 750
    my $temporary_mode = 1;
    $temporary_mode = 2 if (weechat::config_get_plugin('temporary_mode') eq "on");
    _add($server.".".$n,$temporary_mode) unless nick_allowed($server.".".$n) or $msg =~ /^$prefix/;
751 752 753 754

    return weechat::WEECHAT_RC_OK;
}

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
sub query_blocker_buffer_open
{
    my $query_blocker_buffer = weechat::buffer_new($SCRIPT, "query_blocker_buffer_input", "", "query_blocker_buffer_close", "");

    if ($query_blocker_buffer ne "")
    {
        if (weechat::config_get_plugin("hotlist_show") eq "off"){
            weechat::buffer_set($query_blocker_buffer, "notify", "0");
        }elsif (weechat::config_get_plugin("hotlist_show") eq "on"){
            weechat::buffer_set($query_blocker_buffer, "notify", "3");
        }
        weechat::buffer_set($query_blocker_buffer, "title", $SCRIPT);
        # logger
        weechat::buffer_set($query_blocker_buffer, "localvar_set_no_log", "1") if (weechat::config_get_plugin("logger") eq "off");
    }
    return $query_blocker_buffer;
}
sub query_blocker_buffer_close
{
    return weechat::WEECHAT_RC_OK;
}
sub query_blocker_buffer_input
{
    return weechat::WEECHAT_RC_OK;
}

781 782
sub buffer_closing_cb
{
783 784 785
    my ($data, $signal, $signal_data) = @_;
    return weechat::WEECHAT_RC_OK if ( weechat::buffer_get_string($signal_data, "localvar_type" ne "private"));
    my $name = weechat::buffer_get_string($signal_data, "localvar_name");
786 787
    foreach ( sort { "\L$a" cmp "\L$b" } keys %Allowed )
    {
788
        my ($server,$nick) = split(/\./,$_);
789
        delete $Allowed{$_} if ( defined $Allowed{$_} and $Allowed{$server.".".$nick} == 2 and $name eq $server.".".$nick );
790 791 792 793
    }
    return weechat::WEECHAT_RC_OK;
}

794 795 796 797
# -----------------------------------------------------------------------------
#
if ( weechat::register( $SCRIPT, $AUTHOR, $VERSION, $LICENSE, $DESCRIPTION, "", "" ) ) {
    weechat::hook_command( $COMMAND, $DESCRIPTION, $ARGS_HELP, $CMD_HELP, $COMPLETITION, $CALLBACK, "" );
798
    $weechat_version = weechat::info_get("version_number", "");
799 800
    if ( ($weechat_version ne "") && (weechat::info_get("version_number", "") < 0x00040200) ) {
        weechat::print("",weechat::prefix("error")."$SCRIPT: needs WeeChat >= 0.4.2. Please upgrade: http://www.weechat.org/");
801 802
        weechat::command("","/wait 1ms /perl unload $SCRIPT");
  }
803 804

    if ( weechat::config_get_plugin("whitelist") eq '' ) {
805
        weechat::config_set_plugin( "whitelist", weechat::info_get( "weechat_dir", "" ) . "/" . $SETTINGS{"whitelist"} );
806 807 808 809 810
    }
    while ( my ( $option, $default_value ) = each(%SETTINGS) ) {
        weechat::config_set_plugin( $option, $default_value )
          if weechat::config_get_plugin($option) eq "";
    }
811 812 813 814 815

    if ( whitelist_read() ){
        weechat::command("","/wait 1ms /perl unload $SCRIPT");
        return;
    }
816

817 818
    weechat::print( '', "$COMMAND: loaded whitelist '" . weechat::config_get_plugin( "whitelist" ) . "'");

819 820
    ignore_auto_message_read();

821
    weechat::hook_signal("buffer_closing","buffer_closing_cb","");
822
    weechat::hook_config( "plugins.var.perl.$SCRIPT.block_queries", 'toggled_by_set', $SCRIPT );
823 824 825 826 827
    if ( ($weechat_version ne "") && (weechat::info_get("version_number", "") >= 0x00030500) ) {    # v0.3.5
        foreach my $option ( keys %help_desc ){
            weechat::config_set_desc_plugin( $option,$help_desc{$option} );
        }
    }
828

829
    if ( lc(weechat::config_get_plugin('block_queries') eq "on")) {
830 831
        qb_hook();
        weechat::print( '', "$COMMAND: private messages will be blocked");
832 833 834 835 836
        if ( lc(weechat::config_get_plugin('open_on_startup')) eq "on" and lc(weechat::config_get_plugin('msgbuffer')) eq "buffer" )
        {
            my $buf_pointer = weechat::buffer_search("perl",$SCRIPT);
            $buf_pointer = query_blocker_buffer_open() if ( $buf_pointer eq "" );
}
837 838 839 840
    } else {
        weechat::print( '', "$COMMAND: disabled");
    }
}