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

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

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