#!%PERL%
# Copyright (c) vhffs project and its contributors
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without 
# modification, are permitted provided that the following conditions 
# are met:
#
# 1. Redistributions of source code must retain the above copyright 
#   notice, this list of conditions and the following disclaimer.
#2. Redistributions in binary form must reproduce the above copyright
#   notice, this list of conditions and the following disclaimer in 
#   the documentation and/or other materials provided with the 
#   distribution.
#3. Neither the name of vhffs nor the names of its contributors 
#   may be used to endorse or promote products derived from this 
#   software without specific prior written permission.
#
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
#"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
#LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 
#FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 
#COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 
#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 
#BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
#LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 
#CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
# POSSIBILITY OF SUCH DAMAGE.

use strict;
use utf8;

package Vhffs::Panel::User;

use DBI;
use POSIX qw(locale_h);
use locale;
use Locale::gettext;
use Encode;

use Vhffs::User;
use Vhffs::Main;
use Vhffs::Panel::Main;

=pod

=head1 NAME

Vhffs::Panel::User - Light weight user method.

Provides methods which can be used when you need informations
about users put don't want to use heavy objects.

=head1 CONSTANTS

=head2 RELATION_OWNER

Constant to pass to C<get_groups> to restrict fetched groups
to owned projects.

=head2 RELATION_CONTRIB

Constant to pass to C<get_groups> to restrict fetched groups
to projects where user is not the owner.

=cut

our $RELATION_OWNER = 1;
our $RELATION_CONTRIB = 2;

=pod
=head1 METHODS
=cut

=head2 get_last_users

Fetches and returns an array of hashrefs {username, firstname, lastname,
groups => {groupname}} containing information about the last ten users of the
platform

=cut

sub get_last_users
{
	my ($main) = @_;

	my $sql = 'SELECT u.uid, u.username, u.firstname, u.lastname '.
		'FROM vhffs_users u '.
		'INNER JOIN vhffs_object o ON o.object_id=u.object_id '.
		'WHERE o.state=? ORDER BY o.date_creation DESC LIMIT 10';
	
	my $dbh = $main->get_db_object();
    
    my $users = $dbh->selectall_hashref($sql, 'uid', undef, Vhffs::Constants::ACTIVATED);
	
	fill_groups($main, $users);
	
	my @val = values(%$users);
	
	return \@val;	
}

sub search {
	my ($main, $name) = @_;

	my $sql;
    my @params;
    my $users = [];

    if( defined $name ) {
		$sql = 'SELECT u.username, u.firstname, u.lastname , o.state FROM vhffs_users u INNER JOIN vhffs_object o ON o.object_id = u.object_id WHERE u.username LIKE ? OR u.firstname ILIKE ? OR u.lastname ILIKE ?';
        push(@params, '%'.lc($name).'%', '%'.$name.'%', '%'.$name.'%');
	} else {
        $sql = 'SELECT u.username, u.firstname, u.lastname , o.state FROM vhffs_users u INNER JOIN vhffs_object o ON o.object_id = u.object_id';
	}

	my $dbh = $main->get_db_object();
    my $sth = $dbh->prepare($sql);
    return undef unless($sth->execute(@params));

    while(my $u = $sth->fetchrow_hashref('NAME_lc')) {
        $u->{state} = Vhffs::Functions::status_string_from_status_id($u->{state});
        $u->{firstname} = $u->{firstname};
        $u->{lastname} = $u->{lastname};
        push(@$users, $u);
    }
    return $users;
}

=head2 public_search

    $users = Vhffs::Panel::User::public_search($vhffs, $username, $start);

Returns all users whose username contains C<$username>.

=cut

sub public_search {
    my ($main, $username, $start) = @_;
    my $result = {};

    my $select_clause = 'SELECT u.uid, u.username, u.firstname, u.lastname ';
    my $sql = 
    	'FROM vhffs_users u '.
    	'INNER JOIN vhffs_object o ON o.object_id = u.object_id '.
    	'WHERE o.state = ? ';
    my @params;
    push @params, Vhffs::Constants::ACTIVATED;

    if(defined $username) {
        # usernames are enforced in lowercase
        $sql .= ' AND username ILIKE ?';
        push @params, '%'.$username.'%';
    }

    my $limit = ' LIMIT 10';
    $limit .= ' OFFSET '.($start * 10) if(defined $start); 
    
    my $dbh = $main->get_db_object();
    
    my $users = $dbh->selectall_hashref($select_clause.$sql.' ORDER BY u.username '.$limit, 'uid', undef, @params);
	
	my ($count) = $dbh->selectrow_array('SELECT COUNT(*) '.$sql, undef, @params);
	
	fill_groups($main, $users);
	
	my @val = values(%$users);
	
	# We've to sort manualy since we use a hash
	@val = sort { $a->{username} cmp $b->{username}} @val;
	
	return (\@val, $count);
}

=head2 fill_groups

	Vhffs::Panel::User::fill_groups($main, $users);

C<$users> is a HASHREF indexed by uid containing at least
the C<uid> field. It is modified inplace to add a field
C<groups> containing the names of the groups the user belongs
to.

=cut 

sub fill_groups {
	my ($main, $users) =@_;
	
	my $dbh = $main->get_db_object();
	my @uids = ();
	
	foreach my $uid(keys(%$users)) {
		push @uids, $uid;
	}
	
	# Fetch all groups in one shot
	my $sql = 'SELECT g.groupname, u.uid FROM vhffs_groups g '.
		'INNER JOIN vhffs_user_group ug ON ug.gid = g.gid '.
		'INNER JOIN vhffs_users u ON u.uid = ug.uid '.
		'WHERE g.groupname != u.username AND u.uid IN ( '.join(', ', @uids).') '.
		'ORDER BY g.groupname';
	
	my $groups = $dbh->selectall_arrayref($sql, { Slice => {}});
	my $i = 0;
	
	foreach my $g(@$groups) {
		if(!exists $users->{$g->{uid}}{groups}) {
			$users->{$g->{uid}}{groups} = [];
		}
		push(@{$users->{$g->{uid}}{groups}}, $g->{groupname});
	}
}

sub fetch_users_and_groups {
    my ($main, $sql, @params) = @_;
    my @users;

    my $dbh = $main->get_db_object;
    my $sth = $dbh->prepare($sql);
    $sth->execute( @params );
    $sql = 'SELECT g.groupname FROM vhffs_groups g INNER JOIN vhffs_user_group ug ON ug.gid = g.gid WHERE ug.uid = ? AND g.groupname != ?';
    my $ssth = $dbh->prepare($sql);
    while(my $row = $sth->fetchrow_hashref) {
       $ssth->execute($row->{uid}, $row->{username});
       $row->{groups} = $ssth->fetchall_arrayref({});
       push @users, $row;
    }

    return \@users;

}

sub set_lang
{
	my $user = shift;
	my $lang = shift;
	return -1 unless defined $user and defined $lang;

	my $sql = 'UPDATE vhffs_users SET language = ? WHERE uid = ?';
	my $sth = $user->{db}->prepare($sql);
	$sth->execute($lang, $user->get_uid) or return -1;
	$user->{'language'} = $lang;
	setlocale(LC_ALL, $lang);
}


sub set_theme
{
	my $user = shift;
	my $theme = shift;
	return -1 unless defined $user and defined $theme;

	my $sql = 'UPDATE vhffs_users SET theme = ? WHERE uid = ?';
	my $dbh = $user->{db};
	my $sth = $dbh->prepare($sql);
	$sth->execute($theme, $user->get_uid) or return -1;
	$user->{'theme'} = $theme;
}

sub get_lang
{
	my $user = shift;
	return -1 if( ! defined $user );
	return $user->get_lang;
}


sub get_theme
{
	my $user = shift;
	return -1 if( ! defined $user );
	my $theme = $user->get_theme;
	$theme = $user->get_main->get_config->get_panel->{'default_theme'} unless defined $theme;
	return $theme;
}


sub get_shell
{
	my $user = shift;
	return -1 if( ! defined $user );
	return $user->get_shell;
}


sub list_shells
{
	my $vhffs = shift;
	return -1 unless defined $vhffs;
	return split(/ /,$vhffs->get_config->get_users->{'available_shells'});
}


sub default_shell
{
	my $vhffs = shift;
	return -1 unless defined $vhffs;
	return $vhffs->get_config->get_users->{'default_shell'};
}


=pod

=head2 get_groups

    my $groups = Vhffs::Panel::User::get_groups($user);
    print $groups->[0]->{project};

Returns an array reference which contains all the groupname for
a given user whose uid is C<$uid>.

An optional second parameter can be used to restrict project
list to owned or contributed project

=cut

sub get_groups {
    my $user = shift;
    my $relation = shift;
    my @params;
    

    my $groups = [];
    my $sql;
    push @params, $user->get_uid;
    if( defined $relation) {
        if( $relation == $RELATION_OWNER ) {
            $sql = 'SELECT g.groupname, o.state , o.object_id AS oid FROM vhffs_groups g INNER JOIN vhffs_object o ON o.object_id = g.object_id WHERE o.owner_uid = ? AND g.groupname != ? ORDER BY g.groupname';
            push @params, $user->get_username;
        } else {
            $sql = 'SELECT g.groupname, o.state , o.object_id AS oid FROM vhffs_groups g INNER JOIN vhffs_user_group ug ON g.gid=ug.gid INNER JOIN vhffs_object o ON o.object_id = g.object_id WHERE ug.uid=? AND o.owner_uid != ug.uid ORDER BY g.groupname';
        }
    } else {
        $sql = 'SELECT g.groupname, o.state , o.object_id AS oid FROM vhffs_groups g INNER JOIN vhffs_user_group ug ON g.gid=ug.gid INNER JOIN vhffs_object o ON o.object_id = g.object_id WHERE ug.uid=? ORDER BY g.groupname';
    }
    my $sth = $user->get_db_object->prepare( $sql );
    return undef if( ! $sth->execute(@params) );
    while(my $g = $sth->fetchrow_hashref) {
        $g->{active} = ($g->{state} == Vhffs::Constants::ACTIVATED);
        $g->{refused} = ($g->{state} == Vhffs::Constants::VALIDATION_REFUSED);
        $g->{state} = Vhffs::Functions::status_string_from_status_id($g->{state});
        push @$groups, $g;
    }
    return $groups;
}

1;
