#!/usr/bin/perl
#
# Automated Report Availability 
#
# $Id: Autoreport.pl,v 1.2 2010/01/11 13:16:09 gci Exp $
# Run as www. Call this from an entry in /etc/cron.d/loncapa
#
# www /home/httpd/perl/Autoreport.pl
#

    use strict;
    use lib '/home/httpd/lib/perl';
    use Apache::lonnet;
    use Apache::loncommon;
    use Apache::lonmsg;
    use Apache::lonlocal;
    use LONCAPA::Configuration;
    use LONCAPA qw(:DEFAULT :match);

# Determine the library server's domain and hostID
    my $perlvarref = &LONCAPA::Configuration::read_conf('loncapa.conf');
    my $logfile = $$perlvarref{'lonDaemons'}.'/logs/autoreport.log';
    my @hostids = &Apache::lonnet::current_machine_ids();

# Determine the present time;
    my $now = time();
    my $output;
    $env{'user.domain'} = 'gci';
    # Initialize language handler
    &Apache::lonlocal::get_language_handle();
    # Determine the courses
    my %courses = 
        &Apache::lonnet::courseiddump('gcitest','.',1,'.','.','.',1,\@hostids,'Course');
    foreach my $key (sort(keys(%courses))) {
        my %args = (
                     one_time => 1,
                   );
# Get course settings
        my %settings = &Apache::lonnet::coursedescription($key,\%args);
        my $cnum = $settings{'num'};
        next if ($settings{'domain'} ne 'gcitest');
        next if ($settings{'internal.autoreportmailsent'});
        my $courseopt=&Apache::lonnet::get_courseresdata($cnum,'gcitest');
        my $duedate = $courseopt->{$key.'.0.duedate'};
        my %courseenv;
        if ($duedate < $now) {
            my $numsent = &send_message($settings{'internal.courseowner'},
                                     $settings{'description'},$cnum,'gcitest');
            $output .= &mt('[quant,_1,message] sent with statistics link for concept test: [_2] owned by [_3].',$numsent,$settings{'description'}.' ('.$cnum.':gcitest)',$settings{'internal.courseowner'})."\n";
            $courseenv{'internal.autoreportmailsent'} = 1;
            my $putresult = &Apache::lonnet::put('environment',\%courseenv,'gcitest',$cnum);
            if ($putresult eq 'ok') {
                $output .= &mt('autoreportmailsent item set to [_1] for [_2].',$courseenv{'internal.autoreportmailsent'},$settings{'description'}.' ('.$cnum.':gcitest)')."\n\n";
            } else {
                $output .= &mt('An error - [_1] occurred storing autoreportmailsent in the course environment for [_2].',$putresult,$settings{'description'}.' ('.$cnum.':gcitest)')."\n\n";
            }
        }
    }
    delete($env{'user.domain'});
    if ($output) {
        if (open (my $fh,">>$logfile")) {
            print $fh "********************\n".localtime(time)." Autoreport messages start --\n".$output."-- ".localtime(time).' '.&mt('Autoreport messages end')."\n*******************\n\n";
            close($fh);
        }
    }

sub send_message {
    my ($owner,$cdesc,$cnum,$dom) = @_;
    my ($ownername,$ownerdom) = split(':',$owner);
    my $numsent = 0;
    if (($ownername =~ /^$match_username$/) &&
        ($ownerdom =~ /^$match_domain$/)) {
        $env{'form.can_reply'} = 'N';
        $env{'user.name'} = $ownername;
        $env{'user.domain'} = $ownerdom;
        $env{'user.home'} = &Apache::lonnet::homeserver($env{'user.name'},$env{'user.domain'});
        $env{'request.course.id'} = $dom.'_'.$cnum;
        my $subject = &mt('GCI Concept Test Report in [_1]',$cdesc);
        my $message = &mt('Aggregated test performance data are available from the Overall Statistics Page of your GCI Concept Test: [_1]:',$cdesc).'<br /><br />'."\n\n".
                      &mt('The following link will take you to the statistics page for the Concept Test: ').'<br /><br />'."\n\n".
                      'http://gci.lite.msu.edu/adm/login?username='.$ownername.'&symb=%2fadm%2fstatistics&role=cc.%2f'.$dom.'%2f'.$cnum."\n\n";
        my @recusers;
        my @recudoms;
        my %cc_hash = &Apache::lonnet::get_my_roles($cnum,$dom,'','',['cc']);
        my @to_notify;
        my $msgcc = {};
        foreach my $key (keys(%cc_hash)) {
            if ($key =~ /^($match_username:$match_domain):cc$/) {
                my $cc = $1;
                unless (grep(/^\Q$cc\E/,@to_notify)) {
                    push(@to_notify,$cc);
                }
            }
        }
        if (@to_notify) {
            foreach my $cc (@to_notify) {
                my ($ccname,$ccdom) = split(/:/,$cc);
                unless((grep(/^\Q$ccname\E$/,@recusers)) && (grep(/^\Q$ccdom\E$/,@recudoms))) {
                    push(@recusers,$ccname);
                    push(@recudoms,$ccdom);
                    $msgcc->{$ccname.':'.$ccdom}='';
                    $numsent ++;
                }
            }
        }
        if ($numsent) {
            my %reciphash = (
                             cc => $msgcc,
                            );
            my %sentmessage;
            my $stamp = time;
            my $msgcount = &Apache::lonmsg::get_uniq();
            &Apache::lonmsg::process_sent_mail($subject,'',$numsent,$stamp,$env{'user.name'},$env{'user.domain'},$msgcount,$cnum,$$,$message,\@recusers,\@recudoms);
            my ($recipid,$recipstatus) =
                &Apache::lonmsg::store_recipients($subject,
                    $env{'user.name'},$env{'user.domain'},\%reciphash);
            foreach my $recip (sort(keys(%{$msgcc}))) {
                my ($ccname,$ccdom) = split(/:/,$recip);
                my $status =
                    &Apache::lonmsg::user_normal_msg($ccname,$ccdom,$subject,$message,undef,undef,undef,1,\%sentmessage,undef,undef,undef,1,$recipid);
            }
            delete($env{'form.can_reply'});
        }
        delete($env{'user.name'});
        delete($env{'user.home'});
        delete($env{'request.course.id'});
    }
    return $numsent;
}

