buddylist.pl 80.4 KB
Newer Older
1
#
2
# Copyright (c) 2010-2013 by Nils Görs <weechatter@arcor.de>
3
#
4
# display the status and visited buffers of your buddies in a buddylist bar
5 6 7 8 9 10 11 12 13 14 15 16 17 18
#
# 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/>.
#
19 20
# 1.8   : fixed: problem with temporary server
#       : added: %h variable for filename
21 22 23
# 1.7   : fixed: perl error when adding and removing nick
#       : fixed: perl error: Use of uninitialized value $bitlbee_service_separator (reported by gtmanfred)
#       : improved: a warning will be displayed if no filename for the buddylist is given.
24
# 1.6   : added: support for new option "irc.network.whois_double_nick"
25 26 27
# 1.5   : fixed: wrong pointer in bar_item_remove()
#       : fixed: perl error: Use of uninitialized value $nickname
# 1.4   : added: option hide.servername.in.buddylist (suggested by Cubox)
28
# 1.3.1 : fixed: perl error: Use of uninitialized value in string comparison (reported by ArcAngel)
29 30 31 32 33
# 1.3   : added: mouse support (weechat >= v0.3.6)
#       : added: nick completion for add/del
#       : improved: hide_bar function (for example after /upgrade).
#       : fixed: did action on bar in the build callback => crashed latest git
#       : fixed: typo with option "hide.bar" and "social.net.color" removed.
34
# 1.2.1 : fixed: bitlbee_service was not set, for new added buddy
35
# v1.2  : added: function "hide_bar = always" (requested by: Emralegna)
36
#       : added: buddies will be separated by protocol (msn/jabber etc.pp.) on bitlbee server (requested by: ArcAngel)
37 38
#       : added: options "text.online", "text.away", "text.offline" (maybe usefull for color-blind people:-) 
#       : added: function weechat_config_set_desc_plugin() (only for weechat >= v0.3.5)
39
# v1.1  : fixed: offline users on bitlbee were shown as away. (reported and beta-testing by javuchi)
40 41 42 43 44 45 46
# v1.0  : redirection implemented (needs weechat >= 0.3.4). Now, its a real buddylist
#	: new options: "check.buddies", "callback.timeout", "use.redirection", "display.original.nick"
#	: buffer-number will be displayed behind nickname (option: "color.number")
#	: buddylist will be build instandly when switching bar-position.
#	: thanks to shariebeth for beta-testing
# 0.9.4 : now using irc.server_default.away_check_max_nicks and irc.server_default.away_check
# 0.9.3 : check for JOIN signal (requested by Rupp)
47 48 49 50 51 52
# 0.9.2 : server wasn't hidden for "default" settings
#	  server will be hidden if all buddies are offline for this server (option: hide.server.if.buddies.offline (requested by TenOfTen))
#	  buddies will be hidden when offline (option: hide.buddy.if.offline (requested by TenOfTen))
#	  new function added: "list"
#	  the buddylist will be saved in a new format : servername.nickname (old format will be recognized, too)
#	  and other internal changes
53 54
# 0.9.1	: bar could not be hidden (detrate-)
#	: error message for old datafile (bazerka)
55
# 0.9   : servername without nicks will not be displayed in buddylist
56
#	  servername will be displayed in different color or will be hidden if not connected (option "color.server.offline")
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
#	  buddylist bar will be hidden if you are not connected to a server (option "hide.bar")
# 0.8   : - major changes - (buddylist file changed!!!)
#	  buddylist uses now server / nick structure
#         change entries in buddylist to : servername,nickname (e.g.: freenode,nils_2)
#	  or add your buddies again with the add function.
# 0.7   : nick change will be recognize
# 0.6   : nick wasn't set to offline, if buddy leave channel
# 0.5   : server information will be used now instead of nicklist
#	  reduction of cpu load (reported by ArcAngel and tigrmesh)
#	  bar will be removed if you unload the script. (requested by bazerka)
#	  help page will be displayed when you call buddylist without arguments
# 0.4   : added option "sort"
# 0.3   : remove spaces for indenting when bar position is top/bottom
#	  hook_config when settings changed.
# 0.2   : work-around for crash when searching nick in buffer without nicklist (function nicklist_search_nick) removed 
# 0.1   : initial release
73
#
74 75 76
# Development is currently hosted at
# https://github.com/weechatter/weechat-scripts
#
77 78 79
# TODO:
# /monitor function:
# :holmes.freenode.net 730 * :weechatter!~nils@mue-99-999-999-999.dsl.xxxxx.de
80

81 82
use strict;

83
my $prgname		= "buddylist";
84
my $version		= "1.8";
85
my $description		= "display status from your buddies a bar-item.";
86

87
# -------------------------------[ config ]-------------------------------------
88
my $default_buddylist	= "%h/buddylist.txt";
89 90
my %buddylist_level = (0 => "online", 1 => "away", 2 => "offline");
my %default_color_buddylist = ("online" => "yellow",
91 92
			       "away"    => "cyan",
			       "offline"    => "blue");
93

94
my %default_options = (	"position"		=>	"top",
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
                        "hide_bar"		=>	"on",		# hide buddylist bar when all servers are offline
                        "hide_server"		=>	"off",		# hide server if no buddy is online on this server
                        "hide_buddy"		=>	"off",		# hide buddy when offline
                        "buddy_on_server"	=>	"on",		# show connected buddy (on server and not channel)
                        "buddy_on_server_color"	=>	"lightgreen",	# color for buddy who is connected to server
                        "sort"			=>	"default",	# sort method
                        "color_default"		=>	"default",
                        "color_server_online"	=>	"white",
                        "color_server_offline"	=>	"hide",
                        "color_number"		=>	"lightred",
                        "show_query"		=>	"on",
                        "check_buddies"		=>	"20",		# delay (in seconds)
                        "callback_timeout"	=>	"60",		# delay (in seconds)
                        "use_redirection"	=>	"on",
                        "display_original_nick"	=>	"off",
                        "display_social_net"    =>      "on",
111
                        "display_social_net_color"=>    "yellow",
112 113 114 115
                        "text_online"           =>      "",
                        "text_away"             =>      "",
                        "text_offline"          =>      "",
                        "text_color"            =>      "white",
116
                        "hide_servername_in_buddylist"       =>      "off",
117

118
);
119 120 121 122 123
my %mouse_keys = ("\@item(buddylist):button1*"                                  => "hsignal:buddylist_mouse",
                  "\@item(buffer_nicklist)>item(buddylist):button1-gesture-*"   => "hsignal:buddylist_mouse",
                  "\@chat(*)>item(buddylist):button1-gesture-*"                 => "hsignal:buddylist_mouse",
                  "\@item(buddylist):button1-gesture-*"                         => "hsignal:buddylist_mouse");

124 125 126 127
my $debug_redir_out	= "off";

# ------------------------------[ internal ]-----------------------------------
my %Hooks		= ();					# space for my hooks
128
my %buddies		= ();					# to store the buddylist with status for each nick
129
my %nick_structure	= ();					# to store servername, nickname and status
130
my $default_version     = 0;                                    # minimum version (0.3.4)
131 132 133
my $bar_hidden          = "off";                                # status of bar
my $servertest          = 0;                                    # 0 = no server connected
my @buddylist_focus = ();
134

135
#$VAR1 = {
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
#       'freenode' =>   {
#                               'nils_2'        =>      'status'        =>      'online',
#                               'nil2_2'        =>      'buffer'        =>      '1,2,3',
#                               'nil2_2'        =>      'counter'       =>      0 or 1,
#                               'nil2_2'        =>      'buf_name'      =>      "#weechat #weechat-fr",
#                               'nil2_2'        =>      'bitlbee_service'=>       "msn",
#                               'nick_name'     =>      'status'        =>      'offline',
#                               'nick_name'     =>      'buffer'        =>      '',
#                               'nick_name'     =>      'counter'       =>      0 or 1,
#                               'nick_name'     =>      'buf_name'      =>      "#weechat #weechat-fr",
#                               'nick_name'     =>      'bitlbee_service'=>       "jabber",
#                               'nick_name2'    =>      'status'        =>      'online',
#                               'nick_name2'    =>      'buffer'        =>      '3,4',
#                               'nick_name2'    =>      'counter'       =>      0 or 1,
#                               'nick_name2'    =>      'buf_name'      =>      "#weechat #weechat-fr",
#                               'nick_name2'    =>      'bitlbee_service'=>      "facebook",
#                       },
#       'fu-berlin' =>  {
#                               'nils_2'        =>      'status'        =>      'away',
#                               'nils_2'        =>      'buffer'        =>      '4,5',
#                               'nil2_2'        =>      'counter'       =>      0 or 1,
#                               'nil2_2'        =>      'buf_name'      =>      "#amiga #motorrad",
#                               'nils_2'        =>      'bitlbee_service'=>      "",
#                       }
#       };
161

162
# -------------------------------[ main ]-------------------------------------
163 164
# first function called by a WeeChat-script.
weechat::register($prgname, "Nils Görs <weechatter\@arcor.de>", $version,
165
		"GPL3", $description, "shutdown", "");
166
my $weechat_version = "";
167 168 169
init();
buddylist_read();

170
weechat::bar_item_new($prgname, "build_buddylist", "");
171
weechat::bar_new($prgname, "1", "0", "root", "", "left", "horizontal",
172 173
                 "vertical", "0", "0", "default", "default", "default", "1",
                 $prgname);
174 175 176

weechat::hook_signal("buffer_*", "buddylist_signal_buffer", "");

177

178
weechat::hook_signal("*,irc_in2_352", "from_hook_who","");			# RFC command with use,channel,status etc..
179

180 181
weechat::hook_signal("*,irc_in_part", "remove_nick", "");
weechat::hook_signal("*,irc_in_quit", "remove_nick", "");
182 183
weechat::hook_signal("*,irc_in_join", "add_nick", "");

184
weechat::hook_signal("buffer_closing", "buffer_closing", "");
185 186 187
#weechat::hook_signal("buffer_moved", "buffer_moved", "");


188
weechat::hook_signal("*,irc_in_nick", "nick_changed", "");
189 190
weechat::hook_signal("irc_server_connected", "server_connected", "");
weechat::hook_signal("irc_server_disconnected", "server_disconnected", "");
191
weechat::hook_config("plugins.var.perl.$prgname.*", "toggled_by_set", "");	# buddylist options changed?
192 193 194 195 196 197 198 199 200 201
weechat::hook_completion("perl_buddylist", "buddylist completion", "buddy_list_completion_cb", "");

weechat::hook_signal("upgrade_ended", "buddylist_upgrade_ended", "");

if ($weechat_version >= 0x00030600){
  weechat::hook_focus($prgname, "hook_focus_buddylist", "");
  weechat::hook_hsignal("buddylist_mouse","buddylist_hsignal_mouse", "");
  weechat::key_bind("mouse", \%mouse_keys);
}

202 203

hook_timer_and_redirect() if ($default_options{check_buddies} ne "0" and $default_options{use_redirection} eq "on");
204 205

weechat::hook_command($prgname, $description,
206 207 208 209 210 211 212
                "<add>[nick_1 [... nick_n]] | <del>[nick_1 [... nick_n]]", 

                "<add> [nick(s)] add nick(s) to the buddylist\n".
                "<del> [nick(s)] delete nick(s) from the buddylist\n".
                "<list> show buddylist\n".
                "\n".
                "Options:\n".
213
                "'plugins.var.perl.buddylist.buddylist'            : path/file-name to store your buddies. \"%h\" will be replaced by WeeChat home (by default: ~/.weechat)\n".
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
                "\n".
                "'plugins.var.perl.buddylist.color.default         : fall back color. (default: standard weechat color)\n".
                "'plugins.var.perl.buddylist.color.online'         : color for " . weechat::color($default_color_buddylist{online}) . "online " . weechat::color("reset") . "buddies.\n".
                "'plugins.var.perl.buddylist.color.away'           : color for " . weechat::color($default_color_buddylist{away}) . "away " . weechat::color("reset") . "buddies.\n".
                "'plugins.var.perl.buddylist.color.offline'        : color for " . weechat::color($default_color_buddylist{offline}) . "offline " . weechat::color("reset") . "buddies.\n".
                "'plugins.var.perl.buddylist.color.server'         : color for " . weechat::color($default_options{color_server_online}) . "servername" . weechat::color("reset") . ".\n".
                "'plugins.var.perl.buddylist.color.server.offline' : color for disconnected server (default: hide).\n".
                "'plugins.var.perl.buddylist.color.number'         : color for channel number (default: " . weechat::color($default_options{color_number}) . "lightred" . weechat::color("reset") ."). If empty, channel list option is off.\n".
                "\n".
                "'plugins.var.perl.buddylist.show.query'           : displays a query buffer in front of the channel list.\n".
                "\n".
                "'plugins.var.perl.buddylist.hide.server.if.buddies.offline': hides server when all buddies are offline for this server (default: off).\n".
                "'plugins.var.perl.buddylist.hide.buddy.if.offline': hide buddy if offline (default: off).\n".
                "'plugins.var.perl.buddylist.buddy.on.server'      : show buddy who is connected to a server, but not visiting the same channel(s) (default: on).\n".
                "'plugins.var.perl.buddylist.buddy.on.server.color': color for online buddy but not visiting the same channel(s) (default: " . weechat::color($default_options{buddy_on_server_color}) . "lightgreen" . weechat::color("reset") .").\n".
                "'plugins.var.perl.buddylist.hide.bar'             : hides $prgname bar when all servers with added buddies are offline (default: on).\n".
                "                                          always  : $prgname bar will be hidden (for example if you want to add item 'buddylist' to 'weechat.bar.status.items'\n".
                "                                          off     : $prgname bar will not be hidden.\n".
                "\n".
                "'plugins.var.perl.buddylist.check.buddies'        : time in seconds to send a /whois request to server. Be careful not to flood server (default: 20).\n".
                "'plugins.var.perl.buddylist.callback.timeout'     : time in seconds to wait for answer from server. (default: 60).\n".
                "'plugins.var.perl.buddylist.display.original.nick': display original nickname even if buddy changed his /nick (you have to add new nick to buddylist) (default: off).\n".
                "\n".
                "'plugins.var.perl.buddylist.sort'                 : sort method for buddylist (default or status).\n".
                "                                          default : $prgname will be sort by nickname\n".
                "                                          status  : $prgname will be sort by status (online, away, offline)\n".
                "\n".
                "'plugins.var.perl.buddylist.display.social.net'   : using bitlbee, buddies will be sorted in sublists with social-network name (eg. msn/jabber/facebook)(default: on)\n".
                "'plugins.var.perl.buddylist.display.social.net.color': color for social-network name (default: yellow)\n".
                "\n".
                "'plugins.var.perl.buddylist.text.color'           : color for optional online/away/offline-text in buddylist (default: white)\n".
                "'plugins.var.perl.buddylist.text.online'          : optional online text in buddylist (sort method has to be 'status')\n".
                "'plugins.var.perl.buddylist.text.away'            : optional away text in buddylist (sort method has to be 'status')\n".
                "'plugins.var.perl.buddylist.text.offline'         : optional offline text in buddylist (sort method has to be 'status')\n".
                "\n".
                "'plugins.var.perl.buddylist.use.redirection'      : using redirection to get status of buddies (needs weechat >=0.3.4) (default: on).\n".
                "\n\n".
251 252 253 254 255 256 257 258 259 260 261
                "Mouse-support (standard key bindings):\n".
                "  click left mouse-button on buddy to open a query buffer.\n".
                "  add a buddy by dragging a nick with left mouse-button from nicklist or chat-area and drop on buddylist.\n".
                "  remove a buddy by dragging a buddy with left mouse-button from buddylist and drop it on any area.\n".
                "\n\n".
                "Troubleshooting:\n".
                "If buddylist will not be refreshed in nicklist-mode, check the following WeeChat options:\n".
                "'irc.server_default.away_check'          : interval between two checks, in minutes. (has to be >= 1 (default:0)).\n".
                "'irc.server_default.away_check_max_nicks': channels with high number of nicks will not be checked (default: 25).\n".
                "\n\n".
                "name of buddy has to be written 'case sensitive' (it's recommended to use nick-completion or to drag'n'drop buddy with mouse).\n".
262
                "\n\n".
263 264 265 266 267 268 269 270
                "Examples:\n".
                "  Add buddy (nils) to buddylist (server of current buffer will be used):\n".
                "    /$prgname add nils\n".
                "  Delete buddy (nils) from buddylist:\n".
                "    /$prgname del nils (server of current buffer will be used)\n",
                "add %(nick)|%*||".
                "del %(perl_buddylist)|%*||".
                "list %-", "settings_cb", "");
271
server_check();
272 273
return weechat::WEECHAT_RC_OK;

274

275 276 277 278
sub buddylist_upgrade_ended
{
    server_check();
    return weechat::WEECHAT_RC_OK;
279
}
280

281
# weechat connected to a server (irc_server_connected)
282 283 284 285 286
sub server_connected
{
    server_check();
    weechat::bar_item_update($prgname);
    return weechat::WEECHAT_RC_OK;
287 288
}

289
# weechat disconnected from server (irc_server_disconnected)
290 291 292 293 294 295 296
sub server_disconnected
{
    my $server = $_[2];
    set_nick_status_for_one_server("2",$server);                                                # all nicks off for server
    server_check();
    weechat::bar_item_update($prgname);
    return weechat::WEECHAT_RC_OK;
297 298
}

299

300 301 302
sub set_nick_status_for_one_server
{
    my ($status, $server) = @_;
303

304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
    foreach my $nickname (%{$nick_structure{$server}} )
    {
        if (exists $nick_structure{$server}{$nickname})                                         # set buddy to offline
        {
            $nick_structure{$server}{$nickname}{status} = $status;
            if ($status eq "2")
            {
                $nick_structure{$server}{$nickname}{buffer} = "";
                $nick_structure{$server}{$nickname}{buf_name} = "";
            }elsif($status eq "0")                                                              # set buddy online
            {
                $nick_structure{$server}{$nickname}{buffer} = "()";
            }
        }
    }
319 320
}

321 322 323 324 325
sub buffer_closing
{
    my ($signal, $callback, $callback_data) = @_;
    weechat::bar_item_update($prgname);
    return weechat::WEECHAT_RC_OK;
326 327 328 329 330 331 332 333
}
#    my $infolist_buf_closing = weechat::infolist_get("buffer",$callback_data,"");		# get pointer from closing buffer
#       weechat::infolist_next($infolist_buf_closing);
#       my $num_closing_buf = weechat::infolist_integer($infolist_buf_closing,"number");	# get number of closing buffer
#       my $server_name = weechat::infolist_string($infolist_buf_closing,"name");
#       my $buffer_name_short = weechat::infolist_string($infolist_buf_closing,"short_name");
#       weechat::infolist_free($infolist_buf_closing);
#       $server_name =~ s/\.$buffer_name_short//;
334 335 336 337 338 339 340 341 342 343 344 345 346

#	my $buffer_number = "";
#	my $str = "";
#	my $infolist_buffer = weechat::infolist_get("buffer","","*");
#	while ( weechat::infolist_next($infolist_buffer) ){
#	  if ( index (weechat::infolist_string($infolist_buffer,"name"), $server_name) ne "-1" and weechat::infolist_pointer($infolist_buffer,"pointer") ne $callback_data ){
#	      $buffer_number = weechat::infolist_string($infolist_buffer,"short_name");		# get short_name of buffer
#	      $str .= $buffer_number . " ";
#	  }
#	}
#	weechat::infolist_free($infolist_buffer);
#	$str =~ s/^\s+//g;									# delete last space

347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
#    foreach my $nickname ( sort keys %{$nick_structure{$server_name}} ) {			# sortiert die Nicks alphabetisch
#        my $status = $nick_structure{$server_name}{$nickname}{status};
#        next if ( not defined $status or $status eq "2" );
#        my $buf_name = $nick_structure{$server_name}{$nickname}{buf_name};
#        next if ( not defined $buf_name );

#        if ( index($buf_name,$buffer_name_short) ne "-1" or $buf_name ne "" or $buf_name ne "()" ){
#            $buf_name =~ s/$buffer_name_short//;
#            $buf_name =~ s/\s+$//g;								# delete last space
#            if ($buf_name eq ""){								# no more buffer
#                $nick_structure{$server_name}{$nickname}{buf_name} = "";
#                $nick_structure{$server_name}{$nickname}{buffer} = "";
#            }else{
#                $nick_structure{$server_name}{$nickname}{buf_name} = "";
#                $nick_structure{$server_name}{$nickname}{buffer} = "";
#                check_for_channels($server_name, $nickname, $buf_name);
#            }
#        }
#    }
#weechat::bar_item_update($prgname);
#return weechat::WEECHAT_RC_OK;

369

370 371 372 373 374 375 376
sub buffer_moved
{
    my ($signal, $callback, $callback_data) = @_;
    weechat::print("","signal: " . $signal);
    weechat::print("","callback: " . $callback);
    weechat::print("","callback_data: " . $callback_data);
    return weechat::WEECHAT_RC_OK;
377 378
}

379
# build buddylist in bar
380
my $str = "";
381
my $number;
382 383
my $bitlbee_service_separator = "";
my $bitlbee_service_separator_copy = "";
384
sub build_buddylist{
385
        $str = "";
386 387
        $number = 0;
        @buddylist_focus = ();
388

389 390 391 392 393
# crashes weechat...
#        if ( $default_options{hide_bar} eq "on" or $default_options{hide_bar} eq "always" ){    # hide buddylist bar?
#          my $servertest = server_check();                                                      # check for server
#          return $str if ( $servertest == 0 );                                                  # no server with buddies online!
#        }
394

395 396 397
        my $visual = " ";                                                       # placeholder after servername
        my $cr = "\n";
        $visual  = $cr if (($default_options{position} eq "left") || ($default_options{position} eq "right"));
398

399 400 401
# get bar position (left/right/top/bottom) and sort (default/status)
	my $option = weechat::config_get("weechat.bar.$prgname.position");
	if ($option ne ""){
402
		$default_options{position} = weechat::config_string($option);
403
	}
404

405
	if ($default_options{sort} eq "status"){						# use sort option "status"
406
		foreach my $s ( sort keys %nick_structure ) {
407 408
                  $bitlbee_service_separator = "";
                  $bitlbee_service_separator_copy = "";
409 410
			if (keys (%{$nick_structure{$s}}) eq "0"){				# check out if nicks exists for server in nick_structure
				next;								# no nick for server. jump to next server
411
			}
412

413 414
                  # sort list by status (online => away => offline) for internal use.
                  my ($n) = ( sort { $nick_structure{$s}{$a}->{status} <=> $nick_structure{$s}{$b}->{status}} keys %{$nick_structure{$s}} );
415
                  $nick_structure{$s}{$n}{bitlbee_service} = "" if ( not defined $nick_structure{$s}{$n}{bitlbee_service} );
416
                  if ($nick_structure{$s}{$n}{status} eq "2" and $default_options{hide_server} eq "on"){	# status from first buddy in list!
417 418 419
		      next;									# first sorted buddy is offline (2)
		  }

420
			my $color_server = get_server_status($s);				# get server color
421
			if ($color_server eq "1"){
422
			  next;									# hide server if result = 1
423
			}
424 425 426
                        if ($default_options{hide_servername_in_buddylist} ne "on"){
                            $str .= weechat::color($color_server) . $s . ":" . $visual;		# add servername ($s ;) to buddylist
                        }
427
                        add_buddy_focus("","","");                                              # create focus for servername
428

429 430
# sorted by status first, then bitlbee_service and nick case insensitiv at least
#                              foreach my $n (sort { $nick_structure{$s}{$a}->{status} cmp $nick_structure{$s}{$b}->{status}} (sort {uc($a) cmp uc($b)} (sort keys(%{$nick_structure{$s}})))){
431
                              
432 433 434 435 436 437 438
                              my $status_output = "";
                              my $status_output_copy = "";
                              foreach my $n (sort { $nick_structure{$s}{$a}->{status} cmp $nick_structure{$s}{$b}->{status}} (sort { $nick_structure{$s}{$a}->{bitlbee_service} cmp $nick_structure{$s}{$b}->{bitlbee_service}} (sort {uc($a) cmp uc($b)} (sort keys(%{$nick_structure{$s}})) ) ) ){
                                # write status to nicklist (optional!!)
                                $status_output = $nick_structure{$s}{$n}{status};
                                if ( $nick_structure{$s}{$n}{status} == 0 and $status_output ne $status_output_copy and $default_options{text_online} ne ""){
                                  $str .= weechat::color($default_options{text_color}) . $default_options{text_online} . weechat::color("reset") .$visual;
439
                                  add_buddy_focus("","","");
440 441
                                }elsif ( $nick_structure{$s}{$n}{status} == 1 and $status_output ne $status_output_copy and $default_options{text_away} ne ""){
                                  $str .= weechat::color($default_options{text_color}) . $default_options{text_away} . weechat::color("reset") .$visual;
442
                                  add_buddy_focus("","","");
443 444
                                }elsif ( $nick_structure{$s}{$n}{status} == 2 and $status_output ne $status_output_copy and $default_options{text_offline} ne "" and $default_options{hide_buddy} eq "off"){
                                  $str .= weechat::color($default_options{text_color}) . $default_options{text_offline} . weechat::color("reset") .$visual;
445
                                  add_buddy_focus("","","");
446 447 448 449
                                }
                                  $status_output_copy = $status_output;

                                # write each bitlbee_service only once
450
                                $nick_structure{$s}{$n}{bitlbee_service} = "" if ( not defined $nick_structure{$s}{$n}{bitlbee_service} );
451
                                $bitlbee_service_separator = $nick_structure{$s}{$n}{bitlbee_service};
452 453 454 455
                                if ( $bitlbee_service_separator ne "" and $bitlbee_service_separator_copy ne $bitlbee_service_separator ){
                                  $str .= weechat::color($default_options{display_social_net_color}) . "(" . $bitlbee_service_separator . ") " . $visual;
                                  add_buddy_focus("","","");
                                }
456 457 458 459
                                createoutput($s,$n);
                                $bitlbee_service_separator_copy = $bitlbee_service_separator;
                              }
                }
460

461 462
	} elsif ($default_options{sort} ne "status") {						# use sort option "default"
		foreach my $s ( sort keys %nick_structure ) {					# sort server alphabetically
463 464
                  $bitlbee_service_separator = "";
                  $bitlbee_service_separator_copy = "";
465 466
			if (keys (%{$nick_structure{$s}}) eq "0"){				# check out if nicks exists for server
				next;								# no nick for server. jump to next server
467 468
			}
		# sort list by status (from online, away, offline)
469 470 471
		my ($n) = ( sort { $nick_structure{$s}{$a}->{status} <=> $nick_structure{$s}{$b}->{status}} keys %{$nick_structure{$s}} );
		if ($nick_structure{$s}{$n}{status} eq "2" and $default_options{hide_server} eq "on"){	# status from first buddy in list!
		  next;										# first sorted buddy is offline (2)
472
		}
473
			my $visual = " ";							# placeholder after servername
474
				my $cr = "\n";
475
			$visual  = $cr if (($default_options{position} eq "left") || ($default_options{position} eq "right"));
476

477
			my $color_server = get_server_status($s);                               # get server color
478
			if ($color_server eq "1"){
479
			  next;                                                                 # hide server if result = 1
480
			}
481 482 483
                        if ($default_options{hide_servername_in_buddylist} ne "on"){
                            $str .= weechat::color($color_server) . $s . ":" . $visual;         # add servername ($s ;) to buddylist
                        }
484

485 486
                        add_buddy_focus("","","");                                              # create focus for servername

487 488 489 490
#                                foreach my $n (sort {uc($a) cmp uc($b)} (sort keys(%{$nick_structure{$s}} ))){ # sort by name case insensitiv
                                # first sort by bitlbee_service and then name case insensitiv
                                foreach my $n (sort { $nick_structure{$s}{$b}->{bitlbee_service} cmp $nick_structure{$s}{$a}->{bitlbee_service}} (sort {uc($a) cmp uc($b)} (sort keys(%{$nick_structure{$s}})) ) ){
                                  # write each bitlbee_service only once
491
                                  $nick_structure{$s}{$n}{bitlbee_service} = "" if ( not defined $nick_structure{$s}{$n}{bitlbee_service} );
492
                                  $bitlbee_service_separator = $nick_structure{$s}{$n}{bitlbee_service};
493 494 495 496
                                  if ( $bitlbee_service_separator ne "" and $bitlbee_service_separator_copy ne $bitlbee_service_separator ){
                                    $str .= weechat::color($default_options{display_social_net_color}) . "(" . $bitlbee_service_separator . ") " . $visual;
                                    add_buddy_focus("","","");
                                  }
497 498 499 500 501
                                  createoutput($s,$n);
                                  $bitlbee_service_separator_copy = $bitlbee_service_separator;
                                }
                }
        }
502
        if ($str eq ""){
503 504
	    my $network_away_check = weechat::config_integer(weechat::config_get("irc.server_default.away_check"));
	    if ($network_away_check == 0 and $default_options{use_redirection} ne "on"){
505
		$str = "value from option \"irc.server_default.away_check\" is 0.".$visual."It has to be >= 1 or you have to use option".$visual."\"plugins.var.perl.buddylist.use.redirection = on\".";
506
	    }else{
507
                return $str = "Not connected to a server..." if ( $servertest == 0 );
508 509
		return $str = "Searching for buddies,".$visual."please wait..." if ($network_away_check == 0);
		$str = "Please wait, building buddylist".$visual."(this could take $network_away_check minutes)...".$visual."probably there are no buddies in your".$visual."buddylist for connected server,".$visual."or you are not connected to a server".$visual."or your buddies are all offline";
510
	    }
511 512 513
	}
	return $str;
}
514 515

# get status from server and color the servername (or hide it)
516 517 518 519 520 521 522
sub get_server_status{
my $server = $_[0];
	my $infolist_server = weechat::infolist_get("irc_server","",$server);			# get pointer for server %s
	weechat::infolist_next($infolist_server);
	my $is_connected = weechat::infolist_integer($infolist_server,"is_connected");		# get status of connection for server (1 = connected | 0 = disconnected)
	weechat::infolist_free($infolist_server);						# don't forget to free infolist ;-)
		if ($is_connected == 0){							# 0 = not connected
523
				if ($default_options{color_server_offline} eq "hide"){		# hide offline server?
524 525
					return 1;						# yes!
				}
526
		$default_options{color_server_offline} = $default_options{color_default} if ($default_options{color_server_offline} eq "");
527
		return $default_options{color_server_offline};					# color for server offline
528
		}
529 530
$default_options{color_server_online} = $default_options{color_default} if ($default_options{color_server_online} eq "");# fall back color if color_server = ""
return $default_options{color_server_online};							# color for server online
531
}
532

533
# for mouse support, create a focus list
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555
sub add_buddy_focus{
my ($server,$nick, $status) = ($_[0],$_[1],$_[2]);
          my $buddy_struct;
          my %buddy_struct;
          my $key;

          $key = sprintf("%08d", $number);

          if ($nick ne "" and $server ne ""){                                                   # a legal buddy with server
            $buddy_struct->{"status"} = $status;
            $buddy_struct->{"nick"} = $nick;
            $buddy_struct->{"server"} = $server;
            $buddy_struct{$key} = $buddy_struct;
            push(@buddylist_focus, $buddy_struct{$key});
          }else{                                                                                # create a dummy
           undef $buddy_struct;
           $buddy_struct{$key} = $buddy_struct;
           push(@buddylist_focus, $buddy_struct{$key});
          }
          $number++;
}

556
sub createoutput{
557
my ($server,$nick) = ($_[0],$_[1]);
558 559 560 561 562 563 564 565
my $status = $nick_structure{$server}{$nick}{status};                                           # get buddy status
$status = 2 if (not defined $status);                                                           # buddy is offline
my $bitlbee_service = $nick_structure{$server}{$nick}{bitlbee_service};                         # get bitlbee_service name or "" if none

my $buffer_number = $nick_structure{$server}{$nick}{buffer};                                    # get buffers, buddy is currently in
$buffer_number = "" if (not defined $buffer_number);                                            # does variable is defined?

        if ($status eq "2" and $default_options{hide_buddy} eq "on"){                           # buddy is offline
566 567
                                                                                                # do not create focus, if buddy is not displayed in item!
#          add_buddy_focus($server,$nick,$status);                                               # create focus
568 569
          $str .= "";
        }else{                                                                                  # get color for away/online
570 571 572

          add_buddy_focus($server,$nick,$status);                                               # create focus

573 574 575 576 577 578 579 580 581 582 583
          my $cr = "\n";
          my $color = $default_options{color_default};
          $color = "default" if ($color eq "" or not defined $color);
          $color = $default_color_buddylist{$buddylist_level{$status}};

          ### visual settings for left/right or top/bottom
          my $visual = " ";                                                                     # placeholder
          my $move_r = "";                                                                      # move it to right
            if (($default_options{position} eq "left") || ($default_options{position} eq "right")){
              $visual  = $cr;
              $move_r  = "  ";
584
              $move_r  = "" if ($default_options{hide_servername_in_buddylist} eq "on")
585
            }
586

587 588 589 590 591 592 593 594 595 596 597 598 599 600
          return $str .= weechat::color($color) . $move_r . "$nick" . $visual if ($buffer_number eq "" or $default_options{color_number} eq "");

          # print nick with channel number ( "()" = online without channel, "" = offline )
          return $str .= weechat::color($color) . $move_r . "$nick" .
                          weechat::color("reset") . "(" .
                          weechat::color($default_options{color_number}).
                          $buffer_number .
                          weechat::color("reset") . ")" . $visual if ($buffer_number ne "()");

          if ($default_options{buddy_on_server} eq "on" and $buffer_number eq "()" or $buffer_number eq ""){# option "buddy_on_server" = on ?
            return $str .= weechat::color($default_options{buddy_on_server_color}) . $move_r . "$nick" . weechat::color("reset") . $visual if ($status eq 0);# buddy online?
            return $str .= weechat::color($color) . $move_r . "$nick" . weechat::color("reset") . $visual if ($status eq 1); # buddy away?
          }
        }
601
}
602

603
# buddy changed his nick (irc_in_nick)
604
sub nick_changed{
605
	my ($blank, $servername, $args) = @_;
606 607 608 609 610

	return weechat::WEECHAT_RC_OK if ( $default_options{use_redirection} eq "on" );		# do not rename nick in redirection_mode!!!


	my ($server) = split(/,/, $servername);							# get name from server
611
		$args =~ /\:(.*)\!(.*)\:(.*)/;
612 613
	my $old_nickname = $1;
	my $new_nickname = $3;
614

615 616 617
	if (defined $nick_structure{$server}{$old_nickname} and exists $nick_structure{$server}{$old_nickname}){
		my $status = $nick_structure{$server}{$old_nickname}{status};		# get old buddy status
			$nick_structure{$server}{$new_nickname}{status} = $status;	# add /nick buddy with old status
618
			delete $nick_structure{$server}{$old_nickname};                 # delete old buddyname
619

620
			weechat::bar_item_update($prgname);
621 622
	}
}
623 624

sub add_nick{
625 626 627 628 629 630 631 632 633
    my ( $data, $servername, $args ) = @_;
    my ($server) = split(/,/, $servername);                                 # get name from server
        my ($nickname) = ($args =~ /\:(.*)\!/);

    if (defined $nick_structure{$server}{$nickname} and exists $nick_structure{$server}{$nickname}){                        # nick in buddylist?
        $nick_structure{$server}{$nickname}{status} = 0;                    # create structure
        $nick_structure{$server}{$nickname}{bitlbee_service} = "";
        weechat::bar_item_update($prgname);
    }
634 635
}

636
# buddy leaves channel (irc_in_part / irc_in_quit)
637
sub remove_nick{
638
#($nick,$name,$ip,$action,$channel) = ($args =~ /\:(.*)\!n=(.*)@(.*?)\s(.*)\s(.*)/); # maybe for future use
639 640 641 642 643 644 645 646 647 648 649 650 651
    my ( $data, $servername, $args ) = @_;
    my ($server) = split(/,/, $servername);                                 # get name from server
            my ($nickname) = ($args =~ /\:(.*)\!/);


    if (defined $nick_structure{$server}{$nickname} and exists $nick_structure{$server}{$nickname}){                        # nick in buddylist?
        $nick_structure{$server}{$nickname}{status} = 2;                # yes and he left channel
        $nick_structure{$server}{$nickname}{buf_name} = "";
        $nick_structure{$server}{$nickname}{buffer} = "";
        $nick_structure{$server}{$nickname}{counter} = "";
        $nick_structure{$server}{$nickname}{bitlbee_service} = "";
        weechat::bar_item_update($prgname);
    }
652
}
653

654
# get information from who command (irc_in2_352)
655 656 657
#:anthony.freenode.net 352 nils_2 #channelname debian-tor gateway/tor-sasl/nils2/x-72512466 anthony.freenode.net nils_2 H :0 nils
#1                     2   3      4            5                                            6                    7      8 9  10
#
658
sub from_hook_who{
659
    my ( $data, $servername, $args ) = @_;
660

661 662 663
    my @words = split(" ",$args);                               # [7] = nick
    ($servername) = split(/,/, $servername);                    # get name from server
    my $nickname = $words[7];
664

665 666 667 668 669 670 671 672
    return if (not defined $nickname);

    if (exists $nick_structure{$servername}{$nickname}){        # nick in buddylist?
        my $status = 0;                                         # 0 = offline
        $status = 1 if (substr($words[8],0,1) eq "G");          # buddy is away (1)
        add_to_nicktable($servername, $nickname, $status);
        weechat::bar_item_update($prgname);
    }
673
}
674

675 676
# add buddy to my structure
sub add_to_nicktable{
677
	my ($servername, $nickname, $status) = @_;
678
	$nick_structure{$servername}{$nickname}{status} = $status;		# create structure
679
}
680

681
# user commands
682 683
sub settings_cb{
    my ($data, $ptr_buffer, $getargs) = ($_[0], $_[1], $_[2]);
684

685 686 687 688 689
    if ($getargs eq "")
    {
        weechat::command("", "/help $prgname");                                 # no arguments given. print help
        return weechat::WEECHAT_RC_OK;
    }
690

691 692 693 694 695
    my $localvar_name = weechat::buffer_get_string($ptr_buffer, "localvar_name");
    my $localvar_servername = weechat::buffer_get_string($ptr_buffer, "localvar_server");
    my $localvar_channelname = weechat::buffer_get_string($ptr_buffer, "localvar_channel");
    my $localvar_type = weechat::buffer_get_string($ptr_buffer, "localvar_type");
#    my $localvar_plugin = weechat::buffer_get_string($ptr_buffer, "localvar_plugin");
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
    my ( $cmd, $args ) = ( $getargs =~ /(.*?)\s+(.*)/ );                        # get parameters and cut cmd from nicks
    $cmd = $getargs unless $cmd;

    if ($cmd eq "list")                                                        # print buddylist (with status) in core buffer
    {
        weechat::print("",weechat::color("white")."Buddylist:\n" . weechat::color("green"). "Servername" . weechat::color("reset") . "." . weechat::color("lightgreen") . "Nickname" . weechat::color("lightred") . " (status)" . weechat::color("reset") . " ==> Channelname:");
        foreach my $s ( sort keys %nick_structure )                             # sort server (a-z)
        {
            foreach my $n ( sort keys %{$nick_structure{$s}} )                  # sort nicks (a-z)
            {
                my $show_buffer = "";
                my $show_bitlbee_service = "";
                $show_buffer = "  ==> " . $nick_structure{$s}{$n}{buf_name} if (defined $nick_structure{$s}{$n}{buf_name} and $nick_structure{$s}{$n}{buf_name} ne "");
                $show_bitlbee_service = " (" . $nick_structure{$s}{$n}{bitlbee_service} .")" if (defined $nick_structure{$s}{$n}{bitlbee_service} and $nick_structure{$s}{$n}{bitlbee_service} ne "");
                weechat::print( ""," "
                . weechat::color("green")
                . $s . weechat::color("reset")
                . "."
                . weechat::color("lightgreen")
                . $n
                . weechat::color("reset")
                . $show_bitlbee_service
                # status
                . weechat::color("lightred")
                . " (" . weechat::color($default_color_buddylist{$buddylist_level{$nick_structure{$s}{$n}{status}}})
                . $buddylist_level{$nick_structure{$s}{$n}{status}}
                . weechat::color("lightred") . ")"
                . weechat::color("reset")
                . $show_buffer);
            }
727
        }
728 729
        return weechat::WEECHAT_RC_OK;
    }
730

731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748
    if ( $localvar_type ne "channel" and $localvar_type ne "private" and $localvar_type ne "server" )
    {
        weechat::print("",weechat::prefix("error")."$prgname: You can add/del buddies only in channel/server/private buffers.");
        return weechat::WEECHAT_RC_OK;
    }
    if (defined $args)
    {
        foreach ( split( / +/, $args ) )                                              # more than one nick?
        {
            if ($cmd eq "add")
            {
                $nick_structure{$localvar_servername}{$_}{status} = 2;
                $nick_structure{$localvar_servername}{$_}{bitlbee_service} = "";
                buddylist_save();
            }
            if ($cmd eq "del" and exists $nick_structure{$localvar_servername}{$_})
            {
                delete $nick_structure{$localvar_servername}{$_};
749
# delete servername from structure, if last nick from server was deleted
750 751 752 753 754 755 756 757 758 759 760
                delete $nick_structure{$localvar_servername} if (keys (%{$nick_structure{$localvar_servername}}) == 0);
                buddylist_save();
            }
        }
    }
    else
    {
        weechat::command("", "/help $prgname");                                         # no arguments given. Print help
    }
    weechat::bar_item_update($prgname);
    return weechat::WEECHAT_RC_OK;
761
}
762

763 764
# check server status for option hide_bar (to hide or show bar)
# TODO infolist fails using /upgrade
765
sub server_check{
766
  $servertest = 0;
767
# check if at least one server is online
768

769
	foreach my $s ( sort keys %nick_structure ) {						# sort server alphabetically
770
                my $infolist_server = weechat::infolist_get("irc_server","",$s);                # get pointer for server %s
771
		weechat::infolist_next($infolist_server);
772
		my $is_connected = weechat::infolist_integer($infolist_server,"is_connected");	# get status of connection for server (1 = connected | 0 = disconnected)
773
                weechat::infolist_free($infolist_server);                                       # don't forget to free infolist ;-)
774
			if ($is_connected == 1){
775
			  $servertest = 1;                                                      # one server is at least online!
776
			  last;
777 778
			}
	}
779 780
	if ( $servertest == 0 and $default_options{hide_bar} ne "off" ){                         # no server with buddies
          weechat::command("", "/bar hide " . $prgname);
781
          $bar_hidden = "on";
782 783 784 785 786 787 788
        }elsif ( $default_options{hide_bar} eq "off" ){
          weechat::command("", "/bar show " . $prgname);
          $bar_hidden = "off";
        }elsif ( $servertest == 1 and $default_options{hide_bar} eq "always" ){
          weechat::command("", "/bar hide " . $prgname);
          $bar_hidden = "on";
        }elsif ($servertest == 1 and $default_options{hide_bar} eq "on" ){
789 790 791 792
          weechat::command("", "/bar show " . $prgname);
          $bar_hidden = "off";
        }
return $servertest;
793 794 795 796 797
}

# /query -server <internal servername> <nick>
sub buddy_completer{
return weechat::WEECHAT_RC_OK;
798 799
}

800
### read the buddylist
801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821
sub buddylist_read
{
    my $buddylist = weechat_dir();
    if ($buddylist eq "")
    {
        weechat::print("","Please set a valid filename : /set plugins.var.perl.".$prgname.".buddylist");
        return;
    }
    return unless -e $buddylist;
    open (WL, "<", $buddylist) || DEBUG("$buddylist: $!");
    while (<WL>)
    {
        chomp;                                                              # kill LF
        # search for last "." or "," in buddylist.txt
        # server.nick or irc.temporary.server.nick
        my $cut_here = rindex($_,".");
        $cut_here = rindex($_,",") if ($cut_here == -1);
        if ($cut_here == -1)
        {
            close WL;
            weechat::print("",weechat::prefix("error")."$prgname: $buddylist is not valid or uses old format (new format: servername.nickname).");
822 823
            return;
        }
824 825 826 827 828 829 830 831 832 833 834 835
        my $servername = substr( $_, 0, $cut_here);
        my $nickname = substr( $_,$cut_here + 1);
        if (not defined $nickname)
        {
            close WL;
            weechat::print("",weechat::prefix("error")."$prgname: $buddylist is not valid or uses old format (new format: servername.nickname).");
            return;
        }
        $nick_structure{$servername}{$nickname}{status} = 2  if length $_;	# status offline
        $nick_structure{$servername}{$nickname}{bitlbee_service} = "";
    }
    close WL;
836 837
}
sub buddylist_save {
838
	my $buddylist = weechat_dir();
839 840 841 842 843
        if ($buddylist eq "")
        {
            weechat::print("","Please set a valid filename : /set plugins.var.perl.buddylist.buddylist");
            return;
        }
844
	open (WL, ">", $buddylist) || DEBUG("write buddylist: $!");
845 846 847 848 849
	foreach my $s ( sort keys %nick_structure ) {				# sortiert die Server alphabetisch
		foreach my $n ( sort keys %{$nick_structure{$s}} ) {		# sortiert die Nicks alphabetisch
			print WL "$s.$n\n";					# save as servername.nickname
		}
	}
850
	close WL;
851
}
852

853
# changes in settings hooked by hook_config()?
854 855 856 857
sub toggled_by_set{
	my ( $pointer, $option, $value ) = @_;

	if ($option eq "plugins.var.perl.$prgname.hide.server.if.buddies.offline"){
858
		$default_options{hide_server} = $value;
859
	}elsif ($option eq "plugins.var.perl.$prgname.hide.buddy.if.offline"){
860
		$default_options{hide_buddy} = $value;
861
	}elsif ($option eq "plugins.var.perl.$prgname.sort"){
862
		$default_options{sort} = $value;
863
	}elsif ($option eq "plugins.var.perl.$prgname.hide.bar"){
864
		$default_options{hide_bar} = $value;
865
	}elsif ($option eq "plugins.var.perl.$prgname.color.default"){
866
		$default_options{color_default} = $value;
867
	}elsif ($option eq "plugins.var.perl.$prgname.color.server"){
868
		$default_options{color_server_online} = $value;
869
	}elsif ($option eq "plugins.var.perl.$prgname.color.server.offline"){
870
		$default_options{color_server_offline} = $value;
871 872 873 874 875 876
	}elsif ($option eq "plugins.var.perl.$prgname.color.away"){
		$default_color_buddylist{"away"} = $value;
	}elsif ($option eq "plugins.var.perl.$prgname.color.offline"){
		$default_color_buddylist{"offline"} = $value;
	}elsif ($option eq "plugins.var.perl.$prgname.color.online"){
		$default_color_buddylist{"online"} = $value;
877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892
	}elsif ($option eq "plugins.var.perl.$prgname.color.number"){
		$default_options{"color_number"} = $value;
	}elsif ($option eq "plugins.var.perl.$prgname.show.query"){
		$default_options{"show_query"} = $value;
	}elsif ($option eq "plugins.var.perl.$prgname.buddy.on.server"){
		$default_options{"buddy_on_server"} = $value;
	}elsif ($option eq "plugins.var.perl.$prgname.buddy.on.server.color"){
		$default_options{"buddy_on_server_color"} = $value;
	}elsif ($option eq "plugins.var.perl.$prgname.check.buddies"){
		$default_options{"check_buddies"} = $value;
	}elsif ($option eq "plugins.var.perl.$prgname.callback.timeout"){
		$default_options{"callback_timeout"} = $value;
	}elsif ($option eq "plugins.var.perl.$prgname.use.redirection"){
		$default_options{"use_redirection"} = $value;
	}elsif ($option eq "plugins.var.perl.$prgname.display.original.nick"){
		$default_options{"display_original_nick"} = $value;
893 894 895 896 897
	}elsif ($option eq "plugins.var.perl.$prgname.display.social.net"){
                $default_options{"display_social_net"} = $value;
        }elsif ($option eq "plugins.var.perl.$prgname.display.social.net.color"){
                $default_options{"display_social_net_color"} = $value;
        }elsif ($option eq "plugins.var.perl.$prgname.debug.redir.out"){
898
		$debug_redir_out = $value;
899 900 901 902 903 904 905 906
	}elsif ($option eq "plugins.var.perl.$prgname.text.online"){
                $default_options{text_online} = $value;
        }elsif ($option eq "plugins.var.perl.$prgname.text.away"){
                $default_options{text_away} = $value;
        }elsif ($option eq "plugins.var.perl.$prgname.text.offline"){
                $default_options{text_offline} = $value;
        }elsif ($option eq "plugins.var.perl.$prgname.text.color"){
                $default_options{text_color} = $value;
907 908
        }elsif ($option eq "plugins.var.perl.$prgname.hide.servername.in.buddylist"){
                $default_options{hide_servername_in_buddylist} = $value;
909 910
        }

911 912
  server_check();

913
weechat::bar_item_update($prgname);
914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932

# check Hooks()
	if ($default_options{check_buddies} ne "0" and $default_options{use_redirection} eq "on"){
		if (defined $Hooks{timer} and defined $Hooks{redirect}){
			unhook_timer();
			hook_timer_and_redirect();
			return weechat::WEECHAT_RC_OK;
		}
	}

	if ($default_options{check_buddies} eq "0" or $default_options{use_redirection} ne "on"){
		if (defined $Hooks{timer} and defined $Hooks{redirect}){
			unhook_timer();
		}
	}else{
		if (not defined $Hooks{timer} or not defined $Hooks{redirect}){
			weechat::config_set_plugin("check.buddies", "0") unless hook_timer_and_redirect();	# fall back to '0', if hook fails
		}
	}
933

934
weechat::bar_item_update($prgname);
935
return weechat::WEECHAT_RC_OK;
936
}
937

938 939 940 941
sub buddylist_signal_buffer
{
    weechat::bar_item_update($prgname);
    return weechat::WEECHAT_RC_OK;
942 943
}

944 945 946 947 948 949 950 951 952 953 954
sub weechat_dir
{
    my $dir = weechat::config_get_plugin("buddylist");
    if ( $dir =~ /%h/ )
    {
        my $weechat_dir = weechat::info_get( 'weechat_dir', '');
        $dir =~ s/%h/$weechat_dir/;
    }
    return $dir;
}

955 956
# init the settings
sub init{
957 958 959 960 961 962
    $weechat_version = weechat::info_get("version_number", "");
    $default_version = 0;
    if (($weechat_version ne "") && ($weechat_version >= 0x00030400))   # v0.3.4
    {
        $default_version = 1;
    }
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
    # a filename is defined in option?
    weechat::config_set_plugin("buddylist", $default_buddylist ) if ( weechat::config_get_plugin("buddylist") eq "" );

    if (!weechat::config_is_set_plugin("color.default"))
    {
        weechat::config_set_plugin("color.default", $default_options{color_default});
    }else
    {
        $default_options{color_default} = weechat::config_get_plugin("color.default");
    }
    if (!weechat::config_is_set_plugin("color.server"))
    {
        weechat::config_set_plugin("color.server", $default_options{color_server_online});
    }else
    {
        $default_options{color_server_online} = weechat::config_get_plugin("color.server");
    }
    if (!weechat::config_is_set_plugin("color.server.offline"))
    {
        weechat::config_set_plugin("color.server.offline", $default_options{color_server_offline});
    }else
    {
        $default_options{color_server_offline} = weechat::config_get_plugin("color.server.offline");
    }
    if (!weechat::config_is_set_plugin("buddy.on.server.color"))
    {
        weechat::config_set_plugin("buddy.on.server.color", $default_options{buddy_on_server_color});
    }else
    {
        $default_options{buddy_on_server_color} = weechat::config_get_plugin("buddy.on.server.color");
    }
    if (!weechat::config_is_set_plugin("color.number"))
    {
        weechat::config_set_plugin("color.number", $default_options{color_number});
    }else
    {
        $default_options{color_number} = weechat::config_get_plugin("color.number");
    }
    if (!weechat::config_is_set_plugin("show.query"))
    {
        weechat::config_set_plugin("show.query", $default_options{show_query});
    }else
    {
        $default_options{show_query} = weechat::config_get_plugin("show.query");
    }
    if (!weechat::config_is_set_plugin("hide.bar"))
    {
        weechat::config_set_plugin("hide.bar", $default_options{hide_bar});
    }else
    {
        $default_options{hide_bar} = weechat::config_get_plugin("hide.bar");
    }
    if (!weechat::config_is_set_plugin("sort"))
    {
        weechat::config_set_plugin("sort", $default_options{sort});
    }else
    {
        $default_options{sort} = weechat::config_get_plugin("sort");
    }
    if (!weechat::config_is_set_plugin("hide.server.if.buddies.offline"))
    {
        weechat::config_set_plugin("hide.server.if.buddies.offline", $default_options{hide_server});
    }else
    {
        $default_options{hide_server} = weechat::config_get_plugin("hide.server.if.buddies.offline");
    }
    if (!weechat::config_is_set_plugin("hide.buddy.if.offline"))
    {
        weechat::config_set_plugin("hide.buddy.if.offline", $default_options{hide_buddy});
    }else
    {
        $default_options{hide_buddy} = weechat::config_get_plugin("hide.buddy.if.offline");
    }
    if (!weechat::config_is_set_plugin("buddy.on.server")){
        weechat::config_set_plugin("buddy.on.server", $default_options{buddy_on_server});
    }else{
        $default_options{buddy_on_server} = weechat::config_get_plugin("buddy.on.server");
    }
    if (!weechat::config_is_set_plugin("check.buddies")){
        weechat::config_set_plugin("check.buddies", $default_options{check_buddies});
    }else{
        $default_options{check_buddies} = weechat::config_get_plugin("check.buddies");
    }
    if (!weechat::config_is_set_plugin("callback.timeout")){
        weechat::config_set_plugin("callback.timeout", $default_options{callback_timeout});
    }else{
        $default_options{callback_timeout} = weechat::config_get_plugin("callback.timeout");
    }
    if (!weechat::config_is_set_plugin("use.redirection")){
        weechat::config_set_plugin("use.redirection", $default_options{use_redirection});
    }else{
        $default_options{use_redirection} = weechat::config_get_plugin("use.redirection");
    }
    if (!weechat::config_is_set_plugin("display.original.nick")){
        weechat::config_set_plugin("display.original.nick", $default_options{display_original_nick});
    }else{
        $default_options{display_original_nick} = weechat::config_get_plugin("display.original.nick");
    }
    if (!weechat::config_is_set_plugin("display.social.net")){
        weechat::config_set_plugin("display.social.net", $default_options{display_social_net});
    }else{
        $default_options{display_social_net} = weechat::config_get_plugin("display.social.net");
    }
    if (!weechat::config_is_set_plugin("display.social.net.color")){
        weechat::config_set_plugin("display.social.net.color", $default_options{display_social_net_color});
    }else{
        $default_options{display_social_net_color} = weechat::config_get_plugin("display.social.net.color");
    }
    if (!weechat::config_is_set_plugin("text.online")){
        weechat::config_set_plugin("text.online", $default_options{text_online});
    }else{
        $default_options{text_online} = weechat::config_get_plugin("text.online");
    }
    if (!weechat::config_is_set_plugin("text.away")){
        weechat::config_set_plugin("text.away", $default_options{text_away});
    }else{
        $default_options{text_away} = weechat::config_get_plugin("text.away");
    }
    if (!weechat::config_is_set_plugin("text.offline")){
        weechat::config_set_plugin("text.offline", $default_options{text_offline});
    }else{
        $default_options{text_offline} = weechat::config_get_plugin("text.offline");
    }
    if (!weechat::config_is_set_plugin("text.color")){
        weechat::config_set_plugin("text.color", $default_options{text_color});
    }else{
        $default_options{text_color} = weechat::config_get_plugin("text.color");
    }
    if (!weechat::config_is_set_plugin("hide.servername.in.buddylist")){
        weechat::config_set_plugin("hide.servername.in.buddylist", $default_options{hide_servername_in_buddylist});
    }else{
        $default_options{hide_servername_in_buddylist} = weechat::config_get_plugin("hide.servername.in.buddylist");
    }
1097

1098 1099 1100 1101 1102 1103 1104 1105 1106 1107
    if ( ($weechat_version ne "") && (weechat::info_get("version_number", "") >= 0x00030500) )  # v0.3.5
    {
        weechat::config_set_desc_plugin("buddylist","path/file-name to store your buddies. \"%h\" will be replaced by WeeChat home (by default: ~/.weechat)");
        weechat::config_set_desc_plugin("color.default","fall back color. (default: standard weechat color)");
        weechat::config_set_desc_plugin("color.online","color for online buddies");
        weechat::config_set_desc_plugin("color.away","color for away buddies");
        weechat::config_set_desc_plugin("color.offline","color for offline buddies");
        weechat::config_set_desc_plugin("color.server","color for servername");
        weechat::config_set_desc_plugin("color.server.offline","color for disconnected server (default: hide)");
        weechat::config_set_desc_plugin("color.number","color for channel number (default: lightred). If empty, channel list option is off");
1108

1109
        weechat::config_set_desc_plugin("show.query","displays a query buffer in front of the channel list");
1110

1111 1112
        weechat::config_set_desc_plugin("hide.server.if.buddies.offline","hides server when all buddies are offline for this server (default: off)");
        weechat::config_set_desc_plugin("hide.buddy.if.offline","hide buddy if offline (default: off)");
1113

1114 1115
        weechat::config_set_desc_plugin("buddy.on.server","show buddy who is connected to a server, but not visiting the same channel(s) (default: on)");
        weechat::config_set_desc_plugin("buddy.on.server.color","color for online buddy but not visiting the same channel(s) (default: lightgreen)");
1116

1117 1118 1119 1120
        weechat::config_set_desc_plugin("hide.bar","hides buddylist bar when all servers with added buddies are offline (on = default, always = buddylist bar will be hidden (for example if you want to add item 'buddylist' to 'weechat.bar.status.items', off = buddylist bar will not be hidden))");
        weechat::config_set_desc_plugin("check.buddies","time in seconds to send a /whois request to server. Be careful not to flood server (default: 20)");
        weechat::config_set_desc_plugin("callback.timeout","time in seconds to wait for answer from server. (default: 60)");
        weechat::config_set_desc_plugin("display.original.nick","display original nickname even if buddy changed his /nick (you have to add new nick to buddylist (default: off)");
1121

1122
        weechat::config_set_desc_plugin("sort","sort method for buddylist (default = buddylist will be sort by nickname, status = buddylist will be sort by status (online, away, offline))");
1123

1124 1125
        weechat::config_set_desc_plugin("display.social.net","using bitlbee, buddies will be sorted in sublists with social-network name (eg. msn/jabber/facebook)(default: on)");
        weechat::config_set_desc_plugin("display.social.net.color","color for social-network name (default: yellow)");
1126

1127 1128 1129 1130
        weechat::config_set_desc_plugin("text.color","color for optional online/away/offline-text in buddylist (default: white)");
        weechat::config_set_desc_plugin("text.online","optional online text in buddylist (sort method has to be 'status')");
        weechat::config_set_desc_plugin("text.away","optional away text in buddylist (sort method has to be 'status')");
        weechat::config_set_desc_plugin("text.offline","optional offline text in buddylist (sort method has to be 'status')");
1131

1132 1133 1134
        weechat::config_set_desc_plugin("use.redirection","using redirection to get status of buddies (needs weechat >=0.3.4) (default: on)");
        weechat::config_set_desc_plugin("hide.servername.in.buddylist","hide the servername in buddylist. If \"on\" only nicks will be displayed in buddylist (default: off)");
    }
1135

1136
# only for debugging
1137
    $debug_redir_out = weechat::config_get_plugin("debug.redir.out") if (weechat::config_is_set_plugin("debug.redir.out"));
1138
# get color settings.
1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
    foreach my $level (values %buddylist_level)
    {
        if (weechat::config_get_plugin("color.".$level) eq "")
        {
            weechat::config_set_plugin("color.".$level,
                                       $default_color_buddylist{$level});
        }
        else
        {
            $default_color_buddylist{$level} = weechat::config_get_plugin("color.".$level);
        }
    }
1151
}
1152

1153
# hide bar when buddylist was closed
1154 1155
sub shutdown{
	weechat::command("", "/bar hide " . $prgname);
1156
return weechat::WEECHAT_RC_OK;
1157
}
1158

1159
sub DEBUG {weechat::print('', "***\t" . $_[0]);}
1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183

sub hook_timer_and_redirect{

      if ($default_version eq 1){		# if weechat is <= 0.3.4 no hooks() will be installed. Means no redirection!
	$Hooks{redirect} = weechat::hook_hsignal("irc_redirection_buddylist_whois", "redirect_whois", "");	# install hsignal()
		if ($Hooks{redirect} eq '')
		{
			weechat::print("",weechat::prefix("error")."hook failed. can't enable hook_hsignal() for $prgname.");
			return 0;
		}
	$Hooks{timer} = weechat::hook_timer($default_options{check_buddies} * 1000 * 1, 0, 0, "call_whois_all", "");	# period * millisec(1000) * second(1) * minutes(0)
		if ($Hooks{timer} eq '')
		{
			weechat::print("",weechat::prefix("error")."hook failed. can't enable hook_timer() for $prgname.");
			if (defined $Hooks{redirect}){
			  weechat::unhook($Hooks{redirect});
			  delete $Hooks{redirect};
			}
			return 0;
		}
      }
	return 1;
}

1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195
sub unhook_timer
{
    if (defined $Hooks{timer})
    {
        weechat::unhook($Hooks{timer});
        delete $Hooks{timer};
    }
    if (defined $Hooks{redirect})
    {
        weechat::unhook($Hooks{redirect});
        delete $Hooks{redirect};
    }
1196 1197
}

1198 1199 1200
sub call_whois_one
{
    my ( $server, $nickname ) = @_;
1201
    my $hash = { "server" => $server, "pattern" => "whois", "signal" => "buddylist",
1202
                "count" => "1", "string" => $nickname, "timeout" => $default_options{callback_timeout}, "cmd_filter" => "" };
1203 1204 1205 1206
    weechat::hook_hsignal_send("irc_redirect_command", $hash);
    weechat::hook_signal_send("irc_input_send", weechat::WEECHAT_HOOK_SIGNAL_STRING, $server.";;2;;/whois ".$nickname); #server;channel;flags;tags;text
}

1207
# -------------------------------[ redirection ]-------------------------------------
1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218
# calling /whois all x seconds using hook:timer()
sub call_whois_all{
my $int_count = 0;
my $foreach_count = 0;
	  # sort server and check if server is online
	  foreach my $server ( sort keys %nick_structure ){				# sort server (a-z)
	      my $color_server = get_server_status($server);				# get server status
	      if ($color_server eq $default_options{color_server_offline} or $color_server eq "1"){# server is offline
		next;									# goto next server
	      }
		# sort nick structure and call /whois
1219
		foreach my $nickname ( keys %{$nick_structure{$server}} ) {		# sort nicks (a-z)
1220
		  if (not defined $nick_structure{$server}{$nickname}{counter} or $nick_structure{$server}{$nickname}{counter} eq 0){
1221 1222
		    delete $nick_structure{$server}{$nickname} if ( $nickname eq ":seconds" );	# wrong parsing!?
		    next if ( $nickname eq ":seconds" );					# wrong parsing!?
1223 1224 1225 1226 1227
		    $nick_structure{$server}{$nickname}{counter} = 1;
		    $foreach_count = 1;
		    $int_count = 1;

		    next if ($server eq "" or $nickname eq "");
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
		    # calling hsignal(redirect)
		    my $hash = { "server" => $server, "pattern" => "whois", "signal" => "buddylist",
				  "count" => "1", "string" => $nickname, "timeout" => $default_options{callback_timeout}, "cmd_filter" => "" };
		    weechat::hook_hsignal_send("irc_redirect_command", $hash);
		    weechat::hook_signal_send("irc_input_send", weechat::WEECHAT_HOOK_SIGNAL_STRING, $server.";;2;;/whois ".$nickname); #server;channel;flags;tags;text

		    last;								# jump to end of list
		  }else{
		    next;
		  }

		}
	  last if ($foreach_count eq 1);
	  }
# set counter for each buddy back to zero to start count from beginning
  if ($int_count eq 0){
  $int_count = 0;
	  foreach my $server ( sort keys %nick_structure ){				# sort server (a-z)
		foreach my $nickname ( sort keys %{$nick_structure{$server}} ) {	# sort nicks (a-z)
		    $nick_structure{$server}{$nickname}{counter} = 0;
		}
	  }
  $foreach_count = 0;
  }
}

# backcall from hook_hsignal()
sub redirect_whois{
    my ($data, $signal, %hashtable) = ($_[0], $_[1], %{$_[2]});

# for testing purpose, to see whats inside of hashtable
1260 1261 1262 1263
    if ( $debug_redir_out eq "on" ){
        while (my($key, $value) = each %hashtable){
            weechat::print("",$key . " is key with value " .$hashtable{$key});
        }
1264 1265
    }

1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283
    # get nick from hashtable command: /whois nick
    my (undef, $main_nickname) = split /\s+/, $hashtable{"command"}, 2;
    # weechat >=0.4.0 and "irc.network.whois_double_nick = on", command is: /whois nick nick
    if ($weechat_version >= 0x00040000  and  weechat::config_boolean(weechat::config_get("irc.network.whois_double_nick")) == 1){
        (undef,$main_nickname) = split /\s+/,$main_nickname;
    }

    # timeout error...
    if ($hashtable{"error"} eq "timeout"){
        weechat::print("",weechat::prefix("error").
                    "buddylist: timeout error for server ".
                    weechat::color(weechat::config_color(weechat::config_get("weechat.color.chat_server"))).
                    $hashtable{"server"}.
                    weechat::color("reset").
                    ". Increase value \"callback.timeout\" (current value: ".
                    $default_options{callback_timeout} . ")");
        return weechat::WEECHAT_RC_OK;
    }
1284

1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
    # check if buddy is online and look for visiting channels
    my $rfc_319 = "319";							# rfc number containing channels
    my ( $nickname,$channel_name ) = parse_redirect($hashtable{"server"},$rfc_319,$hashtable{"output"});	# check redirection output for channels
    return weechat::WEECHAT_RC_OK if ( $channel_name eq -1 );		# -1 = buddy not online

    if ($channel_name eq -2 and exists $nick_structure{$hashtable{"server"}}{$main_nickname}){
        my $sorted_numbers = check_query_buffer($hashtable{"server"},$main_nickname,"");
        $nick_structure{$hashtable{"server"}}{$main_nickname}{buffer} = "()" if ($sorted_numbers eq "");	# buddy online but not in a channel
        $nick_structure{$hashtable{"server"}}{$main_nickname}{buffer} = $sorted_numbers if ($sorted_numbers ne ""); # /query buffer open
    }else{
        check_for_channels($hashtable{"server"}, $main_nickname, $channel_name);
    }

    weechat::bar_item_update($prgname);
1299 1300 1301 1302 1303
return weechat::WEECHAT_RC_OK;
}

# compare if your buddy is in same channels you are already in. channel-number(s) will be saved in nick_structure(buffer)
sub check_for_channels{
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
    my ($server, $nickname, $channel_name) = @_;
    return if (not exists $nick_structure{$server}{$nickname}); # does nick exists in nick_structure? NO?

    $nick_structure{$server}{$nickname}{buf_name} = "";         # delete
    $channel_name =~ s/:|@|!|\+//g;                             # kill channel-modes (not needed for channelname)

    $nick_structure{$server}{$nickname}{buf_name} = $channel_name;# save name of visit channels
    my @array=split(/ /,$channel_name);                         # split channelnames into array

    # check out if buddy is in same channels as you are
    my @buf_count;
    $nick_structure{$server}{$nickname}{buffer} = "()";		# delete buffer number in nick_structure{buffer]

    foreach (@array){
        my $buffer_pointer = weechat::buffer_search("irc", $server . "." . $_);
        if ($buffer_pointer ne ""){					# buffer exists?
            my $buffer_number = search_buffer_number($buffer_pointer);# check if buddy is in same channels as you
            if ($buffer_number ne 0){
                push @buf_count,($buffer_number) ;
                # check if option "color.number" has valid entry and write buffer number to nick_structure
                if ($default_options{color_number} ne ""){		# color for color_number set?
                    @buf_count = del_double(@buf_count);
                    my $sorted_numbers = join(",",sort{$a<=>$b}(@buf_count));		# channel numbers (1,2....)
                    $sorted_numbers = check_query_buffer($server,$nickname,$sorted_numbers);
                    $nick_structure{$server}{$nickname}{buffer} = $sorted_numbers;# save buffer number in nick_structure{buffer]
                }
            }
        }elsif ($nick_structure{$server}{$nickname}{buffer} eq "()"){# buddy online but not in a channel you are in
            my $sorted_numbers = check_query_buffer($server,$nickname,"");
            $nick_structure{$server}{$nickname}{buffer} = "()" if ($sorted_numbers eq "");
            $nick_structure{$server}{$nickname}{buffer} = $sorted_numbers if ($sorted_numbers ne "");
        }
    }
1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352
}

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

# looking for /query buffer
sub check_query_buffer{
my ($server,$nickname,$sorted_numbers) = @_;

return $sorted_numbers if ($default_options{show_query} ne "on");

my $buffer_pointer = weechat::buffer_search("irc", $server . "." . $nickname);
1353
if ($buffer_pointer ne ""){
1354
    my $buffer_number = search_buffer_number($buffer_pointer);
1355 1356 1357 1358 1359 1360
    if ($sorted_numbers ne ""){
        $sorted_numbers = "Q:" . $buffer_number . "," . $sorted_numbers;
    }else{
        $sorted_numbers = "Q:" . $buffer_number;
    }
}
1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374

return $sorted_numbers;
}
# search buffer
sub search_buffer_number{
my ( $buffer_name ) = @_;
  my $infolist_buffer = weechat::infolist_get("buffer",$buffer_name,"");	# get infolist_pointer for buffer
  weechat::infolist_next($infolist_buffer);
  my $buffer_number = weechat::infolist_integer($infolist_buffer,"number");	# get buffer_number
  weechat::infolist_free($infolist_buffer);					# don't forget to free infolist ;-)

return $buffer_number;
}

1375
# checks if buddy is connected to server and look for $rfc line from /whois redirection
1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391
# :anthony.freenode.net 330 mynick 2nd_nick 1st_nick :is logged in as		# [2nd_nick] is logged in as 1st_nick
sub parse_redirect{
my ( $servername,$rfc,$args ) = @_;

return ("",-1) if (not defined $servername or $servername eq "");
  # nick is not online
  my $rfc_401 = " 401 ";							# No such nick/channel
  $args =~ /($rfc_401)(.*?) (.*?) (.*)\n/;
  if (defined $1 and $1 eq $rfc_401 and defined $3){
	$nick_structure{$servername}{$3}{status} = 2;				# buddy offline
	$nick_structure{$servername}{$3}{buffer} = "";				# clear buffer number
	$nick_structure{$servername}{$3}{buf_name} = "";			# clear name of buffer
    return ("",-1);
  }

  my $rfc_301 = " 301 ";							# nick :away
1392
### part for bitlbee
1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411
  # bitlbee offline check
  # :localhost 312 nils_2 nickname mail@gmail.com. :jabber network
  # :localhost 301 nils_2 nickname :User is offline
  my $rfc_312 = " 312 ";							# 312 nick server :info
  my $offline_text = "(:User is offline|:Offline)\n";				# (bitlbee|bitlbee-libpurple)
  my $network = "(:msn|:jabber|:yahoo)";					# possible networks
  my ($a1,$a2,$a3,$a4)  = "";
  ($a1,$a2,$a3,$a4) = ($args =~ /(.*)($rfc_312)(.*)($network)/);
  if ( defined $a4 and $a4 ne ""){
    ($a1,$a2,$a3,$a4) = "";
    ($a1,$a2,$a3,$a4) = ($args =~ /($rfc_301)(.*?) (.*?) ($offline_text)/);
    if ( defined $a4 and $a4 ne ""){
	$nick_structure{$servername}{$a3}{status} = 2;				# buddy offline on bitlbee
	$nick_structure{$servername}{$a3}{buffer} = "";				# clear buffer number
	$nick_structure{$servername}{$a3}{buf_name} = "";			# clear name of buffer
	return ("",-1);
    }
  }

1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427
  # bitlbee: add a tag for msn/jabber/facebook to display in buddylist
    ($a1,$a2,$a3,$a4) = "";
  my ($a5,$a6)  = "";
  ($a1,$a2,$a3,$a4,$a5,$a6) = ($args =~ /(.*)($rfc_312)(.*?) (.*?) (.*)($network)/);

if ( $default_options{display_social_net} eq "on" ){
  if ( defined $a6 ){
    my ($string) = split / /,$a6;                                               # get first word from network
    if ( $string eq ":msn" ){
        $nick_structure{$servername}{$a4}{bitlbee_service} = "msn";
    }elsif ( $string eq ":jabber" ){
        $nick_structure{$servername}{$a4}{bitlbee_service} = "jabber";
        $nick_structure{$servername}{$a4}{bitlbee_service} = "facebook" if ( index($args,"chat.facebook.com") ne "-1" );
    }elsif ( $string eq ":yahoo" ){
        $nick_structure{$servername}{$a4}{bitlbee_service} = "yahoo";
    }else{
1428
        $nick_structure{$servername}{$a4}{bitlbee_service} = "";                # no unknown service
1429 1430 1431
    }
  }
}elsif( defined $a6 ){
1432
        $nick_structure{$servername}{$a4}{bitlbee_service} = "";                # no unknown service
1433 1434 1435
}

### bitlbee part end
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

if ( $default_options{display_original_nick} eq "on" ){
  my $rfc_330 = " 330 ";							# nick :is logged in as
  # check if nick has a different nick name (/nick blafasel)
  $args =~ /($rfc_330)(.*?) (.*?) (.*?) :(.*)\n/;				# non-greedy
    my $nickname_as = $3;
    my $nickname = $4;

    if ( defined $nickname_as and defined $nickname and $nickname_as ne $nickname ){
      if ( exists $nick_structure{$servername}{$nickname} ){
	$args =~ /($rfc_301)/;
	if (defined $1 and $1 eq $rfc_301){					# buddy is away
	  return ($nickname,-1) if (not defined $nickname or not exists $nick_structure{$servername}{$nickname});		# does nick exists in nick_structure? NO?
	  $nick_structure{$servername}{$nickname}{status} = 1;			# buddy away
	  $nick_structure{$servername}{$nickname_as}{status} = 2 if (exists $nick_structure{