--- loncom/interface/lonuserutils.pm	2010/08/20 20:28:21	1.97.2.18
+++ loncom/interface/lonuserutils.pm	2010/09/26 01:57:21	1.127
@@ -1,7 +1,7 @@
 # The LearningOnline Network with CAPA
 # Utility functions for managing LON-CAPA user accounts
 #
-# $Id: lonuserutils.pm,v 1.97.2.18 2010/08/20 20:28:21 raeburn Exp $
+# $Id: lonuserutils.pm,v 1.127 2010/09/26 01:57:21 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
@@ -585,6 +587,31 @@ END
 ###############################################################
 ###############################################################
 sub upload_manager_javascript_forward_associate {
+    my ($can_assign) = @_;
+    my $auth_update;
+    if (ref($can_assign) eq 'HASH') {
+        if (keys(%{$can_assign}) > 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);
+END
+        }
+        if ($can_assign->{'krb4'} || $can_assign->{'krb5'}) {
+           $auth_update .= "      vf.krbarg.value='';\n";
+        }
+        if ($can_assign->{'int'}) {
+           $auth_update .= "      vf.intarg.value='';\n";
+        }
+        if ($can_assign->{'loc'}) {
+           $auth_update .= "      vf.locarg.value='';\n";
+        }
+        $auth_update .= "
+   }\n";
+    }
+
     return(<<ENDPICK);
 function verify(vf,sec_caller) {
     var founduname=0;
@@ -661,15 +688,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 +706,29 @@ ENDPICK
 ###############################################################
 ###############################################################
 sub upload_manager_javascript_reverse_associate {
+    my ($can_assign) = @_;
+    my $auth_update; 
+    if (ref($can_assign) eq 'HASH') {
+        if (keys(%{$can_assign}) > 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);
+END
+        }
+        if ($can_assign->{'krb'}) {      
+           $auth_update .= "      vf.krbarg.value='';\n";
+        }
+        if ($can_assign->{'int'}) {
+           $auth_update .= "      vf.intarg.value='';\n";
+        }
+        if ($can_assign->{'loc'}) {
+           $auth_update .= "      vf.locarg.value='';\n";
+        }
+        $auth_update .= "
+   }\n";
+    }
     return(<<ENDPICK);
 function verify(vf,sec_caller) {
     var founduname=0;
@@ -726,14 +768,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 +1013,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) {
@@ -1447,7 +1483,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 +1494,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 +1508,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 +1730,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 +1961,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 +1970,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 +1978,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 +2315,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 +2326,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 +2347,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 +2368,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 +2413,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 +2424,7 @@ END
                                          $env{'request.course.sec'})) {
                 push(@linkdests,'track');
             }
+
             $output .= '<td>';
             my $usernamelink = $env{'form.usernamelink'};
             if ($usernamelink eq '') {
@@ -2403,7 +2441,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,7 +2694,7 @@ END
         if ($clickers!~/\w/) { $clickers='-'; }
         $in{'clicker'} = $clickers; 
 	my $role = $in{'role'};
-        $in{'role'}=&Apache::lonnet::plaintext($sdata->[$index{'role'}],$crstype); 
+        $in{'role'}=&Apache::lonnet::plaintext($sdata->[$index{'role'}],$crstype);
         if (! defined($in{'start'}) || $in{'start'} == 0) {
             $in{'start'} = &mt('none');
         } else {
@@ -3175,7 +3213,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 +3446,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 +3709,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 +3851,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,10 +3958,15 @@ 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',
+                        );
+        map { $cancreate{$_} = &can_create_user($domain,$context,$_); } keys(%longtypes);
         # Get new users list
         foreach my $line (@userdata) {
             my @secs;
@@ -4063,9 +4112,16 @@ 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 $domain) {
+                            $r->print('<br />'.
+                                &mt('[_1]: The domain specified ([_2]) is different to that of the course.',
+                                    '<b>'.$username.'</b>',$userdomain).'<br />'.
+                                &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.':'.$domain;
                         my $checkhash;
                         my $checks = { 'username' => 1 };
                         $checkhash->{$username.':'.$domain} = { 'newuser' => 1, };
@@ -4074,9 +4130,26 @@ sub upfile_drop_add {
                             \%got_rules);
                         if (ref($alerts{'username'}) eq 'HASH') {
                             if (ref($alerts{'username'}{$domain}) eq 'HASH') {
-                                next if ($alerts{'username'}{$domain}{$username});
+                                if ($alerts{'username'}{$domain}{$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: $showtype.",'<b>'.$username.'</b>'));
+                            next;
+                        }
                     } else {
                         if ($context eq 'course' || $context eq 'author') {
                             if ($userdomain eq $domain ) {
@@ -4127,7 +4200,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 +4237,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 +4300,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) {
@@ -4565,7 +4643,7 @@ sub update_user_list {
                     if ($sec eq '') {
                         $nochg = 1;
                         $keepnosection = 1;
-                    } else { 
+                    } else {
                         push(@retained,$sec);
                     }
                 }
@@ -4594,12 +4672,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 {
@@ -4607,10 +4685,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 '') {
@@ -4623,10 +4701,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);
+                                
                             }
                         }
                     }
@@ -4676,7 +4755,7 @@ 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,
+                $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 ++;
@@ -4713,7 +4792,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') {
@@ -4928,7 +5007,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.',
@@ -5508,7 +5587,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',