#####################################################
#  GT-Chat 0.95+ Plugin                             #
#                                                   #
#  Author: SoftCreatR Media <info@softcreatr.de>    #
#  License: ISC                                     #
#                                                   #
#  This plugin provides a simple integration of     #
#  GT-Chat 0.95+ into Woltlab Suite Core 3.0+.      #
#####################################################
package GTChat::Plugins::ExternalLink::WoltLabSuite;
use strict;
use warnings;
use DBI;
my $wscSessionID = '';
my $wscInstallNumber = 0;
my $useWscProfile = 0;
my $dsn = '';
my $dbh;
my $userID = 0;
return bless({});
sub cleanUp {}
sub checkProfile {}
sub getEnvironment {
    my ($self, $main, $environment) = @_;
    my %info = {};
    # Integration configuration & database connection
    if (exists($main->{settings}{woltlab_suite_integration}{database})) {
        my $dbHost = $main->{settings}{woltlab_suite_integration}{database}{host};
        my $dbPort = $main->{settings}{woltlab_suite_integration}{database}{port};
        my $dbName = $main->{settings}{woltlab_suite_integration}{database}{name};
        my $dbUser = $main->{settings}{woltlab_suite_integration}{database}{user};
        my $dbPass = $main->{settings}{woltlab_suite_integration}{database}{password};
        
        $wscInstallNumber = $main->{settings}{woltlab_suite_integration}{database}{install_number};
        $dsn = "DBI:mysql:database=${dbName};host=${dbHost};port=${dbPort};mysql_connect_timeout=3";
        $dbh = DBI->connect($dsn, $dbUser, $dbPass) || die "Database connection not made: $DBI::errstr";
        
        if (exists($main->{settings}{woltlab_suite_integration}{cookie_prefix}) && $main->{settings}{woltlab_suite_integration}{cookie_prefix} ne '') {
            my $wscCookie = $main->{settings}{woltlab_suite_integration}{cookie_prefix} . 'cookieHash';
            
            if (exists($main->{cookie}{$wscCookie}) && $main->{cookie}{$wscCookie} ne '') {
                $wscSessionID = $main->{cookie}{$wscCookie};
            } else {
                $main->fatal_error('nopermission');
            }
        } else {
            $main->fatal_error('bad_config');
        }
        
        if (exists($main->{settings}{woltlab_suite_integration}{use_wsc_profile})) {
            $useWscProfile = $main->{settings}{woltlab_suite_integration}{use_wsc_profile};
        }
    } else {
        $main->fatal_error('bad_config');
    }
    if ($wscSessionID ne '') {
        my $externalUser = getExternalLogin();
        if (defined($externalUser)) {
            unless ($environment->{has_uncrypted_password}) {
                $environment->{name} = $externalUser->{name};
                $environment->{is_username} = 1;
                $environment->{has_password} = $self;
            }
        }
    } else {
        $main->fatal_error('nopermission');
    }
}
sub checkPassword {
    return 1;
}
sub generateUser {
    my ($self, $main, $user) = @_;
    my $externalUser = getExternalUser();
    if (defined($externalUser)) {
        $externalUser->{password} = '';
        $main->{runtime}{allow_registration} = 1;
        $main->addUser($externalUser);
        return $main->loadUser($externalUser->{name});
    }
    else {
        $main->fatal_error('nopermission');
    }
}
sub checkLogin {
    my ($self, $main, $user, $room) = @_;
    my $externalUser = getExternalUser();
    if (defined($externalUser)) {
        foreach my $key (keys %$externalUser) {
            $user->{$key} = $externalUser->{$key};
        }
        foreach (keys %{$main->{settings}{default}}) {
            $user->{$_} = $main->{settings}{default}{$_} unless exists($user->{$_});
        }
        $user->{registration} = $main->{runtime}{now} unless exists($user->{registration});
    }
    else {
        $main->fatal_error('nopermission');
    }
}
sub getExternalLogin {
    if ($wscSessionID ne '') {
        my $user = {};
        my $sth;
        # Retrieve user ID from a given security token
        $sth = $dbh->prepare("SELECT userID FROM wcf${wscInstallNumber}_session WHERE sessionID = ?");
        $sth->execute($wscSessionID);
        $userID = $dbh->selectrow_array($sth);
        if ($userID > 0) {
            $sth = $dbh->prepare("SELECT username FROM wcf${wscInstallNumber}_user WHERE userID = ?");
            $sth->execute($userID);
            $user->{name} = $dbh->selectrow_array($sth);
            $dbh->disconnect();
            $sth->finish();
            return $user;
        }
    }
    $dbh->disconnect();
    return undef;
}
sub getExternalUser {
    if ($userID > 0) {
        my $user = {};
        my $sth;
        my ($main) = @_;
        my @row;
        # Retrieve basic user information
        $sth = $dbh->prepare("SELECT username, password, email FROM wcf${wscInstallNumber}_user WHERE userID = ? AND activationCode = 0 AND banned = 0");
        $sth->execute($userID);
        while (@row = $sth->fetchrow_array) {
            $user->{wscUserId} = $userID;
            $user->{nick} = $row[0];
            $user->{password} = crypt($row[1], $main->{settings}{pwseed});
            $user->{email} = $row[2];
        }
        $sth = $dbh->prepare("SELECT groupID FROM wcf${wscInstallNumber}_user_to_group WHERE userID = ?");
        $sth->execute($userID);
        my $groupIDs = $sth->fetchall_arrayref();
        # Chat / WSC user group mapping
        #
        # -1 / 2 = Guest
        #  0 / 3 = User
        # 10 / 4 = Chat master
        if (4 ~~ $groupIDs) {
            $user->{group} = 10;
            $user->{tempgroup} = 10;
        }
        elsif (3 ~~ $groupIDs) {
            $user->{group} = 0;
            $user->{tempgroup} = 0;
        }
        if ($useWscProfile == 0 && $user->{group} >= 0) {
            my ($birthdayFieldID, $genderFieldID, $homePageFieldID) = 0;
            # Retrieve ID for birthday option field
            $sth = $dbh->prepare("SELECT optionID FROM wcf${wscInstallNumber}_user_option WHERE optionName = ?");
            $sth->execute('birthday');
            $birthdayFieldID = $dbh->selectrow_array($sth);
            # Retrieve ID for gender option field
            $sth = $dbh->prepare("SELECT optionID FROM wcf${wscInstallNumber}_user_option WHERE optionName = ?");
            $sth->execute('gender');
            $genderFieldID = $dbh->selectrow_array($sth);
            # Retrieve ID for homepage option field
            $sth = $dbh->prepare("SELECT optionID FROM wcf${wscInstallNumber}_user_option WHERE optionName = ?");
            $sth->execute('homepage');
            $homePageFieldID = $dbh->selectrow_array($sth);
            # Select option field values for the given user
            $sth = $dbh->prepare("SELECT userOption${birthdayFieldID}, userOption${genderFieldID}, userOption${homePageFieldID} FROM wcf${wscInstallNumber}_user_option_value WHERE userID = ?");
            $sth->execute($userID);
            # Process option field values and assign them to the given user
            while (@row = $sth->fetchrow_array) {
                my $date = $row[0];
                my ($year, $month, $day) = split /\-/, $date;
                $user->{birth_date} = "${day}.${month}.${year}";
                $user->{gender} = $row[1];
                $user->{homepage} = $row[2];
                ($user->{homepagetitle} = $row[2]) =~ s/^https?:\/\///i;
            }
        }
        $sth->finish();
        $dbh->disconnect();
        return $user;
    }
    $dbh->disconnect();
    return undef;
}