File:  [LON-CAPA] / loncom / enrollment / Enrollment.pm
Revision 1.38: download - view: text, annotated - select for diffs
Wed Apr 30 23:59:13 2008 UTC (16 years ago) by raeburn
Branches: MAIN
CVS tags: version_2_6_99_1, version_2_6_99_0, HEAD
Bug 5176. Record of role changes in a course in nohist_rolelog.db
- Pass context arg to lonnet::assignrole() and lonnet::modify_student_enrollment().
- Replace separate subroutines (CL_*) for authargm authtype, email,enddate, etc indices with call to &place_hash() and retrieve as a hash.

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

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