#!/usr/bin/perl

##
# Copyright (C) 2002-2004 Curtis "Mr_Person" Hawthorne
#
# 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 2 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, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
##

use Net::Jabber qw(Client);

use Net::IRC;

use strict;
use warnings;

our $VERSION = '0.1.2';

our %GLOBALS;

# READ THE DOCUMENTATION BEFORE USING!

%GLOBALS = (
	pidfile => '/home/user/irj/irj.pid',
	writepid => '1',
	logfile => '/home/user/irj/irj.log',
	writelog => '1',
	quietmode => '0',
	daemonmode => '0', # Should only be enabled on Unix-style platforms

	jabberserver => 'example.com',
	jabberport => '5222',
	jabberusername => 'username',
	jabberpassword => 'password',
	jabberssl => '0',

	ircserver => 'example.com',
	ircport => '6667',
	ircnick => 'IRJ',
	ircchannel => '#IRJ',

	ircconnectscript => '/home/user/irj/irj.script',

	ircowner => [qw( Nick Nick-Awy )],
	ircanyowner => '0',
	ircmultipleowners => '0',

	msnautonick => '1',

	debuglevel => '1',

# Do not edit below here

	ircconnection => 0,
	ircownerstatus => 0,
	ircnames => [],
	roster => {},
	conversation => '',
);

if($GLOBALS{writelog}) {
	open(LOG, ">>$GLOBALS{logfile}") or die "Unable to open log file: $!";
	select(LOG);
	$| = 1;
	select(STDOUT);
}

if($GLOBALS{daemonmode}) {
	require Proc::Daemon;
	$GLOBALS{quietmode} = 1;
	&debug(1, "Entering daemon mode");
	&Proc::Daemon::Init;

	# Logging has to be started twice because in the process of becoming a daemon, all file descriptors are closed, but we need to log just before becoming a daemon also.
	if($GLOBALS{writelog}) {
		open(LOG, ">>$GLOBALS{logfile}") or die "Unable to open log file: $!";
		select(LOG);
		$| = 1;
		# Might as well leave LOG selected just in case
	}

	open(STDERR, ">&LOG"); # Redirect STDERR to the log because it will not be seen otherwise.
}

&debug(1, "IRJ Version $VERSION is starting");

if($GLOBALS{writepid}) {
	debug(1, "Writing $$ to PID file");
	open(PID, ">$GLOBALS{pidfile}") or die "Unable to open PID file: $!";
	print PID "$$\n";
	close(PID) or die "Unable to close PID file: $!";
}

my $irc = new Net::IRC;

$GLOBALS{IRCConnection} = $irc->newconn (
	Server	=> $GLOBALS{ircserver},
	Port	=> $GLOBALS{ircport},
	Nick	=> $GLOBALS{ircnick},
	Ircname	=> "http://irj.sourceforge.net/",
);

$GLOBALS{IRCConnection}->add_handler('endofmotd', \&IRCConnect);
$GLOBALS{IRCConnection}->add_handler('public', \&IRCPublic);
$GLOBALS{IRCConnection}->add_handler('msg', \&IRCMsg);
$GLOBALS{IRCConnection}->add_handler('caction', \&IRCAction);
$GLOBALS{IRCConnection}->add_handler('353', \&IRCNames);

# Behold, the lovely new nick tracking system!
$GLOBALS{IRCConnection}->add_handler('quit', \&IRCQuit);
$GLOBALS{IRCConnection}->add_handler('part', \&IRCPart);
$GLOBALS{IRCConnection}->add_handler('join', \&IRCJoin);
$GLOBALS{IRCConnection}->add_handler('kick', \&IRCKick);
$GLOBALS{IRCConnection}->add_handler('nick', \&IRCNick);

&debug(1, "Connecting to IRC...");

until($GLOBALS{ircconnection}) {
	$irc->do_one_loop;
}

&debug(1, "Connected to IRC.");

$GLOBALS{JabberConnection} = new Net::Jabber::Client();

$GLOBALS{JabberConnection}->Info(name => 'IRJ', version => $VERSION);

$GLOBALS{JabberConnection}->SetCallBacks(message => \&JabberMessage, presence => \&JabberPresence);
$GLOBALS{JabberConnection}->SetIQCallBacks("jabber:iq:roster" => { set => \&JabberRoster, result => \&JabberRoster });

&jabber_connect;

&irc_say("Getting Roster...");

%{$GLOBALS{roster}} = $GLOBALS{JabberConnection}->RosterGet();

##
# Enter loop for IRC and Jabber
##

while(1 == 1) {
	unless(defined($GLOBALS{JabberConnection}->Process(1))) {
		&irc_say("! Jabber connection error, attempting to reconnect...");
		&jabber_connect;

		# Reset owner status to send presence.
		$GLOBALS{ircownerstatus} = 0;
		$GLOBALS{IRCConnection}->names($GLOBALS{ircchannel});
	}

	unless(defined($irc->do_one_loop)) {
		die "IRC Connection Error.";
	}
}

$GLOBALS{JabberConnection}->Disconnect;

if($GLOBALS{writelog}) {
	close(LOG);
}

##
# General Subs
##

sub nicklookup {
	my ($shortrecipient) = @_;

	unless($shortrecipient) { return; } # No need to try and match if there's nothing to match against

	my $resource;
	if($shortrecipient =~ m#([^/]+)/(.+)#) {
		$shortrecipient = $1;
		$resource = $2;
	}

	my @jids = grep {
		if($GLOBALS{roster}{$_} and $GLOBALS{roster}{$_}{name}) {
			$GLOBALS{roster}{$_}{name} =~ /^$shortrecipient/i || $_ =~ /^$shortrecipient/i;
		} else {
			$_=~ /^$shortrecipient/i;
		}
	} (keys %{$GLOBALS{roster}});

	if(scalar(@jids) == 1) {
		if($resource) {
			return $jids[0] . '/' . $resource;
		} else {
			return $jids[0];
		}
	} else {
		return;
	}

}

sub debug {
	if($_[0] <= $GLOBALS{debuglevel}) {
		unless($GLOBALS{quietmode}) {
			print "$_[1]\n";
		}

		if($GLOBALS{writelog}) {
			print LOG scalar(localtime(time)), " $_[1]", "\n";
		}
	}
}

##
# General IRC Subs
##

sub irc_incoming {
	my ($message) = @_;

	my ($shortrecipient, $fullrecipient, $body);

	if ($message =~ /^\!([^\s]+)\s+(.*)/) {
		$shortrecipient = $1;
		$body = $2;
	} elsif ($message =~ /^([^\:\s]+)\:\s*(.*)/) {
		$shortrecipient = $1;
		$body = $2;
	} else {
		if($GLOBALS{conversation}) {
			$shortrecipient = $GLOBALS{conversation};
			$body = $message;
		} else {
			&irc_say("Couldn't determine recipient");
			return;
		}
	}

	unless($fullrecipient = &nicklookup($shortrecipient)) {
		if($shortrecipient =~ /\@/) {
			$fullrecipient = $shortrecipient;
			# It's got an @ in it, so they're probably sending it to someone not in the roster, allow it
		}
	}

	unless($fullrecipient) {
		&irc_say("Couldn't lookup receipient for $shortrecipient");
	} else {
		&irc_conversation($fullrecipient);
		
		$body = &irc_stripcodes($body);
		debug(2, "[Jabber - $fullrecipient] $body");
		$GLOBALS{JabberConnection}->MessageSend(to => $fullrecipient, body=> $body);
	}
}

sub irc_conversation {
	my ($fullrecipient, $force) = @_;
	my $nick = $fullrecipient;
	if($GLOBALS{roster}{$fullrecipient} and $GLOBALS{roster}{$fullrecipient}{name}) {
		$nick = $GLOBALS{roster}{$fullrecipient}{name}; # Use user-specified nicks when possible
	}
	if(($GLOBALS{conversation} ne $fullrecipient) or $force) {
		$GLOBALS{IRCConnection}->topic($GLOBALS{ircchannel}, "IRJ - Talking with: $nick");
		$GLOBALS{conversation} = $fullrecipient;
	}
}

sub irc_nicktrack {
	my @temp = @{$GLOBALS{ircnames}};
	@{$GLOBALS{ircnames}} = ();
	foreach (@temp) {
		s/^[+@]//;
		unless($_ eq $GLOBALS{ircnick}) { push @{$GLOBALS{ircnames}}, $_; }
	}

	if($GLOBALS{ircanyowner}) {
		@{$GLOBALS{ircowner}} = @{$GLOBALS{ircnames}};
	}

	foreach my $nick (@{$GLOBALS{ircnames}}) {
		foreach(@{$GLOBALS{ircowner}}) {
			if($nick eq $_) {
				unless($GLOBALS{ircownerstatus}) {
					&debug(1, "Owner has joined channel.");
					&irc_say("Sending Presence...");
					$GLOBALS{JabberConnection}->PresenceSend(type => 'available');
				}
				$GLOBALS{ircownerstatus} = $nick;
				return;
			}
		}
	}

	if($GLOBALS{ircownerstatus}) {
		&debug(1, "Owner has left channel.");
		$GLOBALS{JabberConnection}->PresenceSend(type => 'unavailable');
		$GLOBALS{JabberConnection}->PresenceDBClear; # Clear out Presence DB, when we come back online it will be out of sync and we'll get info from the server about what's going on anyway.
		$GLOBALS{ircownerstatus} = 0;
	}
}

sub irc_say {
	&debug(2, "[IRC-C] $_[0]");
	$GLOBALS{IRCConnection}->privmsg($GLOBALS{ircchannel}, $_[0]);
}

sub irc_msg {
	unless($GLOBALS{ircownerstatus}) { return; }
	&debug(2, "[IRC-P] $_[0]");
	$GLOBALS{IRCConnection}->privmsg($GLOBALS{ircownerstatus}, $_[0]);
}

sub irc_notice {
	unless($GLOBALS{ircownerstatus}) { return; }
	&debug(2, "[IRC-N] $_[0]");
	$GLOBALS{IRCConnection}->notice($GLOBALS{ircownerstatus}, $_[0]);
}

sub irc_stripcodes {
	my $string = $_[0];
	
	$string =~ s/\cB//g;
	$string =~ s/\c_//g;
	$string =~ s/\cV//g;
	$string =~ s/\cC\d{1,2},\d{1,2}//g;
	$string =~ s/\cC\d{1,2}//g;	
	$string =~ s/\cC//g;
	
	return $string;
}

##
# General Jabber Subs
##

sub jabber_connect {
	&irc_say("Connecting to Jabber...");

	if($GLOBALS{JabberConnection}->Connected) {
		$GLOBALS{JabberConnection}->Disconnect;
	}

	my $status;
	for(my $i = 0; $i < 5; $i++) {
		debug(1, "Jabber Connection Attempt #$i...");
		$status = $GLOBALS{JabberConnection}->Connect(hostname => $GLOBALS{jabberserver}, port => $GLOBALS{jabberport}, ssl => $GLOBALS{jabberssl});
		if($status) { last; }
		sleep 5;
	}

	unless($status) { die "Error connecting to Jabber server\n"; }

	my @jabber_auth_result = $GLOBALS{JabberConnection}->AuthSend(username => $GLOBALS{jabberusername}, password => $GLOBALS{jabberpassword}, resource => 'IRJ');

	if ($jabber_auth_result[0] ne "ok") {
		die "Jabber Authorization failed: $jabber_auth_result[0] - $jabber_auth_result[1]\n";
	}

	&irc_say("Connected to Jabber Server successfully.");
}

sub jabber_presence {
	my ($presence, $from) = @_;
	# $from is there in case $presence hasn't been defined in PresenceDB

	my ($type, $show, $status);

	if(defined($presence)) {
		$from = $presence->GetFrom;
		$type = $presence->GetType;
		$show = $presence->GetShow;
		$status = $presence->GetStatus;
	} else {
		$type = 'unavailable';
	}

	# Get rid of warnings:
	unless ($type) { $type = 'available'; } # Available is default
	unless ($show) { $show = 'available'; } # Available is default

	my $resource;
	if($from =~ m#([^/]+)/(.+)#) {
		$from = $1;
		$resource = $2;
		# Split the JID and the resource
	}

	if($status) {
		$status =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg; # Take away annoying nick encoding.
	}

	my $friendlynick = $from;
	if($GLOBALS{roster}{$from} and $GLOBALS{roster}{$from}{name}) {
		$friendlynick = $GLOBALS{roster}{$from}{name};
	}
	my $announce;

	if($type eq 'unavailable') {
		$announce = "[_] $friendlynick is 'Unavailable'";
	} elsif($show eq 'away') {
		$announce = "[-] $friendlynick is 'Away'";
	} elsif($show eq 'xa') {
		$announce = "[-] $friendlynick is 'Extended Away'";
	} elsif($show eq 'dnd') {
		$announce = "[-] $friendlynick is 'Do not Disturb'";
	} else {
		$announce = "[^] $friendlynick is 'Available'";
	}

	if($status) {
		if($from =~ /\@.*?msn/i and $GLOBALS{msnautonick}) {
			unless($GLOBALS{roster}{$from}) {
				$announce .= " and is '$status'";
			} elsif ($GLOBALS{roster}{$from}{name} ne $status) {
				$GLOBALS{JabberConnection}->RosterAdd(jid => $from, name => $status);
				&debug(2, "Autochanged MSN user $from to nickname $status");
				$announce .= " and is now '$status'";
			}
		} else {
			$announce .= " and is '$status'";
		}
	}

	if($resource) {
		$announce .= " on resource '$resource'";
	}

	$announce .= ".";

	return $announce;
}

##
# IRC Callback Subs
##

sub IRCConnect {
	my $self = shift;	

	if($GLOBALS{ircconnectscript} && -r $GLOBALS{ircconnectscript} && -f $GLOBALS{ircconnectscript}) {
		open(SCRIPT, $GLOBALS{ircconnectscript}) or die "Error opening connect script: $!";
		my @script = <SCRIPT>;
		close(SCRIPT);
		chomp @script;

		foreach(@script) {
			if($_) {
				$self->sl($_);
				debug(2, "Executing connection script item: $_");
			} else {
				debug(2, "Blank script line: Sleeping 1 second...");
				sleep 1;
			}
		}
	}

	$self->join($GLOBALS{ircchannel});
	$self->topic($GLOBALS{ircchannel}, "IRJ - IRJ Initiated");
	$GLOBALS{ircconnection} = 1;
}

sub IRCPublic {
	my ($self, $event) = @_;

	my $nick = $event->nick;
	unless($GLOBALS{ircownerstatus} && (grep /\A$nick\z/, @{$GLOBALS{ircowner}})) { return; }

	my ($message) = $event->args;

	&irc_incoming($message);
}

sub IRCAction {
	my ($self, $event) = @_;

	my $nick = $event->nick;
	unless($GLOBALS{ircownerstatus} && (grep /\A$nick\z/, @{$GLOBALS{ircowner}})) { return; }

	unless($GLOBALS{conversation}) {
		&irc_say("Cannot use actions until conversation is started.");
		return;
	}

	my ($message) = $event->args;

	$message = "* $nick $message";

	&irc_incoming($message);
}

sub IRCMsg {
	my ($self, $event) = @_;

	my $nick = $event->nick;
	unless($GLOBALS{ircownerstatus} && (grep /\A$nick\z/, @{$GLOBALS{ircowner}})) { return; }

	my ($message) = $event->args;

	if ($message =~ /\!away(?:\s(.+))?/i) {
		my $status = $1;
		&debug(2, "Received !away request ($status)");
		$GLOBALS{JabberConnection}->PresenceSend(type => 'available', status => $status, show => 'away');
	} elsif ($message =~ /\!(?:extendedaway|exaway|xa)(?:\s(.+))?/i) {
		my $status = $1;
		&debug(2, "Received !extendedaway request ($status)");
		$GLOBALS{JabberConnection}->PresenceSend(type => 'available', status => $status, show => 'xa');
	} elsif ($message =~ /\!(?:dnd|donotdisturb)(?:\s(.+))?/i) {
		my $status = $1;
		&debug(2, "Received !dnd request ($status)");
		$GLOBALS{JabberConnection}->PresenceSend(type => 'available', status => $status, show => 'dnd');
	} elsif ($message =~ /\!subscribed\s+(.*)/i) {
		my $to = $1;
		&debug(2, "Received !subscribed request for $to");
		my $jid;
		unless($jid = &nicklookup($to)) {
			&irc_say("! Unable to determine requested user");
			return;
		}
		$GLOBALS{JabberConnection}->PresenceSend(to => $jid, type => 'subscribed');
	} elsif ($message =~ /\!subscribe\s+(.*)/i) {
		my $jid = $1;
		&debug(2, "Received !subscribe request for $jid");
		$GLOBALS{JabberConnection}->PresenceSend(to => $jid, type => 'subscribe');
	} elsif ($message =~ /\!fullsubscribe\s+(.*)/i) {
		my $jid = $1;
		&debug(2, "Received !fullsubscribe request for $jid");
		$GLOBALS{JabberConnection}->PresenceSend(to => $jid, type => 'subscribe');
		$GLOBALS{JabberConnection}->PresenceSend(to => $jid, type => 'subscribed');
	} elsif ($message =~ /!unsubscribe\s+(.*)/i) {
		my $to = $1;
		&debug(2, "Received !unsubscribe request for $to");
		my $jid;
		unless($jid = &nicklookup($to)) {
			&irc_say("Unable to determine requested user");
			return;
		}
		$GLOBALS{JabberConnection}->PresenceSend(to => $jid, type => 'unsubscribed');
		$GLOBALS{JabberConnection}->PresenceSend(to => $jid, type => 'unsubscribe');
	} elsif ($message =~ /\!nick\s+(.+?)\s+(.*)/i) {
		my $jid = $1;
		my $name = $2;
		&debug(2, "Setting $jid nickname to $name");
		$GLOBALS{JabberConnection}->RosterAdd(jid => $jid, name => $name);
	} elsif ($message =~ /\!(?:deletenick|delnick|removenick)\s+(.*)/i) {
		my $to = $1;
		&debug(2, "Deleting $to from roster");
		my $jid;
		unless($jid = &nicklookup($to)) {
			&irc_say("Unable to determine requested user");
			return;
		}
		$GLOBALS{JabberConnection}->RosterRemove(jid => $jid);
	} elsif($message =~ /\!info\s+(.*)/i) {
		my $jid;
		unless($jid = &nicklookup($1)) {
			irc_say("Unable to determine user");
			return;
		}

		my $presence = $GLOBALS{JabberConnection}->PresenceDBQuery($jid);
		&irc_say(&jabber_presence($presence, $jid));

		if($GLOBALS{roster}{$jid}) {
	                &irc_say("$jid has a subscription status of \"" . $GLOBALS{roster}{$jid}{subscription} . '"');
			if($GLOBALS{roster}{$jid}{ask}) {
				&irc_say("$jid is asking for $GLOBALS{roster}{$jid}{ask}");
			}
		}
	} elsif ($message =~ /\!conversation\s+(.*)/i) {
		my $jid;
		
		unless($jid = &nicklookup($1)) {
			irc_say("Unable to determine user");
			return;
		}
		
		&irc_conversation($jid);
	} elsif ($message =~ /\!back/i) {
		&debug(2, "Received !back request, setting presence to available");
		$GLOBALS{JabberConnection}->PresenceSend(type => 'available');
	} elsif($message =~ /\!allstatus/i) {
		foreach(keys %{$GLOBALS{roster}}) {
			unless(/\@/) { next; } # Don't care about transports and such

			my $presence = $GLOBALS{JabberConnection}->PresenceDBQuery($_);
			&irc_say(&jabber_presence($presence, $_));
		}
	} elsif ($message =~ /\!ircnames/i) {
		&irc_say("Current IRC users in channel: " . join(', ', @{$GLOBALS{ircnames}}));
	} elsif ($message =~ /\!(?:die|ifeelhappy)/i) {
		&debug(1, "User requested termination");
		die "User requested termination";
	} else {
		&debug(2, "Received unkown request: $message");
	}
}

sub IRCNames {
	my ($self, $event) = @_;

	my @names = $event->args;

	my $channel = $names[2];

	unless ($channel =~ /^$GLOBALS{ircchannel}$/i) {
		return;
	}

	@{$GLOBALS{ircnames}} = split(/\s/, $names[3]);

	&debug(2, "Received IRC NAMES update - " . join(',', @{$GLOBALS{ircnames}}));

	&irc_nicktrack;
}

sub IRCNick {
	my ($self, $event) = @_;

	my $oldnick =  $event->nick;
	my $newnick =  ($event->args)[0];

	my @names = @{$GLOBALS{ircnames}};
	@{$GLOBALS{ircnames}} = ();
	
	foreach (@names) {
		if ($_ eq $oldnick) {
			push @{$GLOBALS{ircnames}}, $newnick;
		} else {
			push @{$GLOBALS{ircnames}}, $_;
		}
	}

	&debug(2, "$oldnick changed IRC nick to $newnick");
		
	&irc_nicktrack;
}

sub IRCJoin {
	my ($self, $event) = @_;

	my $channel = ($event->to)[0]; # As per RFC 2812 we don't need to worry about more than one
	unless($channel =~ /^$GLOBALS{ircchannel}$/i) { return; }
	
	push @{$GLOBALS{ircnames}}, $event->nick;

	&debug(2, $event->nick . " joined the channel");
			
	&irc_nicktrack;
}

sub IRCQuit {
	my ($self, $event) = @_;
	
	my @names = @{$GLOBALS{ircnames}};
	@{$GLOBALS{ircnames}} = ();
	
	my $nick = $event->nick;
	foreach (@names) {
		if($_ eq $nick) {
			next;
		} else {
			push @{$GLOBALS{ircnames}}, $_;
		}
	}
	
	&debug(2, "$nick quit IRC");
	
	&irc_nicktrack;
}

sub IRCPart {
	my ($self, $event) = @_;

	my $channel = ($event->to)[0]; # As per RFC 2812 we don't need to worry about more than one	
	unless($channel =~ /^$GLOBALS{ircchannel}$/i) { return; }

	my @names = @{$GLOBALS{ircnames}};
	@{$GLOBALS{ircnames}} = ();
	
	my $nick = $event->nick;
	foreach (@names) {
		if($_ eq $nick) {
			next;
		} else {
			push @{$GLOBALS{ircnames}}, $_;
		}
	}

	&debug(2, "$nick parted the channel");

	&irc_nicktrack;
}

sub IRCKick {
	my ($self, $event) = @_;

	my $channel = ($event->args)[0];
	unless($channel =~ /^$GLOBALS{ircchannel}$/i) { return; }

	my @names = @{$GLOBALS{ircnames}};
	@{$GLOBALS{ircnames}} = ();
	
	my $nick = $event->nick;
	foreach (@names) {
		if($_ eq $nick) {
			next;
		} else {
			push @{$GLOBALS{ircnames}}, $_;
		}
	}

	&irc_nicktrack;
}


##
# Jabber Callback Subs
##

sub JabberMessage {
	my $sid = shift;
	my $message = shift;

	my $from = $message->GetFrom();
	my $body = $message->GetBody();
	my $subject = $message->GetSubject();
	my $type = $message->GetType();

	if($type eq 'error') {
		my @error = ($message->GetError || 'None', $message->GetErrorCode || 'None');
		&irc_say("! Error from $from - $error[0] ($error[1])");
		&debug(1, "[Jabber] Error from $from - $error[0] ($error[1])");
		return;
	}

	if($GLOBALS{roster}{$from} and $GLOBALS{roster}{$from}{name}) {
		$from = $GLOBALS{roster}{$from}{name};
	}

	my @message = split(/\n/, $body); # Messages can have multiple lines, IRC can't.
	foreach(@message) {
		my $line = $_;

		if($subject) {
			$line = "[$subject] $line";
		}

		if($type eq 'headline') {
			$line = "* $line";
		}

		&irc_say("$from: $line");
	}
}

sub JabberPresence {
	my $sid = shift;
	my $presence = shift;

	$GLOBALS{JabberConnection}->PresenceDBParse($presence);

	my $from = $presence->GetFrom();
	my $type = $presence->GetType();
	my $status = $presence->GetStatus();
	my $show = $presence->GetShow();

	unless ($type) { $type = 'available'; } # Available is default

	if($type eq 'error') {
		my @error = ($presence->GetError, $presence->GetErrorCode);
		&irc_say("! Error from $from - $error[0] ($error[1])");
		&debug(1, "[Jabber] Error from $from - $error[0] ($error[1])");
		return;
	}

	unless($from =~ /\@/) { return; } # Now that we've got errors, we don't need to see the presence of transports

	my $friendlynick = $from;
	if($GLOBALS{roster}{$from} and $GLOBALS{roster}{$from}{name}) {
		$friendlynick = $GLOBALS{roster}{$from}{name};
	}

	if($type eq 'subscribe') {
		&irc_msg("% $from requests subscription, to allow - /msg $GLOBALS{ircnick} !fullsubscribe $from");
	} elsif($type eq 'subscribed') {
		&irc_msg("% $from is subscribed");
	} elsif($type eq 'unsubscribe') {
		$GLOBALS{JabberConnection}->Send($presence->Reply(type => 'unsubscribed'));
		$GLOBALS{JabberConnection}->Send($presence->Reply(type => 'unsubscribe'));
		&irc_msg("% $friendlynick requested unsubscription from presence and has been auto-unsubscribed.");
	} elsif($type eq 'unsubscribed') {
		&irc_msg("% $from is unsubscribed");
	} else { # Available is the default type
		&irc_notice(&jabber_presence($presence));
	}
}

sub JabberRoster {
	my $sid = shift;
	my $iq = shift;

	my %rosterupdate = $GLOBALS{JabberConnection}->RosterParse($iq);

	foreach(keys %rosterupdate) {
		if($rosterupdate{$_}{subscription} eq 'remove') {
			delete $GLOBALS{roster}{$_}; # Delete if it's requested of if there's no subscription - cause there's really no reason to keep it
			&debug(2, "Removed $_ from the roster at servers request");
		} elsif ($rosterupdate{$_}{subscription} eq 'none' and !$rosterupdate{$_}{ask}) {
			$GLOBALS{JabberConnection}->RosterRemove(jid => $_);
			&debug(2, "Requested removal of $_ from roster because subscription was 'none'");
		} else {
			if(($GLOBALS{conversation} eq $_) && $rosterupdate{$_}{name} && ($GLOBALS{roster}{$_}{name} ne $rosterupdate{$_}{name})) {
				$GLOBALS{roster}{$_} = $rosterupdate{$_};
				&irc_conversation($_, 1);
			} else {
				$GLOBALS{roster}{$_} = $rosterupdate{$_};
			}
		}
	}

	&debug(2, "Received Roster update from Jabber server successfully.");
}
