#!/usr/bin/perl
#
# Automated Userinfo update script
# $Id: Autoupdate.pl,v 1.5 2007/05/11 17:25:28 raeburn Exp $
#
# Copyright Michigan State University Board of Trustees
#
# This file is part of the LearningOnline Network with CAPA (LON-CAPA).
#
# LON-CAPA 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.
#
# LON-CAPA 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 LON-CAPA; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# /home/httpd/html/adm/gpl.txt
#
# http://www.lon-capa.org/
#
    use strict;
    use lib '/home/httpd/lib/perl';
    use localenroll;
    use Apache::lonnet;
    use Apache::loncommon;
    use Apache::lonlocal;
    use LONCAPA::Configuration;
    use LONCAPA;

    my $perlvarref = LONCAPA::Configuration::read_conf('loncapa.conf');
    my $hostid = $perlvarref->{'lonHostID'}; 
    my @info = ('inststatus','lockedname','lastname','firstname','id');
    # find out which users we need to examine
    my @domains = sort(&Apache::lonnet::current_machine_domains());
    foreach my $dom (@domains) {
        my $primaryhost_id = &Apache::lonnet::domain($dom,'primary');
        if ($primaryhost_id ne $hostid) {
            next;
        } 
        my %domconfig = &Apache::lonnet::get_dom('configuration',['autoupdate'],
                                                 $dom);
        #only run if configured to
        my $run_update = 0;
        my $settings;
        if (ref($domconfig{'autoupdate'}) eq 'HASH') {
            $settings = $domconfig{'autoupdate'};
            if ($settings->{'run'} eq '1') {
                $run_update = 1;
            }
        }
        next if (!$run_update);
        # get user information
        my (%instusers,%instids);
        next if (&localenroll::allusers_info($dom,\%instusers,\%instids) ne 'ok');
        my (%users,%unamechg,%possnames);
        my @types = ('active','future');
        my @roles = ('st');
        my @cdoms = ($dom);
        my $dir = $Apache::lonnet::perlvar{lonUsersDir}.'/'.$dom;
        &descend_tree($dir,0,\%users);
        foreach my $uname (keys(%users)) {
            my %userhash = &Apache::lonnet::userenvironment($dom,$uname,@info);
            my (@inststatuses);
            if (!$userhash{'internalname'}) {
                if (defined($instusers{$uname})) {
                    (my $insttypechg,@inststatuses) = 
                       &affiliations_check(\%userhash,$instusers{$uname});
                    if ($insttypechg) {
                        my $inststatusstr = join(':',&escape(@inststatuses));
                        my %statushash = ( inststatus => $inststatusstr );
                        my $statusres = &Apache::lonnet::put('environment',\%statushash,$dom,$uname);
                    }
                }
            }
            if (!$userhash{'lockedname'} && !$userhash{'internalname'}) {
                if (defined($instusers{$uname})) {
                    my (@fields,%changes,$changed);
                    if (@inststatuses > 0) {
                        foreach my $type (@inststatuses) {
                            if (ref($settings->{fields}{$type}) eq 'ARRAY') {
                                foreach my $field (@{$settings->{fields}{$type}}) {
                                    if (!grep(/^\Q$field\E$/,@fields)) {
                                        push(@fields,$field);
                                    }
                                }
                            } 
                        }
                    } else {
                        if (ref($settings->{fields}{'default'}) eq 'ARRAY') {
                            @fields = @{$settings->{fields}{'default'}};
                        }
                    }
                    foreach my $field (@fields) { 
                        if ($userhash{$field} ne $instusers{$uname}{$field}) {
                            $changed = 1;
                            if ($settings->{'classlists'} eq 'yes') { 
                                if ($field eq 'id') {
                                    $changes{'id'} = 1;
                                } elsif ($field eq 'lastname' || $field eq 'firstname' || $field eq 'middlename' || $field eq 'gen') {
                                    $changes{'fullname'} = 1;
                                }
                            }
                        }  
                    }
                    # Make the change
                    if ($changed) {
                        my %userupdate;
                        foreach my $field (@fields) {
                            $userupdate{$field} = $instusers{$uname}{$field};
                        }
                        my $modresult = &Apache::lonnet::modifyuser($dom,$uname,$userupdate{'id'},undef,undef,$userupdate{'firstname'},$userupdate{'middlename'},$userupdate{'lastname'},$userupdate{'generation'},1);
                        if ($modresult eq 'ok') {
                            if ($settings->{'classlists'} eq 'yes') {
                                if ($changes{'id'} || $changes{'fullname'}) {
                                    my %roleshash = 
                                        &Apache::lonnet::get_my_roles($uname,
                                                  $dom,'userroles',\@types,\@roles,\@cdoms);
                                    foreach my $item (%roleshash) {
                                        my ($cnum,$cdom,$role) = split(/:/,$item);
                                        my ($start,$end) = split(/:/,$roleshash{$item});
                                        if (&Apache::loncommon::is_course($cdom,$cnum)) {
                                            my $result = &update_classlist($cdom,$cnum,$dom,$uname,\%userupdate);
                                        }
                                    }
                                }
                            }
                        }
                    }
                } else {
                    # check if the username has changed
                    if (defined($instids{$userhash{'id'}})) {
                        if (ref($instids{$userhash{'id'}}) eq 'ARRAY') {
                            foreach my $name (@{$instids{$userhash{'id'}}}) {
                                if (!exists($users{$name})) {
                                    push(@{$possnames{$uname}},$name);
                                }
                            }
                        } else {
                            if (!exists($users{$instids{$userhash{'id'}}})) {
                                $unamechg{$uname} = $instids{$userhash{'id'}};
                                print &mt('Username change to [_1] detected for [_2] in domain [_3].',$unamechg{$uname},$uname,$dom)."\n";
                            }
                        }
                    }
                }
            }
        }
        if (keys(%possnames) > 0) {
            foreach my $uname (keys(%possnames)) {
                my $altnames = join(' or ',@{$possnames{$uname}});
                print &mt('Possible username change to [_1] detected for [_2] in domain [_3].',$altnames,$uname,$dom)."\n";
            }
        }
    }

sub descend_tree {
    my ($dir,$depth,$alldomusers) = @_;
    if (-d $dir) {
        opendir(DIR,$dir);
        my @contents = grep(!/^\./,readdir(DIR));
        closedir(DIR);
        $depth ++;
        foreach my $item (@contents) {
            if ($depth < 4) {
                &descend_tree($dir.'/'.$item,$depth,$alldomusers);
            } else {
                if (-e $dir.'/'.$item.'/environment.db') {
                    
                    $$alldomusers{$item} = '';
                }
            }
        }
    }
}

sub update_classlist {
    my ($cdom,$cnum,$udom,$uname,$user) = @_;
    my ($uid,$fullname,$classlistentry);
    my $fullname = 
        &Apache::lonnet::format_name($user->{'first'},$user->{'middle'},
                                     $user->{'last'},$user->{'gene'},'lastname');
    my %classhash = &Apache::lonnet::get('classlist',[$uname.':'.$udom],
                                         $cdom,$cnum);
    my @classinfo = split(/:/,$classhash{$uname.':'.$udom});
    my $ididx=&Apache::loncoursedata::CL_ID() - 2;
    my $nameidx=&Apache::loncoursedata::CL_FULLNAME() - 2;
    for (my $i=0; $i<@classinfo; $i++) {
        if ($i == $ididx) {
            if (defined($user->{'id'})) {
                $classlistentry .= $user->{'id'}.':';
            } else {
                $classlistentry .= $classinfo[$i].':';
            }
        } elsif ($i == $nameidx) {
            $classlistentry .= $fullname.':';
        } else {
            $classlistentry .= $classinfo[$i].':';
        }
    }
    $classlistentry =~ s/:$//;
    my $reply=&Apache::lonnet::cput('classlist',
                                    {"$uname:$udom" => $classlistentry},
                                    $cdom,$cnum);
    if (($reply eq 'ok') || ($reply eq 'delayed')) {
        return 'ok';
    } else { 
        return 'error: '.$reply;
    }
}

sub affiliations_check {
    my ($userhash,$insthashref) = @_;
    my (@inststatuses,$insttypechg);;
    if (ref($insthashref) eq 'HASH') {
        if (ref($insthashref->{type}) eq 'ARRAY') {
            @inststatuses = @{$insthashref->{type}};
        }
    }
    my @currstatuses = &unescape(split(/:/,$userhash->{'inststatus'}));
    foreach my $status (@inststatuses) {
        if (!grep/^\Q$status\E/,@currstatuses) {
            $insttypechg = 1;
        }
    }
    if (!$insttypechg) {
        foreach my $status (@currstatuses) {
            if (!grep/^\Q$status\E/,@inststatuses) {
                $insttypechg = 1;
            }
        }
    }
    return ($insttypechg,@inststatuses);
}

