[LON-CAPA-cvs] cvs: loncom /enrollment Enrollment.pm

raeburn lon-capa-cvs@mail.lon-capa.org
Fri, 05 Dec 2003 17:04:37 -0000


This is a MIME encoded message

--raeburn1070643877
Content-Type: text/plain

raeburn		Fri Dec  5 12:04:37 2003 EDT

  Added files:                 
    /loncom/enrollment	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.
  
  
--raeburn1070643877
Content-Type: text/plain
Content-Disposition: attachment; filename="raeburn-20031205120437.txt"


Index: loncom/enrollment/Enrollment.pm
+++ loncom/enrollment/Enrollment.pm
package LONCAPA::Enrollment;

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

use strict;

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$/) {
            if ($$roster{$uname}[$status] eq "Active") {
                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'} ];
                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) {
        $enrollinfo{$uname}[ $place{'studentID'} ] =~ tr/A-Z/a-z/;
        my $stuID = $enrollinfo{$uname}[ $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} ]) {
                $logmsg .= "Found a section difference for $uname - ".$$currlist{$uname}[$sec] ."versus ".$stuinfo[ $place{groupID} ]." in class $crs\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,'auto',$cid);
                    if ($modify_section_result !~ /^ok/) {
                        $logmsg .= "An error occured during the attempt to expire the $uname from the old section $$currlist{$uname}[$sec] - $modify_section_result\n";
                    }

# Assign the role of student in the new section
                    my $uurl='/'.$cid;
                    $uurl=~s/\_/\//g;
                    if ($stuinfo[ $place{groupID} ]) {
                        $uurl.='/'.$stuinfo[ $place{groupID} ];
                    }
                    my $newend = $stuinfo[ $place{enddate} ];
                    my $newstart = $stuinfo[ $place{startdate} ]);
                    if ($newend eq '') {
                        $end = $enddate;
                    }
                    if ($newstart eq '') {
                        $start = $startdate;
                    }
                    &Apache::lonnet::assignrole($dom,$uname,$uurl,"st",$newend,$newstart); 
                }
            }
        }
        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 =~ m/^krb/) {
                            $passwd = $autharg;
                        } else {
                            $logmsg .= "Invalid authentication type for $uname in $crs\n";
                        }  
                    }
# Now create user.
                    my $reply=&Apache::lonnet::modifystudent($dom,$uname,$pid,$auth,$authparam,$first,$middle,$last,$gene,$usec,$end,$start,'',undef,$emailaddr,'auto',$cid);
                    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";
                    }
                } 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;
                        $changeHash{'id'} = $pid;
                        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
                            $classlist_reply = &modify_student_enrollment($$configvars{'lonHostID'},$dom,$cid,$crs,$uname,$pid,$first,$middle,$last,$gene,$usec,$end,$start,'auto');
                            if ($classlist_reply eq 'ok') {
                                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 ++;
                                $addresult .= "$first $last ($pid) - $uname enrolled in section/group $usec.".$linefeed;
                                $logmsg .= "Existing user $uname enrolled successfully in $crs\n";

                            } else {
                                $logmsg .= "There was a problem updating the classlist db file for user $uname to show the new enrollment, so no enrollment occurred in $crs\n";
                            }
                        } else {
                            $logmsg .= "There was a problem modifying user data for existing user - $uname, so no enrollment occurred in $crs.\n";
                        }
                    }
                }
            }
        }
    }
# 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 $drop_reply = &Apache::lonnet::modifystudent($dom,$uname,'','','',undef,undef,undef,undef,$$currlist{$uname}[$sec],time,undef,undef,undef,undef,undef,$cid);
                        if ($drop_reply !~ /^ok/) {
                            $logmsg .= "An error occured during the attempt to expire the $uname from the old section $$currlist{$uname}[$sec] - $drop_reply\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 parse_classlist {
  my ($tmpdir,$dom,$crs,$class,$placeref,$groupID,$studentsref) = @_;            
  my $configvars = &LONCAPA::Configuration::read_conf();
  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;

--raeburn1070643877--