File:  [LON-CAPA] / loncom / enrollment / Enrollment.pm
Revision 1.26: download - view: text, annotated - select for diffs
Mon Jan 2 20:19:37 2006 UTC (18 years, 4 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
Arguments expected by loncoursedata::get_classlist() were changed in loncoursedata.pm rev 1.150.  Propagating change to to &get_classlist call in Enrollment.pm.

    1: # Automated Enrollment manager
    2: # $Id: Enrollment.pm,v 1.26 2006/01/02 20:19:37 raeburn Exp $
    3: #
    4: # Copyright Michigan State University Board of Trustees
    5: #
    6: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    7: #
    8: # LON-CAPA is free software; you can redistribute it and/or modify
    9: # it under the terms of the GNU General Public License as published by
   10: # the Free Software Foundation; either version 2 of the License, or
   11: # (at your option) any later version.
   12: #
   13: # LON-CAPA is distributed in the hope that it will be useful,
   14: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   15: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   16: # GNU General Public License for more details.
   17: #
   18: # You should have received a copy of the GNU General Public License
   19: # along with LON-CAPA; if not, write to the Free Software
   20: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   21: #
   22: # /home/httpd/html/adm/gpl.txt
   23: #
   24: # http://www.lon-capa.org/
   25: #
   26: package LONCAPA::Enrollment;
   27: 
   28: use Apache::loncoursedata;
   29: use Apache::lonnet;
   30: use Apache::lonmsg;
   31: use HTML::Entities;
   32: use LONCAPA::Configuration;
   33: use Time::Local;
   34: use lib '/home/httpd/lib/perl';
   35: 
   36: use strict;
   37: 
   38: sub update_LC {
   39:     my ($dom,$crs,$adds,$drops,$startdate,$enddate,$authtype,$autharg,$classesref,$groupref,$logmsg,$newusermsg,$context) = @_; 
   40: # Get institutional code and title of this class
   41:     my %courseinfo = ();
   42:     &get_courseinfo($dom,$crs,\%courseinfo);
   43: # Get current LON-CAPA student enrollment for this class
   44:     my $configvars = &LONCAPA::Configuration::read_conf('loncapa.conf');
   45:     my $cid = $dom."_".$crs;
   46:     my $roster = &Apache::loncoursedata::get_classlist($dom,$crs);
   47:     my $cend = &Apache::loncoursedata::CL_END;
   48:     my $cstart = &Apache::loncoursedata::CL_START; 
   49:     my $stuid=&Apache::loncoursedata::CL_ID;
   50:     my $sec=&Apache::loncoursedata::CL_SECTION;
   51:     my $status=&Apache::loncoursedata::CL_STATUS;
   52:     my $type=&Apache::loncoursedata::CL_TYPE;
   53:     my $lockedtype=&Apache::loncoursedata::CL_LOCKEDTYPE;
   54:     my @localstudents = ();
   55:     my @futurestudents = ();
   56:     my @activestudents = ();
   57:     my @excludedstudents = ();
   58:     my $currlist;
   59:     foreach my $uname (keys %{$roster} ) {
   60:         if ($uname =~ m/^(.+):$dom$/) {
   61:             if ($$roster{$uname}[$status] eq "Active") {
   62:                 push @activestudents, $1;
   63:                 @{$$currlist{$1}} = @{$$roster{$uname}};
   64:                 push @localstudents, $1;
   65:             } elsif ( ($$roster{$uname}[$cstart] > time)  && ($$roster{$uname}[$cend] > time || $$roster{$uname}[$cend] == 0 || $$roster{$uname}[$cend] eq '') ) {
   66:                 push @futurestudents, $1;
   67:                 @{$$currlist{$1}} = @{$$roster{$uname}};
   68:                 push @localstudents, $1;
   69:             } elsif ($$roster{$uname}[$lockedtype] == 1) {
   70:                 push @excludedstudents, $1;
   71:             }
   72:         }
   73:     }
   74:     my $linefeed = '';
   75:     my $addresult = '';
   76:     my $dropresult = '';
   77:     my $switchresult = '';
   78:     if ($context eq "updatenow") {
   79:         $linefeed = "</li>\n<li>"; 
   80:     } elsif ($context eq "automated") {
   81:         $linefeed = "\n";
   82:     }
   83:     my $enrollcount = 0;
   84:     my $dropcount = 0;
   85:     my $switchcount = 0;
   86: 
   87: # Get role names
   88:     my %longroles = ();
   89:     open(FILE,"<$$configvars{'lonTabDir'}.'/rolesplain.tab");
   90:     my @rolesplain = <FILE>;
   91:     close(FILE);
   92:     foreach (@rolesplain) {
   93:         if ($_ =~ /^(st|ta|ex|ad|in|cc):([\w\s]+)$/) {
   94:             $longroles{$1} = $2;
   95:         }
   96:     }
   97: 
   98:     srand( time() ^ ($$ + ($$ << 15))  ); # Seed rand in case initial passwords have to be generated for new users.
   99: 
  100: # Get mapping of IDs to usernames for current LON-CAPA student enrollment for this class 
  101:     my @LCids = ();
  102:     my %unameFromLCid = ();
  103:     foreach my $uname (sort keys %{$currlist}) {
  104:         my $stuID = $$currlist{$uname}[$stuid];
  105:         if (!grep/^$stuID$/,@LCids) {
  106:             push @LCids, $stuID;
  107:             @{$unameFromLCid{$stuID}} = ();
  108:         }
  109:         push @{$unameFromLCid{$stuID}},$uname;
  110:     }
  111:  
  112: # Get latest institutional enrollment for this class.
  113:     my %allenrolled = ();
  114:     my @reg_students = ();
  115:     my %place = ();
  116:     $place{'autharg'} = &CL_autharg();
  117:     $place{'authtype'} = &CL_authtype();
  118:     $place{'email'} = &CL_email();
  119:     $place{'enddate'} = &CL_enddate();
  120:     $place{'firstname'} = &CL_firstname();
  121:     $place{'generation'} = &CL_generation();
  122:     $place{'groupID'} = &CL_groupID();
  123:     $place{'lastname'} = &CL_lastname();
  124:     $place{'middlename'} = &CL_middlename();
  125:     $place{'startdate'} = &CL_startdate();
  126:     $place{'studentID'} = &CL_studentID();
  127:     my %ucount = ();
  128:     my %enrollinfo = ();
  129:     foreach my $class (@{$classesref}) {
  130:         my %enrolled = ();
  131:         &parse_classlist($$configvars{'lonDaemons'},$dom,$crs,$class,\%place,$$groupref{$class},\%enrolled);
  132:         foreach my $uname (sort keys %enrolled ) {
  133:             if (!grep/^$uname$/,@reg_students) {
  134:                 push @reg_students,$uname;
  135:                 $ucount{$uname} = 0;
  136:                 @{$allenrolled{$uname}} = ();
  137:             }
  138:             @{$allenrolled{$uname}[$ucount{$uname}]} = @{$enrolled{$uname}};
  139:             $ucount{$uname} ++;
  140:         }
  141:     }
  142: 
  143: # Check for multiple sections for a single student 
  144:     my @okusers = ();
  145:     foreach my $uname (@reg_students)  {
  146:         if (grep/^$uname$/,@excludedstudents) {
  147:             $$logmsg .= "No re-enrollment for $uname - user was previously manually unenrolled and locked.".$linefeed;
  148:         } elsif (@{$allenrolled{$uname}} > 1) {
  149:             my @sections = ();
  150:             my $saved;
  151:             for (my $i=0; $i<@{$allenrolled{$uname}}; $i++) {
  152:                 my @stuinfo = @{$allenrolled{$uname}[$i]};
  153:                 my $secnum = $stuinfo[ $place{'groupID'} ];
  154:                 unless ($secnum eq '') {
  155:                     unless (grep/^$secnum$/,@sections) {
  156:                         $saved = $i; 
  157:                         push @sections,$secnum;
  158:                     }
  159:                 }
  160:             }
  161:             if (@sections == 0) {
  162:                 @{$enrollinfo{$uname}} = @{$allenrolled{$uname}[0]};
  163:                 push @okusers, $uname;
  164:             }
  165:             elsif (@sections == 1) {
  166:                 @{$enrollinfo{$uname}} = @{$allenrolled{$uname}[$saved]};
  167:                 push @okusers, $uname;
  168:             }
  169:             elsif (@sections > 1) {
  170:                 $$logmsg =  "$uname appears in classlists for the more than one section of this course, i.e. in sections: ";
  171:                 foreach (@sections) {
  172:                     $$logmsg .= " $_,";
  173:                 }
  174:                 chop($$logmsg);
  175:                 $$logmsg .= ". Because of this ambiguity, no enrollment action was taken for this student.".$linefeed;
  176:             }
  177:         } else {
  178:             @{$enrollinfo{$uname}} = @{$allenrolled{$uname}[0]};
  179:             push @okusers, $uname;
  180:         }
  181:     }
  182: # Get mapping of student IDs to usernames for users in institutional data for this class  
  183:     my @allINids = ();
  184:     my %unameFromINid = ();
  185:     foreach my $uname (@okusers) {
  186:         $enrollinfo{$uname}[ $place{'studentID'} ] =~ tr/A-Z/a-z/;
  187:         my $stuID = $enrollinfo{$uname}[ $place{'studentID'} ];
  188:         if (grep/^$stuID$/,@allINids)  {
  189:             push @{$unameFromINid{$stuID}},$uname;
  190:         } else {
  191:             push @allINids, $stuID;
  192:             @{$unameFromINid{$stuID}} = $uname; 
  193:         }
  194:     }
  195: # Explicitly allow access to creation/modification of students if called as an automated process.
  196:     if ($context eq 'automated') {
  197:         $env{'allowed.cst'}='F';
  198:     }
  199: 
  200: # Compare IDs with existing LON-CAPA enrollment for this class
  201:     foreach my $uname (@okusers) {
  202:         unless ($uname eq '') {
  203:             my %uidhash=&Apache::lonnet::idrget($dom,$uname);
  204:             my @stuinfo = @{$enrollinfo{$uname}};
  205:             my $access = '';
  206:             if (grep/^$uname$/,@localstudents) {
  207: # Check for studentID changes
  208:                 if ( ($uidhash{$uname}) && ($uidhash{$uname} !~ /error\:/) )  {
  209:                     unless ( ($uidhash{$uname}) eq ($stuinfo[ $place{studentID} ]) ) {
  210:                         $$logmsg .= "Change in ID for $uname. StudentID in LON-CAPA system is $uidhash{$uname}; StudentID in institutional data is $stuinfo[ $place{studentID} ]".$linefeed; 
  211:                     }
  212:                 }
  213: # Check for switch from manual to auto
  214:                 unless (($$currlist{$uname}[$type] eq "auto") || ($$currlist{$uname}[$lockedtype] eq "1") || (!$adds) ) {
  215: # drop manually added student
  216:                     my $drop_reply = &Apache::lonnet::modifystudent($dom,$uname,'','','',undef,undef,undef,undef,$$currlist{$uname}[$sec],time,undef,undef,undef,undef,'auto','',$cid);
  217: # re-enroll as auto student
  218:                     if ($drop_reply !~ /^ok/) {
  219:                             $$logmsg .= "An error occured during the attempt to convert $uname from a manual type to an auto type student - $drop_reply.".$linefeed;
  220:                     } else {
  221: # re-enroll as auto student
  222:                         my ($auth,$authparam,$first,$middle,$last,$gene,$usec,$end,$start,$emailaddr,$pid,$emailenc);
  223:                         &prepare_add($authtype,$autharg,$enddate,$startdate,\@stuinfo,\%place,\$dom,\$uname,\$auth,\$authparam,\$first,\$middle,\$last,\$gene,\$usec,\$end,\$start,\$emailaddr,\$pid,\$emailenc);
  224:                         if ($$currlist{$uname}[$sec] ne $usec) {
  225:                             $switchresult .= "Section for $uname switched from $$currlist{$uname}[$sec] to ".$usec.$linefeed;
  226:                             if ($context eq 'automated') {
  227:                                 $$logmsg .= "Section switch for $uname from $$currlist{$uname}[$sec] to ".$usec.$linefeed; ;
  228:                             }
  229:                             $switchcount ++;
  230:                         }
  231:                         &execute_add($context,'switchtype',$uname,$dom,$auth,$authparam,$first,$middle,$last,$gene,$pid,$usec,$end,$start,$emailenc,$cid,\$addresult,\$enrollcount,$linefeed,$logmsg);
  232:                     }
  233:                 } 
  234: # Check for section changes
  235:                 if ($$currlist{$uname}[$sec] eq $stuinfo[ $place{groupID} ]) {
  236: # Check for access date changes for students with access starting in the future.
  237:                     if ( (grep/^$uname$/,@futurestudents) && ($$currlist{$uname}[$type] eq "auto") && ($adds == 1) ) {
  238:                         my $datechange = &datechange_check($$currlist{$uname}[$cstart],$$currlist{$uname}[$cend],$startdate,$enddate);
  239:                         if ($datechange) {
  240:                             my $modify_access_result = &Apache::lonnet::modify_student_enrollment($dom,$uname,undef,undef,undef,undef,undef,$stuinfo[ $place{groupID} ],$enddate,$startdate,'auto','',$cid);
  241:                             $access = &showaccess($enddate,$startdate);
  242:                             if ($modify_access_result =~ /^ok/) {
  243:                                 $$logmsg .= "Change in access dates for $uname.".$access.$linefeed;
  244:                             } else {
  245:                                 $$logmsg .= "Error when attempting to change start and/or end access dates for $uname in section: ".$stuinfo[ $place{groupID} ]." -error $modify_access_result".$linefeed;
  246:                             }
  247:                         }
  248:                     }
  249:                 } else {
  250:                     if ( ($$currlist{$uname}[$type] eq "auto") && ($adds == 1) ) {
  251: # Delete from roles.db for current section
  252:                         my $expiretime = time;
  253:                         my $uurl='/'.$cid;
  254:                         $uurl=~s/\_/\//g;
  255:                         if ($$currlist{$uname}[$sec]) {
  256:                             $uurl.='/'.$$currlist{$uname}[$sec];
  257:                         }
  258:                         my $expire_role_result = &Apache::lonnet::assignrole($dom,$uname,$uurl,'st',$expiretime);
  259:                         if ($expire_role_result eq 'ok') {
  260:                             my $modify_section_result;
  261:                             if (grep/^$uname$/,@activestudents) {
  262:                                 $modify_section_result = &Apache::lonnet::modify_student_enrollment($dom,$uname,undef,undef,undef,undef,undef,$stuinfo[ $place{groupID} ],$$currlist{$uname}[$cend],$$currlist{$uname}[$cstart],'auto','',$cid);
  263:                             } else {
  264:                                 $modify_section_result =  &Apache::lonnet::modify_student_enrollment($dom,$uname,undef,undef,undef,undef,undef,$stuinfo[ $place{groupID} ],$enddate,$startdate,'auto','',$cid);
  265:                                 $access =  &showaccess($enddate,$startdate);
  266:                             }
  267:                             if ($modify_section_result =~ /^ok/) {
  268:                                 $switchresult .= "Section for $uname switched from old section: ".$$currlist{$uname}[$sec] ." to new section: ".$stuinfo[ $place{groupID} ].".".$access.$linefeed;
  269:                                 if ($context eq 'automated') {
  270:                                     $$logmsg .= "Section switch for $uname from $$currlist{$uname}[$sec] to $stuinfo[ $place{groupID} ]".$linefeed;
  271:                                 }
  272:                                 $switchcount ++;
  273:                             } else {
  274:                                 $$logmsg .= "Error when attempting section change for $uname from old section ".$$currlist{$uname}[$sec]." to new section: ".$stuinfo[ $place{groupID} ]." -error: $modify_section_result".$linefeed;
  275:                             }
  276:                         } else {
  277:                             $$logmsg .= "Error when attempting to expire role for $uname in old section" .$$currlist{$uname}[$sec]." -error: $expire_role_result".$linefeed;
  278:                         }
  279:                     }
  280:                 }
  281:             } else {
  282: # Check for changed usernames by checking studentIDs
  283:                 if ( ($stuinfo[ $place{studentID} ] ne '') && (grep/^$stuinfo[ $place{studentID} ]$/,@LCids) ) {
  284:                     if (grep/^$$currlist{$uname}[ $place{'studentID'} ]$/,@allINids) {
  285:                         foreach my $match ( @{ $unameFromLCid{ $stuinfo[ $place{studentID} ] } }  ) {
  286:                             if (grep/^$match$/,@okusers) {
  287:                                 $$logmsg .= "A possible change in username has been detected for a student enrolled in this course. 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 contact your Domain Coordinator to request a move of the student data files for user: $uname to $match".$linefeed;
  288:                             }
  289:                         }
  290:                     }
  291:                 } elsif ($adds == 1) {
  292:                     my ($auth,$authparam,$first,$middle,$last,$gene,$usec,$end,$start,$emailaddr,$pid,$emailenc);
  293:                     &prepare_add($authtype,$autharg,$enddate,$startdate,\@stuinfo,\%place,\$dom,\$uname,\$auth,\$authparam,\$first,\$middle,\$last,\$gene,\$usec,\$end,\$start,\$emailaddr,\$pid,\$emailenc);
  294: # Check for existing account in this LON-CAPA domain for this username
  295:                     my $uhome=&Apache::lonnet::homeserver($uname,$dom);
  296:                     if ($uhome eq 'no_host') { # User does not exist
  297:                         my $args = {'auth' => $auth,
  298:                                     'authparam' => $authparam,
  299:                                     'emailenc' => $emailenc,
  300:                                     'udom' => $dom,
  301:                                     'uname' => $uname,
  302:                                     'pid' => $pid,
  303:                                     'first' => $first,
  304:                                     'middle' => $middle,
  305:                                     'last' => $last,
  306:                                     'gene' => $gene,
  307:                                     'usec' => $usec,
  308:                                     'end' => $end,
  309:                                     'start' => $start,
  310:                                     'emailaddr' => $emailaddr,
  311:                                     'cid' => $cid,
  312:                                     'crs' => $crs,
  313:                                     'cdom' => $dom,
  314:                                     'context' => $context,
  315:                                     'linefeed' => $linefeed,
  316:                                     'role' => 'st'
  317:                                    };
  318:                         my $outcome = &create_newuser($args,$logmsg,$newusermsg,\$enrollcount,\$addresult,\%longroles,\%courseinfo);
  319:                     } else {
  320:                         &execute_add($context,'newstudent',$uname,$dom,$auth,$authparam,$first,$middle,$last,$gene,$pid,$usec,$end,$start,$emailenc,$cid,\$addresult,\$enrollcount,$linefeed,$logmsg);
  321:                     }
  322:                 }
  323:             }
  324:         }
  325:     }
  326: # Do drops
  327:     if ( ($drops == 1) && (@reg_students > 0) ) {
  328:         foreach my $uname (@localstudents) {
  329:             if ($$currlist{$uname}[$type] eq "auto") {
  330:                 my @saved = ();
  331:                 if (!grep/^$uname$/,@reg_students) {
  332: # Check for changed usernames by checking studentIDs
  333:                     if (grep/^$$currlist{$uname}[ $stuid ]$/,@allINids) {
  334:                         foreach my $match (@{$unameFromINid{$$currlist{$uname}[ $stuid ]}} ) {
  335:                             $$logmsg .= "A possible change in username has been detected for a student enrolled in this course. 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.".$linefeed;
  336:                             push @saved,$uname;
  337:                         }
  338:                     } elsif (@saved == 0) {
  339:                         my $drop_reply = &Apache::lonnet::modifystudent($dom,$uname,'','','',undef,undef,undef,undef,$$currlist{$uname}[$sec],time,undef,undef,undef,undef,'auto','',$cid);
  340:                         if ($drop_reply !~ /^ok/) {
  341:                             $$logmsg .= "An error occured during the attempt to expire the $uname from the old section $$currlist{$uname}[$sec] - $drop_reply.".$linefeed;
  342:                         } else {
  343:                             $dropcount ++;
  344:                             my %userenv = &Apache::lonnet::get('environment',['firstname','lastname','id'],$dom,$uname);
  345:                             $dropresult .= $userenv{'firstname'}." ".$userenv{'lastname'}." (".$userenv{'id'}.") - ".$uname." dropped from section/group ".$$currlist{$uname}[$sec].$linefeed; 
  346:                             if ($context eq 'automated') {
  347:                                 $$logmsg .= "User $uname student role expired from course.".$linefeed;
  348:                             }
  349:                         }
  350:                     }
  351:                 }
  352:             }
  353:         }
  354:     }
  355: 
  356: # Terminated explictly allowed access to student creation/modification
  357:     if ($context eq 'automated') {
  358:         delete($env{'allowed.cst'});
  359:     }
  360:     if ($enrollcount > 0) {
  361:         if ($context eq "updatenow") {
  362:             $addresult = substr($addresult,0,rindex($addresult,"<li>"));
  363:             $addresult = "The following $enrollcount student(s) was/were added to this LON-CAPA course:<br/><ul><li>".$addresult."</ul><br/><br/>";
  364:         } else {
  365:             $addresult = "The following $enrollcount student(s) was/were added to this LON-CAPA course:\n\n".$addresult."\n\n";
  366:         }
  367:     }
  368:     if ($dropcount > 0) {
  369:         if ($context eq "updatenow") {
  370:             $dropresult = substr($dropresult,0,rindex($dropresult,"<li>"));
  371:             $dropresult = "The following $dropcount student(s) was/were expired from this LON-CAPA course:<br/><ul><li>".$dropresult."</ul><br/><br/>";
  372:         } else {
  373:             $dropresult = "The following $dropcount student(s) was/were expired from this LON-CAPA course:\n\n".$dropresult."\n\n";
  374:         }
  375:     }
  376:     if ($switchcount > 0) {
  377:         if ($context eq "updatenow") {
  378:             $switchresult = substr($switchresult,0,rindex($switchresult,"<li>"));
  379:             $switchresult = "The following $switchcount student(s) switched sections in this LON-CAPA course:<br/><ul><li>".$switchresult."</ul><br/><br/>";
  380:         } else {
  381:             $switchresult = "The following $switchcount student(s) switched sections in this LON-CAPA course:\n\n".$switchresult."\n\n";
  382:         }
  383:     }
  384:     if ( ($adds) && ($enrollcount == 0) ) {
  385:         $addresult = "There were no new students to add to the course.";
  386:         if ($context eq "updatenow") {
  387:             $addresult .="<br/><br/>";
  388:         } else {
  389:             $addresult .="\n";
  390:         }
  391:     }
  392:     if ( ($drops) && ($dropcount == 0) ) {
  393:         $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.";
  394:         if ($context eq "updatenow") {
  395:             $dropresult .="<br/>";
  396:         } else {
  397:             $dropresult .="\n";
  398:         }
  399:     }
  400:     my $changecount = $enrollcount + $dropcount + $switchcount;
  401:     return ($changecount,$addresult.$dropresult.$switchresult);
  402: }
  403: 
  404: sub create_newuser {
  405:     my ($args,$logmsg,$newusermsg,$enrollcount,$addresult,$longroles,$courseinfo) = @_;
  406:     my $auth = $args->{'auth'};
  407:     my $authparam = $args->{'authparam'};
  408:     my $emailenc = $args->{'emailenc'};
  409:     my $udom = $args->{'udom'};
  410:     my $uname = $args->{'uname'};
  411:     my $pid = $args->{'pid'};
  412:     my $first = $args->{'first'};
  413:     my $middle = $args->{'middle'};
  414:     my $last = $args->{'last'} ;
  415:     my $gene = $args->{'gene'};
  416:     my $usec = $args->{'usec'};
  417:     my $end = $args->{'end'};
  418:     my $start = $args->{'start'};
  419:     my $emailaddr = $args->{'emailaddr'};
  420:     my $cid = $args->{'cid'};
  421:     my $crs = $args->{'crs'};
  422:     my $cdom = $args->{'cdom'};
  423:     my $context = $args->{'context'};
  424:     my $linefeed = $args->{'linefeed'};
  425:     my $role = $args->{'role'};
  426:     my $create_passwd = 0;
  427:     my $authchk = '';
  428:     my $outcome;
  429:     unless ($authparam eq '') { $authchk = 'ok'; };
  430: # If no account exists and passwords should be generated
  431:     if ($auth eq "internal") {
  432:         if ($authparam eq '') {
  433:             $authparam = &create_password();
  434:             if ($authparam eq '') {
  435:                 $authchk = '';
  436:             } else {
  437:                 $create_passwd = 1;
  438:                 $authchk = 'ok';
  439:             }
  440:         }
  441:     } elsif ($auth eq "localauth") {
  442:         ($authparam,$create_passwd,$authchk) = &Apache::lonnet::auto_create_password($crs,$cdom,$authparam);
  443:     } elsif ($auth =~ m/^krb/) {
  444:         if ($authparam eq '') {
  445:             $$logmsg .= "No Kerberos domain was provided for the new user - $uname, so the new user was not enrolled in the course.".$linefeed;
  446:             $authchk = 'invalid';
  447:         }
  448:     } else {
  449:         $authchk = 'invalid';
  450:         $$logmsg .= "An invalid authentication type was provided for the new user - $uname, so the user was not enrolled in the course.".$linefeed;
  451:     }   
  452:     if ($authchk eq 'ok') {
  453: # Now create user.
  454:         my $type = 'auto';
  455:         my $userurl = '/'.$cdom.'/'.$crs;
  456:         if ($usec ne '') {
  457:             $userurl .= '/'.$usec;
  458:         }
  459:         if ($context eq 'createowner' || $context eq 'createcourse') {
  460:             my $result = &Apache::lonnet::modifyuser($udom,$uname,$pid,$auth,$authparam,$first,$middle,$last,$gene,'1',undef,$emailaddr);
  461:             if ($result eq 'ok' && $context eq 'createcourse') {
  462:                 $outcome = &Apache::loncreateuser::commit_standardrole($udom,$uname,$userurl,$role,$start,$end,$cdom,$crs,$usec);
  463:                 unless ($outcome =~ /^Error:/) {
  464:                     $outcome = 'ok';
  465:                 }
  466:             } else {
  467:                 $outcome = $result;
  468:             }
  469:         } else {
  470:             $outcome=&Apache::lonnet::modifystudent($udom,$uname,$pid,$auth,$authparam,$first,$middle,$last,$gene,$usec,$end,$start,'',undef,$emailaddr,'auto','',$cid);
  471:         }
  472:         if ($outcome eq 'ok') {
  473:             my $access = &showaccess($end,$start);
  474:             $$addresult .= "$first $last ($pid) - $uname enrolled in section/group $usec.".$access.$linefeed;
  475:             unless ($context eq 'createowner' || $context eq 'createcourse') {
  476:                 $$enrollcount ++;
  477:             }
  478:             if ($context eq 'automated') {
  479:                 $$logmsg .= "New $udom user $uname added successfully.";
  480:             }
  481:             unless ($emailenc eq '' || $context eq 'createowner' || $context eq 'createcourse') {
  482:                 my %emailHash;
  483:                 $emailHash{'critnotification'}  = $emailenc;
  484:                 $emailHash{'notification'} = $emailenc;
  485:                 $emailHash{'permanentemail'} = $emailenc;
  486:                 my $putresult = &Apache::lonnet::put('environment',\%emailHash,$udom,$uname);
  487:             }
  488:             if ($create_passwd) {
  489: # Send e-mail with initial password to new user at $emailaddr.
  490: # If e-mail address is invalid, send password via message to courseowner i
  491: # (if automated call) or to user if roster update.
  492:                 if ($emailaddr eq '') {
  493:                     $$newusermsg .= " username: $uname, password: ".$authparam.$linefeed."\n";
  494:                 } else {
  495:                     my $subject = "New LON-CAPA account";
  496:                     my $body;
  497:                     if ($context eq 'createowner') {
  498:                         $body = "A user account has been created for you while creating your new course in the LON-CAPA course management and online homework system.\n\nYou should log-in to the system using the following credentials:\nusername: $uname\npassword: $authparam\n\nThe URL you should use to access the LON-CAPA system at your school is: http://".$ENV{'SERVER_NAME'}."\n\n";
  499:                     } elsif ($context eq 'createcourse') {
  500:                         $body = "You have been assigned the role of $$longroles{$role} in a new course: $$courseinfo{'description'} - $$courseinfo{'inst_code'} in the LON-CAPA course management and online homework system.  As you did not have an existing user account in the system, one has been created for you.\n\nYou should log-in to the system using the following credentials:\nusername: $uname\npassword: $authparam\n\nThe URL you should use to access the LON-CAPA system at your school is: http://".$ENV{'SERVER_NAME'}."\n\n"; 
  501:                     } else {
  502:                         my $access_start = 'immediately';
  503:                         if ($start > 0) {
  504:                             $access_start = localtime($start)
  505:                         }
  506:                         $body = "You have been enrolled in the LON-CAPA system at your school, because you are a registered student in a class that is using the LON-CAPA couse management and online homework system.\n\nYou should log-in to the system using the following credentials:\nusername: $uname\npassword: $authparam\n\nThe URL you should use to access the LON-CAPA system at your school is: http://".$ENV{'SERVER_NAME'}."\n\n.When you log-in you will be able to access the LON-CAPA course for $$courseinfo{'description'} - $$courseinfo{'inst_code'} starting $access_start.\n";
  507:                     }
  508:                     &Apache::lonmsg::sendemail($emailaddr,$subject,$body);
  509:                 }
  510:                 if ($context eq 'automated') {
  511:                     $$logmsg .= " Initial password -  - sent to ".$emailaddr.$linefeed;
  512:                 }
  513:             } else {
  514:                 if ($context eq 'automated') {
  515:                     $$logmsg .= $linefeed;
  516:                 }
  517:             }
  518:         } else {
  519:             $$logmsg .= "An error occurred adding new user $uname - ".$outcome.$linefeed;
  520:         }
  521:     }
  522:     return $outcome;
  523: }
  524: 
  525: sub prepare_add {
  526:     my ($authtype,$autharg,$enddate,$startdate,$stuinfo,$place,$dom,$uname,$auth,$authparam,$first,$middle,$last,$gene,$usec,$end,$start,$emailaddr,$pid,$emailenc) = @_;
  527:     $$auth = $$stuinfo[ $$place{'authtype'} ];
  528:     $$authparam = $$stuinfo[ $$place{'autharg'} ];
  529:     $$first = $$stuinfo[ $$place{'firstname'} ];
  530:     $$middle = $$stuinfo[ $$place{'middlename'} ];
  531:     $$last = $$stuinfo[ $$place{'lastname'} ];
  532:     $$gene = $$stuinfo[ $$place{'generation'} ];
  533:     $$usec = $$stuinfo[ $$place{'groupID'} ];
  534:     $$end = $$stuinfo[ $$place{'enddate'} ];
  535:     $$start = $$stuinfo[ $$place{'startdate'} ];
  536:     $$emailaddr = $$stuinfo[ $$place{'email'} ];
  537:     $$pid = $$stuinfo[ $$place{'studentID'} ];
  538:                                                                                   
  539: # remove non alphanumeric values from section
  540:     $$usec =~ s/\W//g;
  541:                                                                                   
  542:     unless ($$emailaddr =~/^[^\@]+\@[^\@]+$/) { $$emailaddr =''; }
  543:     $$emailenc = &HTML::Entities::encode($$emailaddr,'<>&"');
  544:                                                                                   
  545: # Use course defaults where entry is absent
  546:     if ( ($$auth eq '') || (!defined($$auth)) ) {
  547:         $$auth =  $authtype;
  548:     }
  549:     if ( ($$authparam eq '')  || (!defined($$authparam)) )  {
  550:         $$authparam = $autharg;
  551:     }
  552:     if ( ($$end eq '') || (!defined($$end)) )  {
  553:         $$end = $enddate;
  554:     }
  555:     if ( ($$start eq '')  || (!defined($$start)) )  {
  556:         $$start = $startdate;
  557:     }
  558: # Clean up whitespace
  559:     foreach ($dom,$uname,$pid,$first,$middle,$last,$gene,$usec) {
  560:         $$_ =~ s/(\s+$|^\s+)//g;
  561:     }
  562:     return;
  563: }
  564: 
  565: sub execute_add {
  566:     my ($context,$caller,$uname,$dom,$auth,$authparam,$first,$middle,$last,$gene,$pid,$usec,$end,$start,$emailenc,$cid,$addresult,$enrollcount,$linefeed,$logmsg) = @_;
  567: # Get the user's information and authentication
  568:     my %userenv = &Apache::lonnet::get('environment',['firstname','middlename','lastname','generation','id','critnotification','notification','permanentemail'],$dom,$uname);
  569:     my ($tmp) = keys(%userenv);
  570:     if ($tmp =~ /^(con_lost|error)/i) {
  571:         %userenv = ();
  572:     }
  573: # Get the user's e-mail address
  574:     if ($userenv{critnotification} =~ m/%40/) {
  575:         unless ($emailenc eq $userenv{critnotification}) {
  576:             $$logmsg .= "Current critical notification e-mail
  577: - ".$userenv{critnotification}." for $uname is different to e-mail address in institutional classlist - ".$emailenc.$linefeed;
  578:         }
  579:     }
  580:     if ($userenv{notification} =~ m/%40/) {
  581:         unless ($emailenc eq $userenv{notification}) {
  582:             $$logmsg .= "Current standard notification e-mail
  583: - ".$userenv{notification}." for $uname is different to e-mail address in institutional classlist - ".$emailenc.$linefeed;
  584:         }
  585:     }
  586:     if ($userenv{permanentemail} =~ m/%40/) {
  587:         unless ($emailenc eq $userenv{permanentemail}) {
  588:             $$logmsg .= "Current permanent e-mail
  589: - ".$userenv{permanentemail}." for $uname is different to e-mail address in institutional classlist - ".$emailenc.$linefeed;
  590:         }
  591:     }
  592:     my $krbdefdom = '';
  593:     my $currentauth=&Apache::lonnet::queryauthenticate($uname,$dom);
  594:     if ($currentauth=~/^(krb[45]):(.*)/) {
  595:         $currentauth = $1;
  596:         $krbdefdom = $2;
  597:     } elsif ($currentauth=~ /^(unix|internal|localauth):/) {
  598:         $currentauth = $1;
  599:     } else {
  600:         $$logmsg .= "Invalid authentication method $currentauth for $uname.".$linefeed;
  601:     }
  602: # Report if authentication methods are different.
  603:     if ($currentauth ne $auth) {
  604:         $$logmsg .= "Authentication type mismatch for $uname - '$currentauth' in system, '$auth' based on information in classlist or default for this course.".$linefeed;
  605:     } elsif ($auth =~ m/^krb/) {
  606:         if ($krbdefdom ne $authparam) {
  607:             $$logmsg .= "Kerberos domain mismatch for $uname - '$krbdefdom' in system, '$authparam' based on information in classlist or default for this course.".$linefeed;
  608:         }
  609:     }
  610:                                                                                   
  611: # Check user data
  612:     if ($first  ne $userenv{'firstname'}  ||
  613:         $middle ne $userenv{'middlename'} ||
  614:         $last   ne $userenv{'lastname'}   ||
  615:         $gene   ne $userenv{'generation'} ||
  616:         $pid    ne $userenv{'id'} ||
  617:         $emailenc ne $userenv{'permanentemail'} ) {
  618: # Make the change(s)
  619:         my %changeHash;
  620:         $changeHash{'firstname'}  = $first;
  621:         $changeHash{'middlename'} = $middle;
  622:         $changeHash{'lastname'}   = $last;
  623:         $changeHash{'generation'} = $gene;
  624:         $changeHash{'id'} = $pid;
  625:         $changeHash{'permanentemail'} = $emailenc;
  626:         my $putresult = &Apache::lonnet::put('environment',\%changeHash,$dom,$uname);
  627:         if ($putresult eq 'ok') {
  628:             $$logmsg .= "User information updated for user: $uname prior to enrollment.".$linefeed;
  629:         } else {
  630:             $$logmsg .= "There was a problem modifying user data for existing user - $uname -error: $putresult, enrollment will still be attempted.".$linefeed;
  631:         }
  632:     }
  633:                                                                                   
  634: # Assign the role of student in the course.
  635:     my $classlist_reply = &Apache::lonnet::modify_student_enrollment($dom,$uname,$pid,$first,$middle,$last,$gene,$usec,$end,$start,'auto','',$cid);
  636:     if ($classlist_reply eq 'ok') {
  637:         my $access = &showaccess($end,$start);
  638:         if ($caller eq 'switchtype') {
  639:             $$logmsg .= "Existing user $uname detected in institutional classlist - switched from 'manual' to 'auto' enrollment in section/group $usec.".$access.$linefeed;
  640:         } elsif ($caller eq 'newstudent') {
  641:             $$enrollcount ++;
  642:             $$addresult .= "$first $last ($pid) - $uname enrolled in section/group $usec.".$access.$linefeed;
  643:         }
  644:         if ($context eq 'automated') {
  645:             $$logmsg .= "Existing $dom user $uname enrolled successfully.".$linefeed;
  646:         }
  647:     } else {
  648:            $$logmsg .= "There was a problem updating the classlist db file for user $uname to show the new enrollment -error: $classlist_reply, so no enrollment occurred for this user.".$linefeed;
  649:     }
  650:     return;
  651: }
  652: 
  653: sub datechange_check {
  654:     my ($oldstart,$oldend,$startdate,$enddate) = @_;
  655:     my $datechange = 0;
  656:     unless ($oldstart eq $startdate) {
  657:         $datechange = 1;
  658:     }
  659:     if (!$datechange) {
  660:         if (!$oldend) {
  661:             if ($enddate) {
  662:                 $datechange = 1;
  663:             }
  664:         } elsif ($oldend ne $enddate) {
  665:             $datechange = 1;
  666:         }
  667:     }
  668:     return $datechange;
  669: }
  670: 
  671: sub showaccess {
  672:     my ($end,$start) = @_;
  673:     my $showstart;
  674:     my $showend;
  675:     if ( (!$start) || ($start <= time) ) {
  676:         $showstart = 'immediately';
  677:     } else {
  678:         $showstart = &Apache::lonlocal::locallocaltime($start);
  679:     }
  680:     if (!$end) {
  681:         $showend = 'no end date';
  682:     } else {
  683:         $showend = &Apache::lonlocal::locallocaltime($end);
  684:     }
  685:     my $access_msg = " Access starts: ".$showstart.", ends: ".$showend.".";
  686:     return $access_msg;
  687: }
  688: 
  689: sub parse_classlist {
  690:     my ($tmpdir,$dom,$crs,$class,$placeref,$groupID,$studentsref) = @_;
  691:     my $xmlfile = $tmpdir."/tmp/".$dom."_".$crs."_".$class."_classlist.xml";
  692:     my $uname = '';
  693:     my @state;
  694:     my @items = ('autharg','authtype','email','firstname','generation','lastname','middlename','studentID');
  695:     my $p = HTML::Parser->new
  696:     (
  697:         xml_mode => 1,
  698:         start_h =>
  699:             [sub {
  700:                  my ($tagname, $attr) = @_;
  701:                  push @state, $tagname;
  702:                  if ("@state" eq "students student") {
  703:                      $uname = $attr->{username};
  704:                  }
  705:             }, "tagname, attr"],
  706:          text_h =>
  707:              [sub {
  708:                  my ($text) = @_;
  709:                  if ("@state" eq "students student groupID") {
  710:                      $$studentsref{$uname}[ $$placeref{'groupID'} ] = $groupID;
  711:                  } elsif ("@state" eq "students student startdate") {
  712:                      my $start = $text;
  713:                      unless ($text eq '') {
  714:                          $start = &process_date($text);
  715:                      }
  716:                      $$studentsref{$uname}[ $$placeref{'startdate'} ] = $start; 
  717:                  } elsif ("@state" eq "students student enddate") {
  718:                      my $end = $text;
  719:                      unless ($text eq '') {
  720:                          $end = &process_date($text);
  721:                      }
  722:                      $$studentsref{$uname}[ $$placeref{'enddate'} ] = $end;
  723:                  } else {
  724:                      foreach my $item (@items) {
  725:                          if ("@state" eq "students student $item") {
  726:                              $$studentsref{$uname}[ $$placeref{$item} ] = $text;
  727:                          }
  728:                      }
  729:                  }
  730:                }, "dtext"],
  731:          end_h =>
  732:                [sub {
  733:                    my ($tagname) = @_;
  734:                    pop @state;
  735:                 }, "tagname"],
  736:     );
  737:                                                                                                              
  738:     $p->parse_file($xmlfile);
  739:     $p->eof;
  740:     if (-e "$xmlfile") {
  741:         unlink $xmlfile;
  742:     }
  743:     return;
  744: }
  745: 
  746: sub process_date {
  747:     my $timestr = shift;
  748:     my $timestamp = '';
  749:     if ($timestr =~ m/^\d{4}:\d{2}:\d{2}/) {
  750:         my @entries = split/:/,$timestr;
  751:         for (my $j=0; $j<@entries; $j++) {
  752:             if ( length($entries[$j]) > 1 ) {
  753:                 $entries[$j] =~ s/^0//;
  754:             }
  755:         }
  756:         $entries[1] = $entries[1] - 1;
  757:         $timestamp =  timelocal($entries[5],$entries[4],$entries[3],$entries[2],$entries[1],$entries[0]);
  758:     }
  759:     return $timestamp;
  760: }
  761: 
  762: sub create_password {
  763:     my $passwd = '';
  764:     my @letts = ("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z");
  765:     for (my $i=0; $i<8; $i++) {
  766:         my $lettnum = int (rand 2);
  767:         my $item = '';
  768:         if ($lettnum) {
  769:             $item = $letts[int( rand(26) )];
  770:             my $uppercase = int(rand 2);
  771:             if ($uppercase) {
  772:                 $item =~ tr/a-z/A-Z/;
  773:             }
  774:         } else {
  775:             $item = int( rand(10) );
  776:         } 
  777:         $passwd .= $item;
  778:     }
  779:     return ($passwd);
  780: }
  781: 
  782: sub get_courseinfo {
  783:     my ($dom,$crs,$courseinfo) = @_;
  784:     my $owner;
  785:     if (defined($dom) && defined($crs)) {
  786:         my %settings = &Apache::lonnet::get('environment',['internal.coursecode','description'],$dom,$crs);
  787:         if ( defined($settings{'internal.coursecode'}) ) {
  788:             $$courseinfo{'inst_code'} = $settings{'internal.coursecode'};
  789: 
  790:         }
  791:         if ( defined($settings{'description'}) ) {
  792:             $$courseinfo{'description'} = $settings{'description'};
  793:         }
  794:     }
  795:     return;
  796: }
  797: 
  798: sub CL_autharg { return 0; }
  799: sub CL_authtype { return 1;}
  800: sub CL_email { return 2;}
  801: sub CL_enddate { return 3;}
  802: sub CL_firstname { return 4;}
  803: sub CL_generation { return 5;}
  804: sub CL_groupID { return 6;}
  805: sub CL_lastname { return 7;}
  806: sub CL_middlename { return 8;}
  807: sub CL_startdate { return 9; }
  808: sub CL_studentID { return 10; }
  809: 
  810: 1;

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>