--- loncom/interface/loncreateuser.pm	2014/03/31 02:31:05	1.398
+++ loncom/interface/loncreateuser.pm	2016/10/10 02:53:02	1.415
@@ -1,7 +1,7 @@
 # The LearningOnline Network with CAPA
 # Create a user
 #
-# $Id: loncreateuser.pm,v 1.398 2014/03/31 02:31:05 raeburn Exp $
+# $Id: loncreateuser.pm,v 1.415 2016/10/10 02:53:02 raeburn Exp $
 #
 # Copyright Michigan State University Board of Trustees
 #
@@ -251,13 +251,15 @@ sub build_tools_display {
                    'unofficial' => 'Can request creation of unofficial courses',
                    'community'  => 'Can request creation of communities',
                    'textbook'   => 'Can request creation of textbook courses',
+                   'placement'  => 'Can request creation of placement tests',
                    'requestauthor'  => 'Can request author space',
     );
     if ($context eq 'requestcourses') {
         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
                       'requestcourses.official','requestcourses.unofficial',
-                      'requestcourses.community','requestcourses.textbook');
-        @usertools = ('official','unofficial','community','textbook');
+                      'requestcourses.community','requestcourses.textbook',
+                      'requestcourses.placement');
+        @usertools = ('official','unofficial','community','textbook','placement');
         @options =('norequest','approval','autolimit','validate');
         %validations = &Apache::lonnet::auto_courserequest_checks($ccdomain);
         %reqtitles = &courserequest_titles();
@@ -447,12 +449,14 @@ sub coursereq_externaluser {
                    'unofficial' => 'Can request creation of unofficial courses',
                    'community'  => 'Can request creation of communities',
                    'textbook'   => 'Can request creation of textbook courses',
+                   'placement'  => 'Can request creation of placement tests',
     );
 
     %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
                       'reqcrsotherdom.official','reqcrsotherdom.unofficial',
-                      'reqcrsotherdom.community','reqcrsotherdom.textbook');
-    @usertools = ('official','unofficial','community','textbook');
+                      'reqcrsotherdom.community','reqcrsotherdom.textbook',
+                      'reqcrsotherdom.placement');
+    @usertools = ('official','unofficial','community','textbook','placement');
     @options = ('approval','validate','autolimit');
     %validations = &Apache::lonnet::auto_courserequest_checks($cdom);
     my $optregex = join('|',@options);
@@ -527,12 +531,79 @@ sub domainrole_req {
            &Apache::loncommon::end_data_table();
 }
 
+sub domadhocroles {
+    my ($ccuname,$ccdomain) = @_;
+    my $confname = &Apache::lonnet::get_domainconfiguser($env{'request.role.domain'}); 
+    my %existing=&Apache::lonnet::dump('roles',$env{'request.role.domain'},
+                                       $confname,'rolesdef_');
+    my $output;
+    if (keys(%existing) > 0) {
+        my @current;
+        my $curradhoc = 'adhocroles.'.$env{'request.role.domain'}; 
+        my %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,$curradhoc);
+        if ($userenv{$curradhoc}) {
+            @current = split(/,/,$userenv{$curradhoc});
+        }
+        my %customroles;
+        foreach my $key (keys(%existing)) {
+            if ($key=~/^rolesdef\_(\w+)$/) {
+                my $rolename = $1;
+                my %privs;
+                ($privs{'system'},$privs{'domain'},$privs{'course'}) = split(/\_/,$existing{$key});
+                $customroles{$rolename} = \%privs;
+            }
+        }
+        $output = '<br /><h3>'.
+                  &mt('Ad Hoc Course Roles Selectable via Helpdesk Role').
+                  '</h3>'."\n".
+                  &Apache::loncommon::start_data_table().
+                  &Apache::loncommon::start_data_table_header_row().
+                  '<th>'.&mt('Action').'</th><th>'.&mt('Role').'</th>'.
+                  '<th>'.&mt('Privileges in Course').'<th>'.
+                  &Apache::loncommon::end_data_table_header_row(); 
+        foreach my $key (sort(keys(%customroles))) {
+            $output .= &Apache::loncommon::start_data_table_row();
+            if (grep(/^\Q$key\E$/,@current)) {
+                $output .= '<td><label>'.
+                           '<input type="checkbox" name="adhocroledel" value="'.$key.'" />'.
+                           &mt('Delete').'</label>'.
+                           '</td>';
+            } else {
+                $output .= '<td><label>'.
+                           '<input type="checkbox" name="adhocroleadd" value="'.$key.'" />'.
+                           &mt('Add').'</label>'.
+                           '</td>';
+            }
+            $output .= '<td>'.$key.'</td><td>';
+            foreach my $level ('course','domain','system') {
+                if ($customroles{$key}{$level}) {
+                    my $suffix;
+                    if (($level eq 'domain') || ($level eq 'system')) {
+                        $suffix = '&nbsp;('.&mt($level).')';
+                    }
+                    my @privs = split(/:/,$customroles{$key}{$level});
+                    foreach my $item (@privs) {
+                        next if ($item eq ''); 
+                        my ($priv,$cond) = split(/\&/,$item);
+                        $output .= &Apache::lonnet::plaintext($priv,'Course').$suffix.'<br />';
+                    }
+                }
+            }
+            $output .= '</td>'.
+                       &Apache::loncommon::end_data_table_row();
+        }
+        $output .= &Apache::loncommon::end_data_table();
+    }
+    return $output;
+}
+
 sub courserequest_titles {
     my %titles = &Apache::lonlocal::texthash (
                                    official   => 'Official',
                                    unofficial => 'Unofficial',
                                    community  => 'Communities',
                                    textbook   => 'Textbook',
+                                   placement  => 'Placement Tests',
                                    norequest  => 'Not allowed',
                                    approval   => 'Approval by Dom. Coord.',
                                    validate   => 'With validation',
@@ -750,7 +821,10 @@ sub print_username_entry_form {
         }
         $r->print("<h3>$actiontext</h3>");
         if ($env{'form.origform'} ne 'crtusername') {
-            $r->print("\n".$response);
+            if ($response) {
+               $r->print("\n<div>$response</div>".
+                         '<br clear="all" />');
+            }
         }
         $r->print(&entry_form($defdom,$srch,$forcenewuser,$context,$response,$crstype));
     }
@@ -813,7 +887,7 @@ sub entry_form {
     }
     my $cancreate =
         &Apache::lonuserutils::can_create_user($dom,$context,$usertype);
-    my $userpicker = 
+    my ($userpicker,$cansearch) = 
        &Apache::loncommon::user_picker($dom,$srch,$forcenewuser,
                                        'document.crtuser',$cancreate,$usertype);
     my $srchbutton = &mt('Search');
@@ -822,7 +896,9 @@ sub entry_form {
     } elsif ($cancreate && $responsemsg ne '' && $inexact) {
         $srchbutton = &mt('Search or Add New User');
     }
-    my $output = <<"ENDBLOCK";
+    my $output;
+    if ($cansearch) {
+        $output = <<"ENDBLOCK";
 <form action="/adm/createuser" method="post" name="crtuser">
 <input type="hidden" name="action" value="$env{'form.action'}" />
 <input type="hidden" name="phase" value="get_user_info" />
@@ -830,6 +906,9 @@ $userpicker
 <input name="userrole" type="button" value="$srchbutton" onclick="javascript:validateEntry(document.crtuser)" />
 </form>
 ENDBLOCK
+    } else {
+        $output = '<p>'.$userpicker.'</p>';
+    }
     if ($env{'form.phase'} eq '') {
         my $defdom=$env{'request.role.domain'};
         my $domform = &Apache::loncommon::select_dom_form($defdom,'srchdomain');
@@ -1231,7 +1310,7 @@ ENDFORMINFO
     }
     my $title = '';
     if ($newuser) {
-        my ($portfolioform,$domroleform);
+        my ($portfolioform,$domroleform,$adhocroleform);
         if ((&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) ||
             (&Apache::lonnet::allowed('mut',$env{'request.role.domain'}))) {
             # Current user has quota or user tools modification privileges
@@ -1241,6 +1320,12 @@ ENDFORMINFO
             ($ccdomain eq $env{'request.role.domain'})) {
             $domroleform = '<br />'.&domainrole_req($ccuname,$ccdomain);
         }
+        if (&Apache::lonnet::allowed('cdh',$env{'request.role.domain'})) {
+            $adhocroleform = &domadhocroles($ccuname,$ccdomain);
+            if ($adhocroleform) {
+                $adhocroleform = '<br />'.$adhocroleform;
+            }
+        }
         &initialize_authen_forms($ccdomain,$formname);
         my %lt=&Apache::lonlocal::texthash(
                 'lg'             => 'Login Data',
@@ -1351,7 +1436,7 @@ ENDAUTH
         } else {
             $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc)); 
         }
-        $r->print($portfolioform.$domroleform);
+        $r->print($portfolioform.$domroleform.$adhocroleform);
         if ($env{'form.action'} eq 'singlestudent') {
             $r->print(&date_sections_select($context,$newuser,$formname,
                                             $permission,$crstype,$ccuname,
@@ -1388,7 +1473,7 @@ ENDAUTH
             $r->print(&Apache::loncommon::end_data_table());
         }
         $r->print('</div>');
-        my @order = ('auth','quota','tools','requestauthor');
+        my @order = ('auth','quota','tools','requestauthor','adhocroles');
         my %user_text;
         my ($isadv,$isauthor) = 
             &Apache::lonnet::is_advanced_user($ccuname,$ccdomain);
@@ -1397,6 +1482,9 @@ ENDAUTH
             && ($env{'request.role.domain'} eq $ccdomain)) {
             $user_text{'requestauthor'} = &domainrole_req($ccuname,$ccdomain);
         }
+        if (&Apache::lonnet::allowed('cdh',$env{'request.role.domain'})) {
+            $user_text{'adhocroles'} = &domadhocroles($ccuname,$ccdomain);
+        }
         $user_text{'auth'} =  &user_authentication($ccuname,$ccdomain,$formname);
         if ((&Apache::lonnet::allowed('mpq',$ccdomain)) ||
             (&Apache::lonnet::allowed('mut',$ccdomain))) {
@@ -2244,8 +2332,8 @@ sub personal_data_display {
                    '<input type="text" name="uname" size="25" value="" autocomplete="off" />';
         $rowcount ++;
         $output .= &Apache::lonhtmlcommon::row_closure(1);
-        my $upassone = '<input type="password" name="upass'.$now.'" size="10" autocomplete="off" />';
-        my $upasstwo = '<input type="password" name="upasscheck'.$now.'" size="10" autocomplete="off" />';
+        my $upassone = '<input type="password" name="upass'.$now.'" size="20" autocomplete="off" />';
+        my $upasstwo = '<input type="password" name="upasscheck'.$now.'" size="20" autocomplete="off" />';
         $output .= &Apache::lonhtmlcommon::row_title(&mt('Password').'<b>*</b>',
                                                     'LC_pick_box_title',
                                                     'LC_oddrow_value')."\n".
@@ -2282,19 +2370,15 @@ sub personal_data_display {
                 }
             } else {
                 if ($context eq 'selfcreate') {
-                    if (($item eq 'permanentemail') && ($newuser eq 'email')) {
-                        $row .= $ccuname;
-                    } else {
-                        if ($canmodify{$item}) {
-                            if ($newuser eq 'email') {
-                                $row .= '<input type="text" name="'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
-                            } else {
-                                $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
-                            }
-                            $editable ++;
+                    if ($canmodify{$item}) {
+                        if ($newuser eq 'email') {
+                            $row .= '<input type="text" name="'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
                         } else {
-                            $hiderow = 1;
+                            $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" autocomplete="off" />';
                         }
+                        $editable ++;
+                    } else {
+                        $hiderow = 1;
                     }
                 } else {
                     $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
@@ -2355,7 +2439,7 @@ sub personal_data_display {
     }
     if (($context eq 'selfcreate') && ($newuser eq 'email')) {
         if ($captchaform) {
-            $output .= &Apache::lonhtmlcommon::row_title($lt{'valid'},
+            $output .= &Apache::lonhtmlcommon::row_title($lt{'valid'}.'*',
                                                          'LC_pick_box_title')."\n".
                        $captchaform."\n".'<br /><br />'.
                        &Apache::lonhtmlcommon::row_closure(1); 
@@ -2583,7 +2667,7 @@ sub update_user_data {
     my (%alerts,%rulematch,%inst_results,%curr_rules);
     my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
     my @usertools = ('aboutme','blog','webdav','portfolio');
-    my @requestcourses = ('official','unofficial','community','textbook');
+    my @requestcourses = ('official','unofficial','community','textbook','placement');
     my @requestauthor = ('requestauthor');
     my ($othertitle,$usertypes,$types) = 
         &Apache::loncommon::sorted_inst_types($env{'form.ccdomain'});
@@ -2693,6 +2777,12 @@ sub update_user_data {
                                                     $newcustom{'requestauthor'},
                                                     \%changeHash,'requestauthor');
                 }
+                if (&Apache::lonnet::allowed('cdh',$env{'request.role.domain'})) {
+                    my @adds = &Apache::loncommon::get_env_multiple('form.adhocroleadd');
+                    if (&adhocrole_changes(\%changeHash)) {
+                        $changed{'adhocroles.'.$env{'request.role.domain'}} = $changeHash{'adhocroles.'.$env{'request.role.domain'}};
+                    }  
+                }
             }
             if ($canmodify_status{'inststatus'}) {
                 if (exists($env{'form.inststatus'})) {
@@ -2756,7 +2846,8 @@ sub update_user_data {
              'requestcourses.community','requestcourses.textbook',
              'reqcrsotherdom.official','reqcrsotherdom.unofficial',
              'reqcrsotherdom.community','reqcrsotherdom.textbook',
-             'requestauthor'],
+             'reqcrsotherdom.placement','requestauthor',
+             'adhocroles.'.$env{'request.role.domain'}],
               $env{'form.ccdomain'},$env{'form.ccuname'});
         my ($tmp) = keys(%userenv);
         if ($tmp =~ /^(con_lost|error)/i) { 
@@ -2895,6 +2986,7 @@ sub update_user_data {
                 &Apache::loncommon::default_quota($env{'form.ccdomain'},$oldinststatus,$name);
             ($newdefquota{$name},$newsettingstatus{$name}) = ($olddefquota{$name},$oldsettingstatus{$name});
         }
+        push(@disporder,'adhocroles');
         my %canshow;
         if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
             $canshow{'quota'} = 1;
@@ -2913,6 +3005,9 @@ sub update_user_data {
         if (&Apache::lonnet::allowed('cau',$env{'form.ccdomain'})) {
             $canshow{'requestauthor'} = 1;
         }
+        if (&Apache::lonnet::allowed('cdh',$env{'request.role.domain'})) {
+            $canshow{'adhocroles'} = 1;
+        }
         my (%changeHash,%changed);
         if ($oldinststatus eq '') {
             $oldsettings{'inststatus'} = $othertitle; 
@@ -3026,6 +3121,14 @@ sub update_user_data {
                 &tool_changes('reqcrsotherdom',\@requestcourses,\%oldsettings,\%oldsettingstext,
                               \%userenv,\%changeHash,\%changed,\%newsettings,\%newsettingstext);
             }
+            if ($userenv{'adhocroles.'.$env{'request.role.domain'}}) {
+                $changeHash{'adhocroles.'.$env{'request.role.domain'}} = $userenv{'adhocroles.'.$env{'request.role.domain'}};
+            }
+            if (&adhocrole_changes(\%changeHash,\%userenv)) {
+                $changed{'adhocroles'} = 1;
+                $oldsettings{'adhocroles'} = $userenv{'adhocroles.'.$env{'request.role.domain'}};
+                $newsettings{'adhocroles'} = $changeHash{'adhocroles.'.$env{'request.role.domain'}}; 
+            }
         }
         foreach my $item (@userinfo) {
             if ($env{'form.c'.$item} ne $userenv{$item}) {
@@ -3047,8 +3150,9 @@ sub update_user_data {
                         ($env{'user.domain'} eq $env{'form.ccdomain'})) {
                         my %newenvhash;
                         foreach my $key (keys(%changed)) {
-                            if (($key eq 'official') || ($key eq 'unofficial')
-                                || ($key eq 'community')) {
+                            if (($key eq 'official') || ($key eq 'unofficial') ||
+                                ($key eq 'community') || ($key eq 'textbook') ||
+                                ($key eq 'placement')) {
                                 $newenvhash{'environment.requestcourses.'.$key} =
                                     $changeHash{'requestcourses.'.$key};
                                 if ($changeHash{'requestcourses.'.$key}) {
@@ -3067,6 +3171,9 @@ sub update_user_data {
           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
                                             $key,'reload','requestauthor');
                                 }
+                            } elsif ($key eq 'adhocroles') {
+                                $newenvhash{'adhocroles.'.$env{'request.role.domain'}} =
+                                    $changeHash{'adhocroles.'.$env{'request.role.domain'}};
                             } elsif ($key ne 'quota') {
                                 $newenvhash{'environment.tools.'.$key} = 
                                     $changeHash{'tools.'.$key};
@@ -3114,7 +3221,7 @@ sub update_user_data {
                                   \%newsettingstext);
                 if ($env{'form.cid'} ne $userenv{'id'}) {
                     &Apache::lonnet::idput($env{'form.ccdomain'},
-                         ($env{'form.ccuname'} => $env{'form.cid'}));
+                         {$env{'form.ccuname'} => $env{'form.cid'}},$uhome,'ids');
                     if (($recurseid) &&
                         (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'}))) {
                         my $idresult = 
@@ -3156,9 +3263,9 @@ sub update_user_data {
                 $rolestr = &mt('No roles');
             }
             if ($context eq 'course') {
-                $contextname = &mt('course');
+                $contextname = 'course';
             } elsif ($context eq 'author') {
-                $contextname = &mt('co-author');
+                $contextname = 'co-author';
             }
             $r->print(&mt('The following fields were not updated: ').'<ul>');
             my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
@@ -3167,9 +3274,9 @@ sub update_user_data {
             }
             $r->print('</ul>');
             if (@mod_disallowed == 1) {
-                $r->print(&mt("You do not have the authority to change this field given the user's current set of active/future [_1] roles:",$contextname));
+                $r->print(&mt("You do not have the authority to change this field given the user's current set of active/future $contextname roles:"));
             } else {
-                $r->print(&mt("You do not have the authority to change these fields given the user's current set of active/future [_1] roles:",$contextname));
+                $r->print(&mt("You do not have the authority to change these fields given the user's current set of active/future $contextname roles:"));
             }
             my $helplink = 'javascript:helpMenu('."'display'".')';
             $r->print('<span class="LC_cusr_emph">'.$rolestr.'</span><br />'
@@ -3257,7 +3364,9 @@ sub display_userinfo {
          'unofficial'     => 'Can Request Unofficial Courses',
          'community'      => 'Can Request Communities',
          'textbook'       => 'Can Request Textbook Courses',
+         'placement'      => 'Can Request Placement Tests',
          'requestauthor'  => 'Can Request Author Role',
+         'adhocroles'     => 'Ad Hoc Roles Selectable via Helpdesk Role',
          'inststatus'     => "Affiliation",
          'prvs'           => 'Previous Value:',
          'chto'           => 'Changed To:'
@@ -3623,13 +3732,77 @@ sub tool_changes {
     return;
 }
 
+sub adhocrole_changes {
+    my ($changehashref,$userenv) = @_;
+    my @adds = &Apache::loncommon::get_env_multiple('form.adhocroleadd');
+    my @dels = &Apache::loncommon::get_env_multiple('form.adhocroledel');
+    my (@saved,@added,@alladhoc,$changed);
+    my $adhoc_key = 'adhocroles.'.$env{'request.role.domain'};
+    if (!$env{'form.makeuser'}) {
+        if (ref($userenv) eq 'HASH') {
+            my @current;
+            if ($userenv->{$adhoc_key}) {
+                @current = split(/,/,$userenv->{$adhoc_key});
+                if (@dels) {
+                    foreach my $curr (@current) {
+                        next if ($curr eq ''); 
+                        unless (grep(/\Q$curr\E$/,@dels)) {
+                            push(@saved,$curr);
+                        }
+                    }
+                    $changed = 1;
+                } else {
+                    @saved = @current;
+                }
+            }
+        }
+    }
+    if (@adds) {
+        my $confname = &Apache::lonnet::get_domainconfiguser($env{'request.role.domain'});
+        my %existing=&Apache::lonnet::dump('roles',$env{'request.role.domain'},
+                                           $confname,'rolesdef_');
+        foreach my $poss (@adds) {
+            if (exists($existing{'rolesdef_'.$poss})) {
+                push(@added,$poss);
+                $changed = 1;
+            }
+        }
+    }
+    if (@added) {
+        if (@saved) {
+            foreach my $add (@added) {
+                unless (grep(/^\Q$add\E$/,@saved)) {
+                    push(@alladhoc,$add);
+                }
+            }
+        } else {
+            push(@alladhoc,@added);
+        }
+    }
+    if (@saved) {
+        push(@alladhoc,@saved);
+    }
+    if (@alladhoc) {
+        my $adhocstr = join(',',sort(@alladhoc)); 
+        $changehashref->{$adhoc_key} = $adhocstr;
+    } elsif (@dels) {
+        &Apache::lonnet::del('environment',[$adhoc_key],$env{'form.ccdomain'},$env{'form.ccuname'});
+        delete($changehashref->{$adhoc_key});
+        if (($env{'form.ccdomain'} eq $env{'user.domain'}) &&
+            ($env{'form.ccuname'} eq $env{'user.name'})) {
+            &Apache::lonnet::delenv($adhoc_key);
+        }
+    }
+    return $changed;
+}
+
 sub update_roles {
     my ($r,$context,$showcredits) = @_;
     my $now=time;
     my @rolechanges;
     my %disallowed;
     $r->print('<h3>'.&mt('Modifying Roles').'</h3>');
-    foreach my $key (keys (%env)) {
+    foreach my $key (keys(%env)) {
 	next if (! $env{$key});
         next if ($key eq 'form.action');
 	# Revoke roles
@@ -3811,7 +3984,7 @@ sub update_roles {
                 } else {
 		    my %curr_groups =
 			&Apache::longroup::coursegroups($one,$two);
-                    foreach my $sec (sort {$a cmp $b} keys %sections) {
+                    foreach my $sec (sort {$a cmp $b} keys(%sections)) {
                         if (($sec eq 'none') || ($sec eq 'all') || 
                             exists($curr_groups{$sec})) {
                             $disallowed{$sec} = $url;
@@ -3857,7 +4030,7 @@ sub update_roles {
                     my %curr_groups = 
 			&Apache::longroup::coursegroups($one,$two);
                     my $emptysec = 0;
-                    foreach my $sec (sort {$a cmp $b} keys %sections) {
+                    foreach my $sec (sort {$a cmp $b} keys(%sections)) {
                         $sec =~ s/\W//g;
                         if ($sec ne '') {
                             if (($sec eq 'none') || ($sec eq 'all') || 
@@ -3897,7 +4070,7 @@ sub update_roles {
                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
                 } else {
                     my $emptysec = 0;
-                    foreach my $sec (sort {$a cmp $b} keys %sections) {
+                    foreach my $sec (sort {$a cmp $b} keys(%sections)) {
                         if ($sec ne '') {
                             my $securl = $url.'/'.$sec;
                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$two,$start,$end,$one,undef,$sec,$context));
@@ -4153,7 +4326,7 @@ sub build_roles {
 # ========================================================== Custom Role Editor
 
 sub custom_role_editor {
-    my ($r,$brcrum) = @_;
+    my ($r,$brcrum,$prefix) = @_;
     my $action = $env{'form.customroleaction'};
     my $rolename; 
     if ($action eq 'new') {
@@ -4168,7 +4341,7 @@ sub custom_role_editor {
         $context = 'course';
     } else {
         $context = 'domain';
-        $crstype = $env{'form.templatecrstype'};
+        $crstype = 'course';
     }
 
     $rolename=~s/[^A-Za-z0-9]//gs;
@@ -4177,120 +4350,54 @@ sub custom_role_editor {
         return;
     }
 
-# ------------------------------------------------------- What can be assigned?
-    my %full=();
-    my %courselevel=();
-    my %courselevelcurrent=();
-    my $syspriv='';
-    my $dompriv='';
-    my $coursepriv='';
-    my $body_top;
-    my $newrole;
+    my $formname = 'form1';
+    my %privs=();
+    my $body_top = '<h2>';
+# ------------------------------------------------------- Does this role exist?
     my ($rdummy,$roledef)=
 			 &Apache::lonnet::get('roles',["rolesdef_$rolename"]);
-# ------------------------------------------------------- Does this role exist?
-    $body_top .= '<h2>';
     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
-	$body_top .= &mt('Existing Role').' "';
+        $body_top .= &mt('Existing Role').' "';
 # ------------------------------------------------- Get current role privileges
-	($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
-        if ($crstype eq 'Community') {
-            $syspriv =~ s/bre\&S//;   
+        ($privs{'system'},$privs{'domain'},$privs{'course'})=split(/\_/,$roledef);
+        if ($privs{'system'} =~ /bre\&S/) {
+            if ($context eq 'domain') {
+                $crstype = 'Course'; 
+            } elsif ($crstype eq 'Community') {
+                $privs{'system'} =~ s/bre\&S//;
+            }
+        } elsif ($context eq 'domain') {
+            $crstype = 'Course';
         }
     } else {
-        $newrole = 1;
-	$body_top .= &mt('New Role').' "';
-	$roledef='';
+        $body_top .= &mt('New Role').' "';
+        $roledef='';
     }
     $body_top .= $rolename.'"</h2>';
-    foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
-	my ($priv,$restrict)=split(/\&/,$item);
-        if (!$restrict) { $restrict='F'; }
-        $courselevel{$priv}=$restrict;
-        if ($coursepriv=~/\:$priv/) {
-	    $courselevelcurrent{$priv}=1;
-	}
-	$full{$priv}=1;
-    }
-    my %domainlevel=();
-    my %domainlevelcurrent=();
-    foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:d'})) {
-	my ($priv,$restrict)=split(/\&/,$item);
-        if (!$restrict) { $restrict='F'; }
-        $domainlevel{$priv}=$restrict;
-        if ($dompriv=~/\:$priv/) {
-	    $domainlevelcurrent{$priv}=1;
-	}
-	$full{$priv}=1;
-    }
-    my %systemlevel=();
-    my %systemlevelcurrent=();
-    foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:s'})) {
-	my ($priv,$restrict)=split(/\&/,$item);
-        if (!$restrict) { $restrict='F'; }
-        $systemlevel{$priv}=$restrict;
-        if ($syspriv=~/\:$priv/) {
-	    $systemlevelcurrent{$priv}=1;
-	}
-	$full{$priv}=1;
-    }
+
+# ------------------------------------------------------- What can be assigned?
+    my %full=();
+    my %levels=( 
+                 course => {},
+                 domain => {},
+                 system => {},
+               );
+    my %levelscurrent=(
+                        course => {},
+                        domain => {},
+                        system => {},
+                      );
+    &Apache::lonuserutils::custom_role_privs(\%privs,\%full,\%levels,\%levelscurrent);
     my ($jsback,$elements) = &crumb_utilities();
-    my $button_code = "\n";
-    my $head_script = "\n";
-    $head_script .= '<script type="text/javascript">'."\n"
-                   .'// <![CDATA['."\n";
-    my @template_roles = ("in","ta","ep");
-    if ($context eq 'domain') {
-        push(@template_roles,"ad");
-    }
-    push(@template_roles,"st");
-    if ($crstype eq 'Community') {
-        unshift(@template_roles,'co');
-    } else {
-        unshift(@template_roles,'cc');
-    }
-    foreach my $role (@template_roles) {
-        $head_script .= &make_script_template($role,$crstype);
-        $button_code .= &make_button_code($role,$crstype).' ';
-    }
-    my $context_code;
-    if ($context eq 'domain') {
-        my $checkedCommunity = '';
-        my $checkedCourse = ' checked="checked"';
-        if ($env{'form.templatecrstype'} eq 'Community') {
-            $checkedCommunity = $checkedCourse;
-            $checkedCourse = '';
-        }
-        $context_code = '<label>'.
-                        '<input type="radio" name="templatecrstype" value="Course"'.$checkedCourse.' onclick="this.form.submit();">'.
-                        &mt('Course').
-                        '</label>'.('&nbsp;' x2).
-                        '<label>'.
-                        '<input type="radio" name="templatecrstype" value="Community"'.$checkedCommunity.' onclick="this.form.submit();">'.
-                        &mt('Community').
-                        '</label>'.
-                        '</fieldset>'.
-                        '<input type="hidden" name="customroleaction" value="'.
-                        $action.'" />';
-        if ($env{'form.customroleaction'} eq 'new') {
-            $context_code .= '<input type="hidden" name="newrolename" value="'.
-                             $rolename.'" />';
-        } else {
-            $context_code .= '<input type="hidden" name="rolename" value="'.
-                             $rolename.'" />';
-        }
-        $context_code .= '<input type="hidden" name="action" value="custom" />'.
-                         '<input type="hidden" name="phase" value="selected_custom_edit" />';
-    }
-
-    $head_script .= "\n".$jsback."\n"
-                   .'// ]]>'."\n"
-                   .'</script>'."\n";
+    my @templateroles = &Apache::lonuserutils::custom_template_roles($context,$crstype);
+    my $head_script = 
+        &Apache::lonuserutils::custom_roledefs_js($context,$crstype,$formname,
+                                                  \%full,\@templateroles,$jsback);
     push (@{$brcrum},
-              {href => "javascript:backPage(document.form1,'pickrole','')",
+              {href => "javascript:backPage(document.$formname,'pickrole','')",
                text => "Pick custom role",
                faq  => 282,bug=>'Instructor Interface',},
-              {href => "javascript:backPage(document.form1,'','')",
+              {href => "javascript:backPage(document.$formname,'','')",
                text => "Edit custom role",
                faq  => 282,
                bug  => 'Instructor Interface',
@@ -4302,57 +4409,16 @@ sub custom_role_editor {
     $r->print(&Apache::loncommon::start_page('Custom Role Editor',
                                              $head_script,$args).
               $body_top);
-    my %lt=&Apache::lonlocal::texthash(
-		    'prv'  => "Privilege",
-		    'crl'  => "Course Level",
-                    'dml'  => "Domain Level",
-                    'ssl'  => "System Level");
-
-    $r->print('<div class="LC_left_float">'
-             .'<form action=""><fieldset>'
-             .'<legend>'.&mt('Select a Template').'</legend>'
-             .$button_code
-             .'</fieldset></form></div>');
-    if ($context_code) {
-        $r->print('<div class="LC_left_float">'
-                 .'<form action="/adm/createuser" method="post"><fieldset>'
-                 .'<legend>'.&mt('Context').'</legend>'
-                 .$context_code
-                 .'</form>'
-                 .'</div>'
-        );
-    }
-    $r->print('<br clear="all" />');
+    $r->print('<form name="'.$formname.'" method="post" action="">'."\n".
+              &Apache::lonuserutils::custom_role_header($context,$crstype,
+                                                        \@templateroles,$prefix));
 
     $r->print(<<ENDCCF);
-<form name="form1" method="post" action="">
 <input type="hidden" name="phase" value="set_custom_roles" />
 <input type="hidden" name="rolename" value="$rolename" />
 ENDCCF
-    $r->print(&Apache::loncommon::start_data_table().
-              &Apache::loncommon::start_data_table_header_row(). 
-'<th>'.$lt{'prv'}.'</th><th>'.$lt{'crl'}.'</th><th>'.$lt{'dml'}.
-'</th><th>'.$lt{'ssl'}.'</th>'.
-              &Apache::loncommon::end_data_table_header_row());
-    foreach my $priv (sort(keys(%full))) {
-        my $privtext = &Apache::lonnet::plaintext($priv,$crstype);
-        $r->print(&Apache::loncommon::start_data_table_row().
-	          '<td>'.$privtext.'</td><td>'.
-    ($courselevel{$priv}?'<input type="checkbox" name="'.$priv.'_c"'.
-    ($courselevelcurrent{$priv}?' checked="checked"':'').' />':'&nbsp;').
-    '</td><td>'.
-    ($domainlevel{$priv}?'<input type="checkbox" name="'.$priv.'_d"'.
-    ($domainlevelcurrent{$priv}?' checked="checked"':'').' />':'&nbsp;').
-    '</td><td>');
-        if ($priv eq 'bre' && $crstype eq 'Community') {
-            $r->print('&nbsp;');  
-        } else {
-            $r->print($systemlevel{$priv}?'<input type="checkbox" name="'.$priv.'_s"'.
-                      ($systemlevelcurrent{$priv}?' checked="checked"':'').' />':'&nbsp;');
-        }
-        $r->print('</td>'.
-                  &Apache::loncommon::end_data_table_row());
-    }
+    $r->print(&Apache::lonuserutils::custom_role_table($crstype,\%full,\%levels,
+                                                       \%levelscurrent,$prefix));
     $r->print(&Apache::loncommon::end_data_table().
    '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
    '<input type="hidden" name="startrolename" value="'.$env{'form.rolename'}.
@@ -4360,87 +4426,14 @@ ENDCCF
    '<input type="reset" value="'.&mt("Reset").'" />'."\n".
    '<input type="submit" value="'.&mt('Save').'" /></form>');
 }
-# --------------------------------------------------------
-sub make_script_template {
-    my ($role,$crstype) = @_;
-    my %full_c=();
-    my %full_d=();
-    my %full_s=();
-    my $return_script;
-    foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
-        my ($priv,$restrict)=split(/\&/,$item);
-        $full_c{$priv}=1;
-    }
-    foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:d'})) {
-        my ($priv,$restrict)=split(/\&/,$item);
-        $full_d{$priv}=1;
-    }
-    foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:s'})) {
-        next if (($crstype eq 'Community') && ($item eq 'bre&S'));
-        my ($priv,$restrict)=split(/\&/,$item);
-        $full_s{$priv}=1;
-    }
-    $return_script .= 'function set_'.$role.'() {'."\n";
-    my @temp = split(/:/,$Apache::lonnet::pr{$role.':c'});
-    my %role_c;
-    foreach my $priv (@temp) {
-        my ($priv_item, $dummy) = split(/\&/,$priv);
-        $role_c{$priv_item} = 1;
-    }
-    my %role_d;
-    @temp = split(/:/,$Apache::lonnet::pr{$role.':d'});
-    foreach my $priv(@temp) {
-        my ($priv_item, $dummy) = split(/\&/,$priv);
-        $role_d{$priv_item} = 1;
-    }
-    my %role_s;
-    @temp = split(/:/,$Apache::lonnet::pr{$role.':s'});
-    foreach my $priv(@temp) {
-        my ($priv_item, $dummy) = split(/\&/,$priv);
-        $role_s{$priv_item} = 1;
-    }
-    foreach my $priv_item (keys(%full_c)) {
-        my ($priv, $dummy) = split(/\&/,$priv_item);
-        if ((exists($role_c{$priv})) || (exists($role_d{$priv})) || 
-            (exists($role_s{$priv}))) {
-            $return_script .= "document.form1.$priv"."_c.checked = true;\n";
-        } else {
-            $return_script .= "document.form1.$priv"."_c.checked = false;\n";
-        }
-    }
-    foreach my $priv_item (keys(%full_d)) {
-        my ($priv, $dummy) = split(/\&/,$priv_item);
-        if ((exists($role_d{$priv})) || (exists($role_s{$priv}))) {
-            $return_script .= "document.form1.$priv"."_d.checked = true;\n";
-        } else {
-            $return_script .= "document.form1.$priv"."_d.checked = false;\n";
-        }
-    }
-    foreach my $priv_item (keys(%full_s)) {
-        my ($priv, $dummy) = split(/\&/,$priv_item);
-        if (exists($role_s{$priv})) {
-            $return_script .= "document.form1.$priv"."_s.checked = true;\n";
-        } else {
-            $return_script .= "document.form1.$priv"."_s.checked = false;\n";
-        }
-    }
-    $return_script .= '}'."\n";
-    return ($return_script);
-}
-# ----------------------------------------------------------
-sub make_button_code {
-    my ($role,$crstype) = @_;
-    my $label = &Apache::lonnet::plaintext($role,$crstype);
-    my $button_code = '<input type="button" onclick="set_'.$role.'()" value="'.$label.'" />';
-    return ($button_code);
-}
+
 # ---------------------------------------------------------- Call to definerole
 sub set_custom_role {
-    my ($r,$context,$brcrum) = @_;
+    my ($r,$context,$brcrum,$prefix) = @_;
     my $rolename=$env{'form.rolename'};
     $rolename=~s/[^A-Za-z0-9]//gs;
     if (!$rolename) {
-	&custom_role_editor($r,$brcrum);
+	&custom_role_editor($r,$brcrum,$prefix);
         return;
     }
     my ($jsback,$elements) = &crumb_utilities();
@@ -4465,7 +4458,7 @@ sub set_custom_role {
          help => 'Course_Editing_Custom_Roles'},
         );
     my $args = { bread_crumbs           => $brcrum,
-                 bread_crumbs_component => 'User Management'}; 
+                 bread_crumbs_component => 'User Management'};
     $r->print(&Apache::loncommon::start_page('Save Custom Role',$jscript,$args));
 
     my $newrole;
@@ -4482,38 +4475,13 @@ sub set_custom_role {
         $newrole = 1;
     }
     $r->print($rolename.'"</h3>');
-# ------------------------------------------------------- What can be assigned?
-    my $sysrole='';
-    my $domrole='';
-    my $courole='';
-
-    foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
-	my ($priv,$restrict)=split(/\&/,$item);
-        if (!$restrict) { $restrict=''; }
-        if ($env{'form.'.$priv.'_c'}) {
-	    $courole.=':'.$item;
-	}
-    }
-
-    foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:d'})) {
-	my ($priv,$restrict)=split(/\&/,$item);
-        if (!$restrict) { $restrict=''; }
-        if ($env{'form.'.$priv.'_d'}) {
-	    $domrole.=':'.$item;
-	}
-    }
+# ------------------------------------------------- Assign role and show result
 
-    foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:s'})) {
-	my ($priv,$restrict)=split(/\&/,$item);
-        if (!$restrict) { $restrict=''; }
-        if ($env{'form.'.$priv.'_s'}) {
-	    $sysrole.=':'.$item;
-	}
-    }
-    # Assign role; Compile and show result
     my $errmsg;
-    my $result =
-        &Apache::lonnet::definerole($rolename,$sysrole,$domrole,$courole);
+    my %newprivs = &Apache::lonuserutils::custom_role_update($rolename,$prefix);
+    # Assign role and return result
+    my $result = &Apache::lonnet::definerole($rolename,$newprivs{'s'},$newprivs{'d'},
+                                             $newprivs{'c'});
     if ($result ne 'ok') {
         $errmsg = ': '.$result;
     }
@@ -4720,10 +4688,11 @@ sub handler {
                                        $brcrum);
         }
     } elsif ($env{'form.action'} eq 'custom' && $permission->{'custom'}) {
+        my $prefix;
         if ($env{'form.phase'} eq 'set_custom_roles') {
-            &set_custom_role($r,$context,$brcrum);
+            &set_custom_role($r,$context,$brcrum,$prefix);
         } else {
-            &custom_role_editor($r,$brcrum);
+            &custom_role_editor($r,$brcrum,$prefix);
         }
     } elsif (($env{'form.action'} eq 'processauthorreq') &&
              ($permission->{'cusr'}) && 
@@ -4993,6 +4962,7 @@ sub handler {
                 selfenroll_end_access         => $env{'course.'.$cid.'.internal.selfenroll_end_access'},
                 default_enrollment_start_date => $env{'course.'.$cid.'.default_enrollment_start_date'},
                 default_enrollment_end_date   => $env{'course.'.$cid.'.default_enrollment_end_date'},
+                uniquecode                    => $env{'course.'.$cid.'.internal.uniquecode'},
             );
             push(@{$brcrum},
                     {href => '/adm/createuser?action=selfenroll',
@@ -5012,7 +4982,7 @@ sub handler {
                           bread_crumbs_component => 'Self-enrollment result'};
                 $r->print(&header(undef,$args));
                 $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
-                &update_selfenroll_config($r,$cid,$cdom,$cnum,\%currsettings);
+                &update_selfenroll_config($r,$cid,$cdom,$cnum,$context,$crstype,\%currsettings);
             }
         } else {
             $r->print(&header(undef,{'no_nav_bar' => 1}).
@@ -5048,19 +5018,7 @@ sub handler {
                           $cdom,$cnum,$coursedesc));
         }
     } elsif ($env{'form.action'} eq 'changelogs') {
-        my $helpitem;
-        if ($context eq 'course') {
-            $helpitem = 'Course_User_Logs';
-        }
-        push (@{$brcrum},
-                 {href => '/adm/createuser?action=changelogs',
-                  text => 'User Management Logs',
-                  help => $helpitem});
-        $bread_crumbs_component = 'User Changes';
-        $args = { bread_crumbs           => $brcrum,
-                  bread_crumbs_component => $bread_crumbs_component};
-        $r->print(&header(undef,$args));
-        &print_userchangelogs_display($r,$context,$permission);
+        &print_userchangelogs_display($r,$context,$permission,$brcrum);
     } else {
         $bread_crumbs_component = 'User Management';
         $args = { bread_crumbs           => $brcrum,
@@ -5350,7 +5308,7 @@ sub print_main_menu {
          {categorytitle => 'Administration',
          items => [ ]},
        );
-            
+
     if ($context eq 'domain'){
         
         push(@{ $menu[2]->{items} }, #Category: Administration
@@ -5403,6 +5361,7 @@ sub print_main_menu {
                                           groups => 'Community Groups',
                                         },
                        );
+        $linktext{'Placement'} = $linktext{'Course'};
 
         my %linktitle = (
             'Course' => {
@@ -5417,6 +5376,8 @@ sub print_main_menu {
                            },
         );
 
+        $linktitle{'Placement'} = $linktitle{'Course'};
+
         push(@{ $menu[0]->{items} }, #Category: Single Users
             {   
              linktext => $linktext{$crstype}{'single'},
@@ -5547,6 +5508,7 @@ sub print_selfenroll_menu {
         butn => 'but no user types have been checked.',
         wilf => "Please uncheck 'activate' or check at least one type.",
     );
+    &js_escape(\%alerts);
     my $selfenroll_js = <<"ENDSCRIPT";
 function update_types(caller,num) {
     var delidx = getIndexByName('selfenroll_delete');
@@ -5740,28 +5702,70 @@ ENDSCRIPT
                  '// ]]>'."\n".
                  '</script>'."\n".
                  '<h3>'.$lt->{'selfenroll'}.'</h3>'."\n";
-    my ($visible,$cansetvis,$vismsgs,$visactions) = &visible_in_cat($cdom,$cnum);
-    if (ref($visactions) eq 'HASH') {
-        if ($visible) {
-            $output .= '<p class="LC_info">'.$visactions->{'vis'}.'</p>';
-        } else {
-            $output .= '<p class="LC_warning">'.$visactions->{'miss'}.'</p>'
-                      .$visactions->{'yous'}.
-                       '<p>'.$visactions->{'gen'}.'<br />'.$visactions->{'coca'};
-            if (ref($vismsgs) eq 'ARRAY') {
-                $output .= '<br />'.$visactions->{'make'}.'<ul>';
-                foreach my $item (@{$vismsgs}) {
-                    $output .= '<li>'.$visactions->{$item}.'</li>';
+ 
+    my $visactions = &cat_visibility();
+    my ($cathash,%cattype);
+    my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
+    if (ref($domconfig{'coursecategories'}) eq 'HASH') {
+        $cathash = $domconfig{'coursecategories'}{'cats'};
+        $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
+        $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
+        if ($cattype{'auth'} eq '') {
+            $cattype{'auth'} = 'std';
+        }
+        if ($cattype{'unauth'} eq '') {
+            $cattype{'unauth'} = 'std';
+        }
+    } else {
+        $cathash = {};
+        $cattype{'auth'} = 'std';
+        $cattype{'unauth'} = 'std';
+    }
+    if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
+        $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
+                  '<br />'.
+                  '<br />'.$visactions->{'take'}.'<ul>'.
+                  '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
+                  '</ul>');
+    } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
+        if ($currsettings->{'uniquecode'}) {
+            $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
+        } else {
+            $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
+                  '<br />'.
+                  '<br />'.$visactions->{'take'}.'<ul>'.
+                  '<li>'.$visactions->{'dc_setcode'}.'</li>'.
+                  '</ul><br />');
+        }
+    } else {
+        my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
+        if (ref($visactions) eq 'HASH') {
+            if ($visible) {
+                $output .= '<p class="LC_info">'.$visactions->{'vis'}.'</p>';
+           } else {
+                $output .= '<p class="LC_warning">'.$visactions->{'miss'}.'</p>'
+                          .$visactions->{'yous'}.
+                           '<p>'.$visactions->{'gen'}.'<br />'.$visactions->{'coca'};
+                if (ref($vismsgs) eq 'ARRAY') {
+                    $output .= '<br />'.$visactions->{'make'}.'<ul>';
+                    foreach my $item (@{$vismsgs}) {
+                        $output .= '<li>'.$visactions->{$item}.'</li>';
+                    }
+                    $output .= '</ul>';
                 }
-                $output .= '</ul>';
+                $output .= '</p>';
             }
-            $output .= '</p>';
         }
     }
     my $actionhref = '/adm/createuser';
     if ($context eq 'domain') {
         $actionhref = '/adm/modifycourse';
     }
+
+    my %noedit;
+    unless ($context eq 'domain') {
+        %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
+    }
     $output .= '<form name="'.$formname.'" method="post" action="'.$actionhref.'">'."\n".
                &Apache::lonhtmlcommon::start_pick_box();
     if (ref($row) eq 'ARRAY') {
@@ -5776,6 +5780,37 @@ ENDSCRIPT
                 if (ref($currsettings) eq 'HASH') {
                     $curr_types = $currsettings->{'selfenroll_types'};
                 }
+                if ($noedit{$item}) {
+                    if ($curr_types eq '*') {
+                        $output .= &mt('Any user in any domain');   
+                    } else {
+                        my @entries = split(/;/,$curr_types);
+                        if (@entries > 0) {
+                            $output .= '<ul>'; 
+                            foreach my $entry (@entries) {
+                                my ($currdom,$typestr) = split(/:/,$entry);
+                                next if ($typestr eq '');
+                                my $domdesc = &Apache::lonnet::domain($currdom);
+                                my @currinsttypes = split(',',$typestr);
+                                my ($othertitle,$usertypes,$types) = 
+                                    &Apache::loncommon::sorted_inst_types($currdom);
+                                if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
+                                    $usertypes->{'any'} = &mt('any user'); 
+                                    if (keys(%{$usertypes}) > 0) {
+                                        $usertypes->{'other'} = &mt('other users');
+                                    }
+                                    my @longinsttypes = map { $usertypes->{$_}; } @currinsttypes;
+                                    $output .= '<li>'.$domdesc.':'.join(', ',@longinsttypes).'</li>';
+                                 }
+                            }
+                            $output .= '</ul>';
+                        } else {
+                            $output .= &mt('None');
+                        }
+                    }
+                    $output .= '<br />'.&mt('(Set by Domain Coordinator)');
+                    next;
+                }
                 my $showdomdesc = 1;
                 my $includeempty = 1;
                 my $num = 0;
@@ -5844,6 +5879,15 @@ ENDSCRIPT
                 if (ref($currsettings) eq 'HASH') {
                     $registered = $currsettings->{'selfenroll_registered'};
                 }
+                if ($noedit{$item}) {
+                    if ($registered) {
+                        $output .= &mt('Must be registered in course');
+                    } else {
+                        $output .= &mt('No requirement');
+                    }
+                    $output .= '<br />'.&mt('(Set by Domain Coordinator)');
+                    next;
+                }
                 if ($registered) {
                     $regon = ' checked="checked" ';
                     $regoff = ' ';
@@ -5868,6 +5912,12 @@ ENDSCRIPT
                         $endtime = $currsettings->{'default_enrollment_end_date'};
                     }
                 }
+                if ($noedit{$item}) {
+                    $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
+                                                          &Apache::lonlocal::locallocaltime($endtime));
+                    $output .= '<br />'.&mt('(Set by Domain Coordinator)');
+                    next;
+                }
                 my $startform =
                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_date',$starttime,
                                       undef,undef,undef,undef,undef,undef,undef,$nolink);
@@ -5887,6 +5937,12 @@ ENDSCRIPT
                         $endtime = $currsettings->{'default_enrollment_end_date'};
                     }
                 }
+                if ($noedit{$item}) {
+                    $output .= &mt('From: [_1], to: [_2]',&Apache::lonlocal::locallocaltime($starttime),
+                                                          &Apache::lonlocal::locallocaltime($endtime));
+                    $output .= '<br />'.&mt('(Set by Domain Coordinator)');
+                    next;
+                }
                 my $startform =
                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_access',$starttime,
                                       undef,undef,undef,undef,undef,undef,undef,$nolink);
@@ -5906,6 +5962,15 @@ ENDSCRIPT
                         $newsecval = $currsec;
                     }
                 }
+                if ($noedit{$item}) {
+                    if ($currsec ne '') {
+                        $output .= $currsec;
+                    } else {
+                        $output .= &mt('No specific section');
+                    }
+                    $output .= '<br />'.&mt('(Set by Domain Coordinator)');
+                    next;
+                }
                 my $sections_select = 
                     &Apache::lonuserutils::course_sections(\%sections_count,'st',$currsec);
                 $output .= '<table class="LC_createuser">'."\n".
@@ -5915,7 +5980,6 @@ ENDSCRIPT
                            &mt('New section').'<br />'."\n".
                            '<input type="text" name="newsec" size="15" value="'.$newsecval.'" />'."\n".
                            '<input type="hidden" name="sections" value="" />'."\n".
-                           '<input type="hidden" name="state" value="done" />'."\n".
                            '</td></tr></table>'."\n";
             } elsif ($item eq 'approval') {
                 my ($currnotified,$currapproval,%appchecked);
@@ -5927,6 +5991,11 @@ ENDSCRIPT
                 if ($currapproval !~ /^[012]$/) {
                     $currapproval = 0;
                 }
+                if ($noedit{$item}) {
+                    $output .=  $selfdescs{'approval'}{$currapproval}.
+                                '<br />'.&mt('(Set by Domain Coordinator)');
+                    next;
+                }
                 $appchecked{$currapproval} = ' checked="checked"';
                 for my $i (0..2) {
                     $output .= '<label>'.
@@ -5995,6 +6064,20 @@ ENDSCRIPT
                     $currlim = $currsettings->{'selfenroll_limit'};
                     $currcap = $currsettings->{'selfenroll_cap'};
                 }
+                if ($noedit{$item}) {
+                    if (($currlim eq 'allstudents') || ($currlim eq 'selfenrolled')) {
+                        if ($currlim eq 'allstudents') {
+                            $output .= &mt('Limit by total students');
+                        } elsif ($currlim eq 'selfenrolled') {
+                            $output .= &mt('Limit by total self-enrolled students');
+                        }
+                        $output .= ' '.&mt('Maximum: [_1]',$currcap).
+                                   '<br />'.&mt('(Set by Domain Coordinator)');
+                    } else {
+                        $output .= &mt('No limit').'<br />'.&mt('(Set by Domain Coordinator)');
+                    }
+                    next;
+                }
                 if ($currlim eq 'allstudents') {
                     $crslimit = ' checked="checked" ';
                     $selflimit = ' ';
@@ -6026,43 +6109,51 @@ ENDSCRIPT
     $output .= &Apache::lonhtmlcommon::end_pick_box().
                '<br /><input type="button" name="selfenrollconf" value="'
                .&mt('Save').'" onclick="validate_types(this.form);" />'
-               .'<input type="hidden" name="action" value="selfenroll" />'.
+               .'<input type="hidden" name="action" value="selfenroll" />'
+               .'<input type="hidden" name="state" value="done" />'."\n".
                $additional.'</form>';
     $r->print($output);
     return;
 }
 
-sub visible_in_cat {
-    my ($cdom,$cnum) = @_;
-    my %domconf = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
-    my ($cathash,%settable,@vismsgs,$cansetvis);
-    my %visactions = &Apache::lonlocal::texthash(
-                   vis => 'This course/community currently appears in the Course/Community Catalog for this domain.',
-                   gen => 'Courses can be both self-cataloging, based on an institutional code (e.g., fs08phy231), or can be assigned categories from a hierarchy defined for the domain.',
-                   miss => 'This course/community does not currently appear in the Course/Community Catalog for this domain.',
-                   yous => 'You should remedy this if you plan to allow self-enrollment, otherwise students will have difficulty finding this course.',
-                   coca => 'Courses can be absent from the Catalog, because they do not have an institutional code, have no assigned category, or have been specifically excluded.',
-                   make => 'Make any changes to self-enrollment settings below, click "Save", then take action to include the course in the Catalog:',
-                   take => 'Take the following action to ensure the course appears in the Catalog:',
-                   dc_unhide  => 'Ask a domain coordinator to change the "Exclude from course catalog" setting.',
-                   dc_addinst => 'Ask a domain coordinator to enable display the catalog of "Official courses (with institutional codes)".',
-                   dc_instcode => 'Ask a domain coordinator to assign an institutional code (if this is an official course).',
-                   dc_catalog  => 'Ask a domain coordinator to enable or create at least one course category in the domain.',
-                   dc_categories => 'Ask a domain coordinator to create a hierarchy of categories and sub categories for courses in the domain.',
-                   dc_chgcat => 'Ask a domain coordinator to change the category assigned to the course, as the one currently assigned is no longer used in the domain',
-                   dc_addcat => 'Ask a domain coordinator to assign a category to the course.',
-    );
-    $visactions{'unhide'} = &mt('Use [_1]Categorize course[_2] to change the "Exclude from course catalog" setting.','<a href="/adm/courseprefs?phase=display&actions=courseinfo">','</a>"');
-    $visactions{'chgcat'} = &mt('Use [_1]Categorize course[_2] to change the category assigned to the course, as the one currently assigned is no longer used in the domain.','"<a href="/adm/courseprefs?phase=display&actions=courseinfo">','</a>"');
-    $visactions{'addcat'} = &mt('Use [_1]Categorize course[_2] to assign a category to the course.','"<a href="/adm/courseprefs?phase=display&actions=courseinfo">','</a>"');
-    if (ref($domconf{'coursecategories'}) eq 'HASH') {
-        if ($domconf{'coursecategories'}{'togglecats'} eq 'crs') {
+sub get_noedit_fields {
+    my ($cdom,$cnum,$crstype,$row) = @_;
+    my %noedit;
+    if (ref($row) eq 'ARRAY') {
+        my %settings = &Apache::lonnet::get('environment',['internal.coursecode','internal.textbook',
+                                                           'internal.selfenrollmgrdc',
+                                                           'internal.selfenrollmgrcc'],$cdom,$cnum);
+        my $type = &Apache::lonuserutils::get_extended_type($cdom,$cnum,$crstype,\%settings);
+        my (%specific_managebydc,%specific_managebycc,%default_managebydc);
+        map { $specific_managebydc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrdc'}));
+        map { $specific_managebycc{$_} = 1; } (split(/,/,$settings{'internal.selfenrollmgrcc'}));
+        my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
+        map { $default_managebydc{$_} = 1; } (split(/,/,$domdefaults{$type.'selfenrolladmdc'}));
+
+        foreach my $item (@{$row}) {
+            next if ($specific_managebycc{$item});
+            if (($specific_managebydc{$item}) || ($default_managebydc{$item})) {
+                $noedit{$item} = 1;
+            }
+        }
+    }
+    return %noedit;
+} 
+
+sub visible_in_stdcat {
+    my ($cdom,$cnum,$domconf) = @_;
+    my ($cathash,%settable,@vismsgs,$cansetvis,$visible);
+    unless (ref($domconf) eq 'HASH') {
+        return ($visible,$cansetvis,\@vismsgs);
+    }
+    if (ref($domconf->{'coursecategories'}) eq 'HASH') {
+        if ($domconf->{'coursecategories'}{'togglecats'} eq 'crs') {
             $settable{'togglecats'} = 1;
         }
-        if ($domconf{'coursecategories'}{'categorize'} eq 'crs') {
+        if ($domconf->{'coursecategories'}{'categorize'} eq 'crs') {
             $settable{'categorize'} = 1;
         }
-        $cathash = $domconf{'coursecategories'}{'cats'};
+        $cathash = $domconf->{'coursecategories'}{'cats'};
     }
     if ($settable{'togglecats'} && $settable{'categorize'}) {
         $cansetvis = &mt('You are able to both assign a course category and choose to exclude this course from the catalog.');   
@@ -6077,10 +6168,10 @@ sub visible_in_cat {
     my %currsettings =
         &Apache::lonnet::get('environment',['hidefromcat','categories','internal.coursecode'],
                              $cdom,$cnum);
-    my $visible = 0;
+    $visible = 0;
     if ($currsettings{'internal.coursecode'} ne '') {
-        if (ref($domconf{'coursecategories'}) eq 'HASH') {
-            $cathash = $domconf{'coursecategories'}{'cats'};
+        if (ref($domconf->{'coursecategories'}) eq 'HASH') {
+            $cathash = $domconf->{'coursecategories'}{'cats'};
             if (ref($cathash) eq 'HASH') {
                 if ($cathash->{'instcode::0'} eq '') {
                     push(@vismsgs,'dc_addinst'); 
@@ -6104,8 +6195,8 @@ sub visible_in_cat {
     }
     if ($currsettings{'categories'} ne '') {
         my $cathash;
-        if (ref($domconf{'coursecategories'}) eq 'HASH') {
-            $cathash = $domconf{'coursecategories'}{'cats'};
+        if (ref($domconf->{'coursecategories'}) eq 'HASH') {
+            $cathash = $domconf->{'coursecategories'}{'cats'};
             if (ref($cathash) eq 'HASH') {
                 if (keys(%{$cathash}) == 0) {
                     push(@vismsgs,'dc_catalog');
@@ -6151,7 +6242,33 @@ sub visible_in_cat {
             unshift(@vismsgs,'dc_unhide')
         }
     }
-    return ($visible,$cansetvis,\@vismsgs,\%visactions);
+    return ($visible,$cansetvis,\@vismsgs);
+}
+
+sub cat_visibility {
+    my %visactions = &Apache::lonlocal::texthash(
+                   vis => 'This course/community currently appears in the Course/Community Catalog for this domain.',
+                   gen => 'Courses can be both self-cataloging, based on an institutional code (e.g., fs08phy231), or can be assigned categories from a hierarchy defined for the domain.',
+                   miss => 'This course/community does not currently appear in the Course/Community Catalog for this domain.',
+                   none => 'Display of a course catalog is disabled for this domain.',
+                   yous => 'You should remedy this if you plan to allow self-enrollment, otherwise students will have difficulty finding this course.',
+                   coca => 'Courses can be absent from the Catalog, because they do not have an institutional code, have no assigned category, or have been specifically excluded.',
+                   make => 'Make any changes to self-enrollment settings below, click "Save", then take action to include the course in the Catalog:',
+                   take => 'Take the following action to ensure the course appears in the Catalog:',
+                   dc_chgconf => 'Ask a domain coordinator to change the Catalog type for this domain.',
+                   dc_setcode => 'Ask a domain coordinator to assign a six character code to the course',
+                   dc_unhide  => 'Ask a domain coordinator to change the "Exclude from course catalog" setting.',
+                   dc_addinst => 'Ask a domain coordinator to enable display the catalog of "Official courses (with institutional codes)".',
+                   dc_instcode => 'Ask a domain coordinator to assign an institutional code (if this is an official course).',
+                   dc_catalog  => 'Ask a domain coordinator to enable or create at least one course category in the domain.',
+                   dc_categories => 'Ask a domain coordinator to create a hierarchy of categories and sub categories for courses in the domain.',
+                   dc_chgcat => 'Ask a domain coordinator to change the category assigned to the course, as the one currently assigned is no longer used in the domain',
+                   dc_addcat => 'Ask a domain coordinator to assign a category to the course.',
+    );
+    $visactions{'unhide'} = &mt('Use [_1]Categorize course[_2] to change the "Exclude from course catalog" setting.','<a href="/adm/courseprefs?phase=display&actions=courseinfo">','</a>"');
+    $visactions{'chgcat'} = &mt('Use [_1]Categorize course[_2] to change the category assigned to the course, as the one currently assigned is no longer used in the domain.','"<a href="/adm/courseprefs?phase=display&actions=courseinfo">','</a>"');
+    $visactions{'addcat'} = &mt('Use [_1]Categorize course[_2] to assign a category to the course.','"<a href="/adm/courseprefs?phase=display&actions=courseinfo">','</a>"');
+    return \%visactions;
 }
 
 sub new_selfenroll_dom_row {
@@ -6251,7 +6368,7 @@ sub selfenroll_date_forms {
 }
 
 sub print_userchangelogs_display {
-    my ($r,$context,$permission) = @_;
+    my ($r,$context,$permission,$brcrum) = @_;
     my $formname = 'rolelog';
     my ($username,$domain,$crstype,%roleslog);
     if ($context eq 'domain') {
@@ -6281,6 +6398,32 @@ sub print_userchangelogs_display {
     }
     if ((keys(%roleslog))[0]=~/^error\:/) { undef(%roleslog); }
 
+    my $helpitem;
+    if ($context eq 'course') {
+        $helpitem = 'Course_User_Logs';
+    }
+    push (@{$brcrum},
+             {href => '/adm/createuser?action=changelogs',
+              text => 'User Management Logs',
+              help => $helpitem});
+    my $bread_crumbs_component = 'User Changes';
+    my $args = { bread_crumbs           => $brcrum,
+                 bread_crumbs_component => $bread_crumbs_component};
+
+    # Create navigation javascript
+    my $jsnav = &userlogdisplay_js($formname);
+
+    my $jscript = (<<ENDSCRIPT);
+<script type="text/javascript">
+// <![CDATA[
+$jsnav
+// ]]>
+</script>
+ENDSCRIPT
+
+    # print page header
+    $r->print(&header($jscript,$args));
+
     # set defaults
     my $now = time();
     my $defstart = $now - (7*24*3600); #7 days ago 
@@ -6313,7 +6456,9 @@ sub print_userchangelogs_display {
     my ($minshown,$maxshown);
     $minshown = 1;
     my $count = 0;
-    if ($curr{'show'} ne &mt('all')) { 
+    if ($curr{'show'} =~ /\D/) {
+        $curr{'page'} = 1;
+    } else {
         $maxshown = $curr{'page'} * $curr{'show'};
         if ($curr{'page'} > 1) {
             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
@@ -6325,8 +6470,6 @@ sub print_userchangelogs_display {
               &role_display_filter($context,$formname,$domain,$username,\%curr,
                                    $version,$crstype));
 
-    # Create navigation
-    my ($nav_script,$nav_links) = &userlogdisplay_nav($formname,\%curr,$more_records);
     my $showntableheader = 0;
 
     # Table Header
@@ -6351,7 +6494,7 @@ sub print_userchangelogs_display {
     foreach my $id (sort { $roleslog{$b}{'exe_time'}<=>$roleslog{$a}{'exe_time'} } (keys(%roleslog))) {
         next if (($roleslog{$id}{'exe_time'} < $curr{'rolelog_start_date'}) ||
                  ($roleslog{$id}{'exe_time'} > $curr{'rolelog_end_date'}));
-        if ($curr{'show'} ne &mt('all')) {
+        if ($curr{'show'} !~ /\D/) {
             if ($count >= $curr{'page'} * $curr{'show'}) {
                 $more_records = 1;
                 last;
@@ -6370,9 +6513,7 @@ sub print_userchangelogs_display {
         $count ++;
         next if ($count < $minshown);
         unless ($showntableheader) {
-            $r->print($nav_script
-                     .$nav_links
-                     .&Apache::loncommon::start_data_table()
+            $r->print(&Apache::loncommon::start_data_table()
                      .$tableheader);
             $r->rflush();
             $showntableheader = 1;
@@ -6433,8 +6574,8 @@ sub print_userchangelogs_display {
     }
 
     if ($showntableheader) { # Table footer, if content displayed above
-        $r->print(&Apache::loncommon::end_data_table()
-                 .$nav_links);
+        $r->print(&Apache::loncommon::end_data_table().
+                  &userlogdisplay_navlinks(\%curr,$more_records));
     } else { # No content displayed above
         $r->print('<p class="LC_info">'
                  .&mt('There are no records to display.')
@@ -6450,15 +6591,10 @@ sub print_userchangelogs_display {
     return;
 }
 
-sub userlogdisplay_nav {
-    my ($formname,$curr,$more_records) = @_;
-    my ($nav_script,$nav_links);
-    if (ref($curr) eq 'HASH') {
-        # Create Navigation:
-        # Navigation Script
-        $nav_script = <<"ENDSCRIPT";
-<script type="text/javascript">
-// <![CDATA[
+sub userlogdisplay_js {
+    my ($formname) = @_;
+    return <<"ENDSCRIPT";
+
 function chgPage(caller) {
     if (caller == 'previous') {
         document.$formname.page.value --;
@@ -6469,28 +6605,30 @@ function chgPage(caller) {
     document.$formname.submit();
     return;
 }
-// ]]>
-</script>
 ENDSCRIPT
-        # Navigation Buttons
-        $nav_links = '<p>';
-        if (($curr->{'page'} > 1) || ($more_records)) {
-            if ($curr->{'page'} > 1) {
-                $nav_links .= '<input type="button"'
-                             .' onclick="javascript:chgPage('."'previous'".');"'
-                             .' value="'.&mt('Previous [_1] changes',$curr->{'show'})
-                             .'" /> ';
-            }
-            if ($more_records) {
-                $nav_links .= '<input type="button"'
-                             .' onclick="javascript:chgPage('."'next'".');"'
-                             .' value="'.&mt('Next [_1] changes',$curr->{'show'})
-                             .'" />';
-            }
+}
+
+sub userlogdisplay_navlinks {
+    my ($curr,$more_records) = @_;
+    return unless(ref($curr) eq 'HASH');
+    # Navigation Buttons
+    my $nav_links = '<p>';
+    if (($curr->{'page'} > 1) || ($more_records)) {
+        if (($curr->{'page'} > 1) && ($curr->{'show'} !~ /\D/)) {
+            $nav_links .= '<input type="button"'
+                         .' onclick="javascript:chgPage('."'previous'".');"'
+                         .' value="'.&mt('Previous [_1] changes',$curr->{'show'})
+                         .'" /> ';
+        }
+        if ($more_records) {
+            $nav_links .= '<input type="button"'
+                         .' onclick="javascript:chgPage('."'next'".');"'
+                         .' value="'.&mt('Next [_1] changes',$curr->{'show'})
+                         .'" />';
         }
-        $nav_links .= '</p>';
     }
-    return ($nav_script,$nav_links);
+    $nav_links .= '</p>';
+    return $nav_links;
 }
 
 sub role_display_filter {
@@ -6670,13 +6808,29 @@ sub user_search_result {
         }
     }
     if ($response ne '') {
-        $response = '<span class="LC_warning">'.$response.'</span>';
+        $response = '<span class="LC_warning">'.$response.'</span><br />';
     }
     if ($srch->{'srchin'} eq 'instd') {
-        my $instd_chk = &directorysrch_check($srch);
+        my $instd_chk = &instdirectorysrch_check($srch);
         if ($instd_chk ne 'ok') {
-            $response = '<span class="LC_warning">'.$instd_chk.'</span>'.
-                        '<br />'.&mt('You may want to search in the LON-CAPA domain instead of the institutional directory.').'<br /><br />';
+            my $domd_chk = &domdirectorysrch_check($srch);
+            $response .= '<span class="LC_warning">'.$instd_chk.'</span><br />';
+            if ($domd_chk eq 'ok') {
+                $response .= &mt('You may want to search in the LON-CAPA domain instead of the institutional directory.');
+            }
+            $response .= '<br />';
+        }
+    } else {
+        unless (($context eq 'requestcrs') && ($srch->{'srchtype'} eq 'exact')) { 
+            my $domd_chk = &domdirectorysrch_check($srch);
+            if ($domd_chk ne 'ok') {
+                my $instd_chk = &instdirectorysrch_check($srch);
+                $response .= '<span class="LC_warning">'.$domd_chk.'</span><br />';
+                if ($instd_chk eq 'ok') {
+                    $response .= &mt('You may want to search in the institutional directory instead of the LON-CAPA domain.');
+                }
+                $response .= '<br />';
+            }
         }
     }
     if ($response ne '') {
@@ -6772,7 +6926,7 @@ sub user_search_result {
                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
                     '</span><br />'.
                     &mt('You may want to search in the LON-CAPA domain instead of the institutional directory.').
-                    '<br /><br />'; 
+                    '<br />'; 
             }
         }
     } else {
@@ -6840,18 +6994,38 @@ sub user_search_result {
                 ($currstate,$response,$forcenewuser) = 
                     &build_search_response($context,$srch,%srch_results);
             } else {
-                my $showdom = &display_domain_info($srch->{'srchdomain'});                $response = '<span class="LC_warning">'.
+                my $showdom = &display_domain_info($srch->{'srchdomain'});
+                $response = '<span class="LC_warning">'.
                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
                     '</span><br />'.
                     &mt('You may want to search in the LON-CAPA domain instead of the institutional directory.').
-                    '<br /><br />';
+                    '<br />';
             }
         }
     }
     return ($currstate,$response,$forcenewuser,\%srch_results);
 }
 
-sub directorysrch_check {
+sub domdirectorysrch_check {
+    my ($srch) = @_;
+    my $response;
+    my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
+                                             ['directorysrch'],$srch->{'srchdomain'});
+    my $showdom = &display_domain_info($srch->{'srchdomain'});
+    if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
+        if ($dom_inst_srch{'directorysrch'}{'lcavailable'} eq '0') {
+            return &mt('LON-CAPA directory search is not available in domain: [_1]',$showdom);
+        }
+        if ($dom_inst_srch{'directorysrch'}{'lclocalonly'}) {
+            if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
+                return &mt('LON-CAPA directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom);
+            }
+        }
+    }
+    return 'ok';
+}
+
+sub instdirectorysrch_check {
     my ($srch) = @_;
     my $can_search = 0;
     my $response;
@@ -7053,7 +7227,7 @@ sub build_search_response {
                                  .&mt('Please contact the [_1]helpdesk[_2] if you need to create a new user.'
                                     ,' <a'.$helplink.'>'
                                     ,'</a>')
-                                 .'<br /><br />';
+                                 .'<br />';
                 }
             }
         }
@@ -7164,13 +7338,13 @@ sub course_level_table {
                 ((($role eq 'cc') || ($role eq 'co')) && ($isowner))) {
                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
                                             $plrole,\%sections_count,\%lt,
-                                            $defaultcredits,$crstype);
+                                            $showcredits,$defaultcredits,$crstype);
             } elsif ($env{'request.course.sec'} ne '') {
                 if (&Apache::lonnet::allowed('c'.$role,$thiscourse.'/'.
                                              $env{'request.course.sec'})) {
                     $table .= &course_level_row($protectedcourse,$role,$area,$domain,
                                                 $plrole,\%sections_count,\%lt,
-                                                $defaultcredits,$crstype);
+                                                $showcredits,$defaultcredits,$crstype);
                 }
             }
         }
@@ -7179,7 +7353,8 @@ sub course_level_table {
                 next if ($crstype eq 'Community' && $customroles{$cust} =~ /bre\&S/);
                 my $role = 'cr_cr_'.$env{'user.domain'}.'_'.$env{'user.name'}.'_'.$cust;
                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
-                                            $cust,\%sections_count,\%lt);
+                                            $cust,\%sections_count,\%lt,
+                                            $showcredits,$defaultcredits,$crstype);
             }
 	}
     }
@@ -7193,7 +7368,11 @@ sub course_level_table {
 &Apache::loncommon::start_data_table().
 &Apache::loncommon::start_data_table_header_row().
 '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'."\n".
-'<th>'.$lt{'ext'}.'</th><th>'.$lt{'crd'}.'</th>'."\n".
+'<th>'.$lt{'ext'}.'</th><th>'."\n";
+    if ($showcredits) {
+        $result .= $lt{'crd'}.'</th>';
+    }
+    $result .=
 '<th>'.$lt{'grs'}.'</th><th>'.$lt{'sta'}.'</th>'."\n".
 '<th>'.$lt{'end'}.'</th>'.
 &Apache::loncommon::end_data_table_header_row().
@@ -7204,14 +7383,14 @@ $table.
 
 sub course_level_row {
     my ($protectedcourse,$role,$area,$domain,$plrole,$sections_count,
-        $lt,$defaultcredits,$crstype) = @_;
+        $lt,$showcredits,$defaultcredits,$crstype) = @_;
     my $creditem;
     my $row = &Apache::loncommon::start_data_table_row().
               ' <td><input type="checkbox" name="act_'.
               $protectedcourse.'_'.$role.'" /></td>'."\n".
               ' <td>'.$plrole.'</td>'."\n".
               ' <td>'.$area.'<br />Domain: '.$domain.'</td>'."\n";
-    if (($role eq 'st') && ($crstype eq 'Course')) {
+    if (($showcredits) && ($role eq 'st') && ($crstype eq 'Course')) {
         $row .= 
             '<td><input type="text" name="credits_'.$protectedcourse.'_'.
             $role.'" size="3" value="'.$defaultcredits.'" /></td>';
@@ -7300,8 +7479,8 @@ sub course_level_dc {
         my $plrole=&Apache::lonnet::plaintext($role);
         $otheritems .= '  <option value="'.$role.'">'.$plrole.'</option>';
     }
-    if ( keys %customroles > 0) {
-        foreach my $cust (sort keys %customroles) {
+    if ( keys(%customroles) > 0) {
+        foreach my $cust (sort(keys(%customroles))) {
             my $custrole='cr_cr_'.$env{'user.domain'}.
                     '_'.$env{'user.name'}.'_'.$cust;
             $otheritems .= '  <option value="'.$custrole.'">'.$cust.'</option>';
@@ -7336,14 +7515,19 @@ ENDTIMEENTRY
 }
 
 sub update_selfenroll_config {
-    my ($r,$cid,$cdom,$cnum,$currsettings) = @_;
+    my ($r,$cid,$cdom,$cnum,$context,$crstype,$currsettings) = @_;
     return unless (ref($currsettings) eq 'HASH');
     my ($row,$lt) = &Apache::lonuserutils::get_selfenroll_titles();
     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
     my (%changes,%warning);
     my $curr_types;
+    my %noedit;
+    unless ($context eq 'domain') {
+        %noedit = &get_noedit_fields($cdom,$cnum,$crstype,$row);
+    }
     if (ref($row) eq 'ARRAY') {
         foreach my $item (@{$row}) {
+            next if ($noedit{$item});
             if ($item eq 'enroll_dates') {
                 my (%currenrolldate,%newenrolldate);
                 foreach my $type ('start','end') {
@@ -7663,19 +7847,49 @@ sub update_selfenroll_config {
     } else {
         $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
     }
-    my ($visible,$cansetvis,$vismsgs,$visactions) = &visible_in_cat($cdom,$cnum);
-    if (ref($visactions) eq 'HASH') {
-        if (!$visible) {
+    my $visactions = &cat_visibility();
+    my ($cathash,%cattype);
+    my %domconfig = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
+    if (ref($domconfig{'coursecategories'}) eq 'HASH') {
+        $cathash = $domconfig{'coursecategories'}{'cats'};
+        $cattype{'auth'} = $domconfig{'coursecategories'}{'auth'};
+        $cattype{'unauth'} = $domconfig{'coursecategories'}{'unauth'};
+    } else {
+        $cathash = {};
+        $cattype{'auth'} = 'std';
+        $cattype{'unauth'} = 'std';
+    }
+    if (($cattype{'auth'} eq 'none') && ($cattype{'unauth'} eq 'none')) {
+        $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
+                  '<br />'.
+                  '<br />'.$visactions->{'take'}.'<ul>'.
+                  '<li>'.$visactions->{'dc_chgconf'}.'</li>'.
+                  '</ul>');
+    } elsif (($cattype{'auth'} !~ /^(std|domonly)$/) && ($cattype{'unauth'} !~ /^(std|domonly)$/)) {
+        if ($currsettings->{'uniquecode'}) {
+            $r->print('<span class="LC_info">'.$visactions->{'vis'}.'</span>');
+        } else {
             $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
-                      '<br />');
-            if (ref($vismsgs) eq 'ARRAY') {
-                $r->print('<br />'.$visactions->{'take'}.'<ul>');
-                foreach my $item (@{$vismsgs}) {
-                    $r->print('<li>'.$visactions->{$item}.'</li>');
+                  '<br />'.
+                  '<br />'.$visactions->{'take'}.'<ul>'.
+                  '<li>'.$visactions->{'dc_setcode'}.'</li>'.
+                  '</ul><br />');
+        }
+    } else {
+        my ($visible,$cansetvis,$vismsgs) = &visible_in_stdcat($cdom,$cnum,\%domconfig);
+        if (ref($visactions) eq 'HASH') {
+            if (!$visible) {
+                $r->print('<br /><span class="LC_warning">'.$visactions->{'miss'}.'</span><br />'.$visactions->{'yous'}.
+                          '<br />');
+                if (ref($vismsgs) eq 'ARRAY') {
+                    $r->print('<br />'.$visactions->{'take'}.'<ul>');
+                    foreach my $item (@{$vismsgs}) {
+                        $r->print('<li>'.$visactions->{$item}.'</li>');
+                    }
+                    $r->print('</ul>');
                 }
-                $r->print('</ul>');
+                $r->print($cansetvis);
             }
-            $r->print($cansetvis);
         }
     } 
     return;