Annotation of loncom/interface/lonuserutils.pm, revision 1.185

1.1       raeburn     1: # The LearningOnline Network with CAPA
                      2: # Utility functions for managing LON-CAPA user accounts
                      3: #
1.185   ! raeburn     4: # $Id: lonuserutils.pm,v 1.184 2017/07/07 02:50:41 raeburn Exp $
1.1       raeburn     5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA#
                     23: # /home/httpd/html/adm/gpl.txt
                     24: #
                     25: # http://www.lon-capa.org/
                     26: #
                     27: #
                     28: ###############################################################
                     29: ###############################################################
                     30: 
                     31: package Apache::lonuserutils;
                     32: 
1.175     raeburn    33: =pod
                     34: 
                     35: =head1 NAME
                     36: 
                     37: Apache::lonuserutils.pm
                     38: 
                     39: =head1 SYNOPSIS
                     40: 
                     41:     Utilities for management of users and custom roles
                     42: 
                     43:     Provides subroutines called by loncreateuser.pm
                     44: 
                     45: =head1 OVERVIEW
                     46: 
                     47: =cut
                     48: 
1.1       raeburn    49: use strict;
                     50: use Apache::lonnet;
                     51: use Apache::loncommon();
                     52: use Apache::lonhtmlcommon;
                     53: use Apache::lonlocal;
1.8       raeburn    54: use Apache::longroup;
1.174     raeburn    55: use HTML::Entities;
1.8       raeburn    56: use LONCAPA qw(:DEFAULT :match);
1.1       raeburn    57: 
                     58: ###############################################################
                     59: ###############################################################
                     60: # Drop student from all sections of a course, except optional $csec
                     61: sub modifystudent {
1.52      raeburn    62:     my ($udom,$unam,$courseid,$csec,$desiredhost,$context)=@_;
1.1       raeburn    63:     # if $csec is undefined, drop the student from all the courses matching
                     64:     # this one.  If $csec is defined, drop them from all other sections of
                     65:     # this course and add them to section $csec
1.17      raeburn    66:     my ($cnum,$cdom) = &get_course_identity($courseid);
1.138     raeburn    67:     my %roles = &Apache::lonnet::dump('roles',$udom,$unam);
1.1       raeburn    68:     my ($tmp) = keys(%roles);
                     69:     # Bail out if we were unable to get the students roles
                     70:     return "$1" if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                     71:     # Go through the roles looking for enrollment in this course
                     72:     my $result = '';
                     73:     foreach my $course (keys(%roles)) {
                     74:         if ($course=~m{^/\Q$cdom\E/\Q$cnum\E(?:\/)*(?:\s+)*(\w+)*\_st$}) {
                     75:             # We are in this course
                     76:             my $section=$1;
                     77:             $section='' if ($course eq "/$cdom/$cnum".'_st');
                     78:             if (defined($csec) && $section eq $csec) {
                     79:                 $result .= 'ok:';
                     80:             } elsif ( ((!$section) && (!$csec)) || ($section ne $csec) ) {
                     81:                 my (undef,$end,$start)=split(/\_/,$roles{$course});
                     82:                 my $now=time;
                     83:                 # if this is an active role
                     84:                 if (!($start && ($now<$start)) || !($end && ($now>$end))) {
                     85:                     my $reply=&Apache::lonnet::modifystudent
                     86:                         # dom  name  id mode pass     f     m     l     g
                     87:                         ($udom,$unam,'',  '',  '',undef,undef,undef,undef,
1.22      raeburn    88:                          $section,time,undef,undef,$desiredhost,'','manual',
1.52      raeburn    89:                          '',$courseid,'',$context);
1.1       raeburn    90:                     $result .= $reply.':';
                     91:                 }
                     92:             }
                     93:         }
                     94:     }
                     95:     if ($result eq '') {
1.37      raeburn    96:         $result = &mt('Unable to find section for this student');
1.1       raeburn    97:     } else {
                     98:         $result =~ s/(ok:)+/ok/g;
                     99:     }
                    100:     return $result;
                    101: }
                    102: 
                    103: sub modifyuserrole {
                    104:     my ($context,$setting,$changeauth,$cid,$udom,$uname,$uid,$umode,$upass,
                    105:         $first,$middle,$last,$gene,$sec,$forceid,$desiredhome,$email,$role,
1.84      raeburn   106:         $end,$start,$checkid,$inststatus) = @_;
1.5       raeburn   107:     my ($scope,$userresult,$authresult,$roleresult,$idresult);
1.1       raeburn   108:     if ($setting eq 'course' || $context eq 'course') {
                    109:         $scope = '/'.$cid;
                    110:         $scope =~ s/\_/\//g;
1.103     raeburn   111:         if (($role ne 'cc') && ($role ne 'co') && ($sec ne '')) {
1.1       raeburn   112:             $scope .='/'.$sec;
                    113:         }
1.5       raeburn   114:     } elsif ($context eq 'domain') {
1.1       raeburn   115:         $scope = '/'.$env{'request.role.domain'}.'/';
1.13      raeburn   116:     } elsif ($context eq 'author') {
1.1       raeburn   117:         $scope =  '/'.$env{'user.domain'}.'/'.$env{'user.name'};
                    118:     }
                    119:     if ($context eq 'domain') {
                    120:         my $uhome = &Apache::lonnet::homeserver($uname,$udom);
                    121:         if ($uhome ne 'no_host') {
1.5       raeburn   122:             if (($changeauth eq 'Yes') && (&Apache::lonnet::allowed('mau',$udom))) {
1.1       raeburn   123:                 if ((($umode =~ /^krb4|krb5|internal$/) && $upass ne '') ||
                    124:                     ($umode eq 'localauth')) {
                    125:                     $authresult = &Apache::lonnet::modifyuserauth($udom,$uname,$umode,$upass);
                    126:                 }
                    127:             }
1.5       raeburn   128:             if (($forceid) && (&Apache::lonnet::allowed('mau',$udom)) &&
                    129:                 ($env{'form.recurseid'}) && ($checkid)) {
                    130:                 my %userupdate = (
                    131:                                   lastname   => $last,
                    132:                                   middlename => $middle,
                    133:                                   firstname  => $first,
                    134:                                   generation => $gene,
                    135:                                   id         => $uid,
                    136:                                  );
                    137:                 $idresult = &propagate_id_change($uname,$udom,\%userupdate);
                    138:             }
1.1       raeburn   139:         }
                    140:     }
                    141:     $userresult =
                    142:         &Apache::lonnet::modifyuser($udom,$uname,$uid,$umode,$upass,$first,
                    143:                                     $middle,$last,$gene,$forceid,$desiredhome,
1.84      raeburn   144:                                     $email,$inststatus);
1.1       raeburn   145:     if ($userresult eq 'ok') {
1.5       raeburn   146:         if ($role ne '') {
1.22      raeburn   147:             $role =~ s/_/\//g;
1.1       raeburn   148:             $roleresult = &Apache::lonnet::assignrole($udom,$uname,$scope,
1.52      raeburn   149:                                                       $role,$end,$start,'',
                    150:                                                       '',$context);
1.1       raeburn   151:         }
                    152:     }
1.5       raeburn   153:     return ($userresult,$authresult,$roleresult,$idresult);
1.1       raeburn   154: }
                    155: 
1.5       raeburn   156: sub propagate_id_change {
                    157:     my ($uname,$udom,$user) = @_;
1.12      raeburn   158:     my (@types,@roles);
1.5       raeburn   159:     @types = ('active','future');
                    160:     @roles = ('st');
                    161:     my $idresult;
                    162:     my %roleshash = &Apache::lonnet::get_my_roles($uname,
1.12      raeburn   163:                         $udom,'userroles',\@types,\@roles);
                    164:     my %args = (
                    165:                 one_time => 1,
                    166:                );
1.5       raeburn   167:     foreach my $item (keys(%roleshash)) {
1.22      raeburn   168:         my ($cnum,$cdom,$role) = split(/:/,$item,-1);
1.5       raeburn   169:         my ($start,$end) = split(/:/,$roleshash{$item});
                    170:         if (&Apache::lonnet::is_course($cdom,$cnum)) {
1.12      raeburn   171:             my $result = &update_classlist($cdom,$cnum,$udom,$uname,$user);
                    172:             my %coursehash = 
                    173:                 &Apache::lonnet::coursedescription($cdom.'_'.$cnum,\%args);
                    174:             my $cdesc = $coursehash{'description'};
                    175:             if ($cdesc eq '') { 
                    176:                 $cdesc = $cdom.'_'.$cnum;
                    177:             }
1.5       raeburn   178:             if ($result eq 'ok') {
1.12      raeburn   179:                 $idresult .= &mt('Classlist update for "[_1]" in "[_2]".',$uname.':'.$udom,$cdesc).'<br />'."\n";
1.5       raeburn   180:             } else {
1.12      raeburn   181:                 $idresult .= &mt('Error: "[_1]" during classlist update for "[_2]" in "[_3]".',$result,$uname.':'.$udom,$cdesc).'<br />'."\n";
1.5       raeburn   182:             }
                    183:         }
                    184:     }
                    185:     return $idresult;
                    186: }
                    187: 
                    188: sub update_classlist {
1.63      raeburn   189:     my ($cdom,$cnum,$udom,$uname,$user,$newend) = @_;
1.6       albertel  190:     my ($uid,$classlistentry);
1.5       raeburn   191:     my $fullname =
                    192:         &Apache::lonnet::format_name($user->{'firstname'},$user->{'middlename'},
                    193:                                      $user->{'lastname'},$user->{'generation'},
                    194:                                      'lastname');
                    195:     my %classhash = &Apache::lonnet::get('classlist',[$uname.':'.$udom],
                    196:                                          $cdom,$cnum);
                    197:     my @classinfo = split(/:/,$classhash{$uname.':'.$udom});
                    198:     my $ididx=&Apache::loncoursedata::CL_ID() - 2;
                    199:     my $nameidx=&Apache::loncoursedata::CL_FULLNAME() - 2;
1.63      raeburn   200:     my $endidx = &Apache::loncoursedata::CL_END() - 2;
                    201:     my $startidx = &Apache::loncoursedata::CL_START() - 2;
1.5       raeburn   202:     for (my $i=0; $i<@classinfo; $i++) {
1.63      raeburn   203:         if ($i == $endidx) {
                    204:             if ($newend ne '') {
                    205:                 $classlistentry .= $newend.':';
                    206:             } else {
                    207:                 $classlistentry .= $classinfo[$i].':';
                    208:             }
                    209:         } elsif ($i == $startidx) {
                    210:             if ($newend ne '') {
                    211:                 if ($classinfo[$i] > $newend) {
                    212:                     $classlistentry .= $newend.':';
                    213:                 } else {
                    214:                     $classlistentry .= $classinfo[$i].':';
                    215:                 }
                    216:             } else {
                    217:                 $classlistentry .= $classinfo[$i].':';
                    218:             }
                    219:         } elsif ($i == $ididx) {
1.5       raeburn   220:             if (defined($user->{'id'})) {
                    221:                 $classlistentry .= $user->{'id'}.':';
                    222:             } else {
                    223:                 $classlistentry .= $classinfo[$i].':';
                    224:             }
                    225:         } elsif ($i == $nameidx) {
1.63      raeburn   226:             if (defined($user->{'lastname'})) {
                    227:                 $classlistentry .= $fullname.':';
                    228:             } else {
                    229:                 $classlistentry .= $classinfo[$i].':';
                    230:             }
1.5       raeburn   231:         } else {
                    232:             $classlistentry .= $classinfo[$i].':';
                    233:         }
                    234:     }
                    235:     $classlistentry =~ s/:$//;
                    236:     my $reply=&Apache::lonnet::cput('classlist',
                    237:                                     {"$uname:$udom" => $classlistentry},
                    238:                                     $cdom,$cnum);
                    239:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                    240:         return 'ok';
                    241:     } else {
                    242:         return 'error: '.$reply;
                    243:     }
                    244: }
                    245: 
                    246: 
1.1       raeburn   247: ###############################################################
                    248: ###############################################################
1.2       raeburn   249: # build a role type and role selection form
                    250: sub domain_roles_select {
                    251:     # Set up the role type and role selection boxes when in 
                    252:     # domain context   
                    253:     #
                    254:     # Role types
1.101     raeburn   255:     my @roletypes = ('domain','author','course','community');
1.2       raeburn   256:     my %lt = &role_type_names();
1.149     raeburn   257:     my $onchangefirst = "updateCols('showrole')";
                    258:     my $onchangesecond = "updateCols('showrole')";
1.1       raeburn   259:     #
                    260:     # build up the menu information to be passed to
                    261:     # &Apache::loncommon::linked_select_forms
                    262:     my %select_menus;
1.2       raeburn   263:     if ($env{'form.roletype'} eq '') {
                    264:         $env{'form.roletype'} = 'domain';
                    265:     }
                    266:     foreach my $roletype (@roletypes) {
1.1       raeburn   267:         # set up the text for this domain
1.2       raeburn   268:         $select_menus{$roletype}->{'text'}= $lt{$roletype};
1.102     raeburn   269:         my $crstype;
                    270:         if ($roletype eq 'community') {
                    271:             $crstype = 'Community';
                    272:         }
1.1       raeburn   273:         # we want a choice of 'default' as the default in the second menu
1.2       raeburn   274:         if ($env{'form.roletype'} ne '') {
                    275:             $select_menus{$roletype}->{'default'} = $env{'form.showrole'};
                    276:         } else { 
                    277:             $select_menus{$roletype}->{'default'} = 'Any';
                    278:         }
1.1       raeburn   279:         # Now build up the other items in the second menu
1.2       raeburn   280:         my @roles;
                    281:         if ($roletype eq 'domain') {
                    282:             @roles = &domain_roles();
1.13      raeburn   283:         } elsif ($roletype eq 'author') {
1.2       raeburn   284:             @roles = &construction_space_roles();
                    285:         } else {
1.17      raeburn   286:             my $custom = 1;
1.101     raeburn   287:             @roles = &course_roles('domain',undef,$custom,$roletype);
1.1       raeburn   288:         }
1.2       raeburn   289:         my $order = ['Any',@roles];
                    290:         $select_menus{$roletype}->{'order'} = $order; 
                    291:         foreach my $role (@roles) {
1.5       raeburn   292:             if ($role eq 'cr') {
                    293:                 $select_menus{$roletype}->{'select2'}->{$role} =
                    294:                               &mt('Custom role');
                    295:             } else {
                    296:                 $select_menus{$roletype}->{'select2'}->{$role} = 
1.102     raeburn   297:                               &Apache::lonnet::plaintext($role,$crstype);
1.5       raeburn   298:             }
1.2       raeburn   299:         }
                    300:         $select_menus{$roletype}->{'select2'}->{'Any'} = &mt('Any');
1.1       raeburn   301:     }
1.2       raeburn   302:     my $result = &Apache::loncommon::linked_select_forms
                    303:         ('studentform',('&nbsp;'x3).&mt('Role: '),$env{'form.roletype'},
1.101     raeburn   304:          'roletype','showrole',\%select_menus,
1.149     raeburn   305:          ['domain','author','course','community'],$onchangefirst,
                    306:          $onchangesecond);
1.1       raeburn   307:     return $result;
                    308: }
                    309: 
                    310: ###############################################################
                    311: ###############################################################
                    312: sub hidden_input {
                    313:     my ($name,$value) = @_;
                    314:     return '<input type="hidden" name="'.$name.'" value="'.$value.'" />'."\n";
                    315: }
                    316: 
                    317: sub print_upload_manager_header {
1.123     raeburn   318:     my ($r,$datatoken,$distotal,$krbdefdom,$context,$permission,$crstype,
                    319:         $can_assign)=@_;
1.1       raeburn   320:     my $javascript;
                    321:     #
                    322:     if (! exists($env{'form.upfile_associate'})) {
                    323:         $env{'form.upfile_associate'} = 'forward';
                    324:     }
                    325:     if ($env{'form.associate'} eq 'Reverse Association') {
                    326:         if ( $env{'form.upfile_associate'} ne 'reverse' ) {
                    327:             $env{'form.upfile_associate'} = 'reverse';
                    328:         } else {
                    329:             $env{'form.upfile_associate'} = 'forward';
                    330:         }
                    331:     }
                    332:     if ($env{'form.upfile_associate'} eq 'reverse') {
1.123     raeburn   333:         $javascript=&upload_manager_javascript_reverse_associate($can_assign);
1.1       raeburn   334:     } else {
1.123     raeburn   335:         $javascript=&upload_manager_javascript_forward_associate($can_assign);
1.1       raeburn   336:     }
                    337:     #
                    338:     # Deal with restored settings
                    339:     my $password_choice = '';
                    340:     if (exists($env{'form.ipwd_choice'}) &&
                    341:         $env{'form.ipwd_choice'} ne '') {
                    342:         # If a column was specified for password, assume it is for an
                    343:         # internal password.  This is a bug waiting to be filed (could be
                    344:         # local or krb auth instead of internal) but I do not have the
                    345:         # time to mess around with this now.
                    346:         $password_choice = 'int';
                    347:     }
                    348:     #
1.22      raeburn   349:     my $groupslist;
                    350:     if ($context eq 'course') {
                    351:         $groupslist = &get_groupslist();
                    352:     }
1.1       raeburn   353:     my $javascript_validations =
1.22      raeburn   354:         &javascript_validations('upload',$krbdefdom,$password_choice,undef,
                    355:                                 $env{'request.role.domain'},$context,
1.103     raeburn   356:                                 $groupslist,$crstype);
1.91      bisitz    357:     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
1.147     bisitz    358:     $r->print(
                    359:         '<h3>'.&mt('Identify fields in uploaded list')."</h3>\n".
                    360:         '<p class="LC_info">'.
                    361:         &mt('Total number of records found in file: [_1]'
                    362:            ,'<b>'.$distotal.'</b>').
                    363:         "</p>\n"
                    364:     );
                    365:     if ($distotal == 0) {
                    366:         $r->print('<p class="LC_warning">'.&mt('None found').'</p>');
                    367:     }
                    368:     $r->print(
                    369:         '<p>'.
                    370:         &mt('Enter as many fields as you can.').'<br />'.
                    371:         &mt('The system will inform you and bring you back to this page,[_1]if the data selected are insufficient to add users.','<br />').
                    372:         "</p>\n"
                    373:     );
1.1       raeburn   374:     $r->print(&hidden_input('action','upload').
                    375:               &hidden_input('state','got_file').
                    376:               &hidden_input('associate','').
                    377:               &hidden_input('datatoken',$datatoken).
                    378:               &hidden_input('fileupload',$env{'form.fileupload'}).
                    379:               &hidden_input('upfiletype',$env{'form.upfiletype'}).
                    380:               &hidden_input('upfile_associate',$env{'form.upfile_associate'}));
1.147     bisitz    381:     $r->print(
                    382:         '<div class="LC_left_float">'.
                    383:         '<fieldset><legend>'.&mt('Functions').'</legend>'.
                    384:         '<label><input type="checkbox" name="noFirstLine"'.$checked.' />'.
                    385:               &mt('Ignore First Line').'</label>'.
                    386:         ' <input type="button" value="'.&mt('Reverse Association').'" '.
1.59      bisitz    387:               'name="Reverse Association" '.
1.147     bisitz    388:               'onclick="javascript:this.form.associate.value=\'Reverse Association\';submit(this.form);" />'.
                    389:         '</fieldset></div><br clear="all" />'
                    390:     );
                    391:     $r->print(
                    392:         '<script type="text/javascript" language="Javascript">'."\n".
                    393:         '// <![CDATA['."\n".
                    394:         $javascript."\n".$javascript_validations."\n".
                    395:         '// ]]>'."\n".
                    396:         '</script>'
                    397:     );
1.1       raeburn   398: }
                    399: 
                    400: ###############################################################
                    401: ###############################################################
                    402: sub javascript_validations {
1.22      raeburn   403:     my ($mode,$krbdefdom,$curr_authtype,$curr_authfield,$domain,
1.103     raeburn   404:         $context,$groupslist,$crstype)=@_;
1.22      raeburn   405:     my %param = (
                    406:                   kerb_def_dom => $krbdefdom,
                    407:                   curr_authtype => $curr_authtype,
                    408:                 );
1.37      raeburn   409:     if ($mode eq 'upload') {
1.22      raeburn   410:         $param{'formname'} = 'studentform';
1.1       raeburn   411:     } elsif ($mode eq 'createcourse') {
1.22      raeburn   412:         $param{'formname'} = 'ccrs';
1.1       raeburn   413:     } elsif ($mode eq 'modifycourse') {
1.22      raeburn   414:         $param{'formname'} = 'cmod';
                    415:         $param{'mode'} = 'modifycourse',
                    416:         $param{'curr_autharg'} = $curr_authfield;
                    417:     }
                    418: 
1.150     raeburn   419:     my $showcredits;
                    420:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
1.160     raeburn   421:     if ($domdefaults{'officialcredits'} || $domdefaults{'unofficialcredits'} || $domdefaults{'textbookcredits'}) {
1.150     raeburn   422:         $showcredits = 1;
                    423:     }
                    424: 
1.22      raeburn   425:     my ($setsection_call,$setsections_js);
                    426:     my $finish = "  vf.submit();\n";
                    427:     if ($mode eq 'upload') {
                    428:         if (($context eq 'course') || ($context eq 'domain')) {
                    429:             if ($context eq 'course') {
                    430:                 if ($env{'request.course.sec'} eq '') {
1.109     raeburn   431:                     $setsection_call = 'setSections(document.'.$param{'formname'}.",'$crstype'".');';
1.22      raeburn   432:                     $setsections_js =
                    433:                         &setsections_javascript($param{'formname'},$groupslist,
1.150     raeburn   434:                                                 $mode,'',$crstype,$showcredits);
1.22      raeburn   435:                 } else {
                    436:                     $setsection_call = "'ok'";
                    437:                 }
                    438:             } elsif ($context eq 'domain') {
                    439:                 $setsection_call = 'setCourse()';
1.150     raeburn   440:                 $setsections_js = &dc_setcourse_js($param{'formname'},$mode,
                    441:                                                    $context,$showcredits);
1.22      raeburn   442:             }
                    443:             $finish = "  var checkSec = $setsection_call\n".
                    444:                       "  if (checkSec == 'ok') {\n".
                    445:                       "      vf.submit();\n".
                    446:                       "   }\n";
                    447:         }
1.1       raeburn   448:     }
1.22      raeburn   449:     my $authheader = &Apache::loncommon::authform_header(%param);
1.1       raeburn   450: 
                    451:     my %alert = &Apache::lonlocal::texthash
                    452:         (username => 'You need to specify the username field.',
                    453:          authen   => 'You must choose an authentication type.',
                    454:          krb      => 'You need to specify the Kerberos domain.',
                    455:          ipass    => 'You need to specify the initial password.',
                    456:          name     => 'The optional name field was not specified.',
1.93      bisitz    457:          snum     => 'The optional student/employee ID field was not specified.',
1.1       raeburn   458:          section  => 'The optional section field was not specified.',
1.75      schafran  459:          email    => 'The optional e-mail address field was not specified.',
1.1       raeburn   460:          role     => 'The optional role field was not specified.',
1.57      raeburn   461:          domain   => 'The optional domain field was not specified.',
1.1       raeburn   462:          continue => 'Continue adding users?',
                    463:          );
1.150     raeburn   464:     if ($showcredits) {
                    465:         $alert{'credits'} = &mt('The optional credits field was not specified');
                    466:     }
1.84      raeburn   467:     if (($mode eq 'upload') && ($context eq 'domain')) {
                    468:         $alert{'inststatus'} = &mt('The optional affiliation field was not specified'); 
                    469:     }
1.170     damieng   470:     &js_escape(\%alert);
1.37      raeburn   471:     my $function_name = <<"END";
1.22      raeburn   472: $setsections_js
                    473: 
1.150     raeburn   474: function verify_message (vf,founduname,foundpwd,foundname,foundid,foundsec,foundemail,foundrole,founddomain,foundinststatus,foundcredits) {
1.1       raeburn   475: END
                    476:     my ($authnum,%can_assign) =  &Apache::loncommon::get_assignable_auth($domain);
                    477:     my $auth_checks;
                    478:     if ($mode eq 'createcourse') {
                    479:         $auth_checks .= (<<END);
                    480:     if (vf.autoadds[0].checked == true) {
                    481:         if (current.radiovalue == null || current.radiovalue == 'nochange') {
                    482:             alert('$alert{'authen'}');
                    483:             return;
                    484:         }
                    485:     }
                    486: END
                    487:     } else {
                    488:         $auth_checks .= (<<END);
                    489:     var foundatype=0;
                    490:     if (founduname==0) {
                    491:         alert('$alert{'username'}');
                    492:         return;
                    493:     }
                    494: 
                    495: END
                    496:         if ($authnum > 1) {
                    497:             $auth_checks .= (<<END);
                    498:     if (current.radiovalue == null || current.radiovalue == '' || current.radiovalue == 'nochange') {
                    499:         // They did not check any of the login radiobuttons.
                    500:         alert('$alert{'authen'}');
                    501:         return;
                    502:     }
                    503: END
                    504:         }
                    505:     }
                    506:     if ($mode eq 'createcourse') {
                    507:         $auth_checks .= "
                    508:     if ( (vf.autoadds[0].checked == true) &&
                    509:          (vf.elements[current.argfield].value == null || vf.elements[current.argfield].value == '') ) {
                    510: ";
                    511:     } elsif ($mode eq 'modifycourse') {
                    512:         $auth_checks .= "
                    513:     if (vf.elements[current.argfield].value == null || vf.elements[current.argfield].value == '') {
                    514: ";
                    515:     }
                    516:     if ( ($mode eq 'createcourse') || ($mode eq 'modifycourse') ) {
                    517:         $auth_checks .= (<<END);
                    518:         var alertmsg = '';
                    519:         switch (current.radiovalue) {
                    520:             case 'krb':
                    521:                 alertmsg = '$alert{'krb'}';
                    522:                 break;
                    523:             default:
                    524:                 alertmsg = '';
                    525:         }
                    526:         if (alertmsg != '') {
                    527:             alert(alertmsg);
                    528:             return;
                    529:         }
                    530:     }
1.150     raeburn   531: /* regexp here to check for non \d \. in credits */
1.1       raeburn   532: END
                    533:     } else {
                    534:         $auth_checks .= (<<END);
                    535:     foundatype=1;
                    536:     if (current.argfield == null || current.argfield == '') {
                    537:         var alertmsg = '';
1.38      raeburn   538:         switch (current.radiovalue) {
1.1       raeburn   539:             case 'krb':
                    540:                 alertmsg = '$alert{'krb'}';
                    541:                 break;
                    542:             case 'loc':
                    543:             case 'fsys':
                    544:                 alertmsg = '$alert{'ipass'}';
                    545:                 break;
                    546:             case 'fsys':
                    547:                 alertmsg = '';
                    548:                 break;
                    549:             default:
                    550:                 alertmsg = '';
                    551:         }
                    552:         if (alertmsg != '') {
                    553:             alert(alertmsg);
                    554:             return;
                    555:         }
                    556:     }
                    557: END
                    558:     }
                    559:     my $section_checks;
                    560:     my $optional_checks = '';
                    561:     if ( ($mode eq 'createcourse') || ($mode eq 'modifycourse') ) {
                    562:         $optional_checks = (<<END);
                    563:     vf.submit();
                    564: }
                    565: END
                    566:     } else {
                    567:         $section_checks = &section_check_js();
                    568:         $optional_checks = (<<END);
                    569:     var message='';
                    570:     if (foundname==0) {
                    571:         message='$alert{'name'}';
                    572:     }
                    573:     if (foundid==0) {
                    574:         if (message!='') {
                    575:             message+='\\n';
                    576:         }
                    577:         message+='$alert{'snum'}';
                    578:     }
                    579:     if (foundsec==0) {
                    580:         if (message!='') {
                    581:             message+='\\n';
                    582:         }
1.130     raeburn   583:         message+='$alert{'section'}';
1.1       raeburn   584:     }
                    585:     if (foundemail==0) {
                    586:         if (message!='') {
                    587:             message+='\\n';
                    588:         }
                    589:         message+='$alert{'email'}';
                    590:     }
1.57      raeburn   591:     if (foundrole==0) {
                    592:         if (message!='') {
                    593:             message+='\\n';
                    594:         }
                    595:         message+='$alert{'role'}';
                    596:     }
                    597:     if (founddomain==0) {
                    598:         if (message!='') {
                    599:             message+='\\n';
                    600:         }
                    601:         message+='$alert{'domain'}';
                    602:     }
1.84      raeburn   603: END
1.150     raeburn   604:         if ($showcredits) {
                    605:             $optional_checks .= <<END;
                    606:     if (foundcredits==0) {
                    607:         if (message!='') {
                    608:             message+='\\n';
                    609:         }
                    610:         message+='$alert{'credits'}';
                    611:     }
                    612: END
                    613:         }
1.84      raeburn   614:         if (($mode eq 'upload') && ($context eq 'domain')) {
                    615:             $optional_checks .= (<<END);
                    616: 
                    617:     if (foundinststatus==0) {
                    618:         if (message!='') {
                    619:             message+='\\n';
                    620:         }
                    621:         message+='$alert{'inststatus'}';
                    622:     }
                    623: END
                    624:         }
                    625:         $optional_checks .= (<<END);
                    626: 
1.1       raeburn   627:     if (message!='') {
                    628:         message+= '\\n$alert{'continue'}';
                    629:         if (confirm(message)) {
                    630:             vf.state.value='enrolling';
1.22      raeburn   631:             $finish
1.1       raeburn   632:         }
                    633:     } else {
                    634:         vf.state.value='enrolling';
1.22      raeburn   635:         $finish
1.1       raeburn   636:     }
                    637: }
                    638: END
                    639:     }
1.37      raeburn   640:     my $result = $function_name.$auth_checks.$optional_checks."\n".
                    641:                  $section_checks.$authheader;
1.1       raeburn   642:     return $result;
                    643: }
                    644: ###############################################################
                    645: ###############################################################
                    646: sub upload_manager_javascript_forward_associate {
1.123     raeburn   647:     my ($can_assign) = @_;
1.132     raeburn   648:     my ($auth_update,$numbuttons,$argreset);
1.123     raeburn   649:     if (ref($can_assign) eq 'HASH') {
1.132     raeburn   650:         if ($can_assign->{'krb4'} || $can_assign->{'krb5'}) {
                    651:             $argreset .= "      vf.krbarg.value='';\n";
                    652:             $numbuttons ++ ;
                    653:         }
                    654:         if ($can_assign->{'int'}) {
                    655:             $argreset .= "      vf.intarg.value='';\n";
                    656:             $numbuttons ++;
                    657:         }
                    658:         if ($can_assign->{'loc'}) {
                    659:             $argreset .= "      vf.locarg.value='';\n";
                    660:             $numbuttons ++;
                    661:         }
                    662:         if (!$can_assign->{'int'}) {
1.170     damieng   663:             my $warning = &mt('You may not specify an initial password for each user, as this is only available when new users use LON-CAPA internal authentication.')."\n".
1.132     raeburn   664:                           &mt('Your current role does not have rights to create users with that authentication type.');
1.170     damieng   665:             &js_escape(\$warning);
1.132     raeburn   666:             $auth_update = <<"END";
                    667:    // Currently the initial password field is only supported for internal auth
                    668:    // (see bug 6368).
                    669:    if (nw==9) {
                    670:        eval('vf.f'+tf+'.selectedIndex=0;')
                    671:        alert('$warning');
                    672:    }
                    673: END
                    674:         } elsif ($numbuttons > 1) {
1.123     raeburn   675:             $auth_update = <<"END";
                    676:    // If we set the password, make the password form below correspond to
                    677:    // the new value.
                    678:    if (nw==9) {
                    679:       changed_radio('int',document.studentform);
                    680:       set_auth_radio_buttons('int',document.studentform);
1.132     raeburn   681: $argreset
                    682:    }
                    683: 
1.123     raeburn   684: END
                    685:         }
                    686:     }
                    687: 
1.1       raeburn   688:     return(<<ENDPICK);
                    689: function verify(vf,sec_caller) {
                    690:     var founduname=0;
                    691:     var foundpwd=0;
                    692:     var foundname=0;
                    693:     var foundid=0;
                    694:     var foundsec=0;
                    695:     var foundemail=0;
                    696:     var foundrole=0;
1.57      raeburn   697:     var founddomain=0;
1.84      raeburn   698:     var foundinststatus=0;
1.150     raeburn   699:     var foundcredits=0;
1.1       raeburn   700:     var tw;
                    701:     for (i=0;i<=vf.nfields.value;i++) {
                    702:         tw=eval('vf.f'+i+'.selectedIndex');
                    703:         if (tw==1) { founduname=1; }
                    704:         if ((tw>=2) && (tw<=6)) { foundname=1; }
                    705:         if (tw==7) { foundid=1; }
                    706:         if (tw==8) { foundsec=1; }
                    707:         if (tw==9) { foundpwd=1; }
                    708:         if (tw==10) { foundemail=1; }
                    709:         if (tw==11) { foundrole=1; }
1.57      raeburn   710:         if (tw==12) { founddomain=1; }
1.84      raeburn   711:         if (tw==13) { foundinststatus=1; }
1.150     raeburn   712:         if (tw==14) { foundcredits=1; }
1.1       raeburn   713:     }
1.150     raeburn   714:     verify_message(vf,founduname,foundpwd,foundname,foundid,foundsec,foundemail,foundrole,founddomain,foundinststatus,foundcredits);
1.1       raeburn   715: }
                    716: 
                    717: //
                    718: // vf = this.form
                    719: // tf = column number
                    720: //
                    721: // values of nw
                    722: //
                    723: // 0 = none
                    724: // 1 = username
                    725: // 2 = names (lastname, firstnames)
                    726: // 3 = fname (firstname)
                    727: // 4 = mname (middlename)
                    728: // 5 = lname (lastname)
                    729: // 6 = gen   (generation)
                    730: // 7 = id
                    731: // 8 = section
                    732: // 9 = ipwd  (password)
                    733: // 10 = email address
                    734: // 11 = role
1.57      raeburn   735: // 12 = domain
1.84      raeburn   736: // 13 = inststatus
1.150     raeburn   737: // 14 = foundcredits 
1.1       raeburn   738: 
                    739: function flip(vf,tf) {
                    740:    var nw=eval('vf.f'+tf+'.selectedIndex');
                    741:    var i;
                    742:    // make sure no other columns are labeled the same as this one
                    743:    for (i=0;i<=vf.nfields.value;i++) {
                    744:       if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
                    745:           eval('vf.f'+i+'.selectedIndex=0;')
                    746:       }
                    747:    }
                    748:    // If we set this to 'lastname, firstnames', clear out all the ones
                    749:    // set to 'fname','mname','lname','gen' (3,4,5,6) currently.
                    750:    if (nw==2) {
                    751:       for (i=0;i<=vf.nfields.value;i++) {
                    752:          if ((eval('vf.f'+i+'.selectedIndex')>=3) &&
                    753:              (eval('vf.f'+i+'.selectedIndex')<=6)) {
                    754:              eval('vf.f'+i+'.selectedIndex=0;')
                    755:          }
                    756:       }
                    757:    }
                    758:    // If we set this to one of 'fname','mname','lname','gen' (3,4,5,6),
                    759:    // clear out any that are set to 'lastname, firstnames' (2)
                    760:    if ((nw>=3) && (nw<=6)) {
                    761:       for (i=0;i<=vf.nfields.value;i++) {
                    762:          if (eval('vf.f'+i+'.selectedIndex')==2) {
                    763:              eval('vf.f'+i+'.selectedIndex=0;')
                    764:          }
                    765:       }
                    766:    }
1.123     raeburn   767:    $auth_update
1.1       raeburn   768: }
                    769: 
                    770: function clearpwd(vf) {
                    771:     var i;
                    772:     for (i=0;i<=vf.nfields.value;i++) {
                    773:         if (eval('vf.f'+i+'.selectedIndex')==9) {
                    774:             eval('vf.f'+i+'.selectedIndex=0;')
                    775:         }
                    776:     }
                    777: }
                    778: 
                    779: ENDPICK
                    780: }
                    781: 
                    782: ###############################################################
                    783: ###############################################################
                    784: sub upload_manager_javascript_reverse_associate {
1.123     raeburn   785:     my ($can_assign) = @_;
1.132     raeburn   786:     my ($auth_update,$numbuttons,$argreset);
1.123     raeburn   787:     if (ref($can_assign) eq 'HASH') {
1.132     raeburn   788:         if ($can_assign->{'krb4'} || $can_assign->{'krb5'}) {
                    789:             $argreset .= "      vf.krbarg.value='';\n";
                    790:             $numbuttons ++ ;
                    791:         }
                    792:         if ($can_assign->{'int'}) {
                    793:             $argreset .= "      vf.intarg.value='';\n";
                    794:             $numbuttons ++;
                    795:         }
                    796:         if ($can_assign->{'loc'}) {
                    797:             $argreset .= "      vf.locarg.value='';\n";
                    798:             $numbuttons ++;
                    799:         }
                    800:         if (!$can_assign->{'int'}) {
                    801:             my $warning = &mt('You may not specify an initial password, as this is only available when new users use LON-CAPA internal authentication.\n').
                    802:                           &mt('Your current role does not have rights to create users with that authentication type.');
1.170     damieng   803:             &js_escape(\$warning);
1.132     raeburn   804:             $auth_update = <<"END";
                    805:    // Currently the initial password field is only supported for internal auth
                    806:    // (see bug 6368).
                    807:    if (tf==8 && nw!=0) {
                    808:        eval('vf.f'+tf+'.selectedIndex=0;')
                    809:        alert('$warning');
                    810:    }
                    811: END
                    812:         } elsif ($numbuttons > 1) {
1.123     raeburn   813:             $auth_update = <<"END";
                    814:    // initial password specified, pick internal authentication
                    815:    if (tf==8 && nw!=0) {
                    816:       changed_radio('int',document.studentform);
                    817:       set_auth_radio_buttons('int',document.studentform);
1.132     raeburn   818: $argreset
                    819:    }
                    820: 
1.123     raeburn   821: END
                    822:         }
                    823:     }
1.132     raeburn   824: 
1.1       raeburn   825:     return(<<ENDPICK);
                    826: function verify(vf,sec_caller) {
                    827:     var founduname=0;
                    828:     var foundpwd=0;
                    829:     var foundname=0;
                    830:     var foundid=0;
                    831:     var foundsec=0;
1.131     raeburn   832:     var foundemail=0;
1.1       raeburn   833:     var foundrole=0;
1.57      raeburn   834:     var founddomain=0;
1.84      raeburn   835:     var foundinststatus=0;
1.150     raeburn   836:     var foundcredits=0;
1.1       raeburn   837:     var tw;
                    838:     for (i=0;i<=vf.nfields.value;i++) {
                    839:         tw=eval('vf.f'+i+'.selectedIndex');
                    840:         if (i==0 && tw!=0) { founduname=1; }
                    841:         if (((i>=1) && (i<=5)) && tw!=0 ) { foundname=1; }
                    842:         if (i==6 && tw!=0) { foundid=1; }
                    843:         if (i==7 && tw!=0) { foundsec=1; }
                    844:         if (i==8 && tw!=0) { foundpwd=1; }
1.130     raeburn   845:         if (i==9 && tw!=0) { foundemail=1; }
                    846:         if (i==10 && tw!=0) { foundrole=1; }
                    847:         if (i==11 && tw!=0) { founddomain=1; }
                    848:         if (i==12 && tw!=0) { foundinstatus=1; }
1.150     raeburn   849:         if (i==13 && tw!=0) { foundcredits=1; }
1.1       raeburn   850:     }
1.150     raeburn   851:     verify_message(vf,founduname,foundpwd,foundname,foundid,foundsec,foundemail,foundrole,founddomain,foundinststatus,foundcredits);
1.1       raeburn   852: }
                    853: 
                    854: function flip(vf,tf) {
                    855:    var nw=eval('vf.f'+tf+'.selectedIndex');
                    856:    var i;
                    857:    // picked the all one name field, reset the other name ones to blank
                    858:    if (tf==1 && nw!=0) {
                    859:       for (i=2;i<=5;i++) {
                    860:          eval('vf.f'+i+'.selectedIndex=0;')
                    861:       }
                    862:    }
                    863:    //picked one of the piecewise name fields, reset the all in
                    864:    //one field to blank
                    865:    if ((tf>=2) && (tf<=5) && (nw!=0)) {
                    866:       eval('vf.f1.selectedIndex=0;')
                    867:    }
1.123     raeburn   868:    $auth_update
1.1       raeburn   869: }
                    870: 
                    871: function clearpwd(vf) {
                    872:     var i;
                    873:     if (eval('vf.f8.selectedIndex')!=0) {
                    874:         eval('vf.f8.selectedIndex=0;')
                    875:     }
                    876: }
                    877: ENDPICK
                    878: }
                    879: 
                    880: ###############################################################
                    881: ###############################################################
                    882: sub print_upload_manager_footer {
1.150     raeburn   883:     my ($r,$i,$keyfields,$defdom,$today,$halfyear,$context,$permission,$crstype,
                    884:         $showcredits) = @_;
1.22      raeburn   885:     my $form = 'document.studentform';
                    886:     my $formname = 'studentform';
1.1       raeburn   887:     my ($krbdef,$krbdefdom) =
                    888:         &Apache::loncommon::get_kerberos_defaults($defdom);
1.22      raeburn   889:     my %param = ( formname => $form,
1.1       raeburn   890:                   kerb_def_dom => $krbdefdom,
                    891:                   kerb_def_auth => $krbdef
                    892:                   );
                    893:     if (exists($env{'form.ipwd_choice'}) &&
                    894:         defined($env{'form.ipwd_choice'}) &&
                    895:         $env{'form.ipwd_choice'} ne '') {
                    896:         $param{'curr_authtype'} = 'int';
                    897:     }
                    898:     my $krbform = &Apache::loncommon::authform_kerberos(%param);
                    899:     my $intform = &Apache::loncommon::authform_internal(%param);
                    900:     my $locform = &Apache::loncommon::authform_local(%param);
1.22      raeburn   901:     my $date_table = &date_setting_table(undef,undef,$context,undef,
1.101     raeburn   902:                                          $formname,$permission,$crstype);
1.95      bisitz    903: 
1.1       raeburn   904:     my $Str = "\n".'<div class="LC_left_float">';
                    905:     $Str .= &hidden_input('nfields',$i);
                    906:     $Str .= &hidden_input('keyfields',$keyfields);
1.95      bisitz    907: 
                    908:     $Str .= '<h3>'.&mt('Options').'</h3>'
                    909:            .&Apache::lonhtmlcommon::start_pick_box();
                    910: 
                    911:     $Str .= &Apache::lonhtmlcommon::row_title(&mt('Login Type'));
1.1       raeburn   912:     if ($context eq 'domain') {
1.95      bisitz    913:         $Str .= '<p>'
                    914:                .&mt('Change authentication for existing users in domain "[_1]" to these settings?'
                    915:                    ,$defdom)
                    916:                .'&nbsp;<span class="LC_nobreak"><label>'
                    917:                .'<input type="radio" name="changeauth" value="No" checked="checked" />'
                    918:                .&mt('No').'</label>'
                    919:                .'&nbsp;&nbsp;<label>'
                    920:                .'<input type="radio" name="changeauth" value="Yes" />'
                    921:                .&mt('Yes').'</label>'
                    922:                .'</span></p>'; 
1.1       raeburn   923:     } else {
1.95      bisitz    924:         $Str .= '<p class="LC_info">'."\n".
                    925:             &mt('This will not take effect if the user already exists.').
1.1       raeburn   926:             &Apache::loncommon::help_open_topic('Auth_Options').
                    927:             "</p>\n";
                    928:     }
1.97      raeburn   929:     $Str .= &set_login($defdom,$krbform,$intform,$locform);
1.95      bisitz    930: 
1.1       raeburn   931:     my ($home_server_pick,$numlib) =
                    932:         &Apache::loncommon::home_server_form_item($defdom,'lcserver',
                    933:                                                   'default','hide');
                    934:     if ($numlib > 1) {
1.97      raeburn   935:         $Str .= &Apache::lonhtmlcommon::row_closure()
                    936:                .&Apache::lonhtmlcommon::row_title(
1.95      bisitz    937:                     &mt('LON-CAPA Home Server for New Users'))
                    938:                .&mt('LON-CAPA domain: [_1] with home server:','"'.$defdom.'"')
                    939:                .$home_server_pick
                    940:                .&Apache::lonhtmlcommon::row_closure();
                    941:     } else {
1.97      raeburn   942:         $Str .= $home_server_pick.
                    943:                 &Apache::lonhtmlcommon::row_closure();
1.95      bisitz    944:     }
                    945: 
1.185   ! raeburn   946:     my ($trustedref,$untrustedref);
        !           947:     if ($context eq 'course') {
        !           948:         ($trustedref,$untrustedref) = &Apache::lonnet::trusted_domains('enroll',$defdom);
        !           949:     } elsif ($context eq 'author') {
        !           950:         ($trustedref,$untrustedref) = &Apache::lonnet::trusted_domains('othcoau',$defdom);
        !           951:     }
1.95      bisitz    952:     $Str .= &Apache::lonhtmlcommon::row_title(&mt('Default domain'))
1.185   ! raeburn   953:            .&Apache::loncommon::select_dom_form($defdom,'defaultdomain',undef,1,undef,$trustedref,$untrustedref)
1.95      bisitz    954:            .&Apache::lonhtmlcommon::row_closure();
                    955: 
                    956:     $Str .= &Apache::lonhtmlcommon::row_title(&mt('Starting and Ending Dates'))
                    957:            ."<p>\n".$date_table."</p>\n"
                    958:            .&Apache::lonhtmlcommon::row_closure();
                    959: 
1.1       raeburn   960:     if ($context eq 'domain') {
1.95      bisitz    961:         $Str .= &Apache::lonhtmlcommon::row_title(
                    962:                     &mt('Settings for assigning roles'))
                    963:                .&mt('Pick the action to take on roles for these users:').'<br />'
                    964:                .'<span class="LC_nobreak"><label>'
                    965:                .'<input type="radio" name="roleaction" value="norole" checked="checked" />'
                    966:                .'&nbsp;'.&mt('No role changes').'</label>'
                    967:                .'&nbsp;&nbsp;&nbsp;<label>'
                    968:                .'<input type="radio" name="roleaction" value="domain" />'
                    969:                .'&nbsp;'.&mt('Add a domain role').'</label>'
                    970:                .'&nbsp;&nbsp;&nbsp;<label>'
                    971:                .'<input type="radio" name="roleaction" value="course" />'
1.103     raeburn   972:                .'&nbsp;'.&mt('Add a course/community role').'</label>'
1.95      bisitz    973:                .'</span>';
                    974:     } elsif ($context eq 'author') {
                    975:         $Str .= &Apache::lonhtmlcommon::row_title(
                    976:                     &mt('Default role'))
                    977:                .&mt('Choose the role to assign to users without a value specified in the uploaded file.')
1.1       raeburn   978:     } elsif ($context eq 'course') {
1.150     raeburn   979:         if ($showcredits) {
                    980:             $Str .= &Apache::lonhtmlcommon::row_title(
                    981:                     &mt('Default role, section and credits'))
                    982:                    .&mt('Choose the role and/or section(s) and/or credits to assign to users without values specified in the uploaded file.');
                    983:         } else { 
                    984:             $Str .= &Apache::lonhtmlcommon::row_title(
1.95      bisitz    985:                     &mt('Default role and section'))
1.150     raeburn   986:                    .&mt('Choose the role and/or section(s) to assign to users without values specified in the uploaded file.');
                    987:         }
1.95      bisitz    988:     } else {
                    989:         $Str .= &Apache::lonhtmlcommon::row_title(
                    990:                     &mt('Default role and/or section(s)'))
                    991:                .&mt('Role and/or section(s) for users without values specified in the uploaded file.');
1.1       raeburn   992:     }
1.22      raeburn   993:     if (($context eq 'domain') || ($context eq 'author')) {
1.95      bisitz    994:         $Str .= '<br />';
1.150     raeburn   995:         my ($options,$cb_script,$coursepick) = 
                    996:             &default_role_selector($context,1,'',$showcredits);
1.22      raeburn   997:         if ($context eq 'domain') {
1.95      bisitz    998:             $Str .= '<p>'
                    999:                    .'<b>'.&mt('Domain Level').'</b><br />'
                   1000:                    .$options
                   1001:                    .'</p><p>'
                   1002:                    .'<b>'.&mt('Course Level').'</b>'
                   1003:                    .'</p>'
                   1004:                    .$cb_script.$coursepick
                   1005:                    .&Apache::lonhtmlcommon::row_closure();
1.22      raeburn  1006:         } elsif ($context eq 'author') {
1.95      bisitz   1007:             $Str .= $options
                   1008:                    .&Apache::lonhtmlcommon::row_closure(1); # last row in pick_box
1.22      raeburn  1009:         }
1.1       raeburn  1010:     } else {
1.22      raeburn  1011:         my ($cnum,$cdom) = &get_course_identity();
                   1012:         my $rowtitle = &mt('section');
1.150     raeburn  1013:         my $defaultcredits;
                   1014:         if ($showcredits) {
                   1015:             $defaultcredits = &get_defaultcredits();
                   1016:         }
                   1017:         my $secbox = &section_picker($cdom,$cnum,'Any',$rowtitle,$permission,
                   1018:                                      $context,'upload',$crstype,$showcredits,
                   1019:                                      $defaultcredits);
1.95      bisitz   1020:         $Str .= $secbox
                   1021:                .&Apache::lonhtmlcommon::row_closure();
1.101     raeburn  1022:         my %lt;
                   1023:         if ($crstype eq 'Community') {
                   1024:             %lt = &Apache::lonlocal::texthash (
                   1025:                     disp => 'Display members with current/future access who are not in the uploaded file',
                   1026:                     stus => 'Members selected from this list can be dropped.'
                   1027:             );
                   1028:         } else {
                   1029:             %lt = &Apache::lonlocal::texthash (
                   1030:                     disp => 'Display students with current/future access who are not in the uploaded file',
                   1031:                     stus => 'Students selected from this list can be dropped.'
                   1032:             );
                   1033:         }
1.95      bisitz   1034:         $Str .= &Apache::lonhtmlcommon::row_title(&mt('Full Update'))
1.101     raeburn  1035:                .'<label><input type="checkbox" name="fullup" value="yes" />'
                   1036:                .' '.$lt{'disp'}
1.95      bisitz   1037:                .'</label><br />'
1.101     raeburn  1038:                .$lt{'stus'}
1.95      bisitz   1039:                .&Apache::lonhtmlcommon::row_closure();
1.1       raeburn  1040:     }
1.5       raeburn  1041:     if ($context eq 'course' || $context eq 'domain') {
1.161     bisitz   1042:         $Str .= &Apache::lonhtmlcommon::row_title(&mt('Student/Employee ID'))
                   1043:                .&forceid_change($context)
                   1044:                .&Apache::lonhtmlcommon::row_closure(1); # last row in pick_box
1.5       raeburn  1045:     }
1.95      bisitz   1046: 
                   1047:     $Str .= &Apache::lonhtmlcommon::end_pick_box();
1.73      bisitz   1048:     $Str .= '</div>';
1.95      bisitz   1049: 
                   1050:     # Footer
                   1051:     $Str .= '<div class="LC_clear_float_footer">'
                   1052:            .'<hr />';
1.1       raeburn  1053:     if ($context eq 'course') {
1.95      bisitz   1054:         $Str .= '<p class="LC_info">'
1.103     raeburn  1055:                .&mt('Note: This operation may be time consuming when adding several users.')
1.95      bisitz   1056:                .'</p>';
1.73      bisitz   1057:     }
1.95      bisitz   1058:     $Str .= '<p><input type="button"'
1.96      bisitz   1059:            .' onclick="javascript:verify(this.form,this.form.csec)"'
                   1060:            .' value="'.&mt('Update Users').'" />'
1.95      bisitz   1061:            .'</p>'."\n"
1.73      bisitz   1062:            .'</div>';
1.1       raeburn  1063:     $r->print($Str);
                   1064:     return;
                   1065: }
                   1066: 
1.150     raeburn  1067: sub get_defaultcredits {
                   1068:     my ($cdom,$cnum) = @_;
                   1069:      
                   1070:     if ($cdom eq '' || $cnum eq '') {
                   1071:         return unless ($env{'request.course.id'});
                   1072:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   1073:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   1074:     }
                   1075:     return unless(($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)); 
                   1076:     my ($defaultcredits,$domdefcredits);
                   1077:     my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
1.160     raeburn  1078:     if ($domdefaults{'officialcredits'} || $domdefaults{'unofficialcredits'} || $domdefaults{'textbookcredits'}) {
1.150     raeburn  1079:         my $instcode = $env{'course.'.$cdom.'_'.$cnum.'.internal.coursecode'};
                   1080:         if ($instcode) {
                   1081:             $domdefcredits = $domdefaults{'officialcredits'};
1.160     raeburn  1082:         } elsif ($env{'course.'.$cdom.'_'.$cnum.'.internal.textbook'}) {
                   1083:             $domdefcredits = $domdefaults{'textbookcredits'};
1.150     raeburn  1084:         } else {
                   1085:             $domdefcredits = $domdefaults{'unofficialcredits'};
                   1086:         }
                   1087:     } else {
                   1088:         return;
                   1089:     }
                   1090: 
                   1091:     if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
                   1092:         $defaultcredits = $env{'course.'.$cdom.'_'.$cnum.'.internal.defaultcredits'};
                   1093:     } elsif (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.defaultcredits'})) {
                   1094:         $defaultcredits = $env{'course.'.$cdom.'_'.$cnum.'.internal.defaultcredits'};
                   1095:     } else {
                   1096:         my %crsinfo =
                   1097:             &Apache::lonnet::coursedescription("$cdom/$cnum",{'one_time' => 1});
                   1098:         $defaultcredits = $crsinfo{'internal.defaultcredits'};
                   1099:     }
                   1100:     if ($defaultcredits eq '') {
                   1101:         $defaultcredits = $domdefcredits;
                   1102:     }
                   1103:     return $defaultcredits;
                   1104: }
                   1105: 
1.5       raeburn  1106: sub forceid_change {
                   1107:     my ($context) = @_;
                   1108:     my $output = 
1.161     bisitz   1109:         '<label><input type="checkbox" name="forceid" value="yes" />'
1.164     bisitz   1110:        .&mt('Force change of existing ID')
1.163     raeburn  1111:        .'</label>'.&Apache::loncommon::help_open_topic('ForceIDChange')."\n";
1.5       raeburn  1112:     if ($context eq 'domain') {
1.163     raeburn  1113:         $output .= 
                   1114:             '<br />'
                   1115:            .'<label><input type="checkbox" name="recurseid" value="yes" />'
                   1116:            .&mt("Update ID in user's course(s).").'</label>'."\n";
1.5       raeburn  1117:     }
                   1118:     return $output;
                   1119: }
                   1120: 
1.1       raeburn  1121: ###############################################################
                   1122: ###############################################################
                   1123: sub print_upload_manager_form {
1.150     raeburn  1124:     my ($r,$context,$permission,$crstype,$showcredits) = @_;
1.1       raeburn  1125:     my $firstLine;
                   1126:     my $datatoken;
                   1127:     if (!$env{'form.datatoken'}) {
                   1128:         $datatoken=&Apache::loncommon::upfile_store($r);
                   1129:     } else {
                   1130:         $datatoken=$env{'form.datatoken'};
                   1131:         &Apache::loncommon::load_tmp_file($r);
                   1132:     }
                   1133:     my @records=&Apache::loncommon::upfile_record_sep();
                   1134:     if($env{'form.noFirstLine'}){
                   1135:         $firstLine=shift(@records);
                   1136:     }
                   1137:     my $total=$#records;
                   1138:     my $distotal=$total+1;
                   1139:     my $today=time;
                   1140:     my $halfyear=$today+15552000;
                   1141:     #
                   1142:     # Restore memorized settings
                   1143:     my $col_setting_names =  { 'username_choice' => 'scalar', # column settings
                   1144:                                'names_choice' => 'scalar',
                   1145:                                'fname_choice' => 'scalar',
                   1146:                                'mname_choice' => 'scalar',
                   1147:                                'lname_choice' => 'scalar',
                   1148:                                'gen_choice' => 'scalar',
                   1149:                                'id_choice' => 'scalar',
                   1150:                                'sec_choice' => 'scalar',
                   1151:                                'ipwd_choice' => 'scalar',
                   1152:                                'email_choice' => 'scalar',
                   1153:                                'role_choice' => 'scalar',
1.57      raeburn  1154:                                'domain_choice' => 'scalar',
1.84      raeburn  1155:                                'inststatus_choice' => 'scalar',
1.1       raeburn  1156:                              };
1.150     raeburn  1157:     if ($showcredits) {
                   1158:         $col_setting_names->{'credits_choice'} = 'scalar';
                   1159:     }
1.1       raeburn  1160:     if ($context eq 'course') {
                   1161:         &Apache::loncommon::restore_course_settings('enrollment_upload',
                   1162:                                                     $col_setting_names);
                   1163:     } else {
                   1164:         &Apache::loncommon::restore_settings($context,'user_upload',
                   1165:                                              $col_setting_names);
                   1166:     }
1.150     raeburn  1167:     my $defdom = $env{'request.role.domain'};
1.1       raeburn  1168:     #
                   1169:     # Determine kerberos parameters as appropriate
                   1170:     my ($krbdef,$krbdefdom) =
                   1171:         &Apache::loncommon::get_kerberos_defaults($defdom);
                   1172:     #
1.123     raeburn  1173:     my ($authnum,%can_assign) =  &Apache::loncommon::get_assignable_auth($defdom);
1.22      raeburn  1174:     &print_upload_manager_header($r,$datatoken,$distotal,$krbdefdom,$context,
1.123     raeburn  1175:                                  $permission,$crstype,\%can_assign);
1.1       raeburn  1176:     my $i;
                   1177:     my $keyfields;
                   1178:     if ($total>=0) {
                   1179:         my @field=
                   1180:             (['username',&mt('Username'),     $env{'form.username_choice'}],
                   1181:              ['names',&mt('Last Name, First Names'),$env{'form.names_choice'}],
                   1182:              ['fname',&mt('First Name'),      $env{'form.fname_choice'}],
                   1183:              ['mname',&mt('Middle Names/Initials'),$env{'form.mname_choice'}],
                   1184:              ['lname',&mt('Last Name'),       $env{'form.lname_choice'}],
                   1185:              ['gen',  &mt('Generation'),      $env{'form.gen_choice'}],
1.61      bisitz   1186:              ['id',   &mt('Student/Employee ID'),$env{'form.id_choice'}],
1.1       raeburn  1187:              ['sec',  &mt('Section'),          $env{'form.sec_choice'}],
                   1188:              ['ipwd', &mt('Initial Password'),$env{'form.ipwd_choice'}],
                   1189:              ['email',&mt('E-mail Address'),   $env{'form.email_choice'}],
1.57      raeburn  1190:              ['role',&mt('Role'),             $env{'form.role_choice'}],
1.84      raeburn  1191:              ['domain',&mt('Domain'),         $env{'form.domain_choice'}],
                   1192:              ['inststatus',&mt('Affiliation'), $env{'form.inststatus_choice'}]);
1.150     raeburn  1193:         if ($showcredits) {     
                   1194:             push(@field,
                   1195:                  ['credits',&mt('Student Credits'), $env{'form.credits_choice'}]);
                   1196:         }
1.1       raeburn  1197:         if ($env{'form.upfile_associate'} eq 'reverse') {
                   1198:             &Apache::loncommon::csv_print_samples($r,\@records);
                   1199:             $i=&Apache::loncommon::csv_print_select_table($r,\@records,
                   1200:                                                           \@field);
                   1201:             foreach (@field) {
                   1202:                 $keyfields.=$_->[0].',';
                   1203:             }
                   1204:             chop($keyfields);
                   1205:         } else {
                   1206:             unshift(@field,['none','']);
                   1207:             $i=&Apache::loncommon::csv_samples_select_table($r,\@records,
                   1208:                                                             \@field);
                   1209:             my %sone=&Apache::loncommon::record_sep($records[0]);
                   1210:             $keyfields=join(',',sort(keys(%sone)));
                   1211:         }
                   1212:     }
                   1213:     &print_upload_manager_footer($r,$i,$keyfields,$defdom,$today,$halfyear,
1.150     raeburn  1214:                                  $context,$permission,$crstype,$showcredits);
1.1       raeburn  1215: }
                   1216: 
                   1217: sub setup_date_selectors {
1.22      raeburn  1218:     my ($starttime,$endtime,$mode,$nolink,$formname) = @_;
                   1219:     if ($formname eq '') {
                   1220:         $formname = 'studentform';
                   1221:     }
1.1       raeburn  1222:     if (! defined($starttime)) {
                   1223:         $starttime = time;
                   1224:         unless ($mode eq 'create_enrolldates' || $mode eq 'create_defaultdates') {
                   1225:             if (exists($env{'course.'.$env{'request.course.id'}.
                   1226:                             '.default_enrollment_start_date'})) {
                   1227:                 $starttime = $env{'course.'.$env{'request.course.id'}.
                   1228:                                   '.default_enrollment_start_date'};
                   1229:             }
                   1230:         }
                   1231:     }
                   1232:     if (! defined($endtime)) {
                   1233:         $endtime = time+(6*30*24*60*60); # 6 months from now, approx
                   1234:         unless ($mode eq 'createcourse') {
                   1235:             if (exists($env{'course.'.$env{'request.course.id'}.
                   1236:                             '.default_enrollment_end_date'})) {
                   1237:                 $endtime = $env{'course.'.$env{'request.course.id'}.
                   1238:                                 '.default_enrollment_end_date'};
                   1239:             }
                   1240:         }
                   1241:     }
1.11      raeburn  1242: 
                   1243:     my $startdateform = 
1.22      raeburn  1244:         &Apache::lonhtmlcommon::date_setter($formname,'startdate',$starttime,
1.11      raeburn  1245:             undef,undef,undef,undef,undef,undef,undef,$nolink);
                   1246: 
                   1247:     my $enddateform = 
1.22      raeburn  1248:         &Apache::lonhtmlcommon::date_setter($formname,'enddate',$endtime,
1.11      raeburn  1249:             undef,undef,undef,undef,undef,undef,undef,$nolink);
                   1250: 
1.1       raeburn  1251:     if ($mode eq 'create_enrolldates') {
                   1252:         $startdateform = &Apache::lonhtmlcommon::date_setter('ccrs',
                   1253:                                                             'startenroll',
                   1254:                                                             $starttime);
                   1255:         $enddateform = &Apache::lonhtmlcommon::date_setter('ccrs',
                   1256:                                                           'endenroll',
                   1257:                                                           $endtime);
                   1258:     }
                   1259:     if ($mode eq 'create_defaultdates') {
                   1260:         $startdateform = &Apache::lonhtmlcommon::date_setter('ccrs',
                   1261:                                                             'startaccess',
                   1262:                                                             $starttime);
                   1263:         $enddateform = &Apache::lonhtmlcommon::date_setter('ccrs',
                   1264:                                                           'endaccess',
                   1265:                                                           $endtime);
                   1266:     }
                   1267:     return ($startdateform,$enddateform);
                   1268: }
                   1269: 
                   1270: 
                   1271: sub get_dates_from_form {
1.54      raeburn  1272:     my ($startname,$endname) = @_;
                   1273:     if ($startname eq '') {
                   1274:         $startname = 'startdate';
                   1275:     }
                   1276:     if ($endname eq '') {
                   1277:         $endname = 'enddate';
                   1278:     }
                   1279:     my $startdate = &Apache::lonhtmlcommon::get_date_from_form($startname);
                   1280:     my $enddate   = &Apache::lonhtmlcommon::get_date_from_form($endname);
1.1       raeburn  1281:     if ($env{'form.no_end_date'}) {
                   1282:         $enddate = 0;
                   1283:     }
                   1284:     return ($startdate,$enddate);
                   1285: }
                   1286: 
                   1287: sub date_setting_table {
1.101     raeburn  1288:     my ($starttime,$endtime,$mode,$bulkaction,$formname,$permission,$crstype) = @_;
1.11      raeburn  1289:     my $nolink;
                   1290:     if ($bulkaction) {
                   1291:         $nolink = 1;
                   1292:     }
                   1293:     my ($startform,$endform) = 
1.22      raeburn  1294:         &setup_date_selectors($starttime,$endtime,$mode,$nolink,$formname);
1.1       raeburn  1295:     my $dateDefault;
                   1296:     if ($mode eq 'create_enrolldates' || $mode eq 'create_defaultdates') {
                   1297:         $dateDefault = '&nbsp;';
1.13      raeburn  1298:     } elsif ($mode ne 'author' && $mode ne 'domain') {
1.11      raeburn  1299:         if (($bulkaction eq 'reenable') || 
                   1300:             ($bulkaction eq 'activate') || 
1.22      raeburn  1301:             ($bulkaction eq 'chgdates') ||
                   1302:             ($env{'form.action'} eq 'upload')) {
                   1303:             if ($env{'request.course.sec'} eq '') {
                   1304:                 $dateDefault = '<span class="LC_nobreak">'.
1.101     raeburn  1305:                     '<label><input type="checkbox" name="makedatesdefault" value="1" /> ';
                   1306:                 if ($crstype eq 'Community') {
                   1307:                     $dateDefault .= &mt("make these dates the default access dates for future community enrollment");
                   1308:                 } else {
                   1309:                     $dateDefault .= &mt("make these dates the default access dates for future course enrollment");
                   1310:                 }
                   1311:                 $dateDefault .= '</label></span>';
1.22      raeburn  1312:             }
1.11      raeburn  1313:         }
1.1       raeburn  1314:     }
1.11      raeburn  1315:     my $perpetual = '<span class="LC_nobreak"><label><input type="checkbox" name="no_end_date"';
1.1       raeburn  1316:     if (defined($endtime) && $endtime == 0) {
1.70      bisitz   1317:         $perpetual .= ' checked="checked"';
1.1       raeburn  1318:     }
1.11      raeburn  1319:     $perpetual.= ' /> '.&mt('no ending date').'</label></span>';
1.1       raeburn  1320:     if ($mode eq 'create_enrolldates') {
                   1321:         $perpetual = '&nbsp;';
                   1322:     }
1.11      raeburn  1323:     my $result = &Apache::lonhtmlcommon::start_pick_box()."\n";
                   1324:     $result .= &Apache::lonhtmlcommon::row_title(&mt('Starting Date'),
                   1325:                                                      'LC_oddrow_value')."\n".
                   1326:                $startform."\n".
                   1327:                &Apache::lonhtmlcommon::row_closure(1).
                   1328:                &Apache::lonhtmlcommon::row_title(&mt('Ending Date'), 
                   1329:                                                      'LC_oddrow_value')."\n".
                   1330:                $endform.'&nbsp;'.$perpetual.
                   1331:                &Apache::lonhtmlcommon::row_closure(1).
1.22      raeburn  1332:                &Apache::lonhtmlcommon::end_pick_box();
1.1       raeburn  1333:     if ($dateDefault) {
                   1334:         $result .=  $dateDefault.'<br />'."\n";
                   1335:     }
                   1336:     return $result;
                   1337: }
                   1338: 
                   1339: sub make_dates_default {
1.101     raeburn  1340:     my ($startdate,$enddate,$context,$crstype) = @_;
1.1       raeburn  1341:     my $result = '';
                   1342:     if ($context eq 'course') {
1.17      raeburn  1343:         my ($cnum,$cdom) = &get_course_identity();
1.1       raeburn  1344:         my $put_result = &Apache::lonnet::put('environment',
                   1345:                 {'default_enrollment_start_date'=>$startdate,
1.17      raeburn  1346:                  'default_enrollment_end_date'  =>$enddate},$cdom,$cnum);
1.1       raeburn  1347:         if ($put_result eq 'ok') {
1.101     raeburn  1348:             if ($crstype eq 'Community') {
                   1349:                 $result .= &mt('Set default start and end access dates for community.');
                   1350:             } else {
                   1351:                 $result .= &mt('Set default start and end access dates for course.');
                   1352:             }
                   1353:             $result .= '<br />'."\n";
1.1       raeburn  1354:             #
                   1355:             # Refresh the course environment
                   1356:             &Apache::lonnet::coursedescription($env{'request.course.id'},
                   1357:                                                {'freshen_cache' => 1});
                   1358:         } else {
1.101     raeburn  1359:             if ($crstype eq 'Community') {
                   1360:                 $result .= &mt('Unable to set default access dates for community');
                   1361:             } else {
                   1362:                 $result .= &mt('Unable to set default access dates for course');
                   1363:             }
                   1364:             $result .= ':'.$put_result.'<br />';
1.1       raeburn  1365:         }
                   1366:     }
                   1367:     return $result;
                   1368: }
                   1369: 
                   1370: sub default_role_selector {
1.150     raeburn  1371:     my ($context,$checkpriv,$crstype,$showcredits) = @_;
1.1       raeburn  1372:     my %customroles;
                   1373:     my ($options,$coursepick,$cb_jscript);
1.13      raeburn  1374:     if ($context ne 'author') {
1.104     raeburn  1375:         %customroles = &my_custom_roles($crstype);
1.1       raeburn  1376:     }
                   1377: 
                   1378:     my %lt=&Apache::lonlocal::texthash(
                   1379:                     'rol'  => "Role",
                   1380:                     'grs'  => "Section",
                   1381:                     'exs'  => "Existing sections",
                   1382:                     'new'  => "New section",
1.150     raeburn  1383:                     'crd'  => "Credits",
1.1       raeburn  1384:                   );
                   1385:     $options = '<select name="defaultrole">'."\n".
                   1386:                ' <option value="">'.&mt('Please select').'</option>'."\n"; 
                   1387:     if ($context eq 'course') {
1.101     raeburn  1388:         $options .= &default_course_roles($context,$checkpriv,$crstype,%customroles);
1.13      raeburn  1389:     } elsif ($context eq 'author') {
1.2       raeburn  1390:         my @roles = &construction_space_roles($checkpriv);
1.1       raeburn  1391:         foreach my $role (@roles) {
                   1392:            my $plrole=&Apache::lonnet::plaintext($role);
                   1393:            $options .= '  <option value="'.$role.'">'.$plrole.'</option>'."\n";
                   1394:         }
                   1395:     } elsif ($context eq 'domain') {
1.2       raeburn  1396:         my @roles = &domain_roles($checkpriv);
1.1       raeburn  1397:         foreach my $role (@roles) {
                   1398:            my $plrole=&Apache::lonnet::plaintext($role);
                   1399:            $options .= '  <option value="'.$role.'">'.$plrole.'</option>';
                   1400:         }
                   1401:         my $courseform = &Apache::loncommon::selectcourse_link
1.103     raeburn  1402:             ('studentform','dccourse','dcdomain','coursedesc',"$env{'request.role.domain'}",undef,'Course/Community');
1.150     raeburn  1403:         my ($credit_elem,$creditsinput);
                   1404:         if ($showcredits) {
                   1405:             $credit_elem = 'credits';
                   1406:             $creditsinput = '<td><input type="text" name="credits" value="" /></td>';
                   1407:         }
1.1       raeburn  1408:         $cb_jscript = 
1.150     raeburn  1409:             &Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'},'currsec','studentform','courserole','Course/Community',$credit_elem);
1.1       raeburn  1410:         $coursepick = &Apache::loncommon::start_data_table().
                   1411:                       &Apache::loncommon::start_data_table_header_row().
                   1412:                       '<th>'.$courseform.'</th><th>'.$lt{'rol'}.'</th>'.
                   1413:                       '<th>'.$lt{'grs'}.'</th>'.
1.150     raeburn  1414:                       '<th>'.$lt{'crd'}.'</th>'.
1.1       raeburn  1415:                       &Apache::loncommon::end_data_table_header_row().
                   1416:                       &Apache::loncommon::start_data_table_row()."\n".
1.103     raeburn  1417:                       '<td><input type="text" name="coursedesc" value="" onfocus="this.blur();opencrsbrowser('."'studentform','dccourse','dcdomain','coursedesc','','','','crstype'".')" /></td>'."\n".
1.1       raeburn  1418:                       '<td><select name="courserole">'."\n".
1.101     raeburn  1419:                       &default_course_roles($context,$checkpriv,'Course',%customroles)."\n".
1.1       raeburn  1420:                       '</select></td><td>'.
                   1421:                       '<table class="LC_createuser">'.
1.162     bisitz   1422:                       '<tr class="LC_section_row"><td valign="top">'.
1.22      raeburn  1423:                       $lt{'exs'}.'<br /><select name="currsec">'.
1.162     bisitz   1424:                       ' <option value="">&lt;--'.&mt('Pick course first').
1.1       raeburn  1425:                       '</select></td>'.
                   1426:                       '<td>&nbsp;&nbsp;</td>'.
                   1427:                       '<td valign="top">'.$lt{'new'}.'<br />'.
                   1428:                       '<input type="text" name="newsec" value="" size="5" />'.
1.22      raeburn  1429:                       '<input type="hidden" name="groups" value="" />'.
                   1430:                       '<input type="hidden" name="sections" value="" />'.
                   1431:                       '<input type="hidden" name="origdom" value="'.
                   1432:                       $env{'request.role.domain'}.'" />'.
                   1433:                       '<input type="hidden" name="dccourse" value="" />'.
                   1434:                       '<input type="hidden" name="dcdomain" value="" />'.
1.103     raeburn  1435:                       '<input type="hidden" name="crstype" value="" />'.
1.150     raeburn  1436:                       '</td></tr></table></td>'.$creditsinput.
1.1       raeburn  1437:                       &Apache::loncommon::end_data_table_row().
1.22      raeburn  1438:                       &Apache::loncommon::end_data_table()."\n";
1.1       raeburn  1439:     }
                   1440:     $options .= '</select>';
                   1441:     return ($options,$cb_jscript,$coursepick);
                   1442: }
                   1443: 
                   1444: sub default_course_roles {
1.101     raeburn  1445:     my ($context,$checkpriv,$crstype,%customroles) = @_;
1.1       raeburn  1446:     my $output;
1.17      raeburn  1447:     my $custom = 1;
1.101     raeburn  1448:     my @roles = &course_roles($context,$checkpriv,$custom,lc($crstype));
1.1       raeburn  1449:     foreach my $role (@roles) {
1.22      raeburn  1450:         if ($role ne 'cr') {
1.101     raeburn  1451:             my $plrole=&Apache::lonnet::plaintext($role,$crstype);
1.22      raeburn  1452:             $output .= '  <option value="'.$role.'">'.$plrole.'</option>';
                   1453:         }
1.1       raeburn  1454:     }
                   1455:     if (keys(%customroles) > 0) {
1.22      raeburn  1456:         if (grep(/^cr$/,@roles)) {
                   1457:             foreach my $cust (sort(keys(%customroles))) {
                   1458:                 my $custrole='cr_'.$env{'user.domain'}.
                   1459:                              '_'.$env{'user.name'}.'_'.$cust;
                   1460:                 $output .= '  <option value="'.$custrole.'">'.$cust.'</option>';
                   1461:             }
1.1       raeburn  1462:         }
                   1463:     }
                   1464:     return $output;
                   1465: }
                   1466: 
                   1467: sub construction_space_roles {
1.2       raeburn  1468:     my ($checkpriv) = @_;
1.17      raeburn  1469:     my @allroles = &roles_by_context('author');
1.1       raeburn  1470:     my @roles;
1.2       raeburn  1471:     if ($checkpriv) {
                   1472:         foreach my $role (@allroles) {
                   1473:             if (&Apache::lonnet::allowed('c'.$role,$env{'user.domain'}.'/'.$env{'user.name'})) { 
                   1474:                 push(@roles,$role); 
                   1475:             }
1.1       raeburn  1476:         }
1.2       raeburn  1477:         return @roles;
                   1478:     } else {
                   1479:         return @allroles;
1.1       raeburn  1480:     }
                   1481: }
                   1482: 
                   1483: sub domain_roles {
1.2       raeburn  1484:     my ($checkpriv) = @_;
1.17      raeburn  1485:     my @allroles = &roles_by_context('domain');
1.1       raeburn  1486:     my @roles;
1.2       raeburn  1487:     if ($checkpriv) {
                   1488:         foreach my $role (@allroles) {
                   1489:             if (&Apache::lonnet::allowed('c'.$role,$env{'request.role.domain'})) {
                   1490:                 push(@roles,$role);
                   1491:             }
1.1       raeburn  1492:         }
1.2       raeburn  1493:         return @roles;
                   1494:     } else {
                   1495:         return @allroles;
1.1       raeburn  1496:     }
                   1497: }
                   1498: 
                   1499: sub course_roles {
1.101     raeburn  1500:     my ($context,$checkpriv,$custom,$roletype) = @_;
1.102     raeburn  1501:     my $crstype;
                   1502:     if ($roletype eq 'community') {
                   1503:         $crstype = 'Community' ;
                   1504:     } else {
                   1505:         $crstype = 'Course';
                   1506:     }
                   1507:     my @allroles = &roles_by_context('course',$custom,$crstype);
1.1       raeburn  1508:     my @roles;
                   1509:     if ($context eq 'domain') {
                   1510:         @roles = @allroles;
                   1511:     } elsif ($context eq 'course') {
                   1512:         if ($env{'request.course.id'}) {
1.2       raeburn  1513:             if ($checkpriv) { 
                   1514:                 foreach my $role (@allroles) {
                   1515:                     if (&Apache::lonnet::allowed('c'.$role,$env{'request.course.id'})) {
                   1516:                         push(@roles,$role);
                   1517:                     } else {
1.101     raeburn  1518:                         if ((($role ne 'cc') && ($role ne 'co')) && ($env{'request.course.sec'} ne '')) {
1.22      raeburn  1519:                             if (&Apache::lonnet::allowed('c'.$role,
1.2       raeburn  1520:                                              $env{'request.course.id'}.'/'.
1.22      raeburn  1521:                                              $env{'request.course.sec'})) {
1.2       raeburn  1522:                                 push(@roles,$role);
                   1523:                             }
1.1       raeburn  1524:                         }
                   1525:                     }
                   1526:                 }
1.2       raeburn  1527:             } else {
                   1528:                 @roles = @allroles;
1.1       raeburn  1529:             }
                   1530:         }
                   1531:     }
                   1532:     return @roles;
                   1533: }
                   1534: 
                   1535: sub curr_role_permissions {
1.101     raeburn  1536:     my ($context,$setting,$checkpriv,$type) = @_; 
1.17      raeburn  1537:     my $custom = 1;
1.1       raeburn  1538:     my @roles;
1.13      raeburn  1539:     if ($context eq 'author') {
1.2       raeburn  1540:         @roles = &construction_space_roles($checkpriv);
1.1       raeburn  1541:     } elsif ($context eq 'domain') {
                   1542:         if ($setting eq 'course') {
1.101     raeburn  1543:             @roles = &course_roles($context,$checkpriv,$custom,$type); 
1.1       raeburn  1544:         } else {
1.2       raeburn  1545:             @roles = &domain_roles($checkpriv);
1.1       raeburn  1546:         }
                   1547:     } elsif ($context eq 'course') {
1.101     raeburn  1548:         @roles = &course_roles($context,$checkpriv,$custom,$type);
1.1       raeburn  1549:     }
                   1550:     return @roles;
                   1551: }
                   1552: 
                   1553: # ======================================================= Existing Custom Roles
                   1554: 
                   1555: sub my_custom_roles {
1.175     raeburn  1556:     my ($crstype,$udom,$uname) = @_;
1.1       raeburn  1557:     my %returnhash=();
1.137     raeburn  1558:     my $extra = &Apache::lonnet::freeze_escape({'skipcheck' => 1});
1.175     raeburn  1559:     my %rolehash=&Apache::lonnet::dump('roles',$udom,$uname);
1.104     raeburn  1560:     foreach my $key (keys(%rolehash)) {
1.1       raeburn  1561:         if ($key=~/^rolesdef\_(\w+)$/) {
1.104     raeburn  1562:             if ($crstype eq 'Community') {
                   1563:                 next if ($rolehash{$key} =~ /bre\&S/); 
                   1564:             }
1.1       raeburn  1565:             $returnhash{$1}=$1;
                   1566:         }
                   1567:     }
                   1568:     return %returnhash;
                   1569: }
                   1570: 
1.2       raeburn  1571: sub print_userlist {
                   1572:     my ($r,$mode,$permission,$context,$formname,$totcodes,$codetitles,
1.150     raeburn  1573:         $idlist,$idlist_titles,$showcredits) = @_;
1.2       raeburn  1574:     my $format = $env{'form.output'};
1.1       raeburn  1575:     if (! exists($env{'form.sortby'})) {
                   1576:         $env{'form.sortby'} = 'username';
                   1577:     }
1.2       raeburn  1578:     if ($env{'form.Status'} !~ /^(Any|Expired|Active|Future)$/) {
                   1579:         $env{'form.Status'} = 'Active';
1.1       raeburn  1580:     }
1.140     raeburn  1581:     my $onchange = "javascript:updateCols('Status');";
1.1       raeburn  1582:     my $status_select = &Apache::lonhtmlcommon::StatusOptions
1.140     raeburn  1583:         ($env{'form.Status'},undef,undef,$onchange);
1.1       raeburn  1584: 
1.2       raeburn  1585:     if ($env{'form.showrole'} eq '') {
1.13      raeburn  1586:         if ($context eq 'course') {
                   1587:             $env{'form.showrole'} = 'st';
                   1588:         } else {
                   1589:             $env{'form.showrole'} = 'Any';            
                   1590:         }
1.2       raeburn  1591:     }
1.1       raeburn  1592:     if (! defined($env{'form.output'}) ||
                   1593:         $env{'form.output'} !~ /^(csv|excel|html)$/ ) {
                   1594:         $env{'form.output'} = 'html';
                   1595:     }
                   1596: 
1.2       raeburn  1597:     my @statuses;
                   1598:     if ($env{'form.Status'} eq 'Any') {
                   1599:         @statuses = ('previous','active','future');
                   1600:     } elsif ($env{'form.Status'} eq 'Expired') {
                   1601:         @statuses = ('previous');
                   1602:     } elsif ($env{'form.Status'} eq 'Active') {
                   1603:         @statuses = ('active');
                   1604:     } elsif ($env{'form.Status'} eq 'Future') {
                   1605:         @statuses = ('future');
                   1606:     }
1.1       raeburn  1607: 
                   1608:     # Interface output
1.2       raeburn  1609:     $r->print('<form name="studentform" method="post" action="/adm/createuser">'."\n".
                   1610:               '<input type="hidden" name="action" value="'.
1.1       raeburn  1611:               $env{'form.action'}.'" />');
1.140     raeburn  1612:     $r->print('<div>'."\n");
1.1       raeburn  1613:     if ($env{'form.action'} ne 'modifystudent') {
                   1614:         my %lt=&Apache::lonlocal::texthash('csv' => "CSV",
                   1615:                                            'excel' => "Excel",
                   1616:                                            'html'  => 'HTML');
1.140     raeburn  1617:         my $output_selector = '<select size="1" name="output" onchange="javascript:updateCols('."'output'".');" >';
1.1       raeburn  1618:         foreach my $outputformat ('html','csv','excel') {
1.96      bisitz   1619:             my $option = '<option value="'.$outputformat.'"';
1.1       raeburn  1620:             if ($outputformat eq $env{'form.output'}) {
1.96      bisitz   1621:                 $option .= ' selected="selected"';
1.1       raeburn  1622:             }
                   1623:             $option .='>'.$lt{$outputformat}.'</option>';
                   1624:             $output_selector .= "\n".$option;
                   1625:         }
                   1626:         $output_selector .= '</select>';
1.140     raeburn  1627:         $r->print('<span class="LC_nobreak">'
1.70      bisitz   1628:                  .&mt('Output Format: [_1]',$output_selector)
1.140     raeburn  1629:                  .'</span>'.('&nbsp;'x3));
1.70      bisitz   1630:     }
1.140     raeburn  1631:     $r->print('<span class="LC_nobreak">'
1.70      bisitz   1632:              .&mt('User Status: [_1]',$status_select)
1.140     raeburn  1633:              .'</span>'.('&nbsp;'x3)."\n");
1.2       raeburn  1634:     my $roleselected = '';
                   1635:     if ($env{'form.showrole'} eq 'Any') {
1.91      bisitz   1636:        $roleselected = ' selected="selected"'; 
1.2       raeburn  1637:     }
1.53      raeburn  1638:     my ($cnum,$cdom);
                   1639:     $r->print(&role_filter($context));
                   1640:     if ($context eq 'course') {
                   1641:         ($cnum,$cdom) = &get_course_identity();
                   1642:         $r->print(&section_group_filter($cnum,$cdom));
1.2       raeburn  1643:     }
1.140     raeburn  1644:     $r->print('</div><div class="LC_left_float">'.
1.150     raeburn  1645:               &column_checkboxes($context,$mode,$formname,$showcredits).
1.149     raeburn  1646:               '</div>');
1.78      raeburn  1647:     if ($env{'form.phase'} eq '') {
1.149     raeburn  1648:         $r->print('<br clear="all" />'.
                   1649:                   &list_submit_button(&mt('Display List of Users'))."\n".
1.78      raeburn  1650:                   '<input type="hidden" name="phase" value="" /></form>');
                   1651:         return;
                   1652:     }
1.106     raeburn  1653:     if (!(($context eq 'domain') && 
                   1654:           (($env{'form.roletype'} eq 'course') || ($env{'form.roletype'} eq 'community')))) {
1.149     raeburn  1655:         $r->print('<br clear="all" />'.
                   1656:                   &list_submit_button(&mt('Update Display'))."\n");
1.140     raeburn  1657:     }
                   1658: 
1.150     raeburn  1659:     my @cols = &infocolumns($context,$mode,$showcredits);  
1.140     raeburn  1660:     if (!@cols) {
1.152     bisitz   1661:          $r->print('<hr style="clear:both;" /><span class="LC_warning">'.
1.140     raeburn  1662:                    &mt('No user information selected for display.').'</span>'.
                   1663:                    '<input type="hidden" name="phase" value="display" /></form>'."\n");
                   1664:          return;
1.2       raeburn  1665:     }
                   1666:     my ($indexhash,$keylist) = &make_keylist_array();
1.159     raeburn  1667:     my (%userlist,%userinfo,$clearcoursepick,$needauthorquota,$needauthorusage);
1.102     raeburn  1668:     if (($context eq 'domain') && 
                   1669:         ($env{'form.roletype'} eq 'course') || 
                   1670:         ($env{'form.roletype'} eq 'community')) {
                   1671:         my ($crstype,$numcodes,$title,$warning);
                   1672:         if ($env{'form.roletype'} eq 'course') {
                   1673:             $crstype = 'Course';
                   1674:             $numcodes = $totcodes;
                   1675:             $title = &mt('Select Courses');
                   1676:             $warning = &mt('Warning: data retrieval for multiple courses can take considerable time, as this operation is not currently optimized.');
                   1677:         } elsif ($env{'form.roletype'} eq 'community') {
                   1678:             $crstype = 'Community';
                   1679:             $numcodes = 0;
                   1680:             $title = &mt('Select Communities');
                   1681:             $warning = &mt('Warning: data retrieval for multiple communities can take considerable time, as this operation is not currently optimized.');
                   1682:         }
1.120     raeburn  1683:         my @standardnames = &Apache::loncommon::get_standard_codeitems();
1.3       raeburn  1684:         my $courseform =
1.102     raeburn  1685:             &Apache::lonhtmlcommon::course_selection($formname,$numcodes,
1.120     raeburn  1686:                             $codetitles,$idlist,$idlist_titles,$crstype,
                   1687:                             \@standardnames);
1.148     bisitz   1688:         $r->print('<div class="LC_left_float">'.
                   1689:                   '<fieldset><legend>'.$title.'</legend>'."\n".
1.3       raeburn  1690:                   $courseform."\n".
1.148     bisitz   1691:                   '</fieldset></div><br clear="all" />'.
1.106     raeburn  1692:                   '<p><input type="hidden" name="origroletype" value="'.$env{'form.roletype'}.'" />'.
                   1693:                   &list_submit_button(&mt('Update Display')).
1.102     raeburn  1694:                   "\n".'</p><span class="LC_warning">'.$warning.'</span>'."\n");
1.106     raeburn  1695:         $clearcoursepick = 0;
                   1696:         if (($env{'form.origroletype'} ne '') &&
                   1697:             ($env{'form.origroletype'} ne $env{'form.roletype'})) {
                   1698:             $clearcoursepick = 1;
                   1699:         }
                   1700:         if (($env{'form.coursepick'}) && (!$clearcoursepick)) {
1.147     bisitz   1701:             $r->print('<hr />'.&mt('Searching ...').'<br />&nbsp;<br />');
1.11      raeburn  1702:         }
                   1703:     } else {
1.152     bisitz   1704:         $r->print('<hr style="clear:both;" /><div id="searching">'.&mt('Searching ...').'</div>');
1.3       raeburn  1705:     }
                   1706:     $r->rflush();
1.1       raeburn  1707:     if ($context eq 'course') {
1.46      raeburn  1708:         if (($env{'form.showrole'} eq 'st') || ($env{'form.showrole'} eq 'Any')) { 
1.45      raeburn  1709:             my $classlist = &Apache::loncoursedata::get_classlist();
1.66      raeburn  1710:             if (ref($classlist) eq 'HASH') {
                   1711:                 %userlist = %{$classlist};
                   1712:             }
1.45      raeburn  1713:         }
1.43      raeburn  1714:         if ($env{'form.showrole'} ne 'st') {
                   1715:             my $showroles;
                   1716:             if ($env{'form.showrole'} ne 'Any') {
                   1717:                 $showroles = [$env{'form.showrole'}];
1.3       raeburn  1718:             } else {
1.43      raeburn  1719:                 $showroles = undef;
1.1       raeburn  1720:             }
1.43      raeburn  1721:             my $withsec = 1;
                   1722:             my $hidepriv = 1;
                   1723:             my %advrolehash = &Apache::lonnet::get_my_roles($cnum,$cdom,undef,
                   1724:                               \@statuses,$showroles,undef,$withsec,$hidepriv);
                   1725:             &gather_userinfo($context,$format,\%userlist,$indexhash,\%userinfo,
                   1726:                              \%advrolehash,$permission);
1.1       raeburn  1727:         }
1.2       raeburn  1728:     } else {
                   1729:         my (%cstr_roles,%dom_roles);
1.13      raeburn  1730:         if ($context eq 'author') {
1.2       raeburn  1731:             # List co-authors and assistant co-authors
1.17      raeburn  1732:             my @possroles = &roles_by_context($context);
1.2       raeburn  1733:             %cstr_roles = &Apache::lonnet::get_my_roles(undef,undef,undef,
                   1734:                                               \@statuses,\@possroles);
                   1735:             &gather_userinfo($context,$format,\%userlist,$indexhash,\%userinfo,
1.11      raeburn  1736:                              \%cstr_roles,$permission);
1.2       raeburn  1737:         } elsif ($context eq 'domain') {
                   1738:             if ($env{'form.roletype'} eq 'domain') {
1.159     raeburn  1739:                 if (grep(/^authorusage$/,@cols)) {
                   1740:                     $needauthorusage = 1;
                   1741:                 }
                   1742:                 if (grep(/^authorquota$/,@cols)) {
                   1743:                     $needauthorquota = 1;
                   1744:                 }
1.2       raeburn  1745:                 %dom_roles = &Apache::lonnet::get_domain_roles($env{'request.role.domain'});
                   1746:                 foreach my $key (keys(%dom_roles)) {
                   1747:                     if (ref($dom_roles{$key}) eq 'HASH') {
                   1748:                         &gather_userinfo($context,$format,\%userlist,$indexhash,
1.11      raeburn  1749:                                          \%userinfo,$dom_roles{$key},$permission);
1.2       raeburn  1750:                     }
                   1751:                 }
1.13      raeburn  1752:             } elsif ($env{'form.roletype'} eq 'author') {
1.2       raeburn  1753:                 my %dom_roles = &Apache::lonnet::get_domain_roles($env{'request.role.domain'},['au']);
                   1754:                 my %coauthors;
                   1755:                 foreach my $key (keys(%dom_roles)) {
                   1756:                     if (ref($dom_roles{$key}) eq 'HASH') {
                   1757:                         if ($env{'form.showrole'} eq 'au') {
                   1758:                             &gather_userinfo($context,$format,\%userlist,$indexhash,
1.11      raeburn  1759:                                              \%userinfo,$dom_roles{$key},$permission);
1.2       raeburn  1760:                         } else {
                   1761:                             my @possroles;
                   1762:                             if ($env{'form.showrole'} eq 'Any') {
1.22      raeburn  1763:                                 @possroles = &roles_by_context('author');
1.2       raeburn  1764:                             } else {
                   1765:                                 @possroles = ($env{'form.showrole'}); 
                   1766:                             }
                   1767:                             foreach my $author (sort(keys(%{$dom_roles{$key}}))) {
1.22      raeburn  1768:                                 my ($role,$authorname,$authordom) = split(/:/,$author,-1);
1.2       raeburn  1769:                                 my $extent = '/'.$authordom.'/'.$authorname;
                   1770:                                 %{$coauthors{$extent}} =
                   1771:                                     &Apache::lonnet::get_my_roles($authorname,
                   1772:                                        $authordom,undef,\@statuses,\@possroles);
                   1773:                             }
                   1774:                             &gather_userinfo($context,$format,\%userlist,
1.11      raeburn  1775:                                      $indexhash,\%userinfo,\%coauthors,$permission);
1.2       raeburn  1776:                         }
                   1777:                     }
                   1778:                 }
1.101     raeburn  1779:             } elsif (($env{'form.roletype'} eq 'course') ||
                   1780:                      ($env{'form.roletype'} eq 'community')) {
1.106     raeburn  1781:                 if (($env{'form.coursepick'}) && (!$clearcoursepick)) {
1.2       raeburn  1782:                     my %courses = &process_coursepick();
1.39      raeburn  1783:                     my %allusers;
                   1784:                     my $hidepriv = 1;
1.2       raeburn  1785:                     foreach my $cid (keys(%courses)) {
1.17      raeburn  1786:                         my ($cnum,$cdom,$cdesc) = &get_course_identity($cid);
1.11      raeburn  1787:                         next if ($cnum eq '' || $cdom eq '');
1.17      raeburn  1788:                         my $custom = 1;
1.2       raeburn  1789:                         my (@roles,@sections,%access,%users,%userdata,
1.6       albertel 1790:                             %statushash);
1.2       raeburn  1791:                         if ($env{'form.showrole'} eq 'Any') {
1.101     raeburn  1792:                             @roles = &course_roles($context,undef,$custom,
                   1793:                                                    $env{'form.roletype'});
1.2       raeburn  1794:                         } else {
                   1795:                             @roles = ($env{'form.showrole'});
                   1796:                         }
                   1797:                         foreach my $role (@roles) {
                   1798:                             %{$users{$role}} = ();
                   1799:                         }
                   1800:                         foreach my $type (@statuses) {
                   1801:                             $access{$type} = $type;
                   1802:                         }
1.39      raeburn  1803:                         &Apache::loncommon::get_course_users($cdom,$cnum,\%access,\@roles,\@sections,\%users,\%userdata,\%statushash,$hidepriv);
1.2       raeburn  1804:                         foreach my $user (keys(%userdata)) {
                   1805:                             next if (ref($userinfo{$user}) eq 'HASH');
                   1806:                             foreach my $item ('fullname','id') {
                   1807:                                 $userinfo{$user}{$item} = $userdata{$user}[$indexhash->{$item}];
                   1808:                             }
                   1809:                         }
                   1810:                         foreach my $role (keys(%users)) {
                   1811:                             foreach my $user (keys(%{$users{$role}})) {
                   1812:                                 my $uniqid = $user.':'.$role;
                   1813:                                 $allusers{$uniqid}{$cid} = { desc => $cdesc,
                   1814:                                                              secs  => $statushash{$user}{$role},
                   1815:                                                            };
                   1816:                             }
                   1817:                         }
                   1818:                     }
                   1819:                     &gather_userinfo($context,$format,\%userlist,$indexhash,
1.11      raeburn  1820:                                      \%userinfo,\%allusers,$permission);
1.2       raeburn  1821:                 } else {
1.10      raeburn  1822:                     $r->print('<input type="hidden" name="phase" value="'.
                   1823:                               $env{'form.phase'}.'" /></form>');
1.2       raeburn  1824:                     return;
                   1825:                 }
1.1       raeburn  1826:             }
                   1827:         }
1.3       raeburn  1828:     }
                   1829:     if (keys(%userlist) == 0) {
1.142     bisitz   1830:         my $msg = '';
1.13      raeburn  1831:         if ($context eq 'author') {
1.142     bisitz   1832:             $msg = &mt('There are no co-authors to display.');
1.3       raeburn  1833:         } elsif ($context eq 'domain') {
                   1834:             if ($env{'form.roletype'} eq 'domain') {
1.142     bisitz   1835:                 $msg = &mt('There are no users with domain roles to display.');
1.13      raeburn  1836:             } elsif ($env{'form.roletype'} eq 'author') {
1.142     bisitz   1837:                 $msg = &mt('There are no authors or co-authors to display.');
1.3       raeburn  1838:             } elsif ($env{'form.roletype'} eq 'course') {
1.142     bisitz   1839:                 $msg = &mt('There are no course users to display');
1.101     raeburn  1840:             } elsif ($env{'form.roletype'} eq 'community') {
1.142     bisitz   1841:                 $msg = &mt('There are no community users to display');
1.2       raeburn  1842:             }
1.3       raeburn  1843:         } elsif ($context eq 'course') {
                   1844:             $r->print(&mt('There are no course users to display.')."\n");
                   1845:         }
1.148     bisitz   1846:         $r->print('<p class="LC_info">'.$msg.'</p>'."\n") if $msg;
1.3       raeburn  1847:     } else {
                   1848:         # Print out the available choices
1.4       raeburn  1849:         my $usercount;
1.3       raeburn  1850:         if ($env{'form.action'} eq 'modifystudent') {
1.10      raeburn  1851:             ($usercount) = &show_users_list($r,$context,'view',$permission,
1.150     raeburn  1852:                                  $env{'form.Status'},\%userlist,$keylist,'',
                   1853:                                  $showcredits);
1.1       raeburn  1854:         } else {
1.4       raeburn  1855:             ($usercount) = &show_users_list($r,$context,$env{'form.output'},
1.150     raeburn  1856:                                $permission,$env{'form.Status'},\%userlist,
1.159     raeburn  1857:                                $keylist,'',$showcredits,$needauthorquota,$needauthorusage);
1.4       raeburn  1858:         }
                   1859:         if (!$usercount) {
1.142     bisitz   1860:             $r->print('<br /><span class="LC_info">'
1.72      bisitz   1861:                      .&mt('There are no users matching the search criteria.')
                   1862:                      .'</span>'
                   1863:             ); 
1.2       raeburn  1864:         }
                   1865:     }
1.10      raeburn  1866:     $r->print('<input type="hidden" name="phase" value="'.
                   1867:               $env{'form.phase'}.'" /></form>');
1.140     raeburn  1868:     return;
1.2       raeburn  1869: }
                   1870: 
1.53      raeburn  1871: sub role_filter {
                   1872:     my ($context) = @_;
                   1873:     my $output;
                   1874:     my $roleselected = '';
                   1875:     if ($env{'form.showrole'} eq 'Any') {
1.91      bisitz   1876:        $roleselected = ' selected="selected"';
1.53      raeburn  1877:     }
                   1878:     my ($role_select);
                   1879:     if ($context eq 'domain') {
                   1880:         $role_select = &domain_roles_select();
1.140     raeburn  1881:         $output = '<span class="LC_nobreak">'
1.70      bisitz   1882:                  .&mt('Role Type: [_1]',$role_select)
1.140     raeburn  1883:                  .'</span>';
1.53      raeburn  1884:     } else {
1.140     raeburn  1885:         $role_select = '<select name="showrole" onchange="javascript:updateCols('."'showrole'".');">'."\n".
1.53      raeburn  1886:                        '<option value="Any" '.$roleselected.'>'.
                   1887:                        &mt('Any role').'</option>';
1.101     raeburn  1888:         my ($roletype,$crstype);
                   1889:         if ($context eq 'course') {
                   1890:             $crstype = &Apache::loncommon::course_type();
                   1891:             if ($crstype eq 'Community') {
                   1892:                 $roletype = 'community';
                   1893:             } else {
                   1894:                 $roletype = 'course';
                   1895:             } 
                   1896:         }
                   1897:         my @poss_roles = &curr_role_permissions($context,'','',$roletype);
1.53      raeburn  1898:         foreach my $role (@poss_roles) {
                   1899:             $roleselected = '';
                   1900:             if ($role eq $env{'form.showrole'}) {
1.91      bisitz   1901:                 $roleselected = ' selected="selected"';
1.53      raeburn  1902:             }
                   1903:             my $plrole;
                   1904:             if ($role eq 'cr') {
                   1905:                 $plrole = &mt('Custom role');
                   1906:             } else {
1.101     raeburn  1907:                 $plrole=&Apache::lonnet::plaintext($role,$crstype);
1.53      raeburn  1908:             }
                   1909:             $role_select .= '<option value="'.$role.'"'.$roleselected.'>'.$plrole.'</option>';
                   1910:         }
                   1911:         $role_select .= '</select>';
1.140     raeburn  1912:         $output = '<span class="LC_nobreak">'
1.70      bisitz   1913:                  .&mt('Role: [_1]',$role_select)
1.140     raeburn  1914:                  .'</span>';
1.53      raeburn  1915:     }
                   1916:     return $output;
                   1917: }
                   1918: 
1.33      raeburn  1919: sub section_group_filter {
                   1920:     my ($cnum,$cdom) = @_;
                   1921:     my @filters;
                   1922:     if ($env{'request.course.sec'} eq '') {
                   1923:         @filters = ('sec');
                   1924:     }
                   1925:     push(@filters,'grp');
                   1926:     my %name = (
                   1927:                  sec => 'secfilter',
                   1928:                  grp => 'grpfilter',
                   1929:                );
                   1930:     my %title = &Apache::lonlocal::texthash (
                   1931:                                               sec  => 'Section(s)',
                   1932:                                               grp  => 'Group(s)',
                   1933:                                               all  => 'all',
                   1934:                                               none => 'none',
                   1935:                                             );
1.47      raeburn  1936:     my $output;
1.33      raeburn  1937:     foreach my $item (@filters) {
1.47      raeburn  1938:         my ($markup,@options); 
1.33      raeburn  1939:         if ($env{'form.'.$name{$item}} eq '') {
                   1940:             $env{'form.'.$name{$item}} = 'all';
                   1941:         }
                   1942:         if ($item eq 'sec') {
1.103     raeburn  1943:             if (($env{'form.showrole'} eq 'cc') || ($env{'form.showrole'} eq 'co')) {
1.33      raeburn  1944:                 $env{'form.'.$name{$item}} = 'none';
                   1945:             }
                   1946:             my %sections_count = &Apache::loncommon::get_sections($cdom,$cnum);
                   1947:             @options = sort(keys(%sections_count));
                   1948:         } elsif ($item eq 'grp') {
                   1949:             my %curr_groups = &Apache::longroup::coursegroups();
                   1950:             @options = sort(keys(%curr_groups));
                   1951:         }
                   1952:         if (@options > 0) {
                   1953:             my $currsel;
1.112     bisitz   1954:             $markup = '<select name="'.$name{$item}.'">'."\n";
1.33      raeburn  1955:             foreach my $option ('all','none',@options) { 
                   1956:                 $currsel = '';
                   1957:                 if ($env{'form.'.$name{$item}} eq $option) {
1.96      bisitz   1958:                     $currsel = ' selected="selected"';
1.33      raeburn  1959:                 }
                   1960:                 $markup .= ' <option value="'.$option.'"'.$currsel.'>';
                   1961:                 if (($option eq 'all') || ($option eq 'none')) {
                   1962:                     $markup .= $title{$option};
                   1963:                 } else {
                   1964:                     $markup .= $option;
                   1965:                 }   
                   1966:                 $markup .= '</option>'."\n";
                   1967:             }
                   1968:             $markup .= '</select>'."\n";
1.111     bisitz   1969:             $output .= ('&nbsp;'x3).'<span class="LC_nobreak">'
                   1970:                       .'<label>'.$title{$item}.': '.$markup.'</label>'
                   1971:                       .'</span> ';
1.33      raeburn  1972:         }
                   1973:     }
                   1974:     return $output;
                   1975: }
                   1976: 
1.140     raeburn  1977: sub infocolumns {
1.150     raeburn  1978:     my ($context,$mode,$showcredits) = @_;
1.140     raeburn  1979:     my @cols;
                   1980:     if (($mode eq 'pickauthor') || ($mode eq 'autoenroll')) {
1.150     raeburn  1981:         @cols = &get_cols_array($context,$mode,$showcredits);
1.140     raeburn  1982:     } else {
1.150     raeburn  1983:         my @posscols = &get_cols_array($context,$mode,$showcredits);
1.140     raeburn  1984:         if ($env{'form.phase'} ne '') {
                   1985:             my @checkedcols = &Apache::loncommon::get_env_multiple('form.showcol');
                   1986:             foreach my $col (@checkedcols) {
                   1987:                 if (grep(/^$col$/,@posscols)) {
                   1988:                     push(@cols,$col);
                   1989:                 }
                   1990:             }
                   1991:         } else {
                   1992:             @cols = @posscols;
                   1993:         }
                   1994:     }
                   1995:     return @cols;
                   1996: }
                   1997: 
                   1998: sub get_cols_array {
1.150     raeburn  1999:     my ($context,$mode,$showcredits) = @_;
1.140     raeburn  2000:     my @cols;
                   2001:     if ($mode eq 'pickauthor') {
                   2002:         @cols = ('username','fullname','status','email');
                   2003:     } else {
                   2004:         @cols = ('username','domain','id','fullname');
                   2005:         if ($context eq 'course') {
                   2006:             push(@cols,'section');
                   2007:         }
                   2008:         push(@cols,('start','end','role'));
                   2009:         unless (($mode eq 'autoenroll') && ($env{'form.Status'} ne 'Any')) {
                   2010:             push(@cols,'status');
                   2011:         }
                   2012:         if ($context eq 'course') {
                   2013:             push(@cols,'groups');
                   2014:         }
                   2015:         push(@cols,'email');
                   2016:         if (($context eq 'course') && ($mode ne 'autoenroll')) {
1.150     raeburn  2017:             if ($showcredits) {
                   2018:                 push(@cols,'credits');
                   2019:             }
1.140     raeburn  2020:             push(@cols,'lastlogin','clicker');
                   2021:         }
                   2022:         if (($context eq 'course') && ($mode ne 'autoenroll') &&
                   2023:             ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'})) {
1.156     raeburn  2024:             push(@cols,'photo');
1.140     raeburn  2025:         }
1.149     raeburn  2026:         if ($context eq 'domain') {
1.159     raeburn  2027:             push (@cols,('authorusage','authorquota','extent'));
1.149     raeburn  2028:         }
1.140     raeburn  2029:     }
                   2030:     return @cols;
                   2031: }
                   2032: 
                   2033: sub column_checkboxes {
1.150     raeburn  2034:     my ($context,$mode,$formname,$showcredits) = @_;
                   2035:     my @cols = &get_cols_array($context,$mode,$showcredits);
1.140     raeburn  2036:     my @showncols = &Apache::loncommon::get_env_multiple('form.showcol');
                   2037:     my (%disabledchk,%unchecked);
                   2038:     if ($env{'form.phase'} eq '') {
                   2039:         $disabledchk{'status'} = 1;
                   2040:         if ($context eq 'course') {
                   2041:             $disabledchk{'role'} = 1;
                   2042:             $unchecked{'photo'} = 1;
1.149     raeburn  2043:             $unchecked{'clicker'} = 1;
1.150     raeburn  2044:             if ($showcredits) {
                   2045:                 $unchecked{'credits'} = 1;
                   2046:             }
1.149     raeburn  2047:         } elsif ($context eq 'domain') { 
                   2048:             $unchecked{'extent'} = 1; 
1.140     raeburn  2049:         }
                   2050:         $unchecked{'start'} = 1;
                   2051:         $unchecked{'end'} = 1;
                   2052:     } else {
                   2053:         if ($env{'form.Status'} ne 'Any') {
                   2054:             $disabledchk{'status'} = 1;
                   2055:         }
1.146     raeburn  2056:         if (($env{'form.showrole'} ne 'Any') && ($env{'form.showrole'} ne 'cr')) {
                   2057:             $disabledchk{'role'} = 1;
1.140     raeburn  2058:         }
1.149     raeburn  2059:         if ($context eq 'domain') {
                   2060:             if (($env{'form.roletype'} eq 'course') || 
                   2061:                 ($env{'form.roletype'} eq 'community')) {
                   2062:                 $disabledchk{'status'} = 1;
1.159     raeburn  2063:                 $disabledchk{'authorusage'} = 1;
                   2064:                 $disabledchk{'authorquota'} = 1;
1.149     raeburn  2065:             } elsif ($env{'form.roletype'} eq 'domain') {
                   2066:                 $disabledchk{'extent'} = 1; 
                   2067:             }
                   2068:         }
1.140     raeburn  2069:     }
                   2070:     my $numposs = scalar(@cols);
1.149     raeburn  2071:     my $numinrow = 7;
1.140     raeburn  2072:     my %lt = &get_column_names($context);
                   2073:     my $output = '<fieldset><legend>'.&mt('Information to show').'</legend>'."\n".'<span class="LC_nobreak">'.
                   2074:                  '<input type="button" onclick="javascript:checkAll(document.'.$formname.'.showcol);" value="'.&mt('check all').'" />'.
                   2075:                  ('&nbsp;'x3).
                   2076:                  '<input type="button" onclick="javascript:uncheckAll(document.'.$formname.'.showcol);" value="'.&mt('uncheck all').'" />'.
                   2077:                  '</span><table>';
                   2078:     
                   2079:     for (my $i=0; $i<$numposs; $i++) {
                   2080:         my $rem = $i%($numinrow);
                   2081:         if ($rem == 0) {
                   2082:             if ($i > 0) {
                   2083:                 $output .= '</tr>';
                   2084:             }
                   2085:             $output .= '<tr>';
                   2086:         }
                   2087:         my $checked;
                   2088:         if ($env{'form.phase'} eq '') {
                   2089:             $checked = ' checked="checked"';
                   2090:             if ($unchecked{$cols[$i]}) { 
                   2091:                $checked = '';
                   2092:             }
                   2093:             if ($disabledchk{$cols[$i]}) {
                   2094:                 $checked = ' disabled="disabled"';
                   2095:             }
                   2096:         } elsif (grep(/^\Q$cols[$i]\E$/,@showncols)) {
                   2097:             $checked = ' checked="checked"';
                   2098:         } elsif ($disabledchk{$cols[$i]}) {
                   2099:             $checked = ' disabled="disabled"';
                   2100:         }
                   2101:         if ($i == $numposs-1) {
                   2102:             my $colsleft = $numinrow-$rem;
                   2103:             if ($colsleft > 1) {
                   2104:                 $output .= '<td colspan="'.$colsleft.'">';
                   2105:             } else {
                   2106:                 $output .= '<td>';
                   2107:             }
                   2108:         } else {
                   2109:             $output .= '<td>';
                   2110:         }
1.149     raeburn  2111:         my $style;
                   2112:         if ($cols[$i] eq 'extent') {
                   2113:             if (($env{'form.roletype'} eq 'domain') || ($env{'form.roletype'} eq '')) {
                   2114:                 $style = ' style="display: none;"';
                   2115:             } 
1.159     raeburn  2116:         } elsif (($cols[$i] eq 'authorusage') || ($cols[$i] eq 'authorquota')) {
                   2117:             if ($env{'form.roletype'} ne 'domain') {
                   2118:                 $style = ' style="display: none;"';
                   2119:             }
                   2120:         }
1.149     raeburn  2121:         $output .= '<span id="show'.$cols[$i].'"'.$style.'><label>'.
                   2122:                    '<input id="showcol'.$cols[$i].'" type="checkbox" name="showcol" value="'.$cols[$i].'"'.$checked.' /><span id="showcoltext'.$cols[$i].'">'.
                   2123:                    $lt{$cols[$i]}.'</span>'.
                   2124:                    '</label></span></td>';
1.140     raeburn  2125:     }
                   2126:     $output .= '</tr></table></fieldset>';
                   2127:     return $output;
                   2128: }
                   2129: 
1.2       raeburn  2130: sub list_submit_button {
                   2131:     my ($text) = @_;
1.11      raeburn  2132:     return '<input type="button" name="updatedisplay" value="'.$text.'" onclick="javascript:display_update()" />';
1.2       raeburn  2133: }
                   2134: 
1.140     raeburn  2135: sub get_column_names {
                   2136:     my ($context) = @_;
                   2137:     my %lt = &Apache::lonlocal::texthash(
                   2138:         'username'   => "username",
                   2139:         'domain'     => "domain",
                   2140:         'id'         => 'ID',
                   2141:         'fullname'   => "name",
                   2142:         'section'    => "section",
                   2143:         'groups'     => "active groups",
                   2144:         'start'      => "start date",
                   2145:         'end'        => "end date",
                   2146:         'status'     => "status",
                   2147:         'role'       => "role",
1.150     raeburn  2148:         'credits'    => "credits",
1.140     raeburn  2149:         'type'       => "enroll type/action",
                   2150:         'email'      => "e-mail address",
                   2151:         'photo'      => "photo",
                   2152:         'lastlogin'  => "last login",
                   2153:         'extent'     => "extent",
1.159     raeburn  2154:         'authorusage' => "disk usage (%)",
                   2155:         'authorquota' => "disk quota (MB)",
1.140     raeburn  2156:         'ca'         => "check all",
                   2157:         'ua'         => "uncheck all",
                   2158:         'clicker'    => "clicker-ID",
                   2159:     );
                   2160:     if ($context eq 'domain' && $env{'form.roletype'} eq 'course') {
1.149     raeburn  2161:         $lt{'extent'} = &mt('course(s): description, section(s), status');
1.140     raeburn  2162:     } elsif ($context eq 'domain' && $env{'form.roletype'} eq 'community') {
1.154     raeburn  2163:         $lt{'extent'} = &mt('community(s): description, section(s), status');
1.149     raeburn  2164:     } elsif (($context eq 'author') || 
                   2165:              ($context eq 'domain' && $env{'form.roletype'} eq 'author')) {
                   2166:         $lt{'extent'} = &mt('author');
1.140     raeburn  2167:     }
                   2168:     return %lt;
                   2169: }
                   2170: 
1.2       raeburn  2171: sub gather_userinfo {
1.11      raeburn  2172:     my ($context,$format,$userlist,$indexhash,$userinfo,$rolehash,$permission) = @_;
1.52      raeburn  2173:     my $viewablesec;
                   2174:     if ($context eq 'course') {
                   2175:         $viewablesec = &viewable_section($permission);
                   2176:     }
1.2       raeburn  2177:     foreach my $item (keys(%{$rolehash})) {
                   2178:         my %userdata;
1.22      raeburn  2179:         if ($context eq 'author') { 
1.2       raeburn  2180:             ($userdata{'username'},$userdata{'domain'},$userdata{'role'}) =
                   2181:                 split(/:/,$item);
                   2182:             ($userdata{'start'},$userdata{'end'})=split(/:/,$rolehash->{$item});
1.24      raeburn  2183:             &build_user_record($context,\%userdata,$userinfo,$indexhash,
                   2184:                                $item,$userlist);
1.22      raeburn  2185:         } elsif ($context eq 'course') {
                   2186:             ($userdata{'username'},$userdata{'domain'},$userdata{'role'},
                   2187:              $userdata{'section'}) = split(/:/,$item,-1);
                   2188:             ($userdata{'start'},$userdata{'end'})=split(/:/,$rolehash->{$item});
                   2189:             if (($viewablesec ne '') && ($userdata{'section'} ne '')) {
                   2190:                 next if ($viewablesec ne $userdata{'section'});
                   2191:             }
1.24      raeburn  2192:             &build_user_record($context,\%userdata,$userinfo,$indexhash,
                   2193:                                $item,$userlist);
1.2       raeburn  2194:         } elsif ($context eq 'domain') {
                   2195:             if ($env{'form.roletype'} eq 'domain') {
                   2196:                 ($userdata{'role'},$userdata{'username'},$userdata{'domain'}) =
                   2197:                     split(/:/,$item);
                   2198:                 ($userdata{'end'},$userdata{'start'})=split(/:/,$rolehash->{$item});
1.24      raeburn  2199:                 &build_user_record($context,\%userdata,$userinfo,$indexhash,
                   2200:                                    $item,$userlist);
1.13      raeburn  2201:             } elsif ($env{'form.roletype'} eq 'author') {
1.2       raeburn  2202:                 if (ref($rolehash->{$item}) eq 'HASH') {
                   2203:                     $userdata{'extent'} = $item;
                   2204:                     foreach my $key (keys(%{$rolehash->{$item}})) {
                   2205:                         ($userdata{'username'},$userdata{'domain'},$userdata{'role'}) =  split(/:/,$key);
                   2206:                         ($userdata{'start'},$userdata{'end'}) = 
                   2207:                             split(/:/,$rolehash->{$item}{$key});
                   2208:                         my $uniqid = $key.':'.$item;
1.25      raeburn  2209:                         &build_user_record($context,\%userdata,$userinfo,
                   2210:                                            $indexhash,$uniqid,$userlist);
1.2       raeburn  2211:                     }
                   2212:                 }
1.102     raeburn  2213:             } elsif (($env{'form.roletype'} eq 'course') || 
                   2214:                      ($env{'form.roletype'} eq 'community')) {
1.2       raeburn  2215:                 ($userdata{'username'},$userdata{'domain'},$userdata{'role'}) =
                   2216:                     split(/:/,$item);
                   2217:                 if (ref($rolehash->{$item}) eq 'HASH') {
1.11      raeburn  2218:                     my $numcids = keys(%{$rolehash->{$item}});
1.2       raeburn  2219:                     foreach my $cid (sort(keys(%{$rolehash->{$item}}))) {
                   2220:                         if (ref($rolehash->{$item}{$cid}) eq 'HASH') {
                   2221:                             my $spanstart = '';
                   2222:                             my $spanend = '; ';
                   2223:                             my $space = ', ';
                   2224:                             if ($format eq 'html' || $format eq 'view') {
                   2225:                                 $spanstart = '<span class="LC_nobreak">';
1.23      raeburn  2226:                                 # FIXME: actions on courses disabled for now
                   2227: #                                if ($permission->{'cusr'}) {
                   2228: #                                    if ($numcids > 1) {
1.25      raeburn  2229: #                                        $spanstart .= '<input type="radio" name="'.$item.'" value="'.$cid.'" />&nbsp;';
1.23      raeburn  2230: #                                    } else {
1.25      raeburn  2231: #                                        $spanstart .= '<input type="hidden" name="'.$item.'" value="'.$cid.'" />&nbsp;';
1.23      raeburn  2232: #                                    }
                   2233: #                                }
1.2       raeburn  2234:                                 $spanend = '</span><br />';
                   2235:                                 $space = ',&nbsp;';
                   2236:                             }
                   2237:                             $userdata{'extent'} .= $spanstart.
                   2238:                                     $rolehash->{$item}{$cid}{'desc'}.$space;
                   2239:                             if (ref($rolehash->{$item}{$cid}{'secs'}) eq 'HASH') { 
                   2240:                                 foreach my $sec (sort(keys(%{$rolehash->{$item}{$cid}{'secs'}}))) {
1.25      raeburn  2241:                                     if (($env{'form.Status'} eq 'Any') ||
                   2242:                                         ($env{'form.Status'} eq $rolehash->{$item}{$cid}{'secs'}{$sec})) {
                   2243:                                         $userdata{'extent'} .= $sec.$space.$rolehash->{$item}{$cid}{'secs'}{$sec}.$spanend;
                   2244:                                         $userdata{'status'} = $rolehash->{$item}{$cid}{'secs'}{$sec};
                   2245:                                     }
1.2       raeburn  2246:                                 }
                   2247:                             }
                   2248:                         }
                   2249:                     }
                   2250:                 }
1.25      raeburn  2251:                 if ($userdata{'status'} ne '') {
                   2252:                     &build_user_record($context,\%userdata,$userinfo,
                   2253:                                        $indexhash,$item,$userlist);
                   2254:                 }
1.2       raeburn  2255:             }
                   2256:         }
                   2257:     }
                   2258:     return;
                   2259: }
                   2260: 
                   2261: sub build_user_record {
1.24      raeburn  2262:     my ($context,$userdata,$userinfo,$indexhash,$record_key,$userlist) = @_;
1.11      raeburn  2263:     next if ($userdata->{'start'} eq '-1' && $userdata->{'end'} eq '-1');
1.102     raeburn  2264:     if (!(($context eq 'domain') && (($env{'form.roletype'} eq 'course')
                   2265:                              && ($env{'form.roletype'} eq 'community')))) {
1.24      raeburn  2266:         &process_date_info($userdata);
                   2267:     }
1.2       raeburn  2268:     my $username = $userdata->{'username'};
                   2269:     my $domain = $userdata->{'domain'};
                   2270:     if (ref($userinfo->{$username.':'.$domain}) eq 'HASH') {
1.24      raeburn  2271:         $userdata->{'fullname'} = $userinfo->{$username.':'.$domain}{'fullname'};
1.2       raeburn  2272:         $userdata->{'id'} = $userinfo->{$username.':'.$domain}{'id'};
                   2273:     } else {
                   2274:         &aggregate_user_info($domain,$username,$userinfo);
                   2275:         $userdata->{'fullname'} = $userinfo->{$username.':'.$domain}{'fullname'};
                   2276:         $userdata->{'id'} = $userinfo->{$username.':'.$domain}{'id'};
                   2277:     }
                   2278:     foreach my $key (keys(%{$indexhash})) {
                   2279:         if (defined($userdata->{$key})) {
                   2280:             $userlist->{$record_key}[$indexhash->{$key}] = $userdata->{$key};
                   2281:         }
                   2282:     }
                   2283:     return;
                   2284: }
                   2285: 
                   2286: sub courses_selector {
                   2287:     my ($cdom,$formname) = @_;
                   2288:     my %coursecodes = ();
                   2289:     my %codes = ();
                   2290:     my @codetitles = ();
                   2291:     my %cat_titles = ();
                   2292:     my %cat_order = ();
                   2293:     my %idlist = ();
                   2294:     my %idnums = ();
                   2295:     my %idlist_titles = ();
                   2296:     my $caller = 'global';
                   2297:     my $format_reply;
                   2298:     my $jscript = '';
                   2299: 
1.7       albertel 2300:     my $totcodes = 0;
                   2301:     $totcodes =
1.2       raeburn  2302:         &Apache::courseclassifier::retrieve_instcodes(\%coursecodes,
                   2303:                                                       $cdom,$totcodes);
                   2304:     if ($totcodes > 0) {
                   2305:         $format_reply =
                   2306:              &Apache::lonnet::auto_instcode_format($caller,$cdom,\%coursecodes,
                   2307:                                 \%codes,\@codetitles,\%cat_titles,\%cat_order);
                   2308:         if ($format_reply eq 'ok') {
                   2309:             my $numtypes = @codetitles;
                   2310:             &Apache::courseclassifier::build_code_selections(\%codes,\@codetitles,\%cat_titles,\%cat_order,\%idlist,\%idnums,\%idlist_titles);
                   2311:             my ($scripttext,$longtitles) = &Apache::courseclassifier::javascript_definitions(\@codetitles,\%idlist,\%idlist_titles,\%idnums,\%cat_titles);
                   2312:             my $longtitles_str = join('","',@{$longtitles});
                   2313:             my $allidlist = $idlist{$codetitles[0]};
                   2314:             $jscript .= &Apache::courseclassifier::courseset_js_start($formname,$longtitles_str,$allidlist);
                   2315:             $jscript .= $scripttext;
1.181     raeburn  2316:             $jscript .= &Apache::courseclassifier::javascript_code_selections($formname,\@codetitles);
1.2       raeburn  2317:         }
                   2318:     }
                   2319:     my $cb_jscript = &Apache::loncommon::coursebrowser_javascript($cdom);
                   2320: 
                   2321:     my %elements = (
                   2322:                      Year => 'selectbox',
                   2323:                      coursepick => 'radio',
                   2324:                      coursetotal => 'text',
                   2325:                      courselist => 'text',
                   2326:                    );
                   2327:     $jscript .= &Apache::lonhtmlcommon::set_form_elements(\%elements);
                   2328:     if ($env{'form.coursepick'} eq 'category') {
                   2329:         $jscript .= qq|
                   2330: function setCourseCat(formname) {
                   2331:     if (formname.Year.options[formname.Year.selectedIndex].value == -1) {
                   2332:         return;
                   2333:     }
1.120     raeburn  2334:     courseSet('$codetitles[0]');
1.2       raeburn  2335:     for (var j=0; j<formname.Semester.length; j++) {
                   2336:         if (formname.Semester.options[j].value == "$env{'form.Semester'}") {
                   2337:             formname.Semester.options[j].selected = true;
                   2338:         }
                   2339:     }
                   2340:     if (formname.Semester.options[formname.Semester.selectedIndex].value == -1) {
                   2341:         return;
                   2342:     }
1.120     raeburn  2343:     courseSet('$codetitles[1]');
1.2       raeburn  2344:     for (var j=0; j<formname.Department.length; j++) {
                   2345:         if (formname.Department.options[j].value == "$env{'form.Department'}") {            formname.Department.options[j].selected = true;
                   2346:         }
                   2347:     }
                   2348:     if (formname.Department.options[formname.Department.selectedIndex].value == -1) {
                   2349:         return;
                   2350:     }
1.120     raeburn  2351:     courseSet('$codetitles[2]');
1.2       raeburn  2352:     for (var j=0; j<formname.Number.length; j++) {
                   2353:         if (formname.Number.options[j].value == "$env{'form.Number'}") {
                   2354:             formname.Number.options[j].selected = true;
                   2355:         }
                   2356:     }
                   2357: }
                   2358: |;
                   2359:     }
                   2360:     return ($cb_jscript,$jscript,$totcodes,\@codetitles,\%idlist,
                   2361:             \%idlist_titles);
                   2362: }
                   2363: 
                   2364: sub course_selector_loadcode {
                   2365:     my ($formname) = @_;
                   2366:     my $loadcode;
                   2367:     if ($env{'form.coursepick'} ne '') {
                   2368:         $loadcode = 'javascript:setFormElements(document.'.$formname.')';
                   2369:         if ($env{'form.coursepick'} eq 'category') {
                   2370:             $loadcode .= ';javascript:setCourseCat(document.'.$formname.')';
                   2371:         }
                   2372:     }
                   2373:     return $loadcode;
                   2374: }
                   2375: 
                   2376: sub process_coursepick {
                   2377:     my $coursefilter = $env{'form.coursepick'};
                   2378:     my $cdom = $env{'request.role.domain'};
                   2379:     my %courses;
1.105     raeburn  2380:     my $crssrch = 'Course';
                   2381:     if ($env{'form.roletype'} eq 'community') {
                   2382:         $crssrch = 'Community';
                   2383:     }
1.2       raeburn  2384:     if ($coursefilter eq 'all') {
                   2385:         %courses = &Apache::lonnet::courseiddump($cdom,'.','.','.','.','.',
1.105     raeburn  2386:                                                  undef,undef,$crssrch);
1.2       raeburn  2387:     } elsif ($coursefilter eq 'category') {
                   2388:         my $instcode = &instcode_from_coursefilter();
                   2389:         %courses = &Apache::lonnet::courseiddump($cdom,'.','.',$instcode,'.','.',
1.105     raeburn  2390:                                                  undef,undef,$crssrch);
1.2       raeburn  2391:     } elsif ($coursefilter eq 'specific') {
                   2392:         if ($env{'form.coursetotal'} > 1) {
                   2393:             my @course_ids = split(/&&/,$env{'form.courselist'});
                   2394:             foreach my $cid (@course_ids) {
                   2395:                 $courses{$cid} = '';
1.1       raeburn  2396:             }
1.2       raeburn  2397:         } else {
                   2398:             $courses{$env{'form.courselist'}} = '';
1.1       raeburn  2399:         }
1.2       raeburn  2400:     }
                   2401:     return %courses;
                   2402: }
                   2403: 
                   2404: sub instcode_from_coursefilter {
                   2405:     my $instcode = '';
                   2406:     my @cats = ('Semester','Year','Department','Number');
                   2407:     foreach my $category (@cats) {
                   2408:         if (defined($env{'form.'.$category})) {
                   2409:             unless ($env{'form.'.$category} eq '-1') {
                   2410:                 $instcode .= $env{'form.'.$category};
                   2411:            }
                   2412:         }
                   2413:     }
                   2414:     if ($instcode eq '') {
                   2415:         $instcode = '.';
                   2416:     }
                   2417:     return $instcode;
                   2418: }
                   2419: 
                   2420: sub make_keylist_array {
                   2421:     my ($index,$keylist);
                   2422:     $index->{'domain'} = &Apache::loncoursedata::CL_SDOM();
                   2423:     $index->{'username'} = &Apache::loncoursedata::CL_SNAME();
                   2424:     $index->{'end'} = &Apache::loncoursedata::CL_END();
                   2425:     $index->{'start'} = &Apache::loncoursedata::CL_START();
                   2426:     $index->{'id'} = &Apache::loncoursedata::CL_ID();
                   2427:     $index->{'section'} = &Apache::loncoursedata::CL_SECTION();
                   2428:     $index->{'fullname'} = &Apache::loncoursedata::CL_FULLNAME();
                   2429:     $index->{'status'} = &Apache::loncoursedata::CL_STATUS();
                   2430:     $index->{'type'} = &Apache::loncoursedata::CL_TYPE();
                   2431:     $index->{'lockedtype'} = &Apache::loncoursedata::CL_LOCKEDTYPE();
                   2432:     $index->{'groups'} = &Apache::loncoursedata::CL_GROUP();
                   2433:     $index->{'email'} = &Apache::loncoursedata::CL_PERMANENTEMAIL();
                   2434:     $index->{'role'} = &Apache::loncoursedata::CL_ROLE();
                   2435:     $index->{'extent'} = &Apache::loncoursedata::CL_EXTENT();
1.44      raeburn  2436:     $index->{'photo'} = &Apache::loncoursedata::CL_PHOTO();
1.47      raeburn  2437:     $index->{'thumbnail'} = &Apache::loncoursedata::CL_THUMBNAIL();
1.150     raeburn  2438:     $index->{'credits'} = &Apache::loncoursedata::CL_CREDITS();
1.174     raeburn  2439:     $index->{'instsec'} = &Apache::loncoursedata::CL_INSTSEC();
1.159     raeburn  2440:     $index->{'authorquota'} = &Apache::loncoursedata::CL_AUTHORQUOTA();
                   2441:     $index->{'authorusage'} = &Apache::loncoursedata::CL_AUTHORUSAGE();
1.2       raeburn  2442:     foreach my $key (keys(%{$index})) {
                   2443:         $keylist->[$index->{$key}] = $key;
                   2444:     }
                   2445:     return ($index,$keylist);
                   2446: }
                   2447: 
                   2448: sub aggregate_user_info {
                   2449:     my ($udom,$uname,$userinfo) = @_;
                   2450:     my %info=&Apache::lonnet::get('environment',
                   2451:                                   ['firstname','middlename',
                   2452:                                    'lastname','generation','id'],
                   2453:                                    $udom,$uname);
                   2454:     my ($tmp) = keys(%info);
                   2455:     my ($fullname,$id);
                   2456:     if ($tmp =~/^(con_lost|error|no_such_host)/i) {
                   2457:         $fullname = 'not available';
                   2458:         $id = 'not available';
                   2459:         &Apache::lonnet::logthis('unable to retrieve environment '.
                   2460:                                  'for '.$uname.':'.$udom);
1.1       raeburn  2461:     } else {
1.2       raeburn  2462:         $fullname = &Apache::lonnet::format_name(@info{qw/firstname middlename lastname generation/},'lastname');
                   2463:         $id = $info{'id'};
                   2464:     }
                   2465:     $userinfo->{$uname.':'.$udom} = { 
                   2466:                                       fullname => $fullname,
                   2467:                                       id       => $id,
                   2468:                                     };
                   2469:     return;
                   2470: }
1.1       raeburn  2471: 
1.2       raeburn  2472: sub process_date_info {
                   2473:     my ($userdata) = @_;
                   2474:     my $now = time;
1.83      raeburn  2475:     $userdata->{'status'} = 'Active';
1.2       raeburn  2476:     if ($userdata->{'start'} > 0) {
                   2477:         if ($now < $userdata->{'start'}) {
1.83      raeburn  2478:             $userdata->{'status'} = 'Future';
1.2       raeburn  2479:         }
1.1       raeburn  2480:     }
1.2       raeburn  2481:     if ($userdata->{'end'} > 0) {
                   2482:         if ($now > $userdata->{'end'}) {
1.83      raeburn  2483:             $userdata->{'status'} = 'Expired';
1.2       raeburn  2484:         }
                   2485:     }
                   2486:     return;
1.1       raeburn  2487: }
                   2488: 
                   2489: sub show_users_list {
1.150     raeburn  2490:     my ($r,$context,$mode,$permission,$statusmode,$userlist,$keylist,$formname,
1.159     raeburn  2491:         $showcredits,$needauthorquota,$needauthorusage)=@_;
1.55      raeburn  2492:     if ($formname eq '') {
                   2493:         $formname = 'studentform';
                   2494:     }
1.159     raeburn  2495:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1       raeburn  2496:     #
                   2497:     # Variables for excel output
                   2498:     my ($excel_workbook, $excel_sheet, $excel_filename,$row,$format);
                   2499:     #
                   2500:     # Variables for csv output
                   2501:     my ($CSVfile,$CSVfilename);
                   2502:     #
                   2503:     my $sortby = $env{'form.sortby'};
1.3       raeburn  2504:     my @sortable = ('username','domain','id','fullname','start','end','email','role');
1.2       raeburn  2505:     if ($context eq 'course') {
1.3       raeburn  2506:         push(@sortable,('section','groups','type'));
1.150     raeburn  2507:         if ($showcredits) {
                   2508:             push(@sortable,'credits');
                   2509:         }
1.2       raeburn  2510:     } else {
1.3       raeburn  2511:         push(@sortable,'extent');
1.159     raeburn  2512:         if (($context eq 'domain') && ($env{'form.roletype'} eq 'domain') &&
                   2513:             (($env{'form.showrole'} eq 'Any') || ($env{'form.showrole'} eq 'au'))) {
                   2514:             push(@sortable,('authorusage','authorquota'));
                   2515:         }
1.3       raeburn  2516:     }
1.55      raeburn  2517:     if ($mode eq 'pickauthor') {
                   2518:         @sortable = ('username','fullname','email','status');
                   2519:     }
1.156     raeburn  2520:     my %is_sortable;
1.158     raeburn  2521:     map { $is_sortable{$_} = 1; } @sortable;
1.156     raeburn  2522:     unless ($is_sortable{$sortby}) {
1.3       raeburn  2523:         $sortby = 'username';
1.1       raeburn  2524:     }
1.22      raeburn  2525:     my $setting = $env{'form.roletype'};
1.150     raeburn  2526:     my ($cid,$cdom,$cnum,$classgroups,$crstype,$defaultcredits);
1.1       raeburn  2527:     if ($context eq 'course') {
1.22      raeburn  2528:         $cid = $env{'request.course.id'};
1.101     raeburn  2529:         $crstype = &Apache::loncommon::course_type();
1.17      raeburn  2530:         ($cnum,$cdom) = &get_course_identity($cid);
1.150     raeburn  2531:         $defaultcredits = $env{'course.'.$cid.'.internal.defaultcredits'};
1.2       raeburn  2532:         ($classgroups) = &Apache::loncoursedata::get_group_memberships(
                   2533:                                      $userlist,$keylist,$cdom,$cnum);
1.16      raeburn  2534:         if ($mode eq 'autoenroll') {
                   2535:             $env{'form.showrole'} = 'st';
                   2536:         } else {
                   2537:             if ($env{'course.'.$cid.'.internal.showphoto'}) {
                   2538:                 $r->print('
1.1       raeburn  2539: <script type="text/javascript">
1.96      bisitz   2540: // <![CDATA[
1.1       raeburn  2541: function photowindow(photolink) {
                   2542:     var title = "Photo_Viewer";
                   2543:     var options = "scrollbars=1,resizable=1,menubar=0";
                   2544:     options += ",width=240,height=240";
                   2545:     stdeditbrowser = open(photolink,title,options,"1");
                   2546:     stdeditbrowser.focus();
                   2547: }
1.96      bisitz   2548: // ]]>
1.1       raeburn  2549: </script>
1.16      raeburn  2550:                ');
                   2551:             }
                   2552:         }
1.102     raeburn  2553:     } elsif ($context eq 'domain') {
                   2554:         if ($setting eq 'community') {
                   2555:             $crstype = 'Community';
1.105     raeburn  2556:         } elsif ($setting eq 'course') {
1.102     raeburn  2557:             $crstype = 'Course';
                   2558:         }
1.1       raeburn  2559:     }
1.55      raeburn  2560:     if ($mode ne 'autoenroll' && $mode ne 'pickauthor') {
1.40      raeburn  2561:         my $date_sec_selector = &date_section_javascript($context,$setting,$statusmode);
1.56      raeburn  2562:         my $verify_action_js = &bulkaction_javascript($formname);
1.1       raeburn  2563:         $r->print(<<END);
1.10      raeburn  2564: 
                   2565: <script type="text/javascript" language="Javascript">
1.96      bisitz   2566: // <![CDATA[
1.11      raeburn  2567: 
1.56      raeburn  2568: $verify_action_js
1.10      raeburn  2569: 
                   2570: function username_display_launch(username,domain) {
                   2571:     var target;
1.177     raeburn  2572:     if (!document.$formname.usernamelink.length) {
                   2573:         target = document.$formname.usernamelink.value;
                   2574:     } else {
                   2575:         for (var i=0; i<document.$formname.usernamelink.length; i++) {
                   2576:             if (document.$formname.usernamelink[i].checked) {
                   2577:                target = document.$formname.usernamelink[i].value;
                   2578:             }
1.10      raeburn  2579:         }
                   2580:     }
1.179     raeburn  2581:     if ((target == 'modify') || (target == 'activity')) {
                   2582:         var nextaction = 'singleuser';
                   2583:         if (target == 'activity') {
                   2584:             nextaction = 'accesslogs';
                   2585:         }
1.55      raeburn  2586:         if (document.$formname.userwin.checked == true) {
1.179     raeburn  2587:             var url = '/adm/createuser?srchterm='+username+'&srchdomain='+domain+'&phase=get_user_info&srchin=dom&srchby=uname&srchtype=exact&popup=1&action='+nextaction;
1.50      raeburn  2588:             var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
                   2589:             modifywin = window.open(url,'',options,1);
                   2590:             modifywin.focus();
                   2591:             return;
                   2592:         } else {
1.55      raeburn  2593:             document.$formname.srchterm.value=username;
                   2594:             document.$formname.srchdomain.value=domain;
                   2595:             document.$formname.phase.value='get_user_info';
1.179     raeburn  2596:             document.$formname.action.value = nextaction;
1.55      raeburn  2597:             document.$formname.submit();
1.50      raeburn  2598:         }
1.10      raeburn  2599:     }
1.48      raeburn  2600:     if (target == 'aboutme') {
1.55      raeburn  2601:         if (document.$formname.userwin.checked == true) {
1.50      raeburn  2602:             var url = '/adm/'+domain+'/'+username+'/aboutme?popup=1';
                   2603:             var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
                   2604:             aboutmewin = window.open(url,'',options,1);
                   2605:             aboutmewin.focus();
                   2606:             return;
                   2607:         } else {
                   2608:             document.location.href = '/adm/'+domain+'/'+username+'/aboutme';
                   2609:         }
1.48      raeburn  2610:     }
1.98      raeburn  2611:     if (target == 'track') {
                   2612:         if (document.$formname.userwin.checked == true) {
                   2613:             var url = '/adm/trackstudent?selected_student='+username+':'+domain+'&only_body=1';
                   2614:             var options = 'height=600,width=800,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no';
                   2615:             var trackwin = window.open(url,'',options,1);
                   2616:             trackwin.focus();
                   2617:             return;
                   2618:         } else {
                   2619:             document.location.href = '/adm/trackstudent?selected_student='+username+':'+domain;
                   2620:         }
                   2621:     }
1.10      raeburn  2622: }
1.96      bisitz   2623: // ]]>
1.10      raeburn  2624: </script>
1.11      raeburn  2625: $date_sec_selector
1.1       raeburn  2626: <input type="hidden" name="state" value="$env{'form.state'}" />
                   2627: END
                   2628:     }
                   2629:     $r->print(<<END);
                   2630: <input type="hidden" name="sortby" value="$sortby" />
                   2631: END
1.150     raeburn  2632:     my @cols = &infocolumns($context,$mode,$showcredits);
1.140     raeburn  2633:     my %coltxt = &get_column_names($context);
                   2634:     my %acttxt = &Apache::lonlocal::texthash(
1.11      raeburn  2635:                        'pr'         => "Proceed",
                   2636:                        'ac'         => "Action to take for selected users",
1.56      raeburn  2637:                        'link'       => "Behavior of clickable username link for each user",
1.82      weissno  2638:                        'aboutme'    => "Display a user's personal information page",
1.50      raeburn  2639:                        'owin'       => "Open in a new window",
1.10      raeburn  2640:                        'modify'     => "Modify a user's information",
1.98      raeburn  2641:                        'track'      => "View a user's recent activity",
1.179     raeburn  2642:                        'activity'   => "View a user's access log", 
1.1       raeburn  2643:                       );
1.140     raeburn  2644:     my %lt = (%coltxt,%acttxt);
1.4       raeburn  2645:     my $rolefilter = $env{'form.showrole'};
1.5       raeburn  2646:     if ($env{'form.showrole'} eq 'cr') {
                   2647:         $rolefilter = &mt('custom');  
                   2648:     } elsif ($env{'form.showrole'} ne 'Any') {
1.101     raeburn  2649:         $rolefilter = &Apache::lonnet::plaintext($env{'form.showrole'},$crstype);
1.2       raeburn  2650:     }
1.16      raeburn  2651:     my $results_description;
                   2652:     if ($mode ne 'autoenroll') {
                   2653:         $results_description = &results_header_row($rolefilter,$statusmode,
1.102     raeburn  2654:                                                    $context,$permission,$mode,$crstype);
1.140     raeburn  2655:         $r->print('<b>'.$results_description.'</b><br clear="all" />');
1.16      raeburn  2656:     }
1.26      raeburn  2657:     my ($output,$actionselect,%canchange,%canchangesec);
1.55      raeburn  2658:     if ($mode eq 'html' || $mode eq 'view' || $mode eq 'autoenroll' || $mode eq 'pickauthor') {
                   2659:         if ($mode ne 'autoenroll' && $mode ne 'pickauthor') {
1.16      raeburn  2660:             if ($permission->{'cusr'}) {
1.105     raeburn  2661:                 unless (($context eq 'domain') && 
                   2662:                         (($setting eq 'course') || ($setting eq 'community'))) {
                   2663:                     $actionselect = 
                   2664:                         &select_actions($context,$setting,$statusmode,$formname);
                   2665:                 }
1.16      raeburn  2666:             }
                   2667:             $r->print(<<END);
1.10      raeburn  2668: <input type="hidden" name="srchby"  value="uname" />
                   2669: <input type="hidden" name="srchin"   value="dom" />
                   2670: <input type="hidden" name="srchtype" value="exact" />
                   2671: <input type="hidden" name="srchterm" value="" />
1.11      raeburn  2672: <input type="hidden" name="srchdomain" value="" /> 
1.1       raeburn  2673: END
1.16      raeburn  2674:             if ($actionselect) {
1.41      raeburn  2675:                 $output .= <<"END";
1.94      bisitz   2676: <div class="LC_left_float"><fieldset><legend>$lt{'ac'}</legend>
1.56      raeburn  2677: $actionselect
                   2678: <br/><br /><input type="button" value="$lt{'ca'}" onclick="javascript:checkAll(document.$formname.actionlist)" /> &nbsp;
                   2679: <input type="button" value="$lt{'ua'}" onclick="javascript:uncheckAll(document.$formname.actionlist)" /><br /><input type="button" value="$lt{'pr'}" onclick="javascript:verify_action('actionlist')" /></fieldset></div>
1.11      raeburn  2680: END
1.26      raeburn  2681:                 my @allroles;
                   2682:                 if ($env{'form.showrole'} eq 'Any') {
                   2683:                     my $custom = 1;
                   2684:                     if ($context eq 'domain') {
1.101     raeburn  2685:                         @allroles = &roles_by_context($setting,$custom,$crstype);
1.26      raeburn  2686:                     } else {
1.101     raeburn  2687:                         @allroles = &roles_by_context($context,$custom,$crstype);
1.26      raeburn  2688:                     }
                   2689:                 } else {
                   2690:                     @allroles = ($env{'form.showrole'});
                   2691:                 }
                   2692:                 foreach my $role (@allroles) {
                   2693:                     if ($context eq 'domain') {
                   2694:                         if ($setting eq 'domain') {
                   2695:                             if (&Apache::lonnet::allowed('c'.$role,
                   2696:                                     $env{'request.role.domain'})) {
                   2697:                                 $canchange{$role} = 1;
                   2698:                             }
1.31      raeburn  2699:                         } elsif ($setting eq 'author') {
                   2700:                             if (&Apache::lonnet::allowed('c'.$role,
                   2701:                                     $env{'request.role.domain'})) {
                   2702:                                 $canchange{$role} = 1;
                   2703:                             }
1.26      raeburn  2704:                         }
                   2705:                     } elsif ($context eq 'author') {
                   2706:                         if (&Apache::lonnet::allowed('c'.$role,
                   2707:                             $env{'user.domain'}.'/'.$env{'user.name'})) {
                   2708:                             $canchange{$role} = 1;
                   2709:                         }
                   2710:                     } elsif ($context eq 'course') {
                   2711:                         if (&Apache::lonnet::allowed('c'.$role,$env{'request.course.id'})) {
                   2712:                             $canchange{$role} = 1;
                   2713:                         } elsif ($env{'request.course.sec'} ne '') {
                   2714:                             if (&Apache::lonnet::allowed('c'.$role,$env{'request.course.id'}.'/'.$env{'request.course.sec'})) {
                   2715:                                 $canchangesec{$role} = $env{'request.course.sec'};
                   2716:                             }
1.141     raeburn  2717:                         } elsif ((($role eq 'co') && ($crstype eq 'Community')) ||
                   2718:                                  (($role eq 'cc') && ($crstype eq 'Course'))) {
                   2719:                             if (&is_courseowner($env{'request.course.id'},
                   2720:                                                 $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'})) {
                   2721:                                 $canchange{$role} = 1;
                   2722:                             }
1.26      raeburn  2723:                         }
                   2724:                     }
                   2725:                 }
1.16      raeburn  2726:             }
1.94      bisitz   2727:             $output .= '<div class="LC_left_float"><fieldset><legend>'.$lt{'link'}.'</legend>'.
1.56      raeburn  2728:                        '<table><tr>';
                   2729:             my @linkdests = ('aboutme');
                   2730:             if ($permission->{'cusr'}) {
                   2731:                 unshift (@linkdests,'modify');
                   2732:             }
1.179     raeburn  2733:             if ($context eq 'course') {
                   2734:                 if (&Apache::lonnet::allowed('vsa', $env{'request.course.id'}) ||
                   2735:                     &Apache::lonnet::allowed('vsa', $env{'request.course.id'}.'/'.
                   2736:                                              $env{'request.course.sec'})) {
                   2737:                     push(@linkdests,'track');
                   2738:                 }
                   2739:             } elsif ($context eq 'domain') {
                   2740:                 if (&Apache::lonnet::allowed('vac',$env{'request.role.domain'})) {
                   2741:                     push(@linkdests,'activity');
                   2742:                 }
1.98      raeburn  2743:             }
1.56      raeburn  2744:             $output .= '<td>';
                   2745:             my $usernamelink = $env{'form.usernamelink'};
                   2746:             if ($usernamelink eq '') {
                   2747:                 $usernamelink = 'aboutme';
                   2748:             }
                   2749:             foreach my $item (@linkdests) {
                   2750:                 my $checkedstr = '';
                   2751:                 if ($item eq $usernamelink) {
1.86      bisitz   2752:                     $checkedstr = ' checked="checked"';
1.56      raeburn  2753:                 }
1.86      bisitz   2754:                 $output .= '<span class="LC_nobreak"><label><input type="radio" name="usernamelink" value="'.$item.'"'.$checkedstr.' />&nbsp;'.$lt{$item}.'</label></span><br />';
1.56      raeburn  2755:             }
                   2756:             my $checkwin;
                   2757:             if ($env{'form.userwin'}) {
1.86      bisitz   2758:                 $checkwin = ' checked="checked"';
1.56      raeburn  2759:             }
1.144     bisitz   2760:             $output .=
                   2761:                 '</td><td valign="top"  style="border-left: 1px solid;">'
                   2762:                .'<span class="LC_nobreak"><label>'
                   2763:                .'<input type="checkbox" name="userwin" value="1"'.$checkwin.' />'.$lt{'owin'}
                   2764:                .'</label></span></td></tr></table></fieldset></div>';
1.4       raeburn  2765:         }
1.184     raeburn  2766:         $output .= "\n".'<div style="padding:0;clear:both;margin:0;border:0"></div>'."\n".
1.1       raeburn  2767:                   &Apache::loncommon::start_data_table().
1.4       raeburn  2768:                   &Apache::loncommon::start_data_table_header_row();
1.1       raeburn  2769:         if ($mode eq 'autoenroll') {
1.4       raeburn  2770:             $output .= "
1.55      raeburn  2771:  <th><a href=\"javascript:document.$formname.sortby.value='type';document.$formname.submit();\">$lt{'type'}</a></th>
1.4       raeburn  2772:             ";
1.1       raeburn  2773:         } else {
1.105     raeburn  2774:             $output .= "\n".'<th>&nbsp;</th>'."\n";
1.11      raeburn  2775:             if ($actionselect) {
1.159     raeburn  2776:                 $output .= '<th class="LC_nobreak" valign="top">'.&mt('Select').'</th>'."\n";
1.11      raeburn  2777:             }
1.1       raeburn  2778:         }
                   2779:         foreach my $item (@cols) {
1.159     raeburn  2780:             $output .= '<th class="LC_nobreak" valign="top">';
1.156     raeburn  2781:             if ($is_sortable{$item}) {
1.159     raeburn  2782:                 $output .= "<a href=\"javascript:document.$formname.sortby.value='$item';document.$formname.submit();\" style=\"text-decoration:none;\">$lt{$item}<span class=\"LC_fontsize_small\"> &#9660;</span></a>";
1.156     raeburn  2783:             } else {
                   2784:                 $output .= $lt{$item};
                   2785:             }
                   2786:             $output .= "</th>\n";
1.1       raeburn  2787:         }
1.2       raeburn  2788:         my %role_types = &role_type_names();
1.16      raeburn  2789:         $output .= &Apache::loncommon::end_data_table_header_row();
1.1       raeburn  2790: # Done with the HTML header line
                   2791:     } elsif ($mode eq 'csv') {
                   2792:         #
                   2793:         # Open a file
                   2794:         $CSVfilename = '/prtspool/'.
1.2       raeburn  2795:                        $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
                   2796:                        time.'_'.rand(1000000000).'.csv';
1.1       raeburn  2797:         unless ($CSVfile = Apache::File->new('>/home/httpd'.$CSVfilename)) {
                   2798:             $r->log_error("Couldn't open $CSVfilename for output $!");
1.108     bisitz   2799:             $r->print(
                   2800:                 '<p class="LC_error">'
                   2801:                .&mt('Problems occurred in writing the CSV file.')
                   2802:                .' '.&mt('This error has been logged.')
                   2803:                .' '.&mt('Please alert your LON-CAPA administrator.')
                   2804:                .'</p>'
                   2805:             );
1.1       raeburn  2806:             $CSVfile = undef;
                   2807:         }
                   2808:         #
                   2809:         # Write headers and data to file
1.2       raeburn  2810:         print $CSVfile '"'.$results_description.'"'."\n"; 
1.1       raeburn  2811:         print $CSVfile '"'.join('","',map {
                   2812:             &Apache::loncommon::csv_translate($lt{$_})
1.67      droeschl 2813:             } (@cols))."\"\n";
1.1       raeburn  2814:     } elsif ($mode eq 'excel') {
                   2815:         # Create the excel spreadsheet
                   2816:         ($excel_workbook,$excel_filename,$format) =
                   2817:             &Apache::loncommon::create_workbook($r);
                   2818:         return if (! defined($excel_workbook));
                   2819:         $excel_sheet = $excel_workbook->addworksheet('userlist');
1.2       raeburn  2820:         $excel_sheet->write($row++,0,$results_description,$format->{'h2'});
1.1       raeburn  2821:         #
                   2822:         my @colnames = map {$lt{$_}} (@cols);
1.67      droeschl 2823: 
1.1       raeburn  2824:         $excel_sheet->write($row++,0,\@colnames,$format->{'bold'});
                   2825:     }
                   2826: 
                   2827: # Done with header lines in all formats
                   2828:     my %index;
                   2829:     my $i;
1.2       raeburn  2830:     foreach my $idx (@$keylist) {
                   2831:         $index{$idx} = $i++;
                   2832:     }
1.4       raeburn  2833:     my $usercount = 0;
1.33      raeburn  2834:     my ($secfilter,$grpfilter);
                   2835:     if ($context eq 'course') {
                   2836:         $secfilter = $env{'form.secfilter'};
                   2837:         $grpfilter = $env{'form.grpfilter'};
                   2838:         if ($secfilter eq '') {
                   2839:             $secfilter = 'all';
                   2840:         }
                   2841:         if ($grpfilter eq '') {
                   2842:             $grpfilter = 'all';
                   2843:         }
                   2844:     }
1.83      raeburn  2845:     my %ltstatus = &Apache::lonlocal::texthash(
                   2846:                                                 Active  => 'Active',
                   2847:                                                 Future  => 'Future',
                   2848:                                                 Expired => 'Expired',
                   2849:                                                );
1.139     raeburn  2850:     # If this is for a single course get last course "log-in".
                   2851:     my %crslogins;
                   2852:     if ($context eq 'course') {
                   2853:         %crslogins=&Apache::lonnet::dump('nohist_crslastlogin',$cdom,$cnum);
                   2854:     }
1.2       raeburn  2855:     # Get groups, role, permanent e-mail so we can sort on them if
                   2856:     # necessary.
                   2857:     foreach my $user (keys(%{$userlist})) {
1.43      raeburn  2858:         if ($user eq '' ) {
                   2859:             delete($userlist->{$user});
                   2860:             next;
                   2861:         }
1.11      raeburn  2862:         if ($context eq 'domain' &&  $user eq $env{'request.role.domain'}.'-domainconfig:'.$env{'request.role.domain'}) {
                   2863:             delete($userlist->{$user});
                   2864:             next;
                   2865:         }
1.2       raeburn  2866:         my ($uname,$udom,$role,$groups,$email);
1.5       raeburn  2867:         if (($statusmode ne 'Any') && 
                   2868:                  ($userlist->{$user}->[$index{'status'}] ne $statusmode)) {
                   2869:             delete($userlist->{$user});
                   2870:             next;
                   2871:         }
1.2       raeburn  2872:         if ($context eq 'domain') {
                   2873:             if ($env{'form.roletype'} eq 'domain') {
                   2874:                 ($role,$uname,$udom) = split(/:/,$user);
1.11      raeburn  2875:                 if (($uname eq $env{'request.role.domain'}.'-domainconfig') &&
                   2876:                     ($udom eq $env{'request.role.domain'})) {
                   2877:                     delete($userlist->{$user});
                   2878:                     next;
                   2879:                 }
1.13      raeburn  2880:             } elsif ($env{'form.roletype'} eq 'author') {
1.2       raeburn  2881:                 ($uname,$udom,$role) = split(/:/,$user,-1);
1.102     raeburn  2882:             } elsif (($env{'form.roletype'} eq 'course') || 
                   2883:                      ($env{'form.roletype'} eq 'community')) {
1.2       raeburn  2884:                 ($uname,$udom,$role) = split(/:/,$user);
                   2885:             }
                   2886:         } else {
                   2887:             ($uname,$udom,$role) = split(/:/,$user,-1);
                   2888:             if (($context eq 'course') && $role eq '') {
                   2889:                 $role = 'st';
                   2890:             }
                   2891:         }
                   2892:         $userlist->{$user}->[$index{'role'}] = $role;
                   2893:         if (($env{'form.showrole'} ne 'Any') && (!($env{'form.showrole'}  eq 'cr' && $role =~ /^cr\//)) && ($role ne $env{'form.showrole'})) {
                   2894:             delete($userlist->{$user});
                   2895:             next;
                   2896:         }
1.33      raeburn  2897:         if ($context eq 'course') {
                   2898:             my @ac_groups;
                   2899:             if (ref($classgroups) eq 'HASH') {
                   2900:                 $groups = $classgroups->{$user};
                   2901:             }
                   2902:             if (ref($groups->{'active'}) eq 'HASH') {
                   2903:                 @ac_groups = keys(%{$groups->{'active'}});
                   2904:                 $userlist->{$user}->[$index{'groups'}] = join(', ',@ac_groups);
                   2905:             }
                   2906:             if ($mode ne 'autoenroll') {
                   2907:                 my $section = $userlist->{$user}->[$index{'section'}];
1.43      raeburn  2908:                 if (($env{'request.course.sec'} ne '') && 
                   2909:                     ($section ne $env{'request.course.sec'})) {
                   2910:                     if ($role eq 'st') {
                   2911:                         delete($userlist->{$user});
                   2912:                         next;
                   2913:                     }
                   2914:                 }
1.33      raeburn  2915:                 if ($secfilter eq 'none') {
                   2916:                     if ($section ne '') {
                   2917:                         delete($userlist->{$user});
                   2918:                         next;
                   2919:                     }
                   2920:                 } elsif ($secfilter ne 'all') {
                   2921:                     if ($section ne $secfilter) {
                   2922:                         delete($userlist->{$user});
                   2923:                         next;
                   2924:                     }
                   2925:                 }
                   2926:                 if ($grpfilter eq 'none') {
                   2927:                     if (@ac_groups > 0) {
                   2928:                         delete($userlist->{$user});
                   2929:                         next;
                   2930:                     }
                   2931:                 } elsif ($grpfilter ne 'all') {
                   2932:                     if (!grep(/^\Q$grpfilter\E$/,@ac_groups)) {
                   2933:                         delete($userlist->{$user});
                   2934:                         next;
                   2935:                     }
                   2936:                 }
1.44      raeburn  2937:                 if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.140     raeburn  2938:                     if ((grep/^photo$/,@cols) && ($role eq 'st')) {
1.44      raeburn  2939:                         $userlist->{$user}->[$index{'photo'}] =
1.47      raeburn  2940:                             &Apache::lonnet::retrievestudentphoto($udom,$uname,'jpg');
                   2941:                         $userlist->{$user}->[$index{'thumbnail'}] =
1.44      raeburn  2942:                             &Apache::lonnet::retrievestudentphoto($udom,$uname,
                   2943:                                                                 'gif','thumbnail');
                   2944:                     }
                   2945:                 }
1.150     raeburn  2946:                 if (($role eq 'st') && ($defaultcredits)) {
                   2947:                     if ($userlist->{$user}->[$index{'credits'}] eq '') {
                   2948:                         $userlist->{$user}->[$index{'credits'}] = $defaultcredits;
                   2949:                     }
                   2950:                 }
1.33      raeburn  2951:             }
1.2       raeburn  2952:         }
                   2953:         my %emails   = &Apache::loncommon::getemails($uname,$udom);
                   2954:         if ($emails{'permanentemail'} =~ /\S/) {
                   2955:             $userlist->{$user}->[$index{'email'}] = $emails{'permanentemail'};
                   2956:         }
1.159     raeburn  2957:         if (($context eq 'domain') && ($env{'form.roletype'} eq 'domain') && 
                   2958:             ($role eq 'au')) {
                   2959:             my ($disk_quota,$current_disk_usage,$percent); 
                   2960:             if (($needauthorusage) || ($needauthorquota)) {
                   2961:                 $disk_quota = &Apache::loncommon::get_user_quota($uname,$udom,'author');
                   2962:             }
                   2963:             if ($needauthorusage) {
                   2964:                 $current_disk_usage =
                   2965:                     &Apache::lonnet::diskusage($udom,$uname,"$londocroot/priv/$udom/$uname");
                   2966:                 if ($disk_quota == 0) {
                   2967:                     $percent = 100.0;
                   2968:                 } else {
                   2969:                     $percent = $current_disk_usage/(10 * $disk_quota);
                   2970:                 }
                   2971:                 $userlist->{$user}->[$index{'authorusage'}] = sprintf("%.0f",$percent);
                   2972:             }
                   2973:             if ($needauthorquota) {
                   2974:                 $userlist->{$user}->[$index{'authorquota'}] = sprintf("%.2f",$disk_quota);
                   2975:             }
                   2976:         }
1.4       raeburn  2977:         $usercount ++;
                   2978:     }
                   2979:     my $autocount = 0;
                   2980:     my $manualcount = 0;
                   2981:     my $lockcount = 0;
                   2982:     my $unlockcount = 0;
                   2983:     if ($usercount) {
                   2984:         $r->print($output);
                   2985:     } else {
                   2986:         if ($mode eq 'autoenroll') {
                   2987:             return ($usercount,$autocount,$manualcount,$lockcount,$unlockcount);
                   2988:         } else {
                   2989:             return;
                   2990:         }
1.1       raeburn  2991:     }
1.2       raeburn  2992:     #
                   2993:     # Sort the users
1.1       raeburn  2994:     my $index  = $index{$sortby};
                   2995:     my $second = $index{'username'};
                   2996:     my $third  = $index{'domain'};
1.159     raeburn  2997:     my @sorted_users;
                   2998:     if (($sortby eq 'authorquota') || ($sortby eq 'authorusage')) {  
                   2999:         @sorted_users = sort {
                   3000:             $userlist->{$b}->[$index] <=> $userlist->{$a}->[$index]           ||
                   3001:             lc($userlist->{$a}->[$second]) cmp lc($userlist->{$b}->[$second]) ||
                   3002:             lc($userlist->{$a}->[$third]) cmp lc($userlist->{$b}->[$third])
                   3003:             } (keys(%$userlist));
                   3004:     } else {
                   3005:         @sorted_users = sort {
                   3006:             lc($userlist->{$a}->[$index]) cmp lc($userlist->{$b}->[$index])   ||
                   3007:             lc($userlist->{$a}->[$second]) cmp lc($userlist->{$b}->[$second]) ||
                   3008:             lc($userlist->{$a}->[$third]) cmp lc($userlist->{$b}->[$third])
                   3009:             } (keys(%$userlist));
                   3010:     }
1.4       raeburn  3011:     my $rowcount = 0;
1.178     raeburn  3012:     my $disabled;
                   3013:     if ($mode eq 'autoenroll') {
                   3014:         unless ($permission->{'cusr'}) {
                   3015:             $disabled = ' disabled="disabled"';
                   3016:         }
                   3017:     }
1.2       raeburn  3018:     foreach my $user (@sorted_users) {
1.4       raeburn  3019:         my %in;
1.2       raeburn  3020:         my $sdata = $userlist->{$user};
1.4       raeburn  3021:         $rowcount ++; 
1.2       raeburn  3022:         foreach my $item (@{$keylist}) {
                   3023:             $in{$item} = $sdata->[$index{$item}];
                   3024:         }
1.67      droeschl 3025:         my $clickers = (&Apache::lonnet::userenvironment($in{'domain'},$in{'username'},'clickers'))[1];
                   3026:         if ($clickers!~/\w/) { $clickers='-'; }
1.159     raeburn  3027:         $in{'clicker'} = $clickers;
1.67      droeschl 3028: 	my $role = $in{'role'};
1.102     raeburn  3029:         $in{'role'}=&Apache::lonnet::plaintext($sdata->[$index{'role'}],$crstype);
1.136     raeburn  3030:         unless ($mode eq 'excel') {
                   3031:             if (! defined($in{'start'}) || $in{'start'} == 0) {
                   3032:                 $in{'start'} = &mt('none');
                   3033:             } else {
                   3034:                 $in{'start'} = &Apache::lonlocal::locallocaltime($in{'start'});
                   3035:             }
                   3036:             if (! defined($in{'end'}) || $in{'end'} == 0) {
                   3037:                 $in{'end'} = &mt('none');
                   3038:             } else {
                   3039:                 $in{'end'} = &Apache::lonlocal::locallocaltime($in{'end'});
                   3040:             }
1.1       raeburn  3041:         }
1.139     raeburn  3042:         if ($context eq 'course') {
                   3043:             my $lastlogin = $crslogins{$in{'username'}.':'.$in{'domain'}.':'.$in{'section'}.':'.$role};
                   3044:             if ($lastlogin ne '') {
                   3045:                 $in{'lastlogin'} = &Apache::lonlocal::locallocaltime($lastlogin);
                   3046:             }
                   3047:         }
1.55      raeburn  3048:         if ($mode eq 'view' || $mode eq 'html' || $mode eq 'autoenroll' || $mode eq 'pickauthor') {
1.2       raeburn  3049:             $r->print(&Apache::loncommon::start_data_table_row());
1.11      raeburn  3050:             my $checkval;
1.16      raeburn  3051:             if ($mode eq 'autoenroll') {
                   3052:                 my $cellentry;
                   3053:                 if ($in{'type'} eq 'auto') {
1.178     raeburn  3054:                     $cellentry = '<b>'.&mt('auto').'</b>&nbsp;<label><input type="checkbox" name="chgauto" value="'.$in{'username'}.':'.$in{'domain'}.'"'.$disabled.' />&nbsp;'.&mt('Change').'</label>';
1.16      raeburn  3055:                     $autocount ++;
                   3056:                 } else {
1.178     raeburn  3057:                     $cellentry = '<table border="0" cellspacing="0"><tr><td rowspan="2"><b>'.&mt('manual').'</b></td><td><span class="LC_nobreak"><label><input type="checkbox" name="chgmanual" value="'.$in{'username'}.':'.$in{'domain'}.'"'.$disabled.' />&nbsp;'.&mt('Change').'</label></span></td></tr><tr><td><span class="LC_nobreak">';
1.16      raeburn  3058:                     $manualcount ++;
                   3059:                     if ($in{'lockedtype'}) {
1.178     raeburn  3060:                         $cellentry .= '<label><input type="checkbox" name="unlockchg" value="'.$in{'username'}.':'.$in{'domain'}.'"'.$disabled.' />&nbsp;'.&mt('Unlock').'</label>';
1.16      raeburn  3061:                         $unlockcount ++;
                   3062:                     } else {
1.178     raeburn  3063:                         $cellentry .= '<label><input type="checkbox" name="lockchg" value="'.$in{'username'}.':'.$in{'domain'}.'"'.$disabled.' />&nbsp;'.&mt('Lock').'</label>';
1.16      raeburn  3064:                         $lockcount ++;
1.11      raeburn  3065:                     }
1.76      bisitz   3066:                     $cellentry .= '</span></td></tr></table>';
1.16      raeburn  3067:                 }
                   3068:                 $r->print("<td>$cellentry</td>\n");
                   3069:             } else {
1.55      raeburn  3070:                 if ($mode ne 'pickauthor') {  
                   3071:                     $r->print("<td>$rowcount</td>\n");
                   3072:                 }
1.16      raeburn  3073:                 if ($actionselect) {
1.26      raeburn  3074:                     my $showcheckbox;
                   3075:                     if ($role =~ /^cr\//) {
                   3076:                         $showcheckbox = $canchange{'cr'};
                   3077:                     } else {
                   3078:                         $showcheckbox = $canchange{$role};
                   3079:                     }
                   3080:                     if (!$showcheckbox) {
                   3081:                         if ($context eq 'course') {
                   3082:                             if ($canchangesec{$role} ne '') {
                   3083:                                 if ($canchangesec{$role} eq $in{'section'}) {
                   3084:                                     $showcheckbox = 1;
                   3085:                                 }
                   3086:                             }
1.16      raeburn  3087:                         }
1.26      raeburn  3088:                     }
                   3089:                     if ($showcheckbox) {
                   3090:                         $checkval = $user; 
                   3091:                         if ($context eq 'course') {
1.141     raeburn  3092:                             if (($role eq 'co' || $role eq 'cc') &&
                   3093:                                 ($user =~ /^\Q$env{'user.name'}:$env{'user.domain'}:$role\E/)) {
                   3094:                                 $showcheckbox = 0;
                   3095:                             } else {
                   3096:                                 if ($role eq 'st') {
                   3097:                                     $checkval .= ':st';
                   3098:                                 }
                   3099:                                 $checkval .= ':'.$in{'section'};
                   3100:                                 if ($role eq 'st') {
                   3101:                                     $checkval .= ':'.$in{'type'}.':'.
1.150     raeburn  3102:                                                  $in{'lockedtype'}.':'.
1.174     raeburn  3103:                                                  $in{'credits'}.':'.
                   3104:                                                  &escape($in{'instsec'});
1.141     raeburn  3105:                                 }
                   3106:                              }
                   3107:                         }
                   3108:                         if ($showcheckbox) {
                   3109:                             $r->print('<td><input type="checkbox" name="'.
1.183     raeburn  3110:                                       'actionlist" value="'.
                   3111:                                       &HTML::Entities::encode($checkval,'&<>"').'" />');
                   3112:                             foreach my $item ('start','end') {
                   3113:                                 $r->print('<input type="hidden" name="'.
                   3114:                                           &HTML::Entities::encode($checkval.'_'.$item,'&<>"').'"'.
                   3115:                                           ' value="'.$sdata->[$index{$item}].'" />');
                   3116:                             }
                   3117:                             $r->print('</td>');
1.141     raeburn  3118:                         } else {
                   3119:                             $r->print('<td>&nbsp;</td>');
1.16      raeburn  3120:                         }
1.26      raeburn  3121:                     } else {
                   3122:                         $r->print('<td>&nbsp;</td>');
1.16      raeburn  3123:                     }
1.55      raeburn  3124:                 } elsif ($mode eq 'pickauthor') {
                   3125:                         $r->print('<td><input type="button" name="chooseauthor" onclick="javascript:gochoose('."'$in{'username'}'".');" value="'.&mt('Select').'" /></td>');
1.11      raeburn  3126:                 }
                   3127:             }
1.2       raeburn  3128:             foreach my $item (@cols) {
1.10      raeburn  3129:                 if ($item eq 'username') {
1.48      raeburn  3130:                     $r->print('<td>'.&print_username_link($mode,\%in).'</td>');
1.83      raeburn  3131:                 } elsif ($item eq 'status') {
                   3132:                     my $showitem = $in{$item};
                   3133:                     if (defined($ltstatus{$in{$item}})) {
                   3134:                         $showitem = $ltstatus{$in{$item}};
                   3135:                     }
                   3136:                     $r->print('<td>'.$showitem.'</td>'."\n");
1.140     raeburn  3137:                 } elsif ($item eq 'photo') {
                   3138:                      if (($context eq 'course') && ($mode ne 'autoenroll') && 
                   3139:                          ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'})) { 
                   3140:                          if ($role eq 'st') {
                   3141:                              $r->print('<td align="right"><a href="javascript:photowindow('."'".$in{'photo'}."'".')"><img src="'.$in{'thumbnail'}.'" border="1" alt="" /></a></td>');
                   3142:                          } else {
                   3143:                              $r->print('<td>&nbsp;</td>');
                   3144:                          }
                   3145:                      }
                   3146:                 } elsif ($item eq 'clicker') {
                   3147:                     if (($context eq 'course') && ($mode ne 'autoenroll')) {
                   3148:                         if ($env{'form.showrole'} eq 'st' || $env{'form.showrole'} eq 'Any') {
                   3149:                             my $clickers =
                   3150:                    (&Apache::lonnet::userenvironment($in{'domain'},$in{'username'},'clickers'))[1];
                   3151:                             if ($clickers!~/\w/) { $clickers='-'; }
                   3152:                             $r->print('<td>'.$clickers.'</td>');
                   3153:                         } else {
                   3154:                              $r->print('<td>&nbsp;</td>'."\n");
                   3155:                         } 
1.149     raeburn  3156:                     }
1.159     raeburn  3157:                 } elsif (($item eq 'authorquota') || ($item eq 'authorusage')) {
                   3158:                     $r->print('<td align="right">'.$in{$item}.'</td>'."\n");
1.10      raeburn  3159:                 } else {
                   3160:                     $r->print('<td>'.$in{$item}.'</td>'."\n");
                   3161:                 }
1.2       raeburn  3162:             }
                   3163:             $r->print(&Apache::loncommon::end_data_table_row());
                   3164:         } elsif ($mode eq 'csv') {
                   3165:             next if (! defined($CSVfile));
                   3166:             # no need to bother with $linkto
                   3167:             my @line = ();
                   3168:             foreach my $item (@cols) {
                   3169:                 push @line,&Apache::loncommon::csv_translate($in{$item});
                   3170:             }
1.67      droeschl 3171:             print $CSVfile '"'.join('","',@line)."\"\n";
1.2       raeburn  3172:         } elsif ($mode eq 'excel') {
                   3173:             my $col = 0;
                   3174:             foreach my $item (@cols) {
                   3175:                 if ($item eq 'start' || $item eq 'end') {
1.136     raeburn  3176:                     if ((defined($in{$item})) && ($in{$item} != 0)) {
1.2       raeburn  3177:                         $excel_sheet->write($row,$col++,
1.136     raeburn  3178:                             &Apache::lonstathelpers::calc_serial($in{$item}),
1.2       raeburn  3179:                                     $format->{'date'});
                   3180:                     } else {
                   3181:                         $excel_sheet->write($row,$col++,'none');
                   3182:                     }
                   3183:                 } else {
                   3184:                     $excel_sheet->write($row,$col++,$in{$item});
                   3185:                 }
                   3186:             }
                   3187:             $row++;
1.1       raeburn  3188:         }
                   3189:     }
1.55      raeburn  3190:     if ($mode eq 'view' || $mode eq 'html' || $mode eq 'autoenroll' || $mode eq 'pickauthor') {
1.2       raeburn  3191:             $r->print(&Apache::loncommon::end_data_table().'<br />');
                   3192:     } elsif ($mode eq 'excel') {
                   3193:         $excel_workbook->close();
1.162     bisitz   3194: 	$r->print('<p>'.&mt('[_1]Your Excel spreadsheet[_2] is ready for download.', '<a href="'.$excel_filename.'">','</a>')."</p>\n");
1.2       raeburn  3195:     } elsif ($mode eq 'csv') {
                   3196:         close($CSVfile);
1.162     bisitz   3197: 	$r->print('<p>'.&mt('[_1]Your CSV file[_2] is ready for download.', '<a href="'.$CSVfilename.'">','</a>')."</p>\n");
1.2       raeburn  3198:         $r->rflush();
                   3199:     }
                   3200:     if ($mode eq 'autoenroll') {
                   3201:         return ($usercount,$autocount,$manualcount,$lockcount,$unlockcount);
1.4       raeburn  3202:     } else {
                   3203:         return ($usercount);
1.2       raeburn  3204:     }
1.1       raeburn  3205: }
                   3206: 
1.56      raeburn  3207: sub bulkaction_javascript {
                   3208:     my ($formname,$caller) = @_;
                   3209:     my $docstart = 'document';
                   3210:     if ($caller eq 'popup') {
                   3211:         $docstart = 'opener.document';
                   3212:     }
                   3213:     my %lt = &Apache::lonlocal::texthash(
                   3214:               acwi => 'Access will be set to start immediately',
                   3215:               asyo => 'as you did not select an end date in the pop-up window',
                   3216:               accw => 'Access will be set to continue indefinitely',
                   3217:               asyd => 'as you did not select an end date in the pop-up window',
                   3218:               sewi => "Sections will be switched to 'No section'",
                   3219:               ayes => "as you either selected the 'No section' option",
                   3220:               oryo => 'or you did not select a section in the pop-up window',
                   3221:               arol => 'A role with no section will be added',
                   3222:               swbs => 'Sections will be switched to:',
                   3223:               rwba => 'Roles will be added for section(s):',
                   3224:             );
                   3225:     my $alert = &mt("You must select at least one user by checking a user's 'Select' checkbox");
                   3226:     my $noaction = &mt("You need to select an action to take for the user(s) you have selected"); 
                   3227:     my $singconfirm = &mt(' for a single user?');
                   3228:     my $multconfirm = &mt(' for multiple users?');
1.170     damieng  3229:     &js_escape(\$alert);
                   3230:     &js_escape(\$noaction);
                   3231:     &js_escape(\$singconfirm);
                   3232:     &js_escape(\$multconfirm);
1.56      raeburn  3233:     my $output = <<"ENDJS";
                   3234: function verify_action (field) {
                   3235:     var numchecked = 0;
                   3236:     var singconf = '$singconfirm';
                   3237:     var multconf = '$multconfirm';
                   3238:     if ($docstart.$formname.elements[field].length > 0) {
                   3239:         for (i=0; i<$docstart.$formname.elements[field].length; i++) {
                   3240:             if ($docstart.$formname.elements[field][i].checked == true) {
                   3241:                numchecked ++;
                   3242:             }
                   3243:         }
                   3244:     } else {
                   3245:         if ($docstart.$formname.elements[field].checked == true) {
                   3246:             numchecked ++;
                   3247:         }
                   3248:     }
                   3249:     if (numchecked == 0) {
                   3250:         alert("$alert");
                   3251:         return;
                   3252:     } else {
                   3253:         var message = $docstart.$formname.bulkaction[$docstart.$formname.bulkaction.selectedIndex].text;
                   3254:         var choice = $docstart.$formname.bulkaction[$docstart.$formname.bulkaction.selectedIndex].value;
                   3255:         if (choice == '') {
                   3256:             alert("$noaction");
                   3257:             return;
                   3258:         } else {
                   3259:             if (numchecked == 1) {
                   3260:                 message += singconf;
                   3261:             } else {
                   3262:                 message += multconf;
                   3263:             }
                   3264: ENDJS
                   3265:     if ($caller ne 'popup') {
                   3266:         $output .= <<"NEWWIN";
                   3267:             if (choice == 'chgdates' || choice == 'reenable' || choice == 'activate' || choice == 'chgsec') {
                   3268:                 opendatebrowser(document.$formname,'$formname','go');
                   3269:                 return;
                   3270: 
                   3271:             } else {
                   3272:                 if (confirm(message)) {
                   3273:                     document.$formname.phase.value = 'bulkchange';
                   3274:                     document.$formname.submit();
                   3275:                     return;
                   3276:                 }
                   3277:             }
                   3278: NEWWIN
                   3279:     } else {
                   3280:         $output .= <<"POPUP";
                   3281:             if (choice == 'chgdates' || choice == 'reenable' || choice == 'activate') {
                   3282:                 var datemsg = '';
                   3283:                 if (($docstart.$formname.startdate_month.value == '') &&
                   3284:                     ($docstart.$formname.startdate_day.value  == '') &&
                   3285:                     ($docstart.$formname.startdate_year.value == '')) {
                   3286:                     datemsg = "\\n$lt{'acwi'},\\n$lt{'asyo'}.\\n";
                   3287:                 }
                   3288:                 if (($docstart.$formname.enddate_month.value == '') &&
                   3289:                     ($docstart.$formname.enddate_day.value  == '') &&
                   3290:                     ($docstart.$formname.enddate_year.value == '')) {
                   3291:                     datemsg += "\\n$lt{'accw'},\\n$lt{'asyd'}.\\n";
                   3292:                 }
                   3293:                 if (datemsg != '') {
                   3294:                     message += "\\n"+datemsg;
                   3295:                 }
                   3296:             }
                   3297:             if (choice == 'chgsec') {
                   3298:                 var rolefilter = $docstart.$formname.showrole.options[$docstart.$formname.showrole.selectedIndex].value;
                   3299:                 var retained =  $docstart.$formname.retainsec.value;
                   3300:                 var secshow = $docstart.$formname.newsecs.value;
                   3301:                 if (secshow == '') {
                   3302:                     if (rolefilter == 'st' || retained == 0 || retained == "") {
                   3303:                         message += "\\n\\n$lt{'sewi'},\\n$lt{'ayes'},\\n$lt{'oryo'}.\\n";
                   3304:                     } else {
                   3305:                         message += "\\n\\n$lt{'arol'}\\n$lt{'ayes'},\\n$lt{'oryo'}.\\n";
                   3306:                     }
                   3307:                 } else {
                   3308:                     if (rolefilter == 'st' || retained == 0 || retained == "") {
                   3309:                         message += "\\n\\n$lt{'swbs'} "+secshow+".\\n";
                   3310:                     } else {
                   3311:                         message += "\\n\\n$lt{'rwba'} "+secshow+".\\n";
                   3312:                     }
                   3313:                 }
                   3314:             }
                   3315:             if (confirm(message)) {
                   3316:                 $docstart.$formname.phase.value = 'bulkchange';
                   3317:                 $docstart.$formname.submit();
                   3318:                 window.close();
                   3319:             }
                   3320: POPUP
                   3321:     }
                   3322:     $output .= '
                   3323:         }
                   3324:     }
                   3325: }
                   3326: ';
                   3327:     return $output;
                   3328: }
                   3329: 
1.10      raeburn  3330: sub print_username_link {
1.48      raeburn  3331:     my ($mode,$in) = @_;
1.10      raeburn  3332:     my $output;
1.16      raeburn  3333:     if ($mode eq 'autoenroll') {
                   3334:         $output = $in->{'username'};
1.10      raeburn  3335:     } else {
                   3336:         $output = '<a href="javascript:username_display_launch('.
1.112     bisitz   3337:                   "'$in->{'username'}','$in->{'domain'}'".')">'.
1.10      raeburn  3338:                   $in->{'username'}.'</a>';
                   3339:     }
                   3340:     return $output;
                   3341: }
                   3342: 
1.2       raeburn  3343: sub role_type_names {
                   3344:     my %lt = &Apache::lonlocal::texthash (
1.13      raeburn  3345:                          'domain' => 'Domain Roles',
                   3346:                          'author' => 'Co-Author Roles',
                   3347:                          'course' => 'Course Roles',
1.101     raeburn  3348:                          'community' => 'Community Roles',
1.2       raeburn  3349:              );
                   3350:     return %lt;
                   3351: }
                   3352: 
1.11      raeburn  3353: sub select_actions {
1.55      raeburn  3354:     my ($context,$setting,$statusmode,$formname) = @_;
1.11      raeburn  3355:     my %lt = &Apache::lonlocal::texthash(
                   3356:                 revoke   => "Revoke user roles",
                   3357:                 delete   => "Delete user roles",
                   3358:                 reenable => "Re-enable expired user roles",
                   3359:                 activate => "Make future user roles active now",
                   3360:                 chgdates  => "Change starting/ending dates",
                   3361:                 chgsec   => "Change section associated with user roles",
                   3362:     );
1.150     raeburn  3363:     # FIXME Add an option to change credits for student roles.
1.11      raeburn  3364:     my ($output,$options,%choices);
1.23      raeburn  3365:     # FIXME Disable actions for now for roletype=course in domain context
                   3366:     if ($context eq 'domain' && $setting eq 'course') {
                   3367:         return;
                   3368:     }
1.26      raeburn  3369:     if ($context eq 'course') {
                   3370:         if ($env{'form.showrole'} ne 'Any') {
1.141     raeburn  3371:             my $showactions;
                   3372:             if (&Apache::lonnet::allowed('c'.$env{'form.showrole'},
                   3373:                                           $env{'request.course.id'})) {
                   3374:                 $showactions = 1;  
                   3375:             } elsif ($env{'request.course.sec'} ne '') {
                   3376:                 if (&Apache::lonnet::allowed('c'.$env{'form.showrole'},$env{'request.course.id'}.'/'.$env{'request.course.sec'})) {
                   3377:                     $showactions = 1;
                   3378:                 }
                   3379:             }
                   3380:             unless ($showactions) {
                   3381:                 unless (&is_courseowner($env{'request.course.id'},
                   3382:                                        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'})) {
                   3383:                     return; 
                   3384:                 }
1.26      raeburn  3385:             }
                   3386:         }
                   3387:     }
1.11      raeburn  3388:     if ($statusmode eq 'Any') {
                   3389:         $options .= '
                   3390: <option value="chgdates">'.$lt{'chgdates'}.'</option>';
                   3391:         $choices{'dates'} = 1;
                   3392:     } else {
                   3393:         if ($statusmode eq 'Future') {
                   3394:             $options .= '
                   3395: <option value="activate">'.$lt{'activate'}.'</option>';
                   3396:             $choices{'dates'} = 1;
                   3397:         } elsif ($statusmode eq 'Expired') {
                   3398:             $options .= '
                   3399: <option value="reenable">'.$lt{'reenable'}.'</option>';
                   3400:             $choices{'dates'} = 1;
                   3401:         }
1.13      raeburn  3402:         if ($statusmode eq 'Active' || $statusmode eq 'Future') {
                   3403:             $options .= '
                   3404: <option value="chgdates">'.$lt{'chgdates'}.'</option>
                   3405: <option value="revoke">'.$lt{'revoke'}.'</option>';
                   3406:             $choices{'dates'} = 1;
                   3407:         }
1.11      raeburn  3408:     }
                   3409:     if ($context eq 'domain') {
                   3410:         $options .= '
                   3411: <option value="delete">'.$lt{'delete'}.'</option>';
                   3412:     }
                   3413:     if (($context eq 'course') || ($context eq 'domain' && $setting eq 'course')) {
1.26      raeburn  3414:         if (($statusmode ne 'Expired') && ($env{'request.course.sec'} eq '')) {
1.11      raeburn  3415:             $options .= '
                   3416: <option value="chgsec">'.$lt{'chgsec'}.'</option>';
                   3417:             $choices{'sections'} = 1;
                   3418:         }
                   3419:     }
                   3420:     if ($options) {
1.56      raeburn  3421:         $output = '<select name="bulkaction">'."\n".
1.11      raeburn  3422:                   '<option value="" selected="selected">'.
                   3423:                   &mt('Please select').'</option>'."\n".$options."\n".'</select>';
                   3424:         if ($choices{'dates'}) {
                   3425:             $output .= 
                   3426:                 '<input type="hidden" name="startdate_month" value="" />'."\n".
                   3427:                 '<input type="hidden" name="startdate_day" value="" />'."\n".
                   3428:                 '<input type="hidden" name="startdate_year" value="" />'."\n".
                   3429:                 '<input type="hidden" name="startdate_hour" value="" />'."\n".
                   3430:                 '<input type="hidden" name="startdate_minute" value="" />'."\n".
                   3431:                 '<input type="hidden" name="startdate_second" value="" />'."\n".
                   3432:                 '<input type="hidden" name="enddate_month" value="" />'."\n".
                   3433:                 '<input type="hidden" name="enddate_day" value="" />'."\n".
                   3434:                 '<input type="hidden" name="enddate_year" value="" />'."\n".
                   3435:                 '<input type="hidden" name="enddate_hour" value="" />'."\n".
                   3436:                 '<input type="hidden" name="enddate_minute" value="" />'."\n".
1.56      raeburn  3437:                 '<input type="hidden" name="enddate_second" value="" />'."\n".
                   3438:                 '<input type="hidden" name="no_end_date" value="" />'."\n";
1.11      raeburn  3439:             if ($context eq 'course') {
                   3440:                 $output .= '<input type="hidden" name="makedatesdefault" value="" />'."\n";
                   3441:             }
                   3442:         }
                   3443:         if ($choices{'sections'}) {
1.91      bisitz   3444:             $output .= '<input type="hidden" name="retainsec" value="" />'."\n".
                   3445:                        '<input type="hidden" name="newsecs" value="" />'."\n";
1.11      raeburn  3446:         }
                   3447:     }
                   3448:     return $output;
                   3449: }
                   3450: 
                   3451: sub date_section_javascript {
                   3452:     my ($context,$setting) = @_;
1.49      raeburn  3453:     my $title = 'Date_And_Section_Selector';
1.41      raeburn  3454:     my %nopopup = &Apache::lonlocal::texthash (
                   3455:         revoke => "Check the boxes for any users for whom roles are to be revoked, and click 'Proceed'",
                   3456:         delete => "Check the boxes for any users for whom roles are to be deleted, and click 'Proceed'",
                   3457:         none   => "Choose an action to take for selected users",
                   3458:     );  
1.96      bisitz   3459:     my $output = <<"ENDONE";
                   3460: <script type="text/javascript">
                   3461: // <![CDATA[
1.41      raeburn  3462:     function opendatebrowser(callingform,formname,calledby) {
1.11      raeburn  3463:         var bulkaction = callingform.bulkaction.options[callingform.bulkaction.selectedIndex].value;
                   3464:         var url = '/adm/createuser?';
                   3465:         var type = '';
                   3466:         var showrole = callingform.showrole.options[callingform.showrole.selectedIndex].value;
                   3467: ENDONE
                   3468:     if ($context eq 'domain') {
                   3469:         $output .= '
                   3470:         type = callingform.roletype.options[callingform.roletype.selectedIndex].value;
                   3471: ';
                   3472:     }
                   3473:     my $width= '700';
                   3474:     my $height = '400';
                   3475:     $output .= <<"ENDTWO";
                   3476:         url += 'action=dateselect&callingform=' + formname + 
                   3477:                '&roletype='+type+'&showrole='+showrole +'&bulkaction='+bulkaction;
                   3478:         var title = '$title';
                   3479:         var options = 'scrollbars=1,resizable=1,menubar=0';
                   3480:         options += ',width=$width,height=$height';
                   3481:         stdeditbrowser = open(url,title,options,'1');
                   3482:         stdeditbrowser.focus();
                   3483:     }
1.96      bisitz   3484: // ]]>
1.11      raeburn  3485: </script>
                   3486: ENDTWO
                   3487:     return $output;
                   3488: }
                   3489: 
                   3490: sub date_section_selector {
1.150     raeburn  3491:     my ($context,$permission,$crstype,$showcredits) = @_;
1.11      raeburn  3492:     my $callingform = $env{'form.callingform'};
                   3493:     my $formname = 'dateselect';  
                   3494:     my $groupslist = &get_groupslist();
1.150     raeburn  3495:     my $sec_js =
                   3496:         &setsections_javascript($formname,$groupslist,undef,undef,$crstype,
                   3497:                                 $showcredits);
1.11      raeburn  3498:     my $output = <<"END";
                   3499: <script type="text/javascript">
1.96      bisitz   3500: // <![CDATA[
1.11      raeburn  3501: 
                   3502: $sec_js
                   3503: 
                   3504: function saveselections(formname) {
                   3505: 
                   3506: END
                   3507:     if ($env{'form.bulkaction'} eq 'chgsec') {
                   3508:         $output .= <<"END";
1.40      raeburn  3509:         if (formname.retainsec.length > 1) {  
                   3510:             for (var i=0; i<formname.retainsec.length; i++) {
                   3511:                 if (formname.retainsec[i].checked == true) {
                   3512:                     opener.document.$callingform.retainsec.value = formname.retainsec[i].value;
                   3513:                 }
                   3514:             }
                   3515:         } else {
                   3516:             opener.document.$callingform.retainsec.value = formname.retainsec.value;
                   3517:         }
1.103     raeburn  3518:         setSections(formname,'$crstype');
1.11      raeburn  3519:         if (seccheck == 'ok') {
                   3520:             opener.document.$callingform.newsecs.value = formname.sections.value;
                   3521:         }
                   3522: END
                   3523:     } else {
                   3524:         if ($context eq 'course') {
                   3525:             if (($env{'form.bulkaction'} eq 'reenable') || 
                   3526:                 ($env{'form.bulkaction'} eq 'activate') || 
                   3527:                 ($env{'form.bulkaction'} eq 'chgdates')) {
1.26      raeburn  3528:                 if ($env{'request.course.sec'} eq '') {
                   3529:                     $output .= <<"END";
1.11      raeburn  3530:  
                   3531:         if (formname.makedatesdefault.checked == true) {
                   3532:             opener.document.$callingform.makedatesdefault.value = 1;
                   3533:         }
                   3534:         else {
                   3535:             opener.document.$callingform.makedatesdefault.value = 0;
                   3536:         }
                   3537: 
                   3538: END
1.26      raeburn  3539:                 }
1.11      raeburn  3540:             }
                   3541:         }
                   3542:         $output .= <<"END";
                   3543:     opener.document.$callingform.startdate_month.value =  formname.startdate_month.options[formname.startdate_month.selectedIndex].value;
                   3544:     opener.document.$callingform.startdate_day.value =  formname.startdate_day.value;
                   3545:     opener.document.$callingform.startdate_year.value = formname.startdate_year.value;
                   3546:     opener.document.$callingform.startdate_hour.value =  formname.startdate_hour.options[formname.startdate_hour.selectedIndex].value;
                   3547:     opener.document.$callingform.startdate_minute.value =  formname.startdate_minute.value;
                   3548:     opener.document.$callingform.startdate_second.value = formname.startdate_second.value;
                   3549:     opener.document.$callingform.enddate_month.value =  formname.enddate_month.options[formname.enddate_month.selectedIndex].value;
                   3550:     opener.document.$callingform.enddate_day.value =  formname.enddate_day.value;
                   3551:     opener.document.$callingform.enddate_year.value = formname.enddate_year.value;
                   3552:     opener.document.$callingform.enddate_hour.value =  formname.enddate_hour.options[formname.enddate_hour.selectedIndex].value;
                   3553:     opener.document.$callingform.enddate_minute.value =  formname.enddate_minute.value;
                   3554:     opener.document.$callingform.enddate_second.value = formname.enddate_second.value;
1.56      raeburn  3555:     if (formname.no_end_date.checked) {
                   3556:         opener.document.$callingform.no_end_date.value = '1';
                   3557:     } else {
                   3558:         opener.document.$callingform.no_end_date.value = '0';
                   3559:     }
1.11      raeburn  3560: END
                   3561:     }
1.56      raeburn  3562:     my $verify_action_js = &bulkaction_javascript($callingform,'popup');
                   3563:     $output .= <<"ENDJS";
                   3564:     verify_action('actionlist');
1.11      raeburn  3565: }
1.56      raeburn  3566: 
                   3567: $verify_action_js
                   3568: 
1.96      bisitz   3569: // ]]>
1.11      raeburn  3570: </script>
1.56      raeburn  3571: ENDJS
1.11      raeburn  3572:     my %lt = &Apache::lonlocal::texthash (
                   3573:                  chac => 'Access dates to apply for selected users',
                   3574:                  chse => 'Changes in section affiliation to apply to selected users',
1.118     raeburn  3575:                  fors => 'For student roles, changing the section will result in a section switch as students may only be in one section of a course at a time.',
                   3576:                  forn => 'For a course role that is not "student", users may have roles in more than one section at a time.',
                   3577:                  reta => "Retain each user's current section affiliations?",
1.103     raeburn  3578:                  dnap => '(Does not apply to student roles).',
1.11      raeburn  3579:             );
                   3580:     my ($date_items,$headertext);
                   3581:     if ($env{'form.bulkaction'} eq 'chgsec') {
                   3582:         $headertext = $lt{'chse'};
                   3583:     } else {
                   3584:         $headertext = $lt{'chac'};
                   3585:         my $starttime;
                   3586:         if (($env{'form.bulkaction'} eq 'activate') || 
                   3587:             ($env{'form.bulkaction'} eq 'reenable')) {
                   3588:             $starttime = time;
                   3589:         }
                   3590:         $date_items = &date_setting_table($starttime,undef,$context,
1.21      raeburn  3591:                                           $env{'form.bulkaction'},$formname,
1.101     raeburn  3592:                                           $permission,$crstype);
1.11      raeburn  3593:     }
                   3594:     $output .= '<h3>'.$headertext.'</h3>'.
1.118     raeburn  3595:                '<form name="'.$formname.'" method="post" action="">'."\n".
1.11      raeburn  3596:                 $date_items;
                   3597:     if ($context eq 'course' && $env{'form.bulkaction'} eq 'chgsec') {
1.17      raeburn  3598:         my ($cnum,$cdom) = &get_course_identity();
1.103     raeburn  3599:         if ($crstype eq 'Community') {
1.118     raeburn  3600:             $lt{'fors'} = &mt('For member roles, changing the section will result in a section switch, as members may only be in one section of a community at a time.');
                   3601:             $lt{'forn'} = &mt('For a community role that is not "member", users may have roles in more than one section at a time.');
1.103     raeburn  3602:             $lt{'dnap'} = &mt('(Does not apply to member roles).'); 
                   3603:         }
1.11      raeburn  3604:         my $info;
                   3605:         if ($env{'form.showrole'} eq 'st') {
                   3606:             $output .= '<p>'.$lt{'fors'}.'</p>'; 
1.26      raeburn  3607:         } elsif ($env{'form.showrole'} eq 'Any') {
1.11      raeburn  3608:             $output .= '<p>'.$lt{'fors'}.'</p>'.
                   3609:                        '<p>'.$lt{'forn'}.'&nbsp;';
                   3610:             $info = $lt{'reta'};
                   3611:         } else {
                   3612:             $output .= '<p>'.$lt{'forn'}.'&nbsp;';
                   3613:             $info = $lt{'reta'};
                   3614:         }
                   3615:         if ($info) {
                   3616:             $info .= '<span class="LC_nobreak">'.
                   3617:                      '<label><input type="radio" name="retainsec" value="1" '.
                   3618:                      'checked="checked" />'.&mt('Yes').'</label>&nbsp;&nbsp;'.
                   3619:                      '<label><input type="radio" name="retainsec" value="0" />'.
                   3620:                      &mt('No').'</label></span>';
                   3621:             if ($env{'form.showrole'} eq 'Any') {
                   3622:                 $info .= '<br />'.$lt{'dnap'};
                   3623:             }
                   3624:             $info .= '</p>';
                   3625:         } else {
                   3626:             $info = '<input type="hidden" name="retainsec" value="0" />'; 
                   3627:         }
1.21      raeburn  3628:         my $rowtitle = &mt('New section to assign');
1.150     raeburn  3629:         my $secbox = &section_picker($cdom,$cnum,$env{'form.showrole'},$rowtitle,
                   3630:                                      $permission,$context,'chgsec',$crstype);
1.11      raeburn  3631:         $output .= $info.$secbox;
                   3632:     }
                   3633:     $output .= '<p>'.
1.81      schafran 3634: '<input type="button" name="dateselection" value="'.&mt('Save').'" onclick="javascript:saveselections(this.form)" /></p>'."\n".
1.11      raeburn  3635: '</form>';
                   3636:     return $output;
                   3637: }
                   3638: 
1.17      raeburn  3639: sub section_picker {
1.150     raeburn  3640:     my ($cdom,$cnum,$role,$rowtitle,$permission,$context,$mode,$crstype,
                   3641:         $showcredits,$credits) = @_;
1.17      raeburn  3642:     my %sections_count = &Apache::loncommon::get_sections($cdom,$cnum);
                   3643:     my $sections_select .= &course_sections(\%sections_count,$role);
1.118     raeburn  3644:     my $secbox = '<div>'.&Apache::lonhtmlcommon::start_pick_box()."\n";
1.17      raeburn  3645:     if ($mode eq 'upload') {
                   3646:         my ($options,$cb_script,$coursepick) =
1.150     raeburn  3647:             &default_role_selector($context,1,$crstype,$showcredits);
1.59      bisitz   3648:         $secbox .= &Apache::lonhtmlcommon::row_title(&mt('role'),'LC_oddrow_value').
1.17      raeburn  3649:                    $options. &Apache::lonhtmlcommon::row_closure(1)."\n";
                   3650:     }
                   3651:     $secbox .= &Apache::lonhtmlcommon::row_title($rowtitle,'LC_oddrow_value')."\n";
                   3652:     if ($env{'request.course.sec'} eq '') {
                   3653:         $secbox .= '<table class="LC_createuser"><tr class="LC_section_row">'."\n".
                   3654:                    '<td align="center">'.&mt('Existing sections')."\n".
                   3655:                    '<br />'.$sections_select.'</td><td align="center">'.
                   3656:                    &mt('New section').'<br />'."\n".
1.118     raeburn  3657:                    '<input type="text" name="newsec" size="15" value="" />'."\n".
1.17      raeburn  3658:                    '<input type="hidden" name="sections" value="" />'."\n".
                   3659:                    '</td></tr></table>'."\n";
                   3660:     } else {
1.149     raeburn  3661:         $secbox .= '<input type="hidden" name="sections" value="'.
1.17      raeburn  3662:                    $env{'request.course.sec'}.'" />'.
                   3663:                    $env{'request.course.sec'};
                   3664:     }
1.150     raeburn  3665:     $secbox .= &Apache::lonhtmlcommon::row_closure(1)."\n";
                   3666:     unless ($mode eq 'chgsec') {
                   3667:         if ($showcredits) {
                   3668:             $secbox .= 
                   3669:                 &Apache::lonhtmlcommon::row_title(&mt('credits (students)'),
                   3670:                                                   'LC_evenrow_value')."\n".
                   3671:                 '<input type="text" name="credits" size="3" value="'.$credits.'" />'."\n".
                   3672:                 &Apache::lonhtmlcommon::row_closure(1)."\n";
                   3673:         }
                   3674:     }
                   3675:     $secbox .= &Apache::lonhtmlcommon::end_pick_box().'</div>';
1.17      raeburn  3676:     return $secbox;
                   3677: }
                   3678: 
1.2       raeburn  3679: sub results_header_row {
1.102     raeburn  3680:     my ($rolefilter,$statusmode,$context,$permission,$mode,$crstype) = @_;
1.5       raeburn  3681:     my ($description,$showfilter);
                   3682:     if ($rolefilter ne 'Any') {
                   3683:         $showfilter = $rolefilter;
                   3684:     }
1.2       raeburn  3685:     if ($context eq 'course') {
1.24      raeburn  3686:         if ($mode eq 'csv' || $mode eq 'excel') {
1.102     raeburn  3687:             if ($crstype eq 'Community') {
                   3688:                 $description = &mt('Community - [_1]:',$env{'course.'.$env{'request.course.id'}.'.description'}).' ';
                   3689:             } else {
                   3690:                 $description = &mt('Course - [_1]:',$env{'course.'.$env{'request.course.id'}.'.description'}).' ';
                   3691:             }
1.24      raeburn  3692:         }
1.2       raeburn  3693:         if ($statusmode eq 'Expired') {
1.102     raeburn  3694:             if ($crstype eq 'Community') {
                   3695:                 $description .= &mt('Users in community with expired [_1] roles',$showfilter);
                   3696:             } else {
                   3697:                 $description .= &mt('Users in course with expired [_1] roles',$showfilter);
                   3698:             }
1.11      raeburn  3699:         } elsif ($statusmode eq 'Future') {
1.102     raeburn  3700:             if ($crstype eq 'Community') {
                   3701:                 $description .= &mt('Users in community with future [_1] roles',$showfilter);
                   3702:             } else {
                   3703:                 $description .= &mt('Users in course with future [_1] roles',$showfilter);
                   3704:             }
1.2       raeburn  3705:         } elsif ($statusmode eq 'Active') {
1.102     raeburn  3706:             if ($crstype eq 'Community') {
                   3707:                 $description .= &mt('Users in community with active [_1] roles',$showfilter);
                   3708:             } else {
                   3709:                 $description .= &mt('Users in course with active [_1] roles',$showfilter);
                   3710:             }
1.2       raeburn  3711:         } else {
                   3712:             if ($rolefilter eq 'Any') {
1.102     raeburn  3713:                 if ($crstype eq 'Community') {
                   3714:                     $description .= &mt('All users in community');
                   3715:                 } else {
                   3716:                     $description .= &mt('All users in course');
                   3717:                 }
1.2       raeburn  3718:             } else {
1.102     raeburn  3719:                 if ($crstype eq 'Community') {
                   3720:                     $description .= &mt('All users in community with [_1] roles',$rolefilter);
                   3721:                 } else {
                   3722:                     $description .= &mt('All users in course with [_1] roles',$rolefilter);
                   3723:                 }
1.2       raeburn  3724:             }
                   3725:         }
1.33      raeburn  3726:         my $constraint;
1.26      raeburn  3727:         my $viewablesec = &viewable_section($permission);
                   3728:         if ($viewablesec ne '') {
1.15      raeburn  3729:             if ($env{'form.showrole'} eq 'st') {
1.33      raeburn  3730:                 $constraint = &mt('only users in section "[_1]"',$viewablesec);
1.103     raeburn  3731:             } elsif (($env{'form.showrole'} ne 'cc') && ($env{'form.showrole'} ne 'co')) {
1.33      raeburn  3732:                 $constraint = &mt('only users affiliated with no section or section "[_1]"',$viewablesec);
                   3733:             }
                   3734:             if (($env{'form.grpfilter'} ne 'all') && ($env{'form.grpfilter'} ne '')) {
                   3735:                 if ($env{'form.grpfilter'} eq 'none') {
                   3736:                     $constraint .= &mt(' and not in any group');
                   3737:                 } else {
                   3738:                     $constraint .= &mt(' and members of group: "[_1]"',$env{'form.grpfilter'});
                   3739:                 }
                   3740:             }
                   3741:         } else {
                   3742:             if (($env{'form.secfilter'} ne 'all') && ($env{'form.secfilter'} ne '')) {
                   3743:                 if ($env{'form.secfilter'} eq 'none') {
                   3744:                     $constraint = &mt('only users affiliated with no section');
                   3745:                 } else {
                   3746:                     $constraint = &mt('only users affiliated with section "[_1]"',$env{'form.secfilter'});
                   3747:                 }
                   3748:             }
                   3749:             if (($env{'form.grpfilter'} ne 'all') && ($env{'form.grpfilter'} ne '')) {
                   3750:                 if ($env{'form.grpfilter'} eq 'none') {
                   3751:                     if ($constraint eq '') {
                   3752:                         $constraint = &mt('only users not in any group');
                   3753:                     } else {
                   3754:                         $constraint .= &mt(' and also not in any group'); 
                   3755:                     }
                   3756:                 } else {
                   3757:                     if ($constraint eq '') {
                   3758:                         $constraint = &mt('only members of group: "[_1]"',$env{'form.grpfilter'});
                   3759:                     } else {
                   3760:                         $constraint .= &mt(' and also members of group: "[_1]"'.$env{'form.grpfilter'});
                   3761:                     }
                   3762:                 }
1.15      raeburn  3763:             }
                   3764:         }
1.33      raeburn  3765:         if ($constraint ne '') {
                   3766:             $description .= ' ('.$constraint.')';
                   3767:         } 
1.13      raeburn  3768:     } elsif ($context eq 'author') {
1.14      raeburn  3769:         $description = 
1.73      bisitz   3770:             &mt('Author space for [_1]'
                   3771:                 ,'<span class="LC_cusr_emph">'
                   3772:                 .&Apache::loncommon::plainname($env{'user.name'},$env{'user.domain'})
                   3773:                 .'</span>')
                   3774:             .':&nbsp;&nbsp;';
1.2       raeburn  3775:         if ($statusmode eq 'Expired') {
1.5       raeburn  3776:             $description .= &mt('Co-authors with expired [_1] roles',$showfilter);
1.2       raeburn  3777:         } elsif ($statusmode eq 'Future') {
1.5       raeburn  3778:             $description .= &mt('Co-authors with future [_1] roles',$showfilter);
1.2       raeburn  3779:         } elsif ($statusmode eq 'Active') {
1.5       raeburn  3780:             $description .= &mt('Co-authors with active [_1] roles',$showfilter);
1.2       raeburn  3781:         } else {
                   3782:             if ($rolefilter eq 'Any') {
1.5       raeburn  3783:                 $description .= &mt('All co-authors');
1.2       raeburn  3784:             } else {
                   3785:                 $description .= &mt('All co-authors with [_1] roles',$rolefilter);
                   3786:             }
                   3787:         }
                   3788:     } elsif ($context eq 'domain') {
                   3789:         my $domdesc = &Apache::lonnet::domain($env{'request.role.domain'},'description');
1.73      bisitz   3790:         $description = &mt('Domain - [_1]:',$domdesc).' ';
1.2       raeburn  3791:         if ($env{'form.roletype'} eq 'domain') {
                   3792:             if ($statusmode eq 'Expired') {
1.5       raeburn  3793:                 $description .= &mt('Users in domain with expired [_1] roles',$showfilter);
1.2       raeburn  3794:             } elsif ($statusmode eq 'Future') {
1.5       raeburn  3795:                 $description .= &mt('Users in domain with future [_1] roles',$showfilter);
1.2       raeburn  3796:             } elsif ($statusmode eq 'Active') {
1.5       raeburn  3797:                 $description .= &mt('Users in domain with active [_1] roles',$showfilter);
1.2       raeburn  3798:             } else {
                   3799:                 if ($rolefilter eq 'Any') {
1.5       raeburn  3800:                     $description .= &mt('All users in domain');
1.2       raeburn  3801:                 } else {
                   3802:                     $description .= &mt('All users in domain with [_1] roles',$rolefilter);
                   3803:                 }
                   3804:             }
1.13      raeburn  3805:         } elsif ($env{'form.roletype'} eq 'author') {
1.2       raeburn  3806:             if ($statusmode eq 'Expired') {
1.5       raeburn  3807:                 $description .= &mt('Co-authors in domain with expired [_1] roles',$showfilter);
1.2       raeburn  3808:             } elsif ($statusmode eq 'Future') {
1.5       raeburn  3809:                 $description .= &mt('Co-authors in domain with future [_1] roles',$showfilter);
1.2       raeburn  3810:             } elsif ($statusmode eq 'Active') {
1.5       raeburn  3811:                $description .= &mt('Co-authors in domain with active [_1] roles',$showfilter);
1.2       raeburn  3812:             } else {
                   3813:                 if ($rolefilter eq 'Any') {
1.5       raeburn  3814:                     $description .= &mt('All users with co-author roles in domain',$showfilter);
1.2       raeburn  3815:                 } else {
1.116     bisitz   3816:                     $description .= &mt('All co-authors in domain with [_1] roles',$rolefilter);
1.2       raeburn  3817:                 }
                   3818:             }
1.102     raeburn  3819:         } elsif (($env{'form.roletype'} eq 'course') || 
                   3820:                  ($env{'form.roletype'} eq 'community')) {
1.2       raeburn  3821:             my $coursefilter = $env{'form.coursepick'};
1.102     raeburn  3822:             if ($env{'form.roletype'} eq 'course') {
                   3823:                 if ($coursefilter eq 'category') {
                   3824:                     my $instcode = &instcode_from_coursefilter();
                   3825:                     if ($instcode eq '.') {
                   3826:                         $description .= &mt('All courses in domain').' - ';
                   3827:                     } else {
                   3828:                         $description .= &mt('Courses in domain with institutional code: [_1]',$instcode).' - ';
                   3829:                     }
                   3830:                 } elsif ($coursefilter eq 'selected') {
                   3831:                     $description .= &mt('Selected courses in domain').' - ';
                   3832:                 } elsif ($coursefilter eq 'all') {
1.2       raeburn  3833:                     $description .= &mt('All courses in domain').' - ';
                   3834:                 }
1.102     raeburn  3835:             } elsif ($env{'form.roletype'} eq 'community') {
                   3836:                 if ($coursefilter eq 'selected') {
                   3837:                     $description .= &mt('Selected communities in domain').' - ';
                   3838:                 } elsif ($coursefilter eq 'all') {
                   3839:                     $description .= &mt('All communities in domain').' - ';
                   3840:                 }
1.2       raeburn  3841:             }
                   3842:             if ($statusmode eq 'Expired') {
1.5       raeburn  3843:                 $description .= &mt('users with expired [_1] roles',$showfilter);
1.2       raeburn  3844:             } elsif ($statusmode eq 'Future') {
1.5       raeburn  3845:                 $description .= &mt('users with future [_1] roles',$showfilter);
1.2       raeburn  3846:             } elsif ($statusmode eq 'Active') {
1.5       raeburn  3847:                 $description .= &mt('users with active [_1] roles',$showfilter);
1.2       raeburn  3848:             } else {
                   3849:                 if ($rolefilter eq 'Any') {
                   3850:                     $description .= &mt('all users');
                   3851:                 } else {
                   3852:                     $description .= &mt('users with [_1] roles',$rolefilter);
                   3853:                 }
                   3854:             }
                   3855:         }
                   3856:     }
                   3857:     return $description;
                   3858: }
1.22      raeburn  3859: 
                   3860: sub viewable_section {
                   3861:     my ($permission) = @_;
                   3862:     my $viewablesec;
                   3863:     if (ref($permission) eq 'HASH') {
                   3864:         if (exists($permission->{'view_section'})) {
                   3865:             $viewablesec = $permission->{'view_section'};
                   3866:         } elsif (exists($permission->{'cusr_section'})) {
                   3867:             $viewablesec = $permission->{'cusr_section'};
                   3868:         }
                   3869:     }
                   3870:     return $viewablesec;
                   3871: }
                   3872: 
1.2       raeburn  3873:     
1.1       raeburn  3874: #################################################
                   3875: #################################################
                   3876: sub show_drop_list {
1.101     raeburn  3877:     my ($r,$classlist,$nosort,$permission,$crstype) = @_;
1.29      raeburn  3878:     my $cid = $env{'request.course.id'};
1.17      raeburn  3879:     my ($cnum,$cdom) = &get_course_identity($cid);
1.1       raeburn  3880:     if (! exists($env{'form.sortby'})) {
                   3881:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   3882:                                                 ['sortby']);
                   3883:     }
                   3884:     my $sortby = $env{'form.sortby'};
                   3885:     if ($sortby !~ /^(username|domain|section|groups|fullname|id|start|end)$/) {
                   3886:         $sortby = 'username';
                   3887:     }
                   3888:     my $action = "drop";
1.17      raeburn  3889:     my $check_uncheck_js = &Apache::loncommon::check_uncheck_jscript();
1.1       raeburn  3890:     $r->print(<<END);
                   3891: <input type="hidden" name="sortby" value="$sortby" />
                   3892: <input type="hidden" name="action" value="$action" />
                   3893: <input type="hidden" name="state"  value="done" />
1.17      raeburn  3894: <script type="text/javascript" language="Javascript">
1.96      bisitz   3895: // <![CDATA[
1.17      raeburn  3896: $check_uncheck_js
1.96      bisitz   3897: // ]]>
1.1       raeburn  3898: </script>
1.86      bisitz   3899: <input type="hidden" name="phase" value="four" />
1.1       raeburn  3900: END
1.30      raeburn  3901:     my ($indexhash,$keylist) = &make_keylist_array();
                   3902:     my $studentcount = 0;
                   3903:     if (ref($classlist) eq 'HASH') {
                   3904:         foreach my $student (keys(%{$classlist})) {
                   3905:             my $sdata = $classlist->{$student}; 
                   3906:             my $status = $sdata->[$indexhash->{'status'}];
                   3907:             my $section = $sdata->[$indexhash->{'section'}];
                   3908:             if ($status ne 'Active') {
                   3909:                 delete($classlist->{$student});
                   3910:                 next;
                   3911:             }
                   3912:             if ($env{'request.course.sec'} ne '') {
                   3913:                 if ($section ne $env{'request.course.sec'}) {
                   3914:                     delete($classlist->{$student});
                   3915:                     next;
                   3916:                 }
                   3917:             }
                   3918:             $studentcount ++;
                   3919:         }
                   3920:     }
                   3921:     if (!$studentcount) {
1.143     bisitz   3922:        my $msg = '';
1.101     raeburn  3923:         if ($crstype eq 'Community') {
1.143     bisitz   3924:             $msg = &mt('There are no members to drop.');
1.101     raeburn  3925:         } else {
1.143     bisitz   3926:             $msg = &mt('There are no students to drop.');
1.101     raeburn  3927:         }
1.143     bisitz   3928:         $r->print('<p class="LC_info">'.$msg.'</p>');
1.30      raeburn  3929:         return;
                   3930:     }
                   3931:     my ($classgroups) = &Apache::loncoursedata::get_group_memberships(
                   3932:                                               $classlist,$keylist,$cdom,$cnum);
                   3933:     my %lt=&Apache::lonlocal::texthash('usrn'   => "username",
                   3934:                                        'dom'    => "domain",
1.162     bisitz   3935:                                        'id'     => "ID",
1.30      raeburn  3936:                                        'sn'     => "student name",
1.101     raeburn  3937:                                        'mn'     => "member name",
1.30      raeburn  3938:                                        'sec'    => "section",
                   3939:                                        'start'  => "start date",
                   3940:                                        'end'    => "end date",
                   3941:                                        'groups' => "active groups",
                   3942:                                       );
1.101     raeburn  3943:     my $nametitle = $lt{'sn'};
                   3944:     if ($crstype eq 'Community') {
                   3945:         $nametitle = $lt{'mn'};
                   3946:     }
1.1       raeburn  3947:     if ($nosort) {
1.17      raeburn  3948:         $r->print(&Apache::loncommon::start_data_table().
                   3949:                   &Apache::loncommon::start_data_table_header_row());
1.1       raeburn  3950:         $r->print(<<END);
                   3951:     <th>&nbsp;</th>
                   3952:     <th>$lt{'usrn'}</th>
                   3953:     <th>$lt{'dom'}</th>
1.162     bisitz   3954:     <th>$lt{'id'}</th>
1.101     raeburn  3955:     <th>$nametitle</th>
1.1       raeburn  3956:     <th>$lt{'sec'}</th>
                   3957:     <th>$lt{'start'}</th>
                   3958:     <th>$lt{'end'}</th>
                   3959:     <th>$lt{'groups'}</th>
                   3960: END
1.17      raeburn  3961:         $r->print(&Apache::loncommon::end_data_table_header_row());
1.1       raeburn  3962:     } else  {
1.17      raeburn  3963:         $r->print(&Apache::loncommon::start_data_table().
                   3964:                   &Apache::loncommon::start_data_table_header_row());
1.1       raeburn  3965:         $r->print(<<END);
1.17      raeburn  3966:     <th>&nbsp;</th>
1.1       raeburn  3967:     <th>
1.162     bisitz   3968:        <a href="/adm/createuser?action=$action&amp;sortby=username">$lt{'usrn'}</a>
1.1       raeburn  3969:     </th><th>
1.162     bisitz   3970:        <a href="/adm/createuser?action=$action&amp;sortby=domain">$lt{'dom'}</a>
1.1       raeburn  3971:     </th><th>
1.162     bisitz   3972:        <a href="/adm/createuser?action=$action&amp;sortby=id">$lt{'id'}</a>
1.1       raeburn  3973:     </th><th>
1.162     bisitz   3974:        <a href="/adm/createuser?action=$action&amp;sortby=fullname">$nametitle</a>
1.1       raeburn  3975:     </th><th>
1.162     bisitz   3976:        <a href="/adm/createuser?action=$action&amp;sortby=section">$lt{'sec'}</a>
1.1       raeburn  3977:     </th><th>
1.162     bisitz   3978:        <a href="/adm/createuser?action=$action&amp;sortby=start">$lt{'start'}</a>
1.1       raeburn  3979:     </th><th>
1.162     bisitz   3980:        <a href="/adm/createuser?action=$action&amp;sortby=end">$lt{'end'}</a>
1.1       raeburn  3981:     </th><th>
1.162     bisitz   3982:        <a href="/adm/createuser?action=$action&amp;sortby=groups">$lt{'groups'}</a>
1.1       raeburn  3983:     </th>
                   3984: END
1.17      raeburn  3985:         $r->print(&Apache::loncommon::end_data_table_header_row());
1.1       raeburn  3986:     }
                   3987:     #
                   3988:     # Sort the students
1.30      raeburn  3989:     my $index  = $indexhash->{$sortby};
                   3990:     my $second = $indexhash->{'username'};
                   3991:     my $third  = $indexhash->{'domain'};
1.1       raeburn  3992:     my @Sorted_Students = sort {
                   3993:         lc($classlist->{$a}->[$index])  cmp lc($classlist->{$b}->[$index])
                   3994:             ||
                   3995:         lc($classlist->{$a}->[$second]) cmp lc($classlist->{$b}->[$second])
                   3996:             ||
                   3997:         lc($classlist->{$a}->[$third]) cmp lc($classlist->{$b}->[$third])
1.30      raeburn  3998:         } (keys(%{$classlist}));
1.1       raeburn  3999:     foreach my $student (@Sorted_Students) {
                   4000:         my $error;
                   4001:         my $sdata = $classlist->{$student};
1.30      raeburn  4002:         my $username = $sdata->[$indexhash->{'username'}];
                   4003:         my $domain   = $sdata->[$indexhash->{'domain'}];
                   4004:         my $section  = $sdata->[$indexhash->{'section'}];
                   4005:         my $name     = $sdata->[$indexhash->{'fullname'}];
                   4006:         my $id       = $sdata->[$indexhash->{'id'}];
                   4007:         my $start    = $sdata->[$indexhash->{'start'}];
                   4008:         my $end      = $sdata->[$indexhash->{'end'}];
1.1       raeburn  4009:         my $groups = $classgroups->{$student};
                   4010:         my $active_groups;
                   4011:         if (ref($groups->{active}) eq 'HASH') {
                   4012:             $active_groups = join(', ',keys(%{$groups->{'active'}}));
                   4013:         }
                   4014:         if (! defined($start) || $start == 0) {
                   4015:             $start = &mt('none');
                   4016:         } else {
                   4017:             $start = &Apache::lonlocal::locallocaltime($start);
                   4018:         }
                   4019:         if (! defined($end) || $end == 0) {
                   4020:             $end = &mt('none');
                   4021:         } else {
                   4022:             $end = &Apache::lonlocal::locallocaltime($end);
                   4023:         }
1.17      raeburn  4024:         my $studentkey = $student.':'.$section;
1.30      raeburn  4025:         my $startitem = '<input type="hidden" name="'.$studentkey.'_start" value="'.$sdata->[$indexhash->{'start'}].'" />';
1.1       raeburn  4026:         #
                   4027:         $r->print(&Apache::loncommon::start_data_table_row());
                   4028:         $r->print(<<"END");
1.86      bisitz   4029:     <td><input type="checkbox" name="droplist" value="$studentkey" /></td>
1.1       raeburn  4030:     <td>$username</td>
                   4031:     <td>$domain</td>
                   4032:     <td>$id</td>
                   4033:     <td>$name</td>
                   4034:     <td>$section</td>
1.29      raeburn  4035:     <td>$start $startitem</td>
1.1       raeburn  4036:     <td>$end</td>
                   4037:     <td>$active_groups</td>
                   4038: END
                   4039:         $r->print(&Apache::loncommon::end_data_table_row());
                   4040:     }
                   4041:     $r->print(&Apache::loncommon::end_data_table().'<br />');
                   4042:     %lt=&Apache::lonlocal::texthash(
1.29      raeburn  4043:                        'dp'   => "Drop Students",
1.101     raeburn  4044:                        'dm'   => "Drop Members",
1.1       raeburn  4045:                        'ca'   => "check all",
                   4046:                        'ua'   => "uncheck all",
                   4047:                                        );
1.101     raeburn  4048:     my $btn = $lt{'dp'};
                   4049:     if ($crstype eq 'Community') {
                   4050:         $btn = $lt{'dm'}; 
                   4051:     }
1.1       raeburn  4052:     $r->print(<<"END");
1.89      bisitz   4053: <p>
1.86      bisitz   4054: <input type="button" value="$lt{'ca'}" onclick="javascript:checkAll(document.studentform.droplist)" /> &nbsp;
                   4055: <input type="button" value="$lt{'ua'}" onclick="javascript:uncheckAll(document.studentform.droplist)" />
1.89      bisitz   4056: </p>
                   4057: <p>
1.101     raeburn  4058: <input type="submit" value="$btn" />
1.89      bisitz   4059: </p>
1.1       raeburn  4060: END
                   4061:     return;
                   4062: }
                   4063: 
                   4064: #
                   4065: # Print out the initial form to get the file containing a list of users
                   4066: #
                   4067: sub print_first_users_upload_form {
                   4068:     my ($r,$context) = @_;
                   4069:     my $str;
1.86      bisitz   4070:     $str  = '<input type="hidden" name="phase" value="two" />';
1.1       raeburn  4071:     $str .= '<input type="hidden" name="action" value="upload" />';
1.101     raeburn  4072:     $str .= '<input type="hidden" name="state"  value="got_file" />';
1.95      bisitz   4073: 
1.147     bisitz   4074:     $str .= &Apache::grades::checkforfile_js();
                   4075: 
1.85      bisitz   4076:     $str .= '<h2>'.&mt('Upload a file containing information about users').'</h2>'."\n";
1.95      bisitz   4077: 
                   4078:     # Excel and CSV Help
1.147     bisitz   4079:     $str .= '<div class="LC_columnSection">'
1.95      bisitz   4080:            .&Apache::loncommon::help_open_topic("Course_Create_Class_List",
                   4081:                 &mt("How do I create a users list from a spreadsheet"))
1.147     bisitz   4082:            .' '.&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
1.95      bisitz   4083:                 &mt("How do I create a CSV file from a spreadsheet"))
1.147     bisitz   4084:            ."</div>\n";
1.95      bisitz   4085:     $str .= &Apache::lonhtmlcommon::start_pick_box()
1.103     raeburn  4086:            .&Apache::lonhtmlcommon::row_title(&mt('File'));
                   4087:     if (&Apache::lonlocal::current_language() ne 'en') {
                   4088:         if ($context eq 'course') { 
                   4089:             $str .= '<p class="LC_info">'."\n"
                   4090:                    .&mt('Please upload an UTF8 encoded file to ensure a correct character encoding in your classlist.')."\n"
                   4091:                    .'</p>'."\n";
                   4092:         }
                   4093:     }
                   4094:     $str .= &Apache::loncommon::upfile_select_html()
1.95      bisitz   4095:            .&Apache::lonhtmlcommon::row_closure()
                   4096:            .&Apache::lonhtmlcommon::row_title(
                   4097:                 '<label for="noFirstLine">'
                   4098:                .&mt('Ignore First Line')
                   4099:                .'</label>')
                   4100:            .'<input type="checkbox" name="noFirstLine" id="noFirstLine" />'
                   4101:            .&Apache::lonhtmlcommon::row_closure(1)
                   4102:            .&Apache::lonhtmlcommon::end_pick_box();
                   4103: 
                   4104:     $str .= '<p>'
1.147     bisitz   4105:            .'<input type="submit" name="fileupload" value="'.&mt('Next').'"'
                   4106:            .' onclick="javascript:checkUpload(this.form);" />'
1.95      bisitz   4107:            .'</p>';
                   4108: 
1.1       raeburn  4109:     $r->print($str);
                   4110:     return;
                   4111: }
                   4112: 
                   4113: # ================================================= Drop/Add from uploaded file
                   4114: sub upfile_drop_add {
1.150     raeburn  4115:     my ($r,$context,$permission,$showcredits) = @_;
1.1       raeburn  4116:     &Apache::loncommon::load_tmp_file($r);
                   4117:     my @userdata=&Apache::loncommon::upfile_record_sep();
                   4118:     if($env{'form.noFirstLine'}){shift(@userdata);}
                   4119:     my @keyfields = split(/\,/,$env{'form.keyfields'});
                   4120:     my %fields=();
                   4121:     for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
                   4122:         if ($env{'form.upfile_associate'} eq 'reverse') {
                   4123:             if ($env{'form.f'.$i} ne 'none') {
                   4124:                 $fields{$keyfields[$i]}=$env{'form.f'.$i};
                   4125:             }
                   4126:         } else {
                   4127:             $fields{$env{'form.f'.$i}}=$keyfields[$i];
                   4128:         }
                   4129:     }
1.29      raeburn  4130:     if ($env{'form.fullup'} ne 'yes') {
                   4131:         $r->print('<form name="studentform" method="post" action="/adm/createuser">'."\n".
                   4132:                   '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />');
                   4133:     }
1.1       raeburn  4134:     #
                   4135:     # Store the field choices away
1.150     raeburn  4136:     my @storefields = qw/username names fname mname lname gen id 
                   4137:                          sec ipwd email role domain inststatus/;
                   4138:     if ($showcredits) {
                   4139:         push (@storefields,'credits');
                   4140:     }
                   4141:     my %fieldstype; 
                   4142:     foreach my $field (@storefields) {
1.1       raeburn  4143:         $env{'form.'.$field.'_choice'}=$fields{$field};
1.150     raeburn  4144:         $fieldstype{$field.'_choice'} = 'scalar';
1.1       raeburn  4145:     }
1.150     raeburn  4146:     &Apache::loncommon::store_course_settings('enrollment_upload',\%fieldstype);
1.185   ! raeburn  4147:     my ($cid,$crstype,$setting,$crsdom);
1.101     raeburn  4148:     if ($context eq 'domain') {
                   4149:         $setting = $env{'form.roleaction'};
                   4150:     }
                   4151:     if ($env{'request.course.id'} ne '') {
                   4152:         $cid = $env{'request.course.id'};
                   4153:         $crstype = &Apache::loncommon::course_type();
1.185   ! raeburn  4154:         $crsdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
1.101     raeburn  4155:     } elsif ($setting eq 'course') {
                   4156:         if (&Apache::lonnet::is_course($env{'form.dcdomain'},$env{'form.dccourse'})) {
                   4157:             $cid = $env{'form.dcdomain'}.'_'.$env{'form.dccourse'};
                   4158:             $crstype = &Apache::loncommon::course_type($cid);
1.185   ! raeburn  4159:             $crsdom = $env{'form.dcdomain'};
1.101     raeburn  4160:         }
                   4161:     }
1.1       raeburn  4162:     my ($startdate,$enddate) = &get_dates_from_form();
                   4163:     if ($env{'form.makedatesdefault'}) {
1.101     raeburn  4164:         $r->print(&make_dates_default($startdate,$enddate,$context,$crstype));
1.1       raeburn  4165:     }
                   4166:     # Determine domain and desired host (home server)
1.57      raeburn  4167:     my $defdom=$env{'request.role.domain'};
                   4168:     my $domain;
                   4169:     if ($env{'form.defaultdomain'} ne '') {
1.185   ! raeburn  4170:         if (($context eq 'course') || ($setting eq 'course')) {
        !          4171:             unless ($env{'form.defaultdomain'} eq $crsdom) {
        !          4172:                 if (&Apache::lonnet::will_trust('enroll',$crsdom,$env{'form.defaultdomain'})) {
        !          4173:                     $domain = $env{'form.defaultdomain'};
        !          4174:                 } else {
        !          4175:                     $r->print('<span class="LC_error">'.&mt('Error').
        !          4176:                               &mt('Enrollment of users not permitted for specified default domain: [_1].',
        !          4177:                                   &Apache::lonnet::domain($env{'form.defaultdomain'},'description')).'</span>');
        !          4178:                     $r->print(&Apache::loncommon::end_page());
        !          4179:                 }
        !          4180:                 return;
        !          4181:             }
        !          4182:         } elsif ($context eq 'author') {
        !          4183:             unless ($env{'form.defaultdomain'} eq $defdom) {
        !          4184:                 if ((&Apache::lonnet::will_trust('othcoau',$defdom,$env{'form.defaultdomain'})) &&
        !          4185:                     (&Apache::lonnet::will_trust('coremau',$env{'form.defaultdomain'},$defdom))) {
        !          4186:                     $domain = $env{'form.defaultdomain'};
        !          4187:                 } else {
        !          4188:                     $r->print('<span class="LC_error">'.&mt('Error').
        !          4189:                               &mt('Addition of users not permitted for specified default domain: [_1].',
        !          4190:                                   &Apache::lonnet::domain($env{'form.defaultdomain'},'description')).'</span>');
        !          4191:                     $r->print(&Apache::loncommon::end_page());
        !          4192:                 }
        !          4193:                 return; 
        !          4194:             }
        !          4195:         } elsif (($context eq 'domain') && ($setting eq 'domain')) {
        !          4196:             unless ($env{'form.defaultdomain'} eq $defdom) {
        !          4197:                 if (&Apache::lonnet::will_trust('domroles',$defdom,$env{'form.defaultdomain'})) {
        !          4198:                     $domain = $env{'form.defaultdomain'};
        !          4199:                 } else {
        !          4200:                     $r->print('<span class="LC_error">'.&mt('Error').
        !          4201:                               &mt('Addition of users not permitted for specified default domain: [_1].',
        !          4202:                                   &Apache::lonnet::domain($env{'form.defaultdomain'},'description')).'</span>');
        !          4203:                     $r->print(&Apache::loncommon::end_page());
        !          4204:                 }
        !          4205:             }
        !          4206:         }
1.57      raeburn  4207:     } else {
                   4208:         $domain = $defdom;
                   4209:     }
1.1       raeburn  4210:     my $desiredhost = $env{'form.lcserver'};
                   4211:     if (lc($desiredhost) eq 'default') {
                   4212:         $desiredhost = undef;
                   4213:     } else {
1.57      raeburn  4214:         my %home_servers = &Apache::lonnet::get_servers($defdom,'library');
1.1       raeburn  4215:         if (! exists($home_servers{$desiredhost})) {
                   4216:             $r->print('<span class="LC_error">'.&mt('Error').
                   4217:                       &mt('Invalid home server specified').'</span>');
                   4218:             $r->print(&Apache::loncommon::end_page());
                   4219:             return;
                   4220:         }
                   4221:     }
                   4222:     # Determine authentication mechanism
                   4223:     my $changeauth;
                   4224:     if ($context eq 'domain') {
                   4225:         $changeauth = $env{'form.changeauth'};
                   4226:     }
                   4227:     my $amode  = '';
                   4228:     my $genpwd = '';
                   4229:     if ($env{'form.login'} eq 'krb') {
                   4230:         $amode='krb';
                   4231:         $amode.=$env{'form.krbver'};
                   4232:         $genpwd=$env{'form.krbarg'};
                   4233:     } elsif ($env{'form.login'} eq 'int') {
                   4234:         $amode='internal';
                   4235:         if ((defined($env{'form.intarg'})) && ($env{'form.intarg'})) {
                   4236:             $genpwd=$env{'form.intarg'};
                   4237:         }
                   4238:     } elsif ($env{'form.login'} eq 'loc') {
                   4239:         $amode='localauth';
                   4240:         if ((defined($env{'form.locarg'})) && ($env{'form.locarg'})) {
                   4241:             $genpwd=$env{'form.locarg'};
                   4242:         }
                   4243:     }
                   4244:     if ($amode =~ /^krb/) {
                   4245:         if (! defined($genpwd) || $genpwd eq '') {
                   4246:             $r->print('<span class="Error">'.
                   4247:                       &mt('Unable to enroll users').' '.
                   4248:                       &mt('No Kerberos domain was specified.').'</span></p>');
                   4249:             $amode = ''; # This causes the loop below to be skipped
                   4250:         }
                   4251:     }
1.150     raeburn  4252:     my ($defaultsec,$defaultrole,$defaultcredits,$commoncredits);
1.1       raeburn  4253:     if ($context eq 'domain') {
                   4254:         if ($setting eq 'domain') {
                   4255:             $defaultrole = $env{'form.defaultrole'};
                   4256:         } elsif ($setting eq 'course') {
                   4257:             $defaultrole = $env{'form.courserole'};
1.27      raeburn  4258:             $defaultsec = $env{'form.sections'};
1.150     raeburn  4259:             if ($showcredits) {
                   4260:                 $commoncredits = $env{'form.credits'};
                   4261:                 if ($crstype ne 'Community') {
                   4262:                     my %coursehash=&Apache::lonnet::coursedescription($cid);
                   4263:                     $defaultcredits = $coursehash{'internal.defaultcredits'};
                   4264:                 }
                   4265:             }
1.149     raeburn  4266:         }
1.13      raeburn  4267:     } elsif ($context eq 'author') {
1.1       raeburn  4268:         $defaultrole = $env{'form.defaultrole'};
1.27      raeburn  4269:     } elsif ($context eq 'course') {
                   4270:         $defaultrole = $env{'form.defaultrole'};
                   4271:         $defaultsec = $env{'form.sections'};
1.150     raeburn  4272:         if ($showcredits) {
                   4273:             $commoncredits = $env{'form.credits'};
                   4274:             $defaultcredits = $env{'course.'.$cid.'.internal.defaultcredits'};
                   4275:         }
1.1       raeburn  4276:     }
1.27      raeburn  4277:     # Check to see if user information can be changed
                   4278:     my @userinfo = ('firstname','middlename','lastname','generation',
                   4279:                     'permanentemail','id');
                   4280:     my %canmodify;
                   4281:     if (&Apache::lonnet::allowed('mau',$domain)) {
1.84      raeburn  4282:         push(@userinfo,'inststatus');
1.27      raeburn  4283:         foreach my $field (@userinfo) {
                   4284:             $canmodify{$field} = 1;
                   4285:         }
                   4286:     }
                   4287:     my (%userlist,%modifiable_fields,@poss_roles);
                   4288:     my $secidx = &Apache::loncoursedata::CL_SECTION();
1.102     raeburn  4289:     my @courseroles = &roles_by_context('course',1,$crstype);
1.27      raeburn  4290:     if (!&Apache::lonnet::allowed('mau',$domain)) {
                   4291:         if ($context eq 'course' || $context eq 'author') {
1.101     raeburn  4292:             @poss_roles =  &curr_role_permissions($context,'','',$crstype);
1.27      raeburn  4293:             my @statuses = ('active','future');
                   4294:             my ($indexhash,$keylist) = &make_keylist_array();
                   4295:             my %info;
                   4296:             foreach my $role (@poss_roles) {
                   4297:                 %{$modifiable_fields{$role}} = &can_modify_userinfo($context,$domain,
                   4298:                                                         \@userinfo,[$role]);
                   4299:             }
                   4300:             if ($context eq 'course') {
                   4301:                 my ($cnum,$cdom) = &get_course_identity();
                   4302:                 my $roster = &Apache::loncoursedata::get_classlist();
1.66      raeburn  4303:                 if (ref($roster) eq 'HASH') {
                   4304:                     %userlist = %{$roster};
                   4305:                 }
1.27      raeburn  4306:                 my %advrolehash = &Apache::lonnet::get_my_roles($cnum,$cdom,undef,
                   4307:                                                          \@statuses,\@poss_roles);
                   4308:                 &gather_userinfo($context,'view',\%userlist,$indexhash,\%info,
                   4309:                                 \%advrolehash,$permission);
                   4310:             } elsif ($context eq 'author') {
                   4311:                 my %cstr_roles = &Apache::lonnet::get_my_roles(undef,undef,undef,
                   4312:                                                   \@statuses,\@poss_roles);
                   4313:                 &gather_userinfo($context,'view',\%userlist,$indexhash,\%info,
                   4314:                              \%cstr_roles,$permission);
                   4315: 
                   4316:             }
                   4317:         }
1.1       raeburn  4318:     }
                   4319:     if ( $domain eq &LONCAPA::clean_domain($domain)
                   4320:         && ($amode ne '')) {
                   4321:         #######################################
                   4322:         ##         Add/Modify Users          ##
                   4323:         #######################################
                   4324:         if ($context eq 'course') {
                   4325:             $r->print('<h3>'.&mt('Enrolling Users')."</h3>\n<p>\n");
1.13      raeburn  4326:         } elsif ($context eq 'author') {
1.1       raeburn  4327:             $r->print('<h3>'.&mt('Updating Co-authors')."</h3>\n<p>\n");
                   4328:         } else {
                   4329:             $r->print('<h3>'.&mt('Adding/Modifying Users')."</h3>\n<p>\n");
                   4330:         }
1.87      bisitz   4331:         $r->rflush;
                   4332: 
1.1       raeburn  4333:         my %counts = (
                   4334:                        user => 0,
                   4335:                        auth => 0,
                   4336:                        role => 0,
                   4337:                      );
                   4338:         my $flushc=0;
                   4339:         my %student=();
1.42      raeburn  4340:         my (%curr_groups,@sections,@cleansec,$defaultwarn,$groupwarn);
1.1       raeburn  4341:         my %userchg;
1.27      raeburn  4342:         if ($context eq 'course' || $setting eq 'course') {
                   4343:             if ($context eq 'course') {
                   4344:                 # Get information about course groups
                   4345:                 %curr_groups = &Apache::longroup::coursegroups();
                   4346:             } elsif ($setting eq 'course') {
                   4347:                 if ($cid) {
                   4348:                     %curr_groups =
                   4349:                         &Apache::longroup::coursegroups($env{'form.dcdomain'},
                   4350:                                                         $env{'form.dccourse'});
                   4351:                 }
                   4352:             }
                   4353:             # determine section number
                   4354:             if ($defaultsec =~ /,/) {
                   4355:                 push(@sections,split(/,/,$defaultsec));
                   4356:             } else {
                   4357:                 push(@sections,$defaultsec);
                   4358:             }
                   4359:             # remove non alphanumeric values from section
                   4360:             foreach my $item (@sections) {
                   4361:                 $item =~ s/\W//g;
                   4362:                 if ($item eq "none" || $item eq 'all') {
                   4363:                     $defaultwarn = &mt('Default section name [_1] could not be used as it is a reserved word.',$item);
                   4364:                 } elsif ($item ne ''  && exists($curr_groups{$item})) {
                   4365:                     $groupwarn = &mt('Default section name "[_1]" is the name of a course group. Section names and group names must be distinct.',$item);
                   4366:                 } elsif ($item ne '') {
                   4367:                     push(@cleansec,$item);
                   4368:                 }
                   4369:             }
                   4370:             if ($defaultwarn) {
                   4371:                 $r->print($defaultwarn.'<br />');
                   4372:             }
                   4373:             if ($groupwarn) {
                   4374:                 $r->print($groupwarn.'<br />');
                   4375:             }
1.1       raeburn  4376:         }
1.124     raeburn  4377:         my (%curr_rules,%got_rules,%alerts,%cancreate);
1.104     raeburn  4378:         my %customroles = &my_custom_roles($crstype);
1.101     raeburn  4379:         my @permitted_roles = 
1.124     raeburn  4380:             &roles_on_upload($context,$setting,$crstype,%customroles);
                   4381:         my %longtypes = &Apache::lonlocal::texthash(
                   4382:                             official   => 'Institutional',
                   4383:                             unofficial => 'Non-institutional',
                   4384:                         );
1.135     raeburn  4385:         my $newuserdom = $env{'request.role.domain'};
                   4386:         map { $cancreate{$_} = &can_create_user($newuserdom,$context,$_); } keys(%longtypes);
1.1       raeburn  4387:         # Get new users list
1.172     raeburn  4388:         my (%existinguser,%userinfo,%disallow,%rulematch,%inst_results,%alerts,%checkuname);
1.171     raeburn  4389:         my $counter = -1;
1.185   ! raeburn  4390:         my (%willtrust,%trustchecked);
1.27      raeburn  4391:         foreach my $line (@userdata) {
1.171     raeburn  4392:             $counter ++;
1.42      raeburn  4393:             my @secs;
1.27      raeburn  4394:             my %entries=&Apache::loncommon::record_sep($line);
1.1       raeburn  4395:             # Determine user name
1.128     raeburn  4396:             $entries{$fields{'username'}} =~ s/^\s+|\s+$//g;
1.1       raeburn  4397:             unless (($entries{$fields{'username'}} eq '') ||
                   4398:                     (!defined($entries{$fields{'username'}}))) {
                   4399:                 my ($fname, $mname, $lname,$gen) = ('','','','');
                   4400:                 if (defined($fields{'names'})) {
                   4401:                     ($lname,$fname,$mname)=($entries{$fields{'names'}}=~
                   4402:                                             /([^\,]+)\,\s*(\w+)\s*(.*)$/);
                   4403:                 } else {
                   4404:                     if (defined($fields{'fname'})) {
                   4405:                         $fname=$entries{$fields{'fname'}};
                   4406:                     }
                   4407:                     if (defined($fields{'mname'})) {
                   4408:                         $mname=$entries{$fields{'mname'}};
                   4409:                     }
                   4410:                     if (defined($fields{'lname'})) {
                   4411:                         $lname=$entries{$fields{'lname'}};
                   4412:                     }
                   4413:                     if (defined($fields{'gen'})) {
                   4414:                         $gen=$entries{$fields{'gen'}};
                   4415:                     }
                   4416:                 }
1.128     raeburn  4417: 
1.1       raeburn  4418:                 if ($entries{$fields{'username'}}
                   4419:                     ne &LONCAPA::clean_username($entries{$fields{'username'}})) {
1.128     raeburn  4420:                     my $nowhitespace;
                   4421:                     if ($entries{$fields{'username'}} =~ /\s/) {
                   4422:                         $nowhitespace = ' - '.&mt('usernames may not contain spaces.');
                   4423:                     }
1.171     raeburn  4424:                     $disallow{$counter} =
1.157     bisitz   4425:                         &mt('Unacceptable username [_1] for user [_2] [_3] [_4] [_5]',
1.171     raeburn  4426:                             '"<b>'.$entries{$fields{'username'}}.'</b>"',
                   4427:                             $fname,$mname,$lname,$gen).$nowhitespace;
1.27      raeburn  4428:                     next;
1.1       raeburn  4429:                 } else {
1.129     raeburn  4430:                     $entries{$fields{'domain'}} =~ s/^\s+|\s+$//g;
1.71      droeschl 4431:                     if ($entries{$fields{'domain'}} 
1.57      raeburn  4432:                         ne &LONCAPA::clean_domain($entries{$fields{'domain'}})) {
1.171     raeburn  4433:                         $disallow{$counter} =
1.157     bisitz   4434:                             &mt('Unacceptable domain [_1] for user [_2] [_3] [_4] [_5]',
1.171     raeburn  4435:                                 '"<b>'.$entries{$fields{'domain'}}.'</b>"',
                   4436:                                 $fname,$mname,$lname,$gen);
                   4437:                         next;
1.185   ! raeburn  4438:                     } elsif ($entries{$fields{'domain'}} ne $domain) {
        !          4439:                         my $possdom = $entries{$fields{'domain'}};
        !          4440:                         if ($context eq 'course' || $setting eq 'course') {
        !          4441:                             unless ($trustchecked{$possdom}) {
        !          4442:                                 $willtrust{$possdom} = &Apache::lonnet::will_trust('enroll',$domain,$possdom);
        !          4443:                                 $trustchecked{$possdom} = 1;
        !          4444:                             }
        !          4445:                         } elsif ($context eq 'author') {
        !          4446:                             unless ($trustchecked{$possdom}) {
        !          4447:                                 $willtrust{$possdom} = &Apache::lonnet::will_trust('othcoau',$domain,$possdom);
        !          4448:                             }
        !          4449:                             if ($willtrust{$possdom}) {
        !          4450:                                 $willtrust{$possdom} = &Apache::lonnet::will_trust('coaurem',$possdom,$domain); 
        !          4451:                             }
        !          4452:                         }
        !          4453:                         unless ($willtrust{$possdom}) {
        !          4454:                             $disallow{$counter} =
        !          4455:                                 &mt('Unacceptable domain [_1] for user [_2] [_3] [_4] [_5]',
        !          4456:                                     '"<b>'.$possdom.'</b>"',
        !          4457:                                     $fname,$mname,$lname,$gen);
        !          4458:                             next;
        !          4459:                         }
1.57      raeburn  4460:                     }
1.5       raeburn  4461:                     my $username = $entries{$fields{'username'}};
1.57      raeburn  4462:                     my $userdomain = $entries{$fields{'domain'}};
                   4463:                     if ($userdomain eq '') {
                   4464:                         $userdomain = $domain;
                   4465:                     }
1.27      raeburn  4466:                     if (defined($fields{'sec'})) {
                   4467:                         if (defined($entries{$fields{'sec'}})) {
1.42      raeburn  4468:                             $entries{$fields{'sec'}} =~ s/\W//g;
1.27      raeburn  4469:                             my $item = $entries{$fields{'sec'}};
                   4470:                             if ($item eq "none" || $item eq 'all') {
1.171     raeburn  4471:                                 $disallow{$counter} =
                   4472:                                     &mt('[_1]: Unable to enroll user [_2] [_3] [_4] [_5] in a section named "[_6]" - this is a reserved word.',
                   4473:                                         '<b>'.$username.'</b>',$fname,$mname,$lname,$gen,$item);
1.27      raeburn  4474:                                 next;
                   4475:                             } elsif (exists($curr_groups{$item})) {
1.171     raeburn  4476:                                 $disallow{$counter} =
                   4477:                                     &mt('[_1]: Unable to enroll user [_2] [_3] [_4] [_5] in a section named "[_6]" - this is a course group.',
                   4478:                                         '<b>'.$username.'</b>',$fname,$mname,$lname,$gen,$item).' '.
                   4479:                                     &mt('Section names and group names must be distinct.');
1.27      raeburn  4480:                                 next;
                   4481:                             } else {
                   4482:                                 push(@secs,$item);
                   4483:                             }
                   4484:                         }
                   4485:                     }
                   4486:                     if ($env{'request.course.sec'} ne '') {
                   4487:                         @secs = ($env{'request.course.sec'});
1.57      raeburn  4488:                         if (ref($userlist{$username.':'.$userdomain}) eq 'ARRAY') {
                   4489:                             my $currsec = $userlist{$username.':'.$userdomain}[$secidx];
1.27      raeburn  4490:                             if ($currsec ne $env{'request.course.sec'}) {
1.171     raeburn  4491:                                 $disallow{$counter} =
                   4492:                                     &mt('[_1]: Unable to enroll user [_2] [_3] [_4] [_5] in a section named "[_6]".',
                   4493:                                         '<b>'.$username.'</b>',$fname,$mname,$lname,$gen,$secs[0]);
1.27      raeburn  4494:                                 if ($currsec eq '') {
1.171     raeburn  4495:                                     $disallow{$counter} .=
                   4496:                                         &mt('This user already has an active/future student role in the course, unaffiliated to any section.');
1.27      raeburn  4497: 
                   4498:                                 } else {
1.171     raeburn  4499:                                     $disallow{$counter} .=
                   4500:                                         &mt('This user already has an active/future role in section "[_1]" of the course.',$currsec);
1.27      raeburn  4501:                                 }
1.171     raeburn  4502:                                 $disallow{$counter} .=
                   4503:                                     '<br />'.
                   4504:                                     &mt('Although your current role has privileges to add students to section "[_1]", you do not have privileges to modify existing enrollments in other sections.',
                   4505:                                         $secs[0]);
1.27      raeburn  4506:                                 next;
1.1       raeburn  4507:                             }
                   4508:                         }
1.27      raeburn  4509:                     } elsif ($context eq 'course' || $setting eq 'course') {
                   4510:                         if (@secs == 0) {
                   4511:                             @secs = @cleansec;
1.1       raeburn  4512:                         }
                   4513:                     }
                   4514:                     # determine id number
                   4515:                     my $id='';
                   4516:                     if (defined($fields{'id'})) {
                   4517:                         if (defined($entries{$fields{'id'}})) {
                   4518:                             $id=$entries{$fields{'id'}};
                   4519:                         }
                   4520:                         $id=~tr/A-Z/a-z/;
                   4521:                     }
                   4522:                     # determine email address
                   4523:                     my $email='';
                   4524:                     if (defined($fields{'email'})) {
1.129     raeburn  4525:                         $entries{$fields{'email'}} =~ s/^\s+|\s+$//g;
1.1       raeburn  4526:                         if (defined($entries{$fields{'email'}})) {
                   4527:                             $email=$entries{$fields{'email'}};
1.84      raeburn  4528:                             unless ($email=~/^[^\@]+\@[^\@]+$/) { $email=''; }
                   4529:                         }
                   4530:                     }
                   4531:                     # determine affiliation
                   4532:                     my $inststatus='';
                   4533:                     if (defined($fields{'inststatus'})) {
                   4534:                         if (defined($entries{$fields{'inststatus'}})) {
                   4535:                             $inststatus=$entries{$fields{'inststatus'}};
                   4536:                         }
1.1       raeburn  4537:                     }
                   4538:                     # determine user password
                   4539:                     my $password = $genpwd;
                   4540:                     if (defined($fields{'ipwd'})) {
                   4541:                         if ($entries{$fields{'ipwd'}}) {
                   4542:                             $password=$entries{$fields{'ipwd'}};
                   4543:                         }
                   4544:                     }
                   4545:                     # determine user role
                   4546:                     my $role = '';
                   4547:                     if (defined($fields{'role'})) {
                   4548:                         if ($entries{$fields{'role'}}) {
1.42      raeburn  4549:                             $entries{$fields{'role'}}  =~ s/(\s+$|^\s+)//g;
                   4550:                             if ($entries{$fields{'role'}} ne '') {
                   4551:                                 if (grep(/^\Q$entries{$fields{'role'}}\E$/,@permitted_roles)) {
                   4552:                                     $role = $entries{$fields{'role'}};
1.27      raeburn  4553:                                 }
                   4554:                             }
                   4555:                             if ($role eq '') {
                   4556:                                 my $rolestr = join(', ',@permitted_roles);
1.171     raeburn  4557:                                 $disallow{$counter} =
                   4558:                                     &mt('[_1]: You do not have permission to add the requested role [_2] for the user.'
                   4559:                                         ,'<b>'.$entries{$fields{'username'}}.'</b>'
                   4560:                                         ,$entries{$fields{'role'}})
                   4561:                                         .'<br />'
                   4562:                                         .&mt('Allowable role(s) is/are: [_1].',$rolestr);
1.1       raeburn  4563:                                 next;
                   4564:                             }
                   4565:                         }
                   4566:                     }
                   4567:                     if ($role eq '') {
                   4568:                         $role = $defaultrole;
                   4569:                     }
                   4570:                     # Clean up whitespace
1.129     raeburn  4571:                     foreach (\$id,\$fname,\$mname,\$lname,\$gen,\$inststatus) {
1.1       raeburn  4572:                         $$_ =~ s/(\s+$|^\s+)//g;
                   4573:                     }
1.150     raeburn  4574:                     my $credits;
                   4575:                     if ($showcredits) {
                   4576:                         if (($role eq 'st') && ($crstype ne 'Community')) {
                   4577:                             $credits = $entries{$fields{'credits'}};
                   4578:                             if ($credits ne '') {
                   4579:                                 $credits =~ s/[^\d\.]//g;
                   4580:                             }
                   4581:                             if ($credits eq '') {
                   4582:                                 $credits = $commoncredits;
                   4583:                             }
                   4584:                             if ($credits eq $defaultcredits) {
                   4585:                                 undef($credits);
                   4586:                             }
                   4587:                         }
                   4588:                     }
1.5       raeburn  4589:                     # check against rules
                   4590:                     my $checkid = 0;
                   4591:                     my $newuser = 0;
1.57      raeburn  4592:                     my $uhome=&Apache::lonnet::homeserver($username,$userdomain);
1.5       raeburn  4593:                     if ($uhome eq 'no_host') {
1.135     raeburn  4594:                         if ($userdomain ne $newuserdom) {
                   4595:                             if ($context eq 'course') {
1.171     raeburn  4596:                                 $disallow{$counter} =
                   4597:                                     &mt('[_1]: The domain specified ([_2]) is different to that of the course.',
                   4598:                                        '<b>'.$username.'</b>',$userdomain);
1.135     raeburn  4599:                             } elsif ($context eq 'author') {
1.171     raeburn  4600:                                 $disallow{$counter} =
                   4601:                                     &mt('[_1]: The domain specified ([_2]) is different to that of the author.',
                   4602:                                         '<b>'.$username.'</b>',$userdomain); 
1.135     raeburn  4603:                             } else {
1.171     raeburn  4604:                                 $disallow{$counter} =
                   4605:                                     &mt('[_1]: The domain specified ([_2]) is different to that of your current role.',
                   4606:                                         '<b>'.$username.'</b>',$userdomain);
1.135     raeburn  4607:                             }
1.171     raeburn  4608:                             $disallow{$counter} .=
                   4609:                                 &mt('The user does not already exist, and you may not create a new user in a different domain.');
1.124     raeburn  4610:                             next;
1.171     raeburn  4611:                         } else {
                   4612:                             unless ($password || $env{'form.login'} eq 'loc') {
                   4613:                                 $disallow{$counter} =
                   4614:                                     &mt('[_1]: This is a new user but no default password was provided, and the authentication type requires one.',
                   4615:                                         '<b>'.$username.'</b>');
                   4616:                                 next;
                   4617:                             }
1.124     raeburn  4618:                         }
1.5       raeburn  4619:                         $checkid = 1;
                   4620:                         $newuser = 1;
1.172     raeburn  4621:                         $checkuname{$username.':'.$newuserdom} = { 'newuser' => $newuser, 'id' => $id };
1.13      raeburn  4622:                     } else {
1.27      raeburn  4623:                         if ($context eq 'course' || $context eq 'author') {
1.57      raeburn  4624:                             if ($userdomain eq $domain ) {
                   4625:                                 if ($role eq '') {
                   4626:                                     my @checkroles;
                   4627:                                     foreach my $role (@poss_roles) {
                   4628:                                         my $endkey;
                   4629:                                         if ($role ne 'st') {
                   4630:                                             $endkey = ':'.$role;
                   4631:                                         }
                   4632:                                         if (exists($userlist{$username.':'.$userdomain.$endkey})) {
                   4633:                                             if (!grep(/^\Q$role\E$/,@checkroles)) {
                   4634:                                                 push(@checkroles,$role);
                   4635:                                             }
                   4636:                                         }
1.27      raeburn  4637:                                     }
1.57      raeburn  4638:                                     if (@checkroles > 0) {
                   4639:                                         %canmodify = &can_modify_userinfo($context,$domain,\@userinfo,\@checkroles);
1.27      raeburn  4640:                                     }
1.57      raeburn  4641:                                 } elsif (ref($modifiable_fields{$role}) eq 'HASH') {
                   4642:                                     %canmodify = %{$modifiable_fields{$role}};
1.27      raeburn  4643:                                 }
                   4644:                             }
1.57      raeburn  4645:                             my @newinfo = (\$fname,\$mname,\$lname,\$gen,\$email,\$id);
1.84      raeburn  4646:                             for (my $i=0; $i<@newinfo; $i++) {
1.57      raeburn  4647:                                 if (${$newinfo[$i]} ne '') {
                   4648:                                     if (!$canmodify{$userinfo[$i]}) {
                   4649:                                         ${$newinfo[$i]} = '';
                   4650:                                     }
1.27      raeburn  4651:                                 }
                   4652:                             }
                   4653:                         }
1.171     raeburn  4654:                         if ($id) {
                   4655:                             $existinguser{$userdomain}{$username} = $id;
                   4656:                         }
1.5       raeburn  4657:                     }
1.171     raeburn  4658:                     $userinfo{$counter} = {
                   4659:                                           username   => $username,
                   4660:                                           domain     => $userdomain,
                   4661:                                           fname      => $fname,
                   4662:                                           mname      => $mname,
                   4663:                                           lname      => $lname,
                   4664:                                           gen        => $gen,
                   4665:                                           email      => $email,
                   4666:                                           id         => $id, 
                   4667:                                           password   => $password,
                   4668:                                           inststatus => $inststatus,
                   4669:                                           role       => $role,
                   4670:                                           sections   => \@secs,
                   4671:                                           credits    => $credits,
                   4672:                                           newuser    => $newuser,
                   4673:                                           checkid    => $checkid,
                   4674:                                         };
                   4675:                 }
                   4676:             }
                   4677:         } # end of foreach (@userdata)
                   4678:         if ($counter > -1) {
                   4679:             my $total = $counter + 1;
                   4680:             my %checkids;
1.172     raeburn  4681:             if ((keys(%existinguser)) || (keys(%checkuname))) {
                   4682:                 $r->print(&mt('Please be patient -- checking for institutional data ...'));
                   4683:                 $r->rflush();
                   4684:                 if (keys(%existinguser)) {
                   4685:                     foreach my $dom (keys(%existinguser)) {
                   4686:                         if (ref($existinguser{$dom}) eq 'HASH') {
                   4687:                             my %idhash = &Apache::lonnet::idrget($dom,keys(%{$existinguser{$dom}}));
                   4688:                             foreach my $username (keys(%{$existinguser{$dom}})) {
                   4689:                                 if ($idhash{$username} ne $existinguser{$dom}{$username}) {
                   4690:                                     $checkids{$username.':'.$dom} = {
                   4691:                                                                     'id' => $existinguser{$dom}{$username},
                   4692:                                                                     };
                   4693:                                 }
                   4694:                             }
                   4695:                             if (keys(%checkids)) {
                   4696:                                 &Apache::loncommon::user_rule_check(\%checkids,{ 'id' => 1 },
                   4697:                                                                     \%alerts,\%rulematch,
                   4698:                                                                     \%inst_results,\%curr_rules,
                   4699:                                                                     \%got_rules);
1.171     raeburn  4700:                             }
                   4701:                         }
                   4702:                     }
                   4703:                 }
1.172     raeburn  4704:                 if (keys(%checkuname)) {
                   4705:                     &Apache::loncommon::user_rule_check(\%checkuname,{ 'username' => 1, 'id' => 1, },
                   4706:                                                         \%alerts,\%rulematch,\%inst_results,
                   4707:                                                         \%curr_rules,\%got_rules);
                   4708:                 }
                   4709:                 $r->print(' '.&mt('done').'<br /><br />');
                   4710:                 $r->rflush();
1.171     raeburn  4711:             }
1.172     raeburn  4712:             my %prog_state = &Apache::lonhtmlcommon::Create_PrgWin($r,$total);
1.171     raeburn  4713:             $r->print('<ul>');
                   4714:             for (my $i=0; $i<=$counter; $i++) {
                   4715:                 if ($disallow{$i}) {
                   4716:                     $r->print('<li>'.$disallow{$i}.'</li>');
                   4717:                 } elsif (ref($userinfo{$i}) eq 'HASH') {
                   4718:                     my $password = $userinfo{$i}{'password'}; 
                   4719:                     my $newuser = $userinfo{$i}{'newuser'};
                   4720:                     my $checkid = $userinfo{$i}{'checkid'};
                   4721:                     my $id = $userinfo{$i}{'id'};
                   4722:                     my $role = $userinfo{$i}{'role'};
                   4723:                     my @secs;
                   4724:                     if (ref($userinfo{$i}{'sections'}) eq 'ARRAY') {
                   4725:                         @secs = @{$userinfo{$i}{'sections'}};
                   4726:                     }
                   4727:                     my $fname = $userinfo{$i}{'fname'};
                   4728:                     my $mname = $userinfo{$i}{'mname'}; 
                   4729:                     my $lname = $userinfo{$i}{'lname'};
                   4730:                     my $gen = $userinfo{$i}{'gen'};
                   4731:                     my $email = $userinfo{$i}{'email'};
                   4732:                     my $inststatus = $userinfo{$i}{'inststatus'};
                   4733:                     my $credits = $userinfo{$i}{'credits'};
                   4734:                     my $username = $userinfo{$i}{'username'};
                   4735:                     my $userdomain = $userinfo{$i}{'domain'};
                   4736:                     my $user = $username.':'.$userdomain;
                   4737:                     if ($newuser) {
                   4738:                         if (ref($alerts{'username'}) eq 'HASH') {
                   4739:                             if (ref($alerts{'username'}{$userdomain}) eq 'HASH') {
                   4740:                                 if ($alerts{'username'}{$userdomain}{$username}) {
                   4741:                                     $r->print('<li>'.
                   4742:                                               &mt('[_1]: matches the username format at your institution, but is not known to your directory service.','<b>'.$username.'</b>').'<br />'.
                   4743:                                               &mt('Consequently, the user was not created.').'</li>');
                   4744:                                     next;
                   4745:                                 }
                   4746:                             }
                   4747:                         }
1.172     raeburn  4748:                         if (ref($inst_results{$user}) eq 'HASH') {
                   4749:                             if ($inst_results{$user}{'firstname'} ne '') {
                   4750:                                 $fname = $inst_results{$user}{'firstname'};
                   4751:                             }
                   4752:                             if ($inst_results{$user}{'middlename'} ne '') {
                   4753:                                 $mname = $inst_results{$user}{'middlename'};
                   4754:                             }
                   4755:                             if ($inst_results{$user}{'lasttname'} ne '') {
                   4756:                                 $lname = $inst_results{$user}{'lastname'};
                   4757:                             }
                   4758:                             if ($inst_results{$user}{'permanentemail'} ne '') {
                   4759:                                 $email = $inst_results{$user}{'permanentemail'};
                   4760:                             }
                   4761:                             if ($inst_results{$user}{'id'} ne '') {
                   4762:                                 $id = $inst_results{$user}{'id'};
                   4763:                                 $checkid = 0;
                   4764:                             }
                   4765:                             if (ref($inst_results{$user}{'inststatus'}) eq 'ARRAY') {
                   4766:                                 $inststatus = join(':',@{$inst_results{$user}{'inststatus'}});
                   4767:                             }
                   4768:                         }
                   4769:                         if (($checkid) && ($id ne '')) {
                   4770:                             if (ref($alerts{'id'}) eq 'HASH') {
                   4771:                                 if (ref($alerts{'id'}{$userdomain}) eq 'HASH') {
                   4772:                                     if ($alerts{'id'}{$userdomain}{$username}) {
                   4773:                                         $r->print('<li>'.
                   4774:                                                   &mt('[_1]: has a student/employee ID matching the format at your institution, but the ID is not found by your directory service.',
                   4775:                                                   '<b>'.$username.'</b>').'<br />'.
                   4776:                                                   &mt('Consequently, the user was not created.').'</li>');
                   4777:                                         next;
                   4778:                                     }
                   4779:                                 }
                   4780:                             }
                   4781:                         }
1.171     raeburn  4782:                         my $usertype = 'unofficial';
                   4783:                         if (ref($rulematch{$user}) eq 'HASH') {
                   4784:                             if ($rulematch{$user}{'username'}) {
                   4785:                                 $usertype = 'official';
1.5       raeburn  4786:                             }
                   4787:                         }
1.171     raeburn  4788:                         unless ($cancreate{$usertype}) {
                   4789:                             my $showtype = $longtypes{$usertype};
                   4790:                             $r->print('<li>'.
                   4791:                                       &mt('[_1]: The user does not exist, and you are not permitted to create users of type: [_2].','<b>'.$username.'</b>',$showtype).'</li>');
                   4792:                             next;
                   4793:                         }
1.172     raeburn  4794:                     } elsif ($id ne '') {
1.171     raeburn  4795:                         if (exists($checkids{$user})) {
                   4796:                             $checkid = 1; 
1.5       raeburn  4797:                             if (ref($alerts{'id'}) eq 'HASH') {
1.57      raeburn  4798:                                 if (ref($alerts{'id'}{$userdomain}) eq 'HASH') {
1.172     raeburn  4799:                                     if ($alerts{'id'}{$userdomain}{$username}) {
1.171     raeburn  4800:                                         $r->print('<li>'.
1.172     raeburn  4801:                                                   &mt('[_1]: has a student/employee ID matching the format at your institution, but the ID is not found by your directory service.',
1.124     raeburn  4802:                                                   '<b>'.$username.'</b>').'<br />'.
1.172     raeburn  4803:                                                   &mt('Consequently, the ID was not changed.').'</li>');
                   4804:                                         $id = '';
1.124     raeburn  4805:                                     }
1.5       raeburn  4806:                                 }
                   4807:                             }
                   4808:                         }
                   4809:                     }
1.171     raeburn  4810:                     my $multiple = 0;
                   4811:                     my ($userresult,$authresult,$roleresult,$idresult);
                   4812:                     my (%userres,%authres,%roleres,%idres);
                   4813:                     my $singlesec = '';
                   4814:                     if ($role eq 'st') {
                   4815:                         my $sec;
                   4816:                         if (ref($userinfo{$i}{'sections'}) eq 'ARRAY') {
1.42      raeburn  4817:                             if (@secs > 0) {
                   4818:                                 $sec = $secs[0];
1.27      raeburn  4819:                             }
1.171     raeburn  4820:                         }
                   4821:                         &modifystudent($userdomain,$username,$cid,$sec,
                   4822:                                        $desiredhost,$context);
                   4823:                         $roleresult =
                   4824:                             &Apache::lonnet::modifystudent
                   4825:                                 ($userdomain,$username,$id,$amode,$password,
                   4826:                                  $fname,$mname,$lname,$gen,$sec,$enddate,
                   4827:                                  $startdate,$env{'form.forceid'},
                   4828:                                  $desiredhost,$email,'manual','',$cid,
                   4829:                                  '',$context,$inststatus,$credits);
                   4830:                         $userresult = $roleresult;
                   4831:                     } else {
                   4832:                         if ($role ne '') { 
                   4833:                             if ($context eq 'course' || $setting eq 'course') {
                   4834:                                 if ($customroles{$role}) {
                   4835:                                     $role = 'cr_'.$env{'user.domain'}.'_'.
                   4836:                                             $env{'user.name'}.'_'.$role;
                   4837:                                 }
                   4838:                                 if (($role ne 'cc') && ($role ne 'co')) { 
                   4839:                                    if (@secs > 1) {
                   4840:                                         $multiple = 1;
                   4841:                                         foreach my $sec (@secs) {
                   4842:                                             ($userres{$sec},$authres{$sec},$roleres{$sec},$idres{$sec}) =
                   4843:                                             &modifyuserrole($context,$setting,
                   4844:                                                 $changeauth,$cid,$userdomain,$username,
                   4845:                                                 $id,$amode,$password,$fname,
                   4846:                                                 $mname,$lname,$gen,$sec,
                   4847:                                                 $env{'form.forceid'},$desiredhost,
                   4848:                                                 $email,$role,$enddate,
                   4849:                                                 $startdate,$checkid,$inststatus);
1.42      raeburn  4850:                                         }
1.171     raeburn  4851:                                     } elsif (@secs > 0) {
                   4852:                                         $singlesec = $secs[0];
1.27      raeburn  4853:                                     }
                   4854:                                 }
                   4855:                             }
                   4856:                             if (!$multiple) {
1.28      raeburn  4857:                                 ($userresult,$authresult,$roleresult,$idresult) = 
1.27      raeburn  4858:                                     &modifyuserrole($context,$setting,
1.57      raeburn  4859:                                                     $changeauth,$cid,$userdomain,$username, 
1.42      raeburn  4860:                                                     $id,$amode,$password,$fname,
                   4861:                                                     $mname,$lname,$gen,$singlesec,
                   4862:                                                     $env{'form.forceid'},$desiredhost,
1.84      raeburn  4863:                                                     $email,$role,$enddate,$startdate,
                   4864:                                                     $checkid,$inststatus);
1.27      raeburn  4865:                             }
                   4866:                         }
1.171     raeburn  4867:                     }
                   4868:                     if ($multiple) {
                   4869:                         foreach my $sec (sort(keys(%userres))) {
                   4870:                             $flushc =
1.27      raeburn  4871:                                 &user_change_result($r,$userres{$sec},$authres{$sec},
                   4872:                                                     $roleres{$sec},$idres{$sec},\%counts,$flushc,
1.57      raeburn  4873:                                                     $username,$userdomain,\%userchg);
1.27      raeburn  4874: 
1.1       raeburn  4875:                         }
                   4876:                     } else {
1.171     raeburn  4877:                         $flushc = 
                   4878:                             &user_change_result($r,$userresult,$authresult,
                   4879:                                                 $roleresult,$idresult,\%counts,$flushc,
                   4880:                                                 $username,$userdomain,\%userchg);
1.1       raeburn  4881:                     }
                   4882:                 }
1.172     raeburn  4883:                 &Apache::lonhtmlcommon::Increment_PrgWin($r,\%prog_state,'last user');
1.171     raeburn  4884:             } # end of loop
1.172     raeburn  4885:             $r->print('</ul>');
1.171     raeburn  4886:             &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
                   4887:         }
1.1       raeburn  4888:         # Flush the course logs so reverse user roles immediately updated
1.126     raeburn  4889:         $r->register_cleanup(\&Apache::lonnet::flushcourselogs);
1.29      raeburn  4890:         $r->print("</p>\n<p>\n".&mt('Processed [quant,_1,user].',$counts{'user'}).
1.1       raeburn  4891:                   "</p>\n");
                   4892:         if ($counts{'role'} > 0) {
                   4893:             $r->print("<p>\n".
1.29      raeburn  4894:                       &mt('Roles added for [quant,_1,user].',$counts{'role'}).' '.&mt('If a user is currently logged-in to LON-CAPA, any new roles which are active will be available when the user next logs in.')."</p>\n");
                   4895:         } else {
                   4896:             $r->print('<p>'.&mt('No roles added').'</p>');
1.1       raeburn  4897:         }
                   4898:         if ($counts{'auth'} > 0) {
                   4899:             $r->print("<p>\n".
                   4900:                       &mt('Authentication changed for [_1] existing users.',
                   4901:                           $counts{'auth'})."</p>\n");
                   4902:         }
1.13      raeburn  4903:         $r->print(&print_namespacing_alerts($domain,\%alerts,\%curr_rules));
1.1       raeburn  4904:         #####################################
1.29      raeburn  4905:         # Display list of students to drop  #
1.1       raeburn  4906:         #####################################
                   4907:         if ($env{'form.fullup'} eq 'yes') {
1.29      raeburn  4908:             $r->print('<h3>'.&mt('Students to Drop')."</h3>\n");
1.1       raeburn  4909:             #  Get current classlist
1.30      raeburn  4910:             my $classlist = &Apache::loncoursedata::get_classlist();
1.1       raeburn  4911:             if (! defined($classlist)) {
1.153     bisitz   4912:                 $r->print('<form name="studentform" method="post" action="/adm/createuser">'.
1.29      raeburn  4913:                           '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
1.143     bisitz   4914:                           '<p class="LC_info">'.&mt('There are no students with current/future access to the course.').'</p>'.
1.29      raeburn  4915:                           '</form>'."\n");
1.66      raeburn  4916:             } elsif (ref($classlist) eq 'HASH') {
1.1       raeburn  4917:                 # Remove the students we just added from the list of students.
1.30      raeburn  4918:                 foreach my $line (@userdata) {
                   4919:                     my %entries=&Apache::loncommon::record_sep($line);
1.1       raeburn  4920:                     unless (($entries{$fields{'username'}} eq '') ||
                   4921:                             (!defined($entries{$fields{'username'}}))) {
                   4922:                         delete($classlist->{$entries{$fields{'username'}}.
                   4923:                                                 ':'.$domain});
                   4924:                     }
                   4925:                 }
                   4926:                 # Print out list of dropped students.
1.30      raeburn  4927:                 &show_drop_list($r,$classlist,'nosort',$permission);
1.1       raeburn  4928:             }
                   4929:         }
                   4930:     } # end of unless
1.29      raeburn  4931:     if ($env{'form.fullup'} ne 'yes') {
                   4932:         $r->print('</form>');
                   4933:     }
1.1       raeburn  4934: }
                   4935: 
1.13      raeburn  4936: sub print_namespacing_alerts {
                   4937:     my ($domain,$alerts,$curr_rules) = @_;
                   4938:     my $output;
                   4939:     if (ref($alerts) eq 'HASH') {
                   4940:         if (keys(%{$alerts}) > 0) {
                   4941:             if (ref($alerts->{'username'}) eq 'HASH') {
                   4942:                 foreach my $dom (sort(keys(%{$alerts->{'username'}}))) {
                   4943:                     my $count;
                   4944:                     if (ref($alerts->{'username'}{$dom}) eq 'HASH') {
                   4945:                         $count = keys(%{$alerts->{'username'}{$dom}});
                   4946:                     }
                   4947:                     my $domdesc = &Apache::lonnet::domain($domain,'description');
                   4948:                     if (ref($curr_rules->{$dom}) eq 'HASH') {
                   4949:                         $output .= &Apache::loncommon::instrule_disallow_msg(
                   4950:                                         'username',$domdesc,$count,'upload');
                   4951:                     }
                   4952:                     $output .= &Apache::loncommon::user_rule_formats($dom,
                   4953:                                    $domdesc,$curr_rules->{$dom}{'username'},
                   4954:                                    'username');
                   4955:                 }
                   4956:             }
                   4957:             if (ref($alerts->{'id'}) eq 'HASH') {
                   4958:                 foreach my $dom (sort(keys(%{$alerts->{'id'}}))) {
                   4959:                     my $count;
                   4960:                     if (ref($alerts->{'id'}{$dom}) eq 'HASH') {
                   4961:                         $count = keys(%{$alerts->{'id'}{$dom}});
                   4962:                     }
                   4963:                     my $domdesc = &Apache::lonnet::domain($domain,'description');
                   4964:                     if (ref($curr_rules->{$dom}) eq 'HASH') {
                   4965:                         $output .= &Apache::loncommon::instrule_disallow_msg(
                   4966:                                               'id',$domdesc,$count,'upload');
                   4967:                     }
                   4968:                     $output .= &Apache::loncommon::user_rule_formats($dom,
                   4969:                                     $domdesc,$curr_rules->{$dom}{'id'},'id');
                   4970:                 }
                   4971:             }
                   4972:         }
                   4973:     }
                   4974: }
                   4975: 
1.1       raeburn  4976: sub user_change_result {
1.29      raeburn  4977:     my ($r,$userresult,$authresult,$roleresult,$idresult,$counts,$flushc,
1.57      raeburn  4978:         $username,$userdomain,$userchg) = @_;
1.1       raeburn  4979:     my $okresult = 0;
1.171     raeburn  4980:     my @status;
1.1       raeburn  4981:     if ($userresult ne 'ok') {
                   4982:         if ($userresult =~ /^error:(.+)$/) {
                   4983:             my $error = $1;
1.171     raeburn  4984:             push(@status,
                   4985:                  &mt('[_1]: Unable to add/modify: [_2]','<b>'.$username.':'.$userdomain.'</b>',$error));
1.1       raeburn  4986:         }
                   4987:     } else {
                   4988:         $counts->{'user'} ++;
                   4989:         $okresult = 1;
                   4990:     }
                   4991:     if ($authresult ne 'ok') {
                   4992:         if ($authresult =~ /^error:(.+)$/) {
                   4993:             my $error = $1;
1.171     raeburn  4994:             push(@status, 
                   4995:                  &mt('[_1]: Unable to modify authentication: [_2]','<b>'.$username.':'.$userdomain.'</b>',$error));
1.1       raeburn  4996:         } 
                   4997:     } else {
                   4998:         $counts->{'auth'} ++;
                   4999:         $okresult = 1;
                   5000:     }
                   5001:     if ($roleresult ne 'ok') {
                   5002:         if ($roleresult =~ /^error:(.+)$/) {
                   5003:             my $error = $1;
1.171     raeburn  5004:             push(@status,
                   5005:                  &mt('[_1]: Unable to add role: [_2]','<b>'.$username.':'.$userdomain.'</b>',$error));
1.1       raeburn  5006:         }
                   5007:     } else {
                   5008:         $counts->{'role'} ++;
                   5009:         $okresult = 1;
                   5010:     }
                   5011:     if ($okresult) {
                   5012:         $flushc++;
1.57      raeburn  5013:         $userchg->{$username.':'.$userdomain}=1;
1.1       raeburn  5014:         if ($flushc>15) {
                   5015:             $r->rflush;
                   5016:             $flushc=0;
                   5017:         }
                   5018:     }
1.29      raeburn  5019:     if ($idresult) {
1.171     raeburn  5020:         push(@status,$idresult);
                   5021:     }
                   5022:     if (@status) {
                   5023:         $r->print('<li>'.join('<br />',@status).'</li>');
1.29      raeburn  5024:     }
1.1       raeburn  5025:     return $flushc;
                   5026: }
                   5027: 
                   5028: # ========================================================= Menu Phase Two Drop
1.17      raeburn  5029: sub print_drop_menu {
1.101     raeburn  5030:     my ($r,$context,$permission,$crstype) = @_;
                   5031:     my $heading;
                   5032:     if ($crstype eq 'Community') {
                   5033:         $heading = &mt("Drop Members");
                   5034:     } else {
                   5035:         $heading = &mt("Drop Students");
                   5036:     }
                   5037:     $r->print('<h3>'.$heading.'</h3>'."\n".
1.153     bisitz   5038:               '<form name="studentform" method="post" action="">'."\n");
1.30      raeburn  5039:     my $classlist = &Apache::loncoursedata::get_classlist();
1.1       raeburn  5040:     if (! defined($classlist)) {
1.143     bisitz   5041:         my $msg = '';
1.101     raeburn  5042:         if ($crstype eq 'Community') {
1.143     bisitz   5043:             $msg = &mt('There are no members currently enrolled.');
1.101     raeburn  5044:         } else {
1.143     bisitz   5045:             $msg = &mt('There are no students currently enrolled.');
1.101     raeburn  5046:         }
1.143     bisitz   5047:         $r->print('<p class="LC_info">'.$msg."</p>\n");
1.30      raeburn  5048:     } else {
1.101     raeburn  5049:         &show_drop_list($r,$classlist,'nosort',$permission,$crstype);
1.1       raeburn  5050:     }
1.162     bisitz   5051:     $r->print('</form>');
1.1       raeburn  5052:     return;
                   5053: }
                   5054: 
                   5055: # ================================================================== Phase four
                   5056: 
1.11      raeburn  5057: sub update_user_list {
1.118     raeburn  5058:     my ($r,$context,$setting,$choice,$crstype) = @_;
1.11      raeburn  5059:     my $now = time;
1.1       raeburn  5060:     my $count=0;
1.101     raeburn  5061:     if ($context eq 'course') {
                   5062:         $crstype = &Apache::loncommon::course_type();
                   5063:     }
1.11      raeburn  5064:     my @changelist;
1.29      raeburn  5065:     if ($choice eq 'drop') {
                   5066:         @changelist = &Apache::loncommon::get_env_multiple('form.droplist');
                   5067:     } else {
1.11      raeburn  5068:         @changelist = &Apache::loncommon::get_env_multiple('form.actionlist');
                   5069:     }
                   5070:     my %result_text = ( ok    => { 'revoke'   => 'Revoked',
                   5071:                                    'delete'   => 'Deleted',
                   5072:                                    'reenable' => 'Re-enabled',
1.17      raeburn  5073:                                    'activate' => 'Activated',
                   5074:                                    'chgdates' => 'Changed Access Dates for',
1.118     raeburn  5075:                                    'chgsec'   => 'Changed section(s) for',
1.17      raeburn  5076:                                    'drop'     => 'Dropped',
1.11      raeburn  5077:                                  },
                   5078:                         error => {'revoke'    => 'revoking',
                   5079:                                   'delete'    => 'deleting',
                   5080:                                   'reenable'  => 're-enabling',
                   5081:                                   'activate'  => 'activating',
1.17      raeburn  5082:                                   'chgdates'  => 'changing access dates for',
                   5083:                                   'chgsec'    => 'changing section for',
                   5084:                                   'drop'      => 'dropping',
1.11      raeburn  5085:                                  },
                   5086:                       );
                   5087:     my ($startdate,$enddate);
                   5088:     if ($choice eq 'chgdates' || $choice eq 'reenable' || $choice eq 'activate') {
                   5089:         ($startdate,$enddate) = &get_dates_from_form();
                   5090:     }
                   5091:     foreach my $item (@changelist) {
1.118     raeburn  5092:         my ($role,$uname,$udom,$cid,$sec,$scope,$result,$type,$locktype,
                   5093:             @sections,$scopestem,$singlesec,$showsecs,$warn_singlesec,
1.174     raeburn  5094:             $nothingtodo,$keepnosection,$credits,$instsec);
1.17      raeburn  5095:         if ($choice eq 'drop') {
                   5096:             ($uname,$udom,$sec) = split(/:/,$item,-1);
                   5097:             $role = 'st';
                   5098:             $cid = $env{'request.course.id'};
                   5099:             $scopestem = '/'.$cid;
                   5100:             $scopestem =~s/\_/\//g;
                   5101:             if ($sec eq '') {
                   5102:                 $scope = $scopestem;
                   5103:             } else {
                   5104:                 $scope = $scopestem.'/'.$sec;
                   5105:             }
                   5106:         } elsif ($context eq 'course') {
1.174     raeburn  5107:             ($uname,$udom,$role,$sec,$type,$locktype,$credits,$instsec) =
                   5108:                 split(/\:/,$item,8);
                   5109:             $instsec = &unescape($instsec);
1.11      raeburn  5110:             $cid = $env{'request.course.id'};
                   5111:             $scopestem = '/'.$cid;
                   5112:             $scopestem =~s/\_/\//g;
                   5113:             if ($sec eq '') {
                   5114:                 $scope = $scopestem;
                   5115:             } else {
                   5116:                 $scope = $scopestem.'/'.$sec;
                   5117:             }
1.13      raeburn  5118:         } elsif ($context eq 'author') {
1.11      raeburn  5119:             ($uname,$udom,$role) = split(/\:/,$item,-1);
                   5120:             $scope = '/'.$env{'user.domain'}.'/'.$env{'user.name'};
                   5121:         } elsif ($context eq 'domain') {
                   5122:             if ($setting eq 'domain') {
                   5123:                 ($role,$uname,$udom) = split(/\:/,$item,-1);
                   5124:                 $scope = '/'.$env{'request.role.domain'}.'/';
1.13      raeburn  5125:             } elsif ($setting eq 'author') { 
1.11      raeburn  5126:                 ($uname,$udom,$role,$scope) = split(/\:/,$item);
                   5127:             } elsif ($setting eq 'course') {
1.174     raeburn  5128:                 ($uname,$udom,$role,$cid,$sec,$type,$locktype,$credits,$instsec) = 
                   5129:                     split(/\:/,$item,9);
                   5130:                 $instsec = &unescape($instsec);
1.11      raeburn  5131:                 $scope = '/'.$cid;
                   5132:                 $scope =~s/\_/\//g;
                   5133:                 if ($sec ne '') {
                   5134:                     $scope .= '/'.$sec;
                   5135:                 }
                   5136:             }
                   5137:         }
1.101     raeburn  5138:         my $plrole = &Apache::lonnet::plaintext($role,$crstype);
1.11      raeburn  5139:         my $start = $env{'form.'.$item.'_start'};
                   5140:         my $end = $env{'form.'.$item.'_end'};
1.17      raeburn  5141:         if ($choice eq 'drop') {
                   5142:             # drop students
                   5143:             $end = $now;
                   5144:             $type = 'manual';
                   5145:             $result =
1.52      raeburn  5146:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,$type,$locktype,$cid,'',$context);
1.17      raeburn  5147:         } elsif ($choice eq 'revoke') {
                   5148:             # revoke or delete user role
1.11      raeburn  5149:             $end = $now; 
                   5150:             if ($role eq 'st') {
                   5151:                 $result = 
1.174     raeburn  5152:                     &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,$type,$locktype,$cid,'',$context,$credits,$instsec);
1.11      raeburn  5153:             } else {
                   5154:                 $result = 
1.52      raeburn  5155:                     &Apache::lonnet::revokerole($udom,$uname,$scope,$role,
                   5156:                                                 '','',$context);
1.11      raeburn  5157:             }
                   5158:         } elsif ($choice eq 'delete') {
                   5159:             if ($role eq 'st') {
1.174     raeburn  5160:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$now,$start,$type,$locktype,$cid,'',$context,$credits,$instsec);
1.29      raeburn  5161:             }
                   5162:             $result =
                   5163:                 &Apache::lonnet::assignrole($udom,$uname,$scope,$role,$now,
1.52      raeburn  5164:                                             $start,1,'',$context);
1.11      raeburn  5165:         } else {
                   5166:             #reenable, activate, change access dates or change section
                   5167:             if ($choice ne 'chgsec') {
                   5168:                 $start = $startdate; 
                   5169:                 $end = $enddate;
                   5170:             }
                   5171:             if ($choice eq 'reenable') {
                   5172:                 if ($role eq 'st') {
1.174     raeburn  5173:                     $result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,$type,$locktype,$cid,'',$context,$credits,$instsec);
1.11      raeburn  5174:                 } else {
                   5175:                     $result = 
                   5176:                         &Apache::lonnet::assignrole($udom,$uname,$scope,$role,$end,
1.52      raeburn  5177:                                                     $now,'','',$context);
1.11      raeburn  5178:                 }
                   5179:             } elsif ($choice eq 'activate') {
                   5180:                 if ($role eq 'st') {
1.174     raeburn  5181:                     $result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,$type,$locktype,$cid,'',$context,$credits,$instsec);
1.11      raeburn  5182:                 } else {
                   5183:                     $result = &Apache::lonnet::assignrole($udom,$uname,$scope,$role,$end,
1.52      raeburn  5184:                                             $now,'','',$context);
1.11      raeburn  5185:                 }
                   5186:             } elsif ($choice eq 'chgdates') {
                   5187:                 if ($role eq 'st') {
1.174     raeburn  5188:                     $result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,$type,$locktype,$cid,'',$context,$credits,$instsec);
1.11      raeburn  5189:                 } else {
                   5190:                     $result = &Apache::lonnet::assignrole($udom,$uname,$scope,$role,$end,
1.52      raeburn  5191:                                                 $start,'','',$context);
1.11      raeburn  5192:                 }
                   5193:             } elsif ($choice eq 'chgsec') {
                   5194:                 my (@newsecs,$revresult,$nochg,@retained);
1.103     raeburn  5195:                 if (($role ne 'cc') && ($role ne 'co')) {
1.117     raeburn  5196:                     my @secs = sort(split(/,/,$env{'form.newsecs'}));
                   5197:                     if (@secs) {
                   5198:                         my %curr_groups = &Apache::longroup::coursegroups();
                   5199:                         foreach my $sec (@secs) {
                   5200:                             next if (($sec =~ /\W/) || ($sec eq 'none') ||
                   5201:                             (exists($curr_groups{$sec})));
                   5202:                             push(@newsecs,$sec);
                   5203:                         }
                   5204:                     }
1.11      raeburn  5205:                 }
                   5206:                 # remove existing section if not to be retained.   
1.118     raeburn  5207:                 if (!$env{'form.retainsec'} || ($role eq 'st')) {
1.11      raeburn  5208:                     if ($sec eq '') {
                   5209:                         if (@newsecs == 0) {
1.118     raeburn  5210:                             $result = 'ok';
1.11      raeburn  5211:                             $nochg = 1;
1.118     raeburn  5212:                             $nothingtodo = 1;
1.40      raeburn  5213:                         } else {
                   5214:                             $revresult =
                   5215:                                 &Apache::lonnet::revokerole($udom,$uname,
1.52      raeburn  5216:                                                             $scope,$role,
                   5217:                                                             '','',$context);
1.40      raeburn  5218:                         } 
1.11      raeburn  5219:                     } else {
1.28      raeburn  5220:                         if (@newsecs > 0) {
                   5221:                             if (grep(/^\Q$sec\E$/,@newsecs)) {
                   5222:                                 push(@retained,$sec);
                   5223:                             } else {
                   5224:                                 $revresult =
                   5225:                                     &Apache::lonnet::revokerole($udom,$uname,
1.52      raeburn  5226:                                                                 $scope,$role,
                   5227:                                                                 '','',$context);
1.28      raeburn  5228:                             }
                   5229:                         } else {
1.11      raeburn  5230:                             $revresult =
1.28      raeburn  5231:                                 &Apache::lonnet::revokerole($udom,$uname,
1.52      raeburn  5232:                                                             $scope,$role,
                   5233:                                                             '','',$context);
1.11      raeburn  5234:                         }
                   5235:                     }
                   5236:                 } else {
1.28      raeburn  5237:                     if ($sec eq '') {
                   5238:                         $nochg = 1;
1.118     raeburn  5239:                         $keepnosection = 1;
                   5240:                     } else {
1.28      raeburn  5241:                         push(@retained,$sec);
                   5242:                     }
1.11      raeburn  5243:                 }
                   5244:                 # add new sections
1.118     raeburn  5245:                 my (@diffs,@shownew);
                   5246:                 if (@retained) {
                   5247:                     @diffs = &Apache::loncommon::compare_arrays(\@retained,\@newsecs);
                   5248:                 } else {
                   5249:                     @diffs = @newsecs;
                   5250:                 }
1.11      raeburn  5251:                 if (@newsecs == 0) {
1.118     raeburn  5252:                     if ($nochg) {
                   5253:                         $result = 'ok';
                   5254:                         $nothingtodo = 1;
                   5255:                     } else {
1.28      raeburn  5256:                         if ($role eq 'st') {
                   5257:                             $result = 
1.174     raeburn  5258:                                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,undef,$end,$start,$type,$locktype,$cid,'',$context,$credits,$instsec);
1.28      raeburn  5259:                         } else {
                   5260:                             my $newscope = $scopestem;
1.52      raeburn  5261:                             $result = &Apache::lonnet::assignrole($udom,$uname,$newscope,$role,$end,$start,'','',$context);
1.11      raeburn  5262:                         }
                   5263:                     }
1.118     raeburn  5264:                     $showsecs = &mt('No section');
                   5265:                 } elsif (@diffs == 0) {
                   5266:                     $result = 'ok';
                   5267:                     $nothingtodo = 1;
1.11      raeburn  5268:                 } else {
1.118     raeburn  5269:                     foreach my $newsec (@newsecs) {
1.11      raeburn  5270:                         if (!grep(/^\Q$newsec\E$/,@retained)) {
                   5271:                             if ($role eq 'st') {
1.174     raeburn  5272:                                 $result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$newsec,$end,$start,$type,$locktype,$cid,'',$context,$credits,$instsec);
1.118     raeburn  5273:                                 if (@newsecs > 1) {
                   5274:                                     my $showsingle; 
                   5275:                                     if ($newsec eq '') {
                   5276:                                         $showsingle = &mt('No section');
                   5277:                                     } else {
                   5278:                                         $showsingle = $newsec;
                   5279:                                     }
                   5280:                                     if ($crstype eq 'Community') {
                   5281:                                         $warn_singlesec = &mt('Although more than one section was indicated, a role was only added for the first section - [_1], as each community member may only be in one section at a time.','<i>'.$showsingle.'</i>');
                   5282:                                     } else { 
                   5283:                                         $warn_singlesec = &mt('Although more than one section was indicated, a role was only added for the first section - [_1], as each student may only be in one section of a course at a time.','<i>'.$showsingle.'</i>');
                   5284:                                     }
                   5285:                                     $showsecs = $showsingle; 
                   5286:                                     last;
                   5287:                                 } else {
                   5288:                                     if ($newsec eq '') {
                   5289:                                         $showsecs = &mt('No section');
                   5290:                                     } else {
                   5291:                                         $showsecs = $newsec;
                   5292:                                     }
                   5293:                                 }
1.11      raeburn  5294:                             } else {
                   5295:                                 my $newscope = $scopestem;
                   5296:                                 if ($newsec ne '') {
                   5297:                                    $newscope .= '/'.$newsec;
1.118     raeburn  5298:                                    push(@shownew,$newsec); 
1.11      raeburn  5299:                                 }
                   5300:                                 $result = &Apache::lonnet::assignrole($udom,$uname,
                   5301:                                                         $newscope,$role,$end,$start);
1.118     raeburn  5302:                                 
1.11      raeburn  5303:                             }
                   5304:                         }
                   5305:                     }
                   5306:                 }
1.118     raeburn  5307:                 unless ($role eq 'st') {
                   5308:                     unless ($showsecs) {
                   5309:                         my @tolist = sort(@shownew,@retained);
                   5310:                         if ($keepnosection) {
                   5311:                             push(@tolist,&mt('No section'));
                   5312:                         }
                   5313:                         $showsecs = join(', ',@tolist);
                   5314:                     }
                   5315:                 }
1.11      raeburn  5316:             }
                   5317:         }
1.17      raeburn  5318:         my $extent = $scope;
                   5319:         if ($choice eq 'drop' || $context eq 'course') {
                   5320:             my ($cnum,$cdom,$cdesc) = &get_course_identity($cid);
                   5321:             if ($cdesc) {
                   5322:                 $extent = $cdesc;
                   5323:             }
                   5324:         }
1.1       raeburn  5325:         if ($result eq 'ok' || $result eq 'ok:') {
1.118     raeburn  5326:             my $dates;
                   5327:             if (($choice eq 'chgsec') || ($choice eq 'chgdates')) {
                   5328:                 $dates = &dates_feedback($start,$end,$now);
                   5329:             }
                   5330:             if ($choice eq 'chgsec') {
                   5331:                 if ($nothingtodo) {
                   5332:                     $r->print(&mt("Section assignment for role of '[_1]' in [_2] for '[_3]' unchanged.",$plrole,$extent,'<i>'.
                   5333:                           &Apache::loncommon::plainname($uname,$udom).
                   5334:                           '</i>').' ');
                   5335:                     if ($sec eq '') {
                   5336:                         $r->print(&mt('[_1]No section[_2] - [_3]','<b>','</b>',$dates));
                   5337:                     } else {
                   5338:                         $r->print(&mt('Section(s): [_1] - [_2]',
                   5339:                                       '<b>'.$showsecs.'</b>',$dates));
                   5340:                     }
                   5341:                     $r->print('<br />');
                   5342:                 } else {
                   5343:                     $r->print(&mt("$result_text{'ok'}{$choice} role of '[_1]' in [_2] for '[_3]' to [_4] - [_5]",$plrole,$extent,
                   5344:                         '<i>'.&Apache::loncommon::plainname($uname,$udom).'</i>',
                   5345:                         '<b>'.$showsecs.'</b>',$dates).'<br />');
                   5346:                    $count ++;
                   5347:                }
                   5348:                if ($warn_singlesec) {
                   5349:                    $r->print('<div class="LC_warning">'.$warn_singlesec.'</div>');
                   5350:                }
                   5351:             } elsif ($choice eq 'chgdates') {
                   5352:                 $r->print(&mt("$result_text{'ok'}{$choice} role of '[_1]' in [_2] for '[_3]' - [_4]",$plrole,$extent, 
1.121     raeburn  5353:                       '<i>'.&Apache::loncommon::plainname($uname,$udom).'</i>',
1.118     raeburn  5354:                       $dates).'<br />');
                   5355:                $count ++;
                   5356:             } else {
                   5357:                 $r->print(&mt("$result_text{'ok'}{$choice} role of '[_1]' in [_2] for '[_3]'.",$plrole,$extent,
1.121     raeburn  5358:                       '<i>'.&Apache::loncommon::plainname($uname,$udom).'</i>').
1.118     raeburn  5359:                           '<br />');
                   5360:                 $count ++;
                   5361:             }
1.1       raeburn  5362:         } else {
                   5363:             $r->print(
1.118     raeburn  5364:                 &mt("Error $result_text{'error'}{$choice} [_1] in [_2] for '[_3]': [_4].",
                   5365:                     $plrole,$extent,
1.121     raeburn  5366:                     '<i>'.&Apache::loncommon::plainname($uname,$udom).'</i>',
1.118     raeburn  5367:                     $result).'<br />');
1.11      raeburn  5368:         }
                   5369:     }
1.32      raeburn  5370:     $r->print('<form name="studentform" method="post" action="/adm/createuser">'."\n");
1.33      raeburn  5371:     if ($choice eq 'drop') {
                   5372:         $r->print('<input type="hidden" name="action" value="listusers" />'."\n".
                   5373:                   '<input type="hidden" name="Status" value="Active" />'."\n".
                   5374:                   '<input type="hidden" name="showrole" value="st" />'."\n");
                   5375:     } else {
                   5376:         foreach my $item ('action','sortby','roletype','showrole','Status','secfilter','grpfilter') {
                   5377:             if ($env{'form.'.$item} ne '') {
                   5378:                 $r->print('<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.
                   5379:                           '" />'."\n");
                   5380:             }
1.32      raeburn  5381:         }
                   5382:     }
1.144     bisitz   5383:     $r->print('<p><b>'.&mt("$result_text{'ok'}{$choice} [quant,_1,user role,user roles,no user roles].",$count).'</b></p>');
1.11      raeburn  5384:     if ($count > 0) {
1.17      raeburn  5385:         if ($choice eq 'revoke' || $choice eq 'drop') {
1.74      bisitz   5386:             $r->print('<p>'.&mt('Re-enabling will re-activate data for the role.').'</p>');
1.11      raeburn  5387:         }
                   5388:         # Flush the course logs so reverse user roles immediately updated
1.126     raeburn  5389:         $r->register_cleanup(\&Apache::lonnet::flushcourselogs);
1.11      raeburn  5390:     }
                   5391:     if ($env{'form.makedatesdefault'}) {
                   5392:         if ($choice eq 'chgdates' || $choice eq 'reenable' || $choice eq 'activate') {
1.101     raeburn  5393:             $r->print(&make_dates_default($startdate,$enddate,$context,$crstype));
1.1       raeburn  5394:         }
                   5395:     }
1.33      raeburn  5396:     my $linktext = &mt('Display User Lists');
                   5397:     if ($choice eq 'drop') {
                   5398:         $linktext = &mt('Display current class roster');
                   5399:     }
1.144     bisitz   5400:     $r->print(
                   5401:         &Apache::lonhtmlcommon::actionbox(
                   5402:             ['<a href="javascript:document.studentform.submit()">'.$linktext.'</a>'])
                   5403:        .'</form>'."\n");
1.1       raeburn  5404: }
                   5405: 
1.118     raeburn  5406: sub dates_feedback {
                   5407:     my ($start,$end,$now) = @_;
                   5408:     my $dates;
                   5409:     if ($start < $now) {
                   5410:         if ($end == 0) {
1.147     bisitz   5411:             $dates = &mt('role(s) active now; no end date');
1.118     raeburn  5412:         } elsif ($end > $now) {
                   5413:             $dates = &mt('role(s) active now; ends [_1].',&Apache::lonlocal::locallocaltime($end));
                   5414:         } else {
                   5415:             $dates = &mt('role(s) expired: [_1].',&Apache::lonlocal::locallocaltime($end));
                   5416:         }
                   5417:      } else {
                   5418:         if ($end == 0 || $end > $now) {
                   5419:             $dates = &mt('future role(s); starts: [_1].',&Apache::lonlocal::locallocaltime($start));
                   5420:         } else {
                   5421:             $dates = &mt('role(s) expired: [_1].',&Apache::lonlocal::locallocaltime($end));
                   5422:         }
                   5423:     }
                   5424:     return $dates;
                   5425: }
                   5426: 
1.8       raeburn  5427: sub classlist_drop {
1.29      raeburn  5428:     my ($scope,$uname,$udom,$now) = @_;
1.8       raeburn  5429:     my ($cdom,$cnum) = ($scope=~m{^/($match_domain)/($match_courseid)});
1.29      raeburn  5430:     if (&Apache::lonnet::is_course($cdom,$cnum)) {
1.8       raeburn  5431:         if (!&active_student_roles($cnum,$cdom,$uname,$udom)) {
1.63      raeburn  5432:             my %user;
                   5433:             my $result = &update_classlist($cdom,$cnum,$udom,$uname,\%user,$now);
1.8       raeburn  5434:             return &mt('Drop from classlist: [_1]',
                   5435:                        '<b>'.$result.'</b>').'<br />';
                   5436:         }
                   5437:     }
                   5438: }
                   5439: 
                   5440: sub active_student_roles {
                   5441:     my ($cnum,$cdom,$uname,$udom) = @_;
                   5442:     my %roles =
                   5443:         &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   5444:                                       ['future','active'],['st']);
                   5445:     return exists($roles{"$cnum:$cdom:st"});
                   5446: }
                   5447: 
1.1       raeburn  5448: sub section_check_js {
1.8       raeburn  5449:     my $groupslist= &get_groupslist();
1.170     damieng  5450:     my %js_lt = &Apache::lonlocal::texthash(
                   5451:         mayn   => 'may not be used as the name for a section, as it is a reserved word.',
                   5452:         plch   => 'Please choose a different section name.',
                   5453:         mnot   => 'may not be used as a section name, as it is the name of a course group.',
                   5454:         secn   => 'Section names and group names must be distinct. Please choose a different section name.',
                   5455:     );
                   5456:     &js_escape(\%js_lt);
1.1       raeburn  5457:     return <<"END";
                   5458: function validate(caller) {
1.9       raeburn  5459:     var groups = new Array($groupslist);
1.1       raeburn  5460:     var secname = caller.value;
                   5461:     if ((secname == 'all') || (secname == 'none')) {
1.170     damieng  5462:         alert("'"+secname+"' $js_lt{'mayn'}\\n$js_lt{'plch'}");
1.1       raeburn  5463:         return 'error';
                   5464:     }
                   5465:     if (secname != '') {
                   5466:         for (var k=0; k<groups.length; k++) {
                   5467:             if (secname == groups[k]) {
1.170     damieng  5468:                 alert("'"+secname+"' $js_lt{'mnot'}\\n$js_lt{'secn'}");
1.1       raeburn  5469:                 return 'error';
                   5470:             }
                   5471:         }
                   5472:     }
                   5473:     return 'ok';
                   5474: }
                   5475: END
                   5476: }
                   5477: 
                   5478: sub set_login {
                   5479:     my ($dom,$authformkrb,$authformint,$authformloc) = @_;
                   5480:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   5481:     my $response;
                   5482:     my ($authnum,%can_assign) =
                   5483:         &Apache::loncommon::get_assignable_auth($dom);
                   5484:     if ($authnum) {
                   5485:         $response = &Apache::loncommon::start_data_table();
                   5486:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
                   5487:             $response .= &Apache::loncommon::start_data_table_row().
                   5488:                          '<td>'.$authformkrb.'</td>'.
                   5489:                          &Apache::loncommon::end_data_table_row()."\n";
                   5490:         }
                   5491:         if ($can_assign{'int'}) {
                   5492:             $response .= &Apache::loncommon::start_data_table_row().
                   5493:                          '<td>'.$authformint.'</td>'.
                   5494:                          &Apache::loncommon::end_data_table_row()."\n"
                   5495:         }
                   5496:         if ($can_assign{'loc'}) {
                   5497:             $response .= &Apache::loncommon::start_data_table_row().
                   5498:                          '<td>'.$authformloc.'</td>'.
                   5499:                          &Apache::loncommon::end_data_table_row()."\n";
                   5500:         }
                   5501:         $response .= &Apache::loncommon::end_data_table();
                   5502:     }
                   5503:     return $response;
                   5504: }
                   5505: 
1.8       raeburn  5506: sub course_sections {
1.178     raeburn  5507:     my ($sections_count,$role,$current_sec,$disabled) = @_;
1.8       raeburn  5508:     my $output = '';
1.169     raeburn  5509:     my @sections = (sort {$a <=> $b} keys(%{$sections_count}));
1.29      raeburn  5510:     my $numsec = scalar(@sections);
1.92      bisitz   5511:     my $is_selected = ' selected="selected"';
1.29      raeburn  5512:     if ($numsec <= 1) {
1.178     raeburn  5513:         $output = '<select name="currsec_'.$role.'"'.$disabled.'>'."\n".
1.51      raeburn  5514:                   '  <option value="">'.&mt('Select').'</option>'."\n";
                   5515:         if ($current_sec eq 'none') {
                   5516:             $output .=       
                   5517:                   '  <option value=""'.$is_selected.'>'.&mt('No section').'</option>'."\n";
                   5518:         } else {
                   5519:             $output .=
1.29      raeburn  5520:                   '  <option value="">'.&mt('No section').'</option>'."\n";
1.51      raeburn  5521:         }
1.29      raeburn  5522:         if ($numsec == 1) {
1.51      raeburn  5523:             if ($current_sec eq $sections[0]) {
                   5524:                 $output .=
                   5525:                   '  <option value="'.$sections[0].'"'.$is_selected.'>'.$sections[0].'</option>'."\n";
                   5526:             } else {
                   5527:                 $output .=  
1.8       raeburn  5528:                   '  <option value="'.$sections[0].'" >'.$sections[0].'</option>'."\n";
1.51      raeburn  5529:             }
1.29      raeburn  5530:         }
1.8       raeburn  5531:     } else {
                   5532:         $output = '<select name="currsec_'.$role.'" ';
                   5533:         my $multiple = 4;
                   5534:         if (scalar(@sections) < 4) { $multiple = scalar(@sections); }
1.29      raeburn  5535:         if ($role eq 'st') {
1.178     raeburn  5536:             $output .= $disabled.'>'."\n".
1.51      raeburn  5537:                        '  <option value="">'.&mt('Select').'</option>'."\n";
                   5538:             if ($current_sec eq 'none') {
                   5539:                 $output .= 
                   5540:                        '  <option value=""'.$is_selected.'>'.&mt('No section')."</option>\n";
                   5541:             } else {
                   5542:                 $output .=
1.29      raeburn  5543:                        '  <option value="">'.&mt('No section')."</option>\n";
1.51      raeburn  5544:             }
1.29      raeburn  5545:         } else {
1.178     raeburn  5546:             $output .= 'multiple="multiple" size="'.$multiple.'"'.$disabled.'>'."\n";
1.29      raeburn  5547:         }
1.8       raeburn  5548:         foreach my $sec (@sections) {
1.51      raeburn  5549:             if ($current_sec eq $sec) {
                   5550:                 $output .= '<option value="'.$sec.'"'.$is_selected.'>'.$sec."</option>\n";
                   5551:             } else {
                   5552:                 $output .= '<option value="'.$sec.'">'.$sec."</option>\n";
                   5553:             }
1.8       raeburn  5554:         }
                   5555:     }
                   5556:     $output .= '</select>';
                   5557:     return $output;
                   5558: }
                   5559: 
                   5560: sub get_groupslist {
                   5561:     my $groupslist;
                   5562:     my %curr_groups = &Apache::longroup::coursegroups();
                   5563:     if (%curr_groups) {
                   5564:         $groupslist = join('","',sort(keys(%curr_groups)));
                   5565:         $groupslist = '"'.$groupslist.'"';
                   5566:     }
1.11      raeburn  5567:     return $groupslist; 
1.8       raeburn  5568: }
                   5569: 
                   5570: sub setsections_javascript {
1.150     raeburn  5571:     my ($formname,$groupslist,$mode,$checkauth,$crstype,$showcredits) = @_;
1.28      raeburn  5572:     my ($checkincluded,$finish,$rolecode,$setsection_js);
                   5573:     if ($mode eq 'upload') {
                   5574:         $checkincluded = 'formname.name == "'.$formname.'"';
                   5575:         $finish = "return 'ok';";
                   5576:         $rolecode = "var role = formname.defaultrole.options[formname.defaultrole.selectedIndex].value;\n";
                   5577:     } elsif ($formname eq 'cu') {
1.150     raeburn  5578:         if (($crstype eq 'Course') && ($showcredits)) {
                   5579:             $checkincluded = "((role == 'st') && (formname.elements[i-2].checked == true)) || ((role != 'st') && (formname.elements[i-1].checked == true))";
                   5580:         } else {
                   5581:             $checkincluded = 'formname.elements[i-1].checked == true';
                   5582:         }
1.37      raeburn  5583:         if ($checkauth) {
                   5584:             $finish = "var authcheck = auth_check();\n".
                   5585:                       "   if (authcheck == 'ok') {\n".
                   5586:                       "       formname.submit();\n".
                   5587:                       "   }\n";
                   5588:         } else {
                   5589:             $finish = 'formname.submit()';
                   5590:         }
1.28      raeburn  5591:         $rolecode = "var match = str.split('_');
                   5592:                 var role = match[3];\n";
1.165     raeburn  5593:     } elsif (($formname eq 'enrollstudent') || ($formname eq 'selfenroll')) {
1.28      raeburn  5594:         $checkincluded = 'formname.name == "'.$formname.'"';
1.37      raeburn  5595:         if ($checkauth) {
                   5596:             $finish = "var authcheck = auth_check();\n".
                   5597:                       "   if (authcheck == 'ok') {\n".
                   5598:                       "       formname.submit();\n".
                   5599:                       "   }\n";
                   5600:         } else {
                   5601:             $finish = 'formname.submit()';
                   5602:         }
1.28      raeburn  5603:         $rolecode = "var match = str.split('_');
                   5604:                 var role = match[1];\n";
1.8       raeburn  5605:     } else {
1.28      raeburn  5606:         $checkincluded = 'formname.name == "'.$formname.'"'; 
1.8       raeburn  5607:         $finish = "seccheck = 'ok';";
1.28      raeburn  5608:         $rolecode = "var match = str.split('_');
                   5609:                 var role = match[1];\n";
1.11      raeburn  5610:         $setsection_js = "var seccheck = 'alert';"; 
1.8       raeburn  5611:     }
                   5612:     my %alerts = &Apache::lonlocal::texthash(
                   5613:                     secd => 'Section designations do not apply to Course Coordinator roles.',
1.103     raeburn  5614:                     sedn => 'Section designations do not apply to Coordinator roles.',
1.8       raeburn  5615:                     accr => 'A course coordinator role will be added with access to all sections.',
1.103     raeburn  5616:                     acor => 'A coordinator role will be added with access to all sections',
1.8       raeburn  5617:                     inea => 'In each course, each user may only have one student role at a time.',
1.125     raeburn  5618:                     inco => 'In each community, each user may only have one member role at a time.',
1.145     raeburn  5619:                     youh => 'You had selected',
1.8       raeburn  5620:                     secs => 'sections.',
                   5621:                     plmo => 'Please modify your selections so they include no more than one section.',
                   5622:                     mayn => 'may not be used as the name for a section, as it is a reserved word.',
                   5623:                     plch => 'Please choose a different section name.',
                   5624:                     mnot => 'may not be used as a section name, as it is the name of a course group.',
                   5625:                     secn => 'Section names and group names must be distinct. Please choose a different section name.',
1.113     raeburn  5626:                     nonw => 'Section names may only contain letters or numbers.',
1.170     damieng  5627:                  );
                   5628:     &js_escape(\%alerts);
1.8       raeburn  5629:     $setsection_js .= <<"ENDSECCODE";
                   5630: 
1.103     raeburn  5631: function setSections(formname,crstype) {
1.8       raeburn  5632:     var re1 = /^currsec_/;
1.113     raeburn  5633:     var re2 =/\\W/;
1.115     raeburn  5634:     var trimleading = /^\\s+/;
                   5635:     var trimtrailing = /\\s+\$/;
1.8       raeburn  5636:     var groups = new Array($groupslist);
                   5637:     for (var i=0;i<formname.elements.length;i++) {
                   5638:         var str = formname.elements[i].name;
1.168     raeburn  5639:         if (typeof(str) === "undefined") {
                   5640:             continue;
                   5641:         }
1.8       raeburn  5642:         var checkcurr = str.match(re1);
                   5643:         if (checkcurr != null) {
1.115     raeburn  5644:             var num = i;
1.150     raeburn  5645:             $rolecode
1.8       raeburn  5646:             if ($checkincluded) {
1.103     raeburn  5647:                 if (role == 'cc' || role == 'co') {
                   5648:                     if (role == 'cc') {
                   5649:                         alert("$alerts{'secd'}\\n$alerts{'accr'}");
                   5650:                     } else {
                   5651:                         alert("$alerts{'sedn'}\\n$alerts{'acor'}");
                   5652:                     }
                   5653:                 } else {
1.8       raeburn  5654:                     var sections = '';
                   5655:                     var numsec = 0;
1.115     raeburn  5656:                     var fromexisting = new Array();
                   5657:                     for (var j=0; j<formname.elements[num].length; j++) {
                   5658:                         if (formname.elements[num].options[j].selected == true ) {
                   5659:                             var addsec = formname.elements[num].options[j].value;
1.119     raeburn  5660:                             if ((addsec != "") && (addsec != null)) {
1.115     raeburn  5661:                                 fromexisting.push(addsec);
1.8       raeburn  5662:                                 if (numsec == 0) {
1.115     raeburn  5663:                                     sections = addsec;
                   5664:                                 } else {
                   5665:                                     sections = sections + "," +  addsec;
1.8       raeburn  5666:                                 }
1.115     raeburn  5667:                                 numsec ++;
1.8       raeburn  5668:                             }
                   5669:                         }
                   5670:                     }
1.115     raeburn  5671:                     var newsecs = formname.elements[num+1].value;
1.113     raeburn  5672:                     var validsecs = new Array();
1.115     raeburn  5673:                     var validsecstr = '';
1.113     raeburn  5674:                     var badsecs = new Array();
1.8       raeburn  5675:                     if (newsecs != null && newsecs != "") {
1.115     raeburn  5676:                         var numsplit;
                   5677:                         if (newsecs.indexOf(',') == -1) {
                   5678:                             numsplit = new Array(newsecs);
                   5679:                         } else {
                   5680:                             numsplit = newsecs.split(/,/g);
                   5681:                         }
1.117     raeburn  5682:                         for (var m=0; m<numsplit.length; m++) {
                   5683:                             var newsec = numsplit[m];
1.115     raeburn  5684:                             newsec = newsec.replace(trimleading,'');
                   5685:                             newsec = newsec.replace(trimtrailing,'');
                   5686:                             if (re2.test(newsec) == true) {
                   5687:                                 badsecs.push(newsec);
1.113     raeburn  5688:                             } else {
1.115     raeburn  5689:                                 if (newsec != '') {
                   5690:                                     var isnew = 1;
                   5691:                                     if (fromexisting != null) {
1.117     raeburn  5692:                                         for (var n=0; n<fromexisting.length; n++) {
                   5693:                                             if (newsec == fromexisting[n]) {
1.115     raeburn  5694:                                                 isnew = 0;
                   5695:                                             }
                   5696:                                         }
                   5697:                                     }
                   5698:                                     if (isnew == 1) {
                   5699:                                         validsecs.push(newsec);
                   5700:                                     }
                   5701:                                 }
1.113     raeburn  5702:                             }
                   5703:                         }
                   5704:                         if (badsecs.length > 0) {
                   5705:                             alert("$alerts{'nonw'}\\n$alerts{'plch'}");
                   5706:                             return;
                   5707:                         }
                   5708:                         numsec = numsec + validsecs.length;
1.8       raeburn  5709:                     }
                   5710:                     if ((role == 'st') && (numsec > 1)) {
1.103     raeburn  5711:                         if (crstype == 'Community') {
                   5712:                             alert("$alerts{'inea'} $alerts{'youh'} "+numsec+" $alerts{'secs'}\\n$alerts{'plmo'}");
                   5713:                         } else {
                   5714:                             alert("$alerts{'inco'} $alerts{'youh'} "+numsec+" $alerts{'secs'}\\n$alerts{'plmo'}");
                   5715:                         }
1.8       raeburn  5716:                         return;
1.115     raeburn  5717:                     } else {
                   5718:                         if (validsecs != null) {
                   5719:                             for (var j=0; j<validsecs.length; j++) {
                   5720:                                 if (validsecstr == '' || validsecstr == null) {
                   5721:                                     validsecstr = validsecs[j];
                   5722:                                 } else {
                   5723:                                     validsecstr += ','+validsecs[j];
                   5724:                                 }
                   5725:                                 if ((validsecs[j] == 'all') ||
                   5726:                                     (validsecs[j] == 'none')) {
                   5727:                                     alert("'"+validsecs[j]+"' $alerts{'mayn'}\\n$alerts{'plch'}");
1.8       raeburn  5728:                                     return;
                   5729:                                 }
                   5730:                                 for (var k=0; k<groups.length; k++) {
1.115     raeburn  5731:                                     if (validsecs[j] == groups[k]) {
                   5732:                                         alert("'"+validsecs[j]+"' $alerts{'mnot'}\\n$alerts{'secn'}");
1.8       raeburn  5733:                                         return;
                   5734:                                     }
                   5735:                                 }
                   5736:                             }
                   5737:                         }
                   5738:                     }
1.115     raeburn  5739:                     if ((validsecstr != '') && (validsecstr != null)) {
1.117     raeburn  5740:                         if ((sections == '') || (sections == null)) {
                   5741:                             sections = validsecstr;
                   5742:                         } else {
1.115     raeburn  5743:                             sections = sections + "," + validsecstr;
                   5744:                         }
                   5745:                     }
                   5746:                     formname.elements[num+2].value = sections;
1.8       raeburn  5747:                 }
                   5748:             }
                   5749:         }
                   5750:     }
                   5751:     $finish
                   5752: }
                   5753: ENDSECCODE
1.11      raeburn  5754:     return $setsection_js; 
1.8       raeburn  5755: }
                   5756: 
1.15      raeburn  5757: sub can_create_user {
                   5758:     my ($dom,$context,$usertype) = @_;
                   5759:     my %domconf = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   5760:     my $cancreate = 1;
1.28      raeburn  5761:     if (&Apache::lonnet::allowed('mau',$dom)) {
                   5762:         return $cancreate;
1.178     raeburn  5763:     } elsif ($context eq 'domain') {
                   5764:         $cancreate = 0;
                   5765:         return $cancreate;
1.28      raeburn  5766:     }
1.15      raeburn  5767:     if (ref($domconf{'usercreation'}) eq 'HASH') {
                   5768:         if (ref($domconf{'usercreation'}{'cancreate'}) eq 'HASH') {
1.100     raeburn  5769:             if ($context eq 'course' || $context eq 'author' || $context eq 'requestcrs') {
1.15      raeburn  5770:                 my $creation = $domconf{'usercreation'}{'cancreate'}{$context};
                   5771:                 if ($creation eq 'none') {
                   5772:                     $cancreate = 0;
                   5773:                 } elsif ($creation ne 'any') {
                   5774:                     if (defined($usertype)) {
                   5775:                         if ($creation ne $usertype) {
                   5776:                             $cancreate = 0;
                   5777:                         }
                   5778:                     }
                   5779:                 }
                   5780:             }
                   5781:         }
                   5782:     }
                   5783:     return $cancreate;
                   5784: }
                   5785: 
1.20      raeburn  5786: sub can_modify_userinfo {
                   5787:     my ($context,$dom,$fields,$userroles) = @_;
                   5788:     my %domconfig =
                   5789:        &Apache::lonnet::get_dom('configuration',['usermodification'],
                   5790:                                 $dom);
                   5791:     my %canmodify;
                   5792:     if (ref($fields) eq 'ARRAY') {
                   5793:         foreach my $field (@{$fields}) {
                   5794:             $canmodify{$field}  = 0;
                   5795:             if (&Apache::lonnet::allowed('mau',$dom)) {
                   5796:                 $canmodify{$field} = 1;
                   5797:             } else {
                   5798:                 if (ref($domconfig{'usermodification'}) eq 'HASH') {
                   5799:                     if (ref($domconfig{'usermodification'}{$context}) eq 'HASH') {
                   5800:                         if (ref($userroles) eq 'ARRAY') {
                   5801:                             foreach my $role (@{$userroles}) {
                   5802:                                 my $testrole;
1.60      raeburn  5803:                                 if ($context eq 'selfcreate') {
                   5804:                                     $testrole = $role;
1.20      raeburn  5805:                                 } else {
1.60      raeburn  5806:                                     if ($role =~ /^cr\//) {
                   5807:                                         $testrole = 'cr';
                   5808:                                     } else {
                   5809:                                         $testrole = $role;
                   5810:                                     }
1.20      raeburn  5811:                                 }
                   5812:                                 if (ref($domconfig{'usermodification'}{$context}{$testrole}) eq 'HASH') {
                   5813:                                     if ($domconfig{'usermodification'}{$context}{$testrole}{$field}) {
                   5814:                                         $canmodify{$field} = 1;
                   5815:                                         last;
                   5816:                                     }
                   5817:                                 }
                   5818:                             }
                   5819:                         } else {
                   5820:                             foreach my $key (keys(%{$domconfig{'usermodification'}{$context}})) {
                   5821:                                 if (ref($domconfig{'usermodification'}{$context}{$key}) eq 'HASH') {
                   5822:                                     if ($domconfig{'usermodification'}{$context}{$key}{$field}) {
                   5823:                                         $canmodify{$field} = 1;
                   5824:                                         last;
                   5825:                                     }
                   5826:                                 }
                   5827:                             }
                   5828:                         }
                   5829:                     }
                   5830:                 } elsif ($context eq 'course') {
                   5831:                     if (ref($userroles) eq 'ARRAY') {
                   5832:                         if (grep(/^st$/,@{$userroles})) {
                   5833:                             $canmodify{$field} = 1;
                   5834:                         }
                   5835:                     } else {
                   5836:                         $canmodify{$field} = 1;
                   5837:                     }
                   5838:                 }
                   5839:             }
                   5840:         }
                   5841:     }
                   5842:     return %canmodify;
                   5843: }
                   5844: 
1.18      raeburn  5845: sub check_usertype {
1.134     raeburn  5846:     my ($dom,$uname,$rules,$curr_rules,$got_rules) = @_;
1.18      raeburn  5847:     my $usertype;
1.134     raeburn  5848:     if ((ref($got_rules) eq 'HASH') && (ref($curr_rules) eq 'HASH')) {
                   5849:         if (!$got_rules->{$dom}) {
                   5850:             my %domconfig = &Apache::lonnet::get_dom('configuration',
                   5851:                                               ['usercreation'],$dom);
                   5852:             if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   5853:                 foreach my $item ('username','id') {
                   5854:                     if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   5855:                         $curr_rules->{$dom}{$item} =
                   5856:                                 $domconfig{'usercreation'}{$item.'_rule'};
                   5857:                     }
                   5858:                 }
                   5859:             }
                   5860:             $got_rules->{$dom} = 1;
                   5861:         }
                   5862:         if (ref($rules) eq 'HASH') {
                   5863:             my @user_rules;
                   5864:             if (ref($curr_rules->{$dom}{'username'}) eq 'ARRAY') {
                   5865:                 foreach my $rule (keys(%{$rules})) {
                   5866:                     if (grep(/^\Q$rule\E/,@{$curr_rules->{$dom}{'username'}})) {
                   5867:                         push(@user_rules,$rule);
                   5868:                     }
                   5869:                 } 
                   5870:             }
                   5871:             if (@user_rules > 0) {
                   5872:                 my %rule_check = &Apache::lonnet::inst_rulecheck($dom,$uname,undef,'username',\@user_rules);
                   5873:                 if (keys(%rule_check) > 0) {
                   5874:                     $usertype = 'unofficial';
                   5875:                     foreach my $item (keys(%rule_check)) {
                   5876:                         if ($rule_check{$item}) {
                   5877:                             $usertype = 'official';
                   5878:                             last;
                   5879:                         }
1.18      raeburn  5880:                     }
                   5881:                 }
                   5882:             }
                   5883:         }
                   5884:     }
                   5885:     return $usertype;
                   5886: }
                   5887: 
1.17      raeburn  5888: sub roles_by_context {
1.101     raeburn  5889:     my ($context,$custom,$crstype) = @_;
1.17      raeburn  5890:     my @allroles;
                   5891:     if ($context eq 'course') {
1.99      raeburn  5892:         @allroles = ('st');
                   5893:         if ($env{'request.role'} =~ m{^dc\./}) {
                   5894:             push(@allroles,'ad');
                   5895:         }
1.101     raeburn  5896:         push(@allroles,('ta','ep','in'));
                   5897:         if ($crstype eq 'Community') {
                   5898:             push(@allroles,'co');
                   5899:         } else {
                   5900:             push(@allroles,'cc');
                   5901:         }
1.17      raeburn  5902:         if ($custom) {
                   5903:             push(@allroles,'cr');
                   5904:         }
                   5905:     } elsif ($context eq 'author') {
                   5906:         @allroles = ('ca','aa');
                   5907:     } elsif ($context eq 'domain') {
1.182     raeburn  5908:         @allroles = ('li','ad','dg','dh','da','sc','au','dc');
1.17      raeburn  5909:     }
                   5910:     return @allroles;
                   5911: }
                   5912: 
1.16      raeburn  5913: sub get_permission {
1.101     raeburn  5914:     my ($context,$crstype) = @_;
1.16      raeburn  5915:     my %permission;
                   5916:     if ($context eq 'course') {
1.17      raeburn  5917:         my $custom = 1;
1.101     raeburn  5918:         my @allroles = &roles_by_context($context,$custom,$crstype);
1.17      raeburn  5919:         foreach my $role (@allroles) {
                   5920:             if (&Apache::lonnet::allowed('c'.$role,$env{'request.course.id'})) {
                   5921:                 $permission{'cusr'} = 1;
                   5922:                 last;
                   5923:             }
1.16      raeburn  5924:         }
                   5925:         if (&Apache::lonnet::allowed('ccr',$env{'request.course.id'})) {
                   5926:             $permission{'custom'} = 1;
                   5927:         }
                   5928:         if (&Apache::lonnet::allowed('vcl',$env{'request.course.id'})) {
                   5929:             $permission{'view'} = 1;
                   5930:         }
                   5931:         if (!$permission{'view'}) {
                   5932:             my $scope = $env{'request.course.id'}.'/'.$env{'request.course.sec'};
                   5933:             $permission{'view'} =  &Apache::lonnet::allowed('vcl',$scope);
                   5934:             if ($permission{'view'}) {
                   5935:                 $permission{'view_section'} = $env{'request.course.sec'};
                   5936:             }
                   5937:         }
1.17      raeburn  5938:         if (!$permission{'cusr'}) {
                   5939:             if ($env{'request.course.sec'} ne '') {
                   5940:                 my $scope = $env{'request.course.id'}.'/'.$env{'request.course.sec'};
                   5941:                 $permission{'cusr'} = (&Apache::lonnet::allowed('cst',$scope));
                   5942:                 if ($permission{'cusr'}) {
                   5943:                     $permission{'cusr_section'} = $env{'request.course.sec'};
                   5944:                 }
                   5945:             }
                   5946:         }
1.16      raeburn  5947:         if (&Apache::lonnet::allowed('mdg',$env{'request.course.id'})) {
                   5948:             $permission{'grp_manage'} = 1;
                   5949:         }
1.165     raeburn  5950:         if ($permission{'cusr'}) {
                   5951:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5952:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5953:             my %coursehash = (
                   5954:                 'internal.selfenrollmgrdc' => $env{'course.'.$env{'request.course.id'}.'.internal.selfenrollmgrdc'},
                   5955:                 'internal.selfenrollmgrcc' => $env{'course.'.$env{'request.course.id'}.'.internal.selfenrollmgrcc'},
                   5956:                 'internal.coursecode'      => $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'},
                   5957:                 'internal.textbook'        =>$env{'course.'.$env{'request.course.id'}.'.internal.textbook'},
                   5958:             );
                   5959:             my ($managed_by_cc,$managed_by_dc) = &selfenrollment_administration($cdom,$cnum,$crstype,\%coursehash);
                   5960:             if (ref($managed_by_cc) eq 'ARRAY') {
                   5961:                 if (@{$managed_by_cc}) {
                   5962:                     $permission{'selfenrolladmin'} = 1;
                   5963:                 }
                   5964:             }
                   5965:         }
1.180     raeburn  5966:         if ($env{'request.course.id'}) {
                   5967:             my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5968:             if (($user ne '') && ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq
                   5969:                                   $user)) {
                   5970:                 $permission{'owner'} = 1;
                   5971:             } elsif (($user ne '') && ($env{'course.'.$env{'request.course.id'}.'.internal.co-owners'} ne '')) {
                   5972:                 if (grep(/^\Q$user\E$/,split(/,/,$env{'course.'.$env{'request.course.id'}.'.internal.co-owners'}))) {
                   5973:                     $permission{'co-owner'} = 1;
                   5974:                 }
                   5975:             }
                   5976:         }
1.16      raeburn  5977:     } elsif ($context eq 'author') {
                   5978:         $permission{'cusr'} = &authorpriv($env{'user.name'},$env{'request.role.domain'});
                   5979:         $permission{'view'} = $permission{'cusr'};
                   5980:     } else {
1.17      raeburn  5981:         my @allroles = &roles_by_context($context);
                   5982:         foreach my $role (@allroles) {
1.28      raeburn  5983:             if (&Apache::lonnet::allowed('c'.$role,$env{'request.role.domain'})) {
                   5984:                 $permission{'cusr'} = 1;
1.17      raeburn  5985:                 last;
                   5986:             }
                   5987:         }
                   5988:         if (!$permission{'cusr'}) {
                   5989:             if (&Apache::lonnet::allowed('mau',$env{'request.role.domain'})) {
                   5990:                 $permission{'cusr'} = 1;
                   5991:             }
1.16      raeburn  5992:         }
                   5993:         if (&Apache::lonnet::allowed('ccr',$env{'request.role.domain'})) {
                   5994:             $permission{'custom'} = 1;
                   5995:         }
1.176     raeburn  5996:         if (&Apache::lonnet::allowed('vac',$env{'request.role.domain'})) {
                   5997:             $permission{'activity'} = 1;
                   5998:         }
1.178     raeburn  5999:         if (&Apache::lonnet::allowed('vur',$env{'request.role.domain'})) {
                   6000:             $permission{'view'} = 1;
                   6001:         }
1.180     raeburn  6002:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
                   6003:             $permission{'owner'} = 1;
                   6004:         }
1.16      raeburn  6005:     }
                   6006:     my $allowed = 0;
                   6007:     foreach my $perm (values(%permission)) {
                   6008:         if ($perm) { $allowed=1; last; }
                   6009:     }
                   6010:     return (\%permission,$allowed);
                   6011: }
                   6012: 
                   6013: # ==================================================== Figure out author access
                   6014: 
                   6015: sub authorpriv {
                   6016:     my ($auname,$audom)=@_;
                   6017:     unless ((&Apache::lonnet::allowed('cca',$audom.'/'.$auname))
                   6018:          || (&Apache::lonnet::allowed('caa',$audom.'/'.$auname))) { return ''; }    return 1;
                   6019: }
                   6020: 
1.27      raeburn  6021: sub roles_on_upload {
1.101     raeburn  6022:     my ($context,$setting,$crstype,%customroles) = @_;
1.27      raeburn  6023:     my (@possible_roles,@permitted_roles);
1.101     raeburn  6024:     @possible_roles = &curr_role_permissions($context,$setting,1,$crstype);
1.27      raeburn  6025:     foreach my $role (@possible_roles) {
                   6026:         if ($role eq 'cr') {
                   6027:             push(@permitted_roles,keys(%customroles));
                   6028:         } else {
                   6029:             push(@permitted_roles,$role);
                   6030:         }
                   6031:     }
1.42      raeburn  6032:     return @permitted_roles;
1.27      raeburn  6033: }
                   6034: 
1.17      raeburn  6035: sub get_course_identity {
                   6036:     my ($cid) = @_;
                   6037:     my ($cnum,$cdom,$cdesc);
                   6038:     if ($cid eq '') {
                   6039:         $cid = $env{'request.course.id'}
                   6040:     }
                   6041:     if ($cid ne '') {
                   6042:         $cnum = $env{'course.'.$cid.'.num'};
                   6043:         $cdom = $env{'course.'.$cid.'.domain'};
                   6044:         $cdesc = $env{'course.'.$cid.'.description'};
                   6045:         if ($cnum eq '' || $cdom eq '') {
                   6046:             my %coursehash =
                   6047:                 &Apache::lonnet::coursedescription($cid,{'one_time' => 1});
                   6048:             $cdom = $coursehash{'domain'};
                   6049:             $cnum = $coursehash{'num'};
                   6050:             $cdesc = $coursehash{'description'};
                   6051:         }
                   6052:     }
                   6053:     return ($cnum,$cdom,$cdesc);
                   6054: }
                   6055: 
1.19      raeburn  6056: sub dc_setcourse_js {
1.150     raeburn  6057:     my ($formname,$mode,$context,$showcredits) = @_;
1.37      raeburn  6058:     my ($dc_setcourse_code,$authen_check);
1.19      raeburn  6059:     my $cctext = &Apache::lonnet::plaintext('cc');
1.103     raeburn  6060:     my $cotext = &Apache::lonnet::plaintext('co');
1.19      raeburn  6061:     my %alerts = &sectioncheck_alerts();
                   6062:     my $role = 'role';
                   6063:     if ($mode eq 'upload') {
                   6064:         $role = 'courserole';
1.37      raeburn  6065:     } else {
                   6066:         $authen_check = &verify_authen($formname,$context);
1.19      raeburn  6067:     }
                   6068:     $dc_setcourse_code = (<<"SCRIPTTOP");
1.37      raeburn  6069: $authen_check
                   6070: 
1.19      raeburn  6071: function setCourse() {
                   6072:     var course = document.$formname.dccourse.value;
                   6073:     if (course != "") {
                   6074:         if (document.$formname.dcdomain.value != document.$formname.origdom.value) {
                   6075:             alert("$alerts{'curd'}");
                   6076:             return;
                   6077:         }
                   6078:         var userrole = document.$formname.$role.options[document.$formname.$role.selectedIndex].value
                   6079:         var section="";
                   6080:         var numsections = 0;
                   6081:         var newsecs = new Array();
                   6082:         for (var i=0; i<document.$formname.currsec.length; i++) {
                   6083:             if (document.$formname.currsec.options[i].selected == true ) {
                   6084:                 if (document.$formname.currsec.options[i].value != "" && document.$formname.currsec.options[i].value != null) {
                   6085:                     if (numsections == 0) {
                   6086:                         section = document.$formname.currsec.options[i].value
                   6087:                         numsections = 1;
                   6088:                     }
                   6089:                     else {
                   6090:                         section = section + "," +  document.$formname.currsec.options[i].value
                   6091:                         numsections ++;
                   6092:                     }
                   6093:                 }
                   6094:             }
                   6095:         }
                   6096:         if (document.$formname.newsec.value != "" && document.$formname.newsec.value != null) {
                   6097:             if (numsections == 0) {
                   6098:                 section = document.$formname.newsec.value
                   6099:             }
                   6100:             else {
                   6101:                 section = section + "," +  document.$formname.newsec.value
                   6102:             }
                   6103:             newsecs = document.$formname.newsec.value.split(/,/g);
                   6104:             numsections = numsections + newsecs.length;
                   6105:         }
                   6106:         if ((userrole == 'st') && (numsections > 1)) {
1.103     raeburn  6107:             if (document.$formname.crstype.value == 'Community') {
                   6108:                 alert("$alerts{'inco'}. $alerts{'youh'} "+numsections+" $alerts{'sect'}.\\n$alerts{'plsm'}.")
                   6109:             } else {
                   6110:                 alert("$alerts{'inea'}. $alerts{'youh'} "+numsections+" $alerts{'sect'}.\\n$alerts{'plsm'}.")
                   6111:             }
1.19      raeburn  6112:             return;
                   6113:         }
                   6114:         for (var j=0; j<newsecs.length; j++) {
                   6115:             if ((newsecs[j] == 'all') || (newsecs[j] == 'none')) {
                   6116:                 alert("'"+newsecs[j]+"' $alerts{'mayn'}.\\n$alerts{'plsc'}.");
                   6117:                 return;
                   6118:             }
                   6119:             if (document.$formname.groups.value != '') {
                   6120:                 var groups = document.$formname.groups.value.split(/,/g);
                   6121:                 for (var k=0; k<groups.length; k++) {
                   6122:                     if (newsecs[j] == groups[k]) {
1.103     raeburn  6123:                         if (document.$formname.crstype.value == 'Community') {
                   6124:                             alert("'"+newsecs[j]+"' $alerts{'mayc'}.\\n$alerts{'secn'}. $alerts{'plsc'}.");
                   6125:                         } else {
                   6126:                             alert("'"+newsecs[j]+"' $alerts{'mayt'}.\\n$alerts{'secn'}. $alerts{'plsc'}.");
                   6127:                         }
1.19      raeburn  6128:                         return;
                   6129:                     }
                   6130:                 }
                   6131:             }
                   6132:         }
                   6133:         if ((userrole == 'cc') && (numsections > 0)) {
                   6134:             alert("$alerts{'secd'} $cctext $alerts{'role'}.\\n$alerts{'accr'}.");
                   6135:             section = "";
                   6136:         }
1.103     raeburn  6137:         if ((userrole == 'co') && (numsections > 0)) {
                   6138:             alert("$alerts{'secd'} $cotext $alerts{'role'}.\\n$alerts{'accr'}.");
                   6139:             section = "";
                   6140:         }
1.19      raeburn  6141: SCRIPTTOP
                   6142:     if ($mode ne 'upload') {
1.150     raeburn  6143:         $dc_setcourse_code .= (<<"SCRIPTMID");
1.19      raeburn  6144:         var coursename = "_$env{'request.role.domain'}"+"_"+course+"_"+userrole
                   6145:         var numcourse = getIndex(document.$formname.dccourse);
                   6146:         if (numcourse == "-1") {
1.103     raeburn  6147:             if (document.$formname.type == 'Community') {
                   6148:                 alert("$alerts{'thwc'}");
                   6149:             } else {
                   6150:                 alert("$alerts{'thwa'}");
                   6151:             }
1.19      raeburn  6152:             return;
                   6153:         }
                   6154:         else {
                   6155:             document.$formname.elements[numcourse].name = "act"+coursename;
                   6156:             var numnewsec = getIndex(document.$formname.newsec);
                   6157:             if (numnewsec != "-1") {
                   6158:                 document.$formname.elements[numnewsec].name = "sec"+coursename;
                   6159:                 document.$formname.elements[numnewsec].value = section;
                   6160:             }
                   6161:             var numstart = getIndex(document.$formname.start);
                   6162:             if (numstart != "-1") {
                   6163:                 document.$formname.elements[numstart].name = "start"+coursename;
                   6164:             }
                   6165:             var numend = getIndex(document.$formname.end);
                   6166:             if (numend != "-1") {
                   6167:                 document.$formname.elements[numend].name = "end"+coursename
                   6168:             }
1.150     raeburn  6169: SCRIPTMID
                   6170:         if ($showcredits) {
                   6171:             $dc_setcourse_code .= <<ENDCRED;
                   6172:             var numcredits = getIndex(document.$formname.credits);
                   6173:             if (numcredits != "-1") {
                   6174:                 document.$formname.elements[numcredits].name = "credits"+coursename;
                   6175:             }
                   6176: ENDCRED
                   6177:         }
                   6178:         $dc_setcourse_code .= <<ENDSCRIPT; 
1.19      raeburn  6179:         }
                   6180:     }
1.37      raeburn  6181:     var authcheck = auth_check();
                   6182:     if (authcheck == 'ok') {
                   6183:         document.$formname.submit();
                   6184:     }
1.19      raeburn  6185: }
                   6186: ENDSCRIPT
                   6187:     } else {
                   6188:         $dc_setcourse_code .=  "
                   6189:         document.$formname.sections.value = section;
                   6190:     }
                   6191:     return 'ok';
                   6192: }
                   6193: ";
                   6194:     }
                   6195:     $dc_setcourse_code .= (<<"ENDSCRIPT");
                   6196: 
                   6197:     function getIndex(caller) {
                   6198:         for (var i=0;i<document.$formname.elements.length;i++) {
                   6199:             if (document.$formname.elements[i] == caller) {
                   6200:                 return i;
                   6201:             }
                   6202:         }
                   6203:         return -1;
                   6204:     }
                   6205: ENDSCRIPT
1.37      raeburn  6206:     return $dc_setcourse_code;
                   6207: }
                   6208: 
                   6209: sub verify_authen {
                   6210:     my ($formname,$context) = @_;
                   6211:     my %alerts = &authcheck_alerts();
                   6212:     my $finish = "return 'ok';";
                   6213:     if ($context eq 'author') {
                   6214:         $finish = "document.$formname.submit();";
                   6215:     }
                   6216:     my $outcome = <<"ENDSCRIPT";
                   6217: 
                   6218: function auth_check() {
                   6219:     var logintype;
                   6220:     if (document.$formname.login.length) {
                   6221:         if (document.$formname.login.length > 0) {
                   6222:             var loginpicked = 0;
                   6223:             for (var i=0; i<document.$formname.login.length; i++) {
                   6224:                 if (document.$formname.login[i].checked == true) {
                   6225:                     loginpicked = 1;
                   6226:                     logintype = document.$formname.login[i].value;
                   6227:                 }
                   6228:             }
                   6229:             if (loginpicked == 0) {
                   6230:                 alert("$alerts{'authen'}");
                   6231:                 return;
                   6232:             }
                   6233:         }
                   6234:     } else {
                   6235:         logintype = document.$formname.login.value;
                   6236:     }
                   6237:     if (logintype == 'nochange') {
                   6238:         return 'ok';
                   6239:     }
                   6240:     var argpicked = document.$formname.elements[logintype+'arg'].value;
                   6241:     if ((argpicked == null) || (argpicked == '') || (typeof argpicked == 'undefined')) {
                   6242:         var alertmsg = '';
                   6243:         switch (logintype) {
                   6244:             case 'krb':
                   6245:                 alertmsg = '$alerts{'krb'}';
                   6246:                 break;
                   6247:             case 'int':
                   6248:                 alertmsg = '$alerts{'ipass'}';
                   6249:             case 'fsys':
                   6250:                 alertmsg = '$alerts{'ipass'}';
                   6251:                 break;
                   6252:             case 'loc':
                   6253:                 alertmsg = '';
                   6254:                 break;
                   6255:             default:
                   6256:                 alertmsg = '';
                   6257:         }
                   6258:         if (alertmsg != '') {
                   6259:             alert(alertmsg);
                   6260:             return;
                   6261:         }
                   6262:     }
                   6263:     $finish
                   6264: }
                   6265: ENDSCRIPT
1.19      raeburn  6266: }
                   6267: 
                   6268: sub sectioncheck_alerts {
                   6269:     my %alerts = &Apache::lonlocal::texthash(
1.103     raeburn  6270:                     curd => 'You must select a course or community in the current domain',
1.19      raeburn  6271:                     inea => 'In each course, each user may only have one student role at a time',
1.103     raeburn  6272:                     inco => 'In each community, each user may only have one member role at a time', 
1.19      raeburn  6273:                     youh => 'You had selected',
                   6274:                     sect => 'sections',
                   6275:                     plsm => 'Please modify your selections so they include no more than one section',
                   6276:                     mayn => 'may not be used as the name for a section, as it is a reserved word',
                   6277:                     plsc => 'Please choose a different section name',
                   6278:                     mayt => 'may not be used as the name for a section, as it is the name of a course group',
1.103     raeburn  6279:                     mayc => 'may not be used as the name for a section, as it is the name of a community group',
1.19      raeburn  6280:                     secn => 'Section names and group names must be distinct',
                   6281:                     secd => 'Section designations do not apply to ',
                   6282:                     role => 'roles',
                   6283:                     accr => 'role will be added with access to all sections',
1.103     raeburn  6284:                     thwa => 'There was a problem with your course selection',
                   6285:                     thwc => 'There was a problem with your community selection',
1.19      raeburn  6286:                  );
1.170     damieng  6287:     &js_escape(\%alerts);
1.19      raeburn  6288:     return %alerts;
                   6289: }
1.17      raeburn  6290: 
1.37      raeburn  6291: sub authcheck_alerts {
                   6292:     my %alerts = 
                   6293:         &Apache::lonlocal::texthash(
                   6294:                     authen => 'You must choose an authentication type.',
                   6295:                     krb    => 'You need to specify the Kerberos domain.',
                   6296:                     ipass  => 'You need to specify the initial password.',
                   6297:         );
1.170     damieng  6298:     &js_escape(\%alerts);
1.37      raeburn  6299:     return %alerts;
                   6300: }
                   6301: 
1.141     raeburn  6302: sub is_courseowner {
                   6303:     my ($thiscourse,$courseowner) = @_;
                   6304:     if ($courseowner eq '') {
                   6305:         if ($env{'request.course.id'} eq $thiscourse) {
                   6306:             $courseowner = $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
                   6307:         }
                   6308:     }
                   6309:     if ($courseowner ne '') {
                   6310:         if ($courseowner eq $env{'user.name'}.':'.$env{'user.domain'}) {
                   6311:             return 1;
                   6312:         }
                   6313:     }
                   6314:     return;
                   6315: }
                   6316: 
1.165     raeburn  6317: sub get_selfenroll_titles {
                   6318:     my @row = ('types','registered','enroll_dates','access_dates','section',
                   6319:                'approval','limit');
                   6320:     my %lt = &Apache::lonlocal::texthash (
                   6321:                 types        => 'Users allowed to self-enroll',
                   6322:                 registered   => 'Registration status (official courses)' ,
                   6323:                 enroll_dates => 'Dates self-enrollment available',
                   6324:                 access_dates => 'Access dates for self-enrolling users',
                   6325:                 section      => "Self-enrolling users' section",
                   6326:                 approval     => 'Processing of requests',
                   6327:                 limit        => 'Enrollment limit',
                   6328:              );
                   6329:     return (\@row,\%lt);
                   6330: }
                   6331: 
                   6332: sub selfenroll_default_descs {
                   6333:     my %desc = (
                   6334:                  types => {
                   6335:                             dom => &mt('Course domain'),
                   6336:                             all => &mt('Any domain'),
                   6337:                             ''  => &mt('None'),
                   6338:                           },
                   6339:                  limit => {
                   6340:                             none         => &mt('No limit'),
                   6341:                             allstudents  => &mt('Limit by total students'),
                   6342:                             selfenrolled => &mt('Limit by total self-enrolled'),
                   6343:                           },
                   6344:                  approval => {
                   6345:                                 '0' => &mt('Processed automatically'),
                   6346:                                 '1' => &mt('Queued for approval'),
                   6347:                                 '2' => &mt('Queued, pending validation'),
                   6348:                              },
                   6349:                  registered => {
                   6350:                                  0 => 'No registration required',
                   6351:                                  1 => 'Registered students only',
                   6352:                                },
                   6353:                );
                   6354:     return %desc;
                   6355: }
                   6356: 
                   6357: sub selfenroll_validation_types {
                   6358:     my @items = ('url','fields','button','markup');
                   6359:     my %names =  &Apache::lonlocal::texthash (
                   6360:             url      => 'Web address of validation server/script',
                   6361:             fields   => 'Form fields to send to validator',
                   6362:             button   => 'Text for validation button',
                   6363:             markup   => 'Validation description (HTML)',
                   6364:     );
1.167     raeburn  6365:     my @fields = ('username','domain','uniquecode','course','coursetype','description');
1.165     raeburn  6366:     return (\@items,\%names,\@fields);
                   6367: }
                   6368: 
                   6369: sub get_extended_type {
                   6370:     my ($cdom,$cnum,$crstype,$current) = @_;
                   6371:     my $type = 'unofficial';
                   6372:     my %settings;
                   6373:     if (ref($current) eq 'HASH') {
                   6374:         %settings = %{$current};
                   6375:     } else {
                   6376:         %settings = &Apache::lonnet::get('environment',['internal.coursecode','internal.textbook'],$cdom,$cnum);
                   6377:     }
                   6378:     if ($crstype eq 'Community') {
                   6379:         $type = 'community';
1.173     raeburn  6380:     } elsif ($crstype eq 'Placement') {
                   6381:         $type = 'placement';
1.165     raeburn  6382:     } elsif ($settings{'internal.coursecode'}) {
                   6383:         $type = 'official';
                   6384:     } elsif ($settings{'internal.textbook'}) {
                   6385:         $type = 'textbook';
                   6386:     }
                   6387:     return $type;
                   6388: }
                   6389: 
                   6390: sub selfenrollment_administration {
                   6391:     my ($cdom,$cnum,$crstype,$coursehash) = @_;
                   6392:     my %settings;
                   6393:     if (ref($coursehash) eq 'HASH') {
                   6394:         %settings = %{$coursehash};
                   6395:     } else {
                   6396:         %settings = &Apache::lonnet::get('environment',
                   6397:                         ['internal.selfenrollmgrdc','internal.selfenrollmgrcc',
                   6398:                          'internal.coursecode','internal.textbook'],$cdom,$cnum);
                   6399:     }
                   6400:     my ($possconfigs) = &get_selfenroll_titles(); 
                   6401:     my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
                   6402:     my $selfenrolltype = &get_extended_type($cdom,$cnum,$crstype,\%settings);
                   6403: 
                   6404:     my (@in_course,@in_domain); 
                   6405:     if ($settings{'internal.selfenrollmgrcc'} ne '') {
                   6406:         @in_course = split(/,/,$settings{'internal.selfenrollmgrcc'}); 
                   6407:         my @diffs = &Apache::loncommon::compare_arrays($possconfigs,\@in_course);
                   6408:         unless (@diffs) {
                   6409:             return (\@in_course,\@in_domain);
                   6410:         }
                   6411:     }
                   6412:     if ($settings{'internal.selfenrollmgrdc'} ne '') {
                   6413:         my @in_domain = split(/,/,$settings{'internal.selfenrollmgrdc'});
                   6414:         my @diffs = &Apache::loncommon::compare_arrays(\@in_domain,$possconfigs);
                   6415:         unless (@diffs) {
                   6416:             return (\@in_course,\@in_domain);
                   6417:         }
                   6418:     }
                   6419:     my @combined = @in_course;
                   6420:     push(@combined,@in_domain);
                   6421:     my @diffs = &Apache::loncommon::compare_arrays(\@combined,$possconfigs); 
                   6422:     unless (@diffs) {
                   6423:         return (\@in_course,\@in_domain);
                   6424:     }
                   6425:     if ($domdefaults{$selfenrolltype.'selfenrolladmdc'} eq '') {
                   6426:         push(@in_course,@diffs);
                   6427:     } else {
                   6428:         my @defaultdc = split(/,/,$domdefaults{$selfenrolltype.'selfenrolladmdc'});
                   6429:         foreach my $item (@diffs) {
                   6430:             if (grep(/^\Q$item\E$/,@defaultdc)) {
                   6431:                 push(@in_domain,$item);
                   6432:             } else {
                   6433:                 push(@in_course,$item);
                   6434:             }
                   6435:         }
                   6436:     }
                   6437:     return (\@in_course,\@in_domain);
                   6438: }
                   6439: 
1.175     raeburn  6440: sub custom_role_header {
                   6441:     my ($context,$crstype,$templaterolerefs,$prefix) = @_;
                   6442:     my %lt = &Apache::lonlocal::texthash(
                   6443:                  sele => 'Select a Template',
                   6444:     );
                   6445:     my ($context_code,$button_code);
                   6446:     if ($context eq 'domain') {
                   6447:         $context_code = &custom_coursetype_switch($crstype,$prefix);
                   6448:     }
                   6449:     if (ref($templaterolerefs) eq 'ARRAY') {
                   6450:         foreach my $role (@{$templaterolerefs}) {
                   6451:             my $display = 'inline';
                   6452:             if (($context eq 'domain') && ($role eq 'co')) {
                   6453:                 $display = 'none';
                   6454:             }
                   6455:             $button_code .= &make_button_code($role,$crstype,$display,$prefix).' ';
                   6456:         }
                   6457:     }
                   6458:     return <<"END";
                   6459: <div class="LC_left_float">
                   6460: <fieldset>
                   6461: <legend>$lt{'sele'}</legend>
                   6462: $button_code
                   6463: </fieldset></div>
                   6464: $context_code
                   6465: <br clear="all" />
                   6466: END
                   6467: }
                   6468: 
                   6469: sub custom_coursetype_switch {
                   6470:     my ($crstype,$prefix) = @_;
                   6471:     my ($checkedcourse,$checkedcommunity);
                   6472:     if ($crstype eq 'Community') {
                   6473:         $checkedcommunity = ' checked="checked"';
                   6474:     } else {
                   6475:         $checkedcourse = ' checked="checked"';
                   6476:     }
                   6477:     my %lt = &Apache::lonlocal::texthash(
                   6478:         cont => 'Context',
                   6479:         cour => 'Course',
                   6480:         comm => 'Community',
                   6481:     );
                   6482:     return <<"END";
                   6483: <div class="LC_left_float">
                   6484: <fieldset>
                   6485: <legend>$lt{'cont'}</legend>
                   6486: <label>
                   6487: <input type="radio" name="${prefix}_custrolecrstype" value="Course"$checkedcourse onclick="javascript:customSwitchType('$prefix');" />
                   6488: $lt{'cour'}
                   6489: </label>&nbsp;&nbsp;
                   6490: <label>
                   6491: <input type="radio" name="${prefix}_custrolecrstype" value="Community"$checkedcommunity onclick="javascript:customSwitchType('$prefix');" />
                   6492: $lt{'comm'}
                   6493: </label>
                   6494: </fieldset>
                   6495: </div>
                   6496: END
                   6497: }
                   6498: 
                   6499: sub custom_role_table {
1.180     raeburn  6500:     my ($crstype,$full,$levels,$levelscurrent,$prefix,$add_class,$id) = @_;
1.175     raeburn  6501:     return unless ((ref($full) eq 'HASH') && (ref($levels) eq 'HASH') &&
                   6502:                    (ref($levelscurrent) eq 'HASH'));
                   6503:     my %lt=&Apache::lonlocal::texthash (
                   6504:                     'prv'  => "Privilege",
                   6505:                     'crl'  => "Course Level",
                   6506:                     'dml'  => "Domain Level",
                   6507:                     'ssl'  => "System Level");
                   6508:     my %cr = (
                   6509:                course => '_c',
                   6510:                domain => '_d',
                   6511:                system => '_s',
                   6512:              );
                   6513: 
1.180     raeburn  6514:     my $output=&Apache::loncommon::start_data_table($add_class,$id).
1.175     raeburn  6515:                &Apache::loncommon::start_data_table_header_row().
                   6516:                '<th>'.$lt{'prv'}.'</th><th>'.$lt{'crl'}.'</th><th>'.$lt{'dml'}.
                   6517:                '</th><th>'.$lt{'ssl'}.'</th>'.
                   6518:                &Apache::loncommon::end_data_table_header_row();
                   6519:     foreach my $priv (sort(keys(%{$full}))) {
                   6520:         my $privtext = &Apache::lonnet::plaintext($priv,$crstype);
                   6521:         $output .= &Apache::loncommon::start_data_table_row().
                   6522:                   '<td><span id="'.$prefix.$priv.'">'.$privtext.'</span></td>';
                   6523:         foreach my $type ('course','domain','system') {
                   6524:             if (($type eq 'system') && ($priv eq 'bre') && ($crstype eq 'Community')) {
                   6525:                 $output .= '<td>&nbsp;</td>';
                   6526:             } else {
                   6527:                 $output .= '<td>'.
                   6528:                   ($levels->{$type}{$priv}?'<input type="checkbox" id="'.$prefix.$priv.$cr{$type}.'"'.
                   6529:                   ' name="'.$prefix.$priv.$cr{$type}.'"'.
                   6530:                   ($levelscurrent->{$type}{$priv}?' checked="checked"':'').' />':'&nbsp;').
                   6531:                   '</td>';
                   6532:             }
                   6533:         }
                   6534:         $output .= &Apache::loncommon::end_data_table_row();
                   6535:     }
                   6536:     $output .= &Apache::loncommon::end_data_table();
                   6537:     return $output;
                   6538: }
                   6539: 
                   6540: sub custom_role_privs {
                   6541:     my ($privs,$full,$levels,$levelscurrent)= @_;
                   6542:     return unless ((ref($privs) eq 'HASH') && (ref($full) eq 'HASH') &&
                   6543:                    (ref($levels) eq 'HASH') && (ref($levelscurrent) eq 'HASH'));
                   6544:     my %cr = (
                   6545:                course => 'cr:c',
                   6546:                domain => 'cr:d',
                   6547:                system => 'cr:s',
                   6548:              );
                   6549:     foreach my $type ('course','domain','system') {
                   6550:         foreach my $item (split(/\:/,$Apache::lonnet::pr{$cr{$type}})) {
                   6551:             my ($priv,$restrict)=split(/\&/,$item);
                   6552:             if (!$restrict) { $restrict='F'; }
                   6553:             $levels->{$type}->{$priv}=$restrict;
                   6554:             if ($privs->{$type}=~/\:$priv/) {
                   6555:                 $levelscurrent->{$type}->{$priv}=1;
                   6556:             }
                   6557:             $full->{$priv}=1;
                   6558:         }
                   6559:     }
                   6560:     return;
                   6561: }
                   6562: 
                   6563: sub custom_template_roles {
                   6564:     my ($context,$crstype) = @_;
                   6565:     my @template_roles = ("in","ta","ep");
                   6566:     if (($context eq 'domain') || ($context eq 'domprefs')) {
                   6567:         push(@template_roles,"ad");
                   6568:     }
                   6569:     push(@template_roles,"st");
                   6570:     if ($context eq 'domain') {
                   6571:         unshift(@template_roles,('co','cc'));
                   6572:     } else {
                   6573:         if ($crstype eq 'Community') {
                   6574:             unshift(@template_roles,'co');
                   6575:         } else {
                   6576:             unshift(@template_roles,'cc');
                   6577:         }
                   6578:     }
                   6579:     return @template_roles;
                   6580: }
                   6581: 
                   6582: sub custom_roledefs_js {
                   6583:     my ($context,$crstype,$formname,$full,$templaterolesref,$jsback) = @_;
                   6584:     my $button_code = "\n";
                   6585:     my $head_script = "\n";
                   6586:     my (%roletitlestr,$rolenamestr);
                   6587:     my %role_titles = (
                   6588:                         Course    => [],
                   6589:                         Community => [],
                   6590:                       );
                   6591:     $head_script .= '<script type="text/javascript">'."\n"
                   6592:                    .'// <![CDATA['."\n";
                   6593:     if (ref($templaterolesref) eq 'ARRAY') {
                   6594:         if ($context eq 'domain') {
                   6595:             $rolenamestr = join("','",@{$templaterolesref});
                   6596:         }
                   6597:         foreach my $role (@{$templaterolesref}) {
                   6598:             $head_script .= &make_script_template($role,$crstype,$formname);
                   6599:             if ($context eq 'domain') {
                   6600:                 foreach my $type ('Course','Community') {
                   6601:                     push(@{$role_titles{$type}},&Apache::lonnet::plaintext($role,$type));
                   6602:                 }
                   6603:             }
                   6604:         }
                   6605:     }
                   6606:     if ($context eq 'domain') {
                   6607:         foreach my $type ('Course','Community') {
                   6608:             $roletitlestr{$type} = join("','",@{$role_titles{$type}});
                   6609:         }
                   6610:         my %pt = (
                   6611:             Community => {
                   6612:                            cst => &mt('Grant/revoke role of Member'),
                   6613:                            mdc => &mt('Edit community contents'),
                   6614:                            pch => &mt('Post discussion on community resources'),
                   6615:                            pfo => &mt('Print for other users and entire community'),
                   6616:                          },
                   6617:             Course    => {
                   6618:                            cst => &mt('Grant/revoke role of Student'),
                   6619:                            mdc => &mt('Edit course contents'),
                   6620:                            pch => &mt('Post discussion on course resources'),
                   6621:                            pfo => &mt('Print for other users and entire course'),
                   6622:                          },
                   6623:         );
                   6624:         $head_script .= <<"ENDJS";
                   6625: function customSwitchType(prefix) {
                   6626:     var privnames = new Array('cst','mdc','pch','pfo');
                   6627:     var privtxtcrs = new Array('$pt{Course}{cst}','$pt{Course}{mdc}','$pt{Course}{pch}','$pt{Course}{pfo}');
                   6628:     var privtxtcom = new Array('$pt{Community}{cst}','$pt{Community}{mdc}','$pt{Community}{pch}','$pt{Community}{pfo}');
                   6629:     var rolenames = new Array('$rolenamestr');
                   6630:     var rolescrs = new Array('$roletitlestr{Course}');
                   6631:     var rolescom = new Array('$roletitlestr{Community}');
                   6632:     var radio = prefix+'_custrolecrstype';
                   6633:     if (document.$formname.elements[radio].length > 1) {
                   6634:         for (var i=0; i<document.$formname.elements[radio].length; i++) {
                   6635:             if (document.$formname.elements[radio][i].checked) {
                   6636:                 if ((document.getElementById(prefix+'bre_s')) && (document.getElementById(prefix+'bro_s'))) {
                   6637:                     if (document.$formname.elements[radio][i].value == 'Community') {
                   6638:                         if (document.getElementById(prefix+'bre_s').checked) {
                   6639:                             document.getElementById(prefix+'bro_s').checked = true;
                   6640:                             document.getElementById(prefix+'bre_s').checked = false;
                   6641: 
                   6642:                         }
                   6643:                         document.getElementById(prefix+'bre_s').style.visibility = 'hidden';
                   6644:                     } else {
                   6645:                         document.getElementById(prefix+'bre_s').style.visibility = 'visible';
                   6646:                         if (document.getElementById(prefix+'bro_s').checked) {
                   6647:                             document.getElementById(prefix+'bre_s').checked = true;
                   6648:                             document.getElementById(prefix+'bro_s').checked = false;
                   6649:                         }
                   6650:                     }
                   6651:                 }
                   6652:                 for (var j=0; j<privnames.length; j++) {
                   6653:                     if (document.getElementById(prefix+privnames[j])) {
                   6654:                         if (document.getElementById(prefix+privnames[j])) {
                   6655:                             if (document.$formname.elements[radio][i].value == 'Course') {
                   6656:                                 document.getElementById(prefix+privnames[j]).innerHTML = privtxtcrs[j];
                   6657:                             } else {
                   6658:                                 document.getElementById(prefix+privnames[j]).innerHTML = privtxtcom[j];
                   6659:                             }
                   6660:                         }
                   6661:                     }
                   6662:                 }
                   6663:                 for (var j=0; j<rolenames.length; j++) {
                   6664:                     if (document.getElementById(prefix+rolenames[j])) {
                   6665:                         if (document.getElementById(prefix+rolenames[j])) {
                   6666:                             if (document.$formname.elements[radio][i].value == 'Course') {
                   6667:                                 document.getElementById(prefix+rolenames[j]).value = rolescrs[j];
                   6668:                                 if (rolenames[j] == 'cc') {
                   6669:                                     document.getElementById(prefix+rolenames[j]).style.display = 'inline';
                   6670:                                 }
                   6671:                                 if (rolenames[j] == 'co') {
                   6672:                                     document.getElementById(prefix+rolenames[j]).style.display = 'none';
                   6673:                                 }
                   6674:                             } else {
                   6675:                                 document.getElementById(prefix+rolenames[j]).value = rolescom[j];
                   6676:                                 if (rolenames[j] == 'cc') {
                   6677:                                     document.getElementById(prefix+rolenames[j]).style.display = 'none';
                   6678:                                 }
                   6679:                                 if (rolenames[j] == 'co') {
                   6680:                                     document.getElementById(prefix+rolenames[j]).style.display = 'inline';
                   6681:                                 }
                   6682:                             }
                   6683:                         }
                   6684:                     }
                   6685:                 }
                   6686:             }
                   6687:         }
                   6688:     }
                   6689:     return;
                   6690: }
                   6691: ENDJS
                   6692:     }
                   6693:     $head_script .= "\n".$jsback."\n"
                   6694:                    .'// ]]>'."\n"
                   6695:                    .'</script>'."\n";
                   6696:     return $head_script;
                   6697: }
                   6698: 
                   6699: # --------------------------------------------------------
                   6700: sub make_script_template {
                   6701:     my ($role,$crstype,$formname) = @_;
                   6702:     my $return_script = 'function set_'.$role.'(prefix) {'."\n";
                   6703:     my (%full_by_level,%role_priv);
                   6704:     foreach my $level ('c','d','s') {
                   6705:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:'.$level})) {
                   6706:             next if (($level eq 's') && ($crstype eq 'Community') && ($item eq 'bre&S'));
                   6707:             my ($priv,$restrict)=split(/\&/,$item);
                   6708:             $full_by_level{$level}{$priv}=1;
                   6709:         }
                   6710:         $role_priv{$level} = {};
                   6711:         my @temp = split(/:/,$Apache::lonnet::pr{$role.':'.$level});
                   6712:         foreach my $priv (@temp) {
                   6713:             my ($priv_item, $dummy) = split(/\&/,$priv);
                   6714:             $role_priv{$level}{$priv_item} = 1;
                   6715:         }
                   6716:     }
                   6717:     my %to_check = (
                   6718:                       c => ['c','d','s'],
                   6719:                       d => ['d','s'],
                   6720:                       s => ['s'],
                   6721:                    );
                   6722:     foreach my $level ('c','d','s') {
                   6723:         if (ref($full_by_level{$level}) eq 'HASH') {
                   6724:             foreach my $priv (keys(%{$full_by_level{$level}})) {
                   6725:                 my $value = 'false';
                   6726:                 if (ref($to_check{$level}) eq 'ARRAY') {
                   6727:                     foreach my $lett (@{$to_check{$level}}) {
                   6728:                         if (exists($role_priv{$lett}{$priv})) {
                   6729:                             $value = 'true';
                   6730:                             last;
                   6731:                         }
                   6732:                     }
                   6733:                     $return_script .= "document.$formname.elements[prefix+'".$priv."_".$level."'].checked = $value;\n";
                   6734:                 }
                   6735:             }
                   6736:         }
                   6737:     }
                   6738:     $return_script .= '}'."\n";
                   6739:     return ($return_script);
                   6740: }
                   6741: # ----------------------------------------------------------
                   6742: sub make_button_code {
                   6743:     my ($role,$crstype,$display,$prefix) = @_;
                   6744:     my $label = &Apache::lonnet::plaintext($role,$crstype);
                   6745:     my $button_code = '<input type="button" onclick="set_'.$role."('$prefix'".')" '.
                   6746:                       'id="'.$prefix.$role.'" value="'.$label.'" '.
                   6747:                       'style="display:'.$display.'" />';
                   6748:     return ($button_code);
                   6749: }
                   6750: 
                   6751: sub custom_role_update {
                   6752:     my ($rolename,$prefix) = @_;
                   6753: # ------------------------------------------------------- What can be assigned?
                   6754:     my %privs = (
                   6755:                       c => '',
                   6756:                       d => '',
                   6757:                       s => '',
                   6758:                     );
                   6759:     foreach my $level (keys(%privs)) {
                   6760:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:'.$level})) {
                   6761:             my ($priv,$restrict)=split(/\&/,$item);
                   6762:             if (!$restrict) { $restrict=''; }
                   6763:             if ($env{'form.'.$prefix.$priv.'_'.$level}) {
                   6764:                 $privs{$level} .=':'.$item;
                   6765:             }
                   6766:         }
                   6767:     }
                   6768:     return %privs;
                   6769: }
                   6770: 
1.180     raeburn  6771: sub adhoc_status_types {
                   6772:     my ($cdom,$context,$role,$selectedref,$othertitle,$usertypes,$types,$disabled) = @_;
                   6773:     my $output = &Apache::loncommon::start_data_table();
                   6774:     my $numinrow = 3;
                   6775:     my $rem;
                   6776:     if (ref($types) eq 'ARRAY') {
                   6777:         for (my $i=0; $i<@{$types}; $i++) {
                   6778:             if (defined($usertypes->{$types->[$i]})) {
                   6779:                 my $rem = $i%($numinrow);
                   6780:                 if ($rem == 0) {
                   6781:                     if ($i > 0) {
                   6782:                         $output .= &Apache::loncommon::end_data_table_row();
                   6783:                     }
                   6784:                     $output .= &Apache::loncommon::start_data_table_row();
                   6785:                 }
                   6786:                 my $check;
                   6787:                 if (ref($selectedref) eq 'ARRAY') {
                   6788:                     if (grep(/^\Q$types->[$i]\E$/,@{$selectedref})) {
                   6789:                         $check = ' checked="checked"';
                   6790:                     }
                   6791:                 }
                   6792:                 $output .= '<td>'.
                   6793:                            '<span class="LC_nobreak"><label>'.
                   6794:                            '<input type="checkbox" name="'.$context.$role.'_status" '.
                   6795:                            'value="'.$types->[$i].'"'.$check.$disabled.' />'.
                   6796:                            $usertypes->{$types->[$i]}.'</label></span></td>';
                   6797:             }
                   6798:         }
                   6799:         $rem = @{$types}%($numinrow);
                   6800:     }
                   6801:     my $colsleft = $numinrow - $rem;
                   6802:     if (($rem == 0) && (@{$types} > 0)) {
                   6803:         $output .= &Apache::loncommon::start_data_table_row();
                   6804:     }
                   6805:     if ($colsleft > 1) {
                   6806:         $output .= '<td colspan="'.$colsleft.'">';
                   6807:     } else {
                   6808:         $output .= '<td>';
                   6809:     }
                   6810:     my $defcheck;
                   6811:     if (ref($selectedref) eq 'ARRAY') {
                   6812:         if (grep(/^default$/,@{$selectedref})) {
                   6813:             $defcheck = ' checked="checked"';
                   6814:         }
                   6815:     }
                   6816:     $output .= '<span class="LC_nobreak"><label>'.
                   6817:                '<input type="checkbox" name="'.$context.$role.'_status"'.
                   6818:                'value="default"'.$defcheck.$disabled.' />'.
                   6819:                $othertitle.'</label></span></td>'.
                   6820:                &Apache::loncommon::end_data_table_row().
                   6821:                &Apache::loncommon::end_data_table();
                   6822:     return $output;
                   6823: }
                   6824: 
                   6825: sub adhoc_staff {
                   6826:     my ($access,$context,$role,$selectedref,$adhocref,$disabled) = @_;
                   6827:     my $output;
                   6828:     if (ref($adhocref) eq 'HASH') {
                   6829:         my %by_fullname;
                   6830:         my $numinrow = 4;
                   6831:         my $rem;
                   6832:         my @personnel = keys(%{$adhocref});
                   6833:         if (@personnel) {
                   6834:             foreach my $person (@personnel) {
                   6835:                 my ($uname,$udom) = split(/:/,$person);
                   6836:                 my $fullname = &Apache::loncommon::plainname($uname,$udom,'lastname');
                   6837:                 $by_fullname{$fullname} = $person;
                   6838:             }
                   6839:             my @sorted = sort(keys(%by_fullname));
                   6840:             my $count = scalar(@sorted);
                   6841:             $output = &Apache::loncommon::start_data_table();
                   6842:             for (my $i=0; $i<$count; $i++) {
                   6843:                 my $rem = $i%($numinrow);
                   6844:                 if ($rem == 0) {
                   6845:                     if ($i > 0) {
                   6846:                         $output .= &Apache::loncommon::end_data_table_row();
                   6847:                     }
                   6848:                     $output .= &Apache::loncommon::start_data_table_row();
                   6849:                 }
                   6850:                 my $check;
                   6851:                 my $user = $by_fullname{$sorted[$i]};
                   6852:                 if (ref($selectedref) eq 'ARRAY') {
                   6853:                     if (grep(/^\Q$user\E$/,@{$selectedref})) {
                   6854:                         $check = ' checked="checked"';
                   6855:                     }
                   6856:                 }
                   6857:                 if ($i == $count-1) {
                   6858:                     my $colsleft = $numinrow - $rem;
                   6859:                     if ($colsleft > 1) {
                   6860:                         $output .= '<td colspan="'.$colsleft.'">';
                   6861:                     } else {
                   6862:                         $output .= '<td>';
                   6863:                     }
                   6864:                 } else {
                   6865:                     $output .= '<td>';
                   6866:                 }
                   6867:                 $output .= '<span class="LC_nobreak"><label>'.
                   6868:                            '<input type="checkbox" name="'.$context.$role.'_staff_'.$access.'" '.
                   6869:                            'value="'.$user.'"'.$check.$disabled.' />'.$sorted[$i].
                   6870:                            '</label></span></td>';
                   6871:                 if ($i == $count-1) {
                   6872:                     $output .= &Apache::loncommon::end_data_table_row();
                   6873:                 }
                   6874:             }
                   6875:             $output .= &Apache::loncommon::end_data_table();
                   6876:         }
                   6877:     }
                   6878:     return $output;
                   6879: }
                   6880: 
                   6881: 
1.1       raeburn  6882: 1;
                   6883: 

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