--- loncom/interface/lonuserutils.pm	2012/10/04 13:41:10	1.143
+++ loncom/interface/lonuserutils.pm	2014/04/04 23:06:31	1.166
@@ -1,7 +1,7 @@
 # The LearningOnline Network with CAPA
 # Utility functions for managing LON-CAPA user accounts
 #
-# $Id: lonuserutils.pm,v 1.143 2012/10/04 13:41:10 bisitz Exp $
+# $Id: lonuserutils.pm,v 1.166 2014/04/04 23:06:31 raeburn Exp $
 #
 # Copyright Michigan State University Board of Trustees
 #
@@ -237,6 +237,8 @@ sub domain_roles_select {
     # Role types
     my @roletypes = ('domain','author','course','community');
     my %lt = &role_type_names();
+    my $onchangefirst = "updateCols('showrole')";
+    my $onchangesecond = "updateCols('showrole')";
     #
     # build up the menu information to be passed to
     # &Apache::loncommon::linked_select_forms
@@ -283,7 +285,8 @@ sub domain_roles_select {
     my $result = &Apache::loncommon::linked_select_forms
         ('studentform',(' 'x3).&mt('Role: '),$env{'form.roletype'},
          'roletype','showrole',\%select_menus,
-         ['domain','author','course','community']);
+         ['domain','author','course','community'],$onchangefirst,
+         $onchangesecond);
     return $result;
 }
 
@@ -335,13 +338,22 @@ sub print_upload_manager_header {
                                 $env{'request.role.domain'},$context,
                                 $groupslist,$crstype);
     my $checked=(($env{'form.noFirstLine'})?' checked="checked"':'');
-    $r->print('<p>'
-             .&mt('Total number of records found in file: [_1]'
-                 ,'<b>'.$distotal.'</b>')
-             ."</p>\n");
-    $r->print('<div class="LC_left_float"><h3>'.
-              &mt('Identify fields in uploaded list')."</h3>\n");
-    $r->print(&mt('Enter as many fields as you can.<br /> The system will inform you and bring you back to this page, <br /> if the data selected are insufficient to add users.')."<br />\n");
+    $r->print(
+        '<h3>'.&mt('Identify fields in uploaded list')."</h3>\n".
+        '<p class="LC_info">'.
+        &mt('Total number of records found in file: [_1]'
+           ,'<b>'.$distotal.'</b>').
+        "</p>\n"
+    );
+    if ($distotal == 0) {
+        $r->print('<p class="LC_warning">'.&mt('None found').'</p>');
+    }
+    $r->print(
+        '<p>'.
+        &mt('Enter as many fields as you can.').'<br />'.
+        &mt('The system will inform you and bring you back to this page,[_1]if the data selected are insufficient to add users.','<br />').
+        "</p>\n"
+    );
     $r->print(&hidden_input('action','upload').
               &hidden_input('state','got_file').
               &hidden_input('associate','').
@@ -349,17 +361,23 @@ sub print_upload_manager_header {
               &hidden_input('fileupload',$env{'form.fileupload'}).
               &hidden_input('upfiletype',$env{'form.upfiletype'}).
               &hidden_input('upfile_associate',$env{'form.upfile_associate'}));
-    $r->print('<br /><label><input type="checkbox" name="noFirstLine"'.$checked.' />'.
-              &mt('Ignore First Line').'</label><br />');
-    $r->print('<br /><input type="button" value="'.&mt('Reverse Association').'" '.
+    $r->print(
+        '<div class="LC_left_float">'.
+        '<fieldset><legend>'.&mt('Functions').'</legend>'.
+        '<label><input type="checkbox" name="noFirstLine"'.$checked.' />'.
+              &mt('Ignore First Line').'</label>'.
+        ' <input type="button" value="'.&mt('Reverse Association').'" '.
               'name="Reverse Association" '.
-              'onclick="javascript:this.form.associate.value=\'Reverse Association\';submit(this.form);" />');
-    $r->print("<br /><br />\n".
-              '<script type="text/javascript" language="Javascript">'."\n".
-              '// <![CDATA['."\n".
-              $javascript."\n".$javascript_validations."\n".
-              '// ]]>'."\n".
-              '</script>');
+              'onclick="javascript:this.form.associate.value=\'Reverse Association\';submit(this.form);" />'.
+        '</fieldset></div><br clear="all" />'
+    );
+    $r->print(
+        '<script type="text/javascript" language="Javascript">'."\n".
+        '// <![CDATA['."\n".
+        $javascript."\n".$javascript_validations."\n".
+        '// ]]>'."\n".
+        '</script>'
+    );
 }
 
 ###############################################################
@@ -381,6 +399,12 @@ sub javascript_validations {
         $param{'curr_autharg'} = $curr_authfield;
     }
 
+    my $showcredits;
+    my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
+    if ($domdefaults{'officialcredits'} || $domdefaults{'unofficialcredits'} || $domdefaults{'textbookcredits'}) {
+        $showcredits = 1;
+    }
+
     my ($setsection_call,$setsections_js);
     my $finish = "  vf.submit();\n";
     if ($mode eq 'upload') {
@@ -390,13 +414,14 @@ sub javascript_validations {
                     $setsection_call = 'setSections(document.'.$param{'formname'}.",'$crstype'".');';
                     $setsections_js =
                         &setsections_javascript($param{'formname'},$groupslist,
-                                                $mode,'',$crstype);
+                                                $mode,'',$crstype,$showcredits);
                 } else {
                     $setsection_call = "'ok'";
                 }
             } elsif ($context eq 'domain') {
                 $setsection_call = 'setCourse()';
-                $setsections_js = &dc_setcourse_js($param{'formname'},$mode,$context);
+                $setsections_js = &dc_setcourse_js($param{'formname'},$mode,
+                                                   $context,$showcredits);
             }
             $finish = "  var checkSec = $setsection_call\n".
                       "  if (checkSec == 'ok') {\n".
@@ -419,13 +444,16 @@ sub javascript_validations {
          domain   => 'The optional domain field was not specified.',
          continue => 'Continue adding users?',
          );
+    if ($showcredits) {
+        $alert{'credits'} = &mt('The optional credits field was not specified');
+    }
     if (($mode eq 'upload') && ($context eq 'domain')) {
         $alert{'inststatus'} = &mt('The optional affiliation field was not specified'); 
     }
     my $function_name = <<"END";
 $setsections_js
 
-function verify_message (vf,founduname,foundpwd,foundname,foundid,foundsec,foundemail,foundrole,founddomain,foundinststatus) {
+function verify_message (vf,founduname,foundpwd,foundname,foundid,foundsec,foundemail,foundrole,founddomain,foundinststatus,foundcredits) {
 END
     my ($authnum,%can_assign) =  &Apache::loncommon::get_assignable_auth($domain);
     my $auth_checks;
@@ -482,6 +510,7 @@ END
             return;
         }
     }
+/* regexp here to check for non \d \. in credits */
 END
     } else {
         $auth_checks .= (<<END);
@@ -554,6 +583,16 @@ END
         message+='$alert{'domain'}';
     }
 END
+        if ($showcredits) {
+            $optional_checks .= <<END;
+    if (foundcredits==0) {
+        if (message!='') {
+            message+='\\n';
+        }
+        message+='$alert{'credits'}';
+    }
+END
+        }
         if (($mode eq 'upload') && ($context eq 'domain')) {
             $optional_checks .= (<<END);
 
@@ -603,7 +642,7 @@ sub upload_manager_javascript_forward_as
             $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').
+            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
@@ -638,6 +677,7 @@ function verify(vf,sec_caller) {
     var foundrole=0;
     var founddomain=0;
     var foundinststatus=0;
+    var foundcredits=0;
     var tw;
     for (i=0;i<=vf.nfields.value;i++) {
         tw=eval('vf.f'+i+'.selectedIndex');
@@ -650,8 +690,9 @@ function verify(vf,sec_caller) {
         if (tw==11) { foundrole=1; }
         if (tw==12) { founddomain=1; }
         if (tw==13) { foundinststatus=1; }
+        if (tw==14) { foundcredits=1; }
     }
-    verify_message(vf,founduname,foundpwd,foundname,foundid,foundsec,foundemail,foundrole,founddomain,foundinststatus);
+    verify_message(vf,founduname,foundpwd,foundname,foundid,foundsec,foundemail,foundrole,founddomain,foundinststatus,foundcredits);
 }
 
 //
@@ -674,6 +715,7 @@ function verify(vf,sec_caller) {
 // 11 = role
 // 12 = domain
 // 13 = inststatus
+// 14 = foundcredits 
 
 function flip(vf,tf) {
    var nw=eval('vf.f'+tf+'.selectedIndex');
@@ -771,6 +813,7 @@ function verify(vf,sec_caller) {
     var foundrole=0;
     var founddomain=0;
     var foundinststatus=0;
+    var foundcredits=0;
     var tw;
     for (i=0;i<=vf.nfields.value;i++) {
         tw=eval('vf.f'+i+'.selectedIndex');
@@ -783,8 +826,9 @@ function verify(vf,sec_caller) {
         if (i==10 && tw!=0) { foundrole=1; }
         if (i==11 && tw!=0) { founddomain=1; }
         if (i==12 && tw!=0) { foundinstatus=1; }
+        if (i==13 && tw!=0) { foundcredits=1; }
     }
-    verify_message(vf,founduname,foundpwd,foundname,foundid,foundsec,foundemail,foundrole,founddomain,foundinststatus);
+    verify_message(vf,founduname,foundpwd,foundname,foundid,foundsec,foundemail,foundrole,founddomain,foundinststatus,foundcredits);
 }
 
 function flip(vf,tf) {
@@ -816,7 +860,8 @@ ENDPICK
 ###############################################################
 ###############################################################
 sub print_upload_manager_footer {
-    my ($r,$i,$keyfields,$defdom,$today,$halfyear,$context,$permission,$crstype) = @_;
+    my ($r,$i,$keyfields,$defdom,$today,$halfyear,$context,$permission,$crstype,
+        $showcredits) = @_;
     my $form = 'document.studentform';
     my $formname = 'studentform';
     my ($krbdef,$krbdefdom) =
@@ -905,9 +950,15 @@ sub print_upload_manager_footer {
                     &mt('Default role'))
                .&mt('Choose the role to assign to users without a value specified in the uploaded file.')
     } elsif ($context eq 'course') {
-        $Str .= &Apache::lonhtmlcommon::row_title(
+        if ($showcredits) {
+            $Str .= &Apache::lonhtmlcommon::row_title(
+                    &mt('Default role, section and credits'))
+                   .&mt('Choose the role and/or section(s) and/or credits to assign to users without values specified in the uploaded file.');
+        } else { 
+            $Str .= &Apache::lonhtmlcommon::row_title(
                     &mt('Default role and section'))
-               .&mt('Choose the role and/or section(s) to assign to users without values specified in the uploaded file.');
+                   .&mt('Choose the role and/or section(s) to assign to users without values specified in the uploaded file.');
+        }
     } else {
         $Str .= &Apache::lonhtmlcommon::row_title(
                     &mt('Default role and/or section(s)'))
@@ -915,7 +966,8 @@ sub print_upload_manager_footer {
     }
     if (($context eq 'domain') || ($context eq 'author')) {
         $Str .= '<br />';
-        my ($options,$cb_script,$coursepick) = &default_role_selector($context,1);
+        my ($options,$cb_script,$coursepick) = 
+            &default_role_selector($context,1,'',$showcredits);
         if ($context eq 'domain') {
             $Str .= '<p>'
                    .'<b>'.&mt('Domain Level').'</b><br />'
@@ -932,8 +984,13 @@ sub print_upload_manager_footer {
     } else {
         my ($cnum,$cdom) = &get_course_identity();
         my $rowtitle = &mt('section');
-        my $secbox = &section_picker($cdom,$cnum,'Any',$rowtitle,
-                                     $permission,$context,'upload',$crstype);
+        my $defaultcredits;
+        if ($showcredits) {
+            $defaultcredits = &get_defaultcredits();
+        }
+        my $secbox = &section_picker($cdom,$cnum,'Any',$rowtitle,$permission,
+                                     $context,'upload',$crstype,$showcredits,
+                                     $defaultcredits);
         $Str .= $secbox
                .&Apache::lonhtmlcommon::row_closure();
         my %lt;
@@ -956,7 +1013,9 @@ sub print_upload_manager_footer {
                .&Apache::lonhtmlcommon::row_closure();
     }
     if ($context eq 'course' || $context eq 'domain') {
-        $Str .= &forceid_change($context);
+        $Str .= &Apache::lonhtmlcommon::row_title(&mt('Student/Employee ID'))
+               .&forceid_change($context)
+               .&Apache::lonhtmlcommon::row_closure(1); # last row in pick_box
     }
 
     $Str .= &Apache::lonhtmlcommon::end_pick_box();
@@ -979,28 +1038,64 @@ sub print_upload_manager_footer {
     return;
 }
 
+sub get_defaultcredits {
+    my ($cdom,$cnum) = @_;
+     
+    if ($cdom eq '' || $cnum eq '') {
+        return unless ($env{'request.course.id'});
+        $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
+        $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
+    }
+    return unless(($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)); 
+    my ($defaultcredits,$domdefcredits);
+    my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
+    if ($domdefaults{'officialcredits'} || $domdefaults{'unofficialcredits'} || $domdefaults{'textbookcredits'}) {
+        my $instcode = $env{'course.'.$cdom.'_'.$cnum.'.internal.coursecode'};
+        if ($instcode) {
+            $domdefcredits = $domdefaults{'officialcredits'};
+        } elsif ($env{'course.'.$cdom.'_'.$cnum.'.internal.textbook'}) {
+            $domdefcredits = $domdefaults{'textbookcredits'};
+        } else {
+            $domdefcredits = $domdefaults{'unofficialcredits'};
+        }
+    } else {
+        return;
+    }
+
+    if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
+        $defaultcredits = $env{'course.'.$cdom.'_'.$cnum.'.internal.defaultcredits'};
+    } elsif (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.defaultcredits'})) {
+        $defaultcredits = $env{'course.'.$cdom.'_'.$cnum.'.internal.defaultcredits'};
+    } else {
+        my %crsinfo =
+            &Apache::lonnet::coursedescription("$cdom/$cnum",{'one_time' => 1});
+        $defaultcredits = $crsinfo{'internal.defaultcredits'};
+    }
+    if ($defaultcredits eq '') {
+        $defaultcredits = $domdefcredits;
+    }
+    return $defaultcredits;
+}
+
 sub forceid_change {
     my ($context) = @_;
     my $output = 
-        &Apache::lonhtmlcommon::row_title(&mt('Student/Employee ID'))
-       .'<label><input type="checkbox" name="forceid" value="yes" />'
-       .&mt('Disable Student/Employee ID Safeguard and force change of conflicting IDs')
-       .'</label><br />'."\n"
-       .&mt('(only do if you know what you are doing.)')."\n";
+        '<label><input type="checkbox" name="forceid" value="yes" />'
+       .&mt('Force change of existing ID')
+       .'</label>'.&Apache::loncommon::help_open_topic('ForceIDChange')."\n";
     if ($context eq 'domain') {
-        $output .= '<br /><label><input type="checkbox" name="recurseid"'.
-                   ' value="yes" />'. 
-  &mt('Update student/employee ID in courses in which user is active/future student,[_1](if forcing change).','<br />').
-                   '</label>'."\n";
+        $output .= 
+            '<br />'
+           .'<label><input type="checkbox" name="recurseid" value="yes" />'
+           .&mt("Update ID in user's course(s).").'</label>'."\n";
     }
-    $output .= &Apache::lonhtmlcommon::row_closure(1); # last row in pick_box
     return $output;
 }
 
 ###############################################################
 ###############################################################
 sub print_upload_manager_form {
-    my ($r,$context,$permission,$crstype) = @_;
+    my ($r,$context,$permission,$crstype,$showcredits) = @_;
     my $firstLine;
     my $datatoken;
     if (!$env{'form.datatoken'}) {
@@ -1033,7 +1128,9 @@ sub print_upload_manager_form {
                                'domain_choice' => 'scalar',
                                'inststatus_choice' => 'scalar',
                              };
-    my $defdom = $env{'request.role.domain'};
+    if ($showcredits) {
+        $col_setting_names->{'credits_choice'} = 'scalar';
+    }
     if ($context eq 'course') {
         &Apache::loncommon::restore_course_settings('enrollment_upload',
                                                     $col_setting_names);
@@ -1041,6 +1138,7 @@ sub print_upload_manager_form {
         &Apache::loncommon::restore_settings($context,'user_upload',
                                              $col_setting_names);
     }
+    my $defdom = $env{'request.role.domain'};
     #
     # Determine kerberos parameters as appropriate
     my ($krbdef,$krbdefdom) =
@@ -1066,6 +1164,10 @@ sub print_upload_manager_form {
              ['role',&mt('Role'),             $env{'form.role_choice'}],
              ['domain',&mt('Domain'),         $env{'form.domain_choice'}],
              ['inststatus',&mt('Affiliation'), $env{'form.inststatus_choice'}]);
+        if ($showcredits) {     
+            push(@field,
+                 ['credits',&mt('Student Credits'), $env{'form.credits_choice'}]);
+        }
         if ($env{'form.upfile_associate'} eq 'reverse') {
             &Apache::loncommon::csv_print_samples($r,\@records);
             $i=&Apache::loncommon::csv_print_select_table($r,\@records,
@@ -1082,9 +1184,8 @@ sub print_upload_manager_form {
             $keyfields=join(',',sort(keys(%sone)));
         }
     }
-    $r->print('</div>');
     &print_upload_manager_footer($r,$i,$keyfields,$defdom,$today,$halfyear,
-                                 $context,$permission,$crstype);
+                                 $context,$permission,$crstype,$showcredits);
 }
 
 sub setup_date_selectors {
@@ -1241,7 +1342,7 @@ sub make_dates_default {
 }
 
 sub default_role_selector {
-    my ($context,$checkpriv,$crstype) = @_;
+    my ($context,$checkpriv,$crstype,$showcredits) = @_;
     my %customroles;
     my ($options,$coursepick,$cb_jscript);
     if ($context ne 'author') {
@@ -1253,6 +1354,7 @@ sub default_role_selector {
                     'grs'  => "Section",
                     'exs'  => "Existing sections",
                     'new'  => "New section",
+                    'crd'  => "Credits",
                   );
     $options = '<select name="defaultrole">'."\n".
                ' <option value="">'.&mt('Please select').'</option>'."\n"; 
@@ -1272,12 +1374,18 @@ sub default_role_selector {
         }
         my $courseform = &Apache::loncommon::selectcourse_link
             ('studentform','dccourse','dcdomain','coursedesc',"$env{'request.role.domain'}",undef,'Course/Community');
+        my ($credit_elem,$creditsinput);
+        if ($showcredits) {
+            $credit_elem = 'credits';
+            $creditsinput = '<td><input type="text" name="credits" value="" /></td>';
+        }
         $cb_jscript = 
-            &Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'},'currsec','studentform','courserole','Course/Community');
+            &Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'},'currsec','studentform','courserole','Course/Community',$credit_elem);
         $coursepick = &Apache::loncommon::start_data_table().
                       &Apache::loncommon::start_data_table_header_row().
                       '<th>'.$courseform.'</th><th>'.$lt{'rol'}.'</th>'.
                       '<th>'.$lt{'grs'}.'</th>'.
+                      '<th>'.$lt{'crd'}.'</th>'.
                       &Apache::loncommon::end_data_table_header_row().
                       &Apache::loncommon::start_data_table_row()."\n".
                       '<td><input type="text" name="coursedesc" value="" onfocus="this.blur();opencrsbrowser('."'studentform','dccourse','dcdomain','coursedesc','','','','crstype'".')" /></td>'."\n".
@@ -1285,9 +1393,9 @@ sub default_role_selector {
                       &default_course_roles($context,$checkpriv,'Course',%customroles)."\n".
                       '</select></td><td>'.
                       '<table class="LC_createuser">'.
-                      '<tr class="LC_section_row"><td valign"top">'.
+                      '<tr class="LC_section_row"><td valign="top">'.
                       $lt{'exs'}.'<br /><select name="currsec">'.
-                      ' <option value=""><--'.&mt('Pick course first').
+                      ' <option value="">&lt;--'.&mt('Pick course first').
                       '</select></td>'.
                       '<td>&nbsp;&nbsp;</td>'.
                       '<td valign="top">'.$lt{'new'}.'<br />'.
@@ -1299,7 +1407,7 @@ sub default_role_selector {
                       '<input type="hidden" name="dccourse" value="" />'.
                       '<input type="hidden" name="dcdomain" value="" />'.
                       '<input type="hidden" name="crstype" value="" />'.
-                      '</td></tr></table></td>'.
+                      '</td></tr></table></td>'.$creditsinput.
                       &Apache::loncommon::end_data_table_row().
                       &Apache::loncommon::end_data_table()."\n";
     }
@@ -1436,7 +1544,7 @@ sub my_custom_roles {
 
 sub print_userlist {
     my ($r,$mode,$permission,$context,$formname,$totcodes,$codetitles,
-        $idlist,$idlist_titles) = @_;
+        $idlist,$idlist_titles,$showcredits) = @_;
     my $format = $env{'form.output'};
     if (! exists($env{'form.sortby'})) {
         $env{'form.sortby'} = 'username';
@@ -1471,10 +1579,6 @@ sub print_userlist {
         @statuses = ('future');
     }
 
-#    if ($context eq 'course') { 
-#        $r->print(&display_adv_courseroles());
-#    }
-    #
     # Interface output
     $r->print('<form name="studentform" method="post" action="/adm/createuser">'."\n".
               '<input type="hidden" name="action" value="'.
@@ -1512,27 +1616,29 @@ sub print_userlist {
         $r->print(&section_group_filter($cnum,$cdom));
     }
     $r->print('</div><div class="LC_left_float">'.
-              &column_checkboxes($context,$mode,$formname).
-              '</div><br clear="all" />');
+              &column_checkboxes($context,$mode,$formname,$showcredits).
+              '</div>');
     if ($env{'form.phase'} eq '') {
-        $r->print(&list_submit_button(&mt('Display List of Users'))."\n".
+        $r->print('<br clear="all" />'.
+                  &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(&list_submit_button(&mt('Update Display'))."\n");
+        $r->print('<br clear="all" />'.
+                  &list_submit_button(&mt('Update Display'))."\n");
     }
 
-    my @cols = &infocolumns($context,$mode);  
+    my @cols = &infocolumns($context,$mode,$showcredits);  
     if (!@cols) {
-         $r->print('<hr /><span class="LC_warning">'.
+         $r->print('<hr style="clear:both;" /><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);
+    my (%userlist,%userinfo,$clearcoursepick,$needauthorquota,$needauthorusage);
     if (($context eq 'domain') && 
         ($env{'form.roletype'} eq 'course') || 
         ($env{'form.roletype'} eq 'community')) {
@@ -1553,12 +1659,10 @@ sub print_userlist {
             &Apache::lonhtmlcommon::course_selection($formname,$numcodes,
                             $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".
+        $r->print('<div class="LC_left_float">'.
+                  '<fieldset><legend>'.$title.'</legend>'."\n".
                   $courseform."\n".
-                  &Apache::lonhtmlcommon::row_closure(1).
-                  &Apache::lonhtmlcommon::end_pick_box().'</p>'.
+                  '</fieldset></div><br clear="all" />'.
                   '<p><input type="hidden" name="origroletype" value="'.$env{'form.roletype'}.'" />'.
                   &list_submit_button(&mt('Update Display')).
                   "\n".'</p><span class="LC_warning">'.$warning.'</span>'."\n");
@@ -1568,10 +1672,10 @@ sub print_userlist {
             $clearcoursepick = 1;
         }
         if (($env{'form.coursepick'}) && (!$clearcoursepick)) {
-            $r->print('<hr />'.&mt('Searching').' ...<br />&nbsp;<br />');
+            $r->print('<hr />'.&mt('Searching ...').'<br />&nbsp;<br />');
         }
     } else {
-        $r->print('<hr /><div id="searching">'.&mt('Searching').' ...</div>');
+        $r->print('<hr style="clear:both;" /><div id="searching">'.&mt('Searching ...').'</div>');
     }
     $r->rflush();
     if ($context eq 'course') {
@@ -1606,6 +1710,12 @@ sub print_userlist {
                              \%cstr_roles,$permission);
         } elsif ($context eq 'domain') {
             if ($env{'form.roletype'} eq 'domain') {
+                if (grep(/^authorusage$/,@cols)) {
+                    $needauthorusage = 1;
+                }
+                if (grep(/^authorquota$/,@cols)) {
+                    $needauthorquota = 1;
+                }
                 %dom_roles = &Apache::lonnet::get_domain_roles($env{'request.role.domain'});
                 foreach my $key (keys(%dom_roles)) {
                     if (ref($dom_roles{$key}) eq 'HASH') {
@@ -1707,16 +1817,18 @@ sub print_userlist {
         } elsif ($context eq 'course') {
             $r->print(&mt('There are no course users to display.')."\n");
         }
-        $r->print('<p class="LC_info"'.$msg.'</p>'."\n") if $msg;
+        $r->print('<p class="LC_info">'.$msg.'</p>'."\n") if $msg;
     } else {
         # Print out the available choices
         my $usercount;
         if ($env{'form.action'} eq 'modifystudent') {
             ($usercount) = &show_users_list($r,$context,'view',$permission,
-                                 $env{'form.Status'},\%userlist,$keylist);
+                                 $env{'form.Status'},\%userlist,$keylist,'',
+                                 $showcredits);
         } else {
             ($usercount) = &show_users_list($r,$context,$env{'form.output'},
-                               $permission,$env{'form.Status'},\%userlist,$keylist);
+                               $permission,$env{'form.Status'},\%userlist,
+                               $keylist,'',$showcredits,$needauthorquota,$needauthorusage);
         }
         if (!$usercount) {
             $r->print('<br /><span class="LC_info">'
@@ -1837,12 +1949,12 @@ sub section_group_filter {
 }
 
 sub infocolumns {
-    my ($context,$mode) = @_;
+    my ($context,$mode,$showcredits) = @_;
     my @cols;
     if (($mode eq 'pickauthor') || ($mode eq 'autoenroll')) {
-        @cols = &get_cols_array($context,$mode);
+        @cols = &get_cols_array($context,$mode,$showcredits);
     } else {
-        my @posscols = &get_cols_array($context,$mode);
+        my @posscols = &get_cols_array($context,$mode,$showcredits);
         if ($env{'form.phase'} ne '') {
             my @checkedcols = &Apache::loncommon::get_env_multiple('form.showcol');
             foreach my $col (@checkedcols) {
@@ -1858,7 +1970,7 @@ sub infocolumns {
 }
 
 sub get_cols_array {
-    my ($context,$mode) = @_;
+    my ($context,$mode,$showcredits) = @_;
     my @cols;
     if ($mode eq 'pickauthor') {
         @cols = ('username','fullname','status','email');
@@ -1868,9 +1980,6 @@ sub get_cols_array {
             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');
         }
@@ -1879,19 +1988,25 @@ sub get_cols_array {
         }
         push(@cols,'email');
         if (($context eq 'course') && ($mode ne 'autoenroll')) {
+            if ($showcredits) {
+                push(@cols,'credits');
+            }
             push(@cols,'lastlogin','clicker');
         }
         if (($context eq 'course') && ($mode ne 'autoenroll') &&
             ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'})) {
-            push(@cols,'photos');
+            push(@cols,'photo');
+        }
+        if ($context eq 'domain') {
+            push (@cols,('authorusage','authorquota','extent'));
         }
     }
     return @cols;
 }
 
 sub column_checkboxes {
-    my ($context,$mode,$formname) = @_;
-    my @cols = &get_cols_array($context,$mode);
+    my ($context,$mode,$formname,$showcredits) = @_;
+    my @cols = &get_cols_array($context,$mode,$showcredits);
     my @showncols = &Apache::loncommon::get_env_multiple('form.showcol');
     my (%disabledchk,%unchecked);
     if ($env{'form.phase'} eq '') {
@@ -1899,20 +2014,35 @@ sub column_checkboxes {
         if ($context eq 'course') {
             $disabledchk{'role'} = 1;
             $unchecked{'photo'} = 1;
+            $unchecked{'clicker'} = 1;
+            if ($showcredits) {
+                $unchecked{'credits'} = 1;
+            }
+        } elsif ($context eq 'domain') { 
+            $unchecked{'extent'} = 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; 
+        if (($env{'form.showrole'} ne 'Any') && ($env{'form.showrole'} ne 'cr')) {
+            $disabledchk{'role'} = 1;
+        }
+        if ($context eq 'domain') {
+            if (($env{'form.roletype'} eq 'course') || 
+                ($env{'form.roletype'} eq 'community')) {
+                $disabledchk{'status'} = 1;
+                $disabledchk{'authorusage'} = 1;
+                $disabledchk{'authorquota'} = 1;
+            } elsif ($env{'form.roletype'} eq 'domain') {
+                $disabledchk{'extent'} = 1; 
+            }
         }
     }
     my $numposs = scalar(@cols);
-    my $numinrow = 8;
+    my $numinrow = 7;
     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').'" />'.
@@ -1952,9 +2082,20 @@ sub column_checkboxes {
         } else {
             $output .= '<td>';
         }
-        $output .= '<label><input id="showcol'.$cols[$i].'" type="checkbox" name="showcol" value="'.$cols[$i].'"'.$checked.' />'.
-                   $lt{$cols[$i]}.'</label></td>';
-
+        my $style;
+        if ($cols[$i] eq 'extent') {
+            if (($env{'form.roletype'} eq 'domain') || ($env{'form.roletype'} eq '')) {
+                $style = ' style="display: none;"';
+            } 
+        } elsif (($cols[$i] eq 'authorusage') || ($cols[$i] eq 'authorquota')) {
+            if ($env{'form.roletype'} ne 'domain') {
+                $style = ' style="display: none;"';
+            }
+        }
+        $output .= '<span id="show'.$cols[$i].'"'.$style.'><label>'.
+                   '<input id="showcol'.$cols[$i].'" type="checkbox" name="showcol" value="'.$cols[$i].'"'.$checked.' /><span id="showcoltext'.$cols[$i].'">'.
+                   $lt{$cols[$i]}.'</span>'.
+                   '</label></span></td>';
     }
     $output .= '</tr></table></fieldset>';
     return $output;
@@ -1978,21 +2119,25 @@ sub get_column_names {
         'end'        => "end date",
         'status'     => "status",
         'role'       => "role",
+        'credits'    => "credits",
         'type'       => "enroll type/action",
         'email'      => "e-mail address",
         'photo'      => "photo",
         'lastlogin'  => "last login",
         'extent'     => "extent",
+        'authorusage' => "disk usage (%)",
+        'authorquota' => "disk quota (MB)",
         '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');
+        $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');
+        $lt{'extent'} = &mt('community(s): description, section(s), status');
+    } elsif (($context eq 'author') || 
+             ($context eq 'domain' && $env{'form.roletype'} eq 'author')) {
+        $lt{'extent'} = &mt('author');
     }
     return %lt;
 }
@@ -2246,29 +2391,6 @@ sub instcode_from_coursefilter {
     return $instcode;
 }
 
-sub display_adv_courseroles {
-    my $output;
-    #
-    # List course personnel
-    my %coursepersonnel = 
-       &Apache::lonnet::get_course_adv_roles($env{'request.course.id'});
-    #
-    $output = '<br />'.&Apache::loncommon::start_data_table();
-    foreach my $role (sort(keys(%coursepersonnel))) {
-        next if ($role =~ /^\s*$/);
-        $output .= &Apache::loncommon::start_data_table_row().
-                  '<td>'.$role.'</td><td>';
-        foreach my $user (split(',',$coursepersonnel{$role})) {
-            my ($puname,$pudom)=split(':',$user);
-            $output .= ' '.&Apache::loncommon::aboutmewrapper(
-                       &Apache::loncommon::plainname($puname,$pudom),
-                       $puname,$pudom);
-        }
-        $output .= '</td>'.&Apache::loncommon::end_data_table_row();
-    }
-    $output .= &Apache::loncommon::end_data_table();
-}
-
 sub make_keylist_array {
     my ($index,$keylist);
     $index->{'domain'} = &Apache::loncoursedata::CL_SDOM();
@@ -2287,6 +2409,9 @@ sub make_keylist_array {
     $index->{'extent'} = &Apache::loncoursedata::CL_EXTENT();
     $index->{'photo'} = &Apache::loncoursedata::CL_PHOTO();
     $index->{'thumbnail'} = &Apache::loncoursedata::CL_THUMBNAIL();
+    $index->{'credits'} = &Apache::loncoursedata::CL_CREDITS();
+    $index->{'authorquota'} = &Apache::loncoursedata::CL_AUTHORQUOTA();
+    $index->{'authorusage'} = &Apache::loncoursedata::CL_AUTHORUSAGE();
     foreach my $key (keys(%{$index})) {
         $keylist->[$index->{$key}] = $key;
     }
@@ -2335,10 +2460,12 @@ sub process_date_info {
 }
 
 sub show_users_list {
-    my ($r,$context,$mode,$permission,$statusmode,$userlist,$keylist,$formname)=@_;
+    my ($r,$context,$mode,$permission,$statusmode,$userlist,$keylist,$formname,
+        $showcredits,$needauthorquota,$needauthorusage)=@_;
     if ($formname eq '') {
         $formname = 'studentform';
     }
+    my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
     #
     # Variables for excel output
     my ($excel_workbook, $excel_sheet, $excel_filename,$row,$format);
@@ -2350,21 +2477,31 @@ sub show_users_list {
     my @sortable = ('username','domain','id','fullname','start','end','email','role');
     if ($context eq 'course') {
         push(@sortable,('section','groups','type'));
+        if ($showcredits) {
+            push(@sortable,'credits');
+        }
     } else {
         push(@sortable,'extent');
+        if (($context eq 'domain') && ($env{'form.roletype'} eq 'domain') &&
+            (($env{'form.showrole'} eq 'Any') || ($env{'form.showrole'} eq 'au'))) {
+            push(@sortable,('authorusage','authorquota'));
+        }
     }
     if ($mode eq 'pickauthor') {
         @sortable = ('username','fullname','email','status');
     }
-    if (!grep(/^\Q$sortby\E$/,@sortable)) {
+    my %is_sortable;
+    map { $is_sortable{$_} = 1; } @sortable;
+    unless ($is_sortable{$sortby}) {
         $sortby = 'username';
     }
     my $setting = $env{'form.roletype'};
-    my ($cid,$cdom,$cnum,$classgroups,$crstype);
+    my ($cid,$cdom,$cnum,$classgroups,$crstype,$defaultcredits);
     if ($context eq 'course') {
         $cid = $env{'request.course.id'};
         $crstype = &Apache::loncommon::course_type();
         ($cnum,$cdom) = &get_course_identity($cid);
+        $defaultcredits = $env{'course.'.$cid.'.internal.defaultcredits'};
         ($classgroups) = &Apache::loncoursedata::get_group_memberships(
                                      $userlist,$keylist,$cdom,$cnum);
         if ($mode eq 'autoenroll') {
@@ -2457,7 +2594,7 @@ END
     $r->print(<<END);
 <input type="hidden" name="sortby" value="$sortby" />
 END
-    my @cols = &infocolumns($context,$mode);
+    my @cols = &infocolumns($context,$mode,$showcredits);
     my %coltxt = &get_column_names($context);
     my %acttxt = &Apache::lonlocal::texthash(
                        'pr'         => "Proceed",
@@ -2579,7 +2716,11 @@ 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"><label>'
+               .'<input type="checkbox" name="userwin" value="1"'.$checkwin.' />'.$lt{'owin'}
+               .'</label></span></td></tr></table></fieldset></div>';
         }
         $output .= "\n".'<br clear="all" />'."\n".
                   &Apache::loncommon::start_data_table().
@@ -2591,11 +2732,17 @@ END
         } else {
             $output .= "\n".'<th>&nbsp;</th>'."\n";
             if ($actionselect) {
-                $output .= '<th>'.&mt('Select').'</th>'."\n";
+                $output .= '<th class="LC_nobreak" valign="top">'.&mt('Select').'</th>'."\n";
             }
         }
         foreach my $item (@cols) {
-            $output .= "<th><a href=\"javascript:document.$formname.sortby.value='$item';document.$formname.submit();\">$lt{$item}</a></th>\n";
+            $output .= '<th class="LC_nobreak" valign="top">';
+            if ($is_sortable{$item}) {
+                $output .= "<a href=\"javascript:document.$formname.sortby.value='$item';document.$formname.submit();\" style=\"text-decoration:none;\">$lt{$item}<span class=\"LC_fontsize_small\"> &#9660;</span></a>";
+            } else {
+                $output .= $lt{$item};
+            }
+            $output .= "</th>\n";
         }
         my %role_types = &role_type_names();
         $output .= &Apache::loncommon::end_data_table_header_row();
@@ -2755,12 +2902,37 @@ END
                                                                 'gif','thumbnail');
                     }
                 }
+                if (($role eq 'st') && ($defaultcredits)) {
+                    if ($userlist->{$user}->[$index{'credits'}] eq '') {
+                        $userlist->{$user}->[$index{'credits'}] = $defaultcredits;
+                    }
+                }
             }
         }
         my %emails   = &Apache::loncommon::getemails($uname,$udom);
         if ($emails{'permanentemail'} =~ /\S/) {
             $userlist->{$user}->[$index{'email'}] = $emails{'permanentemail'};
         }
+        if (($context eq 'domain') && ($env{'form.roletype'} eq 'domain') && 
+            ($role eq 'au')) {
+            my ($disk_quota,$current_disk_usage,$percent); 
+            if (($needauthorusage) || ($needauthorquota)) {
+                $disk_quota = &Apache::loncommon::get_user_quota($uname,$udom,'author');
+            }
+            if ($needauthorusage) {
+                $current_disk_usage =
+                    &Apache::lonnet::diskusage($udom,$uname,"$londocroot/priv/$udom/$uname");
+                if ($disk_quota == 0) {
+                    $percent = 100.0;
+                } else {
+                    $percent = $current_disk_usage/(10 * $disk_quota);
+                }
+                $userlist->{$user}->[$index{'authorusage'}] = sprintf("%.0f",$percent);
+            }
+            if ($needauthorquota) {
+                $userlist->{$user}->[$index{'authorquota'}] = sprintf("%.2f",$disk_quota);
+            }
+        }
         $usercount ++;
     }
     my $autocount = 0;
@@ -2781,12 +2953,20 @@ END
     my $index  = $index{$sortby};
     my $second = $index{'username'};
     my $third  = $index{'domain'};
-    my @sorted_users = sort {
-        lc($userlist->{$a}->[$index])  cmp lc($userlist->{$b}->[$index])
-            ||
-        lc($userlist->{$a}->[$second]) cmp lc($userlist->{$b}->[$second])            ||
-        lc($userlist->{$a}->[$third]) cmp lc($userlist->{$b}->[$third])
-        } (keys(%$userlist));
+    my @sorted_users;
+    if (($sortby eq 'authorquota') || ($sortby eq 'authorusage')) {  
+        @sorted_users = sort {
+            $userlist->{$b}->[$index] <=> $userlist->{$a}->[$index]           ||
+            lc($userlist->{$a}->[$second]) cmp lc($userlist->{$b}->[$second]) ||
+            lc($userlist->{$a}->[$third]) cmp lc($userlist->{$b}->[$third])
+            } (keys(%$userlist));
+    } else {
+        @sorted_users = sort {
+            lc($userlist->{$a}->[$index]) cmp lc($userlist->{$b}->[$index])   ||
+            lc($userlist->{$a}->[$second]) cmp lc($userlist->{$b}->[$second]) ||
+            lc($userlist->{$a}->[$third]) cmp lc($userlist->{$b}->[$third])
+            } (keys(%$userlist));
+    }
     my $rowcount = 0;
     foreach my $user (@sorted_users) {
         my %in;
@@ -2797,7 +2977,7 @@ END
         }
         my $clickers = (&Apache::lonnet::userenvironment($in{'domain'},$in{'username'},'clickers'))[1];
         if ($clickers!~/\w/) { $clickers='-'; }
-        $in{'clicker'} = $clickers; 
+        $in{'clicker'} = $clickers;
 	my $role = $in{'role'};
         $in{'role'}=&Apache::lonnet::plaintext($sdata->[$index{'role'}],$crstype);
         unless ($mode eq 'excel') {
@@ -2824,10 +3004,10 @@ END
             if ($mode eq 'autoenroll') {
                 my $cellentry;
                 if ($in{'type'} eq 'auto') {
-                    $cellentry = '<b>'.&mt('auto').'</b>&nbsp;<label><input type="checkbox" name="chgauto" value="'.$in{'username'}.':'.$in{'domain'}.'" />&nbsp;Change</label>';
+                    $cellentry = '<b>'.&mt('auto').'</b>&nbsp;<label><input type="checkbox" name="chgauto" value="'.$in{'username'}.':'.$in{'domain'}.'" />&nbsp;'.&mt('Change').'</label>';
                     $autocount ++;
                 } else {
-                    $cellentry = '<table border="0" cellspacing="0"><tr><td rowspan="2"><b>'.&mt('manual').'</b></td><td><span class="LC_nobreak"><label><input type="checkbox" name="chgmanual" value="'.$in{'username'}.':'.$in{'domain'}.'" />&nbsp;Change</label></span></td></tr><tr><td><span class="LC_nobreak">';
+                    $cellentry = '<table border="0" cellspacing="0"><tr><td rowspan="2"><b>'.&mt('manual').'</b></td><td><span class="LC_nobreak"><label><input type="checkbox" name="chgmanual" value="'.$in{'username'}.':'.$in{'domain'}.'" />&nbsp;'.&mt('Change').'</label></span></td></tr><tr><td><span class="LC_nobreak">';
                     $manualcount ++;
                     if ($in{'lockedtype'}) {
                         $cellentry .= '<label><input type="checkbox" name="unlockchg" value="'.$in{'username'}.':'.$in{'domain'}.'" />&nbsp;'.&mt('Unlock').'</label>';
@@ -2872,7 +3052,8 @@ END
                                 $checkval .= ':'.$in{'section'};
                                 if ($role eq 'st') {
                                     $checkval .= ':'.$in{'type'}.':'.
-                                                 $in{'lockedtype'};
+                                                 $in{'lockedtype'}.':'.
+                                                 $in{'credits'};
                                 }
                              }
                         }
@@ -2919,7 +3100,9 @@ END
                         } else {
                              $r->print('<td>&nbsp;</td>'."\n");
                         } 
-                    } 
+                    }
+                } elsif (($item eq 'authorquota') || ($item eq 'authorusage')) {
+                    $r->print('<td align="right">'.$in{$item}.'</td>'."\n");
                 } else {
                     $r->print('<td>'.$in{$item}.'</td>'."\n");
                 }
@@ -2955,10 +3138,10 @@ END
             $r->print(&Apache::loncommon::end_data_table().'<br />');
     } elsif ($mode eq 'excel') {
         $excel_workbook->close();
-	$r->print(&mt('[_1]Your Excel spreadsheet[_2] is ready for download.', '<p><a href="'.$excel_filename.'">','</a>')."</p>\n");
+	$r->print('<p>'.&mt('[_1]Your Excel spreadsheet[_2] is ready for download.', '<a href="'.$excel_filename.'">','</a>')."</p>\n");
     } elsif ($mode eq 'csv') {
         close($CSVfile);
-	$r->print(&mt('[_1]Your CSV file[_2] is ready for download.', '<p><a href="'.$CSVfilename.'">','</a>')."</p>\n");
+	$r->print('<p>'.&mt('[_1]Your CSV file[_2] is ready for download.', '<a href="'.$CSVfilename.'">','</a>')."</p>\n");
         $r->rflush();
     }
     if ($mode eq 'autoenroll') {
@@ -3120,6 +3303,7 @@ sub select_actions {
                 chgdates  => "Change starting/ending dates",
                 chgsec   => "Change section associated with user roles",
     );
+    # FIXME Add an option to change credits for student roles.
     my ($output,$options,%choices);
     # FIXME Disable actions for now for roletype=course in domain context
     if ($context eq 'domain' && $setting eq 'course') {
@@ -3247,11 +3431,13 @@ ENDTWO
 }
 
 sub date_section_selector {
-    my ($context,$permission,$crstype) = @_;
+    my ($context,$permission,$crstype,$showcredits) = @_;
     my $callingform = $env{'form.callingform'};
     my $formname = 'dateselect';  
     my $groupslist = &get_groupslist();
-    my $sec_js = &setsections_javascript($formname,$groupslist);
+    my $sec_js =
+        &setsections_javascript($formname,$groupslist,undef,undef,$crstype,
+                                $showcredits);
     my $output = <<"END";
 <script type="text/javascript">
 // <![CDATA[
@@ -3383,7 +3569,8 @@ ENDJS
             $info = '<input type="hidden" name="retainsec" value="0" />'; 
         }
         my $rowtitle = &mt('New section to assign');
-        my $secbox = &section_picker($cdom,$cnum,$env{'form.showrole'},$rowtitle,$permission,$context,'',$crstype);
+        my $secbox = &section_picker($cdom,$cnum,$env{'form.showrole'},$rowtitle,
+                                     $permission,$context,'chgsec',$crstype);
         $output .= $info.$secbox;
     }
     $output .= '<p>'.
@@ -3393,13 +3580,14 @@ ENDJS
 }
 
 sub section_picker {
-    my ($cdom,$cnum,$role,$rowtitle,$permission,$context,$mode,$crstype) = @_;
+    my ($cdom,$cnum,$role,$rowtitle,$permission,$context,$mode,$crstype,
+        $showcredits,$credits) = @_;
     my %sections_count = &Apache::loncommon::get_sections($cdom,$cnum);
     my $sections_select .= &course_sections(\%sections_count,$role);
     my $secbox = '<div>'.&Apache::lonhtmlcommon::start_pick_box()."\n";
     if ($mode eq 'upload') {
         my ($options,$cb_script,$coursepick) =
-            &default_role_selector($context,1,$crstype);
+            &default_role_selector($context,1,$crstype,$showcredits);
         $secbox .= &Apache::lonhtmlcommon::row_title(&mt('role'),'LC_oddrow_value').
                    $options. &Apache::lonhtmlcommon::row_closure(1)."\n";
     }
@@ -3413,12 +3601,21 @@ sub section_picker {
                    '<input type="hidden" name="sections" value="" />'."\n".
                    '</td></tr></table>'."\n";
     } else {
-       $secbox .= '<input type="hidden" name="sections" value="'.
+        $secbox .= '<input type="hidden" name="sections" value="'.
                    $env{'request.course.sec'}.'" />'.
                    $env{'request.course.sec'};
     }
-    $secbox .= &Apache::lonhtmlcommon::row_closure(1)."\n".
-               &Apache::lonhtmlcommon::end_pick_box().'</div>';
+    $secbox .= &Apache::lonhtmlcommon::row_closure(1)."\n";
+    unless ($mode eq 'chgsec') {
+        if ($showcredits) {
+            $secbox .= 
+                &Apache::lonhtmlcommon::row_title(&mt('credits (students)'),
+                                                  'LC_evenrow_value')."\n".
+                '<input type="text" name="credits" size="3" value="'.$credits.'" />'."\n".
+                &Apache::lonhtmlcommon::row_closure(1)."\n";
+        }
+    }
+    $secbox .= &Apache::lonhtmlcommon::end_pick_box().'</div>';
     return $secbox;
 }
 
@@ -3642,7 +3839,6 @@ sub show_drop_list {
 $check_uncheck_js
 // ]]>
 </script>
-<p>
 <input type="hidden" name="phase" value="four" />
 END
     my ($indexhash,$keylist) = &make_keylist_array();
@@ -3679,6 +3875,7 @@ END
                                               $classlist,$keylist,$cdom,$cnum);
     my %lt=&Apache::lonlocal::texthash('usrn'   => "username",
                                        'dom'    => "domain",
+                                       'id'     => "ID",
                                        'sn'     => "student name",
                                        'mn'     => "member name",
                                        'sec'    => "section",
@@ -3697,7 +3894,7 @@ END
     <th>&nbsp;</th>
     <th>$lt{'usrn'}</th>
     <th>$lt{'dom'}</th>
-    <th>ID</th>
+    <th>$lt{'id'}</th>
     <th>$nametitle</th>
     <th>$lt{'sec'}</th>
     <th>$lt{'start'}</th>
@@ -3711,21 +3908,21 @@ END
         $r->print(<<END);
     <th>&nbsp;</th>
     <th>
-       <a href="/adm/createuser?action=$action&sortby=username">$lt{'usrn'}</a>
+       <a href="/adm/createuser?action=$action&amp;sortby=username">$lt{'usrn'}</a>
     </th><th>
-       <a href="/adm/createuser?action=$action&sortby=domain">$lt{'dom'}</a>
+       <a href="/adm/createuser?action=$action&amp;sortby=domain">$lt{'dom'}</a>
     </th><th>
-       <a href="/adm/createuser?action=$action&sortby=id">ID</a>
+       <a href="/adm/createuser?action=$action&amp;sortby=id">$lt{'id'}</a>
     </th><th>
-       <a href="/adm/createuser?action=$action&sortby=fullname">$nametitle</a>
+       <a href="/adm/createuser?action=$action&amp;sortby=fullname">$nametitle</a>
     </th><th>
-       <a href="/adm/createuser?action=$action&sortby=section">$lt{'sec'}</a>
+       <a href="/adm/createuser?action=$action&amp;sortby=section">$lt{'sec'}</a>
     </th><th>
-       <a href="/adm/createuser?action=$action&sortby=start">$lt{'start'}</a>
+       <a href="/adm/createuser?action=$action&amp;sortby=start">$lt{'start'}</a>
     </th><th>
-       <a href="/adm/createuser?action=$action&sortby=end">$lt{'end'}</a>
+       <a href="/adm/createuser?action=$action&amp;sortby=end">$lt{'end'}</a>
     </th><th>
-       <a href="/adm/createuser?action=$action&sortby=groups">$lt{'groups'}</a>
+       <a href="/adm/createuser?action=$action&amp;sortby=groups">$lt{'groups'}</a>
     </th>
 END
         $r->print(&Apache::loncommon::end_data_table_header_row());
@@ -3796,7 +3993,6 @@ END
         $btn = $lt{'dm'}; 
     }
     $r->print(<<"END");
-</p>
 <p>
 <input type="button" value="$lt{'ca'}" onclick="javascript:checkAll(document.studentform.droplist)" /> &nbsp;
 <input type="button" value="$lt{'ua'}" onclick="javascript:uncheckAll(document.studentform.droplist)" />
@@ -3818,16 +4014,17 @@ sub print_first_users_upload_form {
     $str .= '<input type="hidden" name="action" value="upload" />';
     $str .= '<input type="hidden" name="state"  value="got_file" />';
 
+    $str .= &Apache::grades::checkforfile_js();
+
     $str .= '<h2>'.&mt('Upload a file containing information about users').'</h2>'."\n";
 
     # Excel and CSV Help
-    $str .= '<div class="LC_left_float">'
+    $str .= '<div class="LC_columnSection">'
            .&Apache::loncommon::help_open_topic("Course_Create_Class_List",
                 &mt("How do I create a users list from a spreadsheet"))
-           .'</div><div class="LC_left_float">'."\n"
-           .&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
+           .' '.&Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
                 &mt("How do I create a CSV file from a spreadsheet"))
-           .'</div><br clear="all" />'."\n";
+           ."</div>\n";
     $str .= &Apache::lonhtmlcommon::start_pick_box()
            .&Apache::lonhtmlcommon::row_title(&mt('File'));
     if (&Apache::lonlocal::current_language() ne 'en') {
@@ -3848,7 +4045,8 @@ sub print_first_users_upload_form {
            .&Apache::lonhtmlcommon::end_pick_box();
 
     $str .= '<p>'
-           .'<input type="submit" name="fileupload" value="'.&mt('Next').'" />'
+           .'<input type="submit" name="fileupload" value="'.&mt('Next').'"'
+           .' onclick="javascript:checkUpload(this.form);" />'
            .'</p>';
 
     $r->print($str);
@@ -3857,7 +4055,7 @@ sub print_first_users_upload_form {
 
 # ================================================= Drop/Add from uploaded file
 sub upfile_drop_add {
-    my ($r,$context,$permission) = @_;
+    my ($r,$context,$permission,$showcredits) = @_;
     &Apache::loncommon::load_tmp_file($r);
     my @userdata=&Apache::loncommon::upfile_record_sep();
     if($env{'form.noFirstLine'}){shift(@userdata);}
@@ -3878,25 +4076,17 @@ sub upfile_drop_add {
     }
     #
     # Store the field choices away
-    foreach my $field (qw/username names
-                       fname mname lname gen id sec ipwd email role domain/) {
+    my @storefields = qw/username names fname mname lname gen id 
+                         sec ipwd email role domain inststatus/;
+    if ($showcredits) {
+        push (@storefields,'credits');
+    }
+    my %fieldstype; 
+    foreach my $field (@storefields) {
         $env{'form.'.$field.'_choice'}=$fields{$field};
+        $fieldstype{$field.'_choice'} = 'scalar';
     }
-    &Apache::loncommon::store_course_settings('enrollment_upload',
-                                              { 'username_choice' => 'scalar',
-                                                'names_choice' => 'scalar',
-                                                'fname_choice' => 'scalar',
-                                                'mname_choice' => 'scalar',
-                                                'lname_choice' => 'scalar',
-                                                'gen_choice' => 'scalar',
-                                                'id_choice' => 'scalar',
-                                                'sec_choice' => 'scalar',
-                                                'ipwd_choice' => 'scalar',
-                                                'email_choice' => 'scalar',
-                                                'role_choice'  => 'scalar',
-                                                'domain_choice' => 'scalar',
-                                                'inststatus_choice' => 'scalar'});
-    #
+    &Apache::loncommon::store_course_settings('enrollment_upload',\%fieldstype);
     my ($cid,$crstype,$setting);
     if ($context eq 'domain') {
         $setting = $env{'form.roleaction'};
@@ -3964,19 +4154,30 @@ sub upfile_drop_add {
             $amode = ''; # This causes the loop below to be skipped
         }
     }
-    my ($defaultsec,$defaultrole);
+    my ($defaultsec,$defaultrole,$defaultcredits,$commoncredits);
     if ($context eq 'domain') {
         if ($setting eq 'domain') {
             $defaultrole = $env{'form.defaultrole'};
         } elsif ($setting eq 'course') {
             $defaultrole = $env{'form.courserole'};
             $defaultsec = $env{'form.sections'};
-        }  
+            if ($showcredits) {
+                $commoncredits = $env{'form.credits'};
+                if ($crstype ne 'Community') {
+                    my %coursehash=&Apache::lonnet::coursedescription($cid);
+                    $defaultcredits = $coursehash{'internal.defaultcredits'};
+                }
+            }
+        }
     } elsif ($context eq 'author') {
         $defaultrole = $env{'form.defaultrole'};
     } elsif ($context eq 'course') {
         $defaultrole = $env{'form.defaultrole'};
         $defaultsec = $env{'form.sections'};
+        if ($showcredits) {
+            $commoncredits = $env{'form.credits'};
+            $defaultcredits = $env{'course.'.$cid.'.internal.defaultcredits'};
+        }
     }
     # Check to see if user information can be changed
     my @userinfo = ('firstname','middlename','lastname','generation',
@@ -4121,18 +4322,23 @@ sub upfile_drop_add {
                     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).
-                              $nowhitespace);
+                    $r->print(
+                        '<br />'.
+                        &mt('Unacceptable username [_1] for user [_2] [_3] [_4] [_5]',
+                                '"<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'}}.
-                                  '</b>: '.&mt('Unacceptable domain for user [_2] [_3] [_4] [_5]',$fname,$mname,$lname,$gen));
-                        next;
+                        $r->print(
+                            '<br />'.
+                            &mt('Unacceptable domain [_1] for user [_2] [_3] [_4] [_5]',
+                                   '"<b>'.$entries{$fields{'domain'}}.'</b>"',
+                                    $fname,$mname,$lname,$gen));
+                    next;
                     }
                     my $username = $entries{$fields{'username'}};
                     my $userdomain = $entries{$fields{'domain'}};
@@ -4236,6 +4442,21 @@ sub upfile_drop_add {
                     foreach (\$id,\$fname,\$mname,\$lname,\$gen,\$inststatus) {
                         $$_ =~ s/(\s+$|^\s+)//g;
                     }
+                    my $credits;
+                    if ($showcredits) {
+                        if (($role eq 'st') && ($crstype ne 'Community')) {
+                            $credits = $entries{$fields{'credits'}};
+                            if ($credits ne '') {
+                                $credits =~ s/[^\d\.]//g;
+                            }
+                            if ($credits eq '') {
+                                $credits = $commoncredits;
+                            }
+                            if ($credits eq $defaultcredits) {
+                                undef($credits);
+                            }
+                        }
+                    }
                     # check against rules
                     my $checkid = 0;
                     my $newuser = 0;
@@ -4366,7 +4587,7 @@ sub upfile_drop_add {
                                      $fname,$mname,$lname,$gen,$sec,$enddate,
                                      $startdate,$env{'form.forceid'},
                                      $desiredhost,$email,'manual','',$cid,
-                                     '',$context,$inststatus);
+                                     '',$context,$inststatus,$credits);
                             $userresult = $roleresult;
                         } else {
                             if ($role ne '') { 
@@ -4461,7 +4682,7 @@ sub upfile_drop_add {
             #  Get current classlist
             my $classlist = &Apache::loncoursedata::get_classlist();
             if (! defined($classlist)) {
-                $r->print('<form name="studentform" method="post" action="/adm/createuser" />'.
+                $r->print('<form name="studentform" method="post" action="/adm/createuser">'.
                           '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
                           '<p class="LC_info">'.&mt('There are no students with current/future access to the course.').'</p>'.
                           '</form>'."\n");
@@ -4584,7 +4805,7 @@ sub print_drop_menu {
         $heading = &mt("Drop Students");
     }
     $r->print('<h3>'.$heading.'</h3>'."\n".
-              '<form name="studentform" method="post">'."\n");
+              '<form name="studentform" method="post" action="">'."\n");
     my $classlist = &Apache::loncoursedata::get_classlist();
     if (! defined($classlist)) {
         my $msg = '';
@@ -4597,7 +4818,7 @@ sub print_drop_menu {
     } else {
         &show_drop_list($r,$classlist,'nosort',$permission,$crstype);
     }
-    $r->print('</form>'. &Apache::loncommon::end_page());
+    $r->print('</form>');
     return;
 }
 
@@ -4640,7 +4861,7 @@ sub update_user_list {
     foreach my $item (@changelist) {
         my ($role,$uname,$udom,$cid,$sec,$scope,$result,$type,$locktype,
             @sections,$scopestem,$singlesec,$showsecs,$warn_singlesec,
-            $nothingtodo,$keepnosection);
+            $nothingtodo,$keepnosection,$credits);
         if ($choice eq 'drop') {
             ($uname,$udom,$sec) = split(/:/,$item,-1);
             $role = 'st';
@@ -4653,7 +4874,8 @@ sub update_user_list {
                 $scope = $scopestem.'/'.$sec;
             }
         } elsif ($context eq 'course') {
-            ($uname,$udom,$role,$sec,$type,$locktype) = split(/\:/,$item,-1);
+            ($uname,$udom,$role,$sec,$type,$locktype,$credits) =
+                split(/\:/,$item);
             $cid = $env{'request.course.id'};
             $scopestem = '/'.$cid;
             $scopestem =~s/\_/\//g;
@@ -4672,7 +4894,7 @@ sub update_user_list {
             } elsif ($setting eq 'author') { 
                 ($uname,$udom,$role,$scope) = split(/\:/,$item);
             } elsif ($setting eq 'course') {
-                ($uname,$udom,$role,$cid,$sec,$type,$locktype) = 
+                ($uname,$udom,$role,$cid,$sec,$type,$locktype,$credits) = 
                     split(/\:/,$item);
                 $scope = '/'.$cid;
                 $scope =~s/\_/\//g;
@@ -4695,7 +4917,7 @@ sub update_user_list {
             $end = $now; 
             if ($role eq 'st') {
                 $result = 
-                    &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,$type,$locktype,$cid,'',$context);
+                    &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,$type,$locktype,$cid,'',$context,$credits);
             } else {
                 $result = 
                     &Apache::lonnet::revokerole($udom,$uname,$scope,$role,
@@ -4703,7 +4925,7 @@ sub update_user_list {
             }
         } elsif ($choice eq 'delete') {
             if ($role eq 'st') {
-                &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$now,$start,$type,$locktype,$cid,'',$context);
+                &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$now,$start,$type,$locktype,$cid,'',$context,$credits);
             }
             $result =
                 &Apache::lonnet::assignrole($udom,$uname,$scope,$role,$now,
@@ -4716,7 +4938,7 @@ sub update_user_list {
             }
             if ($choice eq 'reenable') {
                 if ($role eq 'st') {
-                    $result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,$type,$locktype,$cid,'',$context);
+                    $result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,$type,$locktype,$cid,'',$context,$credits);
                 } else {
                     $result = 
                         &Apache::lonnet::assignrole($udom,$uname,$scope,$role,$end,
@@ -4724,14 +4946,14 @@ sub update_user_list {
                 }
             } elsif ($choice eq 'activate') {
                 if ($role eq 'st') {
-                    $result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,$type,$locktype,$cid,'',$context);
+                    $result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,$type,$locktype,$cid,'',$context,$credits);
                 } else {
                     $result = &Apache::lonnet::assignrole($udom,$uname,$scope,$role,$end,
                                             $now,'','',$context);
                 }
             } elsif ($choice eq 'chgdates') {
                 if ($role eq 'st') {
-                    $result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,$type,$locktype,$cid,'',$context);
+                    $result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,$type,$locktype,$cid,'',$context,$credits);
                 } else {
                     $result = &Apache::lonnet::assignrole($udom,$uname,$scope,$role,$end,
                                                 $start,'','',$context);
@@ -4801,7 +5023,7 @@ sub update_user_list {
                     } 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);
+                                &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,undef,$end,$start,$type,$locktype,$cid,'',$context,$credits);
                         } else {
                             my $newscope = $scopestem;
                             $result = &Apache::lonnet::assignrole($udom,$uname,$newscope,$role,$end,$start,'','',$context);
@@ -4815,7 +5037,7 @@ sub update_user_list {
                     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);
+                                $result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$newsec,$end,$start,$type,$locktype,$cid,'',$context,$credits);
                                 if (@newsecs > 1) {
                                     my $showsingle; 
                                     if ($newsec eq '') {
@@ -4926,7 +5148,7 @@ sub update_user_list {
             }
         }
     }
-    $r->print('<p><b>'.&mt("$result_text{'ok'}{$choice} for [quant,_1,user role,user roles,no user roles].",$count).'</b></p>');
+    $r->print('<p><b>'.&mt("$result_text{'ok'}{$choice} [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>');
@@ -4943,7 +5165,10 @@ sub update_user_list {
     if ($choice eq 'drop') {
         $linktext = &mt('Display current class roster');
     }
-    $r->print('<a href="javascript:document.studentform.submit()">'.$linktext.'</a></form>'."\n");
+    $r->print(
+        &Apache::lonhtmlcommon::actionbox(
+            ['<a href="javascript:document.studentform.submit()">'.$linktext.'</a>'])
+       .'</form>'."\n");
 }
 
 sub dates_feedback {
@@ -4951,7 +5176,7 @@ sub dates_feedback {
     my $dates;
     if ($start < $now) {
         if ($end == 0) {
-            $dates .= &mt('role(s) active now; no end date');
+            $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 {
@@ -5104,14 +5329,18 @@ sub get_groupslist {
 }
 
 sub setsections_javascript {
-    my ($formname,$groupslist,$mode,$checkauth,$crstype) = @_;
+    my ($formname,$groupslist,$mode,$checkauth,$crstype,$showcredits) = @_;
     my ($checkincluded,$finish,$rolecode,$setsection_js);
     if ($mode eq 'upload') {
         $checkincluded = 'formname.name == "'.$formname.'"';
         $finish = "return 'ok';";
         $rolecode = "var role = formname.defaultrole.options[formname.defaultrole.selectedIndex].value;\n";
     } elsif ($formname eq 'cu') {
-        $checkincluded = 'formname.elements[i-1].checked == true';
+        if (($crstype eq 'Course') && ($showcredits)) {
+            $checkincluded = "((role == 'st') && (formname.elements[i-2].checked == true)) || ((role != 'st') && (formname.elements[i-1].checked == true))";
+        } else {
+            $checkincluded = 'formname.elements[i-1].checked == true';
+        }
         if ($checkauth) {
             $finish = "var authcheck = auth_check();\n".
                       "   if (authcheck == 'ok') {\n".
@@ -5122,7 +5351,7 @@ sub setsections_javascript {
         }
         $rolecode = "var match = str.split('_');
                 var role = match[3];\n";
-    } elsif ($formname eq 'enrollstudent') {
+    } elsif (($formname eq 'enrollstudent') || ($formname eq 'selfenroll')) {
         $checkincluded = 'formname.name == "'.$formname.'"';
         if ($checkauth) {
             $finish = "var authcheck = auth_check();\n".
@@ -5148,7 +5377,7 @@ sub setsections_javascript {
                     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.',
                     inco => 'In each community, each user may only have one member role at a time.',
-                    youh => 'You had selected ',
+                    youh => 'You had selected',
                     secs => 'sections.',
                     plmo => 'Please modify your selections so they include no more than one section.',
                     mayn => 'may not be used as the name for a section, as it is a reserved word.',
@@ -5170,8 +5399,8 @@ function setSections(formname,crstype) {
         var checkcurr = str.match(re1);
         if (checkcurr != null) {
             var num = i;
+            $rolecode
             if ($checkincluded) {
-                $rolecode
                 if (role == 'cc' || role == 'co') {
                     if (role == 'cc') {
                         alert("$alerts{'secd'}\\n$alerts{'accr'}");
@@ -5472,6 +5701,22 @@ sub get_permission {
         if (&Apache::lonnet::allowed('mdg',$env{'request.course.id'})) {
             $permission{'grp_manage'} = 1;
         }
+        if ($permission{'cusr'}) {
+            my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
+            my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
+            my %coursehash = (
+                'internal.selfenrollmgrdc' => $env{'course.'.$env{'request.course.id'}.'.internal.selfenrollmgrdc'},
+                'internal.selfenrollmgrcc' => $env{'course.'.$env{'request.course.id'}.'.internal.selfenrollmgrcc'},
+                'internal.coursecode'      => $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'},
+                'internal.textbook'        =>$env{'course.'.$env{'request.course.id'}.'.internal.textbook'},
+            );
+            my ($managed_by_cc,$managed_by_dc) = &selfenrollment_administration($cdom,$cnum,$crstype,\%coursehash);
+            if (ref($managed_by_cc) eq 'ARRAY') {
+                if (@{$managed_by_cc}) {
+                    $permission{'selfenrolladmin'} = 1;
+                }
+            }
+        }
     } elsif ($context eq 'author') {
         $permission{'cusr'} = &authorpriv($env{'user.name'},$env{'request.role.domain'});
         $permission{'view'} = $permission{'cusr'};
@@ -5544,7 +5789,7 @@ sub get_course_identity {
 }
 
 sub dc_setcourse_js {
-    my ($formname,$mode,$context) = @_;
+    my ($formname,$mode,$context,$showcredits) = @_;
     my ($dc_setcourse_code,$authen_check);
     my $cctext = &Apache::lonnet::plaintext('cc');
     my $cotext = &Apache::lonnet::plaintext('co');
@@ -5630,7 +5875,7 @@ function setCourse() {
         }
 SCRIPTTOP
     if ($mode ne 'upload') {
-        $dc_setcourse_code .= (<<"ENDSCRIPT");
+        $dc_setcourse_code .= (<<"SCRIPTMID");
         var coursename = "_$env{'request.role.domain'}"+"_"+course+"_"+userrole
         var numcourse = getIndex(document.$formname.dccourse);
         if (numcourse == "-1") {
@@ -5656,6 +5901,16 @@ SCRIPTTOP
             if (numend != "-1") {
                 document.$formname.elements[numend].name = "end"+coursename
             }
+SCRIPTMID
+        if ($showcredits) {
+            $dc_setcourse_code .= <<ENDCRED;
+            var numcredits = getIndex(document.$formname.credits);
+            if (numcredits != "-1") {
+                document.$formname.elements[numcredits].name = "credits"+coursename;
+            }
+ENDCRED
+        }
+        $dc_setcourse_code .= <<ENDSCRIPT; 
         }
     }
     var authcheck = auth_check();
@@ -5792,5 +6047,126 @@ sub is_courseowner {
     return;
 }
 
+sub get_selfenroll_titles {
+    my @row = ('types','registered','enroll_dates','access_dates','section',
+               'approval','limit');
+    my %lt = &Apache::lonlocal::texthash (
+                types        => 'Users allowed to self-enroll',
+                registered   => 'Registration status (official courses)' ,
+                enroll_dates => 'Dates self-enrollment available',
+                access_dates => 'Access dates for self-enrolling users',
+                section      => "Self-enrolling users' section",
+                approval     => 'Processing of requests',
+                limit        => 'Enrollment limit',
+             );
+    return (\@row,\%lt);
+}
+
+sub selfenroll_default_descs {
+    my %desc = (
+                 types => {
+                            dom => &mt('Course domain'),
+                            all => &mt('Any domain'),
+                            ''  => &mt('None'),
+                          },
+                 limit => {
+                            none         => &mt('No limit'),
+                            allstudents  => &mt('Limit by total students'),
+                            selfenrolled => &mt('Limit by total self-enrolled'),
+                          },
+                 approval => {
+                                '0' => &mt('Processed automatically'),
+                                '1' => &mt('Queued for approval'),
+                                '2' => &mt('Queued, pending validation'),
+                             },
+                 registered => {
+                                 0 => 'No registration required',
+                                 1 => 'Registered students only',
+                               },
+               );
+    return %desc;
+}
+
+sub selfenroll_validation_types {
+    my @items = ('url','fields','button','markup');
+    my %names =  &Apache::lonlocal::texthash (
+            url      => 'Web address of validation server/script',
+            fields   => 'Form fields to send to validator',
+            button   => 'Text for validation button',
+            markup   => 'Validation description (HTML)',
+    );
+    my @fields = ('username','domain','uniquecode','course','token','coursetype','description');
+    return (\@items,\%names,\@fields);
+}
+
+sub get_extended_type {
+    my ($cdom,$cnum,$crstype,$current) = @_;
+    my $type = 'unofficial';
+    my %settings;
+    if (ref($current) eq 'HASH') {
+        %settings = %{$current};
+    } else {
+        %settings = &Apache::lonnet::get('environment',['internal.coursecode','internal.textbook'],$cdom,$cnum);
+    }
+    if ($crstype eq 'Community') {
+        $type = 'community';
+    } elsif ($settings{'internal.coursecode'}) {
+        $type = 'official';
+    } elsif ($settings{'internal.textbook'}) {
+        $type = 'textbook';
+    }
+    return $type;
+}
+
+sub selfenrollment_administration {
+    my ($cdom,$cnum,$crstype,$coursehash) = @_;
+    my %settings;
+    if (ref($coursehash) eq 'HASH') {
+        %settings = %{$coursehash};
+    } else {
+        %settings = &Apache::lonnet::get('environment',
+                        ['internal.selfenrollmgrdc','internal.selfenrollmgrcc',
+                         'internal.coursecode','internal.textbook'],$cdom,$cnum);
+    }
+    my ($possconfigs) = &get_selfenroll_titles(); 
+    my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
+    my $selfenrolltype = &get_extended_type($cdom,$cnum,$crstype,\%settings);
+
+    my (@in_course,@in_domain); 
+    if ($settings{'internal.selfenrollmgrcc'} ne '') {
+        @in_course = split(/,/,$settings{'internal.selfenrollmgrcc'}); 
+        my @diffs = &Apache::loncommon::compare_arrays($possconfigs,\@in_course);
+        unless (@diffs) {
+            return (\@in_course,\@in_domain);
+        }
+    }
+    if ($settings{'internal.selfenrollmgrdc'} ne '') {
+        my @in_domain = split(/,/,$settings{'internal.selfenrollmgrdc'});
+        my @diffs = &Apache::loncommon::compare_arrays(\@in_domain,$possconfigs);
+        unless (@diffs) {
+            return (\@in_course,\@in_domain);
+        }
+    }
+    my @combined = @in_course;
+    push(@combined,@in_domain);
+    my @diffs = &Apache::loncommon::compare_arrays(\@combined,$possconfigs); 
+    unless (@diffs) {
+        return (\@in_course,\@in_domain);
+    }
+    if ($domdefaults{$selfenrolltype.'selfenrolladmdc'} eq '') {
+        push(@in_course,@diffs);
+    } else {
+        my @defaultdc = split(/,/,$domdefaults{$selfenrolltype.'selfenrolladmdc'});
+        foreach my $item (@diffs) {
+            if (grep(/^\Q$item\E$/,@defaultdc)) {
+                push(@in_domain,$item);
+            } else {
+                push(@in_course,$item);
+            }
+        }
+    }
+    return (\@in_course,\@in_domain);
+}
+
 1;