--- loncom/interface/lonuserutils.pm	2010/03/24 03:09:41	1.97.2.16
+++ loncom/interface/lonuserutils.pm	2012/04/25 21:05:30	1.137
@@ -1,7 +1,7 @@
 # The LearningOnline Network with CAPA
 # Utility functions for managing LON-CAPA user accounts
 #
-# $Id: lonuserutils.pm,v 1.97.2.16 2010/03/24 03:09:41 raeburn Exp $
+# $Id: lonuserutils.pm,v 1.137 2012/04/25 21:05:30 raeburn Exp $
 #
 # Copyright Michigan State University Board of Trustees
 #
@@ -47,7 +47,8 @@ sub modifystudent {
     # this one.  If $csec is defined, drop them from all other sections of
     # this course and add them to section $csec
     my ($cnum,$cdom) = &get_course_identity($courseid);
-    my %roles = &Apache::lonnet::dump('roles',$udom,$unam);
+    my $extra = &Apache::lonnet::freeze_escape({'skipcheck' => 1});
+    my %roles = &Apache::lonnet::dump('roles',$udom,$unam,'.',undef,$extra);
     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);
@@ -295,7 +296,8 @@ sub hidden_input {
 }
 
 sub print_upload_manager_header {
-    my ($r,$datatoken,$distotal,$krbdefdom,$context,$permission,$crstype)=@_;
+    my ($r,$datatoken,$distotal,$krbdefdom,$context,$permission,$crstype,
+        $can_assign)=@_;
     my $javascript;
     #
     if (! exists($env{'form.upfile_associate'})) {
@@ -309,9 +311,9 @@ sub print_upload_manager_header {
         }
     }
     if ($env{'form.upfile_associate'} eq 'reverse') {
-        $javascript=&upload_manager_javascript_reverse_associate();
+        $javascript=&upload_manager_javascript_reverse_associate($can_assign);
     } else {
-        $javascript=&upload_manager_javascript_forward_associate();
+        $javascript=&upload_manager_javascript_forward_associate($can_assign);
     }
     #
     # Deal with restored settings
@@ -532,6 +534,7 @@ END
         if (message!='') {
             message+='\\n';
         }
+        message+='$alert{'section'}';
     }
     if (foundemail==0) {
         if (message!='') {
@@ -585,6 +588,46 @@ END
 ###############################################################
 ###############################################################
 sub upload_manager_javascript_forward_associate {
+    my ($can_assign) = @_;
+    my ($auth_update,$numbuttons,$argreset);
+    if (ref($can_assign) eq 'HASH') {
+        if ($can_assign->{'krb4'} || $can_assign->{'krb5'}) {
+            $argreset .= "      vf.krbarg.value='';\n";
+            $numbuttons ++ ;
+        }
+        if ($can_assign->{'int'}) {
+            $argreset .= "      vf.intarg.value='';\n";
+            $numbuttons ++;
+        }
+        if ($can_assign->{'loc'}) {
+            $argreset .= "      vf.locarg.value='';\n";
+            $numbuttons ++;
+        }
+        if (!$can_assign->{'int'}) {
+            my $warning = &mt('You may not specify an initial password for each user, as this is only available when new users use LON-CAPA internal authentication.\n').
+                          &mt('Your current role does not have rights to create users with that authentication type.');
+            $auth_update = <<"END";
+   // Currently the initial password field is only supported for internal auth
+   // (see bug 6368).
+   if (nw==9) {
+       eval('vf.f'+tf+'.selectedIndex=0;')
+       alert('$warning');
+   }
+END
+        } elsif ($numbuttons > 1) {
+            $auth_update = <<"END";
+   // 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);
+$argreset
+   }
+
+END
+        }
+    }
+
     return(<<ENDPICK);
 function verify(vf,sec_caller) {
     var founduname=0;
@@ -661,15 +704,7 @@ function flip(vf,tf) {
          }
       }
    }
-   // 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='';
-   }
+   $auth_update
 }
 
 function clearpwd(vf) {
@@ -687,6 +722,45 @@ ENDPICK
 ###############################################################
 ###############################################################
 sub upload_manager_javascript_reverse_associate {
+    my ($can_assign) = @_;
+    my ($auth_update,$numbuttons,$argreset);
+    if (ref($can_assign) eq 'HASH') {
+        if ($can_assign->{'krb4'} || $can_assign->{'krb5'}) {
+            $argreset .= "      vf.krbarg.value='';\n";
+            $numbuttons ++ ;
+        }
+        if ($can_assign->{'int'}) {
+            $argreset .= "      vf.intarg.value='';\n";
+            $numbuttons ++;
+        }
+        if ($can_assign->{'loc'}) {
+            $argreset .= "      vf.locarg.value='';\n";
+            $numbuttons ++;
+        }
+        if (!$can_assign->{'int'}) {
+            my $warning = &mt('You may not specify an initial password, as this is only available when new users use LON-CAPA internal authentication.\n').
+                          &mt('Your current role does not have rights to create users with that authentication type.');
+            $auth_update = <<"END";
+   // Currently the initial password field is only supported for internal auth
+   // (see bug 6368).
+   if (tf==8 && nw!=0) {
+       eval('vf.f'+tf+'.selectedIndex=0;')
+       alert('$warning');
+   }
+END
+        } elsif ($numbuttons > 1) {
+            $auth_update = <<"END";
+   // initial password specified, pick internal authentication
+   if (tf==8 && nw!=0) {
+      changed_radio('int',document.studentform);
+      set_auth_radio_buttons('int',document.studentform);
+$argreset
+   }
+
+END
+        }
+    }
+
     return(<<ENDPICK);
 function verify(vf,sec_caller) {
     var founduname=0;
@@ -694,6 +768,7 @@ function verify(vf,sec_caller) {
     var foundname=0;
     var foundid=0;
     var foundsec=0;
+    var foundemail=0;
     var foundrole=0;
     var founddomain=0;
     var foundinststatus=0;
@@ -705,11 +780,12 @@ function verify(vf,sec_caller) {
         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; }
-        if (i==10 && tw!=0) { founddomain=1; }
-        if (i==13 && tw!=0) { foundinstatus=1; }
+        if (i==9 && tw!=0) { foundemail=1; }
+        if (i==10 && tw!=0) { foundrole=1; }
+        if (i==11 && tw!=0) { founddomain=1; }
+        if (i==12 && tw!=0) { foundinstatus=1; }
     }
-    verify_message(vf,founduname,foundpwd,foundname,foundid,foundsec,foundrole,founddomain,foundinststatus);
+    verify_message(vf,founduname,foundpwd,foundname,foundid,foundsec,foundemail,foundrole,founddomain,foundinststatus);
 }
 
 function flip(vf,tf) {
@@ -726,14 +802,7 @@ function flip(vf,tf) {
    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='';
-   }
+   $auth_update
 }
 
 function clearpwd(vf) {
@@ -978,8 +1047,9 @@ sub print_upload_manager_form {
     my ($krbdef,$krbdefdom) =
         &Apache::loncommon::get_kerberos_defaults($defdom);
     #
+    my ($authnum,%can_assign) =  &Apache::loncommon::get_assignable_auth($defdom);
     &print_upload_manager_header($r,$datatoken,$distotal,$krbdefdom,$context,
-                                 $permission,$crstype);
+                                 $permission,$crstype,\%can_assign);
     my $i;
     my $keyfields;
     if ($total>=0) {
@@ -1352,7 +1422,8 @@ sub curr_role_permissions {
 sub my_custom_roles {
     my ($crstype) = @_;
     my %returnhash=();
-    my %rolehash=&Apache::lonnet::dump('roles');
+    my $extra = &Apache::lonnet::freeze_escape({'skipcheck' => 1});
+    my %rolehash=&Apache::lonnet::dump('roles',undef,undef,'.',undef,$extra);
     foreach my $key (keys(%rolehash)) {
         if ($key=~/^rolesdef\_(\w+)$/) {
             if ($crstype eq 'Community') {
@@ -1447,7 +1518,7 @@ sub print_userlist {
         return;
     }
     if (!(($context eq 'domain') && 
-        (($env{'form.roletype'} eq 'course') || ($env{'form.roletype'} eq 'community')))) {
+          (($env{'form.roletype'} eq 'course') || ($env{'form.roletype'} eq 'community')))) {
         $r->print(
             "\n</p>\n"
            .'<p>'
@@ -1458,7 +1529,7 @@ sub print_userlist {
     my ($indexhash,$keylist) = &make_keylist_array();
     my (%userlist,%userinfo,$clearcoursepick);
     if (($context eq 'domain') && 
-        ($env{'form.roletype'} eq 'course') ||
+        ($env{'form.roletype'} eq 'course') || 
         ($env{'form.roletype'} eq 'community')) {
         my ($crstype,$numcodes,$title,$warning);
         if ($env{'form.roletype'} eq 'course') {
@@ -1472,9 +1543,11 @@ sub print_userlist {
             $title = &mt('Select Communities');
             $warning = &mt('Warning: data retrieval for multiple communities can take considerable time, as this operation is not currently optimized.');
         }
+        my @standardnames = &Apache::loncommon::get_standard_codeitems();
         my $courseform =
             &Apache::lonhtmlcommon::course_selection($formname,$numcodes,
-                            $codetitles,$idlist,$idlist_titles,$crstype);
+                            $codetitles,$idlist,$idlist_titles,$crstype,
+                            \@standardnames);
         $r->print('<p>'.&Apache::lonhtmlcommon::start_pick_box()."\n".
                   &Apache::lonhtmlcommon::start_pick_box()."\n".
                   &Apache::lonhtmlcommon::row_title($title,'LC_oddrow_value')."\n".
@@ -1692,7 +1765,7 @@ sub role_filter {
         $role_select .= '</select>';
         $output = '<label><span class="LC_nobreak">'
                  .&mt('Role: [_1]',$role_select)
-                 .'</span></label>';
+                 .'</span></label> ';
     }
     return $output;
 }
@@ -1923,7 +1996,7 @@ function setCourseCat(formname) {
     if (formname.Year.options[formname.Year.selectedIndex].value == -1) {
         return;
     }
-    courseSet('Year');
+    courseSet('$codetitles[0]');
     for (var j=0; j<formname.Semester.length; j++) {
         if (formname.Semester.options[j].value == "$env{'form.Semester'}") {
             formname.Semester.options[j].selected = true;
@@ -1932,7 +2005,7 @@ function setCourseCat(formname) {
     if (formname.Semester.options[formname.Semester.selectedIndex].value == -1) {
         return;
     }
-    courseSet('Semester');
+    courseSet('$codetitles[1]');
     for (var j=0; j<formname.Department.length; j++) {
         if (formname.Department.options[j].value == "$env{'form.Department'}") {            formname.Department.options[j].selected = true;
         }
@@ -1940,7 +2013,7 @@ function setCourseCat(formname) {
     if (formname.Department.options[formname.Department.selectedIndex].value == -1) {
         return;
     }
-    courseSet('Department');
+    courseSet('$codetitles[2]');
     for (var j=0; j<formname.Number.length; j++) {
         if (formname.Number.options[j].value == "$env{'form.Number'}") {
             formname.Number.options[j].selected = true;
@@ -2277,7 +2350,7 @@ END
             push(@cols,'section');
         }
         if (!($context eq 'domain' && ($env{'form.roletype'} eq 'course')
-                              && ($env{'form.roletype'} eq 'community'))) {
+                              && ($env{'form.roletype'} eq 'community'))) { 
             push(@cols,('start','end'));
         }
         if ($env{'form.showrole'} eq 'Any' || $env{'form.showrole'} eq 'cr') {
@@ -2288,7 +2361,7 @@ END
                                     $env{'form.roletype'} eq 'community')) {
             push (@cols,'extent');
         }
-        if (($statusmode eq 'Any') &&
+        if (($statusmode eq 'Any') && 
             (!($context eq 'domain' && (($env{'form.roletype'} eq 'course')
              || ($env{'form.roletype'} eq 'community'))))) {
             push(@cols,'status');
@@ -2309,7 +2382,6 @@ END
     if ($mode ne 'autoenroll') {
         $results_description = &results_header_row($rolefilter,$statusmode,
                                                    $context,$permission,$mode,$crstype);
-
         $r->print('<b>'.$results_description.'</b><br /><br />');
     }
     my ($output,$actionselect,%canchange,%canchangesec);
@@ -2331,7 +2403,7 @@ END
 END
             if ($actionselect) {
                 $output .= <<"END";
-<div class="LC_left_float"><fieldset><legend><b>$lt{'ac'}</b></legend>
+<div class="LC_left_float"><fieldset><legend>$lt{'ac'}</legend>
 $actionselect
 <br/><br /><input type="button" value="$lt{'ca'}" onclick="javascript:checkAll(document.$formname.actionlist)" /> &nbsp;
 <input type="button" value="$lt{'ua'}" onclick="javascript:uncheckAll(document.$formname.actionlist)" /><br /><input type="button" value="$lt{'pr'}" onclick="javascript:verify_action('actionlist')" /></fieldset></div>
@@ -2376,7 +2448,7 @@ END
                     }
                 }
             }
-            $output .= '<div class="LC_left_float"><fieldset><legend><b>'.$lt{'link'}.'</b></legend>'.
+            $output .= '<div class="LC_left_float"><fieldset><legend>'.$lt{'link'}.'</legend>'.
                        '<table><tr>';
             my @linkdests = ('aboutme');
             if ($permission->{'cusr'}) {
@@ -2387,6 +2459,7 @@ END
                                          $env{'request.course.sec'})) {
                 push(@linkdests,'track');
             }
+
             $output .= '<td>';
             my $usernamelink = $env{'form.usernamelink'};
             if ($usernamelink eq '') {
@@ -2403,7 +2476,7 @@ END
             if ($env{'form.userwin'}) {
                 $checkwin = ' checked="checked"';
             }
-            $output .= '</td><td valign="top" style="border-left: 1px solid;><span class="LC_nobreak"><input type="checkbox" name="userwin" value="1"'.$checkwin.' />'.$lt{'owin'}.'</span></td></tr></table></fieldset></div>';
+            $output .= '</td><td valign="top"  style="border-left: 1px solid;"><span class="LC_nobreak"><input type="checkbox" name="userwin" value="1"'.$checkwin.' />'.$lt{'owin'}.'</span></td></tr></table></fieldset></div>';
         }
         $output .= "\n".'<div class="LC_clear_float_footer">&nbsp;</div>'."\n".
                   &Apache::loncommon::start_data_table().
@@ -2656,16 +2729,18 @@ END
         if ($clickers!~/\w/) { $clickers='-'; }
         $in{'clicker'} = $clickers; 
 	my $role = $in{'role'};
-        $in{'role'}=&Apache::lonnet::plaintext($sdata->[$index{'role'}],$crstype); 
-        if (! defined($in{'start'}) || $in{'start'} == 0) {
-            $in{'start'} = &mt('none');
-        } else {
-            $in{'start'} = &Apache::lonlocal::locallocaltime($in{'start'});
-        }
-        if (! defined($in{'end'}) || $in{'end'} == 0) {
-            $in{'end'} = &mt('none');
-        } else {
-            $in{'end'} = &Apache::lonlocal::locallocaltime($in{'end'});
+        $in{'role'}=&Apache::lonnet::plaintext($sdata->[$index{'role'}],$crstype);
+        unless ($mode eq 'excel') {
+            if (! defined($in{'start'}) || $in{'start'} == 0) {
+                $in{'start'} = &mt('none');
+            } else {
+                $in{'start'} = &Apache::lonlocal::locallocaltime($in{'start'});
+            }
+            if (! defined($in{'end'}) || $in{'end'} == 0) {
+                $in{'end'} = &mt('none');
+            } else {
+                $in{'end'} = &Apache::lonlocal::locallocaltime($in{'end'});
+            }
         }
         if ($mode eq 'view' || $mode eq 'html' || $mode eq 'autoenroll' || $mode eq 'pickauthor') {
             $r->print(&Apache::loncommon::start_data_table_row());
@@ -2767,16 +2842,6 @@ END
         } elsif ($mode eq 'csv') {
             next if (! defined($CSVfile));
             # no need to bother with $linkto
-            if (! defined($in{'start'}) || $in{'start'} == 0) {
-                $in{'start'} = &mt('none');
-            } else {
-                $in{'start'} = &Apache::lonlocal::locallocaltime($in{'start'});
-            }
-            if (! defined($in{'end'}) || $in{'end'} == 0) {
-                $in{'end'} = &mt('none');
-            } else {
-                $in{'end'} = &Apache::lonlocal::locallocaltime($in{'end'});
-            }
             my @line = ();
             foreach my $item (@cols) {
                 push @line,&Apache::loncommon::csv_translate($in{$item});
@@ -2786,9 +2851,9 @@ END
             my $col = 0;
             foreach my $item (@cols) {
                 if ($item eq 'start' || $item eq 'end') {
-                    if (defined($item) && $item != 0) {
+                    if ((defined($in{$item})) && ($in{$item} != 0)) {
                         $excel_sheet->write($row,$col++,
-                            &Apache::lonstathelpers::calc_serial($in{item}),
+                            &Apache::lonstathelpers::calc_serial($in{$item}),
                                     $format->{'date'});
                     } else {
                         $excel_sheet->write($row,$col++,'none');
@@ -3175,7 +3240,7 @@ ENDJS
                  chse => 'Changes in section affiliation to apply to selected users',
                  fors => 'For student roles, changing the section will result in a section switch as students may only be in one section of a course at a time.',
                  forn => 'For a course role that is not "student", users may have roles in more than one section at a time.',
-                 reta => "Retain each user's current section affiliations?", 
+                 reta => "Retain each user's current section affiliations?",
                  dnap => '(Does not apply to student roles).',
             );
     my ($date_items,$headertext);
@@ -3408,7 +3473,6 @@ sub results_header_row {
             }
         } elsif (($env{'form.roletype'} eq 'course') || 
                  ($env{'form.roletype'} eq 'community')) {
-
             my $coursefilter = $env{'form.coursepick'};
             if ($env{'form.roletype'} eq 'course') {
                 if ($coursefilter eq 'category') {
@@ -3672,8 +3736,15 @@ sub print_first_users_upload_form {
                 &mt("How do I create a CSV file from a spreadsheet"))
            .'</div><br clear="all" />'."\n";
     $str .= &Apache::lonhtmlcommon::start_pick_box()
-           .&Apache::lonhtmlcommon::row_title(&mt('File'))
-           .&Apache::loncommon::upfile_select_html()
+           .&Apache::lonhtmlcommon::row_title(&mt('File'));
+    if (&Apache::lonlocal::current_language() ne 'en') {
+        if ($context eq 'course') { 
+            $str .= '<p class="LC_info">'."\n"
+                   .&mt('Please upload an UTF8 encoded file to ensure a correct character encoding in your classlist.')."\n"
+                   .'</p>'."\n";
+        }
+    }
+    $str .= &Apache::loncommon::upfile_select_html()
            .&Apache::lonhtmlcommon::row_closure()
            .&Apache::lonhtmlcommon::row_title(
                 '<label for="noFirstLine">'
@@ -3807,7 +3878,7 @@ sub upfile_drop_add {
         } elsif ($setting eq 'course') {
             $defaultrole = $env{'form.courserole'};
             $defaultsec = $env{'form.sections'};
-        }
+        }  
     } elsif ($context eq 'author') {
         $defaultrole = $env{'form.defaultrole'};
     } elsif ($context eq 'course') {
@@ -3914,15 +3985,22 @@ sub upfile_drop_add {
                 $r->print($groupwarn.'<br />');
             }
         }
-        my (%curr_rules,%got_rules,%alerts);
+        my (%curr_rules,%got_rules,%alerts,%cancreate);
         my %customroles = &my_custom_roles($crstype);
         my @permitted_roles = 
-            &roles_on_upload($context,$setting,$crstype,%customroles); 
+            &roles_on_upload($context,$setting,$crstype,%customroles);
+        my %longtypes = &Apache::lonlocal::texthash(
+                            official   => 'Institutional',
+                            unofficial => 'Non-institutional',
+                        );
+        my $newuserdom = $env{'request.role.domain'};
+        map { $cancreate{$_} = &can_create_user($newuserdom,$context,$_); } keys(%longtypes);
         # Get new users list
         foreach my $line (@userdata) {
             my @secs;
             my %entries=&Apache::loncommon::record_sep($line);
             # Determine user name
+            $entries{$fields{'username'}} =~ s/^\s+|\s+$//g;
             unless (($entries{$fields{'username'}} eq '') ||
                     (!defined($entries{$fields{'username'}}))) {
                 my ($fname, $mname, $lname,$gen) = ('','','','');
@@ -3943,13 +4021,20 @@ sub upfile_drop_add {
                         $gen=$entries{$fields{'gen'}};
                     }
                 }
+
                 if ($entries{$fields{'username'}}
                     ne &LONCAPA::clean_username($entries{$fields{'username'}})) {
+                    my $nowhitespace;
+                    if ($entries{$fields{'username'}} =~ /\s/) {
+                        $nowhitespace = ' - '.&mt('usernames may not contain spaces.');
+                    }
                     $r->print('<br />'.
       &mt('[_1]: Unacceptable username for user [_2] [_3] [_4] [_5]',
-          '<b>'.$entries{$fields{'username'}}.'</b>',$fname,$mname,$lname,$gen));
+          '<b>'.$entries{$fields{'username'}}.'</b>',$fname,$mname,$lname,$gen).
+                              $nowhitespace);
                     next;
                 } else {
+                    $entries{$fields{'domain'}} =~ s/^\s+|\s+$//g;
                     if ($entries{$fields{'domain'}} 
                         ne &LONCAPA::clean_domain($entries{$fields{'domain'}})) {
                         $r->print('<br />'. '<b>'.$entries{$fields{'domain'}}.
@@ -4008,6 +4093,7 @@ sub upfile_drop_add {
                     # determine email address
                     my $email='';
                     if (defined($fields{'email'})) {
+                        $entries{$fields{'email'}} =~ s/^\s+|\s+$//g;
                         if (defined($entries{$fields{'email'}})) {
                             $email=$entries{$fields{'email'}};
                             unless ($email=~/^[^\@]+\@[^\@]+$/) { $email=''; }
@@ -4054,7 +4140,7 @@ sub upfile_drop_add {
                         $role = $defaultrole;
                     }
                     # Clean up whitespace
-                    foreach (\$id,\$fname,\$mname,\$lname,\$gen) {
+                    foreach (\$id,\$fname,\$mname,\$lname,\$gen,\$inststatus) {
                         $$_ =~ s/(\s+$|^\s+)//g;
                     }
                     # check against rules
@@ -4063,20 +4149,52 @@ sub upfile_drop_add {
                     my (%rulematch,%inst_results,%idinst_results);
                     my $uhome=&Apache::lonnet::homeserver($username,$userdomain);
                     if ($uhome eq 'no_host') {
-                        next if ($userdomain ne $domain);
+                        if ($userdomain ne $newuserdom) {
+                            if ($context eq 'course') {
+                                $r->print('<br />'.
+                                          &mt('[_1]: The domain specified ([_2]) is different to that of the course.',
+                                          '<b>'.$username.'</b>',$userdomain).'<br />');
+                            } elsif ($context eq 'author') {
+                                $r->print(&mt('[_1]: The domain specified ([_2]) is different to that of the author.',
+                                        '<b>'.$username.'</b>',$userdomain).'<br />'); 
+                            } else {
+                                $r->print(&mt('[_1]: The domain specified ([_2]) is different to that of your current role.',
+                                        '<b>'.$username.'</b>',$userdomain).'<br />');
+                            }
+                            $r->print(&mt('The user does not already exist, and you may not create a new user in a different domain.'));
+                            next;
+                        }
                         $checkid = 1;
                         $newuser = 1;
+                        my $user = $username.':'.$newuserdom;
                         my $checkhash;
                         my $checks = { 'username' => 1 };
-                        $checkhash->{$username.':'.$domain} = { 'newuser' => 1, };
+                        $checkhash->{$username.':'.$newuserdom} = { 'newuser' => 1, };
                         &Apache::loncommon::user_rule_check($checkhash,$checks,
                             \%alerts,\%rulematch,\%inst_results,\%curr_rules,
                             \%got_rules);
                         if (ref($alerts{'username'}) eq 'HASH') {
-                            if (ref($alerts{'username'}{$domain}) eq 'HASH') {
-                                next if ($alerts{'username'}{$domain}{$username});
+                            if (ref($alerts{'username'}{$newuserdom}) eq 'HASH') {
+                                if ($alerts{'username'}{$newuserdom}{$username}) {
+                                    $r->print('<br />'.
+                                              &mt('[_1]: matches the username format at your institution, but is not known to your directory service.','<b>'.$username.'</b>').'<br />'.
+                                              &mt('Consequently, the user was not created.'));
+                                    next;
+                                }
                             }
                         }
+                        my $usertype = 'unofficial';
+                        if (ref($rulematch{$user}) eq 'HASH') {
+                            if ($rulematch{$user}{'username'}) {
+                                $usertype = 'official';
+                            }
+                        }
+                        unless ($cancreate{$usertype}) {
+                            my $showtype = $longtypes{$usertype};
+                            $r->print('<br />'.
+                                      &mt('[_1]: The user does not exist, and you are not permitted to create users of type: [_2].','<b>'.$username.'</b>',$showtype));
+                            next;
+                        }
                     } else {
                         if ($context eq 'course' || $context eq 'author') {
                             if ($userdomain eq $domain ) {
@@ -4127,7 +4245,12 @@ sub upfile_drop_add {
                                 \%got_rules);
                             if (ref($alerts{'id'}) eq 'HASH') {
                                 if (ref($alerts{'id'}{$userdomain}) eq 'HASH') {
-                                    next if ($alerts{'id'}{$userdomain}{$id});
+                                    if ($alerts{'id'}{$userdomain}{$id}) {
+                                        $r->print(&mt('[_1]: has a student/employee ID matching the format at your institution, but the ID is found by your directory service.',
+                                                  '<b>'.$username.'</b>').'<br />'.
+                                                  &mt('Consequently, the user was not created.'));
+                                        next;
+                                    }
                                 }
                             }
                         }
@@ -4159,7 +4282,7 @@ sub upfile_drop_add {
                                         $role = 'cr_'.$env{'user.domain'}.'_'.
                                                 $env{'user.name'}.'_'.$role;
                                     }
-                                    if (($role ne 'cc') && ($role ne 'co')) {
+                                    if (($role ne 'cc') && ($role ne 'co')) { 
                                         if (@secs > 1) {
                                             $multiple = 1;
                                             foreach my $sec (@secs) {
@@ -4222,7 +4345,7 @@ sub upfile_drop_add {
             }
         } # end of foreach (@userdata)
         # Flush the course logs so reverse user roles immediately updated
-        &Apache::lonnet::flushcourselogs();
+        $r->register_cleanup(\&Apache::lonnet::flushcourselogs);
         $r->print("</p>\n<p>\n".&mt('Processed [quant,_1,user].',$counts{'user'}).
                   "</p>\n");
         if ($counts{'role'} > 0) {
@@ -4389,7 +4512,6 @@ sub update_user_list {
     my ($r,$context,$setting,$choice,$crstype) = @_;
     my $now = time;
     my $count=0;
-    my $crstype;
     if ($context eq 'course') {
         $crstype = &Apache::loncommon::course_type();
     }
@@ -4566,7 +4688,7 @@ sub update_user_list {
                     if ($sec eq '') {
                         $nochg = 1;
                         $keepnosection = 1;
-                    } else { 
+                    } else {
                         push(@retained,$sec);
                     }
                 }
@@ -4595,12 +4717,12 @@ sub update_user_list {
                     $result = 'ok';
                     $nothingtodo = 1;
                 } else {
-                    foreach my $newsec (@newsecs) { 
+                    foreach my $newsec (@newsecs) {
                         if (!grep(/^\Q$newsec\E$/,@retained)) {
                             if ($role eq 'st') {
                                 $result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$newsec,$end,$start,$type,$locktype,$cid,'',$context);
                                 if (@newsecs > 1) {
-                                    my $showsingle;
+                                    my $showsingle; 
                                     if ($newsec eq '') {
                                         $showsingle = &mt('No section');
                                     } else {
@@ -4608,10 +4730,10 @@ sub update_user_list {
                                     }
                                     if ($crstype eq 'Community') {
                                         $warn_singlesec = &mt('Although more than one section was indicated, a role was only added for the first section - [_1], as each community member may only be in one section at a time.','<i>'.$showsingle.'</i>');
-                                    } else {
+                                    } else { 
                                         $warn_singlesec = &mt('Although more than one section was indicated, a role was only added for the first section - [_1], as each student may only be in one section of a course at a time.','<i>'.$showsingle.'</i>');
                                     }
-                                    $showsecs = $showsingle;
+                                    $showsecs = $showsingle; 
                                     last;
                                 } else {
                                     if ($newsec eq '') {
@@ -4624,10 +4746,11 @@ sub update_user_list {
                                 my $newscope = $scopestem;
                                 if ($newsec ne '') {
                                    $newscope .= '/'.$newsec;
-                                   push(@shownew,$newsec);
+                                   push(@shownew,$newsec); 
                                 }
                                 $result = &Apache::lonnet::assignrole($udom,$uname,
                                                         $newscope,$role,$end,$start);
+                                
                             }
                         }
                     }
@@ -4677,13 +4800,13 @@ sub update_user_list {
                    $r->print('<div class="LC_warning">'.$warn_singlesec.'</div>');
                }
             } elsif ($choice eq 'chgdates') {
-                $r->print(&mt("$result_text{'ok'}{$choice} role of '[_1]' in [_2] for '[_3]' - [_4]",$plrole,$extent,
-                      '<i>'.&Apache::loncommon::plainname($uname.':'.$udom).'</i>',
+                $r->print(&mt("$result_text{'ok'}{$choice} role of '[_1]' in [_2] for '[_3]' - [_4]",$plrole,$extent, 
+                      '<i>'.&Apache::loncommon::plainname($uname,$udom).'</i>',
                       $dates).'<br />');
                $count ++;
             } else {
                 $r->print(&mt("$result_text{'ok'}{$choice} role of '[_1]' in [_2] for '[_3]'.",$plrole,$extent,
-                      '<i>'.&Apache::loncommon::plainname($uname.':'.$udom).'</i>').
+                      '<i>'.&Apache::loncommon::plainname($uname,$udom).'</i>').
                           '<br />');
                 $count ++;
             }
@@ -4691,7 +4814,7 @@ sub update_user_list {
             $r->print(
                 &mt("Error $result_text{'error'}{$choice} [_1] in [_2] for '[_3]': [_4].",
                     $plrole,$extent,
-                    '<i>'.&Apache::loncommon::plainname($uname.':'.$udom).'</i>',
+                    '<i>'.&Apache::loncommon::plainname($uname,$udom).'</i>',
                     $result).'<br />');
         }
     }
@@ -4714,7 +4837,7 @@ sub update_user_list {
             $r->print('<p>'.&mt('Re-enabling will re-activate data for the role.').'</p>');
         }
         # Flush the course logs so reverse user roles immediately updated
-        &Apache::lonnet::flushcourselogs();
+        $r->register_cleanup(\&Apache::lonnet::flushcourselogs);
     }
     if ($env{'form.makedatesdefault'}) {
         if ($choice eq 'chgdates' || $choice eq 'reenable' || $choice eq 'activate') {
@@ -4929,7 +5052,7 @@ sub setsections_javascript {
                     accr => 'A course coordinator role will be added with access to all sections.',
                     acor => 'A coordinator role will be added with access to all sections',
                     inea => 'In each course, each user may only have one student role at a time.',
-                    inec => 'In each community, each user may only have one member role at a time.',
+                    inco => 'In each community, each user may only have one member role at a time.',
                     youh => 'You had selected ',
                     secs => 'sections.',
                     plmo => 'Please modify your selections so they include no more than one section.',
@@ -5150,18 +5273,40 @@ sub can_modify_userinfo {
 }
 
 sub check_usertype {
-    my ($dom,$uname,$rules) = @_;
+    my ($dom,$uname,$rules,$curr_rules,$got_rules) = @_;
     my $usertype;
-    if (ref($rules) eq 'HASH') {
-        my @user_rules = keys(%{$rules});
-        if (@user_rules > 0) {
-            my %rule_check = &Apache::lonnet::inst_rulecheck($dom,$uname,undef,'username',\@user_rules);
-            if (keys(%rule_check) > 0) {
-                $usertype = 'unofficial';
-                foreach my $item (keys(%rule_check)) {
-                    if ($rule_check{$item}) {
-                        $usertype = 'official';
-                        last;
+    if ((ref($got_rules) eq 'HASH') && (ref($curr_rules) eq 'HASH')) {
+        if (!$got_rules->{$dom}) {
+            my %domconfig = &Apache::lonnet::get_dom('configuration',
+                                              ['usercreation'],$dom);
+            if (ref($domconfig{'usercreation'}) eq 'HASH') {
+                foreach my $item ('username','id') {
+                    if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
+                        $curr_rules->{$dom}{$item} =
+                                $domconfig{'usercreation'}{$item.'_rule'};
+                    }
+                }
+            }
+            $got_rules->{$dom} = 1;
+        }
+        if (ref($rules) eq 'HASH') {
+            my @user_rules;
+            if (ref($curr_rules->{$dom}{'username'}) eq 'ARRAY') {
+                foreach my $rule (keys(%{$rules})) {
+                    if (grep(/^\Q$rule\E/,@{$curr_rules->{$dom}{'username'}})) {
+                        push(@user_rules,$rule);
+                    }
+                } 
+            }
+            if (@user_rules > 0) {
+                my %rule_check = &Apache::lonnet::inst_rulecheck($dom,$uname,undef,'username',\@user_rules);
+                if (keys(%rule_check) > 0) {
+                    $usertype = 'unofficial';
+                    foreach my $item (keys(%rule_check)) {
+                        if ($rule_check{$item}) {
+                            $usertype = 'official';
+                            last;
+                        }
                     }
                 }
             }
@@ -5509,7 +5654,7 @@ sub sectioncheck_alerts {
     my %alerts = &Apache::lonlocal::texthash(
                     curd => 'You must select a course or community in the current domain',
                     inea => 'In each course, each user may only have one student role at a time',
-                    inco => 'In each community, each user may only have one member role at a time',
+                    inco => 'In each community, each user may only have one member role at a time', 
                     youh => 'You had selected',
                     sect => 'sections',
                     plsm => 'Please modify your selections so they include no more than one section',