File:  [LON-CAPA] / loncom / interface / lonuserutils.pm
Revision 1.109.2.12: download - view: text, annotated - select for diffs
Sun Dec 5 17:28:10 2010 UTC (13 years, 6 months ago) by raeburn
Branches: GCI_3
- Customization for GCI_3.
  - Suport for multiple Concept Inventories.

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

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