[LON-CAPA-cvs] cvs: modules /raeburn Enrollment.pm

raeburn lon-capa-cvs@mail.lon-capa.org
Tue, 02 Dec 2003 00:32:39 -0000


This is a MIME encoded message

--raeburn1070325159
Content-Type: text/plain

raeburn		Mon Dec  1 19:32:39 2003 EDT

  Added files:                 
    /modules/raeburn	Enrollment.pm 
  Log:
  Module - LONCAPA::Enrollment used by the automated enrollment script - Autoenroll.pl and the "update roster now" routine in Apache::lonpopulate to perform adds and drops from a LON-CAPA course.  Includes support for multiple sections, and crosslistings, with section/groupID in LON-CAPA set via options in Apache::loncreatecourse (Domain Coordinator) or Apache::lonpopulate (Course Coordinator).  Includes a routine to pass the classlist data (in XML format) generated by localenroll.pm.  Separation of retrieval of institutional data (localenroll.pm) and LON-CAPA course enrollment routines (included in this module - LONCAPA::Enrollment) allows different domains to create their own localenroll.pm code to generate classlists in specified XML format from their institutional data sources.  SPR 1/12/2003. 
  
  
--raeburn1070325159
Content-Type: text/plain
Content-Disposition: attachment; filename="raeburn-20031201193239.txt"


Index: modules/raeburn/Enrollment.pm
+++ modules/raeburn/Enrollment.pm
package LONCAPA::Enrollment;

use Apache::loncoursedata;
use Apache::lonnet;
use HTML::Entities;
use XML::Simple;
use LONCAPA::Configuration;

sub update_LC {
    my ($dom,$crs,$adds,$drops,$startdate,$enddate,$authtype,$autharg,$classesref,$groupref,$logmsg,$context) = @_; 
# Get current LON-CAPA student enrollment for this class
    my $configvars = &LONCAPA::Configuration::read_conf('loncapa.conf');
    my $cid = $dom."_".$crs;
    my $roster = &Apache::loncoursedata::get_classlist($cid,$dom,$crs);
    my $cend = &Apache::loncoursedata::CL_END;
    my $cstart = &Apache::loncoursedata::CL_START; 
    my $stuid=&Apache::loncoursedata::CL_ID;
    my $sec=&Apache::loncoursedata::CL_SECTION;
    my $status=&Apache::loncoursedata::CL_STATUS;
    my $type=&Apache::loncoursedata::CL_TYPE;
    my @localstudents = ();
    my $currlist;
    foreach my $uname (keys %{$roster} ) {
        if ($uname =~ m/^(.+):$dom$/) {
            push @localstudents, $1;
            @{$$currlist{$1}} = @{$$roster{$uname}};
        }
    } 
    my $linefeed = '';
    my $addresult = '';
    my $dropresult = '';
    if ($context eq "updatenow") {
        $linefeed = "</li>\n<li>"; 
    } elsif ($context eq "automated") {
        $linefeed = "\n";
    }
    my $enrollcount = 0;
    my $dropcount = 0;

# Get mapping of IDs to usernames for current LON-CAPA student enrollment for this class 
    my @LCids = ();
    my %unameFromLCid = ();
    foreach my $uname (sort keys %{$currlist}) {
        my $stuID = $$currlist{$uname}[$stuid];
        if (!grep/^$stuID$/,@LCids) {
            push @LCids, $stuID;
            @{$unameFromLCid{$stuID}} = ();
        }
        push @{$unameFromLCid{$stuID}},$uname;
    }
 
# Get latest institutional enrollment for this class.
    my %allenrolled = ();
    my @reg_students = ();
    my %place = ();
    $place{'autharg'} = &CL_autharg();
    $place{'authtype'} = &CL_authtype();
    $place{'email'} = &CL_email();
    $place{'enddate'} = &CL_enddate();
    $place{'firstname'} = &CL_firstname();
    $place{'generation'} = &CL_generation();
    $place{'groupID'} = &CL_groupID();
    $place{'lastname'} = &CL_lastname();
    $place{'middlename'} = &CL_middlename();
    $place{'startdate'} = &CL_startdate();
    $place{'studentID'} = &CL_studentID();
    my %ucount = ();
    my %enrollinfo = ();
    foreach my $class (@{$classesref}) {
        my %enrolled = ();
        &parse_classlist($$configvars{'lonDaemons'},$dom,$crs,$class,\%place,$$groupref{$class},\%enrolled);
        foreach my $uname (sort keys %enrolled ) {
            if (!grep/^$uname$/,@reg_students) {
                push @reg_students,$uname;
                $ucount{$uname} = 0;
                @{$allenrolled{$uname}} = ();
            }
            @{$allenrolled{$uname}[$ucount{$uname}]} = @{$enrolled{$uname}};
            $ucount{$uname} ++;
        }
    }

# Check for multiple sections for a single student 
    my @okusers = ();
    foreach my $uname (@reg_students)  {
        if (@{$allenrolled{$uname}} > 1) {
            my @sections = ();
            my $saved;
            for (my $i=0; $i<@{$allenrolled{$uname}}; $i++) {
                my @stuinfo = @{$allenrolled{$uname}[$i]};
                my $secnum = $stuinfo[ $place{'groupID'} ];
                print STDERR "Section $secnum for $uname\n";
                unless ($secnum eq '') {
                    unless (grep/^$secnum$/,@sections) {
                        $saved = $i; 
                        push @sections,$secnum;
                    }
                }
            }
            if (@sections == 0) {
                @{$enrollinfo{$uname}} = @{$allenrolled{$uname}[0]};
                push @okusers, $uname;
            }
            elsif (@sections == 1) {
                @{$enrollinfo{$uname}} = @{$allenrolled{$uname}[$saved]};
                push @okusers, $uname;
            }
            elsif (@sections > 1) {
                $logmsg =  "$uname appears in classlists for multiple sections of $crs -";
                foreach (@sections) {
                    $logmsg .= " $_,";
                }
                chop($logmsg);
                $logmsg .= " No automated enrollment action taken for this student.\n";
            }
        } else {
            @{$enrollinfo{$uname}} = @{$allenrolled{$uname}[0]};
            push @okusers, $uname;
        }
    }
# Get mapping of student IDs to usernames for users in institutional data for this class  
    my @allINids = ();
    foreach my $uname (@okusers) {
        my @stuinfo = @{$enrollinfo{$uname}};
        my $stuID = $stuinfo[ $place{'studentID'} ];
        if (grep/^$stuID$/,@allINids)  {
            push @{$unameFromINid{$stuID}},$uname;
        } else {
            push @allINids, $stuID;
            @{$unameFromINid{$stuID}} = $uname; 
        }
    }
# Compare IDs with existing LON-CAPA enrollment for this class
    foreach my $uname (@okusers) {
        my %uidhash=&Apache::lonnet::idrget($dom,$uname);
        my @stuinfo = @{$enrollinfo{$uname}};
        if (grep/^$uname$/,@localstudents) {
# Check for studentID changes
            if ( ($uidhash{$uname}) && ($uidhash{$uname} !~ /error\:/) )  {
                unless ( ($uidhash{$uname}) eq ($stuinfo[ $place{studentID} ]) ) {
                    $logmsg .= "Change in ID for $uname in class: $crs. StudentID in LON-CAPA system is $uidhash{$uname}, StudentID in institutional data is $stuinfo[ $place{studentID} ]\n"; 
                }
            }

# Check for section changes
            unless ($$currlist{$uname}[$sec] eq $stuinfo[ $place{groupID} ]) {
                print STDERR "Found a section difference for $uname - ".$$currlist{$uname}[$sec] ."versus ".$stuinfo[ $place{groupID} ]."\n";
                if ($$currlist{$uname}[$type] eq "auto") {
                    my $modify_section_result = &Apache::lonnet::modifystudent($dom,$uname,'','','',undef,undef,undef,undef,$$currlist{$uname}[$sec],$nowtime,undef,undef,undef,undef);
                    if ($modify_section_result !~ /^ok/) {
                        $logmsg .= "An error occured during the attempt to expire the $uname from the old section $$currlist{$uname}[$sec]\n";
                    }

# Assign the role of student in the new section
                    my $uurl='/'.$cid;
                    $uurl=~s/\_/\//g;
                    if ($stuinfo[$sec]) {
                        $uurl.='/'.$stuinfo[$sec];
                    }
                    print STDERR "Section is $uurl\n";
                    &Apache::lonnet::assignrole($dom,$uname,$uurl,"st",$stuinfo[$end],$stuinfo[ $place{start} ],"auto");
                }
            }
        }
        elsif ($uname ne '') {
# Check for changed usernames by checking studentIDs
            if ( ($stuinfo[ $place{studentID} ] ne '') && (grep/^$stuinfo[ $place{studentID} ]$/,@LCids) ) {
                if (grep/^$$currlist{$uname}[ $place{'studentID'} ]$/,@allINids) {
                    foreach my $match ( @{ $unameFromLCid{ $stuinfo[ $place{studentID} ] } }  ) {
                        if (grep/^$match$/,@okusers) {
                            $logmsg .= "A possible change in username has been detected for a student enrolled in $crs. The existing LON-CAPA classlist contains user: $uname and student ID: ".$$currlist{$uname}[ $place{studentID} ].".  This username has been dropped from the institutional classlist, but the same student ID is used for user: $match who still appears in the institutional classlist. You may need to move the student data files for user: $uname to $match\n";
                        }
                    }
                }
            } elsif ($adds == 1) {
# Add student to LON-CAPA classlist
                my $auth = $stuinfo[ $place{'authtype'} ];
                my $authparam = $stuinfo[ $place{'autharg'} ];
                my $first = $stuinfo[ $place{'firstname'} ];
                my $middle = $stuinfo[ $place{'middlename'} ];
                my $last = $stuinfo[ $place{'lastname'} ];
                my $gene = $stuinfo[ $place{'generation'} ];
                my $usec = $stuinfo[ $place{'groupID'} ];
                my $end = $stuinfo[ $place{'enddate'} ];
                my $start = $stuinfo[ $place{'startdate'} ];
                my $emailaddr = $stuinfo[ $place{'email'} ];
                my $pid = $stuinfo[ $place{'studentID'} ];

# remove non alphanumeric values from section
                $usec =~ s/\W//g;

                unless ($emailaddr =~/^[^\@]+\@[^\@]+$/) { $emailaddr =''; }
                my $emailenc = &HTML::Entities::encode($emailaddr); 

# Use course defaults where entry is absent
                if ($auth eq '') {
                    $auth =  $authtype;
                }
                if ($authparam eq '') {
                    $authparam = $autharg;
                }
                if ($end eq '') {
                    $end = $enddate;
                }
                if ($start eq '') {
                    $start = $startdate;
                }
# Clean up whitespace
                foreach (\$dom,\$uname,\$pid,\$first,\$middle,\$last,\$gene,\$usec) {
                    $$_ =~ s/(\s+$|^\s+)//g;
                }

# Check for existing account in this LON-CAPA domain for this username
                my $uhome=&Apache::lonnet::homeserver($uname,$dom);
                if ($uhome eq 'no_host') { # User does not exist
                    $create_passwd = 0;
                    if ($passwd eq '') {
# If no account exists and passwords should be generated
                        if (($authtype eq "int") || ($authtype eq "loc")) {
                            ($passwd,$create_passwd) = &create_password($authtype); }
                        } elsif ($authtype eq "krb") {
                            $passwd = $autharg;
                        } else {
                            $logmsg .= "Invalid authentication type for $uname in $crs\n";
                        }  
                    }
# Now create user.
                    my $reply=&modifystudent($$configvars{'lonHostID'},$dom,$cid,$crs,$uname,$pid,$auth,$authparam,$first,$middle,$last,$gene,$usec,$end,$start,'',undef,$emailaddr,'auto',$context);
                    if ($reply eq 'ok') {
                        $enrollcount ++;
                        $addresult .= "$first $last ($pid) - $uname enrolled in section/group $usec.".$linefeed;
                        $logmsg .= "New user $uname added successfully. ";
                        unless ($emailenc eq '') {
                            my %emailHash;
                            $emailHash{'critnotification'}  = $emailenc;
                            $emailHash{'notification'} = $emailenc;
                            my $putresult = &Apache::lonnet::put('environment',\%emailHash,$dom,$uname);
                        }
                        if ($create_passwd) {
# Send e-mail with inital password to new user at $emailaddr
                            $logmsg .= "Initial password -  - sent to $emailaddr\n";
                        } else {
                            $logmsg .= "\n";
                        }
                    } else {
                       $logmsg .= "An error occurred adding new user $uname - $reply\n";
                    }
# Add 'auto' status to classlist.db file
                } else {
# Get the user's information and authentication
                    my %userenv = &Apache::lonnet::get('environment',['firstname','middlename','lastname','generation','id','critnotification','notification'],$dom,$uname);
                    my ($tmp) = keys(%userenv);
                    if ($tmp =~ /^(con_lost|error)/i) {
                        %userenv = ();
                    }
# Get the user's e-mail address
                    if ($userenv{critnotification} =~ m/%40/) {
                        unless ($emailenc eq $userenv{critnotification}) {
                        $logmsg .= "Current critical notification e-mail - ".$userenv{critnotification}." for $uname is different to e-mail address in Institutional classlist - $emailenc\n";
                    }
                    if ($userenv{notification} =~ m/%40/) {
                        unless ($emailenc eq $userenv{critnotification}) {
                            $logmsg .= "Current standard notification e-mail - ".$userenv{notification}." for $uname is different to e-mail address in Institutional classlist - $emailenc\n";
                        }
                    }                            
                    my $krbdefdom = '';
                    my $currentauth=&Apache::lonnet::queryauthenticate($uname,$dom);
                    if ($currentauth=~/^krb(4|5):/) {
                        $currentauth=~/^krb(4|5):(.*)/;
                        $krbdefdom=$1;
                    }
                    if ($currentauth=~/^krb(4|5):/ || 
                        $currentauth=~/^unix:/ ||
                        $currentauth=~/^internal:/ ||
                        $currentauth=~/^localauth:/) {
                               
                    } else {
                        $logmsg .= "Invalid authentication method $currentauth for $uname.\n";  
                    }
# Report if authentication methods are different.
                    if ($currentauth ne $auth ) {
                         $logmsg .= "Authentication mismatch for $uname - $currentauth in system, $auth for class $crs\n";
                    }
# Check user data
                    if ($first  ne $userenv{'firstname'}  ||
                        $middle ne $userenv{'middlename'} ||
                        $last   ne $userenv{'lastname'}   ||
                        $gene   ne $userenv{'generation'} ||
                        $pid    ne $userenv{'id'} ) {         
# Make the change(s)
                        my %changeHash;
                        $changeHash{'firstname'}  = $first;
                        $changeHash{'middlename'} = $middle;
                        $changeHash{'lastname'}   = $last;
                        $changeHash{'generation'} = $gene;
                        my $putresult = &Apache::lonnet::put('environment',\%changeHash,$dom,$uname);
                        if ($putresult eq 'ok') {
                            $logmsg .= "User: $uname enrolled in $crs\n"; 
# Assign the role of student
                            my $uurl='/'.$cid;
                            $uurl=~s/\_/\//g;
                            if ($usec) {
                                $uurl.='/'.$usec;
                            }
                            &Apache::lonnet::assignrole($dom,$uname,$uurl,"st",$enddate,$startdate);
                            $addresult .=  "$first $last ($pid) - $uname enrolled in section/group $usec.".$linefeed;
                            $enrollcount ++;
# Add 'auto' status to classlist.db file -this is already done.
                        }
                    }
                }
            }
        }
    }
# Do drops
    if ( ($drops == 1) && (@reg_students > 0) ) {
        foreach my $uname (@localstudents) {
            if ($$currlist{$uname}[$type] eq "auto") {
                my @saved = ();
                if (!grep/^$uname$/,@reg_students) {
# Check for changed usernames by checking studentIDs
                    if (grep/^$$currlist{$uname}[ $stuid ]$/,@allINids) {
                        foreach my $match (@{$unameFromINid{$$currlist{$uname}[ $stuid ]}} ) {
                            $logmsg .= "A possible change in username has been detected for a student enrolled in $crs. The existing LON-CAPA classlist contains user: $uname and student ID: $$currlist{$uname}[ $place{studentID} ].  This username has been dropped from the institutional classlist, but the same student ID is used for user: $match who still appears in the institutional classlist. You may need to move the student data files for user: $uname to $match\n";
                            push @saved,$uname;
                        }
                    }
                } elsif (@saved == 0) {
                    my $modify_section_result = &Apache::lonnet::modifystudent($dom,$uname,'','','',undef,undef,undef,undef,$$currlist{$uname}[$sec],$nowtime,undef,undef,undef,undef);
                    if ($modify_section_result !~ /^ok/) {
                        $logmsg .= "An error occured during the attempt to expire the $uname from the old section $$currlist{$uname}[$sec]\n";
                    } else {
                        $dropcount ++;
                        my %userenv = &Apache::lonnet::get('environment',['firstname','lastname','id'],$dom,$uname);
                        $dropresult .= $userenv{'firstname'}." ".$userenv{'lastname'}." (".$userenv{'id'}.") - ".$uname." dropped from section/group ".$$currlist{$uname}[$sec].$linefeed; 
                    }
                }
            }
        }
    }
    if ($enrollcount > 0) {
        if ($context eq "updatenow") {
            $addresult = "The following $enrollcount student(s) was/were added to this LON-CAPA course:<br/><ul><li>".$addresult."</li></ul><br/><br/>";
        } else {
            $addresult = "The following $enrollcount student(s) was/were added to this LON-CAPA course:\n\n".$addresult."\n\n";    
        }      
    }
    if ($dropcount > 0) {
        if ($context eq "updatenow") {
            $dropresult = "The following $dropcount student(s) was/were expired from this LON-CAPA course:<br/><ul><li>".$dropresult."</li></ul><br/><br/>";
        } else {
            $dropresult = "The following $dropcount student(s) was/were expired from this LON-CAPA course:\n\n".$dropresult."\n\n";
        }
    }
    if ( ($adds) && ($enrollcount == 0) ) {
        $addresult = "There were no new students to add to the course.";
        if ($context eq "updatenow") {
            $addresult .="<br/><br/>";
        } else {
            $addresult .="\n";
        }
    }
    if ( ($drops) && ($dropcount == 0) ) {
        $dropresult = "There were no students with roles to expire because all active students previously added to the course from institutional classlist(s) are still officially registered.";
        if ($context eq "updatenow") {
            $dropresult .="<br/>";
        } else {
            $dropresult .="\n";
        }
    }
    print STDERR $logmsg;
    return $addresult.$dropresult; 
} 

sub modifystudent {
    my ($hostID,$udom,$cid,$crs,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
        $end,$start,$forceid,$desiredhome,$email,$type,$context)=@_;
# --------------------------------------------------------------- Make the user
    my $reply=&Apache::lonnet::modifyuser
        ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
         $desiredhome,$email);
    unless ($reply eq 'ok') { return $reply; }
    # This will cause &modify_student_enrollment to get the uid from the
    # students environment
    $uid = undef if (!$forceid);
    if ($context eq "adsgsasa") {
        $reply = &Apache::lonnet::modify_student_enrollment($udom,$cid,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type);
    } else { 
        $reply = &modify_student_enrollment($hostID,$udom,$cid,$crs,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type);
    }
    return $reply;
}
                                                                                       
sub modify_student_enrollment {
    my ($hostID,$udom,$cid,$crs,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type) = @_;
    # Make sure the user exists
    my $uhome=&Apache::lonnet::homeserver($uname,$udom);
    if (($uhome eq '') || ($uhome eq 'no_host')) {
        return 'error: no such user';
    }
    #
    # Get student data if we were not given enough information
    if (!defined($first)  || $first  eq '' ||
        !defined($last)   || $last   eq '' ||
        !defined($uid)    || $uid    eq '' ||
        !defined($middle) || $middle eq '' ||
        !defined($gene)   || $gene   eq '') {
        # They did not supply us with enough data to enroll the student, so
        # we need to pick up more information.
        my %tmp = &Apache::lonnet::get('environment',
                       ['firstname','middlename','lastname', 'generation','id']
                       ,$udom,$uname);
        foreach (keys(%tmp)) {
            &Apache::lonnet::logthis("key $_ = ".$tmp{$_});
        }
        $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
        $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
        $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
        $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
        $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
    }
    my $fullname = &Apache::loncoursedata::ProcessFullName($last,$gene,$first,$middle);
    my $reply=&Apache::lonnet::critical('put:'.$udom.':'.$crs.':classlist:'.&Apache::lonnet::escape($uname.':'.$udom).'='.&Apache::lonnet::escape(join(':',$end,$start,$uid,$usec,$fullname,,$type)),$hostID);
    unless (($reply eq 'ok') || ($reply eq 'delayed')) {
        return 'error: '.$reply;
    }

    # Add student role to user
    my $uurl='/'.$cid;
    $uurl=~s/\_/\//g;
    if ($usec) {
        $uurl.='/'.$usec;
    }
    return &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$end,$start);
}

sub parse_classlist {
  my ($tmpdir,$dom,$crs,$class,$placeref,$groupID,$studentsref) = @_;            
  my $configvars = &LONCAPA::Configuration::read_conf();
  my $xmlfile = "/tmp/".$dom."_".$crs."_classlist.xml"; 
#  my $xmlfile = $tmpdir."/tmp/".$dom."_".$crs."_classlist.xml";
  my $enrolled = XMLin( $xmlfile, KeyAttr => ['username'] );
  foreach my $uname ( sort keys %{$$enrolled{'student'}} ) {
      @{ $$studentsref{$uname} } = ();
      foreach my $key (sort keys %{$$enrolled{'student'}{$uname}} ) {
          my $value = $$enrolled{'student'}{$uname}{$key};
          if (ref($value)) {
              $$studentsref{$uname}[ $$placeref{$key} ] = '';
          } else {
              if ($key eq 'groupID') {
                  $$studentsref{$uname}[ $$placeref{$key} ] = $groupID;
              } else {
                  $$studentsref{$uname}[ $$placeref{$key} ] = $value;
              }
          }
      }
  }
#  if (-e "$xmlfile") {
#      unlink $xmlfile;
#  }
  return;
}

sub create_password {


}

sub CL_autharg { return 0; }
sub CL_authtype { return 1;}
sub CL_email { return 2;}
sub CL_enddate { return 3;}
sub CL_firstname { return 4;}
sub CL_generation { return 5;}
sub CL_groupID { return 6;}
sub CL_lastname { return 7;}
sub CL_middlename { return 8;}
sub CL_startdate { return 9; }
sub CL_studentID { return 10; }

1;

--raeburn1070325159--