[LON-CAPA-cvs] cvs: loncom /auth lonroles.pm /interface loncommon.pm loncreateuser.pm londropadd.pm lonpickcourse.pm lonuserutils.pm

raeburn lon-capa-cvs-allow@mail.lon-capa.org
Mon, 22 Oct 2007 22:16:42 -0000


This is a MIME encoded message

--raeburn1193091402
Content-Type: text/plain

raeburn		Mon Oct 22 18:16:42 2007 EDT

  Added files:                 
    /loncom/interface	lonuserutils.pm 

  Modified files:              
    /loncom/auth	lonroles.pm 
    /loncom/interface	loncommon.pm londropadd.pm loncreateuser.pm 
                     	lonpickcourse.pm 
  Log:
  Bug 2593 csv file upload by DC to change passwords
  - DCs can change authentication, add a domain or course role for uploaded users, and/or change user information (names, ID, e-mail address etc.)
  - Authors can add co-authors
  - Course Coordinators can add course roles.
  - Some subroutines in londropdd.pm moved to lonuserutils.pm.  Some routines in loncreateuser.pm moved to lonuserutils.pm
  - &process_pick() moved from lonroles.pm to lonpickcourse.pm
  - Work in progress.  Ultimate goal is to provide user listing functionality in different contexts and eliminate separate ENRL button. 
  
  
  
--raeburn1193091402
Content-Type: text/plain
Content-Disposition: attachment; filename="raeburn-20071022181642.txt"

Index: loncom/auth/lonroles.pm
diff -u loncom/auth/lonroles.pm:1.179 loncom/auth/lonroles.pm:1.180
--- loncom/auth/lonroles.pm:1.179	Mon Sep 10 12:07:32 2007
+++ loncom/auth/lonroles.pm	Mon Oct 22 18:16:30 2007
@@ -1,7 +1,7 @@
 # The LearningOnline Network with CAPA
 # User Roles Screen
 #
-# $Id: lonroles.pm,v 1.179 2007/09/10 16:07:32 raeburn Exp $
+# $Id: lonroles.pm,v 1.180 2007/10/22 22:16:30 raeburn Exp $
 #
 # Copyright Michigan State University Board of Trustees
 #
@@ -965,32 +965,6 @@
     return $verify_script;
 }
 
-sub processpick {
-    my $process_pick = <<"END";
-<script type="text/javascript">
-function process_pick(dom) {
-    var pickedCourse=opener.document.rolechoice.$env{'form.cnumelement'}.value;
-    var pickedDomain=opener.document.rolechoice.$env{'form.cdomelement'}.value;
-    var okDomain = 0;
-
-    if (pickedDomain == dom) {
-        if (pickedCourse != '') {
-            var courseTarget = "cc./"+pickedDomain+"/"+pickedCourse
-            opener.document.title='Role selected. Please stand by.';
-            opener.status='Role selected. Please stand by.';
-	    opener.document.rolechoice.newrole.value=courseTarget
-            opener.document.rolechoice.submit()
-        }
-    } else {
-        alert("You may only use this screen to select courses in the current domain: "+dom+"\\nPlease return to the roles page window and click the 'Select Course' link for domain: "+pickedDomain+",\\n if you are a Domain Coordinator in that domain, and wish to become a Course Coordinator in a course in the domain");
-    }
-}
- 
-</script>
-END
-    return $process_pick;
-}
-
 sub display_cc_role {
     my $rolekey = shift;
     my $roletext;
Index: loncom/interface/loncommon.pm
diff -u loncom/interface/loncommon.pm:1.593 loncom/interface/loncommon.pm:1.594
--- loncom/interface/loncommon.pm:1.593	Thu Oct 18 17:57:59 2007
+++ loncom/interface/loncommon.pm	Mon Oct 22 18:16:38 2007
@@ -1,7 +1,7 @@
 # The LearningOnline Network with CAPA
 # a pile of common routines
 #
-# $Id: loncommon.pm,v 1.593 2007/10/18 21:57:59 albertel Exp $
+# $Id: loncommon.pm,v 1.594 2007/10/22 22:16:38 raeburn Exp $
 #
 # Copyright Michigan State University Board of Trustees
 #
@@ -407,7 +407,7 @@
 	                            '&cdomelement='+udom+
                                     '&cnameelement='+desc;
         if (extra_element !=null && extra_element != '') {
-            if (formname == 'rolechoice') {
+            if (formname == 'rolechoice' || formname == 'studentform') {
                 url += '&roleelement='+extra_element;
                 if (domainfilter == null || domainfilter == '') {
                     url += '&domainfilter='+extra_element;
@@ -1593,7 +1593,7 @@
                             option, and selected by default. 
     $hide - Value of 'hide' causes hiding of the name of the server, 
                             if 1 server found, or default, if 0 found.
-output: returns 1 items: 
+output: returns 2 items: 
 (a) form element which contains either:
    (i) <select name="$name">
         <option value="$hostid1">$hostid $servers{$hostid}</option>
@@ -4979,6 +4979,10 @@
   vertical-align: top;
 }
 
+span.LC_role_level {
+  font-weight: bold;
+}
+
 div.LC_left_float {
   float: left;
   padding-right: 5%;
@@ -6674,20 +6678,21 @@
     my ($r,$records) = @_;
     my $samples = &get_samples($records,3);
 
-    $r->print(&mt('Samples').'<br /><table border="2"><tr>');
+    $r->print(&mt('Samples').'<br />'.&start_data_table().
+              &start_data_table_header_row());
     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
         $r->print('<th>'.&mt('Column&nbsp;[_1]',($sample+1)).'</th>'); }
-    $r->print('</tr>');
+    $r->print(&end_data_table_header_row());
     foreach my $hash (@$samples) {
-	$r->print('<tr>');
+	$r->print(&start_data_table_row());
 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
 	    $r->print('<td>');
 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
 	    $r->print('</td>');
 	}
-	$r->print('</tr>');
+	$r->print(&end_data_table_row());
     }
-    $r->print('</tr></table><br />'."\n");
+    $r->print(&end_data_table().'<br />'."\n");
 }
 
 ######################################################
@@ -6712,12 +6717,13 @@
     my $i=0;
     my $samples = &get_samples($records,1);
     $r->print(&mt('Associate columns with student attributes.')."\n".
-	     '<table border="2"><tr>'.
+	      &start_data_table().&start_data_table_header_row().
               '<th>'.&mt('Attribute').'</th>'.
-              '<th>'.&mt('Column').'</th></tr>'."\n");
+              '<th>'.&mt('Column').'</th>'.
+              &end_data_table_header_row()."\n");
     foreach my $array_ref (@$d) {
 	my ($value,$display,$defaultcol)=@{ $array_ref };
-	$r->print('<tr><td>'.$display.'</td>');
+	$r->print(&start_data_table_row().'<tr><td>'.$display.'</td>');
 
 	$r->print('<td><select name=f'.$i.
 		  ' onchange="javascript:flip(this.form,'.$i.');">');
@@ -6727,9 +6733,10 @@
                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
                       '>Column '.($sample+1).'</option>');
 	}
-	$r->print('</select></td></tr>'."\n");
+	$r->print('</select></td>'.&end_data_table_row()."\n");
 	$i++;
     }
+    $r->print(&end_data_table());
     $i--;
     return $i;
 }
@@ -6756,11 +6763,13 @@
     my $i=0;
     #
     my $samples = &get_samples($records,3);
-    $r->print('<table border=2><tr><th>'.
-              &mt('Field').'</th><th>'.&mt('Samples').'</th></tr>');
+    $r->print(&start_data_table().
+              &start_data_table_header_row().'<th>'.
+              &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
+              &end_data_table_header_row());
 
     foreach my $key (sort(keys(%{ $samples->[0] }))) {
-	$r->print('<tr><td><select name="f'.$i.'"'.
+	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
 		  ' onchange="javascript:flip(this.form,'.$i.');">');
 	foreach my $option (@$d) {
 	    my ($value,$display,$defaultcol)=@{ $option };
@@ -6774,9 +6783,10 @@
 		$r->print($samples->[$line]{$key}."<br />\n"); 
 	    }
 	}
-	$r->print('</td></tr>');
+	$r->print('</td>'.&end_data_table_row());
 	$i++;
     }
+    $r->print(&end_data_table());
     $i--;
     return($i);
 }
Index: loncom/interface/londropadd.pm
diff -u loncom/interface/londropadd.pm:1.172 loncom/interface/londropadd.pm:1.173
--- loncom/interface/londropadd.pm:1.172	Wed Oct 10 22:16:25 2007
+++ loncom/interface/londropadd.pm	Mon Oct 22 18:16:38 2007
@@ -1,7 +1,7 @@
 # The LearningOnline Network with CAPA
 # Handler to drop and add students in courses 
 #
-# $Id: londropadd.pm,v 1.172 2007/10/11 02:16:25 albertel Exp $
+# $Id: londropadd.pm,v 1.173 2007/10/22 22:16:38 raeburn Exp $
 #
 # Copyright Michigan State University Board of Trustees
 #
@@ -423,7 +423,7 @@
 }
 END
     } else {
-        $section_checks = &section_check_js();
+        $section_checks = &Apache::lonuserutils::section_check_js();
         $optional_checks = (<<END);
     var message='';
     if (foundname==0) { 
@@ -759,9 +759,10 @@
     # in the course is entirely separate from the action of enrolling the
     # student.  Also, a failure in setting the dates as default is not fatal
     # to the process of enrolling / modifying a student.
-    my ($startdate,$enddate) = &get_dates_from_form();
+    my ($startdate,$enddate) = &Apache::lonuserutils::get_dates_from_form();
     if ($env{'form.makedatesdefault'}) {
-        $r->print(&make_dates_default($startdate,$enddate));
+        $r->print(&Apache::lonuserutils::make_dates_default($startdate,
+                                                            $enddate));
     }
 
     $r->print('<h3>'.&mt('Enrolling Student').'</h3>');
@@ -806,7 +807,7 @@
                                                    $env{'form.lcdomain'});
         if ((($amode) && ($genpwd)) || ($home ne 'no_host')) {
             # Clean out any old roles the student has in this class.
-            &modifystudent($env{'form.lcdomain'},$env{'form.cuname'},
+            &Apache::lonuserutils::modifystudent($env{'form.lcdomain'},$env{'form.cuname'},
                            $env{'request.course.id'},$env{'form.csec'},
                             $desiredhost);
             my $login_result = &Apache::lonnet::modifystudent
@@ -1066,7 +1067,8 @@
         my ($krbdef,$krbdefdom) =
             &Apache::loncommon::get_kerberos_defaults($ccdomain);
         $javascript_validations = 
-            &javascript_validations('auth',$krbdefdom,undef,undef,$ccdomain);
+            &Apache::lonuserutils::javascript_validations('auth',$krbdefdom,
+                                                      undef,undef,$ccdomain);
         my %param = ( formname => 'document.studentform',
                       kerb_def_dom => $krbdefdom,
                       kerb_def_auth => $krbdef
@@ -1132,7 +1134,7 @@
     } else {
         # User already exists.  Do not worry about authentication
         my %uenv = &Apache::lonnet::dump('environment',$ccdomain,$ccuname);
-        $javascript_validations = &javascript_validations('noauth');
+        $javascript_validations = &Apache::lonuserutils::javascript_validations('noauth');
 	my %lt=&Apache::lonlocal::texthash(
 		       'udf'  => "User Data for",
                        'fn'   => "First Name",
@@ -1158,7 +1160,7 @@
 </table>
 END
     }
-    my $date_table = &date_setting_table();
+    my $date_table = &Apache::lonuserutils::date_setting_table();
         # Print it all out
     my %lt=&Apache::lonlocal::texthash(
 		   'cd'   => "Course Data",
@@ -1807,7 +1809,8 @@
                 &Apache::lonlocal::locallocaltime($endtime)).'<br />';
 
     }
-    my $date_table = &date_setting_table($starttime,$endtime);
+    my $date_table = 
+        &Apache::lonuserutils::date_setting_table($starttime,$endtime);
     #
     if (! exists($env{'form.Status'}) || 
         $env{'form.Status'} !~ /^(Any|Expired|Active|Future)$/) {
@@ -1829,7 +1832,7 @@
                    'sm'    => "Submit Modifications",
 				       );
 # Check if section name is valid
-    my $section_check = &section_check_js();
+    my $section_check = &Apache::lonuserutils::section_check_js();
     $r->print(<<"END");
 <script type="text/javascript">
 $section_check
@@ -1894,9 +1897,10 @@
     $env{'form.section'} =~ s/\W//g;
     #
     # Do the date defaults first
-    my ($starttime,$endtime) = &get_dates_from_form();
+    my ($starttime,$endtime) = &Apache::lonuserutils::get_dates_from_form();
     if ($env{'form.makedatesdefault'}) {
-        $r->print(&make_dates_default($starttime,$endtime));
+        $r->print(&Apache::lonuserutils::make_dates_default($starttime,
+                                                            $endtime));
     }
     # Get the 'sortby' and 'Status' variables so the user goes back to their
     # previous screen
@@ -2042,9 +2046,10 @@
     #
     # Send request(s) to modify data (final undef is for 'desiredhost',
     # which is a moot point because the student already has an account.
-    my $modify_section_results = &modifystudent($sdom,$slogin,
-                                                $env{'request.course.id'},
-                                                $section,undef);
+    my $modify_section_results = 
+        &Apache::lonuserutils::modifystudent($sdom,$slogin,
+                                             $env{'request.course.id'},
+                                             $section,undef);
     if ($modify_section_results !~ /^ok/) {
         $r->print(&mt('An error occured during the attempt to change the section for this student.')."<br />");
     }
@@ -2504,8 +2509,9 @@
                         $$_ =~ s/(\s+$|^\s+)//g;
                     }
                     if ($password || $env{'form.login'} eq 'loc') {
-                        &modifystudent($domain,$username,$cid,$sec,
-                                       $desiredhost);
+                        &Apache::lonuserutils::modifystudent($domain,
+                                                         $username,$cid,
+                                                         $sec,$desiredhost);
                         my $reply=&Apache::lonnet::modifystudent
                             ($domain,$username,$id,$amode,$password,
                              $fname,$mname,$lname,$gen,$sec,$enddate,
@@ -2572,7 +2578,8 @@
     foreach (@droplist) {
         my ($uname,$udom)=split(/\:/,$_);
         # drop student
-        my $result = &modifystudent($udom,$uname,$env{'request.course.id'});
+        my $result = &Apache::lonuserutils::modifystudent($udom,$uname,
+                                                $env{'request.course.id'});
         if ($result eq 'ok' || $result eq 'ok:') {
             $r->print(&mt('Dropped [_1]',$uname.'@'.$udom).'<br>');
             $count++;
Index: loncom/interface/loncreateuser.pm
diff -u loncom/interface/loncreateuser.pm:1.189 loncom/interface/loncreateuser.pm:1.190
--- loncom/interface/loncreateuser.pm:1.189	Wed Oct 10 22:16:25 2007
+++ loncom/interface/loncreateuser.pm	Mon Oct 22 18:16:38 2007
@@ -1,7 +1,7 @@
 # The LearningOnline Network with CAPA
 # Create a user
 #
-# $Id: loncreateuser.pm,v 1.189 2007/10/11 02:16:25 albertel Exp $
+# $Id: loncreateuser.pm,v 1.190 2007/10/22 22:16:38 raeburn Exp $
 #
 # Copyright Michigan State University Board of Trustees
 #
@@ -65,6 +65,7 @@
 use Apache::loncommon;
 use Apache::lonlocal;
 use Apache::longroup;
+use Apache::lonuserutils;
 use LONCAPA qw(:DEFAULT :match);
 
 my $loginscript; # piece of javascript used in two separate instances
@@ -111,19 +112,6 @@
     return %abv_auth;
 }
 
-# ======================================================= Existing Custom Roles
-
-sub my_custom_roles {
-    my %returnhash=();
-    my %rolehash=&Apache::lonnet::dump('roles');
-    foreach my $key (keys %rolehash) {
-	if ($key=~/^rolesdef\_(\w+)$/) {
-	    $returnhash{$1}=$1;
-	}
-    }
-    return %returnhash;
-}
-
 # ==================================================== Figure out author access
 
 sub authorpriv {
@@ -237,21 +225,25 @@
                 'onload' => "javascript:setFormElements(document.$formtoset)",
                     );
     my $start_page =
-	&Apache::loncommon::start_page('Create Users, Change User Privileges',
+	&Apache::loncommon::start_page('User Management',
 				       $jscript,{'add_entries' => \%loaditems,});
-   &Apache::lonhtmlcommon::add_breadcrumb
-     ({href=>"javascript:backPage(document.crtuser)",
-       text=>"User modify/custom role edit",
-       faq=>282,bug=>'Instructor Interface',});
-
+    if ($env{'form.action'} eq 'singleuser') {
+        &Apache::lonhtmlcommon::add_breadcrumb
+          ({href=>"javascript:backPage(document.crtuser)",
+            text=>"Single user search",
+            faq=>282,bug=>'Instructor Interface',});
+    } elsif ($env{'form.action'} eq 'custom') {
+        &Apache::lonhtmlcommon::add_breadcrumb
+          ({href=>"javascript:backPage(document.crtuser)",
+            text=>"Pick custom role",});
+    }
     my $crumbs = &Apache::lonhtmlcommon::breadcrumbs('User Management');
-    my %existingroles=&my_custom_roles();
+    my %existingroles=&Apache::lonuserutils::my_custom_roles();
     my $choice=&Apache::loncommon::select_form('make new role','rolename',
 		('make new role' => 'Generate new role ...',%existingroles));
     my %lt=&Apache::lonlocal::texthash(
                     'srch' => "User Search",
                      or    => "or",
-		    'siur' => "Set Individual User Roles",
 		    'usr'  => "Username",
                     'dom'  => "Domain",
                     'ecrp' => "Edit Custom Role Privileges",
@@ -266,22 +258,24 @@
     if ($sellink) {
         $sellink = "$lt{'or'} ".$sellink;
     } 
-    $r->print("
-$start_page
-$crumbs
-<h2>$lt{siur}$helpsiur</h2>
-<h3>$lt{'srch'} $sellink $lt{'mod'}</h3>
+    $r->print($start_page."\n".$crumbs);
+    if ($env{'form.action'} eq 'singleuser') {
+        $r->print("
+<h3>$lt{'srch'} $sellink $lt{'mod'}$helpsiur</h3>
 $response");
-    $r->print(&entry_form($defdom,$srch,$forcenewuser));
-    if (&Apache::lonnet::allowed('mcr','/')) {
-        $r->print(<<ENDCUSTOM);
+        $r->print(&entry_form($defdom,$srch,$forcenewuser));
+    } elsif ($env{'form.action'} eq 'custom') {
+        if (&Apache::lonnet::allowed('mcr','/')) {
+            $r->print(<<ENDCUSTOM);
 <form action="/adm/createuser" method="post" name="docustom">
+<input type="hidden" name="action" value="$env{'form.action'}" />
 <input type="hidden" name="phase" value="selected_custom_edit" />
-<h2>$lt{'ecrp'}$helpecpr</h2>
+<h3>$lt{'ecrp'}$helpecpr</h3>
 $lt{'nr'}: $choice <input type="text" size="15" name="newrolename" /><br />
 <input name="customeditor" type="submit" value="$lt{'cre'}" />
 </form>
 ENDCUSTOM
+        }
     }
     $r->print(&Apache::loncommon::end_page());
 }
@@ -294,6 +288,7 @@
     my $srchbutton = &mt('Search');
     my $output = <<"ENDDOCUMENT";
 <form action="/adm/createuser" method="post" name="crtuser">
+<input type="hidden" name="action" value="$env{'form.action'}" />
 <input type="hidden" name="phase" value="get_user_info" />
 $userpicker
 <input name="userrole" type="button" value="$srchbutton" onclick="javascript:validateEntry(document.crtuser)" />
@@ -331,7 +326,7 @@
 
 # =================================================================== Phase two
 sub print_user_selection_page {
-    my ($r,$response,$srch,$srch_results,$context,$srcharray) = @_;
+    my ($r,$response,$srch,$srch_results,$operation,$srcharray) = @_;
     my @fields = ('username','domain','lastname','firstname','permanentemail');
     my $sortby = $env{'form.sortby'};
 
@@ -365,11 +360,11 @@
                                        'firstname'      => "first name",
                                        'permanentemail' => "permanent e-mail",
                                       );
-    if ($context eq 'createuser') {
-        $r->print(&Apache::loncommon::start_page('Create Users, Change User Privileges',$jscript));
+    if ($operation eq 'createuser') {
+        $r->print(&Apache::loncommon::start_page('User Management',$jscript));
         &Apache::lonhtmlcommon::add_breadcrumb
             ({href=>"javascript:backPage(document.usersrchform,'','')",
-              text=>"User modify/custom role edit",
+              text=>"Create/modify user",
               faq=>282,bug=>'Instructor Interface',},
              {href=>"javascript:backPage(document.usersrchform,'get_user_info','select')",
               text=>"Select User",
@@ -425,9 +420,10 @@
               ' <input type="hidden" name="seluname" value="" />'."\n".
               ' <input type="hidden" name="seludom" value="" />'."\n".
               ' <input type="hidden" name="currstate" value="select" />'."\n".
-              ' <input type="hidden" name="phase" value="get_user_info" />'."\n");
+              ' <input type="hidden" name="phase" value="get_user_info" />'."\n".
+              ' <input type="hidden" name="action" value="singleuser" />'."\n");
     $r->print($response);
-    if ($context eq 'createuser') {
+    if ($operation eq 'createuser') {
         $r->print('</form>'.&Apache::loncommon::end_page());
     } else {
         $r->print('<input type="hidden" name="action" value="enrollstudent" />'."\n".
@@ -707,18 +703,18 @@
         my ($krbdef,$krbdefdom) =
             &Apache::loncommon::get_kerberos_defaults($ccdomain);
         $javascript_validations = 
-            &Apache::londropadd::javascript_validations('auth',$krbdefdom,undef,
+            &Apache::lonuserutils::javascript_validations('auth',$krbdefdom,undef,
                                                         undef,$ccdomain);
     }
     $js .= "\n".
        '<script type="text/javascript">'."\n".$jsback."\n".
        $javascript_validations.'</script>';
     my $start_page = 
-	&Apache::loncommon::start_page('Create Users, Change User Privileges',
+	&Apache::loncommon::start_page('User Management',
 				       $js,{'add_entries' => \%loaditem,});
     &Apache::lonhtmlcommon::add_breadcrumb
      ({href=>"javascript:backPage(document.cu)",
-       text=>"User modify/custom role edit",
+       text=>"Create/modify user",
        faq=>282,bug=>'Instructor Interface',});
 
     if ($env{'form.phase'} eq 'userpicked') {
@@ -735,7 +731,7 @@
 
     my $forminfo =<<"ENDFORMINFO";
 <form action="/adm/createuser" method="post" name="cu">
-<input type="hidden" name="phase"       value="update_user_data" />
+<input type="hidden" name="phase" value="update_user_data" />
 <input type="hidden" name="ccuname" value="$ccuname" />
 <input type="hidden" name="ccdomain" value="$ccdomain" />
 <input type="hidden" name="pres_value"  value="" />
@@ -759,6 +755,7 @@
                 'cnu'            => 'Create New User',
                 'ind'            => 'in domain',
                 'lg'             => 'Login Data',
+                'hs'             => "Home Server",
         );
 	$r->print(<<ENDTITLE);
 $start_page
@@ -793,7 +790,7 @@
                 if (ref($rules->{$rulematch}) eq 'HASH') {
                     my $authtype = $rules->{$rulematch}{'authtype'};
                     if ($authtype !~ /^(krb4|krb5|int|fsys|loc)$/) {
-                        $r->print(&set_login($ccdomain));
+                        $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
                     } else { 
                         my $authparm = $rules->{$rulematch}{'authparm'};
                         if ($authtype =~ /^krb(4|5)$/) {
@@ -819,7 +816,7 @@
                         }
                     }
                 } else {
-                    $r->print(&set_login($ccdomain));
+                    $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
                 }
             }
             if ($authmsg) {
@@ -830,7 +827,7 @@
 ENDAUTH
             }
         } else {
-            $r->print(&set_login($ccdomain)); 
+            $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc)); 
         }
         $r->print(<<ENDPORT);
         $portfolioform
@@ -1129,13 +1126,15 @@
 "javascript:pjump('."'date_end','End Date Assistant Co-Author',document.cu.end_$cudom\_$cuname\_aa.value,'end_$cudom\_$cuname\_aa','cu.pres','dateset'".')">'.$lt{'sed'}.'</a></td>'."\n".
          &Apache::loncommon::end_data_table_row()."\n".
          &Apache::loncommon::end_data_table());
-    } elsif (!(&authorpriv($env{'user.name'},$env{'request.role.domain'}))) {
-        $r->print('<span class="LC_error">'.
-                  &mt('You do not have privileges to assign co-author roles.').
-                  '</span>');     
-    } elsif (($env{'user.name'} eq $ccuname) && 
+    } elsif ($env{'request.role'} =~ /^au\./) {
+        if (!(&authorpriv($env{'user.name'},$env{'request.role.domain'}))) {
+            $r->print('<span class="LC_error">'.
+                      &mt('You do not have privileges to assign co-author roles.').
+                      '</span>');
+        } elsif (($env{'user.name'} eq $ccuname) && 
              ($env{'user.domain'} eq $ccdomain)) {
-       $r->print(&mt('Assigning yourself a co-author or assistant co-author role in your own author area in Construction Space is not permitted'));  
+           $r->print(&mt('Assigning yourself a co-author or assistant co-author role in your own author area in Construction Space is not permitted'));
+        }
     }
 #
 # Domain level
@@ -1236,7 +1235,7 @@
         );
         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
             &initialize_authen_forms($ccdomain);
-            my $choices = &set_login($ccdomain);
+            my $choices = &Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc);
             $outcome = <<ENDBADAUTH;
 <script type="text/javascript" language="Javascript">
 $loginscript
@@ -1307,34 +1306,6 @@
     return $outcome;
 }
 
-sub set_login {
-    my ($dom) = @_;
-    my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
-    my $response;
-    my ($authnum,%can_assign) = 
-        &Apache::loncommon::get_assignable_auth($dom);
-    if ($authnum) {
-        $response = &Apache::loncommon::start_data_table();
-        if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
-            $response .= &Apache::loncommon::start_data_table_row().
-                         '<td>'.$authformkrb.'</td>'.
-                         &Apache::loncommon::end_data_table_row()."\n";
-        }
-        if ($can_assign{'int'}) {
-            $response .= &Apache::loncommon::start_data_table_row().
-                         '<td>'.$authformint.'</td>'.
-                         &Apache::loncommon::end_data_table_row()."\n"
-        }
-        if ($can_assign{'loc'}) {
-            $response .= &Apache::loncommon::start_data_table_row().
-                         '<td>'.$authformloc.'</td>'.
-                         &Apache::loncommon::end_data_table_row()."\n";
-        }
-        $response .= &Apache::loncommon::end_data_table();
-    }
-    return $response;
-}
-
 sub modify_login_block {
     my ($dom,$currentauth) = @_;
     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
@@ -1432,7 +1403,6 @@
                 'generation'     => "Generation",
                 'permanentemail' => "Permanent e-mail address",
                 'id'             => "ID/Student Number",
-                'hs'             => "Home Server",
                 'lg'             => "Login Data"
     );
     my @userinfo = ('firstname','middlename','lastname','generation',
@@ -1498,7 +1468,7 @@
     $r->print(&Apache::loncommon::start_page($title,$jscript));
     &Apache::lonhtmlcommon::add_breadcrumb
        ({href=>"javascript:backPage(document.userupdate)",
-         text=>"User modify/custom role edit",
+         text=>"Create/modify user",
          faq=>282,bug=>'Instructor Interface',});
     if ($env{'form.prevphase'} eq 'userpicked') {
         &Apache::lonhtmlcommon::add_breadcrumb
@@ -1799,6 +1769,7 @@
     $r->print('<h3>'.&mt('Modifying Roles').'</h3>');
     foreach my $key (keys (%env)) {
 	next if (! $env{$key});
+        next if ($key eq 'form.action');
 	# Revoke roles
 	if ($key=~/^form\.rev/) {
 	    if ($key=~/^form\.rev\:([^\_]+)\_([^\_\.]+)$/) {
@@ -1990,7 +1961,7 @@
                     }
                 }
 	    } else {
-		$r->print('<p>'.&mt('ERROR').': '.&mt('Unknown command').' <tt>'.$key.'</tt></p><br />');
+		$r->print('<p><span class="LC_error">'.&mt('ERROR').': '.&mt('Unknown command').' <tt>'.$key.'</tt></span></p><br />');
             }
             foreach my $key (sort(keys(%disallowed))) {
                 if (($key eq 'none') || ($key eq 'all')) {  
@@ -2024,6 +1995,7 @@
     }
     $outcome .= '<input type="hidden" name="phase" value="" />'."\n".
                 '<input type ="hidden" name="currstate" value="" />'."\n".
+                '<input type ="hidden" name="action" value="singleuser" />'."\n".
                 '</form>';
     return $outcome;
 }
@@ -2108,7 +2080,7 @@
 
     $rolename=~s/[^A-Za-z0-9]//gs;
 
-    if (!$rolename) {
+    if (!$rolename || $env{'form.phase'} eq 'pickrole') {
 	&print_username_entry_form($r);
         return;
     }
@@ -2177,8 +2149,8 @@
     $head_script .= "\n".$jsback."\n".'</script>'."\n";
     $r->print(&Apache::loncommon::start_page('Custom Role Editor',$head_script));
    &Apache::lonhtmlcommon::add_breadcrumb
-     ({href=>"javascript:backPage(document.form1,'','')",
-       text=>"User modify/custom role edit",
+     ({href=>"javascript:backPage(document.form1,'pickrole','')",
+       text=>"Pick custom role",
        faq=>282,bug=>'Instructor Interface',},
       {href=>"javascript:backPage(document.form1,'','')",
          text=>"Edit custom role",
@@ -2221,6 +2193,7 @@
              &Apache::loncommon::end_data_table_row());
     }
     $r->print(&Apache::loncommon::end_data_table().
+   '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
    '<input type="hidden" name="startrolename" value="'.$env{'form.rolename'}.
    '" />'."\n".'<input type="hidden" name="currstate" value="" />'."\n".   
    '<input type="reset" value="'.&mt("Reset").'" />'."\n".
@@ -2302,23 +2275,19 @@
 # ---------------------------------------------------------- Call to definerole
 sub set_custom_role {
     my ($r) = @_;
-
     my $rolename=$env{'form.rolename'};
-
     $rolename=~s/[^A-Za-z0-9]//gs;
-
     if (!$rolename) {
-	&print_username_entry_form($r);
+	&custom_role_editor($r);
         return;
     }
-
     my ($jsback,$elements) = &crumb_utilities();
     my $jscript = '<script type="text/javascript">'.$jsback."\n".'</script>';
 
     $r->print(&Apache::loncommon::start_page('Save Custom Role'),$jscript);
     &Apache::lonhtmlcommon::add_breadcrumb
-        ({href=>"javascript:backPage(document.customresult,'','')",
-          text=>"User modify/custom role edit",
+        ({href=>"javascript:backPage(document.customresult,'pickrole','')",
+          text=>"Pick custom role",
           faq=>282,bug=>'Instructor Interface',},
          {href=>"javascript:backPage(document.customresult,'selected_custom_edit','')",
           text=>"Edit custom role",
@@ -2381,7 +2350,7 @@
 						$env{'user.name'},
 						$rolename));
     }
-    $r->print('<p><a href="/adm/createuser">Create another role, or Create/Modify a user.</a></p><form name="customresult" method="post">');
+    $r->print('<p><a href="javascript:backPage(document.customresult,'."'pickrole'".')">'.&mt('Create or edit another custom role').'</a></p><form name="customresult" method="post">');
     $r->print(&Apache::lonhtmlcommon::echo_form_input([]).'</form>');
     $r->print(&Apache::loncommon::end_page());
 }
@@ -2389,84 +2358,290 @@
 # ================================================================ Main Handler
 sub handler {
     my $r = shift;
-
     if ($r->header_only) {
        &Apache::loncommon::content_type($r,'text/html');
        $r->send_http_header;
        return OK;
     }
+    my $context;
+    if ($env{'request.course.id'}) {
+        $context = 'course';
+    } elsif ($env{'request.role'} =~ /^au\./) {
+        $context = 'construction_space';
+    } else {
+        $context = 'domain';
+    }
+    &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
+                                            ['action','state']);
+    &Apache::lonhtmlcommon::clear_breadcrumbs();
+    &Apache::lonhtmlcommon::add_breadcrumb
+        ({href=>"/adm/createuser",
+          text=>"User Management"});
+    my ($permission,$allowed) = &get_permission($context);
+    if (!$allowed) {
+        $env{'user.error.msg'}=
+            "/adm/createuser:cst:0:0:Cannot create/modify user data ".
+                                 "or view user status.";
+        return HTTP_NOT_ACCEPTABLE;
+    }
+
+    &Apache::loncommon::content_type($r,'text/html');
+    $r->send_http_header;
+
+    # Main switch on form.action and form.state, as appropriate
+    if (! exists($env{'form.action'})) {
+        $r->print(&header());
+        $r->print(&Apache::lonhtmlcommon::breadcrumbs('User Management'));
+        $r->print(&print_main_menu($permission));
+        $r->print(&Apache::loncommon::end_page());
+    } elsif ($env{'form.action'} eq 'upload' && $permission->{'cusr'}) {
+        $r->print(&header());
+        &Apache::lonhtmlcommon::add_breadcrumb
+            ({href=>'/adm/createuser?action=upload&state=',
+              text=>"Upload Users List"});
+        $r->print(&Apache::lonhtmlcommon::breadcrumbs('Upload Users List',
+                                                   'User_Management_Upload'));
+        $r->print('<form name="studentform" method="post" '.
+                  'enctype="multipart/form-data" '.
+                  ' action="/adm/createuser">'."\n");
+        if (! exists($env{'form.state'})) {
+            &Apache::lonuserutils::print_first_users_upload_form($r,$context);
+        } elsif ($env{'form.state'} eq 'got_file') {
+            &Apache::lonuserutils::print_upload_manager_form($r,$context);
+        } elsif ($env{'form.state'} eq 'enrolling') {
+            if ($env{'form.datatoken'}) {
+                &Apache::lonuserutils::upfile_drop_add($r,$context);
+            }
+        } else {
+            &Apache::lonuserutils::print_first_users_upload_form($r,$context);
+        }
+        $r->print('</form>'.&Apache::loncommon::end_page());
+    } elsif ($env{'form.action'} eq 'expire' && $permission->{'cusr'}) {
+        $r->print(&header());
+        &Apache::lonhtmlcommon::add_breadcrumb
+            ({href=>'/adm/createuser?action=expire',
+              text=>"Expire User Roles"});
+        $r->print(&Apache::lonhtmlcommon::breadcrumbs('Expire User Roles',
+                                                      'User_Management_Drops'));
+        if (! exists($env{'form.state'})) {
+            &Apache::lonuserutils::print_expire_menu($r,$context);
+        } elsif ($env{'form.state'} eq 'done') {
+            &Apache::lonuserutils::expire_user_list($r);
+        } else {
+            &Apache::lonuserutils::print_expire_menu($r,$context);
+        }
+        $r->print(&Apache::loncommon::end_page());
+    } elsif ($env{'form.action'} eq 'singleuser' && $permission->{'cusr'}) {
+        my $phase = $env{'form.phase'};
+        my @search = ('srchterm','srchby','srchin','srchtype','srchdomain');
+
+        if (($phase eq 'get_user_info') || ($phase eq 'userpicked')) {
+            my $srch;
+            foreach my $item (@search) {
+                $srch->{$item} = $env{'form.'.$item};
+            }
+            if ($env{'form.phase'} eq 'get_user_info') {
+                my ($currstate,$response,$forcenewuser,$results) = 
+                    &user_search_result($srch);
+                if ($env{'form.currstate'} eq 'modify') {
+                    $currstate = $env{'form.currstate'};
+                }
+                if ($currstate eq 'select') {
+                    &print_user_selection_page($r,$response,$srch,$results,
+                                               'createuser',\@search);
+                } elsif ($currstate eq 'modify') {
+                    my ($ccuname,$ccdomain);
+                    if (($srch->{'srchby'} eq 'uname') && 
+                        ($srch->{'srchtype'} eq 'exact')) {
+                        $ccuname = $srch->{'srchterm'};
+                        $ccdomain= $srch->{'srchdomain'};
+                    } else {
+                        my @matchedunames = keys(%{$results});
+                        ($ccuname,$ccdomain) = split(/:/,$matchedunames[0]);
+                    }
+                    $ccuname =&LONCAPA::clean_username($ccuname);
+                    $ccdomain=&LONCAPA::clean_domain($ccdomain);
+                    if ($env{'form.forcenewuser'}) {
+                        $response = '';
+                    }
+                    &print_user_modification_page($r,$ccuname,$ccdomain,
+                                                  $srch,$response);
+                } elsif ($currstate eq 'query') {
+                    &print_user_query_page($r,'createuser');
+                } else {
+                    &print_username_entry_form($r,$response,$srch,
+                                               $forcenewuser);
+                }
+            } elsif ($env{'form.phase'} eq 'userpicked') {
+                my $ccuname = &LONCAPA::clean_username($env{'form.seluname'});
+                my $ccdomain = &LONCAPA::clean_domain($env{'form.seludom'});
+                &print_user_modification_page($r,$ccuname,$ccdomain,$srch);
+            }
+        } elsif ($env{'form.phase'} eq 'update_user_data') {
+            &update_user_data($r);
+        } else {
+            &print_username_entry_form($r);
+        }
+    } elsif ($env{'form.action'} eq 'custom' && $permission->{'custom'}) {
+        if ($env{'form.phase'} eq 'set_custom_roles') {
+            &set_custom_role($r);
+        } else {
+            &custom_role_editor($r);
+        }
+    } elsif ($env{'form.action'} eq 'listusers' && $permission->{'view'}) {
+        $r->print(&header());
+        &Apache::lonhtmlcommon::add_breadcrumb
+            ({href=>'/adm/createuser?action=listusers',
+              text=>"List Users' Roles"});
+        $r->print(&Apache::lonhtmlcommon::breadcrumbs("List Users' Roles",
+                                                      'User_Management_List'));
+        if (! exists($env{'form.state'})) {
+            &Apache::lonuserutils::print_html_classlist($r,undef,$permission);
+        } elsif ($env{'form.state'} eq 'csv') {
+            &Apache::lonuserutils::print_html_classlist($r,'csv',$permission);
+        } elsif ($env{'form.state'} eq 'excel') {
+            &Apache::lonuserutils::print_html_classlist($r,'excel',$permission);
+        } else {
+            &Apache::lonuserutils::print_html_classlist($r,undef,$permission);
+        }
+        $r->print(&Apache::loncommon::end_page());
+    } elsif ($env{'form.action'} eq 'expire' && $permission->{'cusr'}) {
+        $r->print(&header());
+        &Apache::lonhtmlcommon::add_breadcrumb
+            ({href=>'/adm/createuser?action=drop',
+              text=>"Expire Users"});
+        $r->print(&Apache::lonhtmlcommon::breadcrumbs('Expire User Roles',
+                                                      'User_Management_Drops'));
+        if (! exists($env{'form.state'})) {
+            &Apache::lonuserutils::print_expire_menu($r,$context);
+        } elsif ($env{'form.state'} eq 'done') {
+            &Apache::lonuserutiles::expire_user_list($r);
+        } else {
+            &print_expire_menu($r,$context);
+        }
+        $r->print(&Apache::loncommon::end_page());
+    } else {
+        $r->print(&header());
+        $r->print(&Apache::lonhtmlcommon::breadcrumbs('User Management'));            $r->print(&print_main_menu($permission));
+        $r->print(&Apache::loncommon::end_page());
+    }
+    return OK;
+}
+
+sub header {
+    my ($jscript,$loaditems) = @_;
+    my $start_page;
+    if (ref($loaditems) eq 'HASH') {
+        $start_page=&Apache::loncommon::start_page('User Management',$jscript,{'add_entries' => $loaditems,});
+    } else {
+        $start_page=&Apache::loncommon::start_page('User Management',$jscript);
+    }
+    return $start_page;
+}
 
-    if ((&Apache::lonnet::allowed('cta',$env{'request.course.id'})) ||
-        (&Apache::lonnet::allowed('cin',$env{'request.course.id'})) || 
-        (&Apache::lonnet::allowed('ccr',$env{'request.course.id'})) || 
-        (&Apache::lonnet::allowed('cep',$env{'request.course.id'})) ||
-	(&authorpriv($env{'user.name'},$env{'request.role.domain'})) ||
-        (&Apache::lonnet::allowed('mau',$env{'request.role.domain'}))) {
-       &Apache::loncommon::content_type($r,'text/html');
-       $r->send_http_header;
-       &Apache::lonhtmlcommon::clear_breadcrumbs();
-      
-       my $phase = $env{'form.phase'};
-       my @search = ('srchterm','srchby','srchin','srchtype','srchdomain');
-       
-       &Apache::loncreateuser::restore_prev_selections();
-       my $srch;
-       foreach my $item (@search) {
-	   $srch->{$item} = $env{'form.'.$item};
-       }
-
-       if (($phase eq 'get_user_info') || ($phase eq 'userpicked')) {
-
-           if ($env{'form.phase'} eq 'get_user_info') {
-               my ($currstate,$response,$forcenewuser,$results) = 
-                   &user_search_result($srch);
-               if ($env{'form.currstate'} eq 'modify') {
-                   $currstate = $env{'form.currstate'};
-               }
-               if ($currstate eq 'select') {
-                   &print_user_selection_page($r,$response,$srch,$results,'createuser',\@search);
-               } elsif ($currstate eq 'modify') {
-                   my ($ccuname,$ccdomain);
-                   if (($srch->{'srchby'} eq 'uname') && 
-                       ($srch->{'srchtype'} eq 'exact')) {
-                       $ccuname = $srch->{'srchterm'};
-                       $ccdomain= $srch->{'srchdomain'};
-                   } else {
-                       my @matchedunames = keys(%{$results});
-                       ($ccuname,$ccdomain) = split(/:/,$matchedunames[0]);
-                   }
-                   $ccuname =&LONCAPA::clean_username($ccuname);
-                   $ccdomain=&LONCAPA::clean_domain($ccdomain);
-                   if ($env{'form.forcenewuser'}) {
-                       $response = '';
-                   }   
-                   &print_user_modification_page($r,$ccuname,$ccdomain,$srch,
-                                                 $response);
-               } elsif ($currstate eq 'query') {
-                   &print_user_query_page($r,'createuser');
-               } else {
-                   &print_username_entry_form($r,$response,$srch,$forcenewuser);
-               }
-           } elsif ($env{'form.phase'} eq 'userpicked') {
-               my $ccuname = &LONCAPA::clean_username($env{'form.seluname'});
-               my $ccdomain = &LONCAPA::clean_domain($env{'form.seludom'});
-               &print_user_modification_page($r,$ccuname,$ccdomain,$srch);
-           }
-       } elsif ($env{'form.phase'} eq 'update_user_data') {
-           &update_user_data($r);
-       } elsif ($env{'form.phase'} eq 'selected_custom_edit') {
-           &custom_role_editor($r);
-       } elsif ($env{'form.phase'} eq 'set_custom_roles') {
-	   &set_custom_role($r);
-       } else {
-           &print_username_entry_form($r,undef,$srch);
-       }
-   } else {
-      $env{'user.error.msg'}=
-        "/adm/createuser:mau:0:0:Cannot modify user data";
-      return HTTP_NOT_ACCEPTABLE; 
-   }
-   return OK;
+###############################################################
+###############################################################
+#  Menu Phase One
+sub print_main_menu {
+    my ($permission) = @_;
+    my @menu =
+        (
+          { text => 'Upload a File of Users to Set Roles',
+            help => 'User_Management_Upload',
+            action => 'upload',
+            permission => $permission->{'cusr'},
+            },
+          { text => 'Set User Roles for an Individual User',
+            help => 'User_Management_Single_User',
+            action => 'singleuser',
+            permission => $permission->{'cusr'},
+            },
+#          { text => 'Display User Roles for Multiple Users',
+#            help => 'User_Management_List',
+#            action => 'listusers',
+#            permission => $permission->{'view'},
+#            },
+#          { text => 'Expire User Roles ',
+#            help => 'User_Management_Drops',
+#            action => 'expire',
+#            permission => $permission->{'cusr'},
+#            },
+          { text => 'Edit Custom Roles',
+            help => 'Custom_Role_Edit',
+            action => 'custom',
+            permission => $permission->{'custom'},
+          },
+        );
+    my $menu_html = '';
+    foreach my $menu_item (@menu) {
+        next if (! $menu_item->{'permission'});
+        $menu_html.='<p>';
+        $menu_html.='<font size="+1">';
+        if (exists($menu_item->{'url'})) {
+            $menu_html.=qq{<a href="$menu_item->{'url'}">};
+        } else {
+            $menu_html.=
+                qq{<a href="/adm/createuser?action=$menu_item->{'action'}">};
+        }
+        $menu_html.= &mt($menu_item->{'text'}).'</a></font>';
+        if (exists($menu_item->{'help'})) {
+            $menu_html.=
+                &Apache::loncommon::help_open_topic($menu_item->{'help'});
+        }
+        $menu_html.='</p>';
+    }
+    return $menu_html;
+}
+
+sub get_permission {
+    my ($context) = @_;
+    my %permission;
+    if ($context eq 'course') {
+        if ((&Apache::lonnet::allowed('cta',$env{'request.course.id'})) ||
+            (&Apache::lonnet::allowed('cin',$env{'request.course.id'})) ||
+            (&Apache::lonnet::allowed('ccr',$env{'request.course.id'})) ||
+            (&Apache::lonnet::allowed('cep',$env{'request.course.id'})) ||
+            (&Apache::lonnet::allowed('cst',$env{'request.course.id'}))) {
+            $permission{'cusr'} = 1;
+            $permission{'view'} =
+                 &Apache::lonnet::allowed('vcl',$env{'request.course.id'});
+
+        }
+        if (&Apache::lonnet::allowed('ccr',$env{'request.course.id'})) {
+            $permission{'custom'} = 1;
+        }
+        if (&Apache::lonnet::allowed('vcl',$env{'request.course.id'})) {
+            $permission{'view'} = 1;
+            if (!$permission{'view'}) {
+                my $scope = $env{'request.course.id'}.'/'.$env{'request.course.sec'};
+                $permission{'view'} =  &Apache::lonnet::allowed('vcl',$scope);
+                if ($permission{'view'}) {
+                    $permission{'view_section'} = $env{'request.course.sec'};
+                }
+            }
+        }
+    } elsif ($context eq 'construction_space') {
+        $permission{'cusr'} = &authorpriv($env{'user.name'},$env{'request.role.domain'});
+        $permission{'view'} = $permission{'cusr'};
+    } else {
+        if ((&Apache::lonnet::allowed('cad',$env{'request.role.domain'})) ||
+            (&Apache::lonnet::allowed('cli',$env{'request.role.domain'})) ||
+            (&Apache::lonnet::allowed('cau',$env{'request.role.domain'})) ||
+            (&Apache::lonnet::allowed('csc',$env{'request.role.domain'})) ||
+            (&Apache::lonnet::allowed('cdg',$env{'request.role.domain'})) || 
+            (&Apache::lonnet::allowed('mau',$env{'request.role.domain'}))) {
+            $permission{'cusr'} = 1;
+        }
+        if (&Apache::lonnet::allowed('ccr',$env{'request.role.domain'})) {
+            $permission{'custom'} = 1;
+        }
+        $permission{'view'} = $permission{'cusr'};
+    }
+    my $allowed = 0;
+    foreach my $perm (values(%permission)) {
+        if ($perm) { $allowed=1; last; }
+    }
+    return (\%permission,$allowed);
 }
 
 sub restore_prev_selections {
@@ -2898,7 +3073,7 @@
     my $table = '';
 # Custom Roles?
 
-    my %customroles=&my_custom_roles();
+    my %customroles=&Apache::lonuserutils::my_custom_roles();
     my %lt=&Apache::lonlocal::texthash(
             'exs'  => "Existing sections",
             'new'  => "Define new section",
@@ -3045,7 +3220,7 @@
 
 sub course_level_dc {
     my ($dcdom) = @_;
-    my %customroles=&my_custom_roles();
+    my %customroles=&Apache::lonuserutils::my_custom_roles();
     my $hiddenitems = '<input type="hidden" name="dcdomain" value="'.$dcdom.'" />'.
                       '<input type="hidden" name="origdom" value="'.$dcdom.'" />'.
                       '<input type="hidden" name="dccourse" value="" />';
Index: loncom/interface/lonpickcourse.pm
diff -u loncom/interface/lonpickcourse.pm:1.65 loncom/interface/lonpickcourse.pm:1.66
--- loncom/interface/lonpickcourse.pm:1.65	Sat Oct  6 00:32:49 2007
+++ loncom/interface/lonpickcourse.pm	Mon Oct 22 18:16:38 2007
@@ -1,7 +1,7 @@
 # The LearningOnline Network
 # Pick a course
 #
-# $Id: lonpickcourse.pm,v 1.65 2007/10/06 04:32:49 raeburn Exp $
+# $Id: lonpickcourse.pm,v 1.66 2007/10/22 22:16:38 raeburn Exp $
 #
 # Copyright Michigan State University Board of Trustees
 #
@@ -72,7 +72,7 @@
     my $roledom = $env{'form.roleelement'};
     if ($roledom) {
         $roleelement = '<input type="hidden" name="roleelement" value="'.$roledom.'" />';
-        $submitopener = &Apache::lonroles::processpick();
+        $submitopener = &processpick();
         $autosubmit = 'process_pick("'.$roledom.'")';
     }
 
@@ -83,7 +83,8 @@
     }
 
     my %loaditem;
-    if ($env{'form.form'} eq 'cu' && $env{'form.pickedcourse'}) {
+    if ((($env{'form.form'} eq 'cu') || ($env{'form.form'} eq 'studentform')) && 
+        ($env{'form.pickedcourse'})) {
         $loaditem{'onload'} ="setSections()";
     }
     $r->print(&Apache::loncommon::start_page($title,undef,
@@ -92,7 +93,7 @@
 
     if ($env{'form.form'} eq 'portform') {
         $lastaction = 'document.courselist.submit()';
-    } elsif ($env{'form.form'} eq 'cu') {
+    } elsif ($env{'form.form'} eq 'cu' || $env{'form.form'} eq 'studentform') {
         $lastaction = 
              'document.courselist.pickedcourse.value = cdom+"_"+cname;'."\n".
              'document.courselist.submit();';
@@ -101,7 +102,7 @@
     }
 
     # if called to assign a role in a course to a user via CUSR
-    if ($env{'form.form'} eq 'cu') {
+    if ($env{'form.form'} eq 'cu' || $env{'form.form'} eq 'studentform') {
         $r->print(&create_user_javascript($type)); 
     }
 
@@ -137,6 +138,49 @@
     return OK;
 }
 
+sub processpick {
+    my $openerform = 'rolechoice';
+    if ($env{'form.form'} eq 'studentform') {
+        $openerform = $env{'form.form'};
+    }
+    my $process_pick = <<"ENDONE";
+<script type="text/javascript">
+function process_pick(dom) {
+    var pickedCourse=opener.document.$openerform.$env{'form.cnumelement'}.value;
+    var pickedDomain=opener.document.$openerform.$env{'form.cdomelement'}.value;
+    var okDomain = 0;
+ENDONE
+    if ($openerform eq 'rolechoice') {
+        $process_pick .= <<"ENDTWO";
+    if (pickedDomain == dom) {
+        if (pickedCourse != '') {
+            var courseTarget = "cc./"+pickedDomain+"/"+pickedCourse
+            opener.document.title='Role selected. Please stand by.';
+            opener.status='Role selected. Please stand by.';
+            opener.document.rolechoice.newrole.value=courseTarget
+            opener.document.rolechoice.submit();
+        }
+    } 
+    else {
+        alert("You may only use this screen to select courses in the current domain: "+dom+"\\nPlease return to the roles page window and click the 'Select Course' link for domain: "+pickedDomain+",\\n if you are a Domain Coordinator in that domain, and wish to become a Course Coordinator in a course in the domain");
+    }
+ENDTWO
+    } else {
+        $process_pick .= <<"ENDTHREE";
+    if (pickedDomain != dom) {
+        alert("You may only use this screen to select courses in the current domain: "+dom+"\\nPlease return to the roles page window and click the 'Select Course' link for domain: "+pickedDomain+",\\n if you are a Domain Coordinator in that domain, and wish to become a Course Coordinator in a course in the domain");
+        return;
+    }
+ENDTHREE
+    }
+    $process_pick .= "
+}
+
+</script>
+";
+    return $process_pick;
+}
+
 sub create_user_javascript {
     my ($type) = @_;
     my $output;
@@ -708,7 +752,7 @@
 X<gochoose_javascript()>
 B<gochoose_javascript($type,$multiple,$autosubmit,$lastaction)>:
 
-Input: 4 - course type; single (0) or multiple courses (1); in context of DC selecting a CC role in a course: javascript code from Apache::lonroles::processpick(); final action to take after user chooses course(s):  either close window, or submit form for display of next page etc.
+Input: 4 - course type; single (0) or multiple courses (1); in context of DC selecting a CC role in a course: javascript code from &processpick(); final action to take after user chooses course(s):  either close window, or submit form for display of next page etc.
 
 Output: 1  $output - javascript wrapped in E<lt>scriptE<gt>E<lt>/scriptE<gt> tags
 

Index: loncom/interface/lonuserutils.pm
+++ loncom/interface/lonuserutils.pm
# The LearningOnline Network with CAPA
# Utility functions for managing LON-CAPA user accounts
#
# $Id: lonuserutils.pm,v 1.1 2007/10/22 22:16:38 raeburn Exp $
#
# Copyright Michigan State University Board of Trustees
#
# This file is part of the LearningOnline Network with CAPA (LON-CAPA).
#
# LON-CAPA is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# LON-CAPA is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with LON-CAPA; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA#
# /home/httpd/html/adm/gpl.txt
#
# http://www.lon-capa.org/
#
#
###############################################################
###############################################################

package Apache::lonuserutils;

use strict;
use Apache::lonnet;
use Apache::loncommon();
use Apache::lonhtmlcommon;
use Apache::lonlocal;
use LONCAPA();

###############################################################
###############################################################
# Drop student from all sections of a course, except optional $csec
sub modifystudent {
    my ($udom,$unam,$courseid,$csec,$desiredhost)=@_;
    # if $csec is undefined, drop the student from all the courses matching
    # this one.  If $csec is defined, drop them from all other sections of
    # this course and add them to section $csec
    my $cdom = $env{'course.'.$courseid.'.domain'};
    my $cnum = $env{'course.'.$courseid.'.num'};
    my %roles = &Apache::lonnet::dump('roles',$udom,$unam);
    my ($tmp) = keys(%roles);
    # Bail out if we were unable to get the students roles
    return "$1" if ($tmp =~ /^(con_lost|error|no_such_host)/i);
    # Go through the roles looking for enrollment in this course
    my $result = '';
    foreach my $course (keys(%roles)) {
        if ($course=~m{^/\Q$cdom\E/\Q$cnum\E(?:\/)*(?:\s+)*(\w+)*\_st$}) {
            # We are in this course
            my $section=$1;
            $section='' if ($course eq "/$cdom/$cnum".'_st');
            if (defined($csec) && $section eq $csec) {
                $result .= 'ok:';
            } elsif ( ((!$section) && (!$csec)) || ($section ne $csec) ) {
                my (undef,$end,$start)=split(/\_/,$roles{$course});
                my $now=time;
                # if this is an active role
                if (!($start && ($now<$start)) || !($end && ($now>$end))) {
                    my $reply=&Apache::lonnet::modifystudent
                        # dom  name  id mode pass     f     m     l     g
                        ($udom,$unam,'',  '',  '',undef,undef,undef,undef,
                         $section,time,undef,undef,$desiredhost);
                    $result .= $reply.':';
                }
            }
        }
    }
    if ($result eq '') {
        $result = 'Unable to find section for this student';
    } else {
        $result =~ s/(ok:)+/ok/g;
    }
    return $result;
}

sub modifyuserrole {
    my ($context,$setting,$changeauth,$cid,$udom,$uname,$uid,$umode,$upass,
        $first,$middle,$last,$gene,$sec,$forceid,$desiredhome,$email,$role,
        $end,$start) = @_;
    my ($scope,$userresult,$authresult,$roleresult);
    if ($setting eq 'course' || $context eq 'course') {
        $scope = '/'.$cid;
        $scope =~ s/\_/\//g;
        if ($role ne 'cc' && $sec ne '') {
            $scope .='/'.$sec;
        }
    } elsif ($setting eq 'domain') {
        $scope = '/'.$env{'request.role.domain'}.'/';
    } elsif ($setting eq 'construction_space') {
        $scope =  '/'.$env{'user.domain'}.'/'.$env{'user.name'};
    }
    if ($context eq 'domain') {
        my $uhome = &Apache::lonnet::homeserver($uname,$udom);
        if ($uhome ne 'no_host') {
            if (($changeauth) && (&Apache::lonnet::allowed('mau',$udom))) {
                if ((($umode =~ /^krb4|krb5|internal$/) && $upass ne '') ||
                    ($umode eq 'localauth')) {
                    $authresult = &Apache::lonnet::modifyuserauth($udom,$uname,$umode,$upass);
                }
            }
        }
    }
    $userresult =
        &Apache::lonnet::modifyuser($udom,$uname,$uid,$umode,$upass,$first,
                                    $middle,$last,$gene,$forceid,$desiredhome,
                                    $email,$role,$start,$end);
    if ($userresult eq 'ok') {
        if ($role ne '') { 
            $roleresult = &Apache::lonnet::assignrole($udom,$uname,$scope,
                                                      $role,$end,$start);
        }
    }
    return ($userresult,$authresult,$roleresult);
}

###############################################################
###############################################################
# build a domain and server selection form
sub domain_form {
    my ($defdom) = @_;
    # Set up domain and server selection forms
    #
    # Get the domains
    my @domains = &Apache::lonnet::all_domains();
    # build up the menu information to be passed to
    # &Apache::loncommon::linked_select_forms
    my %select_menus;
    foreach my $dom (@domains) {
        # set up the text for this domain
        $select_menus{$dom}->{'text'}= $dom;
        # we want a choice of 'default' as the default in the second menu
        $select_menus{$dom}->{'default'}= 'default';
        $select_menus{$dom}->{'select2'}->{'default'} = 'default';
        # Now build up the other items in the second menu
        my %servers = &Apache::lonnet::get_servers($dom,'library');
        foreach my $server (keys(%servers)) {
            $select_menus{$dom}->{'select2'}->{$server}
                                            = "$server $servers{$server}";
        }
    }
    my $result  = &Apache::loncommon::linked_select_forms
        ('studentform',' with home server ',$defdom,
         'lcdomain','lcserver',\%select_menus);
    return $result;
}

###############################################################
###############################################################
sub hidden_input {
    my ($name,$value) = @_;
    return '<input type="hidden" name="'.$name.'" value="'.$value.'" />'."\n";
}

sub print_upload_manager_header {
    my ($r,$datatoken,$distotal,$krbdefdom,$context)=@_;
    my $javascript;
    #
    if (! exists($env{'form.upfile_associate'})) {
        $env{'form.upfile_associate'} = 'forward';
    }
    if ($env{'form.associate'} eq 'Reverse Association') {
        if ( $env{'form.upfile_associate'} ne 'reverse' ) {
            $env{'form.upfile_associate'} = 'reverse';
        } else {
            $env{'form.upfile_associate'} = 'forward';
        }
    }
    if ($env{'form.upfile_associate'} eq 'reverse') {
        $javascript=&upload_manager_javascript_reverse_associate();
    } else {
        $javascript=&upload_manager_javascript_forward_associate();
    }
    #
    # Deal with restored settings
    my $password_choice = '';
    if (exists($env{'form.ipwd_choice'}) &&
        $env{'form.ipwd_choice'} ne '') {
        # If a column was specified for password, assume it is for an
        # internal password.  This is a bug waiting to be filed (could be
        # local or krb auth instead of internal) but I do not have the
        # time to mess around with this now.
        $password_choice = 'int';
    }
    #
    my $javascript_validations =
        &javascript_validations('auth',$krbdefdom,$password_choice,undef,
                                $env{'request.role.domain'});
    my $checked=(($env{'form.noFirstLine'})?' checked="checked" ':'');
    $r->print(&mt('Total number of records found in file: <b>[_1]</b>.',$distotal).
              "<br />\n");
    $r->print('<div class="LC_left_float"><h3>'.
              &mt('Identify fields in uploaded list')."</h3>\n");
    $r->print(&mt('Enter as many fields as you can.<br /> The system will inform you and bring you back to this page, <br /> if the data selected are insufficient to add users.')."<br />\n");
    $r->print(&hidden_input('action','upload').
              &hidden_input('state','got_file').
              &hidden_input('associate','').
              &hidden_input('datatoken',$datatoken).
              &hidden_input('fileupload',$env{'form.fileupload'}).
              &hidden_input('upfiletype',$env{'form.upfiletype'}).
              &hidden_input('upfile_associate',$env{'form.upfile_associate'}));
    $r->print('<br /><input type="button" value="Reverse Association" '.
              'name="'.&mt('Reverse Association').'" '.
              'onClick="javascript:this.form.associate.value=\'Reverse Association\';submit(this.form);" />');
    $r->print('<label><input type="checkbox" name="noFirstLine"'.$checked.'/>'.
              &mt('Ignore First Line').'</label>');
    $r->print("<br /><br />\n".
              '<script type="text/javascript" language="Javascript">'."\n".
              $javascript."\n".$javascript_validations.'</script>');
}

###############################################################
###############################################################
sub javascript_validations {
    my ($mode,$krbdefdom,$curr_authtype,$curr_authfield,$domain)=@_;
    my $authheader;
    if ($mode eq 'auth') {
        my %param = ( formname => 'studentform',
                      kerb_def_dom => $krbdefdom,
                      curr_authtype => $curr_authtype);
        $authheader = &Apache::loncommon::authform_header(%param);
    } elsif ($mode eq 'createcourse') {
        my %param = ( formname => 'ccrs',
                      kerb_def_dom => $krbdefdom,
                      curr_authtype => $curr_authtype );
        $authheader = &Apache::loncommon::authform_header(%param);
    } elsif ($mode eq 'modifycourse') {
        my %param = ( formname => 'cmod',
                  kerb_def_dom => $krbdefdom,
                  mode => 'modifycourse',
                  curr_authtype => $curr_authtype,
                  curr_autharg => $curr_authfield );
        $authheader = &Apache::loncommon::authform_header(%param);
    }

    my %alert = &Apache::lonlocal::texthash
        (username => 'You need to specify the username field.',
         authen   => 'You must choose an authentication type.',
         krb      => 'You need to specify the Kerberos domain.',
         ipass    => 'You need to specify the initial password.',
         name     => 'The optional name field was not specified.',
         snum     => 'The optional ID number field was not specified.',
         section  => 'The optional section field was not specified.',
         email    => 'The optional email address field was not specified.',
         role     => 'The optional role field was not specified.',
         continue => 'Continue adding users?',
         );

#    my $pjump_def = &Apache::lonhtmlcommon::pjump_javascript_definition();
    my $function_name =(<<END);
function verify_message (vf,founduname,foundpwd,foundname,foundid,foundsec,foundemail) {
END
    my ($authnum,%can_assign) =  &Apache::loncommon::get_assignable_auth($domain);
    my $auth_checks;
    if ($mode eq 'createcourse') {
        $auth_checks .= (<<END);
    if (vf.autoadds[0].checked == true) {
        if (current.radiovalue == null || current.radiovalue == 'nochange') {
            alert('$alert{'authen'}');
            return;
        }
    }
END
    } else {
        $auth_checks .= (<<END);
    var foundatype=0;
    if (founduname==0) {
        alert('$alert{'username'}');
        return;
    }

END
        if ($authnum > 1) {
            $auth_checks .= (<<END);
    if (current.radiovalue == null || current.radiovalue == '' || current.radiovalue == 'nochange') {
        // They did not check any of the login radiobuttons.
        alert('$alert{'authen'}');
        return;
    }
END
        }
    }
    if ($mode eq 'createcourse') {
        $auth_checks .= "
    if ( (vf.autoadds[0].checked == true) &&
         (vf.elements[current.argfield].value == null || vf.elements[current.argfield].value == '') ) {
";
    } elsif ($mode eq 'modifycourse') {
        $auth_checks .= "
    if (vf.elements[current.argfield].value == null || vf.elements[current.argfield].value == '') {
";
    }
    if ( ($mode eq 'createcourse') || ($mode eq 'modifycourse') ) {
        $auth_checks .= (<<END);
        var alertmsg = '';
        switch (current.radiovalue) {
            case 'krb':
                alertmsg = '$alert{'krb'}';
                break;
            default:
                alertmsg = '';
        }
        if (alertmsg != '') {
            alert(alertmsg);
            return;
        }
    }
END
    } else {
        $auth_checks .= (<<END);
    foundatype=1;
    if (current.argfield == null || current.argfield == '') {
        var alertmsg = '';
        switch (current.value) {
            case 'krb':
                alertmsg = '$alert{'krb'}';
                break;
            case 'loc':
            case 'fsys':
                alertmsg = '$alert{'ipass'}';
                break;
            case 'fsys':
                alertmsg = '';
                break;
            default:
                alertmsg = '';
        }
        if (alertmsg != '') {
            alert(alertmsg);
            return;
        }
    }
END
    }
    my $section_checks;
    my $optional_checks = '';
    if ( ($mode eq 'createcourse') || ($mode eq 'modifycourse') ) {
        $optional_checks = (<<END);
    vf.submit();
}
END
    } else {
        $section_checks = &section_check_js();
        $optional_checks = (<<END);
    var message='';
    if (foundname==0) {
        message='$alert{'name'}';
    }
    if (foundid==0) {
        if (message!='') {
            message+='\\n';
        }
        message+='$alert{'snum'}';
    }
    if (foundsec==0) {
        if (message!='') {
            message+='\\n';
        }
    }
    if (foundemail==0) {
        if (message!='') {
            message+='\\n';
        }
        message+='$alert{'email'}';
    }
    if (message!='') {
        message+= '\\n$alert{'continue'}';
        if (confirm(message)) {
            vf.state.value='enrolling';
            vf.submit();
        }
    } else {
        vf.state.value='enrolling';
        vf.submit();
    }
}
END
    }
    my $result = $function_name;
    if ( ($mode eq 'auth') || ($mode eq 'createcourse') || ($mode eq 'modifycourse')  ) {
        $result .= $auth_checks;
    }
    $result .= $optional_checks."\n".$section_checks;
    if ( ($mode eq 'auth') || ($mode eq 'createcourse') || ($mode eq 'modifycourse')  ) {
        $result .= $authheader;
    }
    return $result;
}
###############################################################
###############################################################
sub upload_manager_javascript_forward_associate {
    return(<<ENDPICK);
function verify(vf,sec_caller) {
    var founduname=0;
    var foundpwd=0;
    var foundname=0;
    var foundid=0;
    var foundsec=0;
    var foundemail=0;
    var foundrole=0;
    var tw;
    for (i=0;i<=vf.nfields.value;i++) {
        tw=eval('vf.f'+i+'.selectedIndex');
        if (tw==1) { founduname=1; }
        if ((tw>=2) && (tw<=6)) { foundname=1; }
        if (tw==7) { foundid=1; }
        if (tw==8) { foundsec=1; }
        if (tw==9) { foundpwd=1; }
        if (tw==10) { foundemail=1; }
        if (tw==11) { foundrole=1; }
    }
    verify_message(vf,founduname,foundpwd,foundname,foundid,foundsec,foundemail,foundrole);
}

//
// vf = this.form
// tf = column number
//
// values of nw
//
// 0 = none
// 1 = username
// 2 = names (lastname, firstnames)
// 3 = fname (firstname)
// 4 = mname (middlename)
// 5 = lname (lastname)
// 6 = gen   (generation)
// 7 = id
// 8 = section
// 9 = ipwd  (password)
// 10 = email address
// 11 = role

function flip(vf,tf) {
   var nw=eval('vf.f'+tf+'.selectedIndex');
   var i;
   // make sure no other columns are labeled the same as this one
   for (i=0;i<=vf.nfields.value;i++) {
      if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
          eval('vf.f'+i+'.selectedIndex=0;')
      }
   }
   // If we set this to 'lastname, firstnames', clear out all the ones
   // set to 'fname','mname','lname','gen' (3,4,5,6) currently.
   if (nw==2) {
      for (i=0;i<=vf.nfields.value;i++) {
         if ((eval('vf.f'+i+'.selectedIndex')>=3) &&
             (eval('vf.f'+i+'.selectedIndex')<=6)) {
             eval('vf.f'+i+'.selectedIndex=0;')
         }
      }
   }
   // If we set this to one of 'fname','mname','lname','gen' (3,4,5,6),
   // clear out any that are set to 'lastname, firstnames' (2)
   if ((nw>=3) && (nw<=6)) {
      for (i=0;i<=vf.nfields.value;i++) {
         if (eval('vf.f'+i+'.selectedIndex')==2) {
             eval('vf.f'+i+'.selectedIndex=0;')
         }
      }
   }
   // If we set the password, make the password form below correspond to
   // the new value.
   if (nw==9) {
       changed_radio('int',document.studentform);
       set_auth_radio_buttons('int',document.studentform);
       vf.intarg.value='';
       vf.krbarg.value='';
       vf.locarg.value='';
   }
}

function clearpwd(vf) {
    var i;
    for (i=0;i<=vf.nfields.value;i++) {
        if (eval('vf.f'+i+'.selectedIndex')==9) {
            eval('vf.f'+i+'.selectedIndex=0;')
        }
    }
}

ENDPICK
}

###############################################################
###############################################################
sub upload_manager_javascript_reverse_associate {
    return(<<ENDPICK);
function verify(vf,sec_caller) {
    var founduname=0;
    var foundpwd=0;
    var foundname=0;
    var foundid=0;
    var foundsec=0;
    var foundrole=0;
    var tw;
    for (i=0;i<=vf.nfields.value;i++) {
        tw=eval('vf.f'+i+'.selectedIndex');
        if (i==0 && tw!=0) { founduname=1; }
        if (((i>=1) && (i<=5)) && tw!=0 ) { foundname=1; }
        if (i==6 && tw!=0) { foundid=1; }
        if (i==7 && tw!=0) { foundsec=1; }
        if (i==8 && tw!=0) { foundpwd=1; }
        if (i==9 && tw!=0) { foundrole=1; }
    }
    verify_message(vf,founduname,foundpwd,foundname,foundid,foundsec,foundrole);
}

function flip(vf,tf) {
   var nw=eval('vf.f'+tf+'.selectedIndex');
   var i;
   // picked the all one name field, reset the other name ones to blank
   if (tf==1 && nw!=0) {
      for (i=2;i<=5;i++) {
         eval('vf.f'+i+'.selectedIndex=0;')
      }
   }
   //picked one of the piecewise name fields, reset the all in
   //one field to blank
   if ((tf>=2) && (tf<=5) && (nw!=0)) {
      eval('vf.f1.selectedIndex=0;')
   }
   // intial password specified, pick internal authentication
   if (tf==8 && nw!=0) {
       changed_radio('int',document.studentform);
       set_auth_radio_buttons('int',document.studentform);
       vf.krbarg.value='';
       vf.intarg.value='';
       vf.locarg.value='';
   }
}

function clearpwd(vf) {
    var i;
    if (eval('vf.f8.selectedIndex')!=0) {
        eval('vf.f8.selectedIndex=0;')
    }
}
ENDPICK
}

###############################################################
###############################################################
sub print_upload_manager_footer {
    my ($r,$i,$keyfields,$defdom,$today,$halfyear,$context)=@_;
    my $formname;
    if ($context eq 'course') {
        $formname = 'document.studentform';
    } elsif ($context eq 'construction_space') {
        $formname = 'document.studentform';
    } elsif ($context eq 'domain') {
        $formname = 'document.studentform';
    }
    my ($krbdef,$krbdefdom) =
        &Apache::loncommon::get_kerberos_defaults($defdom);
    my %param = ( formname => $formname,
                  kerb_def_dom => $krbdefdom,
                  kerb_def_auth => $krbdef
                  );
    if (exists($env{'form.ipwd_choice'}) &&
        defined($env{'form.ipwd_choice'}) &&
        $env{'form.ipwd_choice'} ne '') {
        $param{'curr_authtype'} = 'int';
    }
    my $krbform = &Apache::loncommon::authform_kerberos(%param);
    my $intform = &Apache::loncommon::authform_internal(%param);
    my $locform = &Apache::loncommon::authform_local(%param);
    my $date_table = &date_setting_table(undef,undef,$context);

    my $Str = "\n".'<div class="LC_left_float">';
    $Str .= &hidden_input('nfields',$i);
    $Str .= &hidden_input('keyfields',$keyfields);
    $Str .= "<h3>".&mt('Login Type')."</h3>\n";
    if ($context eq 'domain') {
        $Str .= '<p>'.&mt('Change authentication for existing users to these settings?').'&nbsp;<span class="LC_nobreak"><label><input type="radio" name="changeauth" value="No" checked="checked" />'.&mt('No').'</label>&nbsp;&nbsp;<label><input type="radio" name="changeauth" value="Yes" />'.&mt('Yes').'</label></span></p>'; 
    } else {
        $Str .= "<p>\n".
            &mt('Note: this will not take effect if the user already exists').
            &Apache::loncommon::help_open_topic('Auth_Options').
            "</p>\n";
    }
    $Str .= &set_login($defdom,$krbform,$intform,$locform);
    my ($home_server_pick,$numlib) =
        &Apache::loncommon::home_server_form_item($defdom,'lcserver',
                                                  'default','hide');
    if ($numlib > 1) {
        $Str .= '<h3>'.&mt('LON-CAPA Home Server for New Users')."</h3>\n".
                &mt('LON-CAPA domain: [_1] with home server: [_2]',$defdom,
                $home_server_pick).'<br />';
    } else {
        $Str .= $home_server_pick;
    }
    $Str .= '<h3>'.&mt('Starting and Ending Dates').
            "</h3>\n";
    $Str .= "<p>\n".$date_table."</p>\n";
    if ($context eq 'domain') {
        $Str .= '<h3>'.&mt('Settings for assigning roles:').'</h3>'."\n".
                &mt('Pick the action to take on roles for these users:').'<br /><span class="LC_nobreak"><label><input type="radio" name="roleaction" value="norole" checked="checked" />&nbsp;'.&mt('No role changes').'</label>&nbsp;&nbsp;&nbsp;<label><input type="radio" name="roleaction" value="domain" />&nbsp;'.&mt('Add a domain role').'</label>&nbsp;&nbsp;&nbsp;<label><input type="radio" name="roleaction" value="course" />&nbsp;'.&mt('Add a course role').'</label></span>';
    }
    if ($context eq 'construction_space') {
        $Str .= '<h3>'.&mt('Default role')."</h3>\n".
                &mt('Choose the role to assign to users without one specified in the uploaded file');
    } elsif ($context eq 'course') {
        $Str .= '<h3>'.&mt('Default role and section')."</h3>\n".
                &mt('Choose the role and/or section to assign to users without one specified in the uploaded file');
    } else {
        $Str .= '<br /><br /><b>'.&mt('Default role and/or section')."</b><br />\n".
                &mt('Role and/or section for users without one in the uploaded file.');
    }
    $Str .= '<br /><br />';
    my ($options,$cb_script,$coursepick) = &default_role_selector($context);
    if ($context eq 'domain') {
        $Str .= '<span class="LC_role_level">'.&mt('Domain Level').'</span><br />'.$options.'<br /><br /><span class="LC_role_level">'.&mt('Course Level').'</span><br />'.$cb_script.$coursepick;
    } else {
        $Str .= $options;
    }
    if ($context eq 'course') {
        $Str .= "<h3>".&mt('Full Update')."</h3>\n".
                '<label><input type="checkbox" name="fullup" value="yes">'.
                ' '.&mt('Full update (also print list of users not enrolled anymore)').
                "</label></p>\n";
    }
    $Str .= "<h3>".&mt('ID/Student Number')."</h3>\n";
    $Str .= "<p>\n".'<label><input type="checkbox" name="forceid" value="yes">';
    $Str .= &mt('Disable ID/Student Number Safeguard and Force Change '.
                'of Conflicting IDs').
                '</label><br />'."\n".
                &mt('(only do if you know what you are doing.)')."</p><p>\n";
    $Str .= '</div><div class="LC_clear_float_footer"><br /><input type="button"'.
              'onClick="javascript:verify(this.form,this.form.csec)" '.
        'value="Update Users" />'."<br />\n";
    if ($context eq 'course') {
        $Str .= &mt('Note: for large courses, this operation may be time '.
                    'consuming');
    }
    $Str .= '</div>';
    $r->print($Str);
    return;
}

###############################################################
###############################################################
sub print_upload_manager_form {
    my ($r,$context) = @_;
    my $firstLine;
    my $datatoken;
    if (!$env{'form.datatoken'}) {
        $datatoken=&Apache::loncommon::upfile_store($r);
    } else {
        $datatoken=$env{'form.datatoken'};
        &Apache::loncommon::load_tmp_file($r);
    }
    my @records=&Apache::loncommon::upfile_record_sep();
    if($env{'form.noFirstLine'}){
        $firstLine=shift(@records);
    }
    my $total=$#records;
    my $distotal=$total+1;
    my $today=time;
    my $halfyear=$today+15552000;
    #
    # Restore memorized settings
    my $col_setting_names =  { 'username_choice' => 'scalar', # column settings
                               'names_choice' => 'scalar',
                               'fname_choice' => 'scalar',
                               'mname_choice' => 'scalar',
                               'lname_choice' => 'scalar',
                               'gen_choice' => 'scalar',
                               'id_choice' => 'scalar',
                               'sec_choice' => 'scalar',
                               'ipwd_choice' => 'scalar',
                               'email_choice' => 'scalar',
                               'role_choice' => 'scalar',
                             };
    my $defdom = $env{'request.role.domain'};
    if ($context eq 'course') {
        &Apache::loncommon::restore_course_settings('enrollment_upload',
                                                    $col_setting_names);
    } else {
        &Apache::loncommon::restore_settings($context,'user_upload',
                                             $col_setting_names);
    }
    #
    # Determine kerberos parameters as appropriate
    my ($krbdef,$krbdefdom) =
        &Apache::loncommon::get_kerberos_defaults($defdom);
    #
    &print_upload_manager_header($r,$datatoken,$distotal,$krbdefdom,$context);
    my $i;
    my $keyfields;
    if ($total>=0) {
        my @field=
            (['username',&mt('Username'),     $env{'form.username_choice'}],
             ['names',&mt('Last Name, First Names'),$env{'form.names_choice'}],
             ['fname',&mt('First Name'),      $env{'form.fname_choice'}],
             ['mname',&mt('Middle Names/Initials'),$env{'form.mname_choice'}],
             ['lname',&mt('Last Name'),       $env{'form.lname_choice'}],
             ['gen',  &mt('Generation'),      $env{'form.gen_choice'}],
             ['id',   &mt('ID/Student Number'),$env{'form.id_choice'}],
             ['sec',  &mt('Section'),          $env{'form.sec_choice'}],
             ['ipwd', &mt('Initial Password'),$env{'form.ipwd_choice'}],
             ['email',&mt('E-mail Address'),   $env{'form.email_choice'}],
             ['role',&mt('Role'),             $env{'form.role_choice'}]);
        if ($env{'form.upfile_associate'} eq 'reverse') {
            &Apache::loncommon::csv_print_samples($r,\@records);
            $i=&Apache::loncommon::csv_print_select_table($r,\@records,
                                                          \@field);
            foreach (@field) {
                $keyfields.=$_->[0].',';
            }
            chop($keyfields);
        } else {
            unshift(@field,['none','']);
            $i=&Apache::loncommon::csv_samples_select_table($r,\@records,
                                                            \@field);
            my %sone=&Apache::loncommon::record_sep($records[0]);
            $keyfields=join(',',sort(keys(%sone)));
        }
    }
    $r->print('</div>');
    &print_upload_manager_footer($r,$i,$keyfields,$defdom,$today,$halfyear,
                                 $context);
}

sub setup_date_selectors {
    my ($starttime,$endtime,$mode) = @_;
    if (! defined($starttime)) {
        $starttime = time;
        unless ($mode eq 'create_enrolldates' || $mode eq 'create_defaultdates') {
            if (exists($env{'course.'.$env{'request.course.id'}.
                            '.default_enrollment_start_date'})) {
                $starttime = $env{'course.'.$env{'request.course.id'}.
                                  '.default_enrollment_start_date'};
            }
        }
    }
    if (! defined($endtime)) {
        $endtime = time+(6*30*24*60*60); # 6 months from now, approx
        unless ($mode eq 'createcourse') {
            if (exists($env{'course.'.$env{'request.course.id'}.
                            '.default_enrollment_end_date'})) {
                $endtime = $env{'course.'.$env{'request.course.id'}.
                                '.default_enrollment_end_date'};
            }
        }
    }
    my $startdateform = &Apache::lonhtmlcommon::date_setter('studentform',
                                                            'startdate',
                                                            $starttime);
    my $enddateform = &Apache::lonhtmlcommon::date_setter('studentform',
                                                          'enddate',
                                                          $endtime);
    if ($mode eq 'create_enrolldates') {
        $startdateform = &Apache::lonhtmlcommon::date_setter('ccrs',
                                                            'startenroll',
                                                            $starttime);
        $enddateform = &Apache::lonhtmlcommon::date_setter('ccrs',
                                                          'endenroll',
                                                          $endtime);
    }
    if ($mode eq 'create_defaultdates') {
        $startdateform = &Apache::lonhtmlcommon::date_setter('ccrs',
                                                            'startaccess',
                                                            $starttime);
        $enddateform = &Apache::lonhtmlcommon::date_setter('ccrs',
                                                          'endaccess',
                                                          $endtime);
    }
    return ($startdateform,$enddateform);
}


sub get_dates_from_form {
    my $startdate = &Apache::lonhtmlcommon::get_date_from_form('startdate');
    my $enddate   = &Apache::lonhtmlcommon::get_date_from_form('enddate');
    if ($env{'form.no_end_date'}) {
        $enddate = 0;
    }
    return ($startdate,$enddate);
}

sub date_setting_table {
    my ($starttime,$endtime,$mode) = @_;
    my ($startform,$endform)=&setup_date_selectors($starttime,$endtime,$mode);
    my $dateDefault;
    if ($mode eq 'create_enrolldates' || $mode eq 'create_defaultdates') {
        $dateDefault = '&nbsp;';
    } elsif ($mode ne 'construction_space' && $mode ne 'domain') {
        $dateDefault = '<nobr>'.
        '<label><input type="checkbox" name="makedatesdefault" /> '.
        &mt('make these dates the default for future enrollment').
        '</label></nobr>';
    }
    my $perpetual = '<nobr><label><input type="checkbox" name="no_end_date"';
    if (defined($endtime) && $endtime == 0) {
        $perpetual .= ' checked';
    }
    $perpetual.= ' /> '.&mt('no ending date').'</label></nobr>';
    if ($mode eq 'create_enrolldates') {
        $perpetual = '&nbsp;';
    }
    my $result = &Apache::lonhtmlcommon::start_pick_box()."\n".
                 &Apache::lonhtmlcommon::row_title(&mt('Starting Date'),
                                                   'LC_oddrow_value')."\n".
                 $startform."\n".
                 &Apache::lonhtmlcommon::row_closure(1).
                 &Apache::lonhtmlcommon::row_title(&mt('Ending Date'),
                                                   'LC_oddrow_value')."\n".
                 $endform.'&nbsp;'.$perpetual.
                 &Apache::lonhtmlcommon::row_closure(1).
                 &Apache::lonhtmlcommon::end_pick_box().'<br />';
    if ($dateDefault) {
        $result .=  $dateDefault.'<br />'."\n";
    }
    return $result;
}

sub make_dates_default {
    my ($startdate,$enddate,$context) = @_;
    my $result = '';
    if ($context eq 'course') {
        my $dom = $env{'course.'.$env{'request.course.id'}.'.domain'};
        my $crs = $env{'course.'.$env{'request.course.id'}.'.num'};
        my $put_result = &Apache::lonnet::put('environment',
                {'default_enrollment_start_date'=>$startdate,
                 'default_enrollment_end_date'  =>$enddate},$dom,$crs);
        if ($put_result eq 'ok') {
            $result .= "Set default start and end dates for course<br />";
            #
            # Refresh the course environment
            &Apache::lonnet::coursedescription($env{'request.course.id'},
                                               {'freshen_cache' => 1});
        } else {
            $result .= &mt('Unable to set default dates for course').":".$put_result.
                       '<br />';
        }
    }
    return $result;
}

sub default_role_selector {
    my ($context) = @_;
    my %customroles;
    my ($options,$coursepick,$cb_jscript);
    if ($context ne 'construction_space') {
        %customroles = &my_custom_roles();
    }

    my %lt=&Apache::lonlocal::texthash(
                    'rol'  => "Role",
                    'grs'  => "Section",
                    'exs'  => "Existing sections",
                    'new'  => "New section",
                  );
    $options = '<select name="defaultrole">'."\n".
               ' <option value="">'.&mt('Please select').'</option>'."\n"; 
    if ($context eq 'course') {
        $options .= &default_course_roles($context,%customroles);
    } elsif ($context eq 'construction_space') {
        my @roles = &construction_space_roles();
        foreach my $role (@roles) {
           my $plrole=&Apache::lonnet::plaintext($role);
           $options .= '  <option value="'.$role.'">'.$plrole.'</option>'."\n";
        }
    } elsif ($context eq 'domain') {
        my @roles = &domain_roles();
        foreach my $role (@roles) {
           my $plrole=&Apache::lonnet::plaintext($role);
           $options .= '  <option value="'.$role.'">'.$plrole.'</option>';
        }
        my $courseform = &Apache::loncommon::selectcourse_link
            ('studentform','defaultcourse','defaultdomain','defaultdesc',"$env{'request.role.domain'}",undef,'Course');
        $cb_jscript = 
            &Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'},'defaultsec','studentform');
        $coursepick = &Apache::loncommon::start_data_table().
                      &Apache::loncommon::start_data_table_header_row().
                      '<th>'.$courseform.'</th><th>'.$lt{'rol'}.'</th>'.
                      '<th>'.$lt{'grs'}.'</th>'.
                      &Apache::loncommon::end_data_table_header_row().
                      &Apache::loncommon::start_data_table_row()."\n".
                      '<td><input type="text" name="defaultdesc" value="" onFocus="this.blur();opencrsbrowser('."'studentform','defcourse','defdomain','coursedesc',''".')" /></td>'."\n".
                      '<td><select name="courserole">'."\n".
                      &default_course_roles($context,%customroles)."\n".
                      '</select></td><td>'.
                      '<table class="LC_createuser">'.
                      '<tr class="LC_section_row"><td valign"top">'.
                      $lt{'exs'}.'<br /><select name="defaultsec">'.
                      ' <option value=""><--'.&mt('Pick course first').
                      '</select></td>'.
                      '<td>&nbsp;&nbsp;</td>'.
                      '<td valign="top">'.$lt{'new'}.'<br />'.
                      '<input type="text" name="newsec" value="" size="5" />'.
                      '<input type="hidden" name="groups" value="" /></td>'.
                      '</tr></table></td>'.
                      &Apache::loncommon::end_data_table_row().
                      &Apache::loncommon::end_data_table()."\n".
                      '<input type="hidden" name="defaultcourse" value="" />'.
                      '<input type="hidden" name="defaultdomain" value="" />';
    }
    $options .= '</select>';
    return ($options,$cb_jscript,$coursepick);
}

sub default_course_roles {
    my ($context,%customroles) = @_;
    my $output;
    my @roles = &course_roles($context);
    foreach my $role (@roles) {
        my $plrole=&Apache::lonnet::plaintext($role);
        $output .= '  <option value="'.$role.'">'.$plrole.'</option>';
    }
    if (keys(%customroles) > 0) {
        foreach my $cust (sort(keys(%customroles))) {
            my $custrole='cr_cr_'.$env{'user.domain'}.
                '_'.$env{'user.name'}.'_'.$cust;
            $output .= '  <option value="'.$custrole.'">'.$cust.'</option>';
        }
    }
    return $output;
}

sub construction_space_roles {
    my @allroles = ('ca','aa');
    my @roles;
    foreach my $role (@allroles) {
        if (&Apache::lonnet::allowed('c'.$role,$env{'user.domain'}.'/'.$env{'user.name'})) { 
            push(@roles,$role); 
        }
    }
    return @roles;
}

sub domain_roles {
    my @allroles = ('dc','li','dg','au','sc');
    my @roles;
    foreach my $role (@allroles) {
        if (&Apache::lonnet::allowed('c'.$role,$env{'request.role.domain'})) {
            push(@roles,$role);
        }
    }
    return @roles;
}

sub course_roles {
    my ($context) = @_;
    my @allroles = ('st','ta','ep','in','cc');
    my @roles;
    if ($context eq 'domain') {
        @roles = @allroles;
    } elsif ($context eq 'course') {
        if ($env{'request.course.id'}) {
            foreach my $role (@allroles) {
                if (&Apache::lonnet::allowed('c'.$role,$env{'request.course.id'})) {
                    push(@roles,$role);  
                } else {
                    if ($role ne 'cc' && $env{'request.course.section'} ne '') {
                        if (!&Apache::lonnet::allowed('c'.$role,
                                         $env{'request.course.id'}.'/'.
                                         $env{'request.course.section'})) {
                            push(@roles,$role);
                        }
                    }
                }
            }
        }
    }
    return @roles;
}

sub curr_role_permissions {
    my ($context,$setting) = @_; 
    my @roles;
    if ($context eq 'construction_space') {
        @roles = &construction_space_roles();
    } elsif ($context eq 'domain') {
        if ($setting eq 'course') {
            @roles = &course_roles($context); 
        } else {
            @roles = &domain_roles();
        }
    } elsif ($context eq 'course') {
        @roles = &course_roles($context);
    }
    return @roles;
}

# ======================================================= Existing Custom Roles

sub my_custom_roles {
    my %returnhash=();
    my %rolehash=&Apache::lonnet::dump('roles');
    foreach my $key (keys %rolehash) {
        if ($key=~/^rolesdef\_(\w+)$/) {
            $returnhash{$1}=$1;
        }
    }
    return %returnhash;
}

sub print_html_classlist {
    my ($r,$mode,$permission,$context) = @_;
    if (! exists($env{'form.sortby'})) {
        $env{'form.sortby'} = 'username';
    }
    if ($env{'form.status'} !~ /^(Any|Expired|Active|Future)$/) {
        $env{'form.status'} = 'Active';
    }
    my $status_select = &Apache::lonhtmlcommon::StatusOptions
        ($env{'form.status'});

    if (! defined($env{'form.output'}) ||
        $env{'form.output'} !~ /^(csv|excel|html)$/ ) {
        $env{'form.output'} = 'html';
    }

    if ($context eq 'course') { 
        my $cid =$env{'request.course.id'};
        my $cdom=$env{'course.'.$cid.'.domain'};
        my $cnum=$env{'course.'.$cid.'.num'};
        #
        # List course personnel
        my %coursepersonnel=&Apache::lonnet::get_course_adv_roles($cdom.'/'.$cnum);
        #

        $r->print('<br />'.&Apache::loncommon::start_data_table());
        foreach my $role (sort keys %coursepersonnel) {
            next if ($role =~ /^\s*$/);
            $r->print(&Apache::loncommon::start_data_table_row().
                      '<td>'.$role.'</td><td>');
            foreach my $user (split(',',$coursepersonnel{$role})) {
                my ($puname,$pudom)=split(':',$user);
                $r->print(' '.&Apache::loncommon::aboutmewrapper(
                          &Apache::loncommon::plainname($puname,$pudom),
                          $puname,$pudom));
            }
            $r->print('</td>'.&Apache::loncommon::end_data_table_row());
        }
        $r->print(&Apache::loncommon::end_data_table());
    }
    #
    # Interface output
    $r->print('<input type="hidden" name="action" value="'.
              $env{'form.action'}.'" />');
    $r->print("<p>\n");
    if ($env{'form.action'} ne 'modifystudent') {
        my %lt=&Apache::lonlocal::texthash('csv' => "CSV",
                                           'excel' => "Excel",
                                           'html'  => 'HTML');
        my $output_selector = '<select size="1" name="output" >';
        foreach my $outputformat ('html','csv','excel') {
            my $option = '<option value="'.$outputformat.'" ';
            if ($outputformat eq $env{'form.output'}) {
                $option .= 'selected ';
            }
            $option .='>'.$lt{$outputformat}.'</option>';
            $output_selector .= "\n".$option;
        }
        $output_selector .= '</select>';
        $r->print('<label>'.&mt('Output Format: [_1]',$output_selector).'</label>'.('&nbsp;'x3));
    }
    $r->print('<label>'.&mt('Student Status: [_1]',$status_select)."</label>\n");
    $r->print('<input type="submit" value="'.&mt('Update Display').'" />'.
              "\n</p>\n");

    if ($context eq 'course') {
        #
        # Print the classlist
        $r->print('<h2>'.&mt('Current Class List').'</h2>');
        my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();

        if (exists($permission->{'view_section'})) {
            my $sec = &Apache::loncoursedata::CL_SECTION();
            foreach my $student (keys(%{$classlist})) {
                if ($classlist->{$student}[$sec] ne $permission->{'view_section'}) {
                    delete($classlist->{$student});
                }
            }
        }

        if (! defined($classlist)) {
            $r->print(&mt('There are no students currently enrolled.')."\n");
        } else {
            # Print out the available choices
            if ($env{'form.action'} eq 'modifystudent') {
                &show_users_list($r,$context,'view','modify',
                                 $env{'form.Status'},$classlist,$keylist);
            } else {
                &show_users_list($r,$context,$env{'form.output'},'aboutme',
                                 $env{'form.Status'},$classlist,$keylist);
            }
        }
    } elsif ($context eq 'construction_space') {
        # List co-authors and assistant co-authors
        my @statuses;
        if ($env{'form.status'} eq 'Any') {
            @statuses = ('previous','active','future');
        } elsif ($env{'form.status'} eq 'Expired') {
            @statuses = ('previous');
        } elsif ($env{'form.status'} eq 'Active') {
            @statuses = ('active');
        } elsif ($env{'form.status'} eq 'Future') {
            @statuses = ('future');
        }
        my @possroles = ('ca','aa');
        my %cstr_roles = &Apache::lonnet::get_my_roles(undef,undef,undef,
                                          \@statuses,\@possroles);
        if (keys(%cstr_roles) == 0) {
             $r->print(&mt('There are no authors or co-authors.')."\n");
        } else {
            # Print out the available choices
            if ($env{'form.action'} eq 'modifystudent') {
                &show_users_list($r,$context,'view','modify',
                                 $env{'form.Status'},\%cstr_roles);
            } else {
                &show_users_list($r,$context,$env{'form.output'},'aboutme',
                                 $env{'form.Status'},\%cstr_roles);
            }
        }
    } else {

    }
}

sub show_users_list {
    my ($r,$context,$mode,$linkto,$statusmode,$classlist,$keylist)=@_;
    #
    # Variables for excel output
    my ($excel_workbook, $excel_sheet, $excel_filename,$row,$format);
    #
    # Variables for csv output
    my ($CSVfile,$CSVfilename);
    #
    my $sortby = $env{'form.sortby'};
    if ($sortby !~ /^(username|domain|section|groups|fullname|id|start|end|type)$/) {
        $sortby = 'username';
    }
    my ($cid,$cdom,$cnum,$classgroups,$displayphotos,$displayclickers)=@_;
    if ($context eq 'course') {
        $cid=$env{'request.course.id'};
        $cdom = $env{'course.'.$cid.'.domain'};
        $cnum = $env{'course.'.$cid.'.num'};
        $classgroups = &Apache::loncoursedata::get_group_memberships(
                                     $classlist,$keylist,$cdom,$cnum);
        if (! exists($env{'form.displayphotos'})) {
            $env{'form.displayphotos'} = 'off';
        }
        $displayphotos = $env{'form.displayphotos'};
        if (! exists($env{'form.displayclickers'})) {
            $env{'form.displayclickers'} = 'off';
        }
        $displayclickers = $env{'form.displayclickers'};
        if ($env{'course.'.$cid.'.internal.showphoto'}) {
            $r->print('
<script type="text/javascript">
function photowindow(photolink) {
    var title = "Photo_Viewer";
    var options = "scrollbars=1,resizable=1,menubar=0";
    options += ",width=240,height=240";
    stdeditbrowser = open(photolink,title,options,"1");
    stdeditbrowser.focus();
}
</script>
           ');
        }
        $r->print(<<END);
<input type="hidden" name="displayphotos" value="$displayphotos" />
<input type="hidden" name="displayclickers" value="$displayclickers" />
END
    }
    unless ($mode eq 'autoenroll') {
        $r->print(<<END);
<input type="hidden" name="state" value="$env{'form.state'}" />
END
    }
    $r->print(<<END);
<input type="hidden" name="sortby" value="$sortby" />
END

    my %lt=&Apache::lonlocal::texthash(
                       'username'   => "username",
                       'domain'     => "domain",
                       'id'         => 'ID',
                       'fullname'   => "name",
                       'section'    => "section",
                       'groups'     => "active groups",
                       'start'      => "start date",
                       'end'        => "end date",
                       'status'     => "status",
                       'type'       => "enroll type/action",
                       'email'      => "email address",
                       'clicker'    => "clicker id",
                       'photo'      => "photo",
                      );
    my @cols = ('username','domain','id','fullname');
    if ($context eq 'course') {
        push(@cols,'section');
    }
    push(@cols,('start','end'));
    if ($statusmode eq 'Any') {
        push(@cols,'status');
    }
    if ($context eq 'course') {
        push(@cols,'groups');
    }
    push(@cols,'email');

    if ($mode eq 'html' || $mode eq 'view') {
        if ($linkto eq 'aboutme') {
            $r->print(&mt("Select a user name to view the user's personal page."));
        } elsif ($linkto eq 'modify') {
            $r->print(&mt("Select a user name to modify the user's information"));
        }
        $r->print(<<END);
<input type="hidden" name="sname"  value="" />
<input type="hidden" name="sdom"   value="" />
END

        $r->print("\n<p>\n".
                  &Apache::loncommon::start_data_table().
                  &Apache::loncommon::start_data_table_header_row());
        if ($mode eq 'autoenroll') {
            $r->print("
 <th><a href=\"javascript:document.studentform.sortby.value='type';document.studentform.submit();\">$lt{'type'}</a></th>
            ");
        } else {
            $r->print("
<th>Count</th>
            ");
        }
        foreach my $item (@cols) {
            $r->print('<th><a href="javascript:document.studentform.sortby.value='.$item.';document.studentform.submit();">'.$lt{$item}.'</a></th>'."\n");
        }
        if ($context eq 'course') {
            # Clicker display on or off?
            my %clicker_options = &Apache::lonlocal::texthash(
                                                        'on' => 'Show',
                                                        'off' => 'Hide',
                                                       );
            my $clickerchg = 'on';
            if ($displayclickers eq 'on') {
                $clickerchg = 'off';
            }
            $r->print('    <th>'."\n".'     '.
                '<a href="javascript:document.studentform.displayclickers.value='.
                      "'".$clickerchg."'".';document.studentform.submit();">'.
                      $clicker_options{$clickerchg}.'</a>&nbsp;'.$lt{'clicker'}."\n".
                      '    </th>'."\n");

            # Photo display on or off?
            if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
                my %photo_options = &Apache::lonlocal::texthash(
                                                        'on' => 'Show',
                                                        'off' => 'Hide',
                                                            );
                my $photochg = 'on';
                if ($displayphotos eq 'on') {
                    $photochg = 'off';
                }
                $r->print('    <th>'."\n".'     '.
            '<a href="javascript:document.studentform.displayphotos.value='.
                      "'".$photochg."'".';document.studentform.submit();">'.
                      $photo_options{$photochg}.'</a>&nbsp;'.$lt{'photo'}."\n".
                      '    </th>'."\n");
            }
            $r->print(&Apache::end_data_table_header_row());
        } 
# Done with the HTML header line

    } elsif ($mode eq 'csv') {
        #
        # Open a file
        $CSVfilename = '/prtspool/'.
            $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
            time.'_'.rand(1000000000).'.csv';
        unless ($CSVfile = Apache::File->new('>/home/httpd'.$CSVfilename)) {
            $r->log_error("Couldn't open $CSVfilename for output $!");
            $r->print("Problems occured in writing the csv file.  ".
                      "This error has been logged.  ".
                      "Please alert your LON-CAPA administrator.");
            $CSVfile = undef;
        }
        #
        # Write headers and data to file
        if($statusmode eq 'Expired') {
            print $CSVfile '"'.&mt('Users with expired roles').'"'."\n";        }
        if($statusmode eq 'Future') {
            print $CSVfile '"'.&mt('Users with future roles').'"'."\n";
        }
        print $CSVfile '"'.join('","',map {
            &Apache::loncommon::csv_translate($lt{$_})
            } (@cols)).'"'."\n";
    } elsif ($mode eq 'excel') {
        # Create the excel spreadsheet
        ($excel_workbook,$excel_filename,$format) =
            &Apache::loncommon::create_workbook($r);
        return if (! defined($excel_workbook));
        $excel_sheet = $excel_workbook->addworksheet('userlist');
        #
        my $description;
        if ($context eq 'course') {
            $description = &mt('Class List for ').
                $env{'course.'.$env{'request.course.id'}.'.description'};
        } elsif ($context eq 'construction_space') {
            $description = &mt('List of co-authors for construction space for [_1]',
                           &Apache::loncommon::plainname($env{'user.name'},$env{'user.domain'}));
        } else {
            $description = &mt('List of users for domain: [_1]',&Apache::lonnet::domain($env{'request.role.domain'},'description'));
        }
        $excel_sheet->write($row++,0,$description,$format->{'h1'});
        #
        my @colnames = map {$lt{$_}} (@cols);
        $excel_sheet->write($row++,0,\@colnames,$format->{'bold'});
    }

# Done with header lines in all formats

    #
    # Sort the users
    my %index;
    my $i;
    foreach (@$keylist) {
        $index{$_} = $i++;
    }
    $index{'groups'} = scalar(@$keylist);
    my $index  = $index{$sortby};
    my $second = $index{'username'};
    my $third  = $index{'domain'};
    my @Sorted_Students = sort {
        lc($classlist->{$a}->[$index])  cmp lc($classlist->{$b}->[$index])
            ||
        lc($classlist->{$a}->[$second]) cmp lc($classlist->{$b}->[$second])            ||
        lc($classlist->{$a}->[$third]) cmp lc($classlist->{$b}->[$third])
        } (keys(%$classlist));
    my $studentcount = 0;
    my $autocount = 0;
    my $manualcount = 0;
    my $unlockcount = 0;
    my $lockcount = 0;
    foreach my $student (@Sorted_Students) {
        my $sdata = $classlist->{$student};
        my $groups = $classgroups->{$student};
        my $username = $sdata->[$index{'username'}];
        my $domain   = $sdata->[$index{'domain'}];
        my $section  = $sdata->[$index{'section'}];
        my $active_groups;
        if (ref($groups->{active}) eq 'HASH') {
            $active_groups = join(', ',keys(%{$groups->{'active'}}));
        }
        my $name     = $sdata->[$index{'fullname'}];
        my $id       = $sdata->[$index{'id'}];
        my $status   = $sdata->[$index{'status'}];
        next if (($statusmode ne 'Any') && ($status ne $statusmode));
        my $start    = $sdata->[$index{'start'}];
        my $end      = $sdata->[$index{'end'}];
        if (! defined($start) || $start == 0) {
            $start = &mt('none');
        } else {
            $start = &Apache::lonlocal::locallocaltime($start);
        }
        if (! defined($end) || $end == 0) {
            $end = &mt('none');
        } else {
            $end = &Apache::lonlocal::locallocaltime($end);
        }
        my $status   = $sdata->[$index{'status'}];
        next if ($status ne 'Active');
        #
        $r->print(&Apache::loncommon::start_data_table_row());
        $r->print(<<"END");
    <td><input type="checkbox" name="droplist" value="$student"></td>
    <td>$username</td>
    <td>$domain</td>
    <td>$id</td>
    <td>$name</td>
    <td>$start</td>
    <td>$end</td>
END
        $r->print(&Apache::loncommon::end_data_table_row());
    }
    $r->print(&Apache::loncommon::end_data_table().'<br />');
    %lt=&Apache::lonlocal::texthash(
                       'dp'   => "Expire User Roles",
                       'ca'   => "check all",
                       'ua'   => "uncheck all",
                                       );
    $r->print(<<"END");
</p><p>
<input type="button" value="$lt{'ca'}" onclick="javascript:checkAll(document.studentform.droplist)"> &nbsp;
<input type="button" value="$lt{'ua'}" onclick="javascript:uncheckAll(document.studentform.droplist)">
<p><input type=submit value="$lt{'dp'}"></p>
END
    return;
}

#################################################
#################################################
sub show_drop_list {
    my ($r,$classlist,$keylist,$nosort)=@_;
    my $cid=$env{'request.course.id'};
    if (! exists($env{'form.sortby'})) {
        &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                                                ['sortby']);
    }
    my $sortby = $env{'form.sortby'};
    if ($sortby !~ /^(username|domain|section|groups|fullname|id|start|end)$/) {
        $sortby = 'username';
    }
    my $cdom = $env{'course.'.$cid.'.domain'};
    my $cnum = $env{'course.'.$cid,'.num'};
    my ($classgroups) = &Apache::loncoursedata::get_group_memberships(
                                              $classlist,$keylist,$cdom,$cnum);
    #
    my $action = "drop";
    $r->print(<<END);
<input type="hidden" name="sortby" value="$sortby" />
<input type="hidden" name="action" value="$action" />
<input type="hidden" name="state"  value="done" />
<script>
function checkAll(field) {
    for (i = 0; i < field.length; i++)
        field[i].checked = true ;
}

function uncheckAll(field) {
    for (i = 0; i < field.length; i++)
        field[i].checked = false ;
}
</script>
<p>
<input type="hidden" name="phase" value="four">
END

my %lt=&Apache::lonlocal::texthash('usrn'   => "username",
                                   'dom'    => "domain",
                                   'sn'     => "student name",
                                   'sec'    => "section",
                                   'start'  => "start date",
                                   'end'    => "end date",
                                   'groups' => "active groups",
                                   );
    if ($nosort) {
        $r->print(&Apache::loncommon::start_data_table());
        $r->print(<<END);
<tr>
    <th>&nbsp;</th>
    <th>$lt{'usrn'}</th>
    <th>$lt{'dom'}</th>
    <th>ID</th>
    <th>$lt{'sn'}</th>
    <th>$lt{'sec'}</th>
    <th>$lt{'start'}</th>
    <th>$lt{'end'}</th>
    <th>$lt{'groups'}</th>
</tr>
END

    } else  {
        $r->print(&Apache::loncommon::start_data_table());
        $r->print(<<END);
<tr><th>&nbsp;</th>
    <th>
       <a href="/adm/dropadd?action=$action&sortby=username">$lt{'usrn'}</a>
    </th><th>
       <a href="/adm/dropadd?action=$action&sortby=domain">$lt{'dom'}</a>
    </th><th>
       <a href="/adm/dropadd?action=$action&sortby=id">ID</a>
    </th><th>
       <a href="/adm/dropadd?action=$action&sortby=fullname">$lt{'sn'}</a>
    </th><th>
       <a href="/adm/dropadd?action=$action&sortby=section">$lt{'sec'}</a>
    </th><th>
       <a href="/adm/dropadd?action=$action&sortby=start">$lt{'start'}</a>
    </th><th>
       <a href="/adm/dropadd?action=$action&sortby=end">$lt{'end'}</a>
    </th><th>
       <a href="/adm/dropadd?action=$action&sortby=groups">$lt{'groups'}</a>
    </th>
</tr>
END
    }
    #
    # Sort the students
    my %index;
    my $i;
    foreach (@$keylist) {
        $index{$_} = $i++;
    }
    $index{'groups'} = scalar(@$keylist);
    my $index  = $index{$sortby};
    my $second = $index{'username'};
    my $third  = $index{'domain'};
    my @Sorted_Students = sort {
        lc($classlist->{$a}->[$index])  cmp lc($classlist->{$b}->[$index])
            ||
        lc($classlist->{$a}->[$second]) cmp lc($classlist->{$b}->[$second])
            ||
        lc($classlist->{$a}->[$third]) cmp lc($classlist->{$b}->[$third])
        } (keys(%$classlist));
    foreach my $student (@Sorted_Students) {
        my $error;
        my $sdata = $classlist->{$student};
        my $username = $sdata->[$index{'username'}];
        my $domain   = $sdata->[$index{'domain'}];
        my $section  = $sdata->[$index{'section'}];
        my $name     = $sdata->[$index{'fullname'}];
        my $id       = $sdata->[$index{'id'}];
        my $start    = $sdata->[$index{'start'}];
        my $end      = $sdata->[$index{'end'}];
        my $groups = $classgroups->{$student};
        my $active_groups;
        if (ref($groups->{active}) eq 'HASH') {
            $active_groups = join(', ',keys(%{$groups->{'active'}}));
        }
        if (! defined($start) || $start == 0) {
            $start = &mt('none');
        } else {
            $start = &Apache::lonlocal::locallocaltime($start);
        }
        if (! defined($end) || $end == 0) {
            $end = &mt('none');
        } else {
            $end = &Apache::lonlocal::locallocaltime($end);
        }
        my $status   = $sdata->[$index{'status'}];
        next if ($status ne 'Active');
        #
        $r->print(&Apache::loncommon::start_data_table_row());
        $r->print(<<"END");
    <td><input type="checkbox" name="droplist" value="$student"></td>
    <td>$username</td>
    <td>$domain</td>
    <td>$id</td>
    <td>$name</td>
    <td>$section</td>
    <td>$start</td>
    <td>$end</td>
    <td>$active_groups</td>
END
        $r->print(&Apache::loncommon::end_data_table_row());
    }
    $r->print(&Apache::loncommon::end_data_table().'<br />');
    %lt=&Apache::lonlocal::texthash(
                       'dp'   => "Expire Users' Roles",
                       'ca'   => "check all",
                       'ua'   => "uncheck all",
                                       );
    $r->print(<<"END");
</p><p>
<input type="button" value="$lt{'ca'}" onclick="javascript:checkAll(document.studentform.droplist)"> &nbsp;
<input type="button" value="$lt{'ua'}" onclick="javascript:uncheckAll(document.studentform.droplist)">
<p><input type=submit value="$lt{'dp'}"></p>
END
    return;
}



#
# Print out the initial form to get the file containing a list of users
#
sub print_first_users_upload_form {
    my ($r,$context) = @_;
    my $str;
    $str  = '<input type="hidden" name="phase" value="two">';
    $str .= '<input type="hidden" name="action" value="upload" />';
    $str .= '<input type="hidden"   name="state"  value="got_file" />';
    $str .= "<h3>".&mt('Upload a list of users')."</h3>\n";
    $str .= &Apache::loncommon::upfile_select_html();
    $str .= "<p>\n";
    $str .= '<input type="submit" name="fileupload" value="'.
        &mt('Upload users list').'">'."\n";
    $str .= '<label><input type="checkbox" name="noFirstLine" /> '.
        &mt('Ignore First Line')."</label></p>\n";
    $str .= &Apache::loncommon::help_open_topic("Course_Create_Class_List",
                         &mt("How do I create a users list from a spreadsheet")).
                             "<br />\n";
    $str .= &Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                           &mt("How do I create a CSV file from a spreadsheet")).
                               "<br />\n";
    $str .= &Apache::loncommon::end_page();
    $r->print($str);
    return;
}

# ================================================= Drop/Add from uploaded file
sub upfile_drop_add {
    my ($r,$context) = @_;
    &Apache::loncommon::load_tmp_file($r);
    my @userdata=&Apache::loncommon::upfile_record_sep();
    if($env{'form.noFirstLine'}){shift(@userdata);}
    my @keyfields = split(/\,/,$env{'form.keyfields'});
    my %fields=();
    for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
        if ($env{'form.upfile_associate'} eq 'reverse') {
            if ($env{'form.f'.$i} ne 'none') {
                $fields{$keyfields[$i]}=$env{'form.f'.$i};
            }
        } else {
            $fields{$env{'form.f'.$i}}=$keyfields[$i];
        }
    }
    #
    # Store the field choices away
    foreach my $field (qw/username names
                       fname mname lname gen id sec ipwd email role/) {
        $env{'form.'.$field.'_choice'}=$fields{$field};
    }
    &Apache::loncommon::store_course_settings('enrollment_upload',
                                              { 'username_choice' => 'scalar',
                                                'names_choice' => 'scalar',
                                                'fname_choice' => 'scalar',
                                                'mname_choice' => 'scalar',
                                                'lname_choice' => 'scalar',
                                                'gen_choice' => 'scalar',
                                                'id_choice' => 'scalar',
                                                'sec_choice' => 'scalar',
                                                'ipwd_choice' => 'scalar',
                                                'email_choice' => 'scalar',
                                                'role_choice'  => 'scalar' });
    #
    my ($startdate,$enddate) = &get_dates_from_form();
    if ($env{'form.makedatesdefault'}) {
        $r->print(&make_dates_default($startdate,$enddate));
    }
    # Determine domain and desired host (home server)
    my $domain=$env{'request.role.domain'};
    my $desiredhost = $env{'form.lcserver'};
    if (lc($desiredhost) eq 'default') {
        $desiredhost = undef;
    } else {
        my %home_servers = &Apache::lonnet::get_servers($domain,'library');
        if (! exists($home_servers{$desiredhost})) {
            $r->print('<span class="LC_error">'.&mt('Error').
                      &mt('Invalid home server specified').'</span>');
            $r->print(&Apache::loncommon::end_page());
            return;
        }
    }
    # Determine authentication mechanism
    my $changeauth;
    if ($context eq 'domain') {
        $changeauth = $env{'form.changeauth'};
    }
    my $amode  = '';
    my $genpwd = '';
    if ($env{'form.login'} eq 'krb') {
        $amode='krb';
        $amode.=$env{'form.krbver'};
        $genpwd=$env{'form.krbarg'};
    } elsif ($env{'form.login'} eq 'int') {
        $amode='internal';
        if ((defined($env{'form.intarg'})) && ($env{'form.intarg'})) {
            $genpwd=$env{'form.intarg'};
        }
    } elsif ($env{'form.login'} eq 'loc') {
        $amode='localauth';
        if ((defined($env{'form.locarg'})) && ($env{'form.locarg'})) {
            $genpwd=$env{'form.locarg'};
        }
    }
    if ($amode =~ /^krb/) {
        if (! defined($genpwd) || $genpwd eq '') {
            $r->print('<span class="Error">'.
                      &mt('Unable to enroll users').' '.
                      &mt('No Kerberos domain was specified.').'</span></p>');
            $amode = ''; # This causes the loop below to be skipped
        }
    }
    my ($cid,$defaultsec,$defaultrole,$setting);
    if ($context eq 'domain') {
        $setting = $env{'form.roleaction'};
        if ($setting eq 'domain') {
            $defaultrole = $env{'form.defaultrole'};
        } elsif ($setting eq 'course') {
            $defaultrole = $env{'form.courserole'};
        }  
    } elsif ($context eq 'construction_space') {
        $defaultrole = $env{'form.defaultrole'};
    }
    if ($context eq 'domain' && $setting eq 'course') { 
        if ($env{'form.newsec'} ne '') {
            $defaultsec = $env{'form.newsec'};
        } elsif ($env{'form.defaultsec'} ne '') {
            $defaultsec = $env{'form.defaultsec'}
        }
    }
    if ($env{'request.course.id'} ne '') {
        $cid = $env{'request.course.id'};
    } elsif ($env{'form.defaultdomain'} ne '' && $env{'form.defaultcourse'} ne '') {
        $cid = $env{'form.defaultdomain'}.'_'.
               $env{'form.defaultcourse'};
    }
    if ( $domain eq &LONCAPA::clean_domain($domain)
        && ($amode ne '')) {
        #######################################
        ##         Add/Modify Users          ##
        #######################################
        if ($context eq 'course') {
            $r->print('<h3>'.&mt('Enrolling Users')."</h3>\n<p>\n");
        } elsif ($context eq 'construction_space') {
            $r->print('<h3>'.&mt('Updating Co-authors')."</h3>\n<p>\n");
        } else {
            $r->print('<h3>'.&mt('Adding/Modifying Users')."</h3>\n<p>\n");
        }
        my %counts = (
                       user => 0,
                       auth => 0,
                       role => 0,
                     );
        my $flushc=0;
        my %student=();
        my %curr_groups;
        my %userchg;
        if ($context eq 'course') {
            # Get information about course groups
            %curr_groups = &Apache::longroup::coursegroups();
        }
        # Get new users list
        foreach (@userdata) {
            my %entries=&Apache::loncommon::record_sep($_);
            # Determine user name
            unless (($entries{$fields{'username'}} eq '') ||
                    (!defined($entries{$fields{'username'}}))) {
                my ($fname, $mname, $lname,$gen) = ('','','','');
                if (defined($fields{'names'})) {
                    ($lname,$fname,$mname)=($entries{$fields{'names'}}=~
                                            /([^\,]+)\,\s*(\w+)\s*(.*)$/);
                } else {
                    if (defined($fields{'fname'})) {
                        $fname=$entries{$fields{'fname'}};
                    }
                    if (defined($fields{'mname'})) {
                        $mname=$entries{$fields{'mname'}};
                    }
                    if (defined($fields{'lname'})) {
                        $lname=$entries{$fields{'lname'}};
                    }
                    if (defined($fields{'gen'})) {
                        $gen=$entries{$fields{'gen'}};
                    }
                }
                if ($entries{$fields{'username'}}
                    ne &LONCAPA::clean_username($entries{$fields{'username'}})) {
                    $r->print('<br />'.
      &mt('<b>[_1]</b>: Unacceptable username for user [_2] [_3] [_4] [_5]',
          $entries{$fields{'username'}},$fname,$mname,$lname,$gen).
                              '</b>');
                } else {
                    my $username = $entries{$fields{'username'}}; 
                    my $sec;
                    if ($context eq 'course' || $setting eq 'course') {
                        # determine section number
                        if (defined($fields{'sec'})) {
                            if (defined($entries{$fields{'sec'}})) {
                                $sec=$entries{$fields{'sec'}};
                            }
                        } else {
                            $sec = $defaultsec;
                        }
                        # remove non alphanumeric values from section
                        $sec =~ s/\W//g;
                        if ($sec eq "none" || $sec eq 'all') {
                            $r->print('<br />'.
      &mt('<b>[_1]</b>: Unable to enroll: section name "[_2]" for user [_3] [_4] [_5] [_6] is a reserved word.',
                                      $username,$sec,$fname,$mname,$lname,$gen));
                            next;
                        } elsif (($sec ne '') && (exists($curr_groups{$sec}))) {
                            $r->print('<br />'.
      &mt('<b>[_1]</b>: Unable to enroll: section name "[_2]" for user [_3] [_4] [_5] [_6] is a course group. Section names and group names must be distinct.',
                                      $username,$sec,$fname,$mname,$lname,$gen));
                            next;
                        }
                    }
                    # determine id number
                    my $id='';
                    if (defined($fields{'id'})) {
                        if (defined($entries{$fields{'id'}})) {
                            $id=$entries{$fields{'id'}};
                        }
                        $id=~tr/A-Z/a-z/;
                    }
                    # determine email address
                    my $email='';
                    if (defined($fields{'email'})) {
                        if (defined($entries{$fields{'email'}})) {
                            $email=$entries{$fields{'email'}};
                            unless ($email=~/^[^\@]+\@[^\@]+$/) { $email=''; }                        }
                    }
                    # determine user password
                    my $password = $genpwd;
                    if (defined($fields{'ipwd'})) {
                        if ($entries{$fields{'ipwd'}}) {
                            $password=$entries{$fields{'ipwd'}};
                        }
                    }
                    # determine user role
                    my $role = '';
                    if (defined($fields{'role'})) {
                        if ($entries{$fields{'role'}}) {
                             my @poss_roles = 
                                 &curr_role_permissions($context,$setting);
                             if (grep(/^\Q$entries{$fields{'role'}}\E/,@poss_roles)) {
                                $role=$entries{$fields{'role'}};
                            } else {
                                my $rolestr = join(', ',@poss_roles);
                                $r->print('<br />'.
      &mt('<b>[_1]</b>: You do not have permission to add the requested role [_2] for the user.',$entries{$fields{'username'}},$entries{$fields{'role'}}).'<br />'.&mt('Allowable role(s) is/are: [_1].',$rolestr)."\n");
                                next;
                            }
                        }
                    }
                    if ($role eq '') {
                        $role = $defaultrole;
                    }
                    # Clean up whitespace
                    foreach (\$domain,\$username,\$id,\$fname,\$mname,
                             \$lname,\$gen,\$sec,\$role) {
                        $$_ =~ s/(\s+$|^\s+)//g;
                    }
                    if ($password || $env{'form.login'} eq 'loc') {
                        my ($userresult,$authresult,$roleresult);
                        if ($role eq 'st') {
                            &modifystudent($domain,$username,$cid,$sec,
                                           $desiredhost);
                            $roleresult = 
                                &Apache::lonnet::modifystudent
                                    ($domain,$username,$id,$amode,$password,
                                     $fname,$mname,$lname,$gen,$sec,$enddate,
                                     $startdate,$env{'form.forceid'},
                                     $desiredhost,$email);
                        } else {
                            ($userresult,$authresult,$roleresult) = 
                                &modifyuserrole($context,$setting,
                                    $changeauth,$cid,$domain,$username, 
                                    $id,$amode,$password,$fname,
                                    $mname,$lname,$gen,$sec,
                                    $env{'form.forceid'},$desiredhost,
                                    $email,$role,$enddate,$startdate);
                        }
                        $flushc = 
                            &user_change_result($r,$userresult,$authresult,
                                                $roleresult,\%counts,$flushc,
                                                $username,%userchg);
                    } else {
                        if ($context eq 'course') {
                            $r->print('<br />'. 
      &mt('<b>[_1]</b>: Unable to enroll.  No password specified.',$username)
                                     );
                        } elsif ($context eq 'construction_space') {
                            $r->print('<br />'.
      &mt('<b>[_1]</b>: Unable to add co-author.  No password specified.',$username)
                                     );
                        } else {
                            $r->print('<br />'.
      &mt('<b>[_1]</b>: Unable to add user.  No password specified.',$username)
                                     );
                        }
                    }
                }
            }
        } # end of foreach (@userdata)
        # Flush the course logs so reverse user roles immediately updated
        if ($context eq 'course' || ($context eq 'domain' && $setting eq 'course')) {
            &Apache::lonnet::flushcourselogs();
        }
        $r->print("</p>\n<p>\n".&mt('Processed [_1] user(s).',$counts{'user'}).
                  "</p>\n");
        if ($counts{'role'} > 0) {
            $r->print("<p>\n".
                      &mt('Roles added for [_1] users. If user is active, the new role will be available when the user next logs in to LON-CAPA.',$counts{'role'})."</p>\n");
        }
        if ($counts{'auth'} > 0) {
            $r->print("<p>\n".
                      &mt('Authentication changed for [_1] existing users.',
                          $counts{'auth'})."</p>\n");
        }
        $r->print('<form name="uploadresult" action="/adm/createuser">');
        $r->print(&Apache::lonhtmlcommon::echo_form_input(['phase','prevphase','currstate']));
        $r->print('</form>');
        #####################################
        #           Drop students           #
        #####################################
        if ($env{'form.fullup'} eq 'yes') {
            $r->print('<h3>'.&mt('Dropping Students')."</h3>\n");
            #  Get current classlist
            my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
            if (! defined($classlist)) {
                $r->print(&mt('There are no students currently enrolled.').
                          "\n");
            } else {
                # Remove the students we just added from the list of students.
                foreach (@userdata) {
                    my %entries=&Apache::loncommon::record_sep($_);
                    unless (($entries{$fields{'username'}} eq '') ||
                            (!defined($entries{$fields{'username'}}))) {
                        delete($classlist->{$entries{$fields{'username'}}.
                                                ':'.$domain});
                    }
                }
                # Print out list of dropped students.
                &show_drop_list($r,$classlist,$keylist,'nosort');
            }
        }
    } # end of unless
}

sub user_change_result {
    my ($r,$userresult,$authresult,$roleresult,$counts,$flushc,$username,
        $userchg) = @_;
    my $okresult = 0;
    if ($userresult ne 'ok') {
        if ($userresult =~ /^error:(.+)$/) {
            my $error = $1;
            $r->print('<br />'.
                  &mt('<b>[_1]</b>:  Unable to add/modify: [_2]',$username,$error));
        }
    } else {
        $counts->{'user'} ++;
        $okresult = 1;
    }
    if ($authresult ne 'ok') {
        if ($authresult =~ /^error:(.+)$/) {
            my $error = $1;
            $r->print('<br />'.
                  &mt('<b>[_1]</b>:  Unable to modify authentication: [_2]',$username,$error));
        } 
    } else {
        $counts->{'auth'} ++;
        $okresult = 1;
    }
    if ($roleresult ne 'ok') {
        if ($roleresult =~ /^error:(.+)$/) {
            my $error = $1;
            $r->print('<br />'.
                  &mt('<b>[_1]</b>:  Unable to add role: [_2]',$username,$error));
        }
    } else {
        $counts->{'role'} ++;
        $okresult = 1;
    }
    if ($okresult) {
        $flushc++;
        $userchg->{$username}=1;
        $r->print('. ');
        if ($flushc>15) {
            $r->rflush;
            $flushc=0;
        }
    }
    return $flushc;
}

# ========================================================= Menu Phase Two Drop
sub print_expire_menu {
    my ($r,$context) = @_;
    $r->print("<h3>".&mt("Expire Users' Roles")."</h3>");
    my $cid=$env{'request.course.id'};
    my ($classlist,$keylist) = &Apache::loncoursedata::get_classlist();
    if (! defined($classlist)) {
        $r->print(&mt('There are no students currently enrolled.')."\n");
        return;
    }
    # Print out the available choices
    &show_drop_list($r,$classlist,$keylist);
    return;
}


# ================================================================== Phase four

sub expire_user_list {
    my ($r,$context) = @_;
    my $count=0;
    my @droplist = &Apache::loncommon::get_env_multiple('form.droplist');
    foreach (@droplist) {
        my ($uname,$udom)=split(/\:/,$_);
        # drop student
        my $result = &modifystudent($udom,$uname,$env{'request.course.id'});
        if ($result eq 'ok' || $result eq 'ok:') {
            $r->print(&mt('Dropped [_1]',$uname.'@'.$udom).'<br>');
            $count++;
        } else {
            $r->print(
          &mt('Error dropping [_1]:[_2]',$uname.'@'.$udom,$result).
                      '<br />');
        }
    }
    $r->print('<p><b>'.&mt('Dropped [_1] user(s).',$count).'</b></p>');
    $r->print('<p>'.&mt('Re-enrollment will re-activate data.')) if ($count);
}

sub section_check_js {
    my $groupslist;
    my %curr_groups = &Apache::longroup::coursegroups();
    if (%curr_groups) {
        $groupslist = join('","',sort(keys(%curr_groups)));
    }
    return <<"END";
function validate(caller) {
    var groups = new Array("$groupslist");
    var secname = caller.value;
    if ((secname == 'all') || (secname == 'none')) {
        alert("'"+secname+"' may not be used as the name for a section, as it is a reserved word.\\nPlease choose a different section name.");
        return 'error';
    }
    if (secname != '') {
        for (var k=0; k<groups.length; k++) {
            if (secname == groups[k]) {
                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.");
                return 'error';
            }
        }
    }
    return 'ok';
}
END
}

sub set_login {
    my ($dom,$authformkrb,$authformint,$authformloc) = @_;
    my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
    my $response;
    my ($authnum,%can_assign) =
        &Apache::loncommon::get_assignable_auth($dom);
    if ($authnum) {
        $response = &Apache::loncommon::start_data_table();
        if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
            $response .= &Apache::loncommon::start_data_table_row().
                         '<td>'.$authformkrb.'</td>'.
                         &Apache::loncommon::end_data_table_row()."\n";
        }
        if ($can_assign{'int'}) {
            $response .= &Apache::loncommon::start_data_table_row().
                         '<td>'.$authformint.'</td>'.
                         &Apache::loncommon::end_data_table_row()."\n"
        }
        if ($can_assign{'loc'}) {
            $response .= &Apache::loncommon::start_data_table_row().
                         '<td>'.$authformloc.'</td>'.
                         &Apache::loncommon::end_data_table_row()."\n";
        }
        $response .= &Apache::loncommon::end_data_table();
    }
    return $response;
}

1;


--raeburn1193091402--