--- loncom/interface/loncreateuser.pm	2007/07/29 04:32:44	1.161
+++ loncom/interface/loncreateuser.pm	2007/08/31 12:33:32	1.181
@@ -1,7 +1,7 @@
 # The LearningOnline Network with CAPA
 # Create a user
 #
-# $Id: loncreateuser.pm,v 1.161 2007/07/29 04:32:44 raeburn Exp $
+# $Id: loncreateuser.pm,v 1.181 2007/08/31 12:33:32 raeburn Exp $
 #
 # Copyright Michigan State University Board of Trustees
 #
@@ -200,111 +200,13 @@ sub print_username_entry_form {
         $formtoset = 'docustom';
         $env{'form.rolename'} = $env{'form.startrolename'};
     }
-    my ($newuserscript,$newuservalidate);
-
-    if ($forcenewuser) {
-        $newuserscript = <<"ENDSCRIPT";
-
-function setSearch() {
-    var createnew = 0;
-    for (var i=0; i<document.crtuser.forcenew.length; i++) {
-        if (document.crtuser.forcenew[i].checked) {
-            if (document.crtuser.forcenew[i].value == 1) {
-                createnew = 1;
-            }
-        }
-    } 
-    if (createnew == 1) {
-        for (var i=0; i<document.crtuser.srchby.length; i++) {
-            if (document.crtuser.srchby.options[i].value == 'uname') {
-                document.crtuser.srchby.selectedIndex = i;
-            }
-        }
-        for (var i=0; i<document.crtuser.srchin.length; i++) {
-            if (document.crtuser.srchin.options[i].value == 'dom') {
-                document.crtuser.srchin.selectedIndex = i;
-            }
-        }
-        for (var i=0; i<document.crtuser.srchtype.length; i++) {
-            if (document.crtuser.srchtype.options[i].value == 'exact') {
-                document.crtuser.srchtype.selectedIndex = i;
-            }
-        }
-        for (var i=0; i<document.crtuser.srchdomain.length; i++) {
-            if (document.crtuser.srchdomain.options[i].value == '$env{'request.role.domain'}') {
-                document.crtuser.srchdomain.selectedIndex = i;
-            }
-        }
-    }
-}
-ENDSCRIPT
-        $newuservalidate = <<"ENDBLOCK";
-    setSearch();
-ENDBLOCK
-    }
-    my $validatescript = <<"ENDSCRIPT";
-
-function validateEntry() {
-    var checkok = 1;
-    var srchin = document.crtuser.srchin.options[document.crtuser.srchin.selectedIndex].value;
-    var srchtype = document.crtuser.srchtype.options[document.crtuser.srchtype.selectedIndex].value;
-    var srchby = document.crtuser.srchby.options[document.crtuser.srchby.selectedIndex].value;
-    var srchdomain = document.crtuser.srchdomain.options[document.crtuser.srchdomain.selectedIndex].value;
-    var srchterm =  document.crtuser.srchterm.value;
-    var msg = "";
-
-    if (srchterm == "") {
-        checkok = 0;
-        msg += "You must include some text to search for.\\n";
-    }
-
-    $newuservalidate
-
-    if (srchtype== 'contains') {
-        if (srchterm.length < 3) {
-            checkok = 0;
-            msg += "The text you are searching for must contain at least three characters when using a 'contained in' type search.\\n";   
-        }
-    }
-    if (srchin == 'instd') {
-        if (srchdomain == '') {
-            checkok = 0;
-            msg += "You must choose a domain when using an institutional directory search.\\n"; 
-        }
-    }
-    if (srchin == 'dom') {
-        if (srchdomain == '') {
-            checkok = 0;
-            msg += "You must choose a domain when using a domain search.\\n";
-        }
-    }
-    if (srchby == 'lastfirst') {
-        if (srchterm.indexOf(",") == -1) {
-            checkok = 0;
-            msg += "When using searching by last,first you must include a comma as separator between last name and first name.\\n";
-        }
-        if (srchterm.indexOf(",") == srchterm.length -1) { 
-            checkok = 0;
-            msg += "When searching by last,first you must include at least one character in the first name.\\n";
-        }
-    }
-    if (checkok == 0) {
-        alert("The following need to be corrected before the search can be run:\\n"+msg);
-        return;
-    }
-    if (checkok == 1) {
-        document.crtuser.submit();
-    }
-}
-
-ENDSCRIPT
 
     my ($jsback,$elements) = &crumb_utilities();
 
     my $jscript = &Apache::loncommon::studentbrowser_javascript()."\n".
-        '<script type"text/javascript">'."\n".
+        '<script type="text/javascript">'."\n".
         &Apache::lonhtmlcommon::set_form_elements($elements->{$formtoset}).
-        $newuserscript.$validatescript.'</script>'."\n";
+        '</script>'."\n";
 
     my %loaditems = (
                 'onload' => "javascript:setFormElements(document.$formtoset)",
@@ -314,7 +216,7 @@ ENDSCRIPT
 				       $jscript,{'add_entries' => \%loaditems,});
    &Apache::lonhtmlcommon::add_breadcrumb
      ({href=>"javascript:backPage(document.crtuser)",
-       text=>"User/custom role search",
+       text=>"User modify/custom role edit",
        faq=>282,bug=>'Instructor Interface',});
 
     my $crumbs = &Apache::lonhtmlcommon::breadcrumbs('User Management');
@@ -330,6 +232,7 @@ ENDSCRIPT
                     'ecrp' => "Edit Custom Role Privileges",
                     'nr'   => "Name of Role",
                     'cre'  => "Custom Role Editor",
+                    'mod'  => "to add/modify roles",
 				       );
     my $help = &Apache::loncommon::help_open_menu(undef,undef,282,'Instructor Interface');
     my $helpsiur=&Apache::loncommon::help_open_topic('Course_Change_Privileges');
@@ -342,7 +245,7 @@ ENDSCRIPT
 $start_page
 $crumbs
 <h2>$lt{siur}$helpsiur</h2>
-<h3>$lt{'srch'} $sellink</h3>
+<h3>$lt{'srch'} $sellink $lt{'mod'}</h3>
 $response");
     $r->print(&entry_form($defdom,$srch,$forcenewuser));
     if (&Apache::lonnet::allowed('mcr','/')) {
@@ -361,13 +264,14 @@ ENDCUSTOM
 sub entry_form {
     my ($dom,$srch,$forcenewuser) = @_;
     my $userpicker = 
-       &Apache::loncommon::user_picker($dom,$srch,$forcenewuser);
+       &Apache::loncommon::user_picker($dom,$srch,$forcenewuser,
+                                       'document.crtuser');
     my $srchbutton = &mt('Search');
     my $output = <<"ENDDOCUMENT";
 <form action="/adm/createuser" method="post" name="crtuser">
 <input type="hidden" name="phase" value="get_user_info" />
 $userpicker
-<input name="userrole" type="button" value="$srchbutton" onclick="javascript:validateEntry()" />
+<input name="userrole" type="button" value="$srchbutton" onclick="javascript:validateEntry(document.crtuser)" />
 </form>
 ENDDOCUMENT
     return $output;
@@ -402,7 +306,7 @@ END
 
 # =================================================================== Phase two
 sub print_user_selection_page {
-    my ($r,$response,$srch,$srch_results) = @_;
+    my ($r,$response,$srch,$srch_results,$context,$srcharray) = @_;
     my @fields = ('username','domain','lastname','firstname','permanentemail');
     my $sortby = $env{'form.sortby'};
 
@@ -426,25 +330,34 @@ $jsback
 ENDSCRIPT
 
     my %lt=&Apache::lonlocal::texthash(
-                                       'srch'           => "User Search",
+                                       'usrch'          => "User Search to add/modify roles",
+                                       'stusrch'        => "User Search to enroll student",
+                                       'usel'           => "Select a user to add/modify roles",
+                                       'stusel'         => "Select a user to enroll as a student", 
                                        'username'       => "username",
                                        'domain'         => "domain",
                                        'lastname'       => "last name",
                                        'firstname'      => "first name",
                                        'permanentemail' => "permanent e-mail",
                                       );
-    $r->print(&Apache::loncommon::start_page('Create Users, Change User Privileges',$jscript));
-    &Apache::lonhtmlcommon::add_breadcrumb
-        ({href=>"javascript:backPage(document.usersrchform,'','')",
-          text=>"User/custom role search",
-          faq=>282,bug=>'Instructor Interface',},
-         {href=>"javascript:backPage(document.usersrchform,'get_user_info','select')",
-          text=>"Select User",
-          faq=>282,bug=>'Instructor Interface',});
-    $r->print(&Apache::lonhtmlcommon::breadcrumbs('User Management'));
-    $r->print("<b>$lt{'srch'}</b><br />");
-    $r->print(&entry_form($srch->{'srchdomain'},$srch));
-    $r->print('<h3>'.&mt('Select a user').'</h3>');
+    if ($context eq 'createuser') {
+        $r->print(&Apache::loncommon::start_page('Create Users, Change User Privileges',$jscript));
+        &Apache::lonhtmlcommon::add_breadcrumb
+            ({href=>"javascript:backPage(document.usersrchform,'','')",
+              text=>"User modify/custom role edit",
+              faq=>282,bug=>'Instructor Interface',},
+             {href=>"javascript:backPage(document.usersrchform,'get_user_info','select')",
+              text=>"Select User",
+              faq=>282,bug=>'Instructor Interface',});
+        $r->print(&Apache::lonhtmlcommon::breadcrumbs('User Management'));
+        $r->print("<b>$lt{'usrch'}</b><br />");
+        $r->print(&entry_form($srch->{'srchdomain'},$srch));
+        $r->print('<h3>'.$lt{'usel'}.'</h3>');
+    } else {
+        $r->print($jscript."<b>$lt{'stusrch'}</b><br />");
+        $r->print(&Apache::londropadd::single_user_entry_form($srch->{'srchdomain'},$srch));
+        $r->print('</form><h3>'.$lt{'stusel'}.'</h3>');
+    }
     $r->print('<form name="usersrchform" method="post">'.
               &Apache::loncommon::start_data_table()."\n".
               &Apache::loncommon::start_data_table_header_row()."\n".
@@ -457,11 +370,13 @@ ENDSCRIPT
     $r->print(&Apache::loncommon::end_data_table_header_row());
 
     my @sorted_users = sort {
-        lc($srch_results->{$a}->{$sortby})  cmp lc($srch_results->{$b}->{$sortby})
+        lc($srch_results->{$a}->{$sortby})   cmp lc($srch_results->{$b}->{$sortby})
             ||
-        lc($srch_results->{$a}->{lastname}) cmp lc($srch_results->{$b}->{lastname})
+        lc($srch_results->{$a}->{lastname})  cmp lc($srch_results->{$b}->{lastname})
             ||
         lc($srch_results->{$a}->{firstname}) cmp lc($srch_results->{$b}->{firstname})
+	    ||
+	lc($a) cmp lc($b)
         } (keys(%$srch_results));
 
     foreach my $user (@sorted_users) {
@@ -476,19 +391,27 @@ ENDSCRIPT
         $r->print(&Apache::loncommon::end_data_table_row());
     }
     $r->print(&Apache::loncommon::end_data_table().'<br /><br />');
-    $r->print(&Apache::lonhtmlcommon::echo_form_input(['sortby','seluname','seludom','state','phase']));
+    if (ref($srcharray) eq 'ARRAY') {
+        foreach my $item (@{$srcharray}) {
+            $r->print('<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n");
+        }
+    }
     $r->print(' <input type="hidden" name="sortby" value="'.$sortby.'" />'."\n".
               ' <input type="hidden" name="seluname" value="" />'."\n".
               ' <input type="hidden" name="seludom" value="" />'."\n".
-              ' <input type="hidden" name="state" value="select" />'."\n".
-              ' <input type="hidden" name="phase" value="get_user_info" />'."\n".
-              '</form>');
+              ' <input type="hidden" name="currstate" value="select" />'."\n".
+              ' <input type="hidden" name="phase" value="get_user_info" />'."\n");
     $r->print($response);
-    $r->print(&Apache::loncommon::end_page());
+    if ($context eq 'createuser') {
+        $r->print('</form>'.&Apache::loncommon::end_page());
+    } else {
+        $r->print('<input type="hidden" name="action" value="enrollstudent" />'."\n".
+                  '<input type="hidden" name="state" value="gotusername" />'."\n");
+    }
 }
 
 sub print_user_query_page {
-    my ($r) = @_;
+    my ($r,$caller) = @_;
 # FIXME - this is for a network-wide name search (similar to catalog search)
 # To use frames with similar behavior to catalog/portfolio search.
 # To be implemented. 
@@ -516,8 +439,6 @@ sub print_user_modification_page {
     $loginscript  = &Apache::loncommon::authform_header(%param);
     $authformkrb  = &Apache::loncommon::authform_kerberos(%param);
 
-    $ccuname =&LONCAPA::clean_username($ccuname);
-    $ccdomain=&LONCAPA::clean_domain($ccdomain);
     my $pjump_def = &Apache::lonhtmlcommon::pjump_javascript_definition();
     my $dc_setcourse_code = '';
     my $nondc_setsection_code = '';                                        
@@ -730,7 +651,7 @@ ENDSECCODE
 				       $js,{'add_entries' => \%loaditem,});
     &Apache::lonhtmlcommon::add_breadcrumb
      ({href=>"javascript:backPage(document.cu)",
-       text=>"User/custom role search",
+       text=>"User modify/custom role edit",
        faq=>282,bug=>'Instructor Interface',});
 
     if ($env{'form.phase'} eq 'userpicked') {
@@ -768,23 +689,25 @@ ENDFORMINFO
                          srchby => 'uname',
                          srchtype => 'exact',
                        };
-        if ((exists($env{'form.seluname'})) && (exists($env{'form.seludom'}))) {
+        if ($env{'form.phase'} eq 'userpicked') {
             $instsrch->{'srchterm'} = $env{'form.seluname'};
             $instsrch->{'srchdomain'} = $env{'form.seludom'};
         } else {
-            $instsrch->{'srchterm'} = $env{'form.srchterm'};
-            $instsrch->{'srchdomain'} = $env{'form.srchdomain'},
+            $instsrch->{'srchterm'} = $ccuname;
+            $instsrch->{'srchdomain'} = $ccdomain,
         }
         if (($instsrch->{'srchterm'} ne '') && ($instsrch->{'srchdomain'} ne '')) {
             $newuser = $instsrch->{'srchterm'}.':'.$instsrch->{'srchdomain'};
         }
-        my (%dirsrch_results,%inst_results);
+        my (%dirsrch_results,%inst_results,$dirsrchres);
         if ($newuser) {
             if (&directorysrch_check($instsrch) eq 'ok') {
-                %dirsrch_results = &Apache::lonnet::inst_directory_query($instsrch);
-                if (ref($dirsrch_results{$newuser}) eq 'HASH') { 
-                    %inst_results = %{$dirsrch_results{$newuser}};
-                } 
+                ($dirsrchres,%dirsrch_results) = &Apache::lonnet::inst_directory_query($instsrch);
+                if ($dirsrchres eq 'ok') {
+                    if (ref($dirsrch_results{$newuser}) eq 'HASH') { 
+                        %inst_results = %{$dirsrch_results{$newuser}};
+                    }
+                }
             }
         }
         my $home_server_list=
@@ -880,7 +803,7 @@ ENDCHANGEUSER
 '<th>'.$lt{'fn'}.'</th><th>'.$lt{'mn'}.'</th><th>'.$lt{'ln'}.'</th><th>'.$lt{'gen'}.'</th><th>'.$lt{'email'}.'</th>'.
                   &Apache::loncommon::end_data_table_header_row().
                   &Apache::loncommon::start_data_table_row());
-        foreach my $item ('firstname','middlename','lastname','generation','permenanentemail') {
+        foreach my $item ('firstname','middlename','lastname','generation','permanentemail') {
            if (&Apache::lonnet::allowed('mau',$ccdomain)) {
               $r->print(<<"END");
 <td><input type="text" name="c$item" value="$userenv{$item}" size="15" /></td>
@@ -1233,7 +1156,7 @@ ENDNOPRIV
            <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_ca" value="" />
              <a href=
 "javascript:pjump('."'date_start','Start Date Co-Author',document.cu.start_$cudom\_$cuname\_ca.value,'start_$cudom\_$cuname\_ca','cu.pres','dateset'".')">'.$lt{'ssd'}.'</a></td>
-<td><input type=hidden name="end_'.$cudom.'_'.$cuname.'_ca" value="" />
+<td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_ca" value="" />
 <a href=
 "javascript:pjump('."'date_end','End Date Co-Author',document.cu.end_$cudom\_$cuname\_ca.value,'end_$cudom\_$cuname\_ca','cu.pres','dateset'".')">'.$lt{'sed'}.'</a></td>'."\n".
           &Apache::loncommon::end_data_table_row()."\n".
@@ -1241,10 +1164,10 @@ ENDNOPRIV
 '<td><input type=checkbox name="act_'.$cudom.'_'.$cuname.'_aa" /></td>
 <td>'.$lt{'caa'}.'</td>
 <td>'.$cudom.'_'.$cuname.'</td>
-<td><input type=hidden name="start_'.$cudom.'_'.$cuname.'_aa" value="" />
+<td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_aa" value="" />
 <a href=
 "javascript:pjump('."'date_start','Start Date Assistant Co-Author',document.cu.start_$cudom\_$cuname\_aa.value,'start_$cudom\_$cuname\_aa','cu.pres','dateset'".')">'.$lt{'ssd'}.'</a></td>
-<td><input type=hidden name="end_'.$cudom.'_'.$cuname.'_aa" value="" />
+<td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_aa" value="" />
 <a href=
 "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".
@@ -1276,10 +1199,10 @@ ENDNOPRIV
 '<td><input type=checkbox name="act_'.$thisdomain.'_'.$role.'" /></td>
 <td>'.$plrole.'</td>
 <td>'.$thisdomain.'</td>
-<td><input type=hidden name="start_'.$thisdomain.'_'.$role.'" value="" />
+<td><input type="hidden" name="start_'.$thisdomain.'_'.$role.'" value="" />
 <a href=
 "javascript:pjump('."'date_start','Start Date $plrole',document.cu.start_$thisdomain\_$role.value,'start_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'ssd'}.'</a></td>
-<td><input type=hidden name="end_'.$thisdomain.'_'.$role.'" value="" />
+<td><input type="hidden" name="end_'.$thisdomain.'_'.$role.'" value="" />
 <a href=
 "javascript:pjump('."'date_end','End Date $plrole',document.cu.end_$thisdomain\_$role.value,'end_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'sed'}.'</a></td>'.
 &Apache::loncommon::end_data_table_row();
@@ -1301,8 +1224,8 @@ ENDNOPRIV
         $r->print(&course_level_table(%inccourses));
         $r->print('<hr /><input type="button" value="'.&mt('Modify User').'" onClick="setSections()" />'."\n");
     }
-    $r->print(&Apache::lonhtmlcommon::echo_form_input(['phase','userrole','ccdomain','prevphase','state']));
-    $r->print('<input type="hidden" name="state" value="" />');
+    $r->print(&Apache::lonhtmlcommon::echo_form_input(['phase','userrole','ccdomain','prevphase','currstate']));
+    $r->print('<input type="hidden" name="currstate" value="" />');
     $r->print('<input type="hidden" name="prevphase" value="'.$env{'form.phase'}.'" />');
     $r->print("</form>".&Apache::loncommon::end_page());
 }
@@ -1330,7 +1253,7 @@ sub update_user_data {
     $r->print(&Apache::loncommon::start_page($title,$jscript));
     &Apache::lonhtmlcommon::add_breadcrumb
        ({href=>"javascript:backPage(document.userupdate)",
-         text=>"User/custom role search",
+         text=>"User modify/custom role edit",
          faq=>282,bug=>'Instructor Interface',});
     if ($env{'form.prevphase'} eq 'userpicked') {
         &Apache::lonhtmlcommon::add_breadcrumb
@@ -1407,15 +1330,13 @@ sub update_user_data {
 	    $r->print($error.&mt('Invalid login mode or password').$end);    
 	    return;
     }
+
+
+    $r->print('<h2>'.&mt('User [_1] in domain [_2]',
+			 $env{'form.ccuname'}, $env{'form.ccdomain'}).'</h2>');
+
     if ($env{'form.makeuser'}) {
-        # Create a new user
-	my %lt=&Apache::lonlocal::texthash(
-                    'cru'  => "Creating user",                    
-                    'id'   => "in domain"
-					   );
-	$r->print(<<ENDNEWUSERHEAD);
-<h3>$lt{'cru'} "$env{'form.ccuname'}" $lt{'id'} "$env{'form.ccdomain'}"</h3>
-ENDNEWUSERHEAD
+	$r->print('<h3>'.&mt('Creating new account.').'</h3>');
         # Check for the authentication mode and password
         if (! $amode || ! $genpwd) {
 	    $r->print($error.&mt('Invalid login mode or password').$end);    
@@ -1448,13 +1369,6 @@ ENDNEWUSERHEAD
     } elsif (($env{'form.login'} ne 'nochange') &&
              ($env{'form.login'} ne ''        )) {
 	# Modify user privileges
-    my %lt=&Apache::lonlocal::texthash(
-                    'usr'  => "User",                    
-                    'id'   => "in domain"
-				       );
-	$r->print(<<ENDMODIFYUSERHEAD);
-<h2>$lt{'usr'} "$env{'form.ccuname'}" $lt{'id'} "$env{'form.ccdomain'}"</h2>
-ENDMODIFYUSERHEAD
         if (! $amode || ! $genpwd) {
 	    $r->print($error.'Invalid login mode or password'.$end);    
 	    return;
@@ -1552,7 +1466,7 @@ ENDMODIFYUSERHEAD
             $changeHash{'middlename'} = $env{'form.cmiddlename'};
             $changeHash{'lastname'}   = $env{'form.clastname'};
             $changeHash{'generation'} = $env{'form.cgeneration'};
-            $changeHash{'permanentemail'} = $env{'form.permanentemail'};
+            $changeHash{'permanentemail'} = $env{'form.cpermanentemail'};
             my $putresult = &Apache::lonnet::put
                 ('environment',\%changeHash,
                  $env{'form.ccdomain'},$env{'form.ccuname'});
@@ -1577,7 +1491,8 @@ ENDMODIFYUSERHEAD
     <th>$lt{'mddl'}</th>
     <th>$lt{'lst'}</th>
     <th>$lt{'gen'}</th>
-    <th>$lt{'disk'}<th></tr>
+    <th>$lt{'mail'}</th>
+    <th>$lt{'disk'}</th></tr>
 <tr><td>$lt{'prvs'}</td>
     <td>$userenv{'firstname'}  </td>
     <td>$userenv{'middlename'} </td>
@@ -1618,16 +1533,11 @@ END
             # They did not want to change the users name but we can
             # still tell them what the name is
 	    my %lt=&Apache::lonlocal::texthash(
-                           'usr'  => "User",                    
-                           'id'   => "in domain",
-                           'gen'  => "Generation",
                            'mail' => "Permanent e-mail",
                            'disk' => "Disk space allocated to user's portfolio files",
 					       );
             $r->print(<<"END");
-<h2>$lt{'usr'} "$env{'form.ccuname'}" $lt{'id'} "$env{'form.ccdomain'}"</h2>
-<h4>$userenv{'firstname'} $userenv{'middlename'} $userenv{'lastname'} </h4>
-<h4>$lt{'gen'}: $userenv{'generation'}</h4>
+<h4>$userenv{'firstname'} $userenv{'middlename'} $userenv{'lastname'} $userenv{'generation'}</h4>
 <h4>$lt{'mail'}: $userenv{'permanentemail'}</h4>
 END
             if ($putresult eq 'ok') {
@@ -1648,23 +1558,20 @@ END
 	if ($key=~/^form\.rev/) {
 	    if ($key=~/^form\.rev\:([^\_]+)\_([^\_\.]+)$/) {
 # Revoke standard role
-	        $r->print(&mt('Revoking').' '.$2.' in '.$1.': <b>'.
-                     &Apache::lonnet::revokerole($env{'form.ccdomain'},
-                     $env{'form.ccuname'},$1,$2).'</b><br />');
-		if ($2 eq 'st') {
-		    $1=~m{^/($match_domain)/($match_courseid)};
-		    my $cid=$1.'_'.$2;
-		    my $user = $env{'form.ccuname'}.':'.$env{'form.ccdomain'};
-		    my $result = 
-			&Apache::lonnet::cput('classlist',
-					      { $user => $now },
-					      $env{'course.'.$cid.'.domain'},
-					      $env{'course.'.$cid.'.num'});
-		    $r->print(&mt('Drop from classlist: [_1]',
-				  '<b>'.$result.'</b>').'<br />');
+		my ($scope,$role) = ($1,$2);
+		my $result =
+		    &Apache::lonnet::revokerole($env{'form.ccdomain'},
+						$env{'form.ccuname'},
+						$scope,$role);
+	        $r->print(&mt('Revoking [_1] in [_2]: [_3]',
+			      $role,$scope,'<b>'.$result.'</b>').'<br />');
+		if ($role eq 'st') {
+		    my $result = &classlist_drop($scope,$env{'form.ccuname'},
+						 $env{'form.ccdomain'},$now);
+		    $r->print($result);
 		}
 	    } 
-	    if ($key=~m{^form\.rev\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
+	    if ($key=~m{^form\.rev\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$ }s) {
 # Revoke custom role
 		$r->print(&mt('Revoking custom role:').
                       ' '.$4.' by '.$3.':'.$2.' in '.$1.': <b>'.
@@ -1675,26 +1582,23 @@ END
 	} elsif ($key=~/^form\.del/) {
 	    if ($key=~/^form\.del\:([^\_]+)\_([^\_\.]+)$/) {
 # Delete standard role
-	        $r->print(&mt('Deleting').' '.$2.' in '.$1.': '.
-                     &Apache::lonnet::assignrole($env{'form.ccdomain'},
-                     $env{'form.ccuname'},$1,$2,$now,0,1).'<br />');
-		if ($2 eq 'st') {
-		    $1=~m{^/($match_domain)/($match_courseid)};
-		    my $cid=$1.'_'.$2;
-		    my $user = $env{'form.ccuname'}.':'.$env{'form.ccdomain'};
-		    my $result = 
-			&Apache::lonnet::cput('classlist',
-					      { $user => $now },
-					      $env{'course.'.$cid.'.domain'},
-					      $env{'course.'.$cid.'.num'});
-		    $r->print(&mt('Drop from classlist: [_1]',
-				  '<b>'.$result.'</b>').'<br />');
+		my ($scope,$role) = ($1,$2);
+		my $result =
+		    &Apache::lonnet::assignrole($env{'form.ccdomain'},
+						$env{'form.ccuname'},
+						$scope,$role,$now,0,1);
+	        $r->print(&mt('Deleting [_1] in [_2]: [_3]',$role,$scope,
+			      '<b>'.$result.'</b>').'<br />');
+		if ($role eq 'st') {
+		    my $result = &classlist_drop($scope,$env{'form.ccuname'},
+						 $env{'form.ccdomain'},$now);
+		    $r->print($result);
 		}
             }
 	    if ($key=~m{^form\.del\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 # Delete custom role
-                $r->print(&mt('Deleting custom role [_1] by [_2]@[_3] in [_4]',
+                $r->print(&mt('Deleting custom role [_1] by [_2]:[_3] in [_4]',
                       $rolename,$rnam,$rdom,$url).': <b>'.
                       &Apache::lonnet::assigncustomrole($env{'form.ccdomain'},
                          $env{'form.ccuname'},$url,$rdom,$rnam,$rolename,$now,
@@ -1855,7 +1759,7 @@ END
     } # End of foreach (keys(%env))
 # Flush the course logs so reverse user roles immediately updated
     &Apache::lonnet::flushcourselogs();
-    $r->print('<p><a href="/adm/createuser">Create/Modify Another User</a></p>');
+    $r->print('<p><a href="/adm/createuser">'.&mt('Create/Modify Another User').'</a></p>');
     $r->print('<form name="userupdate" method="post" />'."\n");
     foreach my $item ('srchby','srchin','srchtype','srchterm','srchdomain','ccuname','ccdomain') {
         $r->print('<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n");
@@ -1866,11 +1770,35 @@ END
         }
     }
     $r->print('<input type="hidden" name="phase" value="" />'."\n".
-              '<input type ="hidden" name="state" value="" />'."\n".
+              '<input type ="hidden" name="currstate" value="" />'."\n".
               '</form>');
     $r->print(&Apache::loncommon::end_page());
 }
 
+sub classlist_drop {
+    my ($scope,$uname,$udom,$now) = @_;
+    my ($cdom,$cnum) = ($scope=~m{^/($match_domain)/($match_courseid)});
+    my $cid=$cdom.'_'.$cnum;
+    my $user = $uname.':'.$udom;
+    if (!&active_student_roles($cnum,$cdom,$uname,$udom)) {
+	my $result = 
+	    &Apache::lonnet::cput('classlist',
+				  { $user => $now },
+				  $env{'course.'.$cid.'.domain'},
+				  $env{'course.'.$cid.'.num'});
+	return &mt('Drop from classlist: [_1]',
+		   '<b>'.$result.'</b>').'<br />';
+    }
+}
+
+sub active_student_roles {
+    my ($cnum,$cdom,$uname,$udom) = @_;
+    my %roles = 
+	&Apache::lonnet::get_my_roles($uname,$udom,'userroles',
+				      ['future','active'],['st']);
+    return exists($roles{"$cnum:$cdom:st"});
+}
+
 sub quota_admin {
     my ($setquota,$changeHash) = @_;
     my $quotachanged;
@@ -1997,7 +1925,7 @@ sub custom_role_editor {
     $r->print(&Apache::loncommon::start_page('Custom Role Editor',$head_script));
    &Apache::lonhtmlcommon::add_breadcrumb
      ({href=>"javascript:backPage(document.form1,'','')",
-       text=>"User/custom role search",
+       text=>"User modify/custom role edit",
        faq=>282,bug=>'Instructor Interface',},
       {href=>"javascript:backPage(document.form1,'','')",
          text=>"Edit custom role",
@@ -2041,7 +1969,7 @@ ENDCCF
     }
     $r->print(&Apache::loncommon::end_data_table().
    '<input type="hidden" name="startrolename" value="'.$env{'form.rolename'}.
-   '" />'."\n".'<input type="hidden" name="state" value="" />'."\n".   
+   '" />'."\n".'<input type="hidden" name="currstate" value="" />'."\n".   
    '<input type="reset" value="'.&mt("Reset").'" />'."\n".
    '<input type="submit" value="'.&mt('Define Role').'" /></form>'.
 	      &Apache::loncommon::end_page());
@@ -2137,7 +2065,7 @@ sub set_custom_role {
     $r->print(&Apache::loncommon::start_page('Save Custom Role'),$jscript);
     &Apache::lonhtmlcommon::add_breadcrumb
         ({href=>"javascript:backPage(document.customresult,'','')",
-          text=>"User/custom role search",
+          text=>"User modify/custom role edit",
           faq=>282,bug=>'Instructor Interface',},
          {href=>"javascript:backPage(document.customresult,'selected_custom_edit','')",
           text=>"Edit custom role",
@@ -2234,13 +2162,14 @@ sub handler {
                $srch->{$item} = $env{'form.'.$item};
            }
            if ($env{'form.phase'} eq 'get_user_info') {
-               my ($state,$response,$forcenewuser,$results) = 
+               my ($currstate,$response,$forcenewuser,$results) = 
                    &user_search_result($srch);
-               if ($state eq 'select') {
-                   &print_user_selection_page($r,$response,$srch,$results);
-               } elsif ($state eq 'modify') {
+               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') {
+                   if (($srch->{'srchby'} eq 'uname') && 
+                       ($srch->{'srchtype'} eq 'exact')) {
                        $ccuname = $srch->{'srchterm'};
                        $ccdomain= $srch->{'srchdomain'};
                    } else {
@@ -2251,8 +2180,8 @@ sub handler {
                    $ccdomain=&LONCAPA::clean_domain($ccdomain);
                    &print_user_modification_page($r,$ccuname,$ccdomain,$srch,
                                                  $response);
-               } elsif ($state eq 'query') {
-                   &print_user_query_page($r);
+               } elsif ($currstate eq 'query') {
+                   &print_user_query_page($r,'createuser');
                } else {
                    &print_username_entry_form($r,$response,$srch,$forcenewuser);
                }
@@ -2281,19 +2210,20 @@ sub handler {
 #-------------------------------------------------- functions for &phase_two
 sub user_search_result {
     my ($srch) = @_;
-    my @alldomains = sort(&Apache::lonnet::all_domains());
     my %allhomes;
     my %inst_matches;
     my %srch_results;
-    my ($response,$state,$forcenewuser);
+    my ($response,$currstate,$forcenewuser,$dirsrchres);
+    $srch->{'srchterm'} =~ s/^\s+//;
+    $srch->{'srchterm'} =~ s/\s+$//;
 
-    if ($srch->{'srchby'} !~ /^(uname|lastname|lastfirst)$/) { 
+    if ($srch->{'srchby'} !~ /^(uname|lastname|lastfirst)$/) {
         $response = &mt('Invalid search.');
     }
     if ($srch->{'srchin'} !~ /^(crs|dom|alc|instd)$/) {
         $response = &mt('Invalid search.');
     }
-    if ($srch->{'srchtype'} !~ /^(exact|contains)$/) {
+    if ($srch->{'srchtype'} !~ /^(exact|contains|begins)$/) {
         $response = &mt('Invalid search.');
     }
     if ($srch->{'srchterm'} eq '') {
@@ -2301,24 +2231,30 @@ sub user_search_result {
     }
     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'instd')) {
         if (($srch->{'srchdomain'} eq '') || 
-            (!(grep/^\Q$srch->{'srchdomain'}\E$/,@alldomains))) {
+	    ! (&Apache::lonnet::domain($srch->{'srchdomain'}))) {
             $response = &mt('You must specify a valid domain when searching in a domain or institutional directory.')
         }
     }
     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs') ||
         ($srch->{'srchin'} eq 'alc')) {
-        if ($srch->{'srchterm'} !~ /^$match_username$/) {
-            $response = &mt('You must specify a valid username. Only the following are allowed: letters numbers - . @');
+        if ($srch->{'srchby'} eq 'uname') {
+            if ($srch->{'srchterm'} !~ /^$match_username$/) {
+                $response = &mt('You must specify a valid username. Only the following are allowed: letters numbers - . @');
+            }
         }
     }
+    if ($response ne '') {
+        $response = '<span class="LC_warning">'.$response.'</span>';
+    }
     if ($srch->{'srchin'} eq 'instd') {
         my $instd_chk = &directorysrch_check($srch);
         if ($instd_chk ne 'ok') {
-            $response = $instd_chk;
+            $response = '<span class="LC_warning">'.$instd_chk.'</span>'.
+                        '<br />'.&mt('You may want to search in the LON-CAPA domain instead of the institutional directory.').'<br /><br />';
         }
     }
     if ($response ne '') {
-        return ($state,$response);
+        return ($currstate,$response);
     }
     if ($srch->{'srchby'} eq 'uname') {
         if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs')) {
@@ -2327,53 +2263,98 @@ sub user_search_result {
                     my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
                     if ($uhome eq 'no_host') {
                         my $domdesc = &Apache::lonnet::domain($env{'request.role.domain'},'description');
-                        $response = &mt('New users can only be created in the domain to which you current role belongs - [_1].',$env{'request.role.domain'}.' ('.$domdesc.')');
+                        my $showdom = &display_domain_info($env{'request.role.domain'});
+                        $response = &mt('New users can only be created in the domain to which your current role belongs - [_1].',$showdom);
                     } else {
-                        $state = 'modify';
+                        $currstate = 'modify';
                     }
                 } else {
-                    $state = 'modify';
+                    $currstate = 'modify';
                 }
             } else {
                 if ($srch->{'srchin'} eq 'dom') {
-                    my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
-                    if ($uhome eq 'no_host') {
-                        ($state,$response,$forcenewuser) =
-                            &build_search_response($srch,%srch_results);
+                    if ($srch->{'srchtype'} eq 'exact') {
+                        my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
+                        if ($uhome eq 'no_host') {
+                            ($currstate,$response,$forcenewuser) =
+                                &build_search_response($srch,%srch_results);
+                        } else {
+                            $currstate = 'modify';
+                        }
                     } else {
-                        $state = 'modify';
+                        %srch_results = &Apache::lonnet::usersearch($srch);
+                        ($currstate,$response,$forcenewuser) =
+                            &build_search_response($srch,%srch_results);
                     }
                 } else {
-                    my %courseusers = &get_courseusers();
-                    if (exists($courseusers{$srch->{'srchterm'}.':'.$srch->{'srchdomain'}})) {
-                        $state = 'modify';
+                    my $courseusers = &get_courseusers();
+                    if ($srch->{'srchtype'} eq 'exact') {
+                        if (exists($courseusers->{$srch->{'srchterm'}.':'.$srch->{'srchdomain'}})) {
+                            $currstate = 'modify';
+                        } else {
+                            ($currstate,$response,$forcenewuser) =
+                                &build_search_response($srch,%srch_results);
+                        }
                     } else {
-                        ($state,$response,$forcenewuser) =
+                        foreach my $user (keys(%$courseusers)) {
+                            my ($cuname,$cudomain) = split(/:/,$user);
+                            if ($cudomain eq $srch->{'srchdomain'}) {
+                                my $matched = 0;
+                                if ($srch->{'srchtype'} eq 'begins') {
+                                    if ($cuname =~ /^\Q$srch->{'srchterm'}\E/i) {
+                                        $matched = 1;
+                                    }
+                                } else {
+                                    if ($cuname =~ /\Q$srch->{'srchterm'}\E/i) {
+                                        $matched = 1;
+                                    }
+                                }
+                                if ($matched) {
+                                    $srch_results{$user} = 
+					{&Apache::lonnet::get('environment',
+							     ['firstname',
+							      'lastname',
+							      'permanentemail'])};
+                                }
+                            }
+                        }
+                        ($currstate,$response,$forcenewuser) =
                             &build_search_response($srch,%srch_results);
                     }
                 }
             }
         } elsif ($srch->{'srchin'} eq 'alc') {
-            $state = 'query';
+            $currstate = 'query';
         } elsif ($srch->{'srchin'} eq 'instd') {
-            %srch_results = &Apache::lonnet::inst_directory_query($srch);
-            ($state,$response,$forcenewuser) = 
-                &build_search_response($srch,%srch_results); 
+            ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch);
+            if ($dirsrchres eq 'ok') {
+                ($currstate,$response,$forcenewuser) = 
+                    &build_search_response($srch,%srch_results);
+            } else {
+                my $showdom = &display_domain_info($srch->{'srchdomain'});
+                $response = '<span class="LC_warning">'.
+                    &mt('Institutional directory search is not available in domain: [_1]',$showdom).
+                    '</span><br />'.
+                    &mt('You may want to search in the LON-CAPA domain instead of the institutional directory.').
+                    '<br /><br />'; 
+            }
         }
     } else {
         if ($srch->{'srchin'} eq 'dom') {
             %srch_results = &Apache::lonnet::usersearch($srch);
-            ($state,$response,$forcenewuser) = 
+            ($currstate,$response,$forcenewuser) = 
                 &build_search_response($srch,%srch_results); 
         } elsif ($srch->{'srchin'} eq 'crs') {
-            my %courseusers = &get_courseusers(); 
-            foreach my $user (keys(%courseusers)) {
+            my $courseusers = &get_courseusers(); 
+            foreach my $user (keys(%$courseusers)) {
                 my ($uname,$udom) = split(/:/,$user);
                 my %names = &Apache::loncommon::getnames($uname,$udom);
                 my %emails = &Apache::loncommon::getemails($uname,$udom);
                 if ($srch->{'srchby'} eq 'lastname') {
                     if ((($srch->{'srchtype'} eq 'exact') && 
                          ($names{'lastname'} eq $srch->{'srchterm'})) || 
+                        (($srch->{'srchtype'} eq 'begins') &&
+                         ($names{'lastname'} =~ /^\Q$srch->{'srchterm'}\E/i)) ||
                         (($srch->{'srchtype'} eq 'contains') &&
                          ($names{'lastname'} =~ /\Q$srch->{'srchterm'}\E/i))) {
                         $srch_results{$user} = {firstname => $names{'firstname'},
@@ -2383,6 +2364,8 @@ sub user_search_result {
                     }
                 } elsif ($srch->{'srchby'} eq 'lastfirst') {
                     my ($srchlast,$srchfirst) = split(/,/,$srch->{'srchterm'});
+                    $srchlast =~ s/\s+$//;
+                    $srchfirst =~ s/^\s+//;
                     if ($srch->{'srchtype'} eq 'exact') {
                         if (($names{'lastname'} eq $srchlast) &&
                             ($names{'firstname'} eq $srchfirst)) {
@@ -2392,7 +2375,15 @@ sub user_search_result {
 
                                            };
                         }
-                    } elsif ($srch->{'srchtype'} eq 'contains') {
+                    } elsif ($srch->{'srchtype'} eq 'begins') {
+                        if (($names{'lastname'} =~ /^\Q$srchlast\E/i) &&
+                            ($names{'firstname'} =~ /^\Q$srchfirst\E/i)) {
+                            $srch_results{$user} = {firstname => $names{'firstname'},
+                                                lastname => $names{'lastname'},
+                                                permanentemail => $emails{'permanentemail'},
+                                               };
+                        }
+                    } else {
                         if (($names{'lastname'} =~ /\Q$srchlast\E/i) && 
                             ($names{'firstname'} =~ /\Q$srchfirst\E/i)) {
                             $srch_results{$user} = {firstname => $names{'firstname'},
@@ -2403,17 +2394,25 @@ sub user_search_result {
                     }
                 }
             }
-            ($state,$response,$forcenewuser) = 
+            ($currstate,$response,$forcenewuser) = 
                 &build_search_response($srch,%srch_results); 
         } elsif ($srch->{'srchin'} eq 'alc') {
-            $state = 'query';
+            $currstate = 'query';
         } elsif ($srch->{'srchin'} eq 'instd') {
-            %srch_results = &Apache::lonnet::inst_directory_query($srch); 
-            ($state,$response,$forcenewuser) = 
-                &build_search_response($srch,%srch_results);
+            ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch); 
+            if ($dirsrchres eq 'ok') {
+                ($currstate,$response,$forcenewuser) = 
+                    &build_search_response($srch,%srch_results);
+            } else {
+                my $showdom = &display_domain_info($srch->{'srchdomain'});                $response = '<span class="LC_warning">'.
+                    &mt('Institutional directory search is not available in domain: [_1]',$showdom).
+                    '</span><br />'.
+                    &mt('You may want to search in the LON-CAPA domain instead of the institutional directory.').
+                    '<br /><br />';
+            }
         }
     }
-    return ($state,$response,$forcenewuser,\%srch_results);
+    return ($currstate,$response,$forcenewuser,\%srch_results);
 }
 
 sub directorysrch_check {
@@ -2422,13 +2421,14 @@ sub directorysrch_check {
     my $response;
     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
                                              ['directorysrch'],$srch->{'srchdomain'});
+    my $showdom = &display_domain_info($srch->{'srchdomain'});
     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
         if (!$dom_inst_srch{'directorysrch'}{'available'}) {
-            return &mt('Directory search unavailable in domain: [_1]',$srch->{'srchdomain'}); 
+            return &mt('Institutional directory search is not available in domain: [_1]',$showdom); 
         }
         if ($dom_inst_srch{'directorysrch'}{'localonly'}) {
             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
-                return &mt('Directory search in domain: [_1] is only allowed for users with a current role in the domain.',$srch->{'srchdomain'}); 
+                return &mt('Institutional directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom); 
             }
             my @usertypes = split(/:/,$env{'environment.inststatus'});
             if (!@usertypes) {
@@ -2449,36 +2449,46 @@ sub directorysrch_check {
                     push (@longtypes,$insttypes->{$item});
                 }
                 my $insttype_str = join(', ',@longtypes); 
-                return &mt('Directory search in domain: [_1] is unavailable to your user type: ',$srch->{'srchdomain'}).$insttype_str;
+                return &mt('Institutional directory search in domain: [_1] is not available to your user type: ',$showdom).$insttype_str;
             } 
         } else {
             $can_search = 1;
         }
     } else {
-        return &mt('Directory search has not been configured for domain: [_1]',$srch->{'srchdomain'});
+        return &mt('Institutional directory search has not been configured for domain: [_1]',$showdom);
     }
     my %longtext = &Apache::lonlocal::texthash (
-                       uname => 'username',
+                       uname     => 'username',
                        lastfirst => 'last name, first name',
-                       lastname => 'last name',
-                       contains => 'is contained in',
-                       exact => 'as exact match to'
+                       lastname  => 'last name',
+                       contains  => 'contains',
+                       exact     => 'as exact match to',
+                       begins    => 'begins with',
                    );
     if ($can_search) {
         if (ref($dom_inst_srch{'directorysrch'}{'searchby'}) eq 'ARRAY') {
             if (!grep(/^\Q$srch->{'srchby'}\E$/,@{$dom_inst_srch{'directorysrch'}{'searchby'}})) {
-                return &mt('Directory search in domain: [_1] is not available for searching by [_2]',$srch->{'srchdomain'},$longtext{$srch->{'srchby'}});
+                return &mt('Institutional directory search in domain: [_1] is not available for searching by "[_2]"',$showdom,$longtext{$srch->{'srchby'}});
             }
         } else {
-            return &mt('Directory search in domain: [_1] is not available.', $srch->{'srchdomain'});
+            return &mt('Institutional directory search in domain: [_1] is not available.', $showdom);
         }
     }
     if ($can_search) {
-        if (($dom_inst_srch{'directorysrch'}{'searchtypes'} eq 'specify') ||
-            ($dom_inst_srch{'directorysrch'}{'searchtypes'} eq $srch->{'srchtype'})) {
-            return 'ok';
-        } else {    
-            return &mt('Directory search in domain [_1] is not available for the requested search type: [_2]',$srch->{'srchdomain'},$longtext{$srch->{'srchtype'}});
+        if (ref($dom_inst_srch{'directorysrch'}{'searchtypes'}) eq 'ARRAY') {
+            if (grep(/^\Q$srch->{'srchtype'}\E/,@{$dom_inst_srch{'directorysrch'}{'searchtypes'}})) {
+                return 'ok';
+            } else {
+                return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
+            }
+        } else {
+            if ((($dom_inst_srch{'directorysrch'}{'searchtypes'} eq 'specify') &&
+                 ($srch->{'srchtype'} eq 'exact' || $srch->{'srchtype'} eq 'contains')) ||
+                ($dom_inst_srch{'directorysrch'}{'searchtypes'} eq $srch->{'srchtype'})) {
+                return 'ok';
+            } else {
+                return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
+            }
         }
     }
 }
@@ -2486,45 +2496,55 @@ sub directorysrch_check {
 
 sub get_courseusers {
     my %advhash;
+    my $classlist = &Apache::loncoursedata::get_classlist();
     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles();
     foreach my $role (sort(keys(%coursepersonnel))) {
         foreach my $user (split(/\,/,$coursepersonnel{$role})) {
-            $advhash{$user} = '';
+	    if (!exists($classlist->{$user})) {
+		$classlist->{$user} = [];
+	    }
         }
     }
-    my $classlist = &Apache::loncoursedata::get_classlist();
-    my %combined = (%advhash, %{$classlist});
-    return %combined;
+    return $classlist;
 }
 
 sub build_search_response {
     my ($srch,%srch_results) = @_;
-    my ($state,$response,$forcenewuser);
+    my ($currstate,$response,$forcenewuser);
     my %names = (
           'uname' => 'username',
           'lastname' => 'last name',
           'lastfirst' => 'last name, first name',
           'crs' => 'this course',
-          'dom' => 'this domain',
-          'instd' => "your institution's directory",
+          'dom' => 'LON-CAPA domain: ',
+          'instd' => 'the institutional directory for domain: ',
     );
 
     my %single = (
+                   begins   => 'A match',
                    contains => 'A match',
-                   exact => 'An exact match',
+                   exact    => 'An exact match',
                  );
     my %nomatch = (
+                   begins   => 'No match',
                    contains => 'No match',
-                   exact => 'No exact match',
+                   exact    => 'No exact match',
                   );
     if (keys(%srch_results) > 1) {
-        $state = 'select';
+        $currstate = 'select';
     } else {
         if (keys(%srch_results) == 1) {
-            $state = 'modify';
-            $response = &mt("$single{$srch->{'srchtype'}} was found for this $names{$srch->{'srchby'}} ([_1]) in $names{$srch->{'srchin'}}.",$srch->{'srchterm'});
+            $currstate = 'modify';
+            $response = &mt("$single{$srch->{'srchtype'}} was found for the $names{$srch->{'srchby'}} ([_1]) in $names{$srch->{'srchin'}}.",$srch->{'srchterm'});
+            if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
+                $response .= &display_domain_info($srch->{'srchdomain'});
+            }
         } else {
-            $response = &mt("$nomatch{$srch->{'srchtype'}} found for this $names{$srch->{'srchby'}} ([_1]) in $names{$srch->{'srchin'}}.",$srch->{'srchterm'});
+            $response = '<span class="LC_warning">'.&mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} ([_1]) in $names{$srch->{'srchin'}}",$srch->{'srchterm'});
+            if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
+                $response .= &display_domain_info($srch->{'srchdomain'});
+            }
+            $response .= '</span>';
             if ($srch->{'srchin'} ne 'alc') {
                 $forcenewuser = 1;
                 my $cansrchinst = 0; 
@@ -2536,21 +2556,35 @@ sub build_search_response {
                         } 
                     }
                 }
-                if (($srch->{'srchby'} eq 'lastfirst') || 
-                    ($srch->{'srchby'} eq 'lastname')) {
-                    if ($srch->{'srchin'} eq 'crs') {
-                        $response .= '<br />'.&mt('You may want to broaden your search to the whole domain.'); 
-                    } elsif ($srch->{'srchin'} eq 'dom') {
-                        if ($cansrchinst) {
-                            $response .= '<br />'.&mt('You may want to broaden your search to a search of the institutional directory for this domain.');
-                        }
+                if ((($srch->{'srchby'} eq 'lastfirst') || 
+                     ($srch->{'srchby'} eq 'lastname')) &&
+                    ($srch->{'srchin'} eq 'dom')) {
+                    if ($cansrchinst) {
+                        $response .= '<br />'.&mt('You may want to broaden your search to a search of the institutional directory for the domain.');
                     }
                 }
-                $response .= '<br />'.&mt("To add as a new user:").'<ul><li>'.&mt("Enter the proposed username in the <i>'Search for'</i> box").'</li><li>'.&mt("Set <i>'Make new user if no match found</i>' to <b>Yes</b>").'</li><li>'.&mt("Click <i>'Search'</i>").'</li></ul>'.&mt("Note: you can only create new users in the domain of your current role -".$env{'request.role.domain'}).'<br /><br />';
+                if ($srch->{'srchin'} eq 'crs') {
+                    $response .= '<br />'.&mt('You may want to broaden your search to the selected LON-CAPA domain.');
+                }
+            }
+            if (!($srch->{'srchby'} eq 'uname' && $srch->{'srchin'} eq 'dom' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchdomain'} eq $env{'request.role.domain'})) {
+                $response .= '<br />'.&mt("<b>To add a new user</b> (you can only create new users in your current role's domain - <span class=\"LC_cusr_emph\">[_1]</span>) ...",$env{'request.role.domain'}).'<ul><li>'.&mt("Set '<span class=\"LC_cusr_emph\">Make new user if no match found</span>' to '<b>Yes</b>'").'</li><li>'.&mt('Provide the proposed username').'</li><li>'.&mt('Search').'</li></ul><br />';
             }
         }
     }
-    return ($state,$response,$forcenewuser);
+    return ($currstate,$response,$forcenewuser);
+}
+
+sub display_domain_info {
+    my ($dom) = @_;
+    my $output = $dom;
+    if ($dom ne '') { 
+        my $domdesc = &Apache::lonnet::domain($dom,'description');
+        if ($domdesc ne '') {
+            $output .= ' <span class="LC_cusr_emph">('.$domdesc.')</span>';
+        }
+    }
+    return $output;
 }
 
 sub crumb_utilities {
@@ -2566,12 +2600,19 @@ sub crumb_utilities {
            rolename => 'selectbox',
            newrolename => 'textbox',
        },
+       studentform => {
+           srchterm => 'text',
+           srchin => 'selectbox',
+           srchby => 'selectbox',
+           srchtype => 'selectbox',
+           srchdomain => 'selectbox',
+       },
     );
 
     my $jsback .= qq|
 function backPage(formname,prevphase,prevstate) {
     formname.phase.value = prevphase;
-    formname.state.value = prevstate;
+    formname.currstate.value = prevstate;
     formname.submit();
 }
 |;
@@ -2642,10 +2683,10 @@ sub course_level_table {
 		    $table .= '<td>&nbsp</td>';
                 }
 		$table .= <<ENDTIMEENTRY;
-<td><input type=hidden name="start_$protectedcourse\_$role" value='' />
+<td><input type="hidden" name="start_$protectedcourse\_$role" value='' />
 <a href=
 "javascript:pjump('date_start','Start Date $plrole',document.cu.start_$protectedcourse\_$role.value,'start_$protectedcourse\_$role','cu.pres','dateset')">$lt{'ssd'}</a></td>
-<td><input type=hidden name="end_$protectedcourse\_$role" value='' />
+<td><input type="hidden" name="end_$protectedcourse\_$role" value='' />
 <a href=
 "javascript:pjump('date_end','End Date $plrole',document.cu.end_$protectedcourse\_$role.value,'end_$protectedcourse\_$role','cu.pres','dateset')">$lt{'sed'}</a></td>
 ENDTIMEENTRY
@@ -2678,10 +2719,10 @@ ENDTIMEENTRY
                      'name="sec_'.$customrole.'" /></td>';
                 }
                 $table .= <<ENDENTRY;
-<td><input type=hidden name="start_$customrole" value='' />
+<td><input type="hidden" name="start_$customrole" value='' />
 <a href=
 "javascript:pjump('date_start','Start Date $plrole',document.cu.start_$customrole.value,'start_$customrole','cu.pres','dateset')">$lt{'ssd'}</a></td>
-<td><input type=hidden name="end_$customrole" value='' />
+<td><input type="hidden" name="end_$customrole" value='' />
 <a href=
 "javascript:pjump('date_end','End Date $plrole',document.cu.end_$customrole.value,'end_$customrole','cu.pres','dateset')">$lt{'sed'}</a></td>
 ENDENTRY
@@ -2773,10 +2814,10 @@ sub course_level_dc {
                      '<input type="hidden" name="groups" value="" /></td>'.
                      '</tr></table></td>';
     $otheritems .= <<ENDTIMEENTRY;
-<td><input type=hidden name="start" value='' />
+<td><input type="hidden" name="start" value='' />
 <a href=
 "javascript:pjump('date_start','Start Date',document.cu.start.value,'start','cu.pres','dateset')">$lt{'ssd'}</a></td>
-<td><input type=hidden name="end" value='' />
+<td><input type="hidden" name="end" value='' />
 <a href=
 "javascript:pjump('date_end','End Date',document.cu.end.value,'end','cu.pres','dateset')">$lt{'sed'}</a></td>
 ENDTIMEENTRY