--- loncom/interface/lonuserutils.pm	2009/11/18 23:46:28	1.106
+++ loncom/interface/lonuserutils.pm	2012/08/21 15:43:27	1.141
@@ -1,7 +1,7 @@
 # The LearningOnline Network with CAPA
 # Utility functions for managing LON-CAPA user accounts
 #
-# $Id: lonuserutils.pm,v 1.106 2009/11/18 23:46:28 raeburn Exp $
+# $Id: lonuserutils.pm,v 1.141 2012/08/21 15:43:27 raeburn Exp $
 #
 # Copyright Michigan State University Board of Trustees
 #
@@ -295,7 +295,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 +310,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
@@ -386,7 +387,7 @@ sub javascript_validations {
         if (($context eq 'course') || ($context eq 'domain')) {
             if ($context eq 'course') {
                 if ($env{'request.course.sec'} eq '') {
-                    $setsection_call = 'setSections(document.'.$param{'formname'}."'$crstype'".');';
+                    $setsection_call = 'setSections(document.'.$param{'formname'}.",'$crstype'".');';
                     $setsections_js =
                         &setsections_javascript($param{'formname'},$groupslist,
                                                 $mode,'',$crstype);
@@ -532,6 +533,7 @@ END
         if (message!='') {
             message+='\\n';
         }
+        message+='$alert{'section'}';
     }
     if (foundemail==0) {
         if (message!='') {
@@ -585,6 +587,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 +703,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 +721,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 +767,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 +779,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 +801,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 +1046,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,6 +1421,7 @@ sub curr_role_permissions {
 sub my_custom_roles {
     my ($crstype) = @_;
     my %returnhash=();
+    my $extra = &Apache::lonnet::freeze_escape({'skipcheck' => 1});
     my %rolehash=&Apache::lonnet::dump('roles');
     foreach my $key (keys(%rolehash)) {
         if ($key=~/^rolesdef\_(\w+)$/) {
@@ -1374,8 +1444,9 @@ sub print_userlist {
     if ($env{'form.Status'} !~ /^(Any|Expired|Active|Future)$/) {
         $env{'form.Status'} = 'Active';
     }
+    my $onchange = "javascript:updateCols('Status');";
     my $status_select = &Apache::lonhtmlcommon::StatusOptions
-        ($env{'form.Status'});
+        ($env{'form.Status'},undef,undef,$onchange);
 
     if ($env{'form.showrole'} eq '') {
         if ($context eq 'course') {
@@ -1408,12 +1479,12 @@ sub print_userlist {
     $r->print('<form name="studentform" method="post" action="/adm/createuser">'."\n".
               '<input type="hidden" name="action" value="'.
               $env{'form.action'}.'" />');
-    $r->print("<p>\n");
+    $r->print('<div>'."\n");
     if ($env{'form.action'} ne 'modifystudent') {
         my %lt=&Apache::lonlocal::texthash('csv' => "CSV",
                                            'excel' => "Excel",
                                            'html'  => 'HTML');
-        my $output_selector = '<select size="1" name="output" >';
+        my $output_selector = '<select size="1" name="output" onchange="javascript:updateCols('."'output'".');" >';
         foreach my $outputformat ('html','csv','excel') {
             my $option = '<option value="'.$outputformat.'"';
             if ($outputformat eq $env{'form.output'}) {
@@ -1423,13 +1494,13 @@ sub print_userlist {
             $output_selector .= "\n".$option;
         }
         $output_selector .= '</select>';
-        $r->print('<label><span class="LC_nobreak">'
+        $r->print('<span class="LC_nobreak">'
                  .&mt('Output Format: [_1]',$output_selector)
-                 .'</span></label>'.('&nbsp;'x3));
+                 .'</span>'.('&nbsp;'x3));
     }
-    $r->print('<label><span class="LC_nobreak">'
+    $r->print('<span class="LC_nobreak">'
              .&mt('User Status: [_1]',$status_select)
-             .'</span></label>'.('&nbsp;'x3)."\n");
+             .'</span>'.('&nbsp;'x3)."\n");
     my $roleselected = '';
     if ($env{'form.showrole'} eq 'Any') {
        $roleselected = ' selected="selected"'; 
@@ -1440,16 +1511,25 @@ sub print_userlist {
         ($cnum,$cdom) = &get_course_identity();
         $r->print(&section_group_filter($cnum,$cdom));
     }
+    $r->print('</div><div class="LC_left_float">'.
+              &column_checkboxes($context,$mode,$formname).
+              '</div><br clear="all" />');
     if ($env{'form.phase'} eq '') {
-        $r->print('<br /><br />'.&list_submit_button(&mt('Display List of Users')).
-                  "\n</p>\n".
+        $r->print(&list_submit_button(&mt('Display List of Users'))."\n".
                   '<input type="hidden" name="phase" value="" /></form>');
         return;
     }
     if (!(($context eq 'domain') && 
           (($env{'form.roletype'} eq 'course') || ($env{'form.roletype'} eq 'community')))) {
-        $r->print('&nbsp;'.&list_submit_button(&mt('Update Display')).
-                  "\n</p>\n");
+        $r->print(&list_submit_button(&mt('Update Display'))."\n");
+    }
+
+    my @cols = &infocolumns($context,$mode);  
+    if (!@cols) {
+         $r->print('<hr /><span class="LC_warning">'.
+                   &mt('No user information selected for display.').'</span>'.
+                   '<input type="hidden" name="phase" value="display" /></form>'."\n");
+         return;
     }
     my ($indexhash,$keylist) = &make_keylist_array();
     my (%userlist,%userinfo,$clearcoursepick);
@@ -1468,9 +1548,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".
@@ -1489,7 +1571,7 @@ sub print_userlist {
             $r->print('<hr />'.&mt('Searching').' ...<br />&nbsp;<br />');
         }
     } else {
-        $r->print('<hr />'.&mt('Searching').' ...<br />&nbsp;<br />');
+        $r->print('<hr /><div id="searching">'.&mt('Searching').' ...</div>');
     }
     $r->rflush();
     if ($context eq 'course') {
@@ -1643,6 +1725,7 @@ sub print_userlist {
     }
     $r->print('<input type="hidden" name="phase" value="'.
               $env{'form.phase'}.'" /></form>');
+    return;
 }
 
 sub role_filter {
@@ -1655,11 +1738,11 @@ sub role_filter {
     my ($role_select);
     if ($context eq 'domain') {
         $role_select = &domain_roles_select();
-        $output = '<label><span class="LC_nobreak">'
+        $output = '<span class="LC_nobreak">'
                  .&mt('Role Type: [_1]',$role_select)
-                 .'</span></label>';
+                 .'</span>';
     } else {
-        $role_select = '<select name="showrole">'."\n".
+        $role_select = '<select name="showrole" onchange="javascript:updateCols('."'showrole'".');">'."\n".
                        '<option value="Any" '.$roleselected.'>'.
                        &mt('Any role').'</option>';
         my ($roletype,$crstype);
@@ -1686,9 +1769,9 @@ sub role_filter {
             $role_select .= '<option value="'.$role.'"'.$roleselected.'>'.$plrole.'</option>';
         }
         $role_select .= '</select>';
-        $output = '<label><span class="LC_nobreak">'
+        $output = '<span class="LC_nobreak">'
                  .&mt('Role: [_1]',$role_select)
-                 .'</span></label>';
+                 .'</span>';
     }
     return $output;
 }
@@ -1728,7 +1811,7 @@ sub section_group_filter {
         }
         if (@options > 0) {
             my $currsel;
-            $markup = '<select name="'.$name{$item}.'" />'."\n";
+            $markup = '<select name="'.$name{$item}.'">'."\n";
             foreach my $option ('all','none',@options) { 
                 $currsel = '';
                 if ($env{'form.'.$name{$item}} eq $option) {
@@ -1743,17 +1826,175 @@ sub section_group_filter {
                 $markup .= '</option>'."\n";
             }
             $markup .= '</select>'."\n";
-            $output .= ('&nbsp;'x3).'<label>'.$title{$item}.': '.$markup.'</label>';
+            $output .= ('&nbsp;'x3).'<span class="LC_nobreak">'
+                      .'<label>'.$title{$item}.': '.$markup.'</label>'
+                      .'</span> ';
         }
     }
     return $output;
 }
 
+sub infocolumns {
+    my ($context,$mode) = @_;
+    my @cols;
+    if (($mode eq 'pickauthor') || ($mode eq 'autoenroll')) {
+        @cols = &get_cols_array($context,$mode);
+    } else {
+        my @posscols = &get_cols_array($context,$mode);
+        if ($env{'form.phase'} ne '') {
+            my @checkedcols = &Apache::loncommon::get_env_multiple('form.showcol');
+            foreach my $col (@checkedcols) {
+                if (grep(/^$col$/,@posscols)) {
+                    push(@cols,$col);
+                }
+            }
+        } else {
+            @cols = @posscols;
+        }
+    }
+    return @cols;
+}
+
+sub get_cols_array {
+    my ($context,$mode) = @_;
+    my @cols;
+    if ($mode eq 'pickauthor') {
+        @cols = ('username','fullname','status','email');
+    } else {
+        @cols = ('username','domain','id','fullname');
+        if ($context eq 'course') {
+            push(@cols,'section');
+        }
+        push(@cols,('start','end','role'));
+        if ($context eq 'domain') {
+            push (@cols,'extent');
+        }
+        unless (($mode eq 'autoenroll') && ($env{'form.Status'} ne 'Any')) {
+            push(@cols,'status');
+        }
+        if ($context eq 'course') {
+            push(@cols,'groups');
+        }
+        push(@cols,'email');
+        if (($context eq 'course') && ($mode ne 'autoenroll')) {
+            push(@cols,'lastlogin','clicker');
+        }
+        if (($context eq 'course') && ($mode ne 'autoenroll') &&
+            ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'})) {
+            push(@cols,'photos');
+        }
+    }
+    return @cols;
+}
+
+sub column_checkboxes {
+    my ($context,$mode,$formname) = @_;
+    my @cols = &get_cols_array($context,$mode);
+    my @showncols = &Apache::loncommon::get_env_multiple('form.showcol');
+    my (%disabledchk,%unchecked);
+    if ($env{'form.phase'} eq '') {
+        $disabledchk{'status'} = 1;
+        if ($context eq 'course') {
+            $disabledchk{'role'} = 1;
+            $unchecked{'photo'} = 1;
+        }
+        $unchecked{'clicker'} = 1;
+        $unchecked{'start'} = 1;
+        $unchecked{'end'} = 1;
+    } else {
+        if ($env{'form.Status'} ne 'Any') {
+            $disabledchk{'status'} = 1;
+        }
+        if ($env{'form.showrole'} ne 'Any') {
+            $disabledchk{'role'} = 1; 
+        }
+    }
+    my $numposs = scalar(@cols);
+    my $numinrow = 8;
+    my %lt = &get_column_names($context);
+    my $output = '<fieldset><legend>'.&mt('Information to show').'</legend>'."\n".'<span class="LC_nobreak">'.
+                 '<input type="button" onclick="javascript:checkAll(document.'.$formname.'.showcol);" value="'.&mt('check all').'" />'.
+                 ('&nbsp;'x3).
+                 '<input type="button" onclick="javascript:uncheckAll(document.'.$formname.'.showcol);" value="'.&mt('uncheck all').'" />'.
+                 '</span><table>';
+    
+    for (my $i=0; $i<$numposs; $i++) {
+        my $rem = $i%($numinrow);
+        if ($rem == 0) {
+            if ($i > 0) {
+                $output .= '</tr>';
+            }
+            $output .= '<tr>';
+        }
+        my $checked;
+        if ($env{'form.phase'} eq '') {
+            $checked = ' checked="checked"';
+            if ($unchecked{$cols[$i]}) { 
+               $checked = '';
+            }
+            if ($disabledchk{$cols[$i]}) {
+                $checked = ' disabled="disabled"';
+            }
+        } elsif (grep(/^\Q$cols[$i]\E$/,@showncols)) {
+            $checked = ' checked="checked"';
+        } elsif ($disabledchk{$cols[$i]}) {
+            $checked = ' disabled="disabled"';
+        }
+        if ($i == $numposs-1) {
+            my $colsleft = $numinrow-$rem;
+            if ($colsleft > 1) {
+                $output .= '<td colspan="'.$colsleft.'">';
+            } else {
+                $output .= '<td>';
+            }
+        } else {
+            $output .= '<td>';
+        }
+        $output .= '<label><input id="showcol'.$cols[$i].'" type="checkbox" name="showcol" value="'.$cols[$i].'"'.$checked.' />'.
+                   $lt{$cols[$i]}.'</label></td>';
+
+    }
+    $output .= '</tr></table></fieldset>';
+    return $output;
+}
+
 sub list_submit_button {
     my ($text) = @_;
     return '<input type="button" name="updatedisplay" value="'.$text.'" onclick="javascript:display_update()" />';
 }
 
+sub get_column_names {
+    my ($context) = @_;
+    my %lt = &Apache::lonlocal::texthash(
+        'username'   => "username",
+        'domain'     => "domain",
+        'id'         => 'ID',
+        'fullname'   => "name",
+        'section'    => "section",
+        'groups'     => "active groups",
+        'start'      => "start date",
+        'end'        => "end date",
+        'status'     => "status",
+        'role'       => "role",
+        'type'       => "enroll type/action",
+        'email'      => "e-mail address",
+        'photo'      => "photo",
+        'lastlogin'  => "last login",
+        'extent'     => "extent",
+        'ca'         => "check all",
+        'ua'         => "uncheck all",
+        'clicker'    => "clicker-ID",
+    );
+    if ($context eq 'domain' && $env{'form.roletype'} eq 'course') {
+        $lt{'extent'} = &mt('Course(s): description, section(s), status');
+    } elsif ($context eq 'domain' && $env{'form.roletype'} eq 'community') {
+        $lt{'extent'} = &mt('Communities: description, section(s), status');
+    } elsif ($context eq 'author') {
+        $lt{'extent'} = &mt('Author');
+    }
+    return %lt;
+}
+
 sub gather_userinfo {
     my ($context,$format,$userlist,$indexhash,$userinfo,$rolehash,$permission) = @_;
     my $viewablesec;
@@ -1917,7 +2158,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;
@@ -1926,7 +2167,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;
         }
@@ -1934,7 +2175,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;
@@ -2117,7 +2358,7 @@ sub show_users_list {
         $sortby = 'username';
     }
     my $setting = $env{'form.roletype'};
-    my ($cid,$cdom,$cnum,$classgroups,$displayphotos,$displayclickers,$crstype);
+    my ($cid,$cdom,$cnum,$classgroups,$crstype);
     if ($context eq 'course') {
         $cid = $env{'request.course.id'};
         $crstype = &Apache::loncommon::course_type();
@@ -2127,14 +2368,6 @@ sub show_users_list {
         if ($mode eq 'autoenroll') {
             $env{'form.showrole'} = 'st';
         } else {
-            if (! exists($env{'form.displayphotos'})) {
-                $env{'form.displayphotos'} = 'off';
-            }
-            $displayphotos = $env{'form.displayphotos'};
-            if (! exists($env{'form.displayclickers'})) {
-                $env{'form.displayclickers'} = 'off';
-            }
-            $displayclickers = $env{'form.displayclickers'};
             if ($env{'course.'.$cid.'.internal.showphoto'}) {
                 $r->print('
 <script type="text/javascript">
@@ -2150,10 +2383,6 @@ function photowindow(photolink) {
 </script>
                ');
             }
-            $r->print(<<END);
-<input type="hidden" name="displayphotos" value="$displayphotos" />
-<input type="hidden" name="displayclickers" value="$displayclickers" />
-END
         }
     } elsif ($context eq 'domain') {
         if ($setting eq 'community') {
@@ -2163,14 +2392,12 @@ END
         }
     }
     if ($mode ne 'autoenroll' && $mode ne 'pickauthor') {
-        my $check_uncheck_js = &Apache::loncommon::check_uncheck_jscript();
         my $date_sec_selector = &date_section_javascript($context,$setting,$statusmode);
         my $verify_action_js = &bulkaction_javascript($formname);
         $r->print(<<END);
 
 <script type="text/javascript" language="Javascript">
 // <![CDATA[
-$check_uncheck_js
 
 $verify_action_js
 
@@ -2228,71 +2455,18 @@ END
     $r->print(<<END);
 <input type="hidden" name="sortby" value="$sortby" />
 END
-
-    my %lt=&Apache::lonlocal::texthash(
-                       'username'   => "username",
-                       'domain'     => "domain",
-                       'id'         => 'ID',
-                       'fullname'   => "name",
-                       'section'    => "section",
-                       'groups'     => "active groups",
-                       'start'      => "start date",
-                       'end'        => "end date",
-                       'status'     => "status",
-                       'role'       => "role",
-                       'type'       => "enroll type/action",
-                       'email'      => "e-mail address",
-                       'photo'      => "photo",
-                       'extent'     => "extent",
+    my @cols = &infocolumns($context,$mode);
+    my %coltxt = &get_column_names($context);
+    my %acttxt = &Apache::lonlocal::texthash(
                        'pr'         => "Proceed",
-                       'ca'         => "check all",
-                       'ua'         => "uncheck all",
                        'ac'         => "Action to take for selected users",
                        'link'       => "Behavior of clickable username link for each user",
                        'aboutme'    => "Display a user's personal information page",
                        'owin'       => "Open in a new window",
                        'modify'     => "Modify a user's information",
                        'track'      => "View a user's recent activity",
-                       'clicker'    => "Clicker-ID",
                       );
-    if ($context eq 'domain' && $env{'form.roletype'} eq 'course') {
-        $lt{'extent'} = &mt('Course(s): description, section(s), status');
-    } elsif ($context eq 'domain' && $env{'form.roletype'} eq 'community') {
-        $lt{'extent'} = &mt('Communities: description, section(s), status');
-    } elsif ($context eq 'author') {
-        $lt{'extent'} = &mt('Author'); 
-    }
-    my @cols;
-    if ($mode eq 'pickauthor') {
-        @cols = ('username','fullname','status','email');
-    } else {
-        @cols = ('username','domain','id','fullname');
-        if ($context eq 'course') {
-            push(@cols,'section');
-        }
-        if (!($context eq 'domain' && ($env{'form.roletype'} eq 'course')
-                              && ($env{'form.roletype'} eq 'community'))) { 
-            push(@cols,('start','end'));
-        }
-        if ($env{'form.showrole'} eq 'Any' || $env{'form.showrole'} eq 'cr') {
-            push(@cols,'role');
-        }
-        if ($context eq 'domain' && ($env{'form.roletype'} eq 'author' ||
-                                    $env{'form.roletype'} eq 'course' ||
-                                    $env{'form.roletype'} eq 'community')) {
-            push (@cols,'extent');
-        }
-        if (($statusmode eq 'Any') && 
-            (!($context eq 'domain' && (($env{'form.roletype'} eq 'course')
-             || ($env{'form.roletype'} eq 'community'))))) {
-            push(@cols,'status');
-        }
-        if ($context eq 'course') {
-            push(@cols,'groups');
-        }
-        push(@cols,'email');
-    }
-
+    my %lt = (%coltxt,%acttxt);
     my $rolefilter = $env{'form.showrole'};
     if ($env{'form.showrole'} eq 'cr') {
         $rolefilter = &mt('custom');  
@@ -2303,7 +2477,7 @@ END
     if ($mode ne 'autoenroll') {
         $results_description = &results_header_row($rolefilter,$statusmode,
                                                    $context,$permission,$mode,$crstype);
-        $r->print('<b>'.$results_description.'</b><br /><br />');
+        $r->print('<b>'.$results_description.'</b><br clear="all" />');
     }
     my ($output,$actionselect,%canchange,%canchangesec);
     if ($mode eq 'html' || $mode eq 'view' || $mode eq 'autoenroll' || $mode eq 'pickauthor') {
@@ -2365,6 +2539,12 @@ END
                             if (&Apache::lonnet::allowed('c'.$role,$env{'request.course.id'}.'/'.$env{'request.course.sec'})) {
                                 $canchangesec{$role} = $env{'request.course.sec'};
                             }
+                        } elsif ((($role eq 'co') && ($crstype eq 'Community')) ||
+                                 (($role eq 'cc') && ($crstype eq 'Course'))) {
+                            if (&is_courseowner($env{'request.course.id'},
+                                                $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'})) {
+                                $canchange{$role} = 1;
+                            }
                         }
                     }
                 }
@@ -2397,9 +2577,9 @@ END
             if ($env{'form.userwin'}) {
                 $checkwin = ' checked="checked"';
             }
-            $output .= '</td><td valign="top"><span class="LC_nobreak"><input type="checkbox" name="userwin" value="1"'.$checkwin.' />'.$lt{'owin'}.'</span></td></tr></table></fieldset></div>';
+            $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".
+        $output .= "\n".'<br clear="all" />'."\n".
                   &Apache::loncommon::start_data_table().
                   &Apache::loncommon::start_data_table_header_row();
         if ($mode eq 'autoenroll') {
@@ -2416,42 +2596,6 @@ END
             $output .= "<th><a href=\"javascript:document.$formname.sortby.value='$item';document.$formname.submit();\">$lt{$item}</a></th>\n";
         }
         my %role_types = &role_type_names();
-        if ($context eq 'course' && $mode ne 'autoenroll') {
-            if ($env{'form.showrole'} eq 'st' || $env{'form.showrole'} eq 'Any') {
-                # Clicker display on or off?
-                my %clicker_options = (
-                                        'on' => 'Show',
-                                        'off' => 'Hide',
-                                      );
-                my $clickerchg = 'on';
-                if ($displayclickers eq 'on') {
-                    $clickerchg = 'off';
-                }
-                $output .= '    <th>'."\n".'     '
-                        .&mt('[_1]'.$clicker_options{$clickerchg}.'[_2] clicker id'
-                            ,'<a href="javascript:document.'.$formname.'.displayclickers.value='
-                             ."'".$clickerchg."'".';document.'.$formname.'.submit();">'
-                            ,'</a>')
-                        ."\n".'    </th>'."\n";
-
-                # Photo display on or off?
-                if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
-                    my %photo_options = &Apache::lonlocal::texthash(
-                                                            'on' => 'Show',
-                                                            'off' => 'Hide',
-                                                                );
-                    my $photochg = 'on';
-                    if ($displayphotos eq 'on') {
-                        $photochg = 'off';
-                    }
-                    $output .= '    <th>'."\n".'     '.
-                '<a href="javascript:document.'.$formname.'.displayphotos.value='.
-                      "'".$photochg."'".';document.'.$formname.'.submit();">'.
-                      $photo_options{$photochg}.'</a>&nbsp;'.$lt{'photo'}."\n".
-                      '    </th>'."\n";
-                }
-            }
-        }
         $output .= &Apache::loncommon::end_data_table_header_row();
 # Done with the HTML header line
     } elsif ($mode eq 'csv') {
@@ -2462,20 +2606,22 @@ END
                        time.'_'.rand(1000000000).'.csv';
         unless ($CSVfile = Apache::File->new('>/home/httpd'.$CSVfilename)) {
             $r->log_error("Couldn't open $CSVfilename for output $!");
-            $r->print(&mt('Problems occurred in writing the CSV file. '
-                         .'This error has been logged. '
-                         .'Please alert your LON-CAPA administrator.'));
+            $r->print(
+                '<p class="LC_error">'
+               .&mt('Problems occurred in writing the CSV file.')
+               .' '.&mt('This error has been logged.')
+               .' '.&mt('Please alert your LON-CAPA administrator.')
+               .'</p>'
+            );
             $CSVfile = undef;
         }
         #
-        push @cols,'clicker';
         # Write headers and data to file
         print $CSVfile '"'.$results_description.'"'."\n"; 
         print $CSVfile '"'.join('","',map {
             &Apache::loncommon::csv_translate($lt{$_})
             } (@cols))."\"\n";
     } elsif ($mode eq 'excel') {
-        push @cols,'clicker';
         # Create the excel spreadsheet
         ($excel_workbook,$excel_filename,$format) =
             &Apache::loncommon::create_workbook($r);
@@ -2511,6 +2657,11 @@ END
                                                 Future  => 'Future',
                                                 Expired => 'Expired',
                                                );
+    # If this is for a single course get last course "log-in".
+    my %crslogins;
+    if ($context eq 'course') {
+        %crslogins=&Apache::lonnet::dump('nohist_crslastlogin',$cdom,$cnum);
+    }
     # Get groups, role, permanent e-mail so we can sort on them if
     # necessary.
     foreach my $user (keys(%{$userlist})) {
@@ -2594,7 +2745,7 @@ END
                     }
                 }
                 if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
-                    if (($displayphotos eq 'on') && ($role eq 'st')) {
+                    if ((grep/^photo$/,@cols) && ($role eq 'st')) {
                         $userlist->{$user}->[$index{'photo'}] =
                             &Apache::lonnet::retrievestudentphoto($udom,$uname,'jpg');
                         $userlist->{$user}->[$index{'thumbnail'}] =
@@ -2647,15 +2798,23 @@ END
         $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'});
+        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 (! defined($in{'end'}) || $in{'end'} == 0) {
-            $in{'end'} = &mt('none');
-        } else {
-            $in{'end'} = &Apache::lonlocal::locallocaltime($in{'end'});
+        if ($context eq 'course') {
+            my $lastlogin = $crslogins{$in{'username'}.':'.$in{'domain'}.':'.$in{'section'}.':'.$role};
+            if ($lastlogin ne '') {
+                $in{'lastlogin'} = &Apache::lonlocal::locallocaltime($lastlogin);
+            }
         }
         if ($mode eq 'view' || $mode eq 'html' || $mode eq 'autoenroll' || $mode eq 'pickauthor') {
             $r->print(&Apache::loncommon::start_data_table_row());
@@ -2701,17 +2860,26 @@ END
                     if ($showcheckbox) {
                         $checkval = $user; 
                         if ($context eq 'course') {
-                            if ($role eq 'st') {
-                                $checkval .= ':st';
-                            }
-                            $checkval .= ':'.$in{'section'};
-                            if ($role eq 'st') {
-                                $checkval .= ':'.$in{'type'}.':'.
-                                             $in{'lockedtype'};
-                            }
+                            if (($role eq 'co' || $role eq 'cc') &&
+                                ($user =~ /^\Q$env{'user.name'}:$env{'user.domain'}:$role\E/)) {
+                                $showcheckbox = 0;
+                            } else {
+                                if ($role eq 'st') {
+                                    $checkval .= ':st';
+                                }
+                                $checkval .= ':'.$in{'section'};
+                                if ($role eq 'st') {
+                                    $checkval .= ':'.$in{'type'}.':'.
+                                                 $in{'lockedtype'};
+                                }
+                             }
+                        }
+                        if ($showcheckbox) {
+                            $r->print('<td><input type="checkbox" name="'.
+                                      'actionlist" value="'.$checkval.'" /></td>');
+                        } else {
+                            $r->print('<td>&nbsp;</td>');
                         }
-                        $r->print('<td><input type="checkbox" name="'.
-                                  'actionlist" value="'.$checkval.'" /></td>');
                     } else {
                         $r->print('<td>&nbsp;</td>');
                     }
@@ -2730,43 +2898,34 @@ END
                         $showitem = $ltstatus{$in{$item}};
                     }
                     $r->print('<td>'.$showitem.'</td>'."\n");
-                } else {
-                    $r->print('<td>'.$in{$item}.'</td>'."\n");
-                }
-            }
-            if (($context eq 'course') && ($mode ne 'autoenroll')) {
-                if ($env{'form.showrole'} eq 'st' || $env{'form.showrole'} eq 'Any') {
-                    if ($displayclickers eq 'on') {
-                        my $clickers =
+                } elsif ($item eq 'photo') {
+                     if (($context eq 'course') && ($mode ne 'autoenroll') && 
+                         ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'})) { 
+                         if ($role eq 'st') {
+                             $r->print('<td align="right"><a href="javascript:photowindow('."'".$in{'photo'}."'".')"><img src="'.$in{'thumbnail'}.'" border="1" alt="" /></a></td>');
+                         } else {
+                             $r->print('<td>&nbsp;</td>');
+                         }
+                     }
+                } elsif ($item eq 'clicker') {
+                    if (($context eq 'course') && ($mode ne 'autoenroll')) {
+                        if ($env{'form.showrole'} eq 'st' || $env{'form.showrole'} eq 'Any') {
+                            my $clickers =
                    (&Apache::lonnet::userenvironment($in{'domain'},$in{'username'},'clickers'))[1];
-                        if ($clickers!~/\w/) { $clickers='-'; }
-                        $r->print('<td>'.$clickers.'</td>');
-                    } else {
-                        $r->print('    <td>&nbsp;</td>  ');
-                    }
-                    if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
-                        if ($displayphotos eq 'on' && $role eq 'st' && $in{'photo'} ne '') {
-                            $r->print('    <td align="right"><a href="javascript:photowindow('."'".$in{'photo'}."'".')"><img src="'.$in{'thumbnail'}.'" border="1" alt="" /></a></td>');
+                            if ($clickers!~/\w/) { $clickers='-'; }
+                            $r->print('<td>'.$clickers.'</td>');
                         } else {
-                            $r->print('    <td>&nbsp;</td>  ');
-                        }
-                    }
+                             $r->print('<td>&nbsp;</td>'."\n");
+                        } 
+                    } 
+                } else {
+                    $r->print('<td>'.$in{$item}.'</td>'."\n");
                 }
             }
             $r->print(&Apache::loncommon::end_data_table_row());
         } 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});
@@ -2776,9 +2935,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');
@@ -2933,7 +3092,7 @@ sub print_username_link {
         $output = $in->{'username'};
     } else {
         $output = '<a href="javascript:username_display_launch('.
-                  "'$in->{'username'}','$in->{'domain'}'".')" />'.
+                  "'$in->{'username'}','$in->{'domain'}'".')">'.
                   $in->{'username'}.'</a>';
     }
     return $output;
@@ -2966,15 +3125,20 @@ sub select_actions {
     }
     if ($context eq 'course') {
         if ($env{'form.showrole'} ne 'Any') {
-             if (!&Apache::lonnet::allowed('c'.$env{'form.showrole'},
-                                           $env{'request.course.id'})) {
-                 if ($env{'request.course.sec'} eq '') {
-                     return;
-                 } else {
-                     if (!&Apache::lonnet::allowed('c'.$env{'form.showrole'},$env{'request.course.id'}.'/'.$env{'request.course.sec'})) {
-                         return;
-                     }
-                 }
+            my $showactions;
+            if (&Apache::lonnet::allowed('c'.$env{'form.showrole'},
+                                          $env{'request.course.id'})) {
+                $showactions = 1;  
+            } elsif ($env{'request.course.sec'} ne '') {
+                if (&Apache::lonnet::allowed('c'.$env{'form.showrole'},$env{'request.course.id'}.'/'.$env{'request.course.sec'})) {
+                    $showactions = 1;
+                }
+            }
+            unless ($showactions) {
+                unless (&is_courseowner($env{'request.course.id'},
+                                       $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'})) {
+                    return; 
+                }
             }
         }
     }
@@ -3163,9 +3327,9 @@ ENDJS
     my %lt = &Apache::lonlocal::texthash (
                  chac => 'Access dates to apply for selected users',
                  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 role in a course that is not a student role, a user may have roles in more than one section of a course at a time.',
-                 reta => "Retain each user's current section affiliations?", 
+                 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?",
                  dnap => '(Does not apply to student roles).',
             );
     my ($date_items,$headertext);
@@ -3183,14 +3347,13 @@ ENDJS
                                           $permission,$crstype);
     }
     $output .= '<h3>'.$headertext.'</h3>'.
-               '<form name="'.$formname.'" method="post">'."\n".
+               '<form name="'.$formname.'" method="post" action="">'."\n".
                 $date_items;
     if ($context eq 'course' && $env{'form.bulkaction'} eq 'chgsec') {
         my ($cnum,$cdom) = &get_course_identity();
-        my $crstype = &Apache::loncommon::course_type();
         if ($crstype eq 'Community') {
-            $lt{'fors'} = &mt('For member roles changing the section, will result in a section switch as members may only be in one section of a community at a time.');
-            $lt{'forn'} = &mt('For a role in a community that is not a member role, a user may have roles in more than one section of a community at a time.');
+            $lt{'fors'} = &mt('For member roles, changing the section will result in a section switch, as members may only be in one section of a community at a time.');
+            $lt{'forn'} = &mt('For a community role that is not "member", users may have roles in more than one section at a time.');
             $lt{'dnap'} = &mt('(Does not apply to member roles).'); 
         }
         my $info;
@@ -3231,7 +3394,7 @@ sub section_picker {
     my ($cdom,$cnum,$role,$rowtitle,$permission,$context,$mode,$crstype) = @_;
     my %sections_count = &Apache::loncommon::get_sections($cdom,$cnum);
     my $sections_select .= &course_sections(\%sections_count,$role);
-    my $secbox = '<p>'.&Apache::lonhtmlcommon::start_pick_box()."\n";
+    my $secbox = '<div>'.&Apache::lonhtmlcommon::start_pick_box()."\n";
     if ($mode eq 'upload') {
         my ($options,$cb_script,$coursepick) =
             &default_role_selector($context,1,$crstype);
@@ -3244,7 +3407,7 @@ sub section_picker {
                    '<td align="center">'.&mt('Existing sections')."\n".
                    '<br />'.$sections_select.'</td><td align="center">'.
                    &mt('New section').'<br />'."\n".
-                   '<input type="text" name="newsec" size="15" />'."\n".
+                   '<input type="text" name="newsec" size="15" value="" />'."\n".
                    '<input type="hidden" name="sections" value="" />'."\n".
                    '</td></tr></table>'."\n";
     } else {
@@ -3253,7 +3416,7 @@ sub section_picker {
                    $env{'request.course.sec'};
     }
     $secbox .= &Apache::lonhtmlcommon::row_closure(1)."\n".
-               &Apache::lonhtmlcommon::end_pick_box().'</p>';
+               &Apache::lonhtmlcommon::end_pick_box().'</div>';
     return $secbox;
 }
 
@@ -3394,7 +3557,7 @@ sub results_header_row {
                 if ($rolefilter eq 'Any') {
                     $description .= &mt('All users with co-author roles in domain',$showfilter);
                 } else {
-                    $description .= &mt('All co-authors in domain  with [_1] roles',$rolefilter);
+                    $description .= &mt('All co-authors in domain with [_1] roles',$rolefilter);
                 }
             }
         } elsif (($env{'form.roletype'} eq 'course') || 
@@ -3654,14 +3817,13 @@ sub print_first_users_upload_form {
     $str .= '<h2>'.&mt('Upload a file containing information about users').'</h2>'."\n";
 
     # Excel and CSV Help
-    $str .= '<p>'
+    $str .= '<div class="LC_left_float">'
            .&Apache::loncommon::help_open_topic("Course_Create_Class_List",
                 &mt("How do I create a users list from a spreadsheet"))
-           ."<br />\n"
+           .'</div><div class="LC_left_float">'."\n"
            .&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                 &mt("How do I create a CSV file from a spreadsheet"))
-           ."</p>\n";
-
+           .'</div><br clear="all" />'."\n";
     $str .= &Apache::lonhtmlcommon::start_pick_box()
            .&Apache::lonhtmlcommon::row_title(&mt('File'));
     if (&Apache::lonlocal::current_language() ne 'en') {
@@ -3685,8 +3847,6 @@ sub print_first_users_upload_form {
            .'<input type="submit" name="fileupload" value="'.&mt('Next').'" />'
            .'</p>';
 
-    $str .= &Apache::loncommon::end_page();
-
     $r->print($str);
     return;
 }
@@ -3914,15 +4074,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 +4110,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 +4182,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 +4229,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 +4238,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 +4334,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;
+                                    }
                                 }
                             }
                         }
@@ -4222,7 +4434,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) {
@@ -4386,10 +4598,9 @@ sub print_drop_menu {
 # ================================================================== Phase four
 
 sub update_user_list {
-    my ($r,$context,$setting,$choice) = @_;
+    my ($r,$context,$setting,$choice,$crstype) = @_;
     my $now = time;
     my $count=0;
-    my $crstype;
     if ($context eq 'course') {
         $crstype = &Apache::loncommon::course_type();
     }
@@ -4404,7 +4615,7 @@ sub update_user_list {
                                    'reenable' => 'Re-enabled',
                                    'activate' => 'Activated',
                                    'chgdates' => 'Changed Access Dates for',
-                                   'chgsec'   => 'Changed section for',
+                                   'chgsec'   => 'Changed section(s) for',
                                    'drop'     => 'Dropped',
                                  },
                         error => {'revoke'    => 'revoking',
@@ -4421,8 +4632,9 @@ sub update_user_list {
         ($startdate,$enddate) = &get_dates_from_form();
     }
     foreach my $item (@changelist) {
-        my ($role,$uname,$udom,$cid,$sec,$scope,$result,$type,$locktype,@sections,
-            $scopestem);
+        my ($role,$uname,$udom,$cid,$sec,$scope,$result,$type,$locktype,
+            @sections,$scopestem,$singlesec,$showsecs,$warn_singlesec,
+            $nothingtodo,$keepnosection);
         if ($choice eq 'drop') {
             ($uname,$udom,$sec) = split(/:/,$item,-1);
             $role = 'st';
@@ -4521,14 +4733,23 @@ sub update_user_list {
             } elsif ($choice eq 'chgsec') {
                 my (@newsecs,$revresult,$nochg,@retained);
                 if (($role ne 'cc') && ($role ne 'co')) {
-                    @newsecs = split(/,/,$env{'form.newsecs'});
+                    my @secs = sort(split(/,/,$env{'form.newsecs'}));
+                    if (@secs) {
+                        my %curr_groups = &Apache::longroup::coursegroups();
+                        foreach my $sec (@secs) {
+                            next if (($sec =~ /\W/) || ($sec eq 'none') ||
+                            (exists($curr_groups{$sec})));
+                            push(@newsecs,$sec);
+                        }
+                    }
                 }
                 # remove existing section if not to be retained.   
-                if (!$env{'form.retainsec'}) {
+                if (!$env{'form.retainsec'} || ($role eq 'st')) {
                     if ($sec eq '') {
                         if (@newsecs == 0) {
-                            $result = &mt('No change in section assignment (none)');
+                            $result = 'ok';
                             $nochg = 1;
+                            $nothingtodo = 1;
                         } else {
                             $revresult =
                                 &Apache::lonnet::revokerole($udom,$uname,
@@ -4555,13 +4776,23 @@ sub update_user_list {
                 } else {
                     if ($sec eq '') {
                         $nochg = 1;
-                    } else { 
+                        $keepnosection = 1;
+                    } else {
                         push(@retained,$sec);
                     }
                 }
                 # add new sections
+                my (@diffs,@shownew);
+                if (@retained) {
+                    @diffs = &Apache::loncommon::compare_arrays(\@retained,\@newsecs);
+                } else {
+                    @diffs = @newsecs;
+                }
                 if (@newsecs == 0) {
-                    if (!$nochg) {
+                    if ($nochg) {
+                        $result = 'ok';
+                        $nothingtodo = 1;
+                    } else {
                         if ($role eq 'st') {
                             $result = 
                                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,undef,$end,$start,$type,$locktype,$cid,'',$context);
@@ -4570,22 +4801,58 @@ sub update_user_list {
                             $result = &Apache::lonnet::assignrole($udom,$uname,$newscope,$role,$end,$start,'','',$context);
                         }
                     }
+                    $showsecs = &mt('No section');
+                } elsif (@diffs == 0) {
+                    $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; 
+                                    if ($newsec eq '') {
+                                        $showsingle = &mt('No section');
+                                    } else {
+                                        $showsingle = $newsec;
+                                    }
+                                    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 { 
+                                        $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; 
+                                    last;
+                                } else {
+                                    if ($newsec eq '') {
+                                        $showsecs = &mt('No section');
+                                    } else {
+                                        $showsecs = $newsec;
+                                    }
+                                }
                             } else {
                                 my $newscope = $scopestem;
                                 if ($newsec ne '') {
                                    $newscope .= '/'.$newsec;
+                                   push(@shownew,$newsec); 
                                 }
                                 $result = &Apache::lonnet::assignrole($udom,$uname,
                                                         $newscope,$role,$end,$start);
+                                
                             }
                         }
                     }
                 }
+                unless ($role eq 'st') {
+                    unless ($showsecs) {
+                        my @tolist = sort(@shownew,@retained);
+                        if ($keepnosection) {
+                            push(@tolist,&mt('No section'));
+                        }
+                        $showsecs = join(', ',@tolist);
+                    }
+                }
             }
         }
         my $extent = $scope;
@@ -4596,13 +4863,48 @@ sub update_user_list {
             }
         }
         if ($result eq 'ok' || $result eq 'ok:') {
-            $r->print(&mt("$result_text{'ok'}{$choice} role of '[_1]' in [_2] for [_3]",
-                          $plrole,$extent,$uname.':'.$udom).'<br />');
-            $count++;
+            my $dates;
+            if (($choice eq 'chgsec') || ($choice eq 'chgdates')) {
+                $dates = &dates_feedback($start,$end,$now);
+            }
+            if ($choice eq 'chgsec') {
+                if ($nothingtodo) {
+                    $r->print(&mt("Section assignment for role of '[_1]' in [_2] for '[_3]' unchanged.",$plrole,$extent,'<i>'.
+                          &Apache::loncommon::plainname($uname,$udom).
+                          '</i>').' ');
+                    if ($sec eq '') {
+                        $r->print(&mt('[_1]No section[_2] - [_3]','<b>','</b>',$dates));
+                    } else {
+                        $r->print(&mt('Section(s): [_1] - [_2]',
+                                      '<b>'.$showsecs.'</b>',$dates));
+                    }
+                    $r->print('<br />');
+                } else {
+                    $r->print(&mt("$result_text{'ok'}{$choice} role of '[_1]' in [_2] for '[_3]' to [_4] - [_5]",$plrole,$extent,
+                        '<i>'.&Apache::loncommon::plainname($uname,$udom).'</i>',
+                        '<b>'.$showsecs.'</b>',$dates).'<br />');
+                   $count ++;
+               }
+               if ($warn_singlesec) {
+                   $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>',
+                      $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>').
+                          '<br />');
+                $count ++;
+            }
         } else {
             $r->print(
-                &mt("Error $result_text{'error'}{$choice} [_1] in [_2] for [_3]: [_4].",
-                    $plrole,$extent,$uname.':'.$udom,$result).'<br />');
+                &mt("Error $result_text{'error'}{$choice} [_1] in [_2] for '[_3]': [_4].",
+                    $plrole,$extent,
+                    '<i>'.&Apache::loncommon::plainname($uname,$udom).'</i>',
+                    $result).'<br />');
         }
     }
     $r->print('<form name="studentform" method="post" action="/adm/createuser">'."\n");
@@ -4618,13 +4920,13 @@ sub update_user_list {
             }
         }
     }
-    $r->print('<p><b>'.&mt("$result_text{'ok'}{$choice} role(s) for [quant,_1,user,users,no users].",$count).'</b></p>');
+    $r->print('<p><b>'.&mt("$result_text{'ok'}{$choice} for [quant,_1,user role,user roles,no user roles].",$count).'</b></p>');
     if ($count > 0) {
         if ($choice eq 'revoke' || $choice eq 'drop') {
             $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') {
@@ -4638,6 +4940,27 @@ sub update_user_list {
     $r->print('<a href="javascript:document.studentform.submit()">'.$linktext.'</a></form>'."\n");
 }
 
+sub dates_feedback {
+    my ($start,$end,$now) = @_;
+    my $dates;
+    if ($start < $now) {
+        if ($end == 0) {
+            $dates .= &mt('role(s) active now; no end date');
+        } elsif ($end > $now) {
+            $dates = &mt('role(s) active now; ends [_1].',&Apache::lonlocal::locallocaltime($end));
+        } else {
+            $dates = &mt('role(s) expired: [_1].',&Apache::lonlocal::locallocaltime($end));
+        }
+     } else {
+        if ($end == 0 || $end > $now) {
+            $dates = &mt('future role(s); starts: [_1].',&Apache::lonlocal::locallocaltime($start));
+        } else {
+            $dates = &mt('role(s) expired: [_1].',&Apache::lonlocal::locallocaltime($end));
+        }
+    }
+    return $dates;
+}
+
 sub classlist_drop {
     my ($scope,$uname,$udom,$now) = @_;
     my ($cdom,$cnum) = ($scope=~m{^/($match_domain)/($match_courseid)});
@@ -4818,7 +5141,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 on 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.',
@@ -4826,16 +5149,21 @@ sub setsections_javascript {
                     plch => 'Please choose a different section name.',
                     mnot => 'may not be used as a section name, as it is the name of a course group.',
                     secn => 'Section names and group names must be distinct. Please choose a different section name.',
+                    nonw => 'Section names may only contain letters or numbers.',
                  );                
     $setsection_js .= <<"ENDSECCODE";
 
 function setSections(formname,crstype) {
     var re1 = /^currsec_/;
+    var re2 =/\\W/;
+    var trimleading = /^\\s+/;
+    var trimtrailing = /\\s+\$/;
     var groups = new Array($groupslist);
     for (var i=0;i<formname.elements.length;i++) {
         var str = formname.elements[i].name;
         var checkcurr = str.match(re1);
         if (checkcurr != null) {
+            var num = i;
             if ($checkincluded) {
                 $rolecode
                 if (role == 'cc' || role == 'co') {
@@ -4847,38 +5175,60 @@ function setSections(formname,crstype) {
                 } else {
                     var sections = '';
                     var numsec = 0;
-                    var sections;
-                    for (var j=0; j<formname.elements[i].length; j++) {
-                        if (formname.elements[i].options[j].selected == true ) {
-                            if (formname.elements[i].options[j].value != "") {
+                    var fromexisting = new Array();
+                    for (var j=0; j<formname.elements[num].length; j++) {
+                        if (formname.elements[num].options[j].selected == true ) {
+                            var addsec = formname.elements[num].options[j].value;
+                            if ((addsec != "") && (addsec != null)) {
+                                fromexisting.push(addsec);
                                 if (numsec == 0) {
-                                    if (formname.elements[i].options[j].value != "") {
-                                        sections = formname.elements[i].options[j].value;
-                                        numsec ++;
-                                    }
-                                }
-                                else {
-                                    sections = sections + "," +  formname.elements[i].options[j].value
-                                    numsec ++;
+                                    sections = addsec;
+                                } else {
+                                    sections = sections + "," +  addsec;
                                 }
+                                numsec ++;
                             }
                         }
                     }
-                    if (numsec > 0) {
-                        if (formname.elements[i+1].value != "" && formname.elements[i+1].value != null) {
-                            sections = sections + "," +  formname.elements[i+1].value;
-                        }
-                    }
-                    else {
-                        sections = formname.elements[i+1].value;
-                    }
-                    var newsecs = formname.elements[i+1].value;
-                    var numsplit;
+                    var newsecs = formname.elements[num+1].value;
+                    var validsecs = new Array();
+                    var validsecstr = '';
+                    var badsecs = new Array();
                     if (newsecs != null && newsecs != "") {
-                        numsplit = newsecs.split(/,/g);
-                        numsec = numsec + numsplit.length;
+                        var numsplit;
+                        if (newsecs.indexOf(',') == -1) {
+                            numsplit = new Array(newsecs);
+                        } else {
+                            numsplit = newsecs.split(/,/g);
+                        }
+                        for (var m=0; m<numsplit.length; m++) {
+                            var newsec = numsplit[m];
+                            newsec = newsec.replace(trimleading,'');
+                            newsec = newsec.replace(trimtrailing,'');
+                            if (re2.test(newsec) == true) {
+                                badsecs.push(newsec);
+                            } else {
+                                if (newsec != '') {
+                                    var isnew = 1;
+                                    if (fromexisting != null) {
+                                        for (var n=0; n<fromexisting.length; n++) {
+                                            if (newsec == fromexisting[n]) {
+                                                isnew = 0;
+                                            }
+                                        }
+                                    }
+                                    if (isnew == 1) {
+                                        validsecs.push(newsec);
+                                    }
+                                }
+                            }
+                        }
+                        if (badsecs.length > 0) {
+                            alert("$alerts{'nonw'}\\n$alerts{'plch'}");
+                            return;
+                        }
+                        numsec = numsec + validsecs.length;
                     }
-
                     if ((role == 'st') && (numsec > 1)) {
                         if (crstype == 'Community') {
                             alert("$alerts{'inea'} $alerts{'youh'} "+numsec+" $alerts{'secs'}\\n$alerts{'plmo'}");
@@ -4886,25 +5236,36 @@ function setSections(formname,crstype) {
                             alert("$alerts{'inco'} $alerts{'youh'} "+numsec+" $alerts{'secs'}\\n$alerts{'plmo'}");
                         }
                         return;
-                    }
-                    else {
-                        if (numsplit != null) {
-                            for (var j=0; j<numsplit.length; j++) {
-                                if ((numsplit[j] == 'all') ||
-                                    (numsplit[j] == 'none')) {
-                                    alert("'"+numsplit[j]+"' $alerts{'mayn'}\\n$alerts{'plch'}");
+                    } else {
+                        if (validsecs != null) {
+                            for (var j=0; j<validsecs.length; j++) {
+                                if (validsecstr == '' || validsecstr == null) {
+                                    validsecstr = validsecs[j];
+                                } else {
+                                    validsecstr += ','+validsecs[j];
+                                }
+                                if ((validsecs[j] == 'all') ||
+                                    (validsecs[j] == 'none')) {
+                                    alert("'"+validsecs[j]+"' $alerts{'mayn'}\\n$alerts{'plch'}");
                                     return;
                                 }
                                 for (var k=0; k<groups.length; k++) {
-                                    if (numsplit[j] == groups[k]) {
-                                        alert("'"+numsplit[j]+"' $alerts{'mnot'}\\n$alerts{'secn'}");
+                                    if (validsecs[j] == groups[k]) {
+                                        alert("'"+validsecs[j]+"' $alerts{'mnot'}\\n$alerts{'secn'}");
                                         return;
                                     }
                                 }
                             }
                         }
-                        formname.elements[i+2].value = sections;
                     }
+                    if ((validsecstr != '') && (validsecstr != null)) {
+                        if ((sections == '') || (sections == null)) {
+                            sections = validsecstr;
+                        } else {
+                            sections = sections + "," + validsecstr;
+                        }
+                    }
+                    formname.elements[num+2].value = sections;
                 }
             }
         }
@@ -5001,18 +5362,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;
+                        }
                     }
                 }
             }
@@ -5388,5 +5771,20 @@ sub authcheck_alerts {
     return %alerts;
 }
 
+sub is_courseowner {
+    my ($thiscourse,$courseowner) = @_;
+    if ($courseowner eq '') {
+        if ($env{'request.course.id'} eq $thiscourse) {
+            $courseowner = $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
+        }
+    }
+    if ($courseowner ne '') {
+        if ($courseowner eq $env{'user.name'}.':'.$env{'user.domain'}) {
+            return 1;
+        }
+    }
+    return;
+}
+
 1;