Annotation of loncom/interface/loncreateuser.pm, revision 1.295.2.3

1.20      harris41    1: # The LearningOnline Network with CAPA
1.1       www         2: # Create a user
                      3: #
1.295.2.3! raeburn     4: # $Id: loncreateuser.pm,v 1.295.2.2 2009/05/23 12:37:51 raeburn Exp $
1.22      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.20      harris41   28: ###
                     29: 
1.1       www        30: package Apache::loncreateuser;
1.66      bowersj2   31: 
                     32: =pod
                     33: 
                     34: =head1 NAME
                     35: 
1.263     jms        36: Apache::loncreateuser.pm
1.66      bowersj2   37: 
                     38: =head1 SYNOPSIS
                     39: 
1.263     jms        40:     Handler to create users and custom roles
                     41: 
                     42:     Provides an Apache handler for creating users,
1.66      bowersj2   43:     editing their login parameters, roles, and removing roles, and
                     44:     also creating and assigning custom roles.
                     45: 
                     46: =head1 OVERVIEW
                     47: 
                     48: =head2 Custom Roles
                     49: 
                     50: In LON-CAPA, roles are actually collections of privileges. "Teaching
                     51: Assistant", "Course Coordinator", and other such roles are really just
                     52: collection of privileges that are useful in many circumstances.
                     53: 
                     54: Creating custom roles can be done by the Domain Coordinator through
                     55: the Create User functionality. That screen will show all privileges
                     56: that can be assigned to users. For a complete list of privileges,
                     57: please see C</home/httpd/lonTabs/rolesplain.tab>.
                     58: 
                     59: Custom role definitions are stored in the C<roles.db> file of the role
                     60: author.
                     61: 
                     62: =cut
1.1       www        63: 
                     64: use strict;
                     65: use Apache::Constants qw(:common :http);
                     66: use Apache::lonnet;
1.54      bowersj2   67: use Apache::loncommon;
1.68      www        68: use Apache::lonlocal;
1.117     raeburn    69: use Apache::longroup;
1.190     raeburn    70: use Apache::lonuserutils;
1.277     raeburn    71: use Apache::selfenroll();
1.139     albertel   72: use LONCAPA qw(:DEFAULT :match);
1.1       www        73: 
1.20      harris41   74: my $loginscript; # piece of javascript used in two separate instances
                     75: my $authformnop;
                     76: my $authformkrb;
                     77: my $authformint;
                     78: my $authformfsys;
                     79: my $authformloc;
                     80: 
1.94      matthew    81: sub initialize_authen_forms {
1.227     raeburn    82:     my ($dom,$formname,$curr_authtype,$mode) = @_;
                     83:     my ($krbdef,$krbdefdom) = &Apache::loncommon::get_kerberos_defaults($dom);
                     84:     my %param = ( formname => $formname,
1.187     raeburn    85:                   kerb_def_dom => $krbdefdom,
1.227     raeburn    86:                   kerb_def_auth => $krbdef,
1.187     raeburn    87:                   domain => $dom,
                     88:                 );
1.188     raeburn    89:     my %abv_auth = &auth_abbrev();
1.227     raeburn    90:     if ($curr_authtype =~ /^(krb4|krb5|internal|localauth|unix):(.*)$/) {
1.188     raeburn    91:         my $long_auth = $1;
1.227     raeburn    92:         my $curr_autharg = $2;
1.188     raeburn    93:         my %abv_auth = &auth_abbrev();
                     94:         $param{'curr_authtype'} = $abv_auth{$long_auth};
                     95:         if ($long_auth =~ /^krb(4|5)$/) {
                     96:             $param{'curr_kerb_ver'} = $1;
1.227     raeburn    97:             $param{'curr_autharg'} = $curr_autharg;
1.188     raeburn    98:         }
1.205     raeburn    99:         if ($mode eq 'modifyuser') {
                    100:             $param{'mode'} = $mode;
                    101:         }
1.187     raeburn   102:     }
1.227     raeburn   103:     $loginscript  = &Apache::loncommon::authform_header(%param);
                    104:     $authformkrb  = &Apache::loncommon::authform_kerberos(%param);
1.31      matthew   105:     $authformnop  = &Apache::loncommon::authform_nochange(%param);
                    106:     $authformint  = &Apache::loncommon::authform_internal(%param);
                    107:     $authformfsys = &Apache::loncommon::authform_filesystem(%param);
                    108:     $authformloc  = &Apache::loncommon::authform_local(%param);
1.20      harris41  109: }
                    110: 
1.188     raeburn   111: sub auth_abbrev {
                    112:     my %abv_auth = (
                    113:                      krb4     => 'krb',
                    114:                      internal => 'int',
                    115:                      localuth => 'loc',
                    116:                      unix     => 'fsys',
                    117:                    );
                    118:     return %abv_auth;
                    119: }
1.43      www       120: 
1.134     raeburn   121: # ====================================================
                    122: 
                    123: sub portfolio_quota {
                    124:     my ($ccuname,$ccdomain) = @_;
                    125:     my %lt = &Apache::lonlocal::texthash(
1.267     raeburn   126:                    'usrt'      => "User Tools",
                    127:                    'disk'      => "Disk space allocated to user's portfolio files",
                    128:                    'cuqu'      => "Current quota",
                    129:                    'cust'      => "Custom quota",
                    130:                    'defa'      => "Default",
                    131:                    'chqu'      => "Change quota",
1.134     raeburn   132:     );
1.149     raeburn   133:     my ($currquota,$quotatype,$inststatus,$defquota) = 
                    134:         &Apache::loncommon::get_user_quota($ccuname,$ccdomain);
                    135:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($ccdomain);
                    136:     my ($longinsttype,$showquota,$custom_on,$custom_off,$defaultinfo);
                    137:     if ($inststatus ne '') {
                    138:         if ($usertypes->{$inststatus} ne '') {
                    139:             $longinsttype = $usertypes->{$inststatus};
                    140:         }
                    141:     }
                    142:     $custom_on = ' ';
                    143:     $custom_off = ' checked="checked" ';
                    144:     my $quota_javascript = <<"END_SCRIPT";
                    145: <script type="text/javascript">
                    146: function quota_changes(caller) {
                    147:     if (caller == "custom") {
                    148:         if (document.cu.customquota[0].checked) {
                    149:             document.cu.portfolioquota.value = "";
                    150:         }
                    151:     }
                    152:     if (caller == "quota") {
                    153:         document.cu.customquota[1].checked = true;
                    154:     }
                    155: }
                    156: </script>
                    157: END_SCRIPT
                    158:     if ($quotatype eq 'custom') {
                    159:         $custom_on = $custom_off;
                    160:         $custom_off = ' ';
                    161:         $showquota = $currquota;
                    162:         if ($longinsttype eq '') {
1.230     bisitz    163:             $defaultinfo = &mt('For this user, the default quota would be [_1]'
                    164:                             .' Mb.',$defquota);
1.149     raeburn   165:         } else {
1.231     raeburn   166:             $defaultinfo = &mt("For this user, the default quota would be [_1]".
                    167:                                " Mb, as determined by the user's institutional".
                    168:                                " affiliation ([_2]).",$defquota,$longinsttype);
1.149     raeburn   169:         }
                    170:     } else {
                    171:         if ($longinsttype eq '') {
1.230     bisitz    172:             $defaultinfo = &mt('For this user, the default quota is [_1]'
                    173:                             .' Mb.',$defquota);
1.149     raeburn   174:         } else {
1.231     raeburn   175:             $defaultinfo = &mt("For this user, the default quota of [_1]".
                    176:                                " Mb, is determined by the user's institutional".
                    177:                                " affiliation ([_2]).",$defquota,$longinsttype);
1.149     raeburn   178:         }
                    179:     }
1.267     raeburn   180: 
                    181:     my $output = $quota_javascript."\n".
                    182:                  '<h3>'.$lt{'usrt'}.'</h3>'."\n".
                    183:                  &Apache::loncommon::start_data_table();
                    184: 
                    185:     if (&Apache::lonnet::allowed('mut',$ccdomain)) {
1.275     raeburn   186:         $output .= &build_tools_display($ccuname,$ccdomain,'tools');
1.267     raeburn   187:     }
                    188:     if (&Apache::lonnet::allowed('mpq',$ccdomain)) {
                    189:         $output .= '<tr class="LC_info_row">'."\n".
                    190:                    '    <td>'.$lt{'disk'}.'</td>'."\n".
                    191:                    '  </tr>'."\n".
                    192:                    &Apache::loncommon::start_data_table_row()."\n".
                    193:                    '  <td>'.$lt{'cuqu'}.': '.
                    194:                    $currquota.'&nbsp;Mb.&nbsp;&nbsp;'.
                    195:                    $defaultinfo.'</td>'."\n".
                    196:                    &Apache::loncommon::end_data_table_row()."\n".
                    197:                    &Apache::loncommon::start_data_table_row()."\n".
                    198:                    '  <td><span class="LC_nobreak">'.$lt{'chqu'}.
                    199:                    ': <label>'.
                    200:                    '<input type="radio" name="customquota" value="0" '.
                    201:                    $custom_off.' onchange="javascript:quota_changes('."'custom'".')"'.
                    202:                    ' />'.$lt{'defa'}.'&nbsp;('.$defquota.' Mb).</label>&nbsp;'.
                    203:                    '&nbsp;<label><input type="radio" name="customquota" value="1" '. 
                    204:                    $custom_on.'  onchange="javascript:quota_changes('."'custom'".')" />'.
                    205:                    $lt{'cust'}.':</label>&nbsp;'.
                    206:                    '<input type="text" name="portfolioquota" size ="5" value="'.
                    207:                    $showquota.'" onfocus="javascript:quota_changes('."'quota'".')" '.
                    208:                    '/>&nbsp;Mb</span></td>'."\n".
                    209:                    &Apache::loncommon::end_data_table_row()."\n";
                    210:     }  
                    211:     $output .= &Apache::loncommon::end_data_table();
1.134     raeburn   212:     return $output;
                    213: }
                    214: 
1.275     raeburn   215: sub build_tools_display {
                    216:     my ($ccuname,$ccdomain,$context) = @_;
                    217:     my (@usertools,%userenv,$output);
                    218:     my %lt = &Apache::lonlocal::texthash (
                    219:                    'blog'       => "Personal User Blog",
                    220:                    'aboutme'    => "Personal Information Page",
                    221:                    'portfolio'  => "Personal User Portfolio",
                    222:                    'avai'       => "Available",
                    223:                    'cusa'       => "availability",
                    224:                    'chse'       => "Change setting",
                    225:                    'usde'       => "Use default",
                    226:                    'uscu'       => "Use custom",
                    227:                    'official'   => 'Can request creation of official courses',
                    228:                    'unofficial' => 'Can request creation of unofficial courses',  
                    229:     );
1.279     raeburn   230:     if ($context eq 'requestcourses') {
1.275     raeburn   231:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
1.279     raeburn   232:                       'requestcourses.official','requestcourses.unofficial');
1.275     raeburn   233:         @usertools = ('official','unofficial');
                    234:     } else {
                    235:         %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
                    236:                           'tools.aboutme','tools.portfolio','tools.blog');
                    237:         @usertools = ('aboutme','blog','portfolio');
                    238:     }
                    239:     foreach my $item (@usertools) {
                    240:         my ($custom_access,$curr_access,$cust_on,$cust_off,$tool_on,$tool_off);
                    241:         $cust_off = 'checked="checked" ';
                    242:         $tool_on = 'checked="checked" ';
                    243:         $curr_access =  
                    244:             &Apache::lonnet::usertools_access($ccuname,$ccdomain,$item,undef,
                    245:                                               $context);
                    246:         if ($userenv{$context.'.'.$item} eq '') {
                    247:             $custom_access = 'default';
                    248:             if (!$curr_access) {
                    249:                 $tool_off = 'checked="checked" ';
                    250:                 $tool_on = '';
                    251:             }
                    252:         } else {
                    253:             $custom_access = 'custom';
                    254:             $cust_on = ' checked="checked" ';
                    255:             $cust_off = '';
                    256:             if ($userenv{$context.'.'.$item} == 0) {
                    257:                 $tool_off = 'checked="checked" ';
                    258:                 $tool_on = '';
                    259:             }
                    260:         }
                    261:         $output .= '  <tr class="LC_info_row">'."\n".
                    262:                    '   <td>'.$lt{$item}.'</td>'."\n".
                    263:                    '  </tr>'."\n".
                    264:                    &Apache::loncommon::start_data_table_row()."\n".
                    265:                    '  <td>'.&mt('Availability determined currently from [_1] setting.',$custom_access).
                    266:                    '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.$lt{'avai'}.': '.
                    267:                    ($curr_access?&mt('Yes'):&mt('No')).'</td>'."\n".
                    268:                    &Apache::loncommon::end_data_table_row()."\n".
                    269:                    &Apache::loncommon::start_data_table_row()."\n".
                    270:                    '  <td><span class="LC_nobreak">'.$lt{'chse'}.': <label>'.
                    271:                    '<input type="radio" name="custom'.$item.'" value="0" '.
                    272:                    $cust_off.'/>'.$lt{'usde'}.'</label>&nbsp;&nbsp;&nbsp;'.
                    273:                     '<label><input type="radio" name="custom'.$item.'" value="1" '.
                    274:                    $cust_on.'/>'.$lt{'uscu'}.'</label>&nbsp;&nbsp;--&nbsp;&nbsp;'.
                    275:                    $lt{'cusa'}.':&nbsp;<label>'.
                    276:                    '<input type="radio" name="'.$context.'_'.$item.'" value="1" '.
                    277:                    $tool_on.'/>'.&mt('On').'</label>&nbsp;<label>'.
                    278:                    '<input type="radio" name="'.$context.'_'.$item.'" value="0" '.
                    279:                    $tool_off.'/>'.&mt('Off').'</label></span></td>'."\n".
                    280:                    &Apache::loncommon::end_data_table_row()."\n";
                    281:     }
                    282:     return $output;
                    283: }
                    284: 
1.295.2.3! raeburn   285: sub coursereq_externaluser {
        !           286:     my ($ccuname,$ccdomain,$cdom) = @_;
        !           287:     my (@usertools,@options,%validations,%userenv,$output);
        !           288:     my %lt = &Apache::lonlocal::texthash (
        !           289:                    'official'   => 'Can request creation of official courses',
        !           290:                    'unofficial' => 'Can request creation of unofficial courses',
        !           291:                    'community'  => 'Can request creation of communities',
        !           292:     );
        !           293: 
        !           294:     %userenv = &Apache::lonnet::userenvironment($ccdomain,$ccuname,
        !           295:                       'reqcrsotherdom.official','reqcrsotherdom.unofficial',
        !           296:                       'reqcrsotherdom.community');
        !           297:     @usertools = ('official','unofficial','community');
        !           298:     @options = ('approve','validate','autolimit');
        !           299:     %validations = &Apache::lonnet::auto_courserequest_checks($cdom);
        !           300:     my $optregex = join('|',@options);
        !           301:     my %reqtitles = &courserequest_titles();
        !           302:     foreach my $item (@usertools) {
        !           303:         my ($curroption,$currlimit,$tooloff);
        !           304:         if ($userenv{'reqcrsotherdom.'.$item} ne '') {
        !           305:             my @curr = split(',',$userenv{'reqcrsotherdom.'.$item});
        !           306:             if (grep(/^\Q$cdom\E:($optregex)=?(\d*)$/,@curr)) {
        !           307:                 $curroption = $1;
        !           308:                 $currlimit = $2;
        !           309:                 if (!$curroption) {
        !           310:                     $curroption = 'norequest';
        !           311:                 }
        !           312:             }
        !           313:         } else {
        !           314:             $curroption = 'norequest';
        !           315:             $tooloff = ' checked="checked"';
        !           316:         }
        !           317:         $output.= &Apache::loncommon::start_data_table_row()."\n".
        !           318:                   '  <td><span class="LC_nobreak">'.$lt{$item}.': '.
        !           319:                   '<label><input type="radio" name="reqcrsotherdom_'.$item.
        !           320:                   '" value="0"'.$tooloff.' />'.$reqtitles{'norequest'}.
        !           321:                   '</label>&nbsp;';
        !           322:         foreach my $option (@options) {
        !           323:             if ($option eq 'validate') {
        !           324:                 my $canvalidate = 0;
        !           325:                 if (ref($validations{$item}) eq 'HASH') {
        !           326:                     if ($validations{$item}{'_external_'}) {
        !           327:                         $canvalidate = 1;
        !           328:                     }
        !           329:                 }
        !           330:                 next if (!$canvalidate);
        !           331:             }
        !           332:             my $checked = '';
        !           333:             if ($option eq $curroption) {
        !           334:                 $checked = ' checked="checked"';
        !           335:             }
        !           336:             $output .= '<span class="LC_nobreak"><label>'.
        !           337:                        '<input type="radio" name="reqcrsotherdom_'.$item.
        !           338:                        '" value="'.$option.'"'.$checked.' />'.
        !           339:                        $reqtitles{$option}.'</label>&nbsp;';
        !           340:             if ($option eq 'autolimit') {
        !           341:                 $output .= '<input type="text" name="reqcrsotherdom_'.
        !           342:                            $item.'_limit" size="1" '.
        !           343:                            'value="'.$currlimit.'" />';
        !           344:             }
        !           345:             $output .= '&nbsp;'
        !           346:         }
        !           347:         $output .= '</span></td>'."\n".
        !           348:                    &Apache::loncommon::end_data_table_row()."\n";
        !           349:     }
        !           350:     return $output;
        !           351: }
        !           352: 
        !           353: sub courserequest_titles {
        !           354:     my %titles = &Apache::lonlocal::texthash (
        !           355:                                    official   => 'Official',                                   unofficial => 'Unofficial',
        !           356:                                    community  => 'Communities',                                   norequest  => 'Not allowed',
        !           357:                                    approve    => 'Approval by Dom. Coord.',
        !           358:                                    validate   => 'With validation',
        !           359:                                    autolimit  => 'Numerical limit',
        !           360:                  );
        !           361:     return %titles;   
        !           362: }                     
        !           363:     
        !           364: sub courserequest_display {
        !           365:     my %titles = &Apache::lonlocal::texthash (
        !           366:                                    approve    => 'Yes, need approval',
        !           367:                                    validate   => 'Yes, with validation',
        !           368:                                    norequest  => 'No',
        !           369:    );   
        !           370:    return %titles;
        !           371: }
        !           372: 
1.2       www       373: # =================================================================== Phase one
1.1       www       374: 
1.42      matthew   375: sub print_username_entry_form {
1.207     raeburn   376:     my ($r,$context,$response,$srch,$forcenewuser) = @_;
1.101     albertel  377:     my $defdom=$env{'request.role.domain'};
1.160     raeburn   378:     my $formtoset = 'crtuser';
                    379:     if (exists($env{'form.startrolename'})) {
                    380:         $formtoset = 'docustom';
                    381:         $env{'form.rolename'} = $env{'form.startrolename'};
1.207     raeburn   382:     } elsif ($env{'form.origform'} eq 'crtusername') {
                    383:         $formtoset =  $env{'form.origform'};
1.160     raeburn   384:     }
                    385: 
                    386:     my ($jsback,$elements) = &crumb_utilities();
                    387: 
                    388:     my $jscript = &Apache::loncommon::studentbrowser_javascript()."\n".
1.165     albertel  389:         '<script type="text/javascript">'."\n".
1.160     raeburn   390:         &Apache::lonhtmlcommon::set_form_elements($elements->{$formtoset}).
1.162     raeburn   391:         '</script>'."\n";
1.160     raeburn   392: 
                    393:     my %loaditems = (
                    394:                 'onload' => "javascript:setFormElements(document.$formtoset)",
                    395:                     );
1.229     raeburn   396:     my %breadcrumb_text = &singleuser_breadcrumb();
1.110     albertel  397:     my $start_page =
1.190     raeburn   398: 	&Apache::loncommon::start_page('User Management',
1.160     raeburn   399: 				       $jscript,{'add_entries' => \%loaditems,});
1.214     raeburn   400:     if ($env{'form.action'} eq 'custom') {
                    401:         &Apache::lonhtmlcommon::add_breadcrumb
                    402:           ({href=>"javascript:backPage(document.crtuser)",
                    403:             text=>"Pick custom role",});
                    404:     } else {
1.190     raeburn   405:         &Apache::lonhtmlcommon::add_breadcrumb
                    406:           ({href=>"javascript:backPage(document.crtuser)",
1.229     raeburn   407:             text=>$breadcrumb_text{'search'},
1.190     raeburn   408:             faq=>282,bug=>'Instructor Interface',});
                    409:     }
1.224     raeburn   410:     my $helpitem = 'Course_Change_Privileges';
                    411:     if ($env{'form.action'} eq 'custom') {
                    412:         $helpitem = 'Course_Editing_Custom_Roles';
                    413:     } elsif ($env{'form.action'} eq 'singlestudent') {
                    414:         $helpitem = 'Course_Add_Student';
                    415:     }
                    416:     my $crumbs = &Apache::lonhtmlcommon::breadcrumbs('User Management',
                    417:                                                      $helpitem);
1.190     raeburn   418:     my %existingroles=&Apache::lonuserutils::my_custom_roles();
1.59      www       419:     my $choice=&Apache::loncommon::select_form('make new role','rolename',
                    420: 		('make new role' => 'Generate new role ...',%existingroles));
1.71      sakharuk  421:     my %lt=&Apache::lonlocal::texthash(
1.229     raeburn   422:                     'srst' => 'Search for a user and enroll as a student',
                    423:                     'srad' => 'Search for a user and modify/add user information or roles',
1.71      sakharuk  424: 		    'usr'  => "Username",
                    425:                     'dom'  => "Domain",
                    426:                     'ecrp' => "Edit Custom Role Privileges",
1.72      sakharuk  427:                     'nr'   => "Name of Role",
1.282     schafran  428:                     'cre'  => "Next",
1.71      sakharuk  429: 				       );
1.190     raeburn   430:     $r->print($start_page."\n".$crumbs);
1.214     raeburn   431:     if ($env{'form.action'} eq 'custom') {
1.190     raeburn   432:         if (&Apache::lonnet::allowed('mcr','/')) {
                    433:             $r->print(<<ENDCUSTOM);
1.58      www       434: <form action="/adm/createuser" method="post" name="docustom">
1.190     raeburn   435: <input type="hidden" name="action" value="$env{'form.action'}" />
1.157     albertel  436: <input type="hidden" name="phase" value="selected_custom_edit" />
1.224     raeburn   437: <h3>$lt{'ecrp'}</h3>
1.282     schafran  438: $choice $lt{'nr'}: <input type="text" size="15" name="newrolename" /><br />
1.71      sakharuk  439: <input name="customeditor" type="submit" value="$lt{'cre'}" />
1.107     www       440: </form>
1.106     www       441: ENDCUSTOM
1.190     raeburn   442:         }
1.213     raeburn   443:     } else {
1.229     raeburn   444:         my $actiontext = $lt{'srad'};
1.213     raeburn   445:         if ($env{'form.action'} eq 'singlestudent') {
1.229     raeburn   446:             $actiontext = $lt{'srst'};
1.213     raeburn   447:         }
                    448:         $r->print("
1.229     raeburn   449: <h3>$actiontext</h3>");
1.213     raeburn   450:         if ($env{'form.origform'} ne 'crtusername') {
                    451:             $r->print("\n".$response);
                    452:         }
                    453:         $r->print(&entry_form($defdom,$srch,$forcenewuser,$context,$response));
1.107     www       454:     }
1.110     albertel  455:     $r->print(&Apache::loncommon::end_page());
                    456: }
                    457: 
1.160     raeburn   458: sub entry_form {
1.214     raeburn   459:     my ($dom,$srch,$forcenewuser,$context,$responsemsg) = @_;
1.207     raeburn   460:     my %domconf = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
1.229     raeburn   461:     my ($usertype,$inexact);
1.214     raeburn   462:     if (ref($srch) eq 'HASH') {
                    463:         if (($srch->{'srchin'} eq 'dom') &&
                    464:             ($srch->{'srchby'} eq 'uname') &&
                    465:             ($srch->{'srchtype'} eq 'exact') &&
                    466:             ($srch->{'srchdomain'} ne '') &&
                    467:             ($srch->{'srchterm'} ne '')) {
                    468:             my ($rules,$ruleorder) =
                    469:                 &Apache::lonnet::inst_userrules($srch->{'srchdomain'},'username');
                    470:             $usertype = &Apache::lonuserutils::check_usertype($srch->{'srchdomain'},$srch->{'srchterm'},$rules);
1.229     raeburn   471:         } else {
                    472:             $inexact = 1;
1.214     raeburn   473:         }
1.207     raeburn   474:     }
1.214     raeburn   475:     my $cancreate =
                    476:         &Apache::lonuserutils::can_create_user($dom,$context,$usertype);
1.160     raeburn   477:     my $userpicker = 
1.179     raeburn   478:        &Apache::loncommon::user_picker($dom,$srch,$forcenewuser,
1.214     raeburn   479:                                        'document.crtuser',$cancreate,$usertype);
1.160     raeburn   480:     my $srchbutton = &mt('Search');
1.229     raeburn   481:     if ($env{'form.action'} eq 'singlestudent') {
                    482:         $srchbutton = &mt('Search and Enroll');
                    483:     } elsif ($cancreate && $responsemsg ne '' && $inexact) {
                    484:         $srchbutton = &mt('Search or Add New User');
                    485:     }
1.207     raeburn   486:     my $output = <<"ENDBLOCK";
1.160     raeburn   487: <form action="/adm/createuser" method="post" name="crtuser">
1.190     raeburn   488: <input type="hidden" name="action" value="$env{'form.action'}" />
1.160     raeburn   489: <input type="hidden" name="phase" value="get_user_info" />
                    490: $userpicker
1.179     raeburn   491: <input name="userrole" type="button" value="$srchbutton" onclick="javascript:validateEntry(document.crtuser)" />
1.160     raeburn   492: </form>
1.207     raeburn   493: ENDBLOCK
1.229     raeburn   494:     if ($env{'form.phase'} eq '') {
1.207     raeburn   495:         my $defdom=$env{'request.role.domain'};
                    496:         my $domform = &Apache::loncommon::select_dom_form($defdom,'srchdomain');
                    497:         my %lt=&Apache::lonlocal::texthash(
1.229     raeburn   498:                   'enro' => 'Enroll one student',
                    499:                   'admo' => 'Add/modify a single user',
                    500:                   'crea' => 'create new user if required',
                    501:                   'uskn' => "username is known",
1.207     raeburn   502:                   'crnu' => 'Create a new user',
                    503:                   'usr'  => 'Username',
                    504:                   'dom'  => 'in domain',
1.229     raeburn   505:                   'enrl' => 'Enroll',
                    506:                   'cram'  => 'Create/Modify user',
1.207     raeburn   507:         );
1.229     raeburn   508:         my $sellink=&Apache::loncommon::selectstudent_link('crtusername','srchterm','srchdomain');
                    509:         my ($title,$buttontext,$showresponse);
                    510:         if ($env{'form.action'} eq 'singlestudent') {   
                    511:             $title = $lt{'enro'};
                    512:             $buttontext = $lt{'enrl'};
                    513:         } else {
                    514:             $title = $lt{'admo'};
                    515:             $buttontext = $lt{'cram'};
                    516:         }
                    517:         if ($cancreate) {
                    518:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'crea'}.')</span>';
                    519:         } else {
                    520:             $title .= ' <span class="LC_cusr_subheading">('.$lt{'uskn'}.')</span>';
                    521:         }
                    522:         if ($env{'form.origform'} eq 'crtusername') {
                    523:             $showresponse = $responsemsg;
                    524:         }
1.207     raeburn   525:         $output .= <<"ENDDOCUMENT";
1.229     raeburn   526: <br />
1.207     raeburn   527: <form action="/adm/createuser" method="post" name="crtusername">
                    528: <input type="hidden" name="action" value="$env{'form.action'}" />
                    529: <input type="hidden" name="phase" value="createnewuser" />
                    530: <input type="hidden" name="srchtype" value="exact" />
1.233     raeburn   531: <input type="hidden" name="srchby" value="uname" />
1.207     raeburn   532: <input type="hidden" name="srchin" value="dom" />
                    533: <input type="hidden" name="forcenewuser" value="1" />
                    534: <input type="hidden" name="origform" value="crtusername" />
1.229     raeburn   535: <h3>$title</h3>
                    536: $showresponse
1.207     raeburn   537: <table>
                    538:  <tr>
                    539:   <td>$lt{'usr'}:</td>
                    540:   <td><input type="text" size="15" name="srchterm" /></td>
                    541:   <td>&nbsp;$lt{'dom'}:</td><td>$domform</td>
1.229     raeburn   542:   <td>&nbsp;$sellink&nbsp;</td>
                    543:   <td>&nbsp;<input name="userrole" type="submit" value="$buttontext" /></td>
1.207     raeburn   544:  </tr>
                    545: </table>
                    546: </form>
1.160     raeburn   547: ENDDOCUMENT
1.207     raeburn   548:     }
1.160     raeburn   549:     return $output;
                    550: }
1.110     albertel  551: 
                    552: sub user_modification_js {
1.113     raeburn   553:     my ($pjump_def,$dc_setcourse_code,$nondc_setsection_code,$groupslist)=@_;
                    554:     
1.110     albertel  555:     return <<END;
                    556: <script type="text/javascript" language="Javascript">
                    557: 
                    558:     function pclose() {
                    559:         parmwin=window.open("/adm/rat/empty.html","LONCAPAparms",
                    560:                  "height=350,width=350,scrollbars=no,menubar=no");
                    561:         parmwin.close();
                    562:     }
                    563: 
                    564:     $pjump_def
                    565:     $dc_setcourse_code
                    566: 
                    567:     function dateset() {
                    568:         eval("document.cu."+document.cu.pres_marker.value+
                    569:             ".value=document.cu.pres_value.value");
                    570:         pclose();
                    571:     }
                    572: 
1.113     raeburn   573:     $nondc_setsection_code
                    574: 
1.110     albertel  575: </script>
                    576: END
1.2       www       577: }
                    578: 
                    579: # =================================================================== Phase two
1.160     raeburn   580: sub print_user_selection_page {
1.229     raeburn   581:     my ($r,$response,$srch,$srch_results,$srcharray,$context) = @_;
1.160     raeburn   582:     my @fields = ('username','domain','lastname','firstname','permanentemail');
                    583:     my $sortby = $env{'form.sortby'};
                    584: 
                    585:     if (!grep(/^\Q$sortby\E$/,@fields)) {
                    586:         $sortby = 'lastname';
                    587:     }
                    588: 
                    589:     my ($jsback,$elements) = &crumb_utilities();
                    590: 
                    591:     my $jscript = (<<ENDSCRIPT);
                    592: <script type="text/javascript">
                    593: function pickuser(uname,udom) {
                    594:     document.usersrchform.seluname.value=uname;
                    595:     document.usersrchform.seludom.value=udom;
                    596:     document.usersrchform.phase.value="userpicked";
                    597:     document.usersrchform.submit();
                    598: }
                    599: 
                    600: $jsback
                    601: </script>
                    602: ENDSCRIPT
                    603: 
                    604:     my %lt=&Apache::lonlocal::texthash(
1.179     raeburn   605:                                        'usrch'          => "User Search to add/modify roles",
                    606:                                        'stusrch'        => "User Search to enroll student",
                    607:                                        'usel'           => "Select a user to add/modify roles",
                    608:                                        'stusel'         => "Select a user to enroll as a student", 
1.160     raeburn   609:                                        'username'       => "username",
                    610:                                        'domain'         => "domain",
                    611:                                        'lastname'       => "last name",
                    612:                                        'firstname'      => "first name",
                    613:                                        'permanentemail' => "permanent e-mail",
                    614:                                       );
1.214     raeburn   615:     $r->print(&Apache::loncommon::start_page('User Management',$jscript));
1.229     raeburn   616: 
                    617:     my %breadcrumb_text = &singleuser_breadcrumb();
                    618:     &Apache::lonhtmlcommon::add_breadcrumb
                    619:         ({href=>"javascript:backPage(document.usersrchform,'','')",
                    620:           text=>$breadcrumb_text{'search'},
                    621:           faq=>282,bug=>'Instructor Interface',},
                    622:          {href=>"javascript:backPage(document.usersrchform,'get_user_info','select')",
                    623:           text=>$breadcrumb_text{'userpicked'},
                    624:           faq=>282,bug=>'Instructor Interface',});
                    625:     if ($env{'form.action'} eq 'singleuser') {
1.224     raeburn   626:         $r->print(&Apache::lonhtmlcommon::breadcrumbs('User Management',
                    627:                                                       'Course_Change_Privileges'));
1.179     raeburn   628:         $r->print("<b>$lt{'usrch'}</b><br />");
1.207     raeburn   629:         $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context));
1.179     raeburn   630:         $r->print('<h3>'.$lt{'usel'}.'</h3>');
1.229     raeburn   631:     } elsif ($env{'form.action'} eq 'singlestudent') {
1.224     raeburn   632:         $r->print(&Apache::lonhtmlcommon::breadcrumbs('User Management',
                    633:                                                       'Course_Add_Student'));
1.179     raeburn   634:         $r->print($jscript."<b>$lt{'stusrch'}</b><br />");
1.214     raeburn   635:         $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context));
1.179     raeburn   636:         $r->print('</form><h3>'.$lt{'stusel'}.'</h3>');
                    637:     }
1.160     raeburn   638:     $r->print('<form name="usersrchform" method="post">'.
                    639:               &Apache::loncommon::start_data_table()."\n".
                    640:               &Apache::loncommon::start_data_table_header_row()."\n".
                    641:               ' <th> </th>'."\n");
                    642:     foreach my $field (@fields) {
                    643:         $r->print(' <th><a href="javascript:document.usersrchform.sortby.value='.
                    644:                   "'".$field."'".';document.usersrchform.submit();">'.
                    645:                   $lt{$field}.'</a></th>'."\n");
                    646:     }
                    647:     $r->print(&Apache::loncommon::end_data_table_header_row());
                    648: 
                    649:     my @sorted_users = sort {
1.167     albertel  650:         lc($srch_results->{$a}->{$sortby})   cmp lc($srch_results->{$b}->{$sortby})
1.160     raeburn   651:             ||
1.167     albertel  652:         lc($srch_results->{$a}->{lastname})  cmp lc($srch_results->{$b}->{lastname})
1.160     raeburn   653:             ||
                    654:         lc($srch_results->{$a}->{firstname}) cmp lc($srch_results->{$b}->{firstname})
1.167     albertel  655: 	    ||
                    656: 	lc($a) cmp lc($b)
1.160     raeburn   657:         } (keys(%$srch_results));
                    658: 
                    659:     foreach my $user (@sorted_users) {
                    660:         my ($uname,$udom) = split(/:/,$user);
                    661:         $r->print(&Apache::loncommon::start_data_table_row().
                    662:                   '<td><input type="button" name="seluser" value="'.&mt('Select').'" onclick="javascript:pickuser('."'".$uname."'".','."'".$udom."'".')" /></td>'.
                    663:                   '<td><tt>'.$uname.'</tt></td>'.
                    664:                   '<td><tt>'.$udom.'</tt></td>');
                    665:         foreach my $field ('lastname','firstname','permanentemail') {
                    666:             $r->print('<td>'.$srch_results->{$user}->{$field}.'</td>');
                    667:         }
                    668:         $r->print(&Apache::loncommon::end_data_table_row());
                    669:     }
                    670:     $r->print(&Apache::loncommon::end_data_table().'<br /><br />');
1.179     raeburn   671:     if (ref($srcharray) eq 'ARRAY') {
                    672:         foreach my $item (@{$srcharray}) {
                    673:             $r->print('<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n");
                    674:         }
                    675:     }
1.160     raeburn   676:     $r->print(' <input type="hidden" name="sortby" value="'.$sortby.'" />'."\n".
                    677:               ' <input type="hidden" name="seluname" value="" />'."\n".
                    678:               ' <input type="hidden" name="seludom" value="" />'."\n".
1.179     raeburn   679:               ' <input type="hidden" name="currstate" value="select" />'."\n".
1.190     raeburn   680:               ' <input type="hidden" name="phase" value="get_user_info" />'."\n".
1.214     raeburn   681:               ' <input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n");
                    682:     $r->print($response.'</form>'.&Apache::loncommon::end_page());
1.160     raeburn   683: }
                    684: 
                    685: sub print_user_query_page {
1.179     raeburn   686:     my ($r,$caller) = @_;
1.160     raeburn   687: # FIXME - this is for a network-wide name search (similar to catalog search)
                    688: # To use frames with similar behavior to catalog/portfolio search.
                    689: # To be implemented. 
                    690:     return;
                    691: }
                    692: 
1.42      matthew   693: sub print_user_modification_page {
1.215     raeburn   694:     my ($r,$ccuname,$ccdomain,$srch,$response,$context,$permission) = @_;
1.185     raeburn   695:     if (($ccuname eq '') || ($ccdomain eq '')) {
1.215     raeburn   696:         my $usermsg = &mt('No username and/or domain provided.');
                    697:         $env{'form.phase'} = '';
1.207     raeburn   698: 	&print_username_entry_form($r,$context,$usermsg);
1.58      www       699:         return;
                    700:     }
1.213     raeburn   701:     my ($form,$formname);
                    702:     if ($env{'form.action'} eq 'singlestudent') {
                    703:         $form = 'document.enrollstudent';
                    704:         $formname = 'enrollstudent';
                    705:     } else {
                    706:         $form = 'document.cu';
                    707:         $formname = 'cu';
                    708:     }
1.188     raeburn   709:     my %abv_auth = &auth_abbrev();
1.227     raeburn   710:     my (%rulematch,%inst_results,$newuser,%alerts,%curr_rules,%got_rules);
1.185     raeburn   711:     my $uhome=&Apache::lonnet::homeserver($ccuname,$ccdomain);
                    712:     if ($uhome eq 'no_host') {
1.215     raeburn   713:         my $usertype;
                    714:         my ($rules,$ruleorder) =
                    715:             &Apache::lonnet::inst_userrules($ccdomain,'username');
                    716:             $usertype =
                    717:                 &Apache::lonuserutils::check_usertype($ccdomain,$ccuname,$rules);
                    718:         my $cancreate =
                    719:             &Apache::lonuserutils::can_create_user($ccdomain,$context,
                    720:                                                    $usertype);
                    721:         if (!$cancreate) {
1.292     bisitz    722:             my $helplink = 'javascript:helpMenu('."'display'".')';
1.215     raeburn   723:             my %usertypetext = (
                    724:                 official   => 'institutional',
                    725:                 unofficial => 'non-institutional',
                    726:             );
                    727:             my $response;
                    728:             if ($env{'form.origform'} eq 'crtusername') {
                    729:                 $response =  '<span class="LC_warning">'.&mt('No match was found for the username ([_1]) in LON-CAPA domain: [_2]',$ccuname,$ccdomain).
                    730:                             '</span><br />';
                    731:             }
1.292     bisitz    732:             $response .= '<p class="LC_warning">'
                    733:                         .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                    734:                         .' '
                    735:                         .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                    736:                             ,'<a href="'.$helplink.'">','</a>')
                    737:                         .'</p><br />';
1.215     raeburn   738:             $env{'form.phase'} = '';
                    739:             &print_username_entry_form($r,$context,$response);
                    740:             return;
                    741:         }
1.188     raeburn   742:         $newuser = 1;
1.193     raeburn   743:         my $checkhash;
                    744:         my $checks = { 'username' => 1 };
1.196     raeburn   745:         $checkhash->{$ccuname.':'.$ccdomain} = { 'newuser' => $newuser };
1.193     raeburn   746:         &Apache::loncommon::user_rule_check($checkhash,$checks,
1.196     raeburn   747:             \%alerts,\%rulematch,\%inst_results,\%curr_rules,\%got_rules);
                    748:         if (ref($alerts{'username'}) eq 'HASH') {
                    749:             if (ref($alerts{'username'}{$ccdomain}) eq 'HASH') {
                    750:                 my $domdesc =
1.193     raeburn   751:                     &Apache::lonnet::domain($ccdomain,'description');
1.196     raeburn   752:                 if ($alerts{'username'}{$ccdomain}{$ccuname}) {
                    753:                     my $userchkmsg;
                    754:                     if (ref($curr_rules{$ccdomain}) eq 'HASH') {  
                    755:                         $userchkmsg = 
                    756:                             &Apache::loncommon::instrule_disallow_msg('username',
1.193     raeburn   757:                                                                  $domdesc,1).
                    758:                         &Apache::loncommon::user_rule_formats($ccdomain,
                    759:                             $domdesc,$curr_rules{$ccdomain}{'username'},
                    760:                             'username');
1.196     raeburn   761:                     }
1.215     raeburn   762:                     $env{'form.phase'} = '';
1.207     raeburn   763:                     &print_username_entry_form($r,$context,$userchkmsg);
1.196     raeburn   764:                     return;
1.215     raeburn   765:                 }
1.193     raeburn   766:             }
1.185     raeburn   767:         }
1.187     raeburn   768:     } else {
1.188     raeburn   769:         $newuser = 0;
1.185     raeburn   770:     }
1.160     raeburn   771:     if ($response) {
1.215     raeburn   772:         $response = '<br />'.$response;
1.160     raeburn   773:     }
1.149     raeburn   774: 
1.52      matthew   775:     my $pjump_def = &Apache::lonhtmlcommon::pjump_javascript_definition();
1.88      raeburn   776:     my $dc_setcourse_code = '';
1.119     raeburn   777:     my $nondc_setsection_code = '';                                        
1.112     albertel  778:     my %loaditem;
1.114     albertel  779: 
1.216     raeburn   780:     my $groupslist = &Apache::lonuserutils::get_groupslist();
1.88      raeburn   781: 
1.216     raeburn   782:     my $js = &validation_javascript($context,$ccdomain,$pjump_def,
                    783:                                $groupslist,$newuser,$formname,\%loaditem);
1.233     raeburn   784:     my $args = {'add_entries' => \%loaditem};  
                    785:     if ($env{'form.popup'}) {
                    786:        $args->{'no_nav_bar'} = 1; 
                    787:     }
1.110     albertel  788:     my $start_page = 
1.233     raeburn   789: 	&Apache::loncommon::start_page('User Management',$js,$args);
1.216     raeburn   790:     my %breadcrumb_text = &singleuser_breadcrumb();
1.160     raeburn   791:     &Apache::lonhtmlcommon::add_breadcrumb
1.216     raeburn   792:      ({href=>"javascript:backPage($form)",
                    793:        text=>$breadcrumb_text{'search'},
1.160     raeburn   794:        faq=>282,bug=>'Instructor Interface',});
                    795: 
                    796:     if ($env{'form.phase'} eq 'userpicked') {
                    797:         &Apache::lonhtmlcommon::add_breadcrumb
1.216     raeburn   798:      ({href=>"javascript:backPage($form,'get_user_info','select')",
                    799:        text=>$breadcrumb_text{'userpicked'},
1.160     raeburn   800:        faq=>282,bug=>'Instructor Interface',});
                    801:     }
                    802:     &Apache::lonhtmlcommon::add_breadcrumb
1.216     raeburn   803:       ({href=>"javascript:backPage($form,'$env{'form.phase'}','modify')",
                    804:         text=>$breadcrumb_text{'modify'},
1.160     raeburn   805:         faq=>282,bug=>'Instructor Interface',});
1.224     raeburn   806:     my $helpitem = 'Course_Change_Privileges';
                    807:     if ($env{'form.action'} eq 'singlestudent') {
                    808:         $helpitem = 'Course_Add_Student';
                    809:     }
                    810:     my $crumbs = &Apache::lonhtmlcommon::breadcrumbs('User Management',
                    811:                                                      $helpitem);
1.3       www       812: 
1.25      matthew   813:     my $forminfo =<<"ENDFORMINFO";
1.216     raeburn   814: <form action="/adm/createuser" method="post" name="$formname">
1.190     raeburn   815: <input type="hidden" name="phase" value="update_user_data" />
1.188     raeburn   816: <input type="hidden" name="ccuname" value="$ccuname" />
                    817: <input type="hidden" name="ccdomain" value="$ccdomain" />
1.157     albertel  818: <input type="hidden" name="pres_value"  value="" />
                    819: <input type="hidden" name="pres_type"   value="" />
                    820: <input type="hidden" name="pres_marker" value="" />
1.25      matthew   821: ENDFORMINFO
1.2       www       822:     my %inccourses;
1.135     raeburn   823:     foreach my $key (keys(%env)) {
1.139     albertel  824: 	if ($key=~/^user\.priv\.cm\.\/($match_domain)\/($match_username)/) {
1.2       www       825: 	    $inccourses{$1.'_'.$2}=1;
                    826:         }
1.24      matthew   827:     }
1.216     raeburn   828:     if ($newuser) {
1.134     raeburn   829:         my $portfolioform;
1.267     raeburn   830:         if ((&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) ||
                    831:             (&Apache::lonnet::allowed('mut',$env{'request.role.domain'}))) {
                    832:             # Current user has quota or user tools modification privileges
1.188     raeburn   833:             $portfolioform = '<br />'.&portfolio_quota($ccuname,$ccdomain);
1.134     raeburn   834:         }
1.227     raeburn   835:         &initialize_authen_forms($ccdomain,$formname);
1.188     raeburn   836:         my %lt=&Apache::lonlocal::texthash(
                    837:                 'cnu'            => 'Create New User',
1.213     raeburn   838:                 'ast'            => 'as a student',
1.188     raeburn   839:                 'ind'            => 'in domain',
                    840:                 'lg'             => 'Login Data',
1.190     raeburn   841:                 'hs'             => "Home Server",
1.188     raeburn   842:         );
1.185     raeburn   843: 	$r->print(<<ENDTITLE);
1.110     albertel  844: $start_page
1.160     raeburn   845: $crumbs
                    846: $response
1.25      matthew   847: $forminfo
1.31      matthew   848: <script type="text/javascript" language="Javascript">
1.20      harris41  849: $loginscript
1.31      matthew   850: </script>
1.20      harris41  851: <input type='hidden' name='makeuser' value='1' />
1.216     raeburn   852: <h2>$lt{'cnu'} "$ccuname" $lt{'ind'} $ccdomain
1.185     raeburn   853: ENDTITLE
1.213     raeburn   854:         if ($env{'form.action'} eq 'singlestudent') {
                    855:             $r->print(' ('.$lt{'ast'}.')');
                    856:         }
                    857:         $r->print('</h2>'."\n".'<div class="LC_left_float">');
1.206     raeburn   858:         my $personal_table = 
1.210     raeburn   859:             &personal_data_display($ccuname,$ccdomain,$newuser,$context,
                    860:                                    $inst_results{$ccuname.':'.$ccdomain});
1.206     raeburn   861:         $r->print($personal_table);
1.187     raeburn   862:         my ($home_server_pick,$numlib) = 
                    863:             &Apache::loncommon::home_server_form_item($ccdomain,'hserver',
                    864:                                                       'default','hide');
                    865:         if ($numlib > 1) {
                    866:             $r->print("
1.185     raeburn   867: <br />
1.187     raeburn   868: $lt{'hs'}: $home_server_pick
                    869: <br />");
                    870:         } else {
                    871:             $r->print($home_server_pick);
                    872:         }
1.188     raeburn   873:         $r->print('</div>'."\n".'<div class="LC_left_float"><h3>'.
                    874:                   $lt{'lg'}.'</h3>');
1.185     raeburn   875:         my ($fixedauth,$varauth,$authmsg); 
1.193     raeburn   876:         if (ref($rulematch{$ccuname.':'.$ccdomain}) eq 'HASH') {
                    877:             my $matchedrule = $rulematch{$ccuname.':'.$ccdomain}{'username'};
                    878:             my ($rules,$ruleorder) = 
                    879:                 &Apache::lonnet::inst_userrules($ccdomain,'username');
1.185     raeburn   880:             if (ref($rules) eq 'HASH') {
1.193     raeburn   881:                 if (ref($rules->{$matchedrule}) eq 'HASH') {
                    882:                     my $authtype = $rules->{$matchedrule}{'authtype'};
1.185     raeburn   883:                     if ($authtype !~ /^(krb4|krb5|int|fsys|loc)$/) {
1.190     raeburn   884:                         $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
1.275     raeburn   885:                     } else { 
1.193     raeburn   886:                         my $authparm = $rules->{$matchedrule}{'authparm'};
1.273     raeburn   887:                         $authmsg = $rules->{$matchedrule}{'authmsg'};
1.185     raeburn   888:                         if ($authtype =~ /^krb(4|5)$/) {
                    889:                             my $ver = $1;
                    890:                             if ($authparm ne '') {
                    891:                                 $fixedauth = <<"KERB"; 
                    892: <input type="hidden" name="login" value="krb" />
                    893: <input type="hidden" name="krbver" value="$ver" />
                    894: <input type="hidden" name="krbarg" value="$authparm" />
                    895: KERB
                    896:                             }
                    897:                         } else {
                    898:                             $fixedauth = 
                    899: '<input type="hidden" name="login" value="'.$authtype.'" />'."\n";
1.193     raeburn   900:                             if ($rules->{$matchedrule}{'authparmfixed'}) {
1.185     raeburn   901:                                 $fixedauth .=    
                    902: '<input type="hidden" name="'.$authtype.'arg" value="'.$authparm.'" />'."\n";
                    903:                             } else {
1.273     raeburn   904:                                 if ($authtype eq 'int') {
                    905:                                     $varauth = '<br />'.
                    906: &mt('[_1] Internally authenticated (with initial password [_2])','','<input type="password" size="10" name="intarg" value="" />')."<label><input type=\"checkbox\" name=\"visible\" onClick='if (this.checked) { this.form.intarg.type=\"text\" } else { this.form.intarg.type=\"password\" }' />".&mt('Visible input').'</label>';
                    907:                                 } elsif ($authtype eq 'loc') {
                    908:                                     $varauth = '<br />'.
                    909: &mt('[_1] Local Authentication with argument [_2]','','<input type="text" name="'.$authtype.'arg" value="" />')."\n";
                    910:                                 } else {
                    911:                                     $varauth =
1.185     raeburn   912: '<input type="text" name="'.$authtype.'arg" value="" />'."\n";
1.273     raeburn   913:                                 }
1.185     raeburn   914:                             }
                    915:                         }
                    916:                     }
                    917:                 } else {
1.190     raeburn   918:                     $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
1.185     raeburn   919:                 }
                    920:             }
                    921:             if ($authmsg) {
                    922:                 $r->print(<<ENDAUTH);
                    923: $fixedauth
                    924: $authmsg
                    925: $varauth
                    926: ENDAUTH
                    927:             }
                    928:         } else {
1.190     raeburn   929:             $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc)); 
1.187     raeburn   930:         }
1.215     raeburn   931:         $r->print($portfolioform);
                    932:         if ($env{'form.action'} eq 'singlestudent') {
                    933:             $r->print(&date_sections_select($context,$newuser,$formname,
                    934:                                             $permission));
                    935:         }
                    936:         $r->print('</div><div class="LC_clear_float_footer"></div>');
1.216     raeburn   937:     } else { # user already exists
1.79      albertel  938: 	my %lt=&Apache::lonlocal::texthash(
1.191     raeburn   939:                     'cup'  => "Modify existing user: ",
1.213     raeburn   940:                     'ens'  => "Enroll one student: ",
1.72      sakharuk  941:                     'id'   => "in domain",
                    942: 				       );
1.26      matthew   943: 	$r->print(<<ENDCHANGEUSER);
1.110     albertel  944: $start_page
1.160     raeburn   945: $crumbs
1.25      matthew   946: $forminfo
1.213     raeburn   947: <h2>
1.26      matthew   948: ENDCHANGEUSER
1.213     raeburn   949:         if ($env{'form.action'} eq 'singlestudent') {
                    950:             $r->print($lt{'ens'});
                    951:         } else {
                    952:             $r->print($lt{'cup'});
                    953:         }
                    954:         $r->print(' "'.$ccuname.'" '.$lt{'id'}.' "'.$ccdomain.'"</h2>'.
                    955:                   "\n".'<div class="LC_left_float">');
1.206     raeburn   956:         my ($personal_table,$showforceid) = 
1.210     raeburn   957:             &personal_data_display($ccuname,$ccdomain,$newuser,$context,
                    958:                                    $inst_results{$ccuname.':'.$ccdomain});
1.206     raeburn   959:         $r->print($personal_table);
                    960:         if ($showforceid) {
1.203     raeburn   961:             $r->print(&Apache::lonuserutils::forceid_change($context));
1.199     raeburn   962:         }
1.275     raeburn   963:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
                    964:             $r->print('<h3>'.&mt('User Can Request Creation of Courses?').'</h3>'.
1.295.2.3! raeburn   965:                       &Apache::loncommon::start_data_table()).
        !           966:             if ($env{'request.role.domain'} eq $ccdomain) {
        !           967:                 $r->print(&build_tools_display($ccuname,$ccdomain,'requestcourses'));
        !           968:             } else {
        !           969:                 $r->print(&coursereq_externaluser($ccuname,$ccdomain,
        !           970:                                                   $env{'request.role.domain'}));
        !           971:             }
        !           972:             $r->print(&Apache::loncommon::end_data_table());
1.275     raeburn   973:         }
1.199     raeburn   974:         $r->print('</div>');
1.227     raeburn   975:         my $user_auth_text =  &user_authentication($ccuname,$ccdomain,$formname);
1.275     raeburn   976:         my ($user_quota_text,$user_tools_text,$user_reqcrs_text);
1.267     raeburn   977:         if ((&Apache::lonnet::allowed('mpq',$ccdomain)) ||
                    978:             (&Apache::lonnet::allowed('mut',$ccdomain))) {
1.188     raeburn   979:             # Current user has quota modification privileges
                    980:             $user_quota_text = &portfolio_quota($ccuname,$ccdomain);
1.267     raeburn   981:         }
                    982:         if (!&Apache::lonnet::allowed('mpq',$ccdomain)) {
                    983:             if (&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) {
                    984:                 # Get the user's portfolio information
                    985:                 my %portq = &Apache::lonnet::get('environment',['portfolioquota'],
                    986:                                                  $ccdomain,$ccuname);
                    987:                 my %lt=&Apache::lonlocal::texthash(
                    988:                     'dska'  => "Disk space allocated to user's portfolio files",
                    989:                     'youd'  => "You do not have privileges to modify the portfolio quota for this user.",
                    990:                     'ichr'  => "If a change is required, contact a domain coordinator for the domain",
                    991:                 );
                    992:                 $user_quota_text = <<ENDNOPORTPRIV;
1.188     raeburn   993: <h3>$lt{'dska'}</h3>
                    994: $lt{'youd'} $lt{'ichr'}: $ccdomain
                    995: ENDNOPORTPRIV
1.267     raeburn   996:             }
                    997:         }
                    998:         if (!&Apache::lonnet::allowed('mut',$ccdomain)) {
                    999:             if (&Apache::lonnet::allowed('mut',$env{'request.role.domain'})) {
                   1000:                 my %lt=&Apache::lonlocal::texthash(
                   1001:                     'utav'  => "User Tools Availability",
1.285     weissno  1002:                     'yodo'  => "You do not have privileges to modify Portfolio, Blog or Personal Information Page settings for this user.",
1.267     raeburn  1003:                     'ifch'  => "If a change is required, contact a domain coordinator for the domain",
                   1004:                 );
                   1005:                 $user_tools_text = <<ENDNOTOOLSPRIV;
                   1006: <h3>$lt{'utav'}</h3>
                   1007: $lt{'yodo'} $lt{'ifch'}: $ccdomain
                   1008: ENDNOTOOLSPRIV
                   1009:             }
1.188     raeburn  1010:         }
                   1011:         if ($user_auth_text ne '') {
                   1012:             $r->print('<div class="LC_left_float">'.$user_auth_text);
                   1013:             if ($user_quota_text ne '') {
                   1014:                 $r->print($user_quota_text);
                   1015:             }
1.267     raeburn  1016:             if ($user_tools_text ne '') {
                   1017:                 $r->print($user_tools_text);
                   1018:             }
1.213     raeburn  1019:             if ($env{'form.action'} eq 'singlestudent') {
                   1020:                 $r->print(&date_sections_select($context,$newuser,$formname));
                   1021:             }
1.188     raeburn  1022:         } elsif ($user_quota_text ne '') {
1.213     raeburn  1023:             $r->print('<div class="LC_left_float">'.$user_quota_text);
1.267     raeburn  1024:             if ($user_tools_text ne '') {
                   1025:                 $r->print($user_tools_text);
                   1026:             }
                   1027:             if ($env{'form.action'} eq 'singlestudent') {
                   1028:                 $r->print(&date_sections_select($context,$newuser,$formname));
                   1029:             }
                   1030:         } elsif ($user_tools_text ne '') {
                   1031:             $r->print('<div class="LC_left_float">'.$user_tools_text);
1.213     raeburn  1032:             if ($env{'form.action'} eq 'singlestudent') {
                   1033:                 $r->print(&date_sections_select($context,$newuser,$formname));
                   1034:             }
                   1035:         } else {
                   1036:             if ($env{'form.action'} eq 'singlestudent') {
                   1037:                 $r->print('<div class="LC_left_float">'.
                   1038:                           &date_sections_select($context,$newuser,$formname));
                   1039:             }
1.188     raeburn  1040:         }
1.213     raeburn  1041:         $r->print('</div><div class="LC_clear_float_footer"></div>');
1.217     raeburn  1042:         if ($env{'form.action'} ne 'singlestudent') {
                   1043:             &display_existing_roles($r,$ccuname,$ccdomain,\%inccourses);
                   1044:         }
1.25      matthew  1045:     } ## End of new user/old user logic
1.218     raeburn  1046: 
                   1047:     if ($env{'form.action'} eq 'singlestudent') {
                   1048:         $r->print('<br /><input type="button" value="'.&mt('Enroll Student').'" onClick="setSections(this.form)" />'."\n");
                   1049:     } else {
                   1050:         $r->print('<h3>'.&mt('Add Roles').'</h3>');
                   1051:         my $addrolesdisplay = 0;
                   1052:         if ($context eq 'domain' || $context eq 'author') {
                   1053:             $addrolesdisplay = &new_coauthor_roles($r,$ccuname,$ccdomain);
                   1054:         }
                   1055:         if ($context eq 'domain') {
                   1056:             my $add_domainroles = &new_domain_roles($r);
                   1057:             if (!$addrolesdisplay) {
                   1058:                 $addrolesdisplay = $add_domainroles;
1.2       www      1059:             }
1.218     raeburn  1060:             $r->print(&course_level_dc($env{'request.role.domain'},'Course'));
1.262     schafran 1061:             $r->print('<br /><input type="button" value="'.&mt('Save').'" onClick="setCourse()" />'."\n");
1.218     raeburn  1062:         } elsif ($context eq 'author') {
                   1063:             if ($addrolesdisplay) {
1.262     schafran 1064:                 $r->print('<br /><input type="button" value="'.&mt('Save').'"');
1.218     raeburn  1065:                 if ($newuser) {
1.227     raeburn  1066:                     $r->print(' onClick="auth_check()" \>'."\n");
1.218     raeburn  1067:                 } else {
                   1068:                     $r->print('onClick="this.form.submit()" \>'."\n");
                   1069:                 }
1.188     raeburn  1070:             } else {
1.218     raeburn  1071:                 $r->print('<br /><a href="javascript:backPage(document.cu)">'.
                   1072:                           &mt('Back to previous page').'</a>');
1.188     raeburn  1073:             }
                   1074:         } else {
1.218     raeburn  1075:             $r->print(&course_level_table(%inccourses));
1.262     schafran 1076:             $r->print('<br /><input type="button" value="'.&mt('Save').'" onClick="setSections(this.form)" />'."\n");
1.188     raeburn  1077:         }
1.88      raeburn  1078:     }
1.188     raeburn  1079:     $r->print(&Apache::lonhtmlcommon::echo_form_input(['phase','userrole','ccdomain','prevphase','currstate','ccuname','ccdomain']));
1.179     raeburn  1080:     $r->print('<input type="hidden" name="currstate" value="" />');
1.160     raeburn  1081:     $r->print('<input type="hidden" name="prevphase" value="'.$env{'form.phase'}.'" />');
1.110     albertel 1082:     $r->print("</form>".&Apache::loncommon::end_page());
1.218     raeburn  1083:     return;
1.2       www      1084: }
1.1       www      1085: 
1.213     raeburn  1086: sub singleuser_breadcrumb {
                   1087:     my %breadcrumb_text;
                   1088:     if ($env{'form.action'} eq 'singlestudent') {
                   1089:         $breadcrumb_text{'search'} = 'Enroll a student';
                   1090:         $breadcrumb_text{'userpicked'} = 'Select a user',
                   1091:         $breadcrumb_text{'modify'} = 'Set section/dates',
                   1092:     } else {
1.229     raeburn  1093:         $breadcrumb_text{'search'} = 'Create/modify a user';
1.213     raeburn  1094:         $breadcrumb_text{'userpicked'} = 'Select a user',
                   1095:         $breadcrumb_text{'modify'} = 'Set user role',
                   1096:     }
                   1097:     return %breadcrumb_text;
                   1098: }
                   1099: 
                   1100: sub date_sections_select {
                   1101:     my ($context,$newuser,$formname,$permission) = @_;
                   1102:     my $cid = $env{'request.course.id'};
                   1103:     my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity($cid);
                   1104:     my $date_table = '<h3>'.&mt('Starting and Ending Dates').'</h3>'."\n".
                   1105:         &Apache::lonuserutils::date_setting_table(undef,undef,$context,
                   1106:                                                   undef,$formname,$permission);
                   1107:     my $rowtitle = 'Section';
                   1108:     my $secbox = '<h3>'.&mt('Section').'</h3>'."\n".
                   1109:         &Apache::lonuserutils::section_picker($cdom,$cnum,'st',$rowtitle,
                   1110:                                               $permission);
                   1111:     my $output = $date_table.$secbox;
                   1112:     return $output;
                   1113: }
                   1114: 
1.216     raeburn  1115: sub validation_javascript {
                   1116:     my ($context,$ccdomain,$pjump_def,$groupslist,$newuser,$formname,
                   1117:         $loaditem) = @_;
                   1118:     my $dc_setcourse_code = '';
                   1119:     my $nondc_setsection_code = '';
                   1120:     if ($context eq 'domain') {
                   1121:         my $dcdom = $env{'request.role.domain'};
                   1122:         $loaditem->{'onload'} = "document.cu.coursedesc.value='';";
1.227     raeburn  1123:         $dc_setcourse_code = 
                   1124:             &Apache::lonuserutils::dc_setcourse_js('cu','singleuser',$context);
1.216     raeburn  1125:     } else {
1.227     raeburn  1126:         my $checkauth; 
                   1127:         if (($newuser) || (&Apache::lonnet::allowed('mau',$ccdomain))) {
                   1128:             $checkauth = 1;
                   1129:         }
                   1130:         if ($context eq 'course') {
                   1131:             $nondc_setsection_code =
                   1132:                 &Apache::lonuserutils::setsections_javascript($formname,$groupslist,
                   1133:                                                               undef,$checkauth);
                   1134:         }
                   1135:         if ($checkauth) {
                   1136:             $nondc_setsection_code .= 
                   1137:                 &Apache::lonuserutils::verify_authen($formname,$context);
                   1138:         }
1.216     raeburn  1139:     }
                   1140:     my $js = &user_modification_js($pjump_def,$dc_setcourse_code,
                   1141:                                    $nondc_setsection_code,$groupslist);
                   1142:     my ($jsback,$elements) = &crumb_utilities();
                   1143:     $js .= "\n".
1.227     raeburn  1144:            '<script type="text/javascript">'."\n".$jsback."\n".'</script>';
1.216     raeburn  1145:     return $js;
                   1146: }
                   1147: 
1.217     raeburn  1148: sub display_existing_roles {
                   1149:     my ($r,$ccuname,$ccdomain,$inccourses) = @_;
                   1150:     my %rolesdump=&Apache::lonnet::dump('roles',$ccdomain,$ccuname);
                   1151:     # Build up table of user roles to allow revocation and re-enabling of roles.
                   1152:     my ($tmp) = keys(%rolesdump);
                   1153:     if ($tmp !~ /^(con_lost|error)/i) {
                   1154:         my $now=time;
                   1155:         my %lt=&Apache::lonlocal::texthash(
                   1156:                     'rer'  => "Existing Roles",
                   1157:                     'rev'  => "Revoke",
                   1158:                     'del'  => "Delete",
                   1159:                     'ren'  => "Re-Enable",
                   1160:                     'rol'  => "Role",
                   1161:                     'ext'  => "Extent",
                   1162:                     'sta'  => "Start",
                   1163:                     'end'  => "End",
                   1164:                                        );
                   1165:         my (%roletext,%sortrole,%roleclass,%rolepriv);
                   1166:         foreach my $area (sort { my $a1=join('_',(split('_',$a))[1,0]);
                   1167:                                     my $b1=join('_',(split('_',$b))[1,0]);
                   1168:                                     return $a1 cmp $b1;
                   1169:                                 } keys(%rolesdump)) {
                   1170:             next if ($area =~ /^rolesdef/);
                   1171:             my $envkey=$area;
                   1172:             my $role = $rolesdump{$area};
                   1173:             my $thisrole=$area;
                   1174:             $area =~ s/\_\w\w$//;
                   1175:             my ($role_code,$role_end_time,$role_start_time) =
                   1176:                 split(/_/,$role);
                   1177: # Is this a custom role? Get role owner and title.
                   1178:             my ($croleudom,$croleuname,$croletitle)=
                   1179:                 ($role_code=~m{^cr/($match_domain)/($match_username)/(\w+)$});
                   1180:             my $allowed=0;
                   1181:             my $delallowed=0;
                   1182:             my $sortkey=$role_code;
                   1183:             my $class='Unknown';
                   1184:             if ($area =~ m{^/($match_domain)/($match_courseid)} ) {
                   1185:                 $class='Course';
                   1186:                 my ($coursedom,$coursedir) = ($1,$2);
                   1187:                 $sortkey.="\0$coursedom";
                   1188:                 # $1.'_'.$2 is the course id (eg. 103_12345abcef103l3).
                   1189:                 my %coursedata=
                   1190:                     &Apache::lonnet::coursedescription($1.'_'.$2);
                   1191:                 my $carea;
                   1192:                 if (defined($coursedata{'description'})) {
                   1193:                     $carea=$coursedata{'description'}.
                   1194:                         '<br />'.&mt('Domain').': '.$coursedom.('&nbsp;'x8).
1.259     bisitz   1195:      &Apache::loncommon::syllabuswrapper(&mt('Syllabus'),$coursedir,$coursedom);
1.217     raeburn  1196:                     $sortkey.="\0".$coursedata{'description'};
                   1197:                     $class=$coursedata{'type'};
                   1198:                 } else {
                   1199:                     $carea=&mt('Unavailable course').': '.$area;
                   1200:                     $sortkey.="\0".&mt('Unavailable course').': '.$area;
                   1201:                 }
                   1202:                 $sortkey.="\0$coursedir";
                   1203:                 $inccourses->{$1.'_'.$2}=1;
                   1204:                 if ((&Apache::lonnet::allowed('c'.$role_code,$1.'/'.$2)) ||
                   1205:                     (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
                   1206:                     $allowed=1;
                   1207:                 }
                   1208:                 if ((&Apache::lonnet::allowed('dro',$1)) ||
                   1209:                     (&Apache::lonnet::allowed('dro',$ccdomain))) {
                   1210:                     $delallowed=1;
                   1211:                 }
                   1212: # - custom role. Needs more info, too
                   1213:                 if ($croletitle) {
                   1214:                     if (&Apache::lonnet::allowed('ccr',$1.'/'.$2)) {
                   1215:                         $allowed=1;
                   1216:                         $thisrole.='.'.$role_code;
                   1217:                     }
                   1218:                 }
                   1219:                 # Compute the background color based on $area
                   1220:                 if ($area=~m{^/($match_domain)/($match_courseid)/(\w+)}) {
                   1221:                     $carea.='<br />Section: '.$3;
                   1222:                     $sortkey.="\0$3";
                   1223:                     if (!$allowed) {
                   1224:                         if ($env{'request.course.sec'} eq $3) {
                   1225:                             if (&Apache::lonnet::allowed('c'.$role_code,$1.'/'.$2.'/'.$3)) {
                   1226:                                 $allowed = 1;
                   1227:                             }
                   1228:                         }
                   1229:                     }
                   1230:                 }
                   1231:                 $area=$carea;
                   1232:             } else {
                   1233:                 $sortkey.="\0".$area;
                   1234:                 # Determine if current user is able to revoke privileges
                   1235:                 if ($area=~m{^/($match_domain)/}) {
                   1236:                     if ((&Apache::lonnet::allowed('c'.$role_code,$1)) ||
                   1237:                        (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
                   1238:                         $allowed=1;
                   1239:                     }
                   1240:                     if (((&Apache::lonnet::allowed('dro',$1))  ||
                   1241:                          (&Apache::lonnet::allowed('dro',$ccdomain))) &&
                   1242:                         ($role_code ne 'dc')) {
                   1243:                         $delallowed=1;
                   1244:                     }
                   1245:                 } else {
                   1246:                     if (&Apache::lonnet::allowed('c'.$role_code,'/')) {
                   1247:                         $allowed=1;
                   1248:                     }
                   1249:                 }
                   1250:                 if ($role_code eq 'ca' || $role_code eq 'au') {
                   1251:                     $class='Construction Space';
                   1252:                 } elsif ($role_code eq 'su') {
                   1253:                     $class='System';
                   1254:                 } else {
                   1255:                     $class='Domain';
                   1256:                 }
                   1257:             }
                   1258:             if (($role_code eq 'ca') || ($role_code eq 'aa')) {
                   1259:                 $area=~m{/($match_domain)/($match_username)};
                   1260:                 if (&Apache::lonuserutils::authorpriv($2,$1)) {
                   1261:                     $allowed=1;
                   1262:                 } else {
                   1263:                     $allowed=0;
                   1264:                 }
                   1265:             }
                   1266:             my $row = '';
                   1267:             $row.= '<td>';
                   1268:             my $active=1;
                   1269:             $active=0 if (($role_end_time) && ($now>$role_end_time));
                   1270:             if (($active) && ($allowed)) {
                   1271:                 $row.= '<input type="checkbox" name="rev:'.$thisrole.'" />';
                   1272:             } else {
                   1273:                 if ($active) {
                   1274:                    $row.='&nbsp;';
                   1275:                 } else {
                   1276:                    $row.=&mt('expired or revoked');
                   1277:                 }
                   1278:             }
                   1279:             $row.='</td><td>';
                   1280:             if ($allowed && !$active) {
                   1281:                 $row.= '<input type="checkbox" name="ren:'.$thisrole.'" />';
                   1282:             } else {
                   1283:                 $row.='&nbsp;';
                   1284:             }
                   1285:             $row.='</td><td>';
                   1286:             if ($delallowed) {
                   1287:                 $row.= '<input type="checkbox" name="del:'.$thisrole.'" />';
                   1288:             } else {
                   1289:                 $row.='&nbsp;';
                   1290:             }
                   1291:             my $plaintext='';
                   1292:             if (!$croletitle) {
                   1293:                 $plaintext=&Apache::lonnet::plaintext($role_code,$class)
                   1294:             } else {
                   1295:                 $plaintext=
                   1296:         "Customrole '$croletitle'<br />defined by $croleuname\@$croleudom";
                   1297:             }
                   1298:             $row.= '</td><td>'.$plaintext.
                   1299:                    '</td><td>'.$area.
                   1300:                    '</td><td>'.($role_start_time?localtime($role_start_time)
                   1301:                                                 : '&nbsp;' ).
                   1302:                    '</td><td>'.($role_end_time  ?localtime($role_end_time)
                   1303:                                                 : '&nbsp;' )
                   1304:                    ."</td>";
                   1305:             $sortrole{$sortkey}=$envkey;
                   1306:             $roletext{$envkey}=$row;
                   1307:             $roleclass{$envkey}=$class;
                   1308:             $rolepriv{$envkey}=$allowed;
                   1309:             #$r->print($row);
                   1310:         } # end of foreach        (table building loop)
                   1311:         my $rolesdisplay = 0;
                   1312:         my %output = ();
                   1313:         foreach my $type ('Construction Space','Course','Group','Domain','System','Unknown') {
                   1314:             $output{$type} = '';
                   1315:             foreach my $which (sort {uc($a) cmp uc($b)} (keys(%sortrole))) {
                   1316:                 if ( ($roleclass{$sortrole{$which}} =~ /^\Q$type\E/ ) && ($rolepriv{$sortrole{$which}}) ) {
                   1317:                     $output{$type}.=
                   1318:                           &Apache::loncommon::start_data_table_row().
                   1319:                           $roletext{$sortrole{$which}}.
                   1320:                           &Apache::loncommon::end_data_table_row();
                   1321:                 }
                   1322:             }
                   1323:             unless($output{$type} eq '') {
                   1324:                 $output{$type} = '<tr class="LC_info_row">'.
                   1325:                           "<td align='center' colspan='7'>".&mt($type)."</td></tr>".
                   1326:                            $output{$type};
                   1327:                 $rolesdisplay = 1;
                   1328:             }
                   1329:         }
                   1330:         if ($rolesdisplay == 1) {
1.290     bisitz   1331:             my $contextrole='';
                   1332:             if ($env{'request.course.id'}) {
                   1333:                 $contextrole = 'Existing Roles in this Course';
                   1334:             } elsif ($env{'request.role'} =~ /^au\./) {
                   1335:                 $contextrole = 'Existing Co-Author Roles in your Construction Space';
                   1336:             } else {
                   1337:                 $contextrole = 'Existing Roles in this Domain';
                   1338:             }
1.217     raeburn  1339:             $r->print('
                   1340: <h3>'.$lt{'rer'}.'</h3>'.
1.290     bisitz   1341: '<div>'.&mt($contextrole).'</div>'.
1.217     raeburn  1342: &Apache::loncommon::start_data_table("LC_createuser").
                   1343: &Apache::loncommon::start_data_table_header_row().
                   1344: '<th>'.$lt{'rev'}.'</th><th>'.$lt{'ren'}.'</th><th>'.$lt{'del'}.
                   1345: '</th><th>'.$lt{'rol'}.'</th><th>'.$lt{'ext'}.
                   1346: '</th><th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'.
                   1347: &Apache::loncommon::end_data_table_header_row());
                   1348:            foreach my $type ('Construction Space','Course','Group','Domain','System','Unknown') {
                   1349:                 if ($output{$type}) {
                   1350:                     $r->print($output{$type}."\n");
                   1351:                 }
                   1352:             }
                   1353:             $r->print(&Apache::loncommon::end_data_table());
                   1354:         }
                   1355:     }  # End of check for keys in rolesdump
                   1356:     return;
                   1357: }
                   1358: 
1.218     raeburn  1359: sub new_coauthor_roles {
                   1360:     my ($r,$ccuname,$ccdomain) = @_;
                   1361:     my $addrolesdisplay = 0;
                   1362:     #
                   1363:     # Co-Author
                   1364:     #
                   1365:     if (&Apache::lonuserutils::authorpriv($env{'user.name'},
                   1366:                                           $env{'request.role.domain'}) &&
                   1367:         ($env{'user.name'} ne $ccuname || $env{'user.domain'} ne $ccdomain)) {
                   1368:         # No sense in assigning co-author role to yourself
                   1369:         $addrolesdisplay = 1;
                   1370:         my $cuname=$env{'user.name'};
                   1371:         my $cudom=$env{'request.role.domain'};
                   1372:         my %lt=&Apache::lonlocal::texthash(
                   1373:                     'cs'   => "Construction Space",
                   1374:                     'act'  => "Activate",
                   1375:                     'rol'  => "Role",
                   1376:                     'ext'  => "Extent",
                   1377:                     'sta'  => "Start",
                   1378:                     'end'  => "End",
                   1379:                     'cau'  => "Co-Author",
                   1380:                     'caa'  => "Assistant Co-Author",
                   1381:                     'ssd'  => "Set Start Date",
                   1382:                     'sed'  => "Set End Date"
                   1383:                                        );
                   1384:         $r->print('<h4>'.$lt{'cs'}.'</h4>'."\n".
                   1385:                   &Apache::loncommon::start_data_table()."\n".
                   1386:                   &Apache::loncommon::start_data_table_header_row()."\n".
                   1387:                   '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'.
                   1388:                   '<th>'.$lt{'ext'}.'</th><th>'.$lt{'sta'}.'</th>'.
                   1389:                   '<th>'.$lt{'end'}.'</th>'."\n".
                   1390:                   &Apache::loncommon::end_data_table_header_row()."\n".
                   1391:                   &Apache::loncommon::start_data_table_row().'
                   1392:            <td>
1.291     bisitz   1393:             <input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_ca" />
1.218     raeburn  1394:            </td>
                   1395:            <td>'.$lt{'cau'}.'</td>
                   1396:            <td>'.$cudom.'_'.$cuname.'</td>
                   1397:            <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_ca" value="" />
                   1398:              <a href=
                   1399: "javascript:pjump('."'date_start','Start Date Co-Author',document.cu.start_$cudom\_$cuname\_ca.value,'start_$cudom\_$cuname\_ca','cu.pres','dateset'".')">'.$lt{'ssd'}.'</a></td>
                   1400: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_ca" value="" />
                   1401: <a href=
                   1402: "javascript:pjump('."'date_end','End Date Co-Author',document.cu.end_$cudom\_$cuname\_ca.value,'end_$cudom\_$cuname\_ca','cu.pres','dateset'".')">'.$lt{'sed'}.'</a></td>'."\n".
                   1403:               &Apache::loncommon::end_data_table_row()."\n".
                   1404:               &Apache::loncommon::start_data_table_row()."\n".
1.291     bisitz   1405: '<td><input type="checkbox" name="act_'.$cudom.'_'.$cuname.'_aa" /></td>
1.218     raeburn  1406: <td>'.$lt{'caa'}.'</td>
                   1407: <td>'.$cudom.'_'.$cuname.'</td>
                   1408: <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_aa" value="" />
                   1409: <a href=
                   1410: "javascript:pjump('."'date_start','Start Date Assistant Co-Author',document.cu.start_$cudom\_$cuname\_aa.value,'start_$cudom\_$cuname\_aa','cu.pres','dateset'".')">'.$lt{'ssd'}.'</a></td>
                   1411: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_aa" value="" />
                   1412: <a href=
                   1413: "javascript:pjump('."'date_end','End Date Assistant Co-Author',document.cu.end_$cudom\_$cuname\_aa.value,'end_$cudom\_$cuname\_aa','cu.pres','dateset'".')">'.$lt{'sed'}.'</a></td>'."\n".
                   1414:              &Apache::loncommon::end_data_table_row()."\n".
                   1415:              &Apache::loncommon::end_data_table());
                   1416:     } elsif ($env{'request.role'} =~ /^au\./) {
                   1417:         if (!(&Apache::lonuserutils::authorpriv($env{'user.name'},
                   1418:                                                 $env{'request.role.domain'}))) {
                   1419:             $r->print('<span class="LC_error">'.
                   1420:                       &mt('You do not have privileges to assign co-author roles.').
                   1421:                       '</span>');
                   1422:         } elsif (($env{'user.name'} eq $ccuname) &&
                   1423:              ($env{'user.domain'} eq $ccdomain)) {
                   1424:             $r->print(&mt('Assigning yourself a co-author or assistant co-author role in your own author area in Construction Space is not permitted'));
                   1425:         }
                   1426:     }
                   1427:     return $addrolesdisplay;;
                   1428: }
                   1429: 
                   1430: sub new_domain_roles {
                   1431:     my ($r) = @_;
                   1432:     my $addrolesdisplay = 0;
                   1433:     #
                   1434:     # Domain level
                   1435:     #
                   1436:     my $num_domain_level = 0;
                   1437:     my $domaintext =
                   1438:     '<h4>'.&mt('Domain Level').'</h4>'.
                   1439:     &Apache::loncommon::start_data_table().
                   1440:     &Apache::loncommon::start_data_table_header_row().
                   1441:     '<th>'.&mt('Activate').'</th><th>'.&mt('Role').'</th><th>'.
                   1442:     &mt('Extent').'</th>'.
                   1443:     '<th>'.&mt('Start').'</th><th>'.&mt('End').'</th>'.
                   1444:     &Apache::loncommon::end_data_table_header_row();
                   1445:     foreach my $thisdomain (sort(&Apache::lonnet::all_domains())) {
                   1446:         foreach my $role ('dc','li','dg','au','sc') {
                   1447:             if (&Apache::lonnet::allowed('c'.$role,$thisdomain)) {
                   1448:                my $plrole=&Apache::lonnet::plaintext($role);
                   1449:                my %lt=&Apache::lonlocal::texthash(
                   1450:                     'ssd'  => "Set Start Date",
                   1451:                     'sed'  => "Set End Date"
                   1452:                                        );
                   1453:                $num_domain_level ++;
                   1454:                $domaintext .=
                   1455: &Apache::loncommon::start_data_table_row().
1.291     bisitz   1456: '<td><input type="checkbox" name="act_'.$thisdomain.'_'.$role.'" /></td>
1.218     raeburn  1457: <td>'.$plrole.'</td>
                   1458: <td>'.$thisdomain.'</td>
                   1459: <td><input type="hidden" name="start_'.$thisdomain.'_'.$role.'" value="" />
                   1460: <a href=
                   1461: "javascript:pjump('."'date_start','Start Date $plrole',document.cu.start_$thisdomain\_$role.value,'start_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'ssd'}.'</a></td>
                   1462: <td><input type="hidden" name="end_'.$thisdomain.'_'.$role.'" value="" />
                   1463: <a href=
                   1464: "javascript:pjump('."'date_end','End Date $plrole',document.cu.end_$thisdomain\_$role.value,'end_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'sed'}.'</a></td>'.
                   1465: &Apache::loncommon::end_data_table_row();
                   1466:             }
                   1467:         }
                   1468:     }
                   1469:     $domaintext.= &Apache::loncommon::end_data_table();
                   1470:     if ($num_domain_level > 0) {
                   1471:         $r->print($domaintext);
                   1472:         $addrolesdisplay = 1;
                   1473:     }
                   1474:     return $addrolesdisplay;
                   1475: }
                   1476: 
1.188     raeburn  1477: sub user_authentication {
1.227     raeburn  1478:     my ($ccuname,$ccdomain,$formname) = @_;
1.188     raeburn  1479:     my $currentauth=&Apache::lonnet::queryauthenticate($ccuname,$ccdomain);
1.227     raeburn  1480:     my $outcome;
1.188     raeburn  1481:     # Check for a bad authentication type
                   1482:     if ($currentauth !~ /^(krb4|krb5|unix|internal|localauth):/) {
                   1483:         # bad authentication scheme
                   1484:         my %lt=&Apache::lonlocal::texthash(
                   1485:                        'err'   => "ERROR",
                   1486:                        'uuas'  => "This user has an unrecognized authentication scheme",
                   1487:                        'adcs'  => "Please alert a domain coordinator of this situation",
                   1488:                        'sldb'  => "Please specify login data below",
                   1489:                        'ld'    => "Login Data"
                   1490:         );
                   1491:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
1.227     raeburn  1492:             &initialize_authen_forms($ccdomain,$formname);
                   1493: 
1.190     raeburn  1494:             my $choices = &Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc);
1.188     raeburn  1495:             $outcome = <<ENDBADAUTH;
                   1496: <script type="text/javascript" language="Javascript">
                   1497: $loginscript
                   1498: </script>
                   1499: <span class="LC_error">$lt{'err'}:
                   1500: $lt{'uuas'} ($currentauth). $lt{'sldb'}.</span>
                   1501: <h3>$lt{'ld'}</h3>
                   1502: $choices
                   1503: ENDBADAUTH
                   1504:         } else {
                   1505:             # This user is not allowed to modify the user's
                   1506:             # authentication scheme, so just notify them of the problem
                   1507:             $outcome = <<ENDBADAUTH;
                   1508: <span class="LC_error"> $lt{'err'}: 
                   1509: $lt{'uuas'} ($currentauth). $lt{'adcs'}.
                   1510: </span>
                   1511: ENDBADAUTH
                   1512:         }
                   1513:     } else { # Authentication type is valid
1.227     raeburn  1514:         &initialize_authen_forms($ccdomain,$formname,$currentauth,'modifyuser');
1.205     raeburn  1515:         my ($authformcurrent,$can_modify,@authform_others) =
1.188     raeburn  1516:             &modify_login_block($ccdomain,$currentauth);
                   1517:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
                   1518:             # Current user has login modification privileges
                   1519:             my %lt=&Apache::lonlocal::texthash (
                   1520:                            'ld'    => "Login Data",
                   1521:                            'ccld'  => "Change Current Login Data",
                   1522:                            'enld'  => "Enter New Login Data"
                   1523:                                                );
                   1524:             $outcome =
                   1525:                        '<script type="text/javascript" language="Javascript">'."\n".
                   1526:                        $loginscript."\n".
                   1527:                        '</script>'."\n".
                   1528:                        '<h3>'.$lt{'ld'}.'</h3>'.
                   1529:                        &Apache::loncommon::start_data_table().
1.205     raeburn  1530:                        &Apache::loncommon::start_data_table_row().
1.188     raeburn  1531:                        '<td>'.$authformnop;
                   1532:             if ($can_modify) {
                   1533:                 $outcome .= '</td>'."\n".
                   1534:                             &Apache::loncommon::end_data_table_row().
                   1535:                             &Apache::loncommon::start_data_table_row().
                   1536:                             '<td>'.$authformcurrent.'</td>'.
                   1537:                             &Apache::loncommon::end_data_table_row()."\n";
                   1538:             } else {
1.200     raeburn  1539:                 $outcome .= '&nbsp;('.$authformcurrent.')</td>'.
                   1540:                             &Apache::loncommon::end_data_table_row()."\n";
1.188     raeburn  1541:             }
1.205     raeburn  1542:             foreach my $item (@authform_others) { 
                   1543:                 $outcome .= &Apache::loncommon::start_data_table_row().
                   1544:                             '<td>'.$item.'</td>'.
                   1545:                             &Apache::loncommon::end_data_table_row()."\n";
1.188     raeburn  1546:             }
1.205     raeburn  1547:             $outcome .= &Apache::loncommon::end_data_table();
1.188     raeburn  1548:         } else {
                   1549:             if (&Apache::lonnet::allowed('mau',$env{'request.role.domain'})) {
                   1550:                 my %lt=&Apache::lonlocal::texthash(
                   1551:                            'ccld'  => "Change Current Login Data",
                   1552:                            'yodo'  => "You do not have privileges to modify the authentication configuration for this user.",
                   1553:                            'ifch'  => "If a change is required, contact a domain coordinator for the domain",
                   1554:                 );
                   1555:                 $outcome .= <<ENDNOPRIV;
                   1556: <h3>$lt{'ccld'}</h3>
                   1557: $lt{'yodo'} $lt{'ifch'}: $ccdomain
1.235     raeburn  1558: <input type="hidden" name="login" value="nochange" />
1.188     raeburn  1559: ENDNOPRIV
                   1560:             }
                   1561:         }
                   1562:     }  ## End of "check for bad authentication type" logic
                   1563:     return $outcome;
                   1564: }
                   1565: 
1.187     raeburn  1566: sub modify_login_block {
                   1567:     my ($dom,$currentauth) = @_;
                   1568:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   1569:     my ($authnum,%can_assign) =
                   1570:         &Apache::loncommon::get_assignable_auth($dom);
1.205     raeburn  1571:     my ($authformcurrent,@authform_others,$show_override_msg);
1.187     raeburn  1572:     if ($currentauth=~/^krb(4|5):/) {
                   1573:         $authformcurrent=$authformkrb;
                   1574:         if ($can_assign{'int'}) {
1.205     raeburn  1575:             push(@authform_others,$authformint);
1.187     raeburn  1576:         }
                   1577:         if ($can_assign{'loc'}) {
1.205     raeburn  1578:             push(@authform_others,$authformloc);
1.187     raeburn  1579:         }
                   1580:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
                   1581:             $show_override_msg = 1;
                   1582:         }
                   1583:     } elsif ($currentauth=~/^internal:/) {
                   1584:         $authformcurrent=$authformint;
                   1585:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
1.205     raeburn  1586:             push(@authform_others,$authformkrb);
1.187     raeburn  1587:         }
                   1588:         if ($can_assign{'loc'}) {
1.205     raeburn  1589:             push(@authform_others,$authformloc);
1.187     raeburn  1590:         }
                   1591:         if ($can_assign{'int'}) {
                   1592:             $show_override_msg = 1;
                   1593:         }
                   1594:     } elsif ($currentauth=~/^unix:/) {
                   1595:         $authformcurrent=$authformfsys;
                   1596:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
1.205     raeburn  1597:             push(@authform_others,$authformkrb);
1.187     raeburn  1598:         }
                   1599:         if ($can_assign{'int'}) {
1.205     raeburn  1600:             push(@authform_others,$authformint);
1.187     raeburn  1601:         }
                   1602:         if ($can_assign{'loc'}) {
1.205     raeburn  1603:             push(@authform_others,$authformloc);
1.187     raeburn  1604:         }
                   1605:         if ($can_assign{'fsys'}) {
                   1606:             $show_override_msg = 1;
                   1607:         }
                   1608:     } elsif ($currentauth=~/^localauth:/) {
                   1609:         $authformcurrent=$authformloc;
                   1610:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
1.205     raeburn  1611:             push(@authform_others,$authformkrb);
1.187     raeburn  1612:         }
                   1613:         if ($can_assign{'int'}) {
1.205     raeburn  1614:             push(@authform_others,$authformint);
1.187     raeburn  1615:         }
                   1616:         if ($can_assign{'loc'}) {
                   1617:             $show_override_msg = 1;
                   1618:         }
                   1619:     }
                   1620:     if ($show_override_msg) {
1.205     raeburn  1621:         $authformcurrent = '<table><tr><td colspan="3">'.$authformcurrent.
                   1622:                            '</td></tr>'."\n".
                   1623:                            '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.
                   1624:                            '<td><b>'.&mt('Currently in use').'</b></td>'.
                   1625:                            '<td align="right"><span class="LC_cusr_emph">'.
1.187     raeburn  1626:                             &mt('will override current values').
1.205     raeburn  1627:                             '</span></td></tr></table>';
1.187     raeburn  1628:     }
1.205     raeburn  1629:     return ($authformcurrent,$show_override_msg,@authform_others); 
1.187     raeburn  1630: }
                   1631: 
1.188     raeburn  1632: sub personal_data_display {
1.252     raeburn  1633:     my ($ccuname,$ccdomain,$newuser,$context,$inst_results,$rolesarray) = @_;
1.286     raeburn  1634:     my ($output,$showforceid,%userenv,%canmodify,%canmodify_status);
1.219     raeburn  1635:     my @userinfo = ('firstname','middlename','lastname','generation',
                   1636:                     'permanentemail','id');
1.252     raeburn  1637:     my $rowcount = 0;
                   1638:     my $editable = 0;
1.286     raeburn  1639:     %canmodify_status = 
                   1640:         &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
                   1641:                                                    ['inststatus'],$rolesarray);
1.253     raeburn  1642:     if (!$newuser) {
1.188     raeburn  1643:         # Get the users information
                   1644:         %userenv = &Apache::lonnet::get('environment',
                   1645:                    ['firstname','middlename','lastname','generation',
1.286     raeburn  1646:                     'permanentemail','id','inststatus'],$ccdomain,$ccuname);
1.219     raeburn  1647:         %canmodify =
                   1648:             &Apache::lonuserutils::can_modify_userinfo($context,$ccdomain,
1.252     raeburn  1649:                                                        \@userinfo,$rolesarray);
1.257     raeburn  1650:     } elsif ($context eq 'selfcreate') {
                   1651:         %canmodify = &selfcreate_canmodify($context,$ccdomain,\@userinfo,
                   1652:                                            $inst_results,$rolesarray);
1.188     raeburn  1653:     }
                   1654:     my %lt=&Apache::lonlocal::texthash(
                   1655:                 'pd'             => "Personal Data",
                   1656:                 'firstname'      => "First Name",
                   1657:                 'middlename'     => "Middle Name",
                   1658:                 'lastname'       => "Last Name",
                   1659:                 'generation'     => "Generation",
                   1660:                 'permanentemail' => "Permanent e-mail address",
1.259     bisitz   1661:                 'id'             => "Student/Employee ID",
1.286     raeburn  1662:                 'lg'             => "Login Data",
                   1663:                 'inststatus'     => "Affiliation",
1.188     raeburn  1664:     );
                   1665:     my %textboxsize = (
                   1666:                        firstname      => '15',
                   1667:                        middlename     => '15',
                   1668:                        lastname       => '15',
                   1669:                        generation     => '5',
                   1670:                        permanentemail => '25',
                   1671:                        id             => '15',
                   1672:                       );
                   1673:     my $genhelp=&Apache::loncommon::help_open_topic('Generation');
                   1674:     $output = '<h3>'.$lt{'pd'}.'</h3>'.
                   1675:               &Apache::lonhtmlcommon::start_pick_box();
                   1676:     foreach my $item (@userinfo) {
                   1677:         my $rowtitle = $lt{$item};
1.252     raeburn  1678:         my $hiderow = 0;
1.188     raeburn  1679:         if ($item eq 'generation') {
                   1680:             $rowtitle = $genhelp.$rowtitle;
                   1681:         }
1.252     raeburn  1682:         my $row = &Apache::lonhtmlcommon::row_title($rowtitle,undef,'LC_oddrow_value')."\n";
1.188     raeburn  1683:         if ($newuser) {
1.210     raeburn  1684:             if (ref($inst_results) eq 'HASH') {
                   1685:                 if ($inst_results->{$item} ne '') {
1.252     raeburn  1686:                     $row .= '<input type="hidden" name="c'.$item.'" value="'.$inst_results->{$item}.'" />'.$inst_results->{$item};
1.210     raeburn  1687:                 } else {
1.252     raeburn  1688:                     if ($context eq 'selfcreate') {
                   1689:                         if ($canmodify{$item}) { 
                   1690:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
                   1691:                             $editable ++;
                   1692:                         } else {
                   1693:                             $hiderow = 1;
                   1694:                         }
1.253     raeburn  1695:                     } else {
                   1696:                         $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
1.252     raeburn  1697:                     }
1.210     raeburn  1698:                 }
1.188     raeburn  1699:             } else {
1.252     raeburn  1700:                 if ($context eq 'selfcreate') {
1.287     raeburn  1701:                     if (($item eq 'permanentemail') && ($newuser eq 'email')) {
                   1702:                         $row .= $ccuname;
1.252     raeburn  1703:                     } else {
1.287     raeburn  1704:                         if ($canmodify{$item}) {
                   1705:                             $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
                   1706:                             $editable ++;
                   1707:                         } else {
                   1708:                             $hiderow = 1;
                   1709:                         }
1.252     raeburn  1710:                     }
1.253     raeburn  1711:                 } else {
                   1712:                     $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
1.252     raeburn  1713:                 }
1.188     raeburn  1714:             }
                   1715:         } else {
1.219     raeburn  1716:             if ($canmodify{$item}) {
1.252     raeburn  1717:                 $row .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="'.$userenv{$item}.'" />';
1.188     raeburn  1718:             } else {
1.252     raeburn  1719:                 $row .= $userenv{$item};
1.188     raeburn  1720:             }
1.206     raeburn  1721:             if ($item eq 'id') {
1.219     raeburn  1722:                 $showforceid = $canmodify{$item};
                   1723:             }
1.188     raeburn  1724:         }
1.252     raeburn  1725:         $row .= &Apache::lonhtmlcommon::row_closure(1);
                   1726:         if (!$hiderow) {
                   1727:             $output .= $row;
                   1728:             $rowcount ++;
                   1729:         }
1.188     raeburn  1730:     }
1.286     raeburn  1731:     if (($canmodify_status{'inststatus'}) || ($context ne 'selfcreate')) {
                   1732:         my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($ccdomain);
                   1733:         if (ref($types) eq 'ARRAY') {
                   1734:             if (@{$types} > 0) {
                   1735:                 my ($hiderow,$shown);
                   1736:                 if ($canmodify_status{'inststatus'}) {
                   1737:                     $shown = &pick_inst_statuses($userenv{'inststatus'},$usertypes,$types);
                   1738:                 } else {
                   1739:                     $shown .= $userenv{'inststatus'};
                   1740:                     if ($userenv{'inststatus'} eq '') {
                   1741:                         $hiderow = 1;
                   1742:                     }
                   1743:                 }
                   1744:                 if (!$hiderow) {
                   1745:                     my $row = &Apache::lonhtmlcommon::row_title(&mt('Affliations'),undef,'LC_oddrow_value')."\n".
                   1746:                               $shown.&Apache::lonhtmlcommon::row_closure(1); 
                   1747:                     if ($context eq 'selfcreate') {
                   1748:                         $rowcount ++;
                   1749:                     }
                   1750:                     $output .= $row;
                   1751:                 }
                   1752:             }
                   1753:         }
                   1754:     }
1.188     raeburn  1755:     $output .= &Apache::lonhtmlcommon::end_pick_box();
1.206     raeburn  1756:     if (wantarray) {
1.252     raeburn  1757:         if ($context eq 'selfcreate') {
                   1758:             return($output,$rowcount,$editable);
                   1759:         } else {
                   1760:             return ($output,$showforceid);
                   1761:         }
1.206     raeburn  1762:     } else {
                   1763:         return $output;
                   1764:     }
1.188     raeburn  1765: }
                   1766: 
1.286     raeburn  1767: sub pick_inst_statuses {
                   1768:     my ($curr,$usertypes,$types) = @_;
                   1769:     my ($output,$rem,@currtypes);
                   1770:     if ($curr ne '') {
                   1771:         @currtypes = map { &unescape($_); } split(/:/,$curr);
                   1772:     }
                   1773:     my $numinrow = 2;
                   1774:     if (ref($types) eq 'ARRAY') {
                   1775:         $output = '<table>';
                   1776:         my $lastcolspan; 
                   1777:         for (my $i=0; $i<@{$types}; $i++) {
                   1778:             if (defined($usertypes->{$types->[$i]})) {
                   1779:                 my $rem = $i%($numinrow);
                   1780:                 if ($rem == 0) {
                   1781:                     if ($i<@{$types}-1) {
                   1782:                         if ($i > 0) { 
                   1783:                             $output .= '</tr>';
                   1784:                         }
                   1785:                         $output .= '<tr>';
                   1786:                     }
                   1787:                 } elsif ($i==@{$types}-1) {
                   1788:                     my $colsleft = $numinrow - $rem;
                   1789:                     if ($colsleft > 1) {
                   1790:                         $lastcolspan = ' colspan="'.$colsleft.'"';
                   1791:                     }
                   1792:                 }
                   1793:                 my $check = ' ';
                   1794:                 if (grep(/^\Q$types->[$i]\E$/,@currtypes)) {
                   1795:                     $check = ' checked="checked" ';
                   1796:                 }
                   1797:                 $output .= '<td class="LC_left_item"'.$lastcolspan.'>'.
                   1798:                            '<span class="LC_nobreak"><label>'.
                   1799:                            '<input type="checkbox" name="inststatus" '.
                   1800:                            'value="'.$types->[$i].'"'.$check.'/>'.
                   1801:                            $usertypes->{$types->[$i]}.'</label></span></td>';
                   1802:             }
                   1803:         }
                   1804:         $output .= '</tr></table>';
                   1805:     }
                   1806:     return $output;
                   1807: }
                   1808: 
1.257     raeburn  1809: sub selfcreate_canmodify {
                   1810:     my ($context,$dom,$userinfo,$inst_results,$rolesarray) = @_;
                   1811:     if (ref($inst_results) eq 'HASH') {
                   1812:         my @inststatuses = &get_inststatuses($inst_results);
                   1813:         if (@inststatuses == 0) {
                   1814:             @inststatuses = ('default');
                   1815:         }
                   1816:         $rolesarray = \@inststatuses;
                   1817:     }
                   1818:     my %canmodify =
                   1819:         &Apache::lonuserutils::can_modify_userinfo($context,$dom,$userinfo,
                   1820:                                                    $rolesarray);
                   1821:     return %canmodify;
                   1822: }
                   1823: 
1.252     raeburn  1824: sub get_inststatuses {
                   1825:     my ($insthashref) = @_;
                   1826:     my @inststatuses = ();
                   1827:     if (ref($insthashref) eq 'HASH') {
                   1828:         if (ref($insthashref->{'inststatus'}) eq 'ARRAY') {
                   1829:             @inststatuses = @{$insthashref->{'inststatus'}};
                   1830:         }
                   1831:     }
                   1832:     return @inststatuses;
                   1833: }
                   1834: 
1.4       www      1835: # ================================================================= Phase Three
1.42      matthew  1836: sub update_user_data {
1.206     raeburn  1837:     my ($r,$context) = @_; 
1.101     albertel 1838:     my $uhome=&Apache::lonnet::homeserver($env{'form.ccuname'},
                   1839:                                           $env{'form.ccdomain'});
1.27      matthew  1840:     # Error messages
1.188     raeburn  1841:     my $error     = '<span class="LC_error">'.&mt('Error').': ';
1.193     raeburn  1842:     my $end       = '</span><br /><br />';
                   1843:     my $rtnlink   = '<a href="javascript:backPage(document.userupdate,'.
1.188     raeburn  1844:                     "'$env{'form.prevphase'}','modify')".'" />'.
1.219     raeburn  1845:                     &mt('Return to previous page').'</a>'.
                   1846:                     &Apache::loncommon::end_page();
                   1847:     my $now = time;
1.40      www      1848:     my $title;
1.101     albertel 1849:     if (exists($env{'form.makeuser'})) {
1.40      www      1850: 	$title='Set Privileges for New User';
                   1851:     } else {
                   1852:         $title='Modify User Privileges';
                   1853:     }
1.213     raeburn  1854:     my $newuser = 0;
1.160     raeburn  1855:     my ($jsback,$elements) = &crumb_utilities();
                   1856:     my $jscript = '<script type="text/javascript">'."\n".
                   1857:                   $jsback."\n".'</script>'."\n";
1.213     raeburn  1858:     my %breadcrumb_text = &singleuser_breadcrumb();
1.233     raeburn  1859:     my $args;
                   1860:     if ($env{'form.popup'}) {
                   1861:         $args->{'no_nav_bar'} = 1;
                   1862:     } else {
                   1863:         $args = undef;
                   1864:     }
                   1865:     $r->print(&Apache::loncommon::start_page($title,$jscript,$args));
1.160     raeburn  1866:     &Apache::lonhtmlcommon::add_breadcrumb
                   1867:        ({href=>"javascript:backPage(document.userupdate)",
1.213     raeburn  1868:          text=>$breadcrumb_text{'search'},
1.160     raeburn  1869:          faq=>282,bug=>'Instructor Interface',});
                   1870:     if ($env{'form.prevphase'} eq 'userpicked') {
                   1871:         &Apache::lonhtmlcommon::add_breadcrumb
                   1872:            ({href=>"javascript:backPage(document.userupdate,'get_user_info','select')",
1.213     raeburn  1873:              text=>$breadcrumb_text{'userpicked'},
1.160     raeburn  1874:              faq=>282,bug=>'Instructor Interface',});
                   1875:     }
                   1876:     &Apache::lonhtmlcommon::add_breadcrumb
                   1877:        ({href=>"javascript:backPage(document.userupdate,'$env{'form.prevphase'}','modify')",
1.219     raeburn  1878:          text=>$breadcrumb_text{'modify'},
1.160     raeburn  1879:          faq=>282,bug=>'Instructor Interface',},
                   1880:         {href=>"/adm/createuser",
                   1881:          text=>"Result",
                   1882:          faq=>282,bug=>'Instructor Interface',});
1.224     raeburn  1883:     my $helpitem = 'Course_Change_Privileges';
                   1884:     if ($env{'form.action'} eq 'singlestudent') {
                   1885:         $helpitem = 'Course_Add_Student';
                   1886:     }
                   1887:     $r->print(&Apache::lonhtmlcommon::breadcrumbs('User Management',
                   1888:                                                  $helpitem));
1.188     raeburn  1889:     $r->print(&update_result_form($uhome));
1.27      matthew  1890:     # Check Inputs
1.101     albertel 1891:     if (! $env{'form.ccuname'} ) {
1.193     raeburn  1892: 	$r->print($error.&mt('No login name specified').'.'.$end.$rtnlink);
1.27      matthew  1893: 	return;
                   1894:     }
1.138     albertel 1895:     if (  $env{'form.ccuname'} ne 
                   1896: 	  &LONCAPA::clean_username($env{'form.ccuname'}) ) {
1.281     bisitz   1897: 	$r->print($error.&mt('Invalid login name.').'  '.
                   1898: 		  &mt('Only letters, numbers, periods, dashes, @, and underscores are valid.').
1.193     raeburn  1899: 		  $end.$rtnlink);
1.27      matthew  1900: 	return;
                   1901:     }
1.101     albertel 1902:     if (! $env{'form.ccdomain'}       ) {
1.193     raeburn  1903: 	$r->print($error.&mt('No domain specified').'.'.$end.$rtnlink);
1.27      matthew  1904: 	return;
                   1905:     }
1.138     albertel 1906:     if (  $env{'form.ccdomain'} ne
                   1907: 	  &LONCAPA::clean_domain($env{'form.ccdomain'}) ) {
1.281     bisitz   1908: 	$r->print($error.&mt('Invalid domain name.').'  '.
                   1909: 		  &mt('Only letters, numbers, periods, dashes, and underscores are valid.').
1.193     raeburn  1910: 		  $end.$rtnlink);
1.27      matthew  1911: 	return;
                   1912:     }
1.219     raeburn  1913:     if ($uhome eq 'no_host') {
                   1914:         $newuser = 1;
                   1915:     }
1.101     albertel 1916:     if (! exists($env{'form.makeuser'})) {
1.29      matthew  1917:         # Modifying an existing user, so check the validity of the name
                   1918:         if ($uhome eq 'no_host') {
1.73      sakharuk 1919:             $r->print($error.&mt('Unable to determine home server for ').
1.101     albertel 1920:                       $env{'form.ccuname'}.&mt(' in domain ').
                   1921:                       $env{'form.ccdomain'}.'.');
1.29      matthew  1922:             return;
                   1923:         }
                   1924:     }
1.27      matthew  1925:     # Determine authentication method and password for the user being modified
                   1926:     my $amode='';
                   1927:     my $genpwd='';
1.101     albertel 1928:     if ($env{'form.login'} eq 'krb') {
1.41      albertel 1929: 	$amode='krb';
1.101     albertel 1930: 	$amode.=$env{'form.krbver'};
                   1931: 	$genpwd=$env{'form.krbarg'};
                   1932:     } elsif ($env{'form.login'} eq 'int') {
1.27      matthew  1933: 	$amode='internal';
1.101     albertel 1934: 	$genpwd=$env{'form.intarg'};
                   1935:     } elsif ($env{'form.login'} eq 'fsys') {
1.27      matthew  1936: 	$amode='unix';
1.101     albertel 1937: 	$genpwd=$env{'form.fsysarg'};
                   1938:     } elsif ($env{'form.login'} eq 'loc') {
1.27      matthew  1939: 	$amode='localauth';
1.101     albertel 1940: 	$genpwd=$env{'form.locarg'};
1.27      matthew  1941: 	$genpwd=" " if (!$genpwd);
1.101     albertel 1942:     } elsif (($env{'form.login'} eq 'nochange') ||
                   1943:              ($env{'form.login'} eq ''        )) { 
1.34      matthew  1944:         # There is no need to tell the user we did not change what they
                   1945:         # did not ask us to change.
1.35      matthew  1946:         # If they are creating a new user but have not specified login
                   1947:         # information this will be caught below.
1.30      matthew  1948:     } else {
1.193     raeburn  1949: 	    $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);    
1.30      matthew  1950: 	    return;
1.27      matthew  1951:     }
1.164     albertel 1952: 
1.188     raeburn  1953:     $r->print('<h3>'.&mt('User [_1] in domain [_2]',
                   1954: 			 $env{'form.ccuname'}, $env{'form.ccdomain'}).'</h3>');
1.193     raeburn  1955:     my (%alerts,%rulematch,%inst_results,%curr_rules);
1.267     raeburn  1956:     my @usertools = ('aboutme','blog','portfolio');
1.275     raeburn  1957:     my @requestcourses = ('official','unofficial');
1.286     raeburn  1958:     my ($othertitle,$usertypes,$types) = 
                   1959:         &Apache::loncommon::sorted_inst_types($env{'form.ccdomain'});
1.101     albertel 1960:     if ($env{'form.makeuser'}) {
1.164     albertel 1961: 	$r->print('<h3>'.&mt('Creating new account.').'</h3>');
1.27      matthew  1962:         # Check for the authentication mode and password
                   1963:         if (! $amode || ! $genpwd) {
1.193     raeburn  1964: 	    $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);    
1.27      matthew  1965: 	    return;
1.18      albertel 1966: 	}
1.29      matthew  1967:         # Determine desired host
1.101     albertel 1968:         my $desiredhost = $env{'form.hserver'};
1.29      matthew  1969:         if (lc($desiredhost) eq 'default') {
                   1970:             $desiredhost = undef;
                   1971:         } else {
1.147     albertel 1972:             my %home_servers = 
                   1973: 		&Apache::lonnet::get_servers($env{'form.ccdomain'},'library');
1.29      matthew  1974:             if (! exists($home_servers{$desiredhost})) {
1.193     raeburn  1975:                 $r->print($error.&mt('Invalid home server specified').$end.$rtnlink);
                   1976:                 return;
                   1977:             }
                   1978:         }
                   1979:         # Check ID format
                   1980:         my %checkhash;
                   1981:         my %checks = ('id' => 1);
                   1982:         %{$checkhash{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}}} = (
1.219     raeburn  1983:             'newuser' => $newuser, 
1.196     raeburn  1984:             'id' => $env{'form.cid'},
1.193     raeburn  1985:         );
1.196     raeburn  1986:         if ($env{'form.cid'} ne '') {
                   1987:             &Apache::loncommon::user_rule_check(\%checkhash,\%checks,\%alerts,
                   1988:                                           \%rulematch,\%inst_results,\%curr_rules);
                   1989:             if (ref($alerts{'id'}) eq 'HASH') {
                   1990:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
                   1991:                     my $domdesc =
                   1992:                         &Apache::lonnet::domain($env{'form.ccdomain'},'description');
                   1993:                     if ($alerts{'id'}{$env{'form.ccdomain'}}{$env{'form.cid'}}) {
                   1994:                         my $userchkmsg;
                   1995:                         if (ref($curr_rules{$env{'form.ccdomain'}}) eq 'HASH') {
                   1996:                             $userchkmsg  = 
                   1997:                                 &Apache::loncommon::instrule_disallow_msg('id',
                   1998:                                                                     $domdesc,1).
                   1999:                                 &Apache::loncommon::user_rule_formats($env{'form.ccdomain'},
                   2000:                                     $domdesc,$curr_rules{$env{'form.ccdomain'}}{'id'},'id');
                   2001:                         }
                   2002:                         $r->print($error.&mt('Invalid ID format').$end.
                   2003:                                   $userchkmsg.$rtnlink);
                   2004:                         return;
                   2005:                     }
                   2006:                 }
1.29      matthew  2007:             }
                   2008:         }
1.27      matthew  2009: 	# Call modifyuser
                   2010: 	my $result = &Apache::lonnet::modifyuser
1.193     raeburn  2011: 	    ($env{'form.ccdomain'},$env{'form.ccuname'},$env{'form.cid'},
1.188     raeburn  2012:              $amode,$genpwd,$env{'form.cfirstname'},
                   2013:              $env{'form.cmiddlename'},$env{'form.clastname'},
                   2014:              $env{'form.cgeneration'},undef,$desiredhost,
                   2015:              $env{'form.cpermanentemail'});
1.77      www      2016: 	$r->print(&mt('Generating user').': '.$result);
1.219     raeburn  2017:         $uhome = &Apache::lonnet::homeserver($env{'form.ccuname'},
1.101     albertel 2018:                                                $env{'form.ccdomain'});
1.267     raeburn  2019:         my (%changeHash,%newcustom,%changed);
                   2020:         if ($uhome ne 'no_host') {
                   2021:             if ($env{'form.customquota'} == 1) {
                   2022:                 if ($env{'form.portfolioquota'} eq '') {
                   2023:                     $newcustom{'quota'} = 0;
                   2024:                 } else {
                   2025:                     $newcustom{'quota'} = $env{'form.portfolioquota'};
                   2026:                     $newcustom{'quota'} =~ s/[^\d\.]//g;
                   2027:                 }
                   2028:                 $changed{'quota'} = &quota_admin($newcustom{'quota'},\%changeHash);
                   2029:             }
                   2030:             foreach my $item (@usertools) {
                   2031:                 if ($env{'form.custom'.$item} == 1) {
                   2032:                     $newcustom{$item} = $env{'form.tools_'.$item};
1.275     raeburn  2033:                     $changed{$item} = &tool_admin($item,$newcustom{$item},
                   2034:                                                  \%changeHash,'tools');
                   2035:                 }
                   2036:             }
1.279     raeburn  2037:             foreach my $item (@requestcourses) {
                   2038:                 $newcustom{$item} = $env{'form.requestcourses_'.$item};
                   2039:                 $changed{$item} = &tool_admin($item,$newcustom{$item},
                   2040:                                               \%changeHash,'requestcourses');
1.232     raeburn  2041:             }
1.286     raeburn  2042:             if (exists($env{'form.inststatus'})) {
                   2043:                 my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
                   2044:                 if (@inststatuses > 0) {
                   2045:                     $changeHash{'inststatus'} = join(',',@inststatuses);
                   2046:                     $changed{'inststatus'} = $changeHash{'inststatus'};
                   2047:                 }
                   2048:             }
1.267     raeburn  2049:             if (keys(%changed)) {
1.232     raeburn  2050:                 $changeHash{'firstname'}  = $env{'form.cfirstname'};
                   2051:                 $changeHash{'middlename'} = $env{'form.cmiddlename'};
                   2052:                 $changeHash{'lastname'}   = $env{'form.clastname'};
                   2053:                 $changeHash{'generation'} = $env{'form.cgeneration'};
                   2054:                 $changeHash{'id'}         = $env{'form.cid'};
                   2055:                 $changeHash{'permanentemail'} = $env{'form.cpermanentemail'};
1.267     raeburn  2056:                 my $chgresult =
                   2057:                      &Apache::lonnet::put('environment',\%changeHash,
                   2058:                                           $env{'form.ccdomain'},$env{'form.ccuname'});
                   2059:             } 
1.232     raeburn  2060:         }
1.219     raeburn  2061:         $r->print('<br />'.&mt('Home server').': '.$uhome.' '.
                   2062:                   &Apache::lonnet::hostname($uhome));
1.101     albertel 2063:     } elsif (($env{'form.login'} ne 'nochange') &&
                   2064:              ($env{'form.login'} ne ''        )) {
1.27      matthew  2065: 	# Modify user privileges
                   2066:         if (! $amode || ! $genpwd) {
1.193     raeburn  2067: 	    $r->print($error.'Invalid login mode or password'.$end.$rtnlink);    
1.27      matthew  2068: 	    return;
1.20      harris41 2069: 	}
1.27      matthew  2070: 	# Only allow authentification modification if the person has authority
1.101     albertel 2071: 	if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
1.20      harris41 2072: 	    $r->print('Modifying authentication: '.
1.31      matthew  2073:                       &Apache::lonnet::modifyuserauth(
1.101     albertel 2074: 		       $env{'form.ccdomain'},$env{'form.ccuname'},
1.21      harris41 2075:                        $amode,$genpwd));
1.102     albertel 2076:             $r->print('<br />'.&mt('Home server').': '.&Apache::lonnet::homeserver
1.101     albertel 2077: 		  ($env{'form.ccuname'},$env{'form.ccdomain'}));
1.4       www      2078: 	} else {
1.27      matthew  2079: 	    # Okay, this is a non-fatal error.
1.193     raeburn  2080: 	    $r->print($error.&mt('You do not have the authority to modify this users authentification information').'.'.$end);    
1.27      matthew  2081: 	}
1.28      matthew  2082:     }
                   2083:     ##
1.213     raeburn  2084:     my (@userroles,%userupdate,$cnum,$cdom,$namechanged);
                   2085:     if ($context eq 'course') {
                   2086:         ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity();
                   2087:     }
1.101     albertel 2088:     if (! $env{'form.makeuser'} ) {
1.28      matthew  2089:         # Check for need to change
                   2090:         my %userenv = &Apache::lonnet::get
1.134     raeburn  2091:             ('environment',['firstname','middlename','lastname','generation',
1.267     raeburn  2092:              'id','permanentemail','portfolioquota','inststatus','tools.aboutme',
1.279     raeburn  2093:              'tools.blog','tools.portfolio','requestcourses.official',
1.295.2.3! raeburn  2094:              'requestcourses.unofficial','requestcourses.community',
        !          2095:              'reqcrsotherdom.official','reqcrsotherdom.unofficial',
        !          2096:              'reqcrsotherdom.community'],
1.160     raeburn  2097:               $env{'form.ccdomain'},$env{'form.ccuname'});
1.28      matthew  2098:         my ($tmp) = keys(%userenv);
                   2099:         if ($tmp =~ /^(con_lost|error)/i) { 
                   2100:             %userenv = ();
                   2101:         }
1.206     raeburn  2102:         my $no_forceid_alert;
                   2103:         # Check to see if user information can be changed
                   2104:         my %domconfig =
                   2105:             &Apache::lonnet::get_dom('configuration',['usermodification'],
                   2106:                                      $env{'form.ccdomain'});
1.213     raeburn  2107:         my @statuses = ('active','future');
                   2108:         my %roles = &Apache::lonnet::get_my_roles($env{'form.ccuname'},$env{'form.ccdomain'},'userroles',\@statuses,undef,$env{'request.role.domain'});
                   2109:         my ($auname,$audom);
1.220     raeburn  2110:         if ($context eq 'author') {
1.206     raeburn  2111:             $auname = $env{'user.name'};
                   2112:             $audom = $env{'user.domain'};     
                   2113:         }
                   2114:         foreach my $item (keys(%roles)) {
1.220     raeburn  2115:             my ($rolenum,$roledom,$role) = split(/:/,$item,-1);
1.206     raeburn  2116:             if ($context eq 'course') {
                   2117:                 if ($cnum ne '' && $cdom ne '') {
                   2118:                     if ($rolenum eq $cnum && $roledom eq $cdom) {
                   2119:                         if (!grep(/^\Q$role\E$/,@userroles)) {
                   2120:                             push(@userroles,$role);
                   2121:                         }
                   2122:                     }
                   2123:                 }
                   2124:             } elsif ($context eq 'author') {
                   2125:                 if ($rolenum eq $auname && $roledom eq $audom) {
                   2126:                     if (!grep(/^\Q$role\E$/,@userroles)) { 
                   2127:                         push(@userroles,$role);
                   2128:                     }
                   2129:                 }
                   2130:             }
                   2131:         }
1.220     raeburn  2132:         if ($env{'form.action'} eq 'singlestudent') {
                   2133:             if (!grep(/^st$/,@userroles)) {
                   2134:                 push(@userroles,'st');
                   2135:             }
                   2136:         } else {
                   2137:             # Check for course or co-author roles being activated or re-enabled
                   2138:             if ($context eq 'author' || $context eq 'course') {
                   2139:                 foreach my $key (keys(%env)) {
                   2140:                     if ($context eq 'author') {
                   2141:                         if ($key=~/^form\.act_\Q$audom\E_\Q$auname\E_([^_]+)/) {
                   2142:                             if (!grep(/^\Q$1\E$/,@userroles)) {
                   2143:                                 push(@userroles,$1);
                   2144:                             }
                   2145:                         } elsif ($key =~/^form\.ren\:\Q$audom\E\/\Q$auname\E_([^_]+)/) {
                   2146:                             if (!grep(/^\Q$1\E$/,@userroles)) {
                   2147:                                 push(@userroles,$1);
                   2148:                             }
1.206     raeburn  2149:                         }
1.220     raeburn  2150:                     } elsif ($context eq 'course') {
                   2151:                         if ($key=~/^form\.act_\Q$cdom\E_\Q$cnum\E_([^_]+)/) {
                   2152:                             if (!grep(/^\Q$1\E$/,@userroles)) {
                   2153:                                 push(@userroles,$1);
                   2154:                             }
                   2155:                         } elsif ($key =~/^form\.ren\:\Q$cdom\E\/\Q$cnum\E(\/?\w*)_([^_]+)/) {
                   2156:                             if (!grep(/^\Q$1\E$/,@userroles)) {
                   2157:                                 push(@userroles,$1);
                   2158:                             }
1.206     raeburn  2159:                         }
                   2160:                     }
                   2161:                 }
                   2162:             }
                   2163:         }
                   2164:         #Check to see if we can change personal data for the user 
                   2165:         my (@mod_disallowed,@longroles);
                   2166:         foreach my $role (@userroles) {
                   2167:             if ($role eq 'cr') {
                   2168:                 push(@longroles,'Custom');
                   2169:             } else {
                   2170:                 push(@longroles,&Apache::lonnet::plaintext($role)); 
                   2171:             }
                   2172:         }
1.219     raeburn  2173:         my @userinfo = ('firstname','middlename','lastname','generation','permanentemail','id');
                   2174:         my %canmodify = &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},\@userinfo,\@userroles);
                   2175:         foreach my $item (@userinfo) {
1.28      matthew  2176:             # Strip leading and trailing whitespace
1.203     raeburn  2177:             $env{'form.c'.$item} =~ s/(\s+$|^\s+)//g;
1.219     raeburn  2178:             if (!$canmodify{$item}) {
1.207     raeburn  2179:                 if (defined($env{'form.c'.$item})) {
                   2180:                     if ($env{'form.c'.$item} ne $userenv{$item}) {
                   2181:                         push(@mod_disallowed,$item);
                   2182:                     }
1.206     raeburn  2183:                 }
                   2184:                 $env{'form.c'.$item} = $userenv{$item};
                   2185:             }
1.28      matthew  2186:         }
1.259     bisitz   2187:         # Check to see if we can change the Student/Employee ID
1.196     raeburn  2188:         my $forceid = $env{'form.forceid'};
                   2189:         my $recurseid = $env{'form.recurseid'};
                   2190:         my (%alerts,%rulematch,%idinst_results,%curr_rules,%got_rules);
1.203     raeburn  2191:         my %uidhash = &Apache::lonnet::idrget($env{'form.ccdomain'},
                   2192:                                             $env{'form.ccuname'});
                   2193:         if (($uidhash{$env{'form.ccuname'}}) && 
                   2194:             ($uidhash{$env{'form.ccuname'}}!~/error\:/) && 
                   2195:             (!$forceid)) {
                   2196:             if ($env{'form.cid'} ne $uidhash{$env{'form.ccuname'}}) {
                   2197:                 $env{'form.cid'} = $userenv{'id'};
1.293     bisitz   2198:                 $no_forceid_alert = &mt('New student/employee ID does not match existing ID for this user.')
1.259     bisitz   2199:                                    .'<br />'
                   2200:                                    .&mt("Change is not permitted without checking the 'Force ID change' checkbox on the previous page.")
                   2201:                                    .'<br />'."\n";
1.203     raeburn  2202:             }
                   2203:         }
                   2204:         if ($env{'form.cid'} ne $userenv{'id'}) {
1.196     raeburn  2205:             my $checkhash;
                   2206:             my $checks = { 'id' => 1 };
                   2207:             $checkhash->{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}} = 
                   2208:                    { 'newuser' => $newuser,
                   2209:                      'id'  => $env{'form.cid'}, 
                   2210:                    };
                   2211:             &Apache::loncommon::user_rule_check($checkhash,$checks,
                   2212:                 \%alerts,\%rulematch,\%idinst_results,\%curr_rules,\%got_rules);
                   2213:             if (ref($alerts{'id'}) eq 'HASH') {
                   2214:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
1.203     raeburn  2215:                    $env{'form.cid'} = $userenv{'id'};
1.196     raeburn  2216:                 }
                   2217:             }
                   2218:         }
1.286     raeburn  2219:         my ($quotachanged,$oldportfolioquota,$newportfolioquota,$oldinststatus,
                   2220:             $inststatus,$newinststatus,$oldisdefault,$newisdefault,$olddefquotatext,
                   2221:             $newdefquotatext,%oldaccess,%oldaccesstext,%newaccess,%newaccesstext,
                   2222:             $oldinststatuses,$newinststatuses);
1.149     raeburn  2223:         my ($defquota,$settingstatus) = 
                   2224:             &Apache::loncommon::default_quota($env{'form.ccdomain'},$inststatus);
1.295.2.3! raeburn  2225:         my ($showquota,$showtools,$showrequestcourses,$showinststatus,$showreqotherdom);
1.220     raeburn  2226:         if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
                   2227:             $showquota = 1;
                   2228:         }
1.267     raeburn  2229:         if (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
                   2230:             $showtools = 1;
                   2231:         }
1.275     raeburn  2232:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
                   2233:             $showrequestcourses = 1;
1.295.2.3! raeburn  2234:         } elsif (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
        !          2235:             $showreqotherdom = 1;
1.275     raeburn  2236:         }
1.286     raeburn  2237:         if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
                   2238:             $showinststatus = 1;
                   2239:         }
1.267     raeburn  2240:         my (%changeHash,%changed);
1.286     raeburn  2241:         $oldinststatus = $userenv{'inststatus'};
                   2242:         if ($oldinststatus eq '') {
                   2243:             $oldinststatuses = $othertitle; 
                   2244:         } else {
                   2245:             if (ref($usertypes) eq 'HASH') {
                   2246:                 $oldinststatuses = join(', ',map{ $usertypes->{ &unescape($_) }; } (split(/:/,$userenv{'inststatus'})));
                   2247:             } else {
                   2248:                 $oldinststatuses = join(', ',map{ &unescape($_); } (split(/:/,$userenv{'inststatus'})));
                   2249:             }
                   2250:         }
                   2251:         $changeHash{'inststatus'} = $userenv{'inststatus'};
                   2252:         my %canmodify_inststatus = &Apache::lonuserutils::can_modify_userinfo($context,$env{'form.ccdomain'},['inststatus'],\@userroles);
                   2253:         if ($canmodify_inststatus{'inststatus'}) {
                   2254:             if (exists($env{'form.inststatus'})) {
                   2255:                 my @inststatuses = &Apache::loncommon::get_env_multiple('form.inststatus');
                   2256:                 if (@inststatuses > 0) {
                   2257:                     $newinststatus = join(':',map { &escape($_); } @inststatuses);
                   2258:                     $changeHash{'inststatus'} = $newinststatus;
                   2259:                     if ($newinststatus ne $oldinststatus) {
                   2260:                         $changed{'inststatus'} = $newinststatus;
                   2261:                     }
                   2262:                     if (ref($usertypes) eq 'HASH') {
                   2263:                         $newinststatuses = join(', ',map{ $usertypes->{$_}; } (@inststatuses)); 
                   2264:                     } else {
                   2265:                         $newinststatuses = join(', ',map{ $usertypes->{$_}; } (@inststatuses));
                   2266:                     }
                   2267:                 } else {
                   2268:                     $newinststatus = '';
                   2269:                     $changeHash{'inststatus'} = $newinststatus;
                   2270:                     $newinststatuses = $othertitle;
                   2271:                     if ($newinststatus ne $oldinststatus) {
                   2272:                         $changed{'inststatus'} = $changeHash{'inststatus'};
                   2273:                     }
                   2274:                 }
                   2275:             }
                   2276:         }
1.204     raeburn  2277:         $changeHash{'portfolioquota'} = $userenv{'portfolioquota'};
1.149     raeburn  2278:         if ($userenv{'portfolioquota'} ne '') {
1.134     raeburn  2279:             $oldportfolioquota = $userenv{'portfolioquota'};
1.149     raeburn  2280:             if ($env{'form.customquota'} == 1) {
                   2281:                 if ($env{'form.portfolioquota'} eq '') {
                   2282:                     $newportfolioquota = 0;
                   2283:                 } else {
                   2284:                     $newportfolioquota = $env{'form.portfolioquota'};
                   2285:                     $newportfolioquota =~ s/[^\d\.]//g;
                   2286:                 }
1.204     raeburn  2287:                 if ($newportfolioquota != $oldportfolioquota) {
1.267     raeburn  2288:                     $changed{'quota'} = &quota_admin($newportfolioquota,\%changeHash);
1.134     raeburn  2289:                 }
1.149     raeburn  2290:             } else {
1.267     raeburn  2291:                 $changed{'quota'} = &quota_admin('',\%changeHash);
1.149     raeburn  2292:                 $newportfolioquota = $defquota;
1.284     bisitz   2293:                 $newisdefault = 1;
1.134     raeburn  2294:             }
                   2295:         } else {
1.204     raeburn  2296:             $oldisdefault = 1;
1.149     raeburn  2297:             $oldportfolioquota = $defquota;
                   2298:             if ($env{'form.customquota'} == 1) {
                   2299:                 if ($env{'form.portfolioquota'} eq '') {
                   2300:                     $newportfolioquota = 0;
                   2301:                 } else {
                   2302:                     $newportfolioquota = $env{'form.portfolioquota'};
                   2303:                     $newportfolioquota =~ s/[^\d\.]//g;
                   2304:                 }
1.267     raeburn  2305:                 $changed{'quota'} = &quota_admin($newportfolioquota,\%changeHash);
1.149     raeburn  2306:             } else {
                   2307:                 $newportfolioquota = $defquota;
1.204     raeburn  2308:                 $newisdefault = 1;
1.149     raeburn  2309:             }
                   2310:         }
1.204     raeburn  2311:         if ($oldisdefault) {
                   2312:             $olddefquotatext = &get_defaultquota_text($settingstatus);
                   2313:         }
                   2314:         if ($newisdefault) {
                   2315:             $newdefquotatext = &get_defaultquota_text($settingstatus);
1.134     raeburn  2316:         }
1.275     raeburn  2317:         &tool_changes('tools',\@usertools,\%oldaccess,\%oldaccesstext,\%userenv,
                   2318:                       \%changeHash,\%changed,\%newaccess,\%newaccesstext);
1.295.2.3! raeburn  2319: 
        !          2320:         if ($env{'form.ccdomain'} eq $env{'request.role.domain'}) {
        !          2321:             &tool_changes('requestcourses',\@requestcourses,\%oldaccess,\%oldaccesstext,
        !          2322:                           \%userenv,\%changeHash,\%changed,\%newaccess,\%newaccesstext);
        !          2323:         } else {
        !          2324:             &tool_changes('reqcrsotherdom',\@requestcourses,\%oldaccess,\%oldaccesstext,
        !          2325:                           \%userenv,\%changeHash,\%changed,\%newaccess,\%newaccesstext);
        !          2326:         }
1.206     raeburn  2327:         if ($env{'form.cfirstname'}  ne $userenv{'firstname'}  ||
                   2328:             $env{'form.cmiddlename'} ne $userenv{'middlename'} ||
                   2329:             $env{'form.clastname'}   ne $userenv{'lastname'}   ||
                   2330:             $env{'form.cgeneration'} ne $userenv{'generation'} ||
                   2331:             $env{'form.cid'} ne $userenv{'id'}                 ||
                   2332:             $env{'form.cpermanentemail'} ne $userenv{'permanentemail'} ) {
1.134     raeburn  2333:             $namechanged = 1;
                   2334:         }
1.267     raeburn  2335:         if (($namechanged) || (keys(%changed) > 0)) {
1.101     albertel 2336:             $changeHash{'firstname'}  = $env{'form.cfirstname'};
                   2337:             $changeHash{'middlename'} = $env{'form.cmiddlename'};
                   2338:             $changeHash{'lastname'}   = $env{'form.clastname'};
                   2339:             $changeHash{'generation'} = $env{'form.cgeneration'};
1.196     raeburn  2340:             $changeHash{'id'}         = $env{'form.cid'};
1.174     raeburn  2341:             $changeHash{'permanentemail'} = $env{'form.cpermanentemail'};
1.267     raeburn  2342:             my ($chgresult,$namechgresult);
                   2343:             if (keys(%changed) > 0) {
                   2344:                 $chgresult = 
1.204     raeburn  2345:                     &Apache::lonnet::put('environment',\%changeHash,
                   2346:                                   $env{'form.ccdomain'},$env{'form.ccuname'});
1.267     raeburn  2347:                 if ($chgresult eq 'ok') {
                   2348:                     if (($env{'user.name'} eq $env{'form.ccuname'}) &&
                   2349:                         ($env{'user.domain'} eq $env{'form.ccdomain'})) {
1.270     raeburn  2350:                         my %newenvhash;
                   2351:                         foreach my $key (keys(%changed)) {
1.275     raeburn  2352:                             if (($key eq 'official') || ($key eq 'unofficial')) {
1.279     raeburn  2353:                                 $newenvhash{'environment.requestcourses.'.$key} =
                   2354:                                     $changeHash{'requestcourses.'.$key};
                   2355:                                 if ($changeHash{'requestcourses.'.$key} ne '') {
                   2356:                                     $newenvhash{'environment.canrequest.'.$key} =
                   2357:                                         $changeHash{'requestcourses.'.$key};
                   2358:                                 } else {
                   2359:                                     $newenvhash{'environment.canrequest.'.$key} =
                   2360:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},
                   2361:                                             $key,'reload','requestcourses');
                   2362:                                 }
1.275     raeburn  2363:                             } elsif ($key ne 'quota') {
1.270     raeburn  2364:                                 $newenvhash{'environment.tools.'.$key} = 
                   2365:                                     $changeHash{'tools.'.$key};
1.279     raeburn  2366:                                 if ($changeHash{'tools.'.$key} ne '') {
                   2367:                                     $newenvhash{'environment.availabletools.'.$key} =
                   2368:                                         $changeHash{'tools.'.$key};
                   2369:                                 } else {
                   2370:                                     $newenvhash{'environment.availabletools.'.$key} =
                   2371:           &Apache::lonnet::usertools_access($env{'user.name'},$env{'user.domain'},                                            $key,'reload','tools');
                   2372:                                 }
1.270     raeburn  2373:                             }
                   2374:                         }
1.271     raeburn  2375:                         if (keys(%newenvhash)) {
                   2376:                             &Apache::lonnet::appenv(\%newenvhash);
                   2377:                         }
1.267     raeburn  2378:                     }
                   2379:                 }
1.204     raeburn  2380:             }
                   2381:             if ($namechanged) {
                   2382:             # Make the change
                   2383:                 $namechgresult =
                   2384:                     &Apache::lonnet::modifyuser($env{'form.ccdomain'},
                   2385:                         $env{'form.ccuname'},$changeHash{'id'},undef,undef,
                   2386:                         $changeHash{'firstname'},$changeHash{'middlename'},
                   2387:                         $changeHash{'lastname'},$changeHash{'generation'},
                   2388:                         $changeHash{'id'},undef,$changeHash{'permanentemail'});
1.220     raeburn  2389:                 %userupdate = (
                   2390:                                lastname   => $env{'form.clastname'},
                   2391:                                middlename => $env{'form.cmiddlename'},
                   2392:                                firstname  => $env{'form.cfirstname'},
                   2393:                                generation => $env{'form.cgeneration'},
                   2394:                                id         => $env{'form.cid'},
                   2395:                              );
1.204     raeburn  2396:             }
                   2397:             if (($namechanged && $namechgresult eq 'ok') || 
1.267     raeburn  2398:                 ((keys(%changed) > 0) && $chgresult eq 'ok')) {
1.28      matthew  2399:             # Tell the user we changed the name
1.73      sakharuk 2400: 		my %lt=&Apache::lonlocal::texthash(
1.284     bisitz   2401:                              'uic'        => 'User Information Changed',
                   2402:                              'frst'       => 'First Name',
                   2403:                              'mddl'       => 'Middle Name',
                   2404:                              'lst'        => 'Last Name',
                   2405:                              'gen'        => 'Generation',
                   2406:                              'id'         => 'Student/Employee ID',
                   2407:                              'mail'       => 'Permanent e-mail address',
                   2408:                              'disk'       => 'Disk space allocated to portfolio files',
                   2409:                              'blog'       => 'Blog Availability',
                   2410:                              'aboutme'    => 'Personal Information Page Availability',
                   2411:                              'portfolio'  => 'Portfolio Availability',
                   2412:                              'official'   => 'Can Request Official Courses',
                   2413:                              'unofficial' => 'Can Request Unofficial Courses',
1.286     raeburn  2414:                              'inststatus' => "Affiliation",
1.284     bisitz   2415:                              'prvs'       => 'Previous Value:',
                   2416:                              'chto'       => 'Changed To:'
1.73      sakharuk 2417: 						   );
1.201     raeburn  2418:                 $r->print('<h4>'.$lt{'uic'}.'</h4>'.
                   2419:                           &Apache::loncommon::start_data_table().
                   2420:                           &Apache::loncommon::start_data_table_header_row());
1.28      matthew  2421:                 $r->print(<<"END");
1.201     raeburn  2422:     <th>&nbsp;</th>
1.73      sakharuk 2423:     <th>$lt{'frst'}</th>
                   2424:     <th>$lt{'mddl'}</th>
                   2425:     <th>$lt{'lst'}</th>
1.134     raeburn  2426:     <th>$lt{'gen'}</th>
1.196     raeburn  2427:     <th>$lt{'id'}</th>
1.173     raeburn  2428:     <th>$lt{'mail'}</th>
1.201     raeburn  2429: END
1.286     raeburn  2430:                 if ($showinststatus) {
                   2431:                     $r->print("
                   2432:     <th>$lt{'inststatus'}</th>\n");
                   2433:                 }
1.275     raeburn  2434:                 if ($showrequestcourses) {
                   2435:                     foreach my $item (@requestcourses) {
                   2436:                         $r->print("
                   2437:     <th>$lt{$item}</th>\n");
                   2438:                     }
1.295.2.3! raeburn  2439:                 } elsif ($showreqotherdom) {
        !          2440:                     foreach my $item (@requestcourses) {
        !          2441:                         $r->print("
        !          2442:     <th>$lt{$item}</th>\n");
        !          2443:                     }
1.275     raeburn  2444:                 }
1.220     raeburn  2445:                 if ($showquota) {
                   2446:                     $r->print("
                   2447:     <th>$lt{'disk'}</th>\n");
                   2448:                 }
1.267     raeburn  2449:                 if ($showtools) {
                   2450:                     foreach my $item (@usertools) {
                   2451:                         $r->print("
                   2452:     <th>$lt{$item}</th>\n");
                   2453:                     }
                   2454:                 }
1.201     raeburn  2455:                 $r->print(&Apache::loncommon::end_data_table_header_row().
                   2456:                           &Apache::loncommon::start_data_table_row());
                   2457:                 $r->print(<<"END");
                   2458:     <td><b>$lt{'prvs'}</b></td>
1.28      matthew  2459:     <td>$userenv{'firstname'}  </td>
                   2460:     <td>$userenv{'middlename'} </td>
                   2461:     <td>$userenv{'lastname'}   </td>
1.134     raeburn  2462:     <td>$userenv{'generation'} </td>
1.196     raeburn  2463:     <td>$userenv{'id'}</td>
1.160     raeburn  2464:     <td>$userenv{'permanentemail'} </td>
1.201     raeburn  2465: END
1.286     raeburn  2466:                 if ($showinststatus) {
                   2467:                     $r->print("
                   2468:     <td>$oldinststatuses</td>\n");
                   2469:                 }  
1.275     raeburn  2470:                 if ($showrequestcourses) {
                   2471:                     foreach my $item (@requestcourses) {
                   2472:                         $r->print("
                   2473:     <td>$oldaccess{$item} $oldaccesstext{$item}</td>\n");
                   2474:                     }
1.295.2.3! raeburn  2475:                 } elsif ($showreqotherdom) {
        !          2476:                     foreach my $item (@requestcourses) {
        !          2477:                         $r->print("
        !          2478:     <td>$oldaccess{$item} $oldaccesstext{$item}</td>\n");
        !          2479:                     }
1.275     raeburn  2480:                 }
1.220     raeburn  2481:                 if ($showquota) {
                   2482:                     $r->print("
                   2483:     <td>$oldportfolioquota Mb $olddefquotatext </td>\n");
                   2484:                 }
1.267     raeburn  2485:                 if ($showtools) {
                   2486:                     foreach my $item (@usertools) {
                   2487:                         $r->print("
                   2488:     <td>$oldaccess{$item} $oldaccesstext{$item} </td>\n");
                   2489:                     }
                   2490:                 }
1.201     raeburn  2491:                 $r->print(&Apache::loncommon::end_data_table_row().
                   2492:                           &Apache::loncommon::start_data_table_row());
                   2493:                 $r->print(<<"END");
1.267     raeburn  2494:     <td><span class="LC_nobreak"><b>$lt{'chto'}</b></span></td>
1.101     albertel 2495:     <td>$env{'form.cfirstname'}  </td>
                   2496:     <td>$env{'form.cmiddlename'} </td>
                   2497:     <td>$env{'form.clastname'}   </td>
1.134     raeburn  2498:     <td>$env{'form.cgeneration'} </td>
1.196     raeburn  2499:     <td>$env{'form.cid'} </td>
1.160     raeburn  2500:     <td>$env{'form.cpermanentemail'} </td>
1.28      matthew  2501: END
1.286     raeburn  2502:                 if ($showinststatus) {
                   2503:                     $r->print("
                   2504:     <td>$newinststatuses</td>\n");
                   2505:                 }
1.275     raeburn  2506:                 if ($showrequestcourses) {
                   2507:                     foreach my $item (@requestcourses) {
                   2508:                         $r->print("
                   2509:     <td>$newaccess{$item} $newaccesstext{$item} </td>\n");
                   2510:                     }
1.295.2.3! raeburn  2511:                 } elsif ($showreqotherdom) {
        !          2512:                     foreach my $item (@requestcourses) {
        !          2513:                         $r->print("
        !          2514:     <td>$newaccess{$item} $newaccesstext{$item} </td>\n");
        !          2515:                     }
1.275     raeburn  2516:                 }
1.220     raeburn  2517:                 if ($showquota) {
                   2518:                     $r->print("
                   2519:     <td>$newportfolioquota Mb $newdefquotatext </td>\n");
                   2520:                 }
1.267     raeburn  2521:                 if ($showtools) {
                   2522:                     foreach my $item (@usertools) {
                   2523:                         $r->print("
                   2524:     <td>$newaccess{$item} $newaccesstext{$item} </td>\n");
                   2525:                     }
                   2526:                 }
1.201     raeburn  2527:                 $r->print(&Apache::loncommon::end_data_table_row().
1.206     raeburn  2528:                           &Apache::loncommon::end_data_table().'<br />');
1.203     raeburn  2529:                 if ($env{'form.cid'} ne $userenv{'id'}) {
                   2530:                     &Apache::lonnet::idput($env{'form.ccdomain'},
                   2531:                          ($env{'form.ccuname'} => $env{'form.cid'}));
                   2532:                     if (($recurseid) &&
                   2533:                         (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'}))) {
                   2534:                         my $idresult = 
                   2535:                             &Apache::lonuserutils::propagate_id_change(
                   2536:                                 $env{'form.ccuname'},$env{'form.ccdomain'},
                   2537:                                 \%userupdate);
                   2538:                         $r->print('<br />'.$idresult.'<br />');
                   2539:                     }
1.196     raeburn  2540:                 }
1.149     raeburn  2541:                 if (($env{'form.ccdomain'} eq $env{'user.domain'}) && 
                   2542:                     ($env{'form.ccuname'} eq $env{'user.name'})) {
                   2543:                     my %newenvhash;
                   2544:                     foreach my $key (keys(%changeHash)) {
                   2545:                         $newenvhash{'environment.'.$key} = $changeHash{$key};
                   2546:                     }
1.238     raeburn  2547:                     &Apache::lonnet::appenv(\%newenvhash);
1.149     raeburn  2548:                 }
1.28      matthew  2549:             } else { # error occurred
1.188     raeburn  2550:                 $r->print('<span class="LC_error">'.&mt('Unable to successfully change environment for').' '.
                   2551:                       $env{'form.ccuname'}.' '.&mt('in domain').' '.
1.206     raeburn  2552:                       $env{'form.ccdomain'}.'</span><br />');
1.28      matthew  2553:             }
1.101     albertel 2554:         }  else { # End of if ($env ... ) logic
1.275     raeburn  2555:             # They did not want to change the users name, quota, tool availability,
                   2556:             # or ability to request creation of courses, 
1.267     raeburn  2557:             # but we can still tell them what the name and quota and availabilities are  
1.73      sakharuk 2558: 	    my %lt=&Apache::lonlocal::texthash(
1.275     raeburn  2559:                            'id'         => "Student/Employee ID",
1.284     bisitz   2560:                            'mail'       => "Permanent e-mail address",
1.275     raeburn  2561:                            'disk'       => "Disk space allocated to user's portfolio files",
                   2562:                            'blog'       => "Blog Availability",
1.285     weissno  2563:                            'aboutme'    => "Personal Information Page Availability",
1.275     raeburn  2564:                            'portfolio'  => "Portfolio Availability",
                   2565:                            'official'   => "Can Request Official Courses",
                   2566:                            'unofficial' => "Can Request Unofficial Course",
1.286     raeburn  2567:                            'inststatus' => "Affiliation",
1.73      sakharuk 2568: 					       );
1.134     raeburn  2569:             $r->print(<<"END");
1.196     raeburn  2570: <h4>$userenv{'firstname'} $userenv{'middlename'} $userenv{'lastname'} $userenv{'generation'}
1.28      matthew  2571: END
1.204     raeburn  2572:             if ($userenv{'permanentemail'} ne '') {
                   2573:                 $r->print('<br />['.$lt{'mail'}.': '.
                   2574:                           $userenv{'permanentemail'}.']');
1.134     raeburn  2575:             }
1.286     raeburn  2576:             if ($showinststatus) {
                   2577:                 $r->print('<br />['.$lt{'inststatus'}.': '.$oldinststatuses.']');
                   2578:             }
1.275     raeburn  2579:             if ($showrequestcourses) {
                   2580:                 foreach my $item (@requestcourses) {
                   2581:                     $r->print('<br />['.$lt{$item}.': '.$newaccess{$item}.' '.
                   2582:                               $newaccesstext{$item}.']'."\n");
                   2583:                 }
1.295.2.3! raeburn  2584:             } elsif ($showreqotherdom) {
        !          2585:                 foreach my $item (@requestcourses) {
        !          2586:                     $r->print('<br />['.$lt{$item}.': '.$newaccess{$item}.' '.
        !          2587:                               $newaccesstext{$item}.']'."\n");
        !          2588:                 }
1.275     raeburn  2589:             }
1.267     raeburn  2590:             if ($showtools) {
                   2591:                 foreach my $item (@usertools) {
                   2592:                     $r->print('<br />['.$lt{$item}.': '.$newaccess{$item}.' '.
                   2593:                               $newaccesstext{$item}.']'."\n");
                   2594:                 }
                   2595:             }
1.220     raeburn  2596:             if ($showquota) {
1.267     raeburn  2597:                 $r->print('<br />['.$lt{'disk'}.': '.$oldportfolioquota.' Mb '.
1.220     raeburn  2598:                           $olddefquotatext.']');
                   2599:             }
                   2600:             $r->print('</h4>');
1.28      matthew  2601:         }
1.206     raeburn  2602:         if (@mod_disallowed) {
                   2603:             my ($rolestr,$contextname);
                   2604:             if (@longroles > 0) {
                   2605:                 $rolestr = join(', ',@longroles);
                   2606:             } else {
                   2607:                 $rolestr = &mt('No roles');
                   2608:             }
                   2609:             if ($context eq 'course') {
                   2610:                 $contextname = &mt('course');
                   2611:             } elsif ($context eq 'author') {
                   2612:                 $contextname = &mt('co-author');
                   2613:             }
                   2614:             $r->print(&mt('The following fields were not updated: ').'<ul>');
                   2615:             my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
                   2616:             foreach my $field (@mod_disallowed) {
                   2617:                 $r->print('<li>'.$fieldtitles{$field}.'</li>'."\n"); 
                   2618:             }
1.207     raeburn  2619:             $r->print('</ul>');
                   2620:             if (@mod_disallowed == 1) {
                   2621:                 $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));
                   2622:             } else {
                   2623:                 $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));
                   2624:             }
1.292     bisitz   2625:             my $helplink = 'javascript:helpMenu('."'display'".')';
                   2626:             $r->print('<span class="LC_cusr_emph">'.$rolestr.'</span><br />'
                   2627:                      .&mt('Please contact your [_1]helpdesk[_2] for more information.'
                   2628:                          ,'<a href="'.$helplink.'">','</a>')
                   2629:                       .'<br />');
1.206     raeburn  2630:         }
1.259     bisitz   2631:         $r->print('<span class="LC_warning">'
                   2632:                   .$no_forceid_alert
                   2633:                   .&Apache::lonuserutils::print_namespacing_alerts($env{'form.ccdomain'},\%alerts,\%curr_rules)
                   2634:                   .'</span>');
1.4       www      2635:     }
1.220     raeburn  2636:     if ($env{'form.action'} eq 'singlestudent') {
1.239     raeburn  2637:         &enroll_single_student($r,$uhome,$amode,$genpwd,$now,$newuser,$context);
                   2638:         $r->print('<p><a href="javascript:backPage(document.userupdate)">'.
                   2639:                   &mt('Enroll Another Student').'</a></p>');
1.220     raeburn  2640:     } else {
1.239     raeburn  2641:         my @rolechanges = &update_roles($r,$context);
1.225     raeburn  2642:         if ($namechanged) {
1.220     raeburn  2643:             if ($context eq 'course') {
                   2644:                 if (@userroles > 0) {
1.225     raeburn  2645:                     if ((@rolechanges == 0) || 
                   2646:                         (!(grep(/^st$/,@rolechanges)))) {
                   2647:                         if (grep(/^st$/,@userroles)) {
                   2648:                             my $classlistupdated =
                   2649:                                 &Apache::lonuserutils::update_classlist($cdom,
1.220     raeburn  2650:                                               $cnum,$env{'form.ccdomain'},
                   2651:                                        $env{'form.ccuname'},\%userupdate);
1.225     raeburn  2652:                         }
1.220     raeburn  2653:                     }
                   2654:                 }
                   2655:             }
                   2656:         }
1.226     raeburn  2657:         my $userinfo = &Apache::loncommon::plainname($env{'form.ccuname'},
1.233     raeburn  2658:                                                      $env{'form.ccdomain'});
                   2659:         if ($env{'form.popup'}) {
                   2660:             $r->print('<p><a href="javascript:window.close()">'.&mt('Close window').'</a></p>');
                   2661:         } else {
1.246     bisitz   2662:             $r->print('<p><a href="javascript:backPage(document.userupdate,'."'$env{'form.prevphase'}','modify'".')">'
                   2663:                      .&mt('Modify this user: [_1]','<span class="LC_cusr_emph">'.$env{'form.ccuname'}.':'.$env{'form.ccdomain'}.' ('.$userinfo.')</span>').'</a>'
                   2664:                      .('&nbsp;'x5).'<a href="javascript:backPage(document.userupdate)">'
                   2665:                      .&mt('Create/Modify Another User').'</a></p>');
1.233     raeburn  2666:         }
1.220     raeburn  2667:     }
                   2668:     $r->print(&Apache::loncommon::end_page());
                   2669: }
                   2670: 
1.275     raeburn  2671: sub tool_changes {
                   2672:     my ($context,$usertools,$oldaccess,$oldaccesstext,$userenv,$changeHash,
                   2673:         $changed,$newaccess,$newaccesstext) = @_;
                   2674:     if (!((ref($usertools) eq 'ARRAY') && (ref($oldaccess) eq 'HASH') &&
                   2675:           (ref($oldaccesstext) eq 'HASH') && (ref($userenv) eq 'HASH') &&
                   2676:           (ref($changeHash) eq 'HASH') && (ref($changed) eq 'HASH') &&
                   2677:           (ref($newaccess) eq 'HASH') && (ref($newaccesstext) eq 'HASH'))) {
                   2678:         return;
                   2679:     }
1.295.2.3! raeburn  2680:     if ($context eq 'reqcrsotherdom') {
        !          2681:         my @options = ('approve','validate','autolimit');
        !          2682:         my $optregex = join('|',@options);
        !          2683:         my %reqdisplay = &courserequest_display();
        !          2684:         my $cdom = $env{'request.role.domain'};
        !          2685:         foreach my $tool (@{$usertools}) {
        !          2686:             $oldaccesstext->{$tool} = &mt('no');
        !          2687:             $changeHash->{$context.'.'.$tool} = $userenv->{$context.'.'.$tool
        !          2688: };
        !          2689:             if ($userenv->{$context.'.'.$tool} eq '') {
        !          2690:                 if ($env{'form.'.$context.'_'.$tool}) {
        !          2691:                     $changed->{$tool}=&tool_admin($tool,$cdom,
        !          2692:                                                   $changeHash,$context);
        !          2693:                     if ($changed->{$tool}) {
        !          2694:                         $newaccesstext->{$tool} = &mt('yes');
        !          2695:                     } else {
        !          2696:                         $newaccesstext->{$tool} = $oldaccesstext->{$tool};                    }
        !          2697:                 }
        !          2698:             } else {
        !          2699:                 my @curr = split(',',$userenv->{$context.'.'.$tool});
        !          2700:                 my @new;
        !          2701:                 my $changedoms;
        !          2702:                 my $newop = $env{'form.'.$context.'_'.$tool};
        !          2703:                 if ($newop eq 'autolimit') {
        !          2704:                     $newop .= '=';
        !          2705:                     unless ($env{'form.'.$context.'_'.$tool.'_limit'} =~ /\D/
        !          2706: ) {
        !          2707:                         $newop .= $env{'form.'.$context.'_'.$tool.'_limit'};
        !          2708:                     }
        !          2709:                 }
        !          2710:                 if (grep(/^\Q$cdom:($optregex\=?\d*)\E$/,@curr)) {
        !          2711:                     $oldaccesstext->{$tool} = &mt('yes');
        !          2712:                     my $oldop = $1;
        !          2713:                     if ($oldop ne $newop) {
        !          2714:                         $changedoms = 1;
        !          2715:                         foreach my $dom (@curr) {
        !          2716:                             unless ($dom eq $cdom) {
        !          2717:                                 push(@new,$dom);
        !          2718:                             }
        !          2719:                         }
        !          2720:                         if ($newop) {
        !          2721:                             push(@new,$cdom.':'.$newop);
        !          2722:                         }
        !          2723:                         @new = sort(@new);
        !          2724:                     }
        !          2725:                 } elsif ($env{'form.'.$context.'_'.$tool}) {
        !          2726:                     $changedoms = 1;
        !          2727:                     $changedoms = 1;
        !          2728:                     @new = sort(@curr,$cdom.':'.$newop);
        !          2729:                 }
        !          2730:                 $newaccesstext->{$tool} = $oldaccesstext->{$tool};
        !          2731:                 if ($changedoms) {
        !          2732:                     my $newdomstr;
        !          2733:                     if (@new) {
        !          2734:                         $newdomstr = join(',',@new);
        !          2735:                     }
        !          2736:                     $changed->{$tool}=&tool_admin($tool,$newdomstr,$changeHash,
        !          2737:                                                   $context);
        !          2738:                     if ($changed->{$tool}) {
        !          2739:                         if ($env{'form.'.$context.'_'.$tool}) {
        !          2740:                             if ($env{'form.'.$context.'_'.$tool} eq 'autolimit') {
        !          2741:                                 if ($env{'form.'.$context.'_'.$tool.'_limit'} =~ /\D/) {
        !          2742:                                     $newaccesstext->{$tool} = &mt('Yes, processed automatically');
        !          2743:                                 } else {
        !          2744:                                     $newaccesstext->{$tool} = &mt('Yes, up to limit of [quant,_1,request] per user).',$env{'form.'.$context.'_'.$tool.'_limit'});
        !          2745:                                 }
        !          2746:                             } else {
        !          2747:                                 $newaccesstext->{$tool} = $reqdisplay{$env{'form.'.$context.'_'.$tool}};
        !          2748:                             }
        !          2749:                         } else {
        !          2750:                             $newaccesstext->{$tool} = &mt('No');
        !          2751:                         }
        !          2752:                     }
        !          2753:                 }
        !          2754:             }
        !          2755:         }
        !          2756:         return;
        !          2757:     }
1.275     raeburn  2758:     foreach my $tool (@{$usertools}) {
                   2759:         if ($userenv->{$context.'.'.$tool} ne '') {
                   2760:             $oldaccess->{$tool} = &mt('custom');
                   2761:             if ($userenv->{$context.'.'.$tool}) {
                   2762:                 $oldaccesstext->{$tool} = &mt("availability set to 'on'");
                   2763:             } else {
                   2764:                 $oldaccesstext->{$tool} = &mt("availability set to 'off'");
                   2765:             }
1.279     raeburn  2766:             $changeHash->{$context.'.'.$tool} = $userenv->{$context.'.'.$tool};
1.275     raeburn  2767:             if ($env{'form.custom'.$tool} == 1) {
1.279     raeburn  2768:                 if ($env{'form.'.$context.'_'.$tool} ne $userenv->{$context.'.'.$tool}) {
1.275     raeburn  2769:                     $changed->{$tool} = &tool_admin($tool,$env{'form.'.$context.'_'.$tool},
                   2770:                                                   $changeHash,$context);
                   2771:                     if ($changed->{$tool}) {
                   2772:                         $newaccess->{$tool} = &mt('custom');
                   2773:                         if ($env{'form.'.$context.'_'.$tool}) {
                   2774:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
                   2775:                         } else {
                   2776:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
                   2777:                         }
                   2778:                     } else {
                   2779:                         $newaccess->{$tool} = $oldaccess->{$tool};
                   2780:                         if ($userenv->{$context.'.'.$tool}) {
                   2781:                             $newaccesstext->{$tool} = &mt("availability set to 'on'");
                   2782:                         } else {
                   2783:                             $newaccesstext->{$tool} = &mt("availability set to 'off'");
                   2784:                         }
                   2785:                     }
                   2786:                 } else {
                   2787:                     $newaccess->{$tool} = $oldaccess->{$tool};
                   2788:                     $newaccesstext->{$tool} = $oldaccesstext->{$tool};
                   2789:                 }
                   2790:             } else {
                   2791:                 $changed->{$tool} = &tool_admin($tool,'',$changeHash,$context);
                   2792:                 if ($changed->{$tool}) {
                   2793:                     $newaccess->{$tool} = &mt('default');
                   2794:                 } else {
                   2795:                     $newaccess->{$tool} = $oldaccess->{$tool};
                   2796:                     if ($userenv->{$context.'.'.$tool}) {
                   2797:                          $newaccesstext->{$tool} = &mt("availability set to 'on'");
                   2798:                     } else {
                   2799:                          $newaccesstext->{$tool} = &mt("availability set to 'off'");
                   2800:                     }
                   2801:                 }
                   2802:             }
                   2803:         } else {
                   2804:             $oldaccess->{$tool} = &mt('default');
                   2805:             if ($env{'form.custom'.$tool} == 1) {
                   2806:                 $changed->{$tool} = &tool_admin($tool,$env{'form.'.$context.'_'.$tool},
                   2807:                                                 $changeHash,$context);
                   2808:                 if ($changed->{$tool}) {
                   2809:                     $newaccess->{$tool} = &mt('custom');
                   2810:                     if ($env{'form.'.$context.'_'.$tool}) {
                   2811:                         $newaccesstext->{$tool} = &mt("availability set to 'on'");
                   2812:                     } else {
                   2813:                         $newaccesstext->{$tool} = &mt("availability set to 'off'");
                   2814:                     }
                   2815:                 } else {
                   2816:                     $newaccess->{$tool} = $oldaccess->{$tool};
                   2817:                 }
                   2818:             } else {
                   2819:                 $newaccess->{$tool} = $oldaccess->{$tool};
                   2820:             }
                   2821:         }
                   2822:     }
                   2823:     return;
                   2824: }
                   2825: 
1.220     raeburn  2826: sub update_roles {
1.239     raeburn  2827:     my ($r,$context) = @_;
1.4       www      2828:     my $now=time;
1.225     raeburn  2829:     my @rolechanges;
1.220     raeburn  2830:     my %disallowed;
1.73      sakharuk 2831:     $r->print('<h3>'.&mt('Modifying Roles').'</h3>');
1.135     raeburn  2832:     foreach my $key (keys (%env)) {
                   2833: 	next if (! $env{$key});
1.190     raeburn  2834:         next if ($key eq 'form.action');
1.27      matthew  2835: 	# Revoke roles
1.135     raeburn  2836: 	if ($key=~/^form\.rev/) {
                   2837: 	    if ($key=~/^form\.rev\:([^\_]+)\_([^\_\.]+)$/) {
1.64      www      2838: # Revoke standard role
1.170     albertel 2839: 		my ($scope,$role) = ($1,$2);
                   2840: 		my $result =
                   2841: 		    &Apache::lonnet::revokerole($env{'form.ccdomain'},
                   2842: 						$env{'form.ccuname'},
1.239     raeburn  2843: 						$scope,$role,'','',$context);
1.170     albertel 2844: 	        $r->print(&mt('Revoking [_1] in [_2]: [_3]',
                   2845: 			      $role,$scope,'<b>'.$result.'</b>').'<br />');
                   2846: 		if ($role eq 'st') {
1.202     raeburn  2847: 		    my $result = 
1.198     raeburn  2848:                         &Apache::lonuserutils::classlist_drop($scope,
                   2849:                             $env{'form.ccuname'},$env{'form.ccdomain'},
1.202     raeburn  2850: 			    $now);
1.170     albertel 2851: 		    $r->print($result);
1.53      www      2852: 		}
1.225     raeburn  2853:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
                   2854:                     push(@rolechanges,$role);
                   2855:                 }
1.196     raeburn  2856: 	    }
1.195     raeburn  2857: 	    if ($key=~m{^form\.rev\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}s) {
1.64      www      2858: # Revoke custom role
1.113     raeburn  2859: 		$r->print(&mt('Revoking custom role:').
1.139     albertel 2860:                       ' '.$4.' by '.$3.':'.$2.' in '.$1.': <b>'.
1.101     albertel 2861:                       &Apache::lonnet::revokecustomrole($env{'form.ccdomain'},
1.239     raeburn  2862: 				  $env{'form.ccuname'},$1,$2,$3,$4,'','',$context).
1.102     albertel 2863: 		'</b><br />');
1.225     raeburn  2864:                 if (!grep(/^cr$/,@rolechanges)) {
                   2865:                     push(@rolechanges,'cr');
                   2866:                 }
1.64      www      2867: 	    }
1.135     raeburn  2868: 	} elsif ($key=~/^form\.del/) {
                   2869: 	    if ($key=~/^form\.del\:([^\_]+)\_([^\_\.]+)$/) {
1.116     raeburn  2870: # Delete standard role
1.170     albertel 2871: 		my ($scope,$role) = ($1,$2);
                   2872: 		my $result =
                   2873: 		    &Apache::lonnet::assignrole($env{'form.ccdomain'},
                   2874: 						$env{'form.ccuname'},
1.239     raeburn  2875: 						$scope,$role,$now,0,1,'',
                   2876:                                                 $context);
1.170     albertel 2877: 	        $r->print(&mt('Deleting [_1] in [_2]: [_3]',$role,$scope,
                   2878: 			      '<b>'.$result.'</b>').'<br />');
                   2879: 		if ($role eq 'st') {
1.202     raeburn  2880: 		    my $result = 
1.198     raeburn  2881:                         &Apache::lonuserutils::classlist_drop($scope,
                   2882:                             $env{'form.ccuname'},$env{'form.ccdomain'},
1.202     raeburn  2883: 			    $now);
1.170     albertel 2884: 		    $r->print($result);
1.81      albertel 2885: 		}
1.225     raeburn  2886:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
                   2887:                     push(@rolechanges,$role);
                   2888:                 }
1.116     raeburn  2889:             }
1.139     albertel 2890: 	    if ($key=~m{^form\.del\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
1.116     raeburn  2891:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
                   2892: # Delete custom role
1.294     bisitz   2893:                 $r->print(&mt('Deleting custom role [_1] by [_2] in [_3]',
                   2894:                       $rolename,$rnam.':'.$rdom,$url).': <b>'.
1.116     raeburn  2895:                       &Apache::lonnet::assigncustomrole($env{'form.ccdomain'},
                   2896:                          $env{'form.ccuname'},$url,$rdom,$rnam,$rolename,$now,
1.240     raeburn  2897:                          0,1,$context).'</b><br />');
1.225     raeburn  2898:                 if (!grep(/^cr$/,@rolechanges)) {
                   2899:                     push(@rolechanges,'cr');
                   2900:                 }
1.116     raeburn  2901:             }
1.135     raeburn  2902: 	} elsif ($key=~/^form\.ren/) {
1.101     albertel 2903:             my $udom = $env{'form.ccdomain'};
                   2904:             my $uname = $env{'form.ccuname'};
1.116     raeburn  2905: # Re-enable standard role
1.135     raeburn  2906: 	    if ($key=~/^form\.ren\:([^\_]+)\_([^\_\.]+)$/) {
1.89      raeburn  2907:                 my $url = $1;
                   2908:                 my $role = $2;
                   2909:                 my $logmsg;
                   2910:                 my $output;
                   2911:                 if ($role eq 'st') {
1.141     albertel 2912:                     if ($url =~ m-^/($match_domain)/($match_courseid)/?(\w*)$-) {
1.129     albertel 2913:                         my $result = &Apache::loncommon::commit_studentrole(\$logmsg,$udom,$uname,$url,$role,$now,0,$1,$2,$3);
1.220     raeburn  2914:                         if (($result =~ /^error/) || ($result eq 'not_in_class') || ($result eq 'unknown_course') || ($result eq 'refused')) {
1.223     raeburn  2915:                             if ($result eq 'refused' && $logmsg) {
                   2916:                                 $output = $logmsg;
                   2917:                             } else { 
                   2918:                                 $output = "Error: $result\n";
                   2919:                             }
1.89      raeburn  2920:                         } else {
                   2921:                             $output = &mt('Assigning').' '.$role.' in '.$url.
                   2922:                                       &mt('starting').' '.localtime($now).
                   2923:                                       ': <br />'.$logmsg.'<br />'.
                   2924:                                       &mt('Add to classlist').': <b>ok</b><br />';
                   2925:                         }
                   2926:                     }
                   2927:                 } else {
1.101     albertel 2928: 		    my $result=&Apache::lonnet::assignrole($env{'form.ccdomain'},
1.239     raeburn  2929:                                $env{'form.ccuname'},$url,$role,0,$now,'','',
                   2930:                                $context);
1.266     bisitz   2931: 		    $output = &mt('Re-enabling [_1] in [_2]: [_3]',
                   2932: 			      $role,$url,'<b>'.$result.'</b>').'<br />';
1.27      matthew  2933: 		}
1.89      raeburn  2934:                 $r->print($output);
1.225     raeburn  2935:                 if (!grep(/^\Q$role\E$/,@rolechanges)) {
                   2936:                     push(@rolechanges,$role);
                   2937:                 }
1.113     raeburn  2938: 	    }
1.116     raeburn  2939: # Re-enable custom role
1.139     albertel 2940: 	    if ($key=~m{^form\.ren\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
1.116     raeburn  2941:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
                   2942:                 my $result = &Apache::lonnet::assigncustomrole(
                   2943:                                $env{'form.ccdomain'}, $env{'form.ccuname'},
1.240     raeburn  2944:                                $url,$rdom,$rnam,$rolename,0,$now,undef,$context);
1.294     bisitz   2945:                 $r->print(&mt('Re-enabling custom role [_1] by [_2] in [_3]: [_4]',
                   2946:                           $rolename,$rnam.':'.$rdom,$url,'<b>'.$result.'</b>').'<br />');
1.225     raeburn  2947:                 if (!grep(/^cr$/,@rolechanges)) {
                   2948:                     push(@rolechanges,'cr');
                   2949:                 }
1.116     raeburn  2950:             }
1.135     raeburn  2951: 	} elsif ($key=~/^form\.act/) {
1.101     albertel 2952:             my $udom = $env{'form.ccdomain'};
                   2953:             my $uname = $env{'form.ccuname'};
1.141     albertel 2954: 	    if ($key=~/^form\.act\_($match_domain)\_($match_courseid)\_cr_cr_($match_domain)_($match_username)_([^\_]+)$/) {
1.65      www      2955:                 # Activate a custom role
1.83      albertel 2956: 		my ($one,$two,$three,$four,$five)=($1,$2,$3,$4,$5);
                   2957: 		my $url='/'.$one.'/'.$two;
                   2958: 		my $full=$one.'_'.$two.'_cr_cr_'.$three.'_'.$four.'_'.$five;
1.65      www      2959: 
1.101     albertel 2960:                 my $start = ( $env{'form.start_'.$full} ?
                   2961:                               $env{'form.start_'.$full} :
1.88      raeburn  2962:                               $now );
1.101     albertel 2963:                 my $end   = ( $env{'form.end_'.$full} ?
                   2964:                               $env{'form.end_'.$full} :
1.88      raeburn  2965:                               0 );
                   2966:                                                                                      
                   2967:                 # split multiple sections
                   2968:                 my %sections = ();
1.101     albertel 2969:                 my $num_sections = &build_roles($env{'form.sec_'.$full},\%sections,$5);
1.88      raeburn  2970:                 if ($num_sections == 0) {
1.240     raeburn  2971:                     $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$url,$three,$four,$five,$start,$end,$context));
1.88      raeburn  2972:                 } else {
1.114     albertel 2973: 		    my %curr_groups =
1.117     raeburn  2974: 			&Apache::longroup::coursegroups($one,$two);
1.113     raeburn  2975:                     foreach my $sec (sort {$a cmp $b} keys %sections) {
                   2976:                         if (($sec eq 'none') || ($sec eq 'all') || 
                   2977:                             exists($curr_groups{$sec})) {
                   2978:                             $disallowed{$sec} = $url;
                   2979:                             next;
                   2980:                         }
                   2981:                         my $securl = $url.'/'.$sec;
1.240     raeburn  2982: 		        $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$securl,$three,$four,$five,$start,$end,$context));
1.88      raeburn  2983:                     }
                   2984:                 }
1.225     raeburn  2985:                 if (!grep(/^cr$/,@rolechanges)) {
                   2986:                     push(@rolechanges,'cr');
                   2987:                 }
1.142     raeburn  2988: 	    } elsif ($key=~/^form\.act\_($match_domain)\_($match_name)\_([^\_]+)$/) {
1.27      matthew  2989: 		# Activate roles for sections with 3 id numbers
                   2990: 		# set start, end times, and the url for the class
1.83      albertel 2991: 		my ($one,$two,$three)=($1,$2,$3);
1.101     albertel 2992: 		my $start = ( $env{'form.start_'.$one.'_'.$two.'_'.$three} ? 
                   2993: 			      $env{'form.start_'.$one.'_'.$two.'_'.$three} : 
1.27      matthew  2994: 			      $now );
1.101     albertel 2995: 		my $end   = ( $env{'form.end_'.$one.'_'.$two.'_'.$three} ? 
                   2996: 			      $env{'form.end_'.$one.'_'.$two.'_'.$three} :
1.27      matthew  2997: 			      0 );
1.83      albertel 2998: 		my $url='/'.$one.'/'.$two;
1.88      raeburn  2999:                 my $type = 'three';
                   3000:                 # split multiple sections
                   3001:                 my %sections = ();
1.101     albertel 3002:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two.'_'.$three},\%sections,$three);
1.88      raeburn  3003:                 if ($num_sections == 0) {
1.240     raeburn  3004:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context));
1.88      raeburn  3005:                 } else {
1.114     albertel 3006:                     my %curr_groups = 
1.117     raeburn  3007: 			&Apache::longroup::coursegroups($one,$two);
1.88      raeburn  3008:                     my $emptysec = 0;
                   3009:                     foreach my $sec (sort {$a cmp $b} keys %sections) {
                   3010:                         $sec =~ s/\W//g;
1.113     raeburn  3011:                         if ($sec ne '') {
                   3012:                             if (($sec eq 'none') || ($sec eq 'all') || 
                   3013:                                 exists($curr_groups{$sec})) {
                   3014:                                 $disallowed{$sec} = $url;
                   3015:                                 next;
                   3016:                             }
1.88      raeburn  3017:                             my $securl = $url.'/'.$sec;
1.240     raeburn  3018:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$three,$start,$end,$one,$two,$sec,$context));
1.88      raeburn  3019:                         } else {
                   3020:                             $emptysec = 1;
                   3021:                         }
                   3022:                     }
                   3023:                     if ($emptysec) {
1.240     raeburn  3024:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,'',$context));
1.88      raeburn  3025:                     }
1.225     raeburn  3026:                 }
                   3027:                 if (!grep(/^\Q$three\E$/,@rolechanges)) {
                   3028:                     push(@rolechanges,$three);
                   3029:                 }
1.135     raeburn  3030: 	    } elsif ($key=~/^form\.act\_([^\_]+)\_([^\_]+)$/) {
1.27      matthew  3031: 		# Activate roles for sections with two id numbers
                   3032: 		# set start, end times, and the url for the class
1.101     albertel 3033: 		my $start = ( $env{'form.start_'.$1.'_'.$2} ? 
                   3034: 			      $env{'form.start_'.$1.'_'.$2} : 
1.27      matthew  3035: 			      $now );
1.101     albertel 3036: 		my $end   = ( $env{'form.end_'.$1.'_'.$2} ? 
                   3037: 			      $env{'form.end_'.$1.'_'.$2} :
1.27      matthew  3038: 			      0 );
1.225     raeburn  3039:                 my $one = $1;
                   3040:                 my $two = $2;
                   3041: 		my $url='/'.$one.'/';
1.88      raeburn  3042:                 # split multiple sections
                   3043:                 my %sections = ();
1.225     raeburn  3044:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two},\%sections,$two);
1.88      raeburn  3045:                 if ($num_sections == 0) {
1.240     raeburn  3046:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
1.88      raeburn  3047:                 } else {
                   3048:                     my $emptysec = 0;
                   3049:                     foreach my $sec (sort {$a cmp $b} keys %sections) {
                   3050:                         if ($sec ne '') {
                   3051:                             my $securl = $url.'/'.$sec;
1.240     raeburn  3052:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$two,$start,$end,$one,undef,$sec,$context));
1.88      raeburn  3053:                         } else {
                   3054:                             $emptysec = 1;
                   3055:                         }
                   3056:                     }
                   3057:                     if ($emptysec) {
1.240     raeburn  3058:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$two,$start,$end,$one,undef,'',$context));
1.88      raeburn  3059:                     }
                   3060:                 }
1.225     raeburn  3061:                 if (!grep(/^\Q$two\E$/,@rolechanges)) {
                   3062:                     push(@rolechanges,$two);
                   3063:                 }
1.64      www      3064: 	    } else {
1.190     raeburn  3065: 		$r->print('<p><span class="LC_error">'.&mt('ERROR').': '.&mt('Unknown command').' <tt>'.$key.'</tt></span></p><br />');
1.64      www      3066:             }
1.113     raeburn  3067:             foreach my $key (sort(keys(%disallowed))) {
1.274     bisitz   3068:                 $r->print('<p class="LC_warning">');
1.113     raeburn  3069:                 if (($key eq 'none') || ($key eq 'all')) {  
1.274     bisitz   3070:                     $r->print(&mt('[_1] may not be used as the name for a section, as it is a reserved word.','<tt>'.$key.'</tt>'));
1.113     raeburn  3071:                 } else {
1.274     bisitz   3072:                     $r->print(&mt('[_1] may not be used as the name for a section, as it is the name of a course group.','<tt>'.$key.'</tt>'));
1.113     raeburn  3073:                 }
1.274     bisitz   3074:                 $r->print('</p><p>'
                   3075:                          .&mt('Please [_1]go back[_2] and choose a different section name.'
                   3076:                              ,'<a href="javascript:history.go(-1)'
                   3077:                              ,'</a>')
                   3078:                          .'</p><br />'
                   3079:                 );
1.113     raeburn  3080:             }
                   3081: 	}
1.101     albertel 3082:     } # End of foreach (keys(%env))
1.75      www      3083: # Flush the course logs so reverse user roles immediately updated
                   3084:     &Apache::lonnet::flushcourselogs();
1.225     raeburn  3085:     if (@rolechanges == 0) {
1.193     raeburn  3086:         $r->print(&mt('No roles to modify'));
                   3087:     }
1.225     raeburn  3088:     return @rolechanges;
1.220     raeburn  3089: }
                   3090: 
                   3091: sub enroll_single_student {
1.239     raeburn  3092:     my ($r,$uhome,$amode,$genpwd,$now,$newuser,$context) = @_;
1.220     raeburn  3093:     $r->print('<h3>'.&mt('Enrolling Student').'</h3>');
                   3094: 
                   3095:     # Remove non alphanumeric values from section
                   3096:     $env{'form.sections'}=~s/\W//g;
                   3097: 
                   3098:     # Clean out any old student roles the user has in this class.
                   3099:     &Apache::lonuserutils::modifystudent($env{'form.ccdomain'},
                   3100:          $env{'form.ccuname'},$env{'request.course.id'},undef,$uhome);
                   3101:     my ($startdate,$enddate) = &Apache::lonuserutils::get_dates_from_form();
                   3102:     my $enroll_result =
                   3103:         &Apache::lonnet::modify_student_enrollment($env{'form.ccdomain'},
                   3104:             $env{'form.ccuname'},$env{'form.cid'},$env{'form.cfirstname'},
                   3105:             $env{'form.cmiddlename'},$env{'form.clastname'},
                   3106:             $env{'form.generation'},$env{'form.sections'},$enddate,
1.239     raeburn  3107:             $startdate,'manual',undef,$env{'request.course.id'},'',$context);
1.220     raeburn  3108:     if ($enroll_result =~ /^ok/) {
                   3109:         $r->print(&mt('<b>[_1]</b> enrolled',$env{'form.ccuname'}.':'.$env{'form.ccdomain'}));
                   3110:         if ($env{'form.sections'} ne '') {
                   3111:             $r->print(' '.&mt('in section [_1]',$env{'form.sections'}));
                   3112:         }
                   3113:         my ($showstart,$showend);
                   3114:         if ($startdate <= $now) {
                   3115:             $showstart = &mt('Access starts immediately');
                   3116:         } else {
                   3117:             $showstart = &mt('Access starts: ').&Apache::lonlocal::locallocaltime($startdate);
                   3118:         }
                   3119:         if ($enddate == 0) {
                   3120:             $showend = &mt('ends: no ending date');
                   3121:         } else {
                   3122:             $showend = &mt('ends: ').&Apache::lonlocal::locallocaltime($enddate);
                   3123:         }
                   3124:         $r->print('.<br />'.$showstart.'; '.$showend);
                   3125:         if ($startdate <= $now && !$newuser) {
                   3126:             $r->print("<p> ".&mt('If the student is currently logged-in to LON-CAPA, the new role will be available when the student next logs in.')."</p>");
                   3127:         }
                   3128:     } else {
                   3129:         $r->print(&mt('unable to enroll').": ".$enroll_result);
                   3130:     }
                   3131:     return;
1.188     raeburn  3132: }
                   3133: 
1.204     raeburn  3134: sub get_defaultquota_text {
                   3135:     my ($settingstatus) = @_;
                   3136:     my $defquotatext; 
                   3137:     if ($settingstatus eq '') {
                   3138:         $defquotatext = &mt('(default)');
                   3139:     } else {
                   3140:         my ($usertypes,$order) =
                   3141:             &Apache::lonnet::retrieve_inst_usertypes($env{'form.ccdomain'});
                   3142:         if ($usertypes->{$settingstatus} eq '') {
                   3143:             $defquotatext = &mt('(default)');
                   3144:         } else {
                   3145:             $defquotatext = &mt('(default for [_1])',$usertypes->{$settingstatus});
                   3146:         }
                   3147:     }
                   3148:     return $defquotatext;
                   3149: }
                   3150: 
1.188     raeburn  3151: sub update_result_form {
                   3152:     my ($uhome) = @_;
                   3153:     my $outcome = 
                   3154:     '<form name="userupdate" method="post" />'."\n";
1.160     raeburn  3155:     foreach my $item ('srchby','srchin','srchtype','srchterm','srchdomain','ccuname','ccdomain') {
1.188     raeburn  3156:         $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
1.160     raeburn  3157:     }
1.207     raeburn  3158:     if ($env{'form.origname'} ne '') {
                   3159:         $outcome .= '<input type="hidden" name="origname" value="'.$env{'form.origname'}.'" />'."\n";
                   3160:     }
1.160     raeburn  3161:     foreach my $item ('sortby','seluname','seludom') {
                   3162:         if (exists($env{'form.'.$item})) {
1.188     raeburn  3163:             $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
1.160     raeburn  3164:         }
                   3165:     }
1.188     raeburn  3166:     if ($uhome eq 'no_host') {
                   3167:         $outcome .= '<input type="hidden" name="forcenewuser" value="1" />'."\n";
                   3168:     }
                   3169:     $outcome .= '<input type="hidden" name="phase" value="" />'."\n".
                   3170:                 '<input type ="hidden" name="currstate" value="" />'."\n".
1.220     raeburn  3171:                 '<input type ="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n".
1.188     raeburn  3172:                 '</form>';
                   3173:     return $outcome;
1.4       www      3174: }
                   3175: 
1.149     raeburn  3176: sub quota_admin {
                   3177:     my ($setquota,$changeHash) = @_;
                   3178:     my $quotachanged;
                   3179:     if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
                   3180:         # Current user has quota modification privileges
1.267     raeburn  3181:         if (ref($changeHash) eq 'HASH') {
                   3182:             $quotachanged = 1;
                   3183:             $changeHash->{'portfolioquota'} = $setquota;
                   3184:         }
1.149     raeburn  3185:     }
                   3186:     return $quotachanged;
                   3187: }
                   3188: 
1.267     raeburn  3189: sub tool_admin {
1.275     raeburn  3190:     my ($tool,$settool,$changeHash,$context) = @_;
                   3191:     my $canchange = 0; 
1.279     raeburn  3192:     if ($context eq 'requestcourses') {
1.275     raeburn  3193:         if (&Apache::lonnet::allowed('ccc',$env{'form.ccdomain'})) {
                   3194:             $canchange = 1;
                   3195:         }
1.295.2.3! raeburn  3196:     } elsif ($context eq 'reqcrsotherdom') {
        !          3197:         if (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'})) {
        !          3198:             $canchange = 1;
        !          3199:         }
1.275     raeburn  3200:     } elsif (&Apache::lonnet::allowed('mut',$env{'form.ccdomain'})) {
                   3201:         # Current user has quota modification privileges
                   3202:         $canchange = 1;
                   3203:     }
1.267     raeburn  3204:     my $toolchanged;
1.275     raeburn  3205:     if ($canchange) {
1.267     raeburn  3206:         if (ref($changeHash) eq 'HASH') {
                   3207:             $toolchanged = 1;
1.275     raeburn  3208:             $changeHash->{$context.'.'.$tool} = $settool;
1.267     raeburn  3209:         }
                   3210:     }
                   3211:     return $toolchanged;
                   3212: }
                   3213: 
1.88      raeburn  3214: sub build_roles {
1.89      raeburn  3215:     my ($sectionstr,$sections,$role) = @_;
1.88      raeburn  3216:     my $num_sections = 0;
                   3217:     if ($sectionstr=~ /,/) {
                   3218:         my @secnums = split/,/,$sectionstr;
1.89      raeburn  3219:         if ($role eq 'st') {
                   3220:             $secnums[0] =~ s/\W//g;
                   3221:             $$sections{$secnums[0]} = 1;
                   3222:             $num_sections = 1;
                   3223:         } else {
                   3224:             foreach my $sec (@secnums) {
                   3225:                 $sec =~ ~s/\W//g;
1.150     banghart 3226:                 if (!($sec eq "")) {
1.89      raeburn  3227:                     if (exists($$sections{$sec})) {
                   3228:                         $$sections{$sec} ++;
                   3229:                     } else {
                   3230:                         $$sections{$sec} = 1;
                   3231:                         $num_sections ++;
                   3232:                     }
1.88      raeburn  3233:                 }
                   3234:             }
                   3235:         }
                   3236:     } else {
                   3237:         $sectionstr=~s/\W//g;
                   3238:         unless ($sectionstr eq '') {
                   3239:             $$sections{$sectionstr} = 1;
                   3240:             $num_sections ++;
                   3241:         }
                   3242:     }
1.129     albertel 3243: 
1.88      raeburn  3244:     return $num_sections;
                   3245: }
                   3246: 
1.58      www      3247: # ========================================================== Custom Role Editor
                   3248: 
                   3249: sub custom_role_editor {
1.160     raeburn  3250:     my ($r) = @_;
1.101     albertel 3251:     my $rolename=$env{'form.rolename'};
1.58      www      3252: 
1.59      www      3253:     if ($rolename eq 'make new role') {
1.101     albertel 3254: 	$rolename=$env{'form.newrolename'};
1.59      www      3255:     }
                   3256: 
1.63      www      3257:     $rolename=~s/[^A-Za-z0-9]//gs;
1.58      www      3258: 
1.190     raeburn  3259:     if (!$rolename || $env{'form.phase'} eq 'pickrole') {
1.58      www      3260: 	&print_username_entry_form($r);
                   3261:         return;
                   3262:     }
1.153     banghart 3263: # ------------------------------------------------------- What can be assigned?
                   3264:     my %full=();
                   3265:     my %courselevel=();
                   3266:     my %courselevelcurrent=();
1.61      www      3267:     my $syspriv='';
                   3268:     my $dompriv='';
                   3269:     my $coursepriv='';
1.153     banghart 3270:     my $body_top;
1.150     banghart 3271:     my ($disp_dummy,$disp_roles) = &Apache::lonnet::get('roles',["st"]);
1.59      www      3272:     my ($rdummy,$roledef)=
                   3273: 			 &Apache::lonnet::get('roles',["rolesdef_$rolename"]);
1.60      www      3274: # ------------------------------------------------------- Does this role exist?
1.153     banghart 3275:     $body_top .= '<h2>';
1.59      www      3276:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
1.153     banghart 3277: 	$body_top .= &mt('Existing Role').' "';
1.61      www      3278: # ------------------------------------------------- Get current role privileges
                   3279: 	($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
1.59      www      3280:     } else {
1.153     banghart 3281: 	$body_top .= &mt('New Role').' "';
1.59      www      3282: 	$roledef='';
                   3283:     }
1.153     banghart 3284:     $body_top .= $rolename.'"</h2>';
1.135     raeburn  3285:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   3286: 	my ($priv,$restrict)=split(/\&/,$item);
1.150     banghart 3287:         if (!$restrict) { $restrict='F'; }
1.60      www      3288:         $courselevel{$priv}=$restrict;
1.61      www      3289:         if ($coursepriv=~/\:$priv/) {
                   3290: 	    $courselevelcurrent{$priv}=1;
                   3291: 	}
1.60      www      3292: 	$full{$priv}=1;
                   3293:     }
                   3294:     my %domainlevel=();
1.61      www      3295:     my %domainlevelcurrent=();
1.135     raeburn  3296:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:d'})) {
                   3297: 	my ($priv,$restrict)=split(/\&/,$item);
1.150     banghart 3298:         if (!$restrict) { $restrict='F'; }
1.60      www      3299:         $domainlevel{$priv}=$restrict;
1.61      www      3300:         if ($dompriv=~/\:$priv/) {
                   3301: 	    $domainlevelcurrent{$priv}=1;
                   3302: 	}
1.60      www      3303: 	$full{$priv}=1;
                   3304:     }
1.61      www      3305:     my %systemlevel=();
                   3306:     my %systemlevelcurrent=();
1.135     raeburn  3307:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:s'})) {
                   3308: 	my ($priv,$restrict)=split(/\&/,$item);
1.150     banghart 3309:         if (!$restrict) { $restrict='F'; }
1.61      www      3310:         $systemlevel{$priv}=$restrict;
                   3311:         if ($syspriv=~/\:$priv/) {
                   3312: 	    $systemlevelcurrent{$priv}=1;
                   3313: 	}
                   3314: 	$full{$priv}=1;
                   3315:     }
1.160     raeburn  3316:     my ($jsback,$elements) = &crumb_utilities();
1.154     banghart 3317:     my $button_code = "\n";
1.153     banghart 3318:     my $head_script = "\n";
                   3319:     $head_script .= '<script type="text/javascript">'."\n";
1.154     banghart 3320:     my @template_roles = ("cc","in","ta","ep","st");
                   3321:     foreach my $role (@template_roles) {
                   3322:         $head_script .= &make_script_template($role);
1.264     bisitz   3323:         $button_code .= &make_button_code($role).' ';
1.154     banghart 3324:     }
1.160     raeburn  3325:     $head_script .= "\n".$jsback."\n".'</script>'."\n";
1.153     banghart 3326:     $r->print(&Apache::loncommon::start_page('Custom Role Editor',$head_script));
1.160     raeburn  3327:    &Apache::lonhtmlcommon::add_breadcrumb
1.190     raeburn  3328:      ({href=>"javascript:backPage(document.form1,'pickrole','')",
                   3329:        text=>"Pick custom role",
1.160     raeburn  3330:        faq=>282,bug=>'Instructor Interface',},
                   3331:       {href=>"javascript:backPage(document.form1,'','')",
                   3332:          text=>"Edit custom role",
                   3333:          faq=>282,bug=>'Instructor Interface',});
1.224     raeburn  3334:     $r->print(&Apache::lonhtmlcommon::breadcrumbs('User Management',
                   3335:                                                   'Course_Editing_Custom_Roles'));
1.160     raeburn  3336: 
1.153     banghart 3337:     $r->print($body_top);
1.73      sakharuk 3338:     my %lt=&Apache::lonlocal::texthash(
                   3339: 		    'prv'  => "Privilege",
1.131     raeburn  3340: 		    'crl'  => "Course Level",
1.73      sakharuk 3341:                     'dml'  => "Domain Level",
1.150     banghart 3342:                     'ssl'  => "System Level");
1.264     bisitz   3343: 
                   3344:     $r->print('<div>'
                   3345:              .'<form action=""><fieldset>'
                   3346:              .'<legend>'.&mt('Select a Template').'</legend>'
                   3347:              .$button_code
                   3348:              .'</fieldset></form>'
                   3349:              .'</div>'
                   3350:     );
                   3351: 
1.61      www      3352:     $r->print(<<ENDCCF);
1.160     raeburn  3353: <form name="form1" method="post">
1.61      www      3354: <input type="hidden" name="phase" value="set_custom_roles" />
                   3355: <input type="hidden" name="rolename" value="$rolename" />
                   3356: ENDCCF
1.135     raeburn  3357:     $r->print(&Apache::loncommon::start_data_table().
                   3358:               &Apache::loncommon::start_data_table_header_row(). 
                   3359: '<th>'.$lt{'prv'}.'</th><th>'.$lt{'crl'}.'</th><th>'.$lt{'dml'}.
                   3360: '</th><th>'.$lt{'ssl'}.'</th>'.
                   3361:               &Apache::loncommon::end_data_table_header_row());
1.119     raeburn  3362:     foreach my $priv (sort keys %full) {
                   3363:         my $privtext = &Apache::lonnet::plaintext($priv);
1.135     raeburn  3364:         $r->print(&Apache::loncommon::start_data_table_row().
                   3365: 	          '<td>'.$privtext.'</td><td>'.
1.288     bisitz   3366:     ($courselevel{$priv}?'<input type="checkbox" name="'.$priv.'_c"'.
                   3367:     ($courselevelcurrent{$priv}?' checked="checked"':'').' />':'&nbsp;').
1.61      www      3368:     '</td><td>'.
1.288     bisitz   3369:     ($domainlevel{$priv}?'<input type="checkbox" name="'.$priv.'_d"'.
                   3370:     ($domainlevelcurrent{$priv}?' checked="checked"':'').' />':'&nbsp;').
1.61      www      3371:     '</td><td>'.
1.288     bisitz   3372:     ($systemlevel{$priv}?'<input type="checkbox" name="'.$priv.'_s"'.
                   3373:     ($systemlevelcurrent{$priv}?' checked="checked"':'').' />':'&nbsp;').
1.135     raeburn  3374:     '</td>'.
                   3375:              &Apache::loncommon::end_data_table_row());
1.60      www      3376:     }
1.135     raeburn  3377:     $r->print(&Apache::loncommon::end_data_table().
1.190     raeburn  3378:    '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
1.160     raeburn  3379:    '<input type="hidden" name="startrolename" value="'.$env{'form.rolename'}.
1.179     raeburn  3380:    '" />'."\n".'<input type="hidden" name="currstate" value="" />'."\n".   
1.160     raeburn  3381:    '<input type="reset" value="'.&mt("Reset").'" />'."\n".
1.282     schafran 3382:    '<input type="submit" value="'.&mt('Save').'" /></form>'.
1.110     albertel 3383: 	      &Apache::loncommon::end_page());
1.61      www      3384: }
1.153     banghart 3385: # --------------------------------------------------------
                   3386: sub make_script_template {
                   3387:     my ($role) = @_;
                   3388:     my %full_c=();
                   3389:     my %full_d=();
                   3390:     my %full_s=();
                   3391:     my $return_script;
                   3392:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   3393:         my ($priv,$restrict)=split(/\&/,$item);
                   3394:         $full_c{$priv}=1;
                   3395:     }
                   3396:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:d'})) {
                   3397:         my ($priv,$restrict)=split(/\&/,$item);
                   3398:         $full_d{$priv}=1;
                   3399:     }
1.154     banghart 3400:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:s'})) {
1.153     banghart 3401:         my ($priv,$restrict)=split(/\&/,$item);
                   3402:         $full_s{$priv}=1;
                   3403:     }
                   3404:     $return_script .= 'function set_'.$role.'() {'."\n";
                   3405:     my @temp = split(/:/,$Apache::lonnet::pr{$role.':c'});
                   3406:     my %role_c;
1.155     banghart 3407:     foreach my $priv (@temp) {
1.153     banghart 3408:         my ($priv_item, $dummy) = split(/\&/,$priv);
                   3409:         $role_c{$priv_item} = 1;
                   3410:     }
1.269     raeburn  3411:     my %role_d;
                   3412:     @temp = split(/:/,$Apache::lonnet::pr{$role.':d'});
                   3413:     foreach my $priv(@temp) {
                   3414:         my ($priv_item, $dummy) = split(/\&/,$priv);
                   3415:         $role_d{$priv_item} = 1;
                   3416:     }
                   3417:     my %role_s;
                   3418:     @temp = split(/:/,$Apache::lonnet::pr{$role.':s'});
                   3419:     foreach my $priv(@temp) {
                   3420:         my ($priv_item, $dummy) = split(/\&/,$priv);
                   3421:         $role_s{$priv_item} = 1;
                   3422:     }
1.153     banghart 3423:     foreach my $priv_item (keys(%full_c)) {
                   3424:         my ($priv, $dummy) = split(/\&/,$priv_item);
1.269     raeburn  3425:         if ((exists($role_c{$priv})) || (exists($role_d{$priv})) || 
                   3426:             (exists($role_s{$priv}))) {
1.153     banghart 3427:             $return_script .= "document.form1.$priv"."_c.checked = true;\n";
                   3428:         } else {
                   3429:             $return_script .= "document.form1.$priv"."_c.checked = false;\n";
                   3430:         }
                   3431:     }
1.154     banghart 3432:     foreach my $priv_item (keys(%full_d)) {
                   3433:         my ($priv, $dummy) = split(/\&/,$priv_item);
1.269     raeburn  3434:         if ((exists($role_d{$priv})) || (exists($role_s{$priv}))) {
1.154     banghart 3435:             $return_script .= "document.form1.$priv"."_d.checked = true;\n";
                   3436:         } else {
                   3437:             $return_script .= "document.form1.$priv"."_d.checked = false;\n";
                   3438:         }
                   3439:     }
                   3440:     foreach my $priv_item (keys(%full_s)) {
1.153     banghart 3441:         my ($priv, $dummy) = split(/\&/,$priv_item);
1.154     banghart 3442:         if (exists($role_s{$priv})) {
                   3443:             $return_script .= "document.form1.$priv"."_s.checked = true;\n";
                   3444:         } else {
                   3445:             $return_script .= "document.form1.$priv"."_s.checked = false;\n";
                   3446:         }
1.153     banghart 3447:     }
                   3448:     $return_script .= '}'."\n";
1.154     banghart 3449:     return ($return_script);
                   3450: }
                   3451: # ----------------------------------------------------------
                   3452: sub make_button_code {
                   3453:     my ($role) = @_;
                   3454:     my $label = &Apache::lonnet::plaintext($role);
1.264     bisitz   3455:     my $button_code = '<input type="button" onClick="set_'.$role.'()" value="'.$label.'" />';
1.154     banghart 3456:     return ($button_code);
1.153     banghart 3457: }
1.61      www      3458: # ---------------------------------------------------------- Call to definerole
                   3459: sub set_custom_role {
1.240     raeburn  3460:     my ($r,$context) = @_;
1.101     albertel 3461:     my $rolename=$env{'form.rolename'};
1.63      www      3462:     $rolename=~s/[^A-Za-z0-9]//gs;
1.150     banghart 3463:     if (!$rolename) {
1.190     raeburn  3464: 	&custom_role_editor($r);
1.61      www      3465:         return;
                   3466:     }
1.160     raeburn  3467:     my ($jsback,$elements) = &crumb_utilities();
                   3468:     my $jscript = '<script type="text/javascript">'.$jsback."\n".'</script>';
                   3469: 
                   3470:     $r->print(&Apache::loncommon::start_page('Save Custom Role'),$jscript);
                   3471:     &Apache::lonhtmlcommon::add_breadcrumb
1.190     raeburn  3472:         ({href=>"javascript:backPage(document.customresult,'pickrole','')",
                   3473:           text=>"Pick custom role",
1.160     raeburn  3474:           faq=>282,bug=>'Instructor Interface',},
                   3475:          {href=>"javascript:backPage(document.customresult,'selected_custom_edit','')",
                   3476:           text=>"Edit custom role",
                   3477:           faq=>282,bug=>'Instructor Interface',},
                   3478:          {href=>"javascript:backPage(document.customresult,'set_custom_roles','')",
                   3479:           text=>"Result",
                   3480:           faq=>282,bug=>'Instructor Interface',});
1.224     raeburn  3481:     $r->print(&Apache::lonhtmlcommon::breadcrumbs('User Management',
                   3482:                                                   'Course_Editing_Custom_Roles'));
1.160     raeburn  3483: 
1.61      www      3484:     my ($rdummy,$roledef)=
1.110     albertel 3485: 	&Apache::lonnet::get('roles',["rolesdef_$rolename"]);
                   3486: 
1.61      www      3487: # ------------------------------------------------------- Does this role exist?
1.188     raeburn  3488:     $r->print('<h3>');
1.61      www      3489:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
1.73      sakharuk 3490: 	$r->print(&mt('Existing Role').' "');
1.61      www      3491:     } else {
1.73      sakharuk 3492: 	$r->print(&mt('New Role').' "');
1.61      www      3493: 	$roledef='';
                   3494:     }
1.188     raeburn  3495:     $r->print($rolename.'"</h3>');
1.61      www      3496: # ------------------------------------------------------- What can be assigned?
                   3497:     my $sysrole='';
                   3498:     my $domrole='';
                   3499:     my $courole='';
                   3500: 
1.135     raeburn  3501:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   3502: 	my ($priv,$restrict)=split(/\&/,$item);
1.150     banghart 3503:         if (!$restrict) { $restrict=''; }
                   3504:         if ($env{'form.'.$priv.'_c'}) {
1.135     raeburn  3505: 	    $courole.=':'.$item;
1.61      www      3506: 	}
                   3507:     }
                   3508: 
1.135     raeburn  3509:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:d'})) {
                   3510: 	my ($priv,$restrict)=split(/\&/,$item);
1.150     banghart 3511:         if (!$restrict) { $restrict=''; }
                   3512:         if ($env{'form.'.$priv.'_d'}) {
1.135     raeburn  3513: 	    $domrole.=':'.$item;
1.61      www      3514: 	}
                   3515:     }
                   3516: 
1.135     raeburn  3517:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:s'})) {
                   3518: 	my ($priv,$restrict)=split(/\&/,$item);
1.150     banghart 3519:         if (!$restrict) { $restrict=''; }
                   3520:         if ($env{'form.'.$priv.'_s'}) {
1.135     raeburn  3521: 	    $sysrole.=':'.$item;
1.61      www      3522: 	}
                   3523:     }
1.63      www      3524:     $r->print('<br />Defining Role: '.
1.61      www      3525: 	   &Apache::lonnet::definerole($rolename,$sysrole,$domrole,$courole));
1.101     albertel 3526:     if ($env{'request.course.id'}) {
                   3527:         my $url='/'.$env{'request.course.id'};
1.63      www      3528:         $url=~s/\_/\//g;
1.73      sakharuk 3529: 	$r->print('<br />'.&mt('Assigning Role to Self').': '.
1.101     albertel 3530: 	      &Apache::lonnet::assigncustomrole($env{'user.domain'},
                   3531: 						$env{'user.name'},
1.63      www      3532: 						$url,
1.101     albertel 3533: 						$env{'user.domain'},
                   3534: 						$env{'user.name'},
1.240     raeburn  3535: 						$rolename,undef,undef,undef,$context));
1.63      www      3536:     }
1.190     raeburn  3537:     $r->print('<p><a href="javascript:backPage(document.customresult,'."'pickrole'".')">'.&mt('Create or edit another custom role').'</a></p><form name="customresult" method="post">');
1.160     raeburn  3538:     $r->print(&Apache::lonhtmlcommon::echo_form_input([]).'</form>');
1.110     albertel 3539:     $r->print(&Apache::loncommon::end_page());
1.58      www      3540: }
                   3541: 
1.2       www      3542: # ================================================================ Main Handler
                   3543: sub handler {
                   3544:     my $r = shift;
                   3545:     if ($r->header_only) {
1.68      www      3546:        &Apache::loncommon::content_type($r,'text/html');
1.2       www      3547:        $r->send_http_header;
                   3548:        return OK;
                   3549:     }
1.190     raeburn  3550:     my $context;
                   3551:     if ($env{'request.course.id'}) {
                   3552:         $context = 'course';
                   3553:     } elsif ($env{'request.role'} =~ /^au\./) {
1.206     raeburn  3554:         $context = 'author';
1.190     raeburn  3555:     } else {
                   3556:         $context = 'domain';
                   3557:     }
                   3558:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
1.233     raeburn  3559:         ['action','state','callingform','roletype','showrole','bulkaction','popup','phase',
                   3560:          'username','domain','srchterm','srchdomain','srchin','srchby','srchtype']);
1.190     raeburn  3561:     &Apache::lonhtmlcommon::clear_breadcrumbs();
1.202     raeburn  3562:     if ($env{'form.action'} ne 'dateselect') {
                   3563:         &Apache::lonhtmlcommon::add_breadcrumb
                   3564:             ({href=>"/adm/createuser",
1.289     droeschl 3565:               text=>"User Management",
                   3566:               help=>'Course_Create_Class_List,Course_Change_Privileges,Course_View_Class_List,Course_Editing_Custom_Roles,Course_Add_Student,Course_Drop_Student,Course_Automated_Enrollment,Course_Self_Enrollment,Course_Manage_Group'});
1.202     raeburn  3567:     }
1.289     droeschl 3568:     #SD Following files not added to help, because the corresponding .tex-files seem to
                   3569:     #be missing: Course_Approve_Selfenroll,Course_User_Logs,
1.209     raeburn  3570:     my ($permission,$allowed) = 
                   3571:         &Apache::lonuserutils::get_permission($context);
1.190     raeburn  3572:     if (!$allowed) {
                   3573:         $env{'user.error.msg'}=
                   3574:             "/adm/createuser:cst:0:0:Cannot create/modify user data ".
                   3575:                                  "or view user status.";
                   3576:         return HTTP_NOT_ACCEPTABLE;
                   3577:     }
                   3578: 
                   3579:     &Apache::loncommon::content_type($r,'text/html');
                   3580:     $r->send_http_header;
                   3581: 
                   3582:     # Main switch on form.action and form.state, as appropriate
                   3583:     if (! exists($env{'form.action'})) {
                   3584:         $r->print(&header());
                   3585:         $r->print(&Apache::lonhtmlcommon::breadcrumbs('User Management'));
1.208     raeburn  3586:         $r->print(&print_main_menu($permission,$context));
1.190     raeburn  3587:         $r->print(&Apache::loncommon::end_page());
                   3588:     } elsif ($env{'form.action'} eq 'upload' && $permission->{'cusr'}) {
                   3589:         $r->print(&header());
                   3590:         &Apache::lonhtmlcommon::add_breadcrumb
                   3591:             ({href=>'/adm/createuser?action=upload&state=',
                   3592:               text=>"Upload Users List"});
                   3593:         $r->print(&Apache::lonhtmlcommon::breadcrumbs('Upload Users List',
1.224     raeburn  3594:                                                    'Course_Create_Class_List'));
1.190     raeburn  3595:         $r->print('<form name="studentform" method="post" '.
                   3596:                   'enctype="multipart/form-data" '.
                   3597:                   ' action="/adm/createuser">'."\n");
                   3598:         if (! exists($env{'form.state'})) {
                   3599:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
                   3600:         } elsif ($env{'form.state'} eq 'got_file') {
1.221     raeburn  3601:             &Apache::lonuserutils::print_upload_manager_form($r,$context,
                   3602:                                                              $permission);
1.190     raeburn  3603:         } elsif ($env{'form.state'} eq 'enrolling') {
                   3604:             if ($env{'form.datatoken'}) {
1.221     raeburn  3605:                 &Apache::lonuserutils::upfile_drop_add($r,$context,$permission);
1.190     raeburn  3606:             }
                   3607:         } else {
                   3608:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
                   3609:         }
                   3610:         $r->print('</form>'.&Apache::loncommon::end_page());
1.213     raeburn  3611:     } elsif ((($env{'form.action'} eq 'singleuser') || ($env{'form.action'}
                   3612:              eq 'singlestudent')) && ($permission->{'cusr'})) {
1.190     raeburn  3613:         my $phase = $env{'form.phase'};
                   3614:         my @search = ('srchterm','srchby','srchin','srchtype','srchdomain');
1.192     albertel 3615: 	&Apache::loncreateuser::restore_prev_selections();
                   3616: 	my $srch;
                   3617: 	foreach my $item (@search) {
                   3618: 	    $srch->{$item} = $env{'form.'.$item};
                   3619: 	}
1.207     raeburn  3620:         if (($phase eq 'get_user_info') || ($phase eq 'userpicked') ||
                   3621:             ($phase eq 'createnewuser')) {
                   3622:             if ($env{'form.phase'} eq 'createnewuser') {
                   3623:                 my $response;
                   3624:                 if ($env{'form.srchterm'} !~ /^$match_username$/) {
                   3625:                     my $response = &mt('You must specify a valid username. Only the following are allowed: letters numbers - . @');
1.221     raeburn  3626:                     $env{'form.phase'} = '';
1.207     raeburn  3627:                     &print_username_entry_form($r,$context,$response,$srch);
                   3628:                 } else {
                   3629:                     my $ccuname =&LONCAPA::clean_username($srch->{'srchterm'});
                   3630:                     my $ccdomain=&LONCAPA::clean_domain($srch->{'srchdomain'});
                   3631:                     &print_user_modification_page($r,$ccuname,$ccdomain,
1.221     raeburn  3632:                                                   $srch,$response,$context,
                   3633:                                                   $permission);
1.207     raeburn  3634:                 }
                   3635:             } elsif ($env{'form.phase'} eq 'get_user_info') {
1.190     raeburn  3636:                 my ($currstate,$response,$forcenewuser,$results) = 
1.221     raeburn  3637:                     &user_search_result($context,$srch);
1.190     raeburn  3638:                 if ($env{'form.currstate'} eq 'modify') {
                   3639:                     $currstate = $env{'form.currstate'};
                   3640:                 }
                   3641:                 if ($currstate eq 'select') {
                   3642:                     &print_user_selection_page($r,$response,$srch,$results,
1.229     raeburn  3643:                                                \@search,$context);
1.190     raeburn  3644:                 } elsif ($currstate eq 'modify') {
                   3645:                     my ($ccuname,$ccdomain);
                   3646:                     if (($srch->{'srchby'} eq 'uname') && 
                   3647:                         ($srch->{'srchtype'} eq 'exact')) {
                   3648:                         $ccuname = $srch->{'srchterm'};
                   3649:                         $ccdomain= $srch->{'srchdomain'};
                   3650:                     } else {
                   3651:                         my @matchedunames = keys(%{$results});
                   3652:                         ($ccuname,$ccdomain) = split(/:/,$matchedunames[0]);
                   3653:                     }
                   3654:                     $ccuname =&LONCAPA::clean_username($ccuname);
                   3655:                     $ccdomain=&LONCAPA::clean_domain($ccdomain);
                   3656:                     if ($env{'form.forcenewuser'}) {
                   3657:                         $response = '';
                   3658:                     }
                   3659:                     &print_user_modification_page($r,$ccuname,$ccdomain,
1.221     raeburn  3660:                                                   $srch,$response,$context,
                   3661:                                                   $permission);
1.190     raeburn  3662:                 } elsif ($currstate eq 'query') {
                   3663:                     &print_user_query_page($r,'createuser');
                   3664:                 } else {
1.229     raeburn  3665:                     $env{'form.phase'} = '';
1.207     raeburn  3666:                     &print_username_entry_form($r,$context,$response,$srch,
1.190     raeburn  3667:                                                $forcenewuser);
                   3668:                 }
                   3669:             } elsif ($env{'form.phase'} eq 'userpicked') {
                   3670:                 my $ccuname = &LONCAPA::clean_username($env{'form.seluname'});
                   3671:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.seludom'});
1.196     raeburn  3672:                 &print_user_modification_page($r,$ccuname,$ccdomain,$srch,'',
1.221     raeburn  3673:                                               $context,$permission);
1.190     raeburn  3674:             }
                   3675:         } elsif ($env{'form.phase'} eq 'update_user_data') {
1.206     raeburn  3676:             &update_user_data($r,$context);
1.190     raeburn  3677:         } else {
1.207     raeburn  3678:             &print_username_entry_form($r,$context,undef,$srch);
1.190     raeburn  3679:         }
                   3680:     } elsif ($env{'form.action'} eq 'custom' && $permission->{'custom'}) {
                   3681:         if ($env{'form.phase'} eq 'set_custom_roles') {
1.240     raeburn  3682:             &set_custom_role($r,$context);
1.190     raeburn  3683:         } else {
                   3684:             &custom_role_editor($r);
                   3685:         }
1.207     raeburn  3686:     } elsif (($env{'form.action'} eq 'listusers') && 
                   3687:              ($permission->{'view'} || $permission->{'cusr'})) {
1.202     raeburn  3688:         if ($env{'form.phase'} eq 'bulkchange') {
                   3689:             &Apache::lonhtmlcommon::add_breadcrumb
1.221     raeburn  3690:                 ({href=>'/adm/createuser?action=listusers',
                   3691:                   text=>"List Users"},
                   3692:                 {href=>"/adm/createuser",
                   3693:                   text=>"Result"});
1.202     raeburn  3694:             my $setting = $env{'form.roletype'};
                   3695:             my $choice = $env{'form.bulkaction'};
                   3696:             $r->print(&header());
1.221     raeburn  3697:             $r->print(&Apache::lonhtmlcommon::breadcrumbs("Update Users",
1.224     raeburn  3698:                                                           'Course_View_Class_List'));
1.202     raeburn  3699:             if ($permission->{'cusr'}) {
                   3700:                 &Apache::lonuserutils::update_user_list($r,$context,$setting,$choice);
1.221     raeburn  3701:                 $r->print(&Apache::loncommon::end_page());
                   3702:             } else {
                   3703:                 $r->print(&mt('You are not authorized to make bulk changes to user roles'));
1.223     raeburn  3704:                 $r->print('<p><a href="/adm/createuser?action=listusers">'.&mt('Display User Lists').'</a>');
1.221     raeburn  3705:                 $r->print(&Apache::loncommon::end_page());
1.202     raeburn  3706:             }
                   3707:         } else {
                   3708:             &Apache::lonhtmlcommon::add_breadcrumb
                   3709:                 ({href=>'/adm/createuser?action=listusers',
                   3710:                   text=>"List Users"});
                   3711:             my ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles);
                   3712:             my $formname = 'studentform';
                   3713:             if ($context eq 'domain' && $env{'form.roletype'} eq 'course') {
                   3714:                 ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles) = 
                   3715:                     &Apache::lonuserutils::courses_selector($env{'request.role.domain'},
                   3716:                                                             $formname);
                   3717:                 $jscript .= &verify_user_display();
                   3718:                 my $js = &add_script($jscript).$cb_jscript;
                   3719:                 my $loadcode = 
                   3720:                     &Apache::lonuserutils::course_selector_loadcode($formname);
                   3721:                 if ($loadcode ne '') {
                   3722:                     $r->print(&header($js,{'onload' => $loadcode,}));
                   3723:                 } else {
                   3724:                     $r->print(&header($js));
                   3725:                 }
1.191     raeburn  3726:             } else {
1.202     raeburn  3727:                 $r->print(&header(&add_script(&verify_user_display())));
1.191     raeburn  3728:             }
1.202     raeburn  3729:             $r->print(&Apache::lonhtmlcommon::breadcrumbs("List Users",
1.224     raeburn  3730:                                                           'Course_View_Class_List'));
1.202     raeburn  3731:             &Apache::lonuserutils::print_userlist($r,undef,$permission,$context,
                   3732:                          $formname,$totcodes,$codetitles,$idlist,$idlist_titles);
                   3733:             $r->print(&Apache::loncommon::end_page());
1.191     raeburn  3734:         }
1.213     raeburn  3735:     } elsif ($env{'form.action'} eq 'drop' && $permission->{'cusr'}) {
                   3736:         $r->print(&header());
                   3737:         &Apache::lonhtmlcommon::add_breadcrumb
                   3738:             ({href=>'/adm/createuser?action=drop',
                   3739:               text=>"Drop Students"});
                   3740:         if (!exists($env{'form.state'})) {
                   3741:             $r->print(&Apache::lonhtmlcommon::breadcrumbs('Drop Students',
                   3742:                                                           'Course_Drop_Student'));
                   3743: 
                   3744:             &Apache::lonuserutils::print_drop_menu($r,$context,$permission);
                   3745:         } elsif ($env{'form.state'} eq 'done') {
                   3746:             &Apache::lonhtmlcommon::add_breadcrumb
                   3747:             ({href=>'/adm/createuser?action=drop',
                   3748:               text=>"Result"});
                   3749:             $r->print(&Apache::lonhtmlcommon::breadcrumbs('Drop Students',
                   3750:                                                           'Course_Drop_Student'));
                   3751:             &Apache::lonuserutils::update_user_list($r,$context,undef,
                   3752:                                                     $env{'form.action'});
                   3753:         }
                   3754:         $r->print(&Apache::loncommon::end_page());
1.202     raeburn  3755:     } elsif ($env{'form.action'} eq 'dateselect') {
                   3756:         if ($permission->{'cusr'}) {
                   3757:             $r->print(&header(undef,undef,{'no_nav_bar' => 1}).
1.221     raeburn  3758:                       &Apache::lonuserutils::date_section_selector($context,
                   3759:                                                                    $permission).
1.202     raeburn  3760:                       &Apache::loncommon::end_page());
                   3761:         } else {
                   3762:             $r->print(&header().
                   3763:                      '<span class="LC_error">'.&mt('You do not have permission to modify dates or sections for users').'</span>'. 
                   3764:                      &Apache::loncommon::end_page());
                   3765:         }
1.237     raeburn  3766:     } elsif ($env{'form.action'} eq 'selfenroll') {
                   3767:         $r->print(&header());
                   3768:         &Apache::lonhtmlcommon::add_breadcrumb
                   3769:             ({href=>'/adm/createuser?action=selfenroll',
                   3770:               text=>"Configure Self-enrollment"});
                   3771:         if (!exists($env{'form.state'})) {
                   3772:             $r->print(&Apache::lonhtmlcommon::breadcrumbs('Configure Self-enrollment',
                   3773:                                                           'Course_Self_Enrollment'));
1.241     raeburn  3774:             $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
1.237     raeburn  3775:             &print_selfenroll_menu($r,$context,$permission);
                   3776:         } elsif ($env{'form.state'} eq 'done') {
                   3777:             &Apache::lonhtmlcommon::add_breadcrumb
                   3778:             ({href=>'/adm/createuser?action=selfenroll',
                   3779:               text=>"Result"});
                   3780:             $r->print(&Apache::lonhtmlcommon::breadcrumbs('Self-enrollment result',
                   3781:                                                           'Course_Self_Enrollment'));
1.241     raeburn  3782:             $r->print('<h3>'.&mt('Self-enrollment with a student role').'</h3>'."\n");
                   3783:             &update_selfenroll_config($r,$context,$permission);
1.237     raeburn  3784:         }
                   3785:         $r->print(&Apache::loncommon::end_page());
1.277     raeburn  3786:     } elsif ($env{'form.action'} eq 'selfenrollqueue') {
                   3787:         $r->print(&header());
                   3788:         &Apache::lonhtmlcommon::add_breadcrumb
                   3789:             ({href=>'/adm/createuser?action=selfenrollqueue',
                   3790:               text=>"Enrollment requests"});
                   3791:         my $cid = $env{'request.course.id'};
                   3792:         my $cdom = $env{'course.'.$cid.'.domain'};
                   3793:         my $cnum = $env{'course.'.$cid.'.num'};
                   3794:         if (!exists($env{'form.state'})) {
                   3795:             $r->print(&Apache::lonhtmlcommon::breadcrumbs('Enrollment requests',
                   3796:                                                           'Course_SelfEnrollment_Approval'));
                   3797:             $r->print('<h3>'.&mt('Pending enrollment requests').'</h3>'."\n");
                   3798:             &display_selfenroll_queue($r,$context,$permission,$cnum,$cdom);
                   3799:         } elsif ($env{'form.state'} eq 'done') {
                   3800:             &Apache::lonhtmlcommon::add_breadcrumb
                   3801:             ({href=>'/adm/createuser?action=selfenrollqueue',
                   3802:               text=>"Result"});
                   3803:             $r->print(&Apache::lonhtmlcommon::breadcrumbs('Enrollment result',
                   3804:                                                           'Course_Self_Enrollment'));
                   3805:             $r->print('<h3>'.&mt('Enrollment request processing').'</h3>'."\n");
                   3806:             &update_selfenroll_queue($r,$context,$permission,$cid,$cnum,$cdom);
                   3807:         }
                   3808:         $r->print(&Apache::loncommon::end_page());
1.239     raeburn  3809:     } elsif ($env{'form.action'} eq 'changelogs') {
                   3810:         $r->print(&header());
                   3811:         &Apache::lonhtmlcommon::add_breadcrumb
                   3812:             ({href=>'/adm/createuser?action=changelogs',
                   3813:               text=>"User Management Logs"});
                   3814:         $r->print(&Apache::lonhtmlcommon::breadcrumbs('User Changes',
                   3815:                                                       'Course_User_Logs'));
                   3816:             &print_userchangelogs_display($r,$context,$permission);
                   3817:         $r->print(&Apache::loncommon::end_page());        
1.190     raeburn  3818:     } else {
                   3819:         $r->print(&header());
1.202     raeburn  3820:         $r->print(&Apache::lonhtmlcommon::breadcrumbs('User Management'));
1.207     raeburn  3821:         $r->print(&print_main_menu($permission,$context));
1.190     raeburn  3822:         $r->print(&Apache::loncommon::end_page());
                   3823:     }
                   3824:     return OK;
                   3825: }
                   3826: 
                   3827: sub header {
1.202     raeburn  3828:     my ($jscript,$loaditems,$args) = @_;
1.190     raeburn  3829:     my $start_page;
                   3830:     if (ref($loaditems) eq 'HASH') {
1.202     raeburn  3831:         $start_page=&Apache::loncommon::start_page('User Management',$jscript,{'add_entries' => $loaditems});
1.190     raeburn  3832:     } else {
1.202     raeburn  3833:         $start_page=&Apache::loncommon::start_page('User Management',$jscript,$args);
1.190     raeburn  3834:     }
                   3835:     return $start_page;
                   3836: }
1.2       www      3837: 
1.191     raeburn  3838: sub add_script {
                   3839:     my ($js) = @_;
                   3840:     return '<script type="text/javascript">'."\n".$js."\n".'</script>';
                   3841: }
                   3842: 
1.202     raeburn  3843: sub verify_user_display {
                   3844:     my $output = <<"END";
                   3845: 
                   3846: function display_update() {
                   3847:     document.studentform.action.value = 'listusers';
                   3848:     document.studentform.phase.value = 'display';
                   3849:     document.studentform.submit();
                   3850: }
                   3851: 
                   3852: END
                   3853:     return $output;
                   3854: 
                   3855: }
                   3856: 
1.190     raeburn  3857: ###############################################################
                   3858: ###############################################################
                   3859: #  Menu Phase One
                   3860: sub print_main_menu {
1.208     raeburn  3861:     my ($permission,$context) = @_;
                   3862:     my %links = (
                   3863:                        domain => {
                   3864:                                    upload => 'Upload a File of Users',
1.221     raeburn  3865:                                    singleuser => 'Add/Modify a Single User',
1.208     raeburn  3866:                                    listusers => 'Manage Multiple Users',
                   3867:                                  },
                   3868:                        author => {
                   3869:                                    upload => 'Upload a File of Co-authors',
1.221     raeburn  3870:                                    singleuser => 'Add/Modify a Single Co-author',
1.208     raeburn  3871:                                    listusers => 'Display Co-authors and Manage Multiple Users',
                   3872:                                  },
                   3873:                        course => {
1.295.2.1  raeburn  3874:                                    upload => 'Upload a File of Course Users',
                   3875:                                    singleuser => 'Add/Modify a Single Course User',
                   3876:                                    listusers => 'Display Class Lists and Manage Multiple Users',
1.208     raeburn  3877:                                  },
1.295.2.1  raeburn  3878:                 );
1.265     mielkec  3879: 
1.295.2.1  raeburn  3880:     my @menu =
                   3881:         (
                   3882:           { text => $links{$context}{'upload'},
                   3883:             help => 'Course_Create_Class_List',
                   3884:             action => 'upload',
                   3885:             permission => $permission->{'cusr'},
                   3886:             },
                   3887:           { text => $links{$context}{'singleuser'},
                   3888:             help => 'Course_Change_Privileges',
                   3889:             action => 'singleuser',
                   3890:             permission => $permission->{'cusr'},
                   3891:             },
                   3892:           { text => $links{$context}{'listusers'},
                   3893:             help => 'Course_View_Class_List',
                   3894:             action => 'listusers',
                   3895:             permission => ($permission->{'view'} || $permission->{'cusr'}),
                   3896:           },
                   3897:         );
                   3898:     if ($context eq 'domain' || $context eq 'course') {
                   3899:         my $customlink =  { text => 'Edit Custom Roles',
                   3900:                             help => 'Course_Editing_Custom_Roles',
                   3901:                             action => 'custom',
                   3902:                             permission => $permission->{'custom'},
                   3903:                           };
                   3904:         push(@menu,$customlink);
                   3905:     }
                   3906:     if ($context eq 'course') {
                   3907:         my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity();
                   3908:         my @courselinks =
                   3909:             (
                   3910:               { text => 'Enroll a Single Student',
                   3911:                  help => 'Course_Add_Student',
                   3912:                  action => 'singlestudent',
                   3913:                  permission => $permission->{'cusr'},
                   3914:                  },
                   3915:               { text => 'Drop Students',
                   3916:                 help => 'Course_Drop_Student',
                   3917:                 action => 'drop',
                   3918:                 permission => $permission->{'cusr'},
                   3919:               });
                   3920:         if (!exists($permission->{'cusr_section'})) {
                   3921:             push(@courselinks,
                   3922:                { text => 'Automated Enrollment Manager',
                   3923:                  help => 'Course_Automated_Enrollment',
                   3924:                  permission => (&Apache::lonnet::auto_run($cnum,$cdom)
                   3925:                                 && $permission->{'cusr'}),
                   3926:                  url  => '/adm/populate',
                   3927:                  },
                   3928:                { text => 'Configure User Self-enrollment',
                   3929:                  help => 'Course_Self_Enrollment',
                   3930:                  action => 'selfenroll',
                   3931:                  permission => $permission->{'cusr'},
                   3932:                });
                   3933:         }
1.295.2.2  raeburn  3934:         if ($env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_approval'}) {
                   3935:             push(@courselinks,
                   3936:                     {   text => 'Enrollment Requests',
                   3937:                         help => 'Course_Approve_Selfenroll',
                   3938:                         action => 'selfenrollqueue',
                   3939:                         permission => $permission->{'cusr'},
                   3940:                     });
                   3941:         }
1.295.2.1  raeburn  3942:         push(@courselinks,
                   3943:                { text => 'Manage Course Groups',
                   3944:                  help => 'Course_Manage_Group',
                   3945:                  permission => $permission->{'grp_manage'},
                   3946:                  url => '/adm/coursegroups?refpage=cusr',
                   3947:                },
                   3948:                { text => 'View Change Logs',
                   3949:                  help => 'Course_User_Logs',
                   3950:                  action => 'changelogs',
                   3951:                  permission => $permission->{'cusr'},
                   3952:                },);
1.250     raeburn  3953: #               { text => 'View Log-in History',
                   3954: #                 help => 'Course_User_Logins',
                   3955: #                 action => 'logins',
                   3956: #                 permission => $permission->{'cusr'},
                   3957: #               });
1.295.2.1  raeburn  3958:         push(@menu,@courselinks);
                   3959:     }
                   3960:     my $menu_html = '';
                   3961:     foreach my $menu_item (@menu) {
                   3962:         next if (! $menu_item->{'permission'});
                   3963:         $menu_html.='<p>';
                   3964:         if (exists($menu_item->{'help'})) {
                   3965:             $menu_html.=
                   3966:                 &Apache::loncommon::help_open_topic($menu_item->{'help'});
                   3967:         }
                   3968:         $menu_html.='<font size="+1">';
                   3969:         if (exists($menu_item->{'url'})) {
                   3970:             $menu_html.=qq{<a href="$menu_item->{'url'}">};
                   3971:         } else {
                   3972:             $menu_html.=
                   3973:                 qq{<a href="/adm/createuser?action=$menu_item->{'action'}">};      }
                   3974:         $menu_html.= &mt($menu_item->{'text'}).'</a></font>';
                   3975:         $menu_html.='</p>';
                   3976:     }
                   3977:     return $menu_html;
1.190     raeburn  3978: }
                   3979: 
1.189     albertel 3980: sub restore_prev_selections {
                   3981:     my %saveable_parameters = ('srchby'   => 'scalar',
                   3982: 			       'srchin'   => 'scalar',
                   3983: 			       'srchtype' => 'scalar',
                   3984: 			       );
                   3985:     &Apache::loncommon::store_settings('user','user_picker',
                   3986: 				       \%saveable_parameters);
                   3987:     &Apache::loncommon::restore_settings('user','user_picker',
                   3988: 					 \%saveable_parameters);
                   3989: }
                   3990: 
1.237     raeburn  3991: sub print_selfenroll_menu {
                   3992:     my ($r,$context,$permission) = @_;
                   3993:     my $formname = 'enrollstudent';
                   3994:     my $nolink = 1;
                   3995:     my ($row,$lt) = &get_selfenroll_titles();
                   3996:     my $groupslist = &Apache::lonuserutils::get_groupslist();
                   3997:     my $setsec_js = 
                   3998:         &Apache::lonuserutils::setsections_javascript($formname,$groupslist);
1.249     raeburn  3999:     my %alerts = &Apache::lonlocal::texthash(
                   4000:         acto => 'Activation of self-enrollment was selected for the following domain(s)',
                   4001:         butn => 'but no user types have been checked.',
                   4002:         wilf => "Please uncheck 'activate' or check at least one type.",
                   4003:     );
                   4004:     my $selfenroll_js = <<"ENDSCRIPT";
                   4005: function update_types(caller,num) {
                   4006:     var delidx = getIndexByName('selfenroll_delete');
                   4007:     var actidx = getIndexByName('selfenroll_activate');
                   4008:     if (caller == 'selfenroll_all') {
                   4009:         var selall;
                   4010:         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
                   4011:             if (document.$formname.selfenroll_all[i].checked) {
                   4012:                 selall = document.$formname.selfenroll_all[i].value;
                   4013:             }
                   4014:         }
                   4015:         if (selall == 1) {
                   4016:             if (delidx != -1) {
                   4017:                 if (document.$formname.selfenroll_delete.length) {
                   4018:                     for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
                   4019:                         document.$formname.selfenroll_delete[j].checked = true;
                   4020:                     }
                   4021:                 } else {
                   4022:                     document.$formname.elements[delidx].checked = true;
                   4023:                 }
                   4024:             }
                   4025:             if (actidx != -1) {
                   4026:                 if (document.$formname.selfenroll_activate.length) {
                   4027:                     for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
                   4028:                         document.$formname.selfenroll_activate[j].checked = false;
                   4029:                     }
                   4030:                 } else {
                   4031:                     document.$formname.elements[actidx].checked = false;
                   4032:                 }
                   4033:             }
                   4034:             document.$formname.selfenroll_newdom.selectedIndex = 0; 
                   4035:         }
                   4036:     }
                   4037:     if (caller == 'selfenroll_activate') {
                   4038:         if (document.$formname.selfenroll_activate.length) {
                   4039:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
                   4040:                 if (document.$formname.selfenroll_activate[j].value == num) {
                   4041:                     if (document.$formname.selfenroll_activate[j].checked) {
                   4042:                         for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
                   4043:                             if (document.$formname.selfenroll_all[i].value == '1') {
                   4044:                                 document.$formname.selfenroll_all[i].checked = false;
                   4045:                             }
                   4046:                             if (document.$formname.selfenroll_all[i].value == '0') {
                   4047:                                 document.$formname.selfenroll_all[i].checked = true;
                   4048:                             }
                   4049:                         }
                   4050:                     }
                   4051:                 }
                   4052:             }
                   4053:         } else {
                   4054:             for (var i=0; i<document.$formname.selfenroll_all.length; i++) {
                   4055:                 if (document.$formname.selfenroll_all[i].value == '1') {
                   4056:                     document.$formname.selfenroll_all[i].checked = false;
                   4057:                 }
                   4058:                 if (document.$formname.selfenroll_all[i].value == '0') {
                   4059:                     document.$formname.selfenroll_all[i].checked = true;
                   4060:                 }
                   4061:             }
                   4062:         }
                   4063:     }
                   4064:     if (caller == 'selfenroll_delete') {
                   4065:         if (document.$formname.selfenroll_delete.length) {
                   4066:             for (var j=0; j<document.$formname.selfenroll_delete.length; j++) {
                   4067:                 if (document.$formname.selfenroll_delete[j].value == num) {
                   4068:                     if (document.$formname.selfenroll_delete[j].checked) {
                   4069:                         var delindex = getIndexByName('selfenroll_types_'+num);
                   4070:                         if (delindex != -1) { 
                   4071:                             if (document.$formname.elements[delindex].length) {
                   4072:                                 for (var k=0; k<document.$formname.elements[delindex].length; k++) {
                   4073:                                     document.$formname.elements[delindex][k].checked = false;
                   4074:                                 }
                   4075:                             } else {
                   4076:                                 document.$formname.elements[delindex].checked = false;
                   4077:                             }
                   4078:                         }
                   4079:                     }
                   4080:                 }
                   4081:             }
                   4082:         } else {
                   4083:             if (document.$formname.selfenroll_delete.checked) {
                   4084:                 var delindex = getIndexByName('selfenroll_types_'+num);
                   4085:                 if (delindex != -1) {
                   4086:                     if (document.$formname.elements[delindex].length) {
                   4087:                         for (var k=0; k<document.$formname.elements[delindex].length; k++) {
                   4088:                             document.$formname.elements[delindex][k].checked = false;
                   4089:                         }
                   4090:                     } else {
                   4091:                         document.$formname.elements[delindex].checked = false;
                   4092:                     }
                   4093:                 }
                   4094:             }
                   4095:         }
                   4096:     }
                   4097:     return;
                   4098: }
                   4099: 
                   4100: function validate_types(form) {
                   4101:     var needaction = new Array();
                   4102:     var countfail = 0;
                   4103:     var actidx = getIndexByName('selfenroll_activate');
                   4104:     if (actidx != -1) {
                   4105:         if (document.$formname.selfenroll_activate.length) {
                   4106:             for (var j=0; j<document.$formname.selfenroll_activate.length; j++) {
                   4107:                 var num = document.$formname.selfenroll_activate[j].value;
                   4108:                 if (document.$formname.selfenroll_activate[j].checked) {
                   4109:                     countfail = check_types(num,countfail,needaction)
                   4110:                 }
                   4111:             }
                   4112:         } else {
                   4113:             if (document.$formname.selfenroll_activate.checked) {
                   4114:                 var num = document.enrollstudent.selfenroll_activate.value;
                   4115:                 countfail = check_types(num,countfail,needaction)
                   4116:             }
                   4117:         }
                   4118:     }
                   4119:     if (countfail > 0) {
                   4120:         var msg = "$alerts{'acto'}\\n";
                   4121:         var loopend = needaction.length -1;
                   4122:         if (loopend > 0) {
                   4123:             for (var m=0; m<loopend; m++) {
                   4124:                 msg += needaction[m]+", ";
                   4125:             }
                   4126:         }
                   4127:         msg += needaction[loopend]+"\\n$alerts{'butn'}\\n$alerts{'wilf'}";
                   4128:         alert(msg);
                   4129:         return; 
                   4130:     }
                   4131:     setSections(form);
                   4132: }
                   4133: 
                   4134: function check_types(num,countfail,needaction) {
                   4135:     var typeidx = getIndexByName('selfenroll_types_'+num);
                   4136:     var count = 0;
                   4137:     if (typeidx != -1) {
                   4138:         if (document.$formname.elements[typeidx].length) {
                   4139:             for (var k=0; k<document.$formname.elements[typeidx].length; k++) {
                   4140:                 if (document.$formname.elements[typeidx][k].checked) {
                   4141:                     count ++;
                   4142:                 }
                   4143:             }
                   4144:         } else {
                   4145:             if (document.$formname.elements[typeidx].checked) {
                   4146:                 count ++;
                   4147:             }
                   4148:         }
                   4149:         if (count == 0) {
                   4150:             var domidx = getIndexByName('selfenroll_dom_'+num);
                   4151:             if (domidx != -1) {
                   4152:                 var domname = document.$formname.elements[domidx].value;
                   4153:                 needaction[countfail] = domname;
                   4154:                 countfail ++;
                   4155:             }
                   4156:         }
                   4157:     }
                   4158:     return countfail;
                   4159: }
                   4160: 
                   4161: function getIndexByName(item) {
                   4162:     for (var i=0;i<document.$formname.elements.length;i++) {
                   4163:         if (document.$formname.elements[i].name == item) {
                   4164:             return i;
                   4165:         }
                   4166:     }
                   4167:     return -1;
                   4168: }
                   4169: ENDSCRIPT
1.256     raeburn  4170:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4171:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4172: 
1.237     raeburn  4173:     my $output = '<script type="text/javascript">'."\n".
1.249     raeburn  4174:                  $setsec_js."\n".$selfenroll_js."\n".
1.237     raeburn  4175:                  '</script>'."\n".
1.256     raeburn  4176:                  '<h3>'.$lt->{'selfenroll'}.'</h3>'."\n";
                   4177:     my ($visible,$cansetvis,$vismsgs,$visactions) = &visible_in_cat($cdom,$cnum);
                   4178:     if (ref($visactions) eq 'HASH') {
                   4179:         if ($visible) {
1.283     bisitz   4180:             $output .= '<p class="LC_info">'.$visactions->{'vis'}.'</p>';
1.256     raeburn  4181:         } else {
1.283     bisitz   4182:             $output .= '<p class="LC_warning">'.$visactions->{'miss'}.'</p>'
                   4183:                       .$visactions->{'yous'}.
1.256     raeburn  4184:                        '<p>'.$visactions->{'gen'}.'<br />'.$visactions->{'coca'};
                   4185:             if (ref($vismsgs) eq 'ARRAY') {
                   4186:                 $output .= '<br />'.$visactions->{'make'}.'<ul>';
                   4187:                 foreach my $item (@{$vismsgs}) {
                   4188:                     $output .= '<li>'.$visactions->{$item}.'</li>';
                   4189:                 }
                   4190:                 $output .= '</ul>';
                   4191:             }
                   4192:             $output .= '</p>';
                   4193:         }
                   4194:     }
                   4195:     $output .= '<form name="'.$formname.'" method="post" action="/adm/createuser">'."\n".
                   4196:                &Apache::lonhtmlcommon::start_pick_box();
1.237     raeburn  4197:     if (ref($row) eq 'ARRAY') {
                   4198:         foreach my $item (@{$row}) {
                   4199:             my $title = $item; 
                   4200:             if (ref($lt) eq 'HASH') {
                   4201:                 $title = $lt->{$item};
                   4202:             }
                   4203:             $output .= 
                   4204:                 &Apache::lonhtmlcommon::row_title($title,
                   4205:                              'LC_selfenroll_pick_box_title','LC_oddrow_value')."\n";
                   4206:             if ($item eq 'types') {
                   4207:                 my $curr_types = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_types'};
1.241     raeburn  4208:                 my $showdomdesc = 1;
                   4209:                 my $includeempty = 1;
                   4210:                 my $num = 0;
                   4211:                 $output .= &Apache::loncommon::start_data_table().
                   4212:                            &Apache::loncommon::start_data_table_row()
                   4213:                            .'<td colspan="2"><span class="LC_nobreak"><label>'
                   4214:                            .&mt('Any user in any domain:')
                   4215:                            .'&nbsp;<input type="radio" name="selfenroll_all" value="1" ';
                   4216:                 if ($curr_types eq '*') {
                   4217:                     $output .= ' checked="checked" '; 
                   4218:                 }
1.249     raeburn  4219:                 $output .= 'onchange="javascript:update_types('.
                   4220:                            "'selfenroll_all'".');" />'.&mt('Yes').'</label>'.
                   4221:                            '&nbsp;&nbsp;<input type="radio" name="selfenroll_all" value="0" ';
1.241     raeburn  4222:                 if ($curr_types ne '*') {
                   4223:                     $output .= ' checked="checked" ';
                   4224:                 }
1.249     raeburn  4225:                 $output .= ' onchange="javascript:update_types('.
                   4226:                            "'selfenroll_all'".');"/>'.&mt('No').'</label></td>'.
                   4227:                            &Apache::loncommon::end_data_table_row().
                   4228:                            &Apache::loncommon::end_data_table().
                   4229:                            &mt('Or').'<br />'.
                   4230:                            &Apache::loncommon::start_data_table();
1.241     raeburn  4231:                 my %currdoms;
1.249     raeburn  4232:                 if ($curr_types eq '') {
1.241     raeburn  4233:                     $output .= &new_selfenroll_dom_row($cdom,'0');
                   4234:                 } elsif ($curr_types ne '*') {
                   4235:                     my @entries = split(/;/,$curr_types);
                   4236:                     if (@entries > 0) {
                   4237:                         foreach my $entry (@entries) {
                   4238:                             my ($currdom,$typestr) = split(/:/,$entry);
                   4239:                             $currdoms{$currdom} = 1;
                   4240:                             my $domdesc = &Apache::lonnet::domain($currdom);
1.249     raeburn  4241:                             my @currinsttypes = split(',',$typestr);
1.241     raeburn  4242:                             $output .= &Apache::loncommon::start_data_table_row()
                   4243:                                        .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'<b>'
                   4244:                                        .'&nbsp;'.$domdesc.' ('.$currdom.')'
                   4245:                                        .'</b><input type="hidden" name="selfenroll_dom_'.$num
                   4246:                                        .'" value="'.$currdom.'" /></span><br />'
                   4247:                                        .'<span class="LC_nobreak"><label><input type="checkbox" '
1.249     raeburn  4248:                                        .'name="selfenroll_delete" value="'.$num.'" onchange="javascript:update_types('."'selfenroll_delete','$num'".');" />'
1.241     raeburn  4249:                                        .&mt('Delete').'</label></span></td>';
1.249     raeburn  4250:                             $output .= '<td valign="top">&nbsp;&nbsp;'.&mt('User types:').'<br />'
1.241     raeburn  4251:                                        .&selfenroll_inst_types($num,$currdom,\@currinsttypes).'</td>'
                   4252:                                        .&Apache::loncommon::end_data_table_row();
                   4253:                             $num ++;
                   4254:                         }
                   4255:                     }
                   4256:                 }
1.249     raeburn  4257:                 my $add_domtitle = &mt('Users in additional domain:');
1.241     raeburn  4258:                 if ($curr_types eq '*') { 
1.249     raeburn  4259:                     $add_domtitle = &mt('Users in specific domain:');
1.241     raeburn  4260:                 } elsif ($curr_types eq '') {
1.249     raeburn  4261:                     $add_domtitle = &mt('Users in other domain:');
1.241     raeburn  4262:                 }
                   4263:                 $output .= &Apache::loncommon::start_data_table_row()
                   4264:                            .'<td colspan="2"><span class="LC_nobreak">'.$add_domtitle.'</span><br />'
                   4265:                            .&Apache::loncommon::select_dom_form('','selfenroll_newdom',
                   4266:                                                                 $includeempty,$showdomdesc)
                   4267:                            .'<input type="hidden" name="selfenroll_types_total" value="'.$num.'" />'
                   4268:                            .'</td>'.&Apache::loncommon::end_data_table_row()
                   4269:                            .&Apache::loncommon::end_data_table();
1.237     raeburn  4270:             } elsif ($item eq 'registered') {
                   4271:                 my ($regon,$regoff);
                   4272:                 if ($env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_registered'}) {
                   4273:                     $regon = ' checked="checked" ';
                   4274:                     $regoff = ' ';
                   4275:                 } else {
                   4276:                     $regon = ' ';
                   4277:                     $regoff = ' checked="checked" ';
                   4278:                 }
                   4279:                 $output .= '<label>'.
1.245     raeburn  4280:                            '<input type="radio" name="selfenroll_registered" value="1"'.$regon.'/>'.
1.244     bisitz   4281:                            &mt('Yes').'</label>&nbsp;&nbsp;<label>'.
1.245     raeburn  4282:                            '<input type="radio" name="selfenroll_registered" value="0"'.$regoff.'/>'.
1.244     bisitz   4283:                            &mt('No').'</label>';
1.237     raeburn  4284:             } elsif ($item eq 'enroll_dates') {
                   4285:                 my $starttime = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_start_date'};
                   4286:                 my $endtime = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_end_date'};
                   4287:                 if ($starttime eq '') {
                   4288:                     $starttime = $env{'course.'.$env{'request.course.id'}.'.default_enrollment_start_date'};
                   4289:                 }
                   4290:                 if ($endtime eq '') {
                   4291:                     $endtime = $env{'course.'.$env{'request.course.id'}.'.default_enrollment_end_date'};
                   4292:                 }
                   4293:                 my $startform =
                   4294:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_date',$starttime,
                   4295:                                       undef,undef,undef,undef,undef,undef,undef,$nolink);
                   4296:                 my $endform =
                   4297:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_date',$endtime,
                   4298:                                       undef,undef,undef,undef,undef,undef,undef,$nolink);
                   4299:                 $output .= &selfenroll_date_forms($startform,$endform);
                   4300:             } elsif ($item eq 'access_dates') {
                   4301:                 my $starttime = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_start_access'};
                   4302:                 my $endtime = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_end_access'};
                   4303:                 if ($starttime eq '') {
                   4304:                     $starttime = $env{'course.'.$env{'request.course.id'}.'.default_enrollment_start_date'};
                   4305:                 }
                   4306:                 if ($endtime eq '') {
                   4307:                     $endtime = $env{'course.'.$env{'request.course.id'}.'.default_enrollment_end_date'};
                   4308:                 }
                   4309:                 my $startform =
                   4310:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_start_access',$starttime,
                   4311:                                       undef,undef,undef,undef,undef,undef,undef,$nolink);
                   4312:                 my $endform =
                   4313:                     &Apache::lonhtmlcommon::date_setter($formname,'selfenroll_end_access',$endtime,
                   4314:                                       undef,undef,undef,undef,undef,undef,undef,$nolink);
                   4315:                 $output .= &selfenroll_date_forms($startform,$endform);
                   4316:             } elsif ($item eq 'section') {
                   4317:                 my $currsec = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_section'}; 
                   4318:                 my %sections_count = &Apache::loncommon::get_sections($cdom,$cnum);
                   4319:                 my $newsecval;
                   4320:                 if ($currsec ne 'none' && $currsec ne '') {
                   4321:                     if (!defined($sections_count{$currsec})) {
                   4322:                         $newsecval = $currsec;
                   4323:                     }
                   4324:                 }
                   4325:                 my $sections_select = 
                   4326:                     &Apache::lonuserutils::course_sections(\%sections_count,'st',$currsec);
                   4327:                 $output .= '<table class="LC_createuser">'."\n".
                   4328:                            '<tr class="LC_section_row">'."\n".
                   4329:                            '<td align="center">'.&mt('Existing sections')."\n".
                   4330:                            '<br />'.$sections_select.'</td><td align="center">'.
                   4331:                            &mt('New section').'<br />'."\n".
                   4332:                            '<input type="text" name="newsec" size="15" value="'.$newsecval.'" />'."\n".
                   4333:                            '<input type="hidden" name="sections" value="" />'."\n".
                   4334:                            '<input type="hidden" name="state" value="done" />'."\n".
                   4335:                            '</td></tr></table>'."\n";
1.276     raeburn  4336:             } elsif ($item eq 'approval') {
                   4337:                 my ($appon,$appoff);
                   4338:                 my $cid = $env{'request.course.id'};
                   4339:                 my $currnotified = $env{'course.'.$cid.'.internal.selfenroll_notifylist'};
                   4340:                 if ($env{'course.'.$cid.'.internal.selfenroll_approval'}) {
                   4341:                     $appon = ' checked="checked" ';
                   4342:                     $appoff = ' ';
                   4343:                 } else {
                   4344:                     $appon = ' ';
                   4345:                     $appoff = ' checked="checked" ';
                   4346:                 }
                   4347:                 $output .= '<label>'.
                   4348:                            '<input type="radio" name="selfenroll_approval" value="1"'.$appon.'/>'.
                   4349:                            &mt('Yes').'</label>&nbsp;&nbsp;<label>'.
                   4350:                            '<input type="radio" name="selfenroll_approval" value="0"'.$appoff.'/>'.
                   4351:                            &mt('No').'</label>';
                   4352:                 my %advhash = &Apache::lonnet::get_course_adv_roles($cid,1);
                   4353:                 my (@ccs,%notified);
                   4354:                 if ($advhash{'cc'}) {
                   4355:                     @ccs = split(/,/,$advhash{'cc'});
                   4356:                 }
                   4357:                 if ($currnotified) {
                   4358:                     foreach my $current (split(/,/,$currnotified)) {
                   4359:                         $notified{$current} = 1;
                   4360:                         if (!grep(/^\Q$current\E$/,@ccs)) {
                   4361:                             push(@ccs,$current);
                   4362:                         }
                   4363:                     }
                   4364:                 }
                   4365:                 if (@ccs) {
1.277     raeburn  4366:                     $output .= '<br />'.&mt('Personnel to be notified when an enrollment request needs approval, or has been approved:').'&nbsp;'.&Apache::loncommon::start_data_table().
1.276     raeburn  4367:                                &Apache::loncommon::start_data_table_row();
                   4368:                     my $count = 0;
                   4369:                     my $numcols = 4;
                   4370:                     foreach my $cc (sort(@ccs)) {
                   4371:                         my $notifyon;
                   4372:                         my ($ccuname,$ccudom) = split(/:/,$cc);
                   4373:                         if ($notified{$cc}) {
                   4374:                             $notifyon = ' checked="checked" ';
                   4375:                         }
                   4376:                         if ($count && !$count%$numcols) {
                   4377:                             $output .= &Apache::loncommon::end_data_table_row().
                   4378:                                        &Apache::loncommon::start_data_table_row()
                   4379:                         }
                   4380:                         $output .= '<td><span class="LC_nobreak"><label>'.
                   4381:                                    '<input type="checkbox" name="selfenroll_notify"'.$notifyon.' value="'.$cc.'" />'.
                   4382:                                    &Apache::loncommon::plainname($ccuname,$ccudom).
                   4383:                                    '</label></span></td>';
                   4384:                         $count;
                   4385:                     }
                   4386:                     my $rem = $count%$numcols;
                   4387:                     if ($rem) {
                   4388:                         my $emptycols = $numcols - $rem;
                   4389:                         for (my $i=0; $i<$emptycols; $i++) { 
                   4390:                             $output .= '<td>&nbsp;</td>';
                   4391:                         }
                   4392:                     }
                   4393:                     $output .= &Apache::loncommon::end_data_table_row().
                   4394:                                &Apache::loncommon::end_data_table();
                   4395:                 }
                   4396:             } elsif ($item eq 'limit') {
                   4397:                 my ($crslimit,$selflimit,$nolimit);
                   4398:                 my $cid = $env{'request.course.id'};
                   4399:                 my $currlim = $env{'course.'.$cid.'.internal.selfenroll_limit'};
                   4400:                 my $currcap = $env{'course.'.$cid.'.internal.selfenroll_cap'};
                   4401:                 my $nolimit = ' checked="checked" ';
                   4402:                 if ($currlim eq 'allstudents') {
                   4403:                     $crslimit = ' checked="checked" ';
                   4404:                     $selflimit = ' ';
                   4405:                     $nolimit = ' ';
                   4406:                 } elsif ($currlim eq 'selfenrolled') {
                   4407:                     $crslimit = ' ';
                   4408:                     $selflimit = ' checked="checked" ';
                   4409:                     $nolimit = ' '; 
                   4410:                 } else {
                   4411:                     $crslimit = ' ';
                   4412:                     $selflimit = ' ';
                   4413:                 }
                   4414:                 $output .= '<table><tr><td><label>'.
1.278     raeburn  4415:                            '<input type="radio" name="selfenroll_limit" value="none"'.$nolimit.'/>'.
1.276     raeburn  4416:                            &mt('No limit').'</label></td><td><label>'.
                   4417:                            '<input type="radio" name="selfenroll_limit" value="allstudents"'.$crslimit.'/>'.
                   4418:                            &mt('Limit by total students').'</label></td><td><label>'.
                   4419:                            '<input type="radio" name="selfenroll_limit" value="selfenrolled"'.$selflimit.'/>'.
                   4420:                            &mt('Limit by total self-enrolled students').
                   4421:                            '</td></tr><tr>'.
                   4422:                            '<td>&nbsp;</td><td colspan="2"><span class="LC_nobreak">'.
                   4423:                            ('&nbsp;'x3).&mt('Maximum number allowed: ').
                   4424:                            '<input type="text" name="selfenroll_cap" size = "5" value="'.$currcap.'" /></td></tr></table>';
1.237     raeburn  4425:             }
                   4426:             $output .= &Apache::lonhtmlcommon::row_closure(1);
                   4427:         }
                   4428:     }
                   4429:     $output .= &Apache::lonhtmlcommon::end_pick_box().
1.241     raeburn  4430:                '<br /><input type="button" name="selfenrollconf" value="'
1.282     schafran 4431:                .&mt('Save').'" onclick="validate_types(this.form);" />'
1.241     raeburn  4432:                .'<input type="hidden" name="action" value="selfenroll" /></form>';
1.237     raeburn  4433:     $r->print($output);
                   4434:     return;
                   4435: }
                   4436: 
1.277     raeburn  4437: sub display_selfenroll_queue {
                   4438:     my ($r,$context,$permission,$cnum,$cdom) = @_;
                   4439:     my $namespace = 'selfenrollrequests';
                   4440:     my ($output,%queue_by_date);
                   4441:     my %requesthash = &Apache::lonnet::dump($namespace,$cdom,$cnum);
                   4442:     if (keys(%requesthash) > 0) {
                   4443:         $r->print('<form method="post" name="changequeue" action="/adm/createuser" />'.
                   4444:                   '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
                   4445:                   '<input type="hidden" name="state" value="done" />'.
                   4446:                   &Apache::loncommon::start_data_table().
                   4447:                   &Apache::loncommon::start_data_table_header_row().
                   4448:                   '<th>'.&mt('Action').'</th>'.
                   4449:                   '<th>'.&mt('Requestor').'</th>'.
                   4450:                   '<th>'.&mt('Section').'</th>'.
                   4451:                   '<th>'.&mt('Date requested').'</th>'.
                   4452:                   &Apache::loncommon::end_data_table_header_row());
                   4453:         foreach my $item (keys(%requesthash)) {
                   4454:             my ($timestamp,$usec) = split(/:/,$requesthash{$item});
                   4455:             if (exists($queue_by_date{$timestamp})) {
                   4456:                 if (ref($queue_by_date{$timestamp}) eq 'ARRAY') {
                   4457:                     push(@{$queue_by_date{$timestamp}},$item.':'.$usec);
                   4458:                 }
                   4459:             } else {
                   4460:                 @{$queue_by_date{$timestamp}} = ($item.':'.$usec);
                   4461:             }
                   4462:         }
                   4463:         my @sortedtimes = sort {$a <=> $b} (keys(%queue_by_date));
                   4464:         my $count = 0;
                   4465:         foreach my $item (@sortedtimes) {
                   4466:             if (ref($queue_by_date{$item}) eq 'ARRAY') {
                   4467:                 foreach my $request (sort(@{$queue_by_date{$item}})) {
                   4468:                     my ($puname,$pudom,$pusec) = split(/:/,$request);
                   4469:                     my $showsec = $pusec;
                   4470:                     if ($showsec eq '') {
                   4471:                         $showsec = &mt('none');
                   4472:                     }
                   4473:                     my $namelink = &Apache::loncommon::aboutmewrapper(
                   4474:                                      &Apache::loncommon::plainname($puname,$pudom),
                   4475:                                      $puname,$pudom);
                   4476:                     $r->print(&Apache::loncommon::start_data_table_row().
                   4477:                               '<td><span class="LC_nobreak"><label>'.
                   4478:                               '<input type="checkbox" value="'.$count.':'.$puname.':'.$pudom.':'.$pusec.'" name="approvereq" />'.&mt('Approve').'</label></span><br />'.
                   4479:                               '<span class="LC_nobreak"><label>'.
                   4480:                               '<input type="checkbox" value="'.$puname.':'.$pudom.'" name="rejectreq" />'.&mt('Reject').'</label></span><br /></td>'.
                   4481:                               '<td>'.$namelink.'</td>'.
                   4482:                               '<td>'.$showsec.'</td>'.
                   4483:                               '<td>'.&Apache::lonlocal::locallocaltime($item).'</td>'.
                   4484:                               &Apache::loncommon::end_data_table_row());
                   4485:                     $count ++;
                   4486:                 }
                   4487:             }
                   4488:         }
                   4489:         $r->print(&Apache::loncommon::end_data_table().
                   4490:                   '<input type="submit" name="processqueue" value="'.&mt('Save').'" /></form>');
                   4491:     } else {
                   4492:         $r->print(&mt('There are currently no enrollment requests.'));  
                   4493:     }
                   4494:     return;
                   4495: }
                   4496: 
                   4497: sub update_selfenroll_queue {
                   4498:     my ($r,$context,$permission,$cid,$cnum,$cdom) = @_;
                   4499:     my @approvals = &Apache::loncommon::get_env_multiple('form.approvereq');
                   4500:     my @rejections = &Apache::loncommon::get_env_multiple('form.rejectreq');
                   4501:     my $access_start =  $env{'course.'.$cid.'.internal.selfenroll_start_access'};
                   4502:     my $access_end =  $env{'course.'.$cid.'.internal.selfenroll_end_access'};
                   4503:     my $limit = $env{'course.'.$cid.'.internal.selfenroll_limit'}; 
                   4504:     my $cap = $env{'course.'.$cid.'.internal.selfenroll_cap'};
                   4505:     my $notifylist = $env{'course.'.$cid.'.internal.selfenroll_notifylist'};
                   4506:     my $namespace = 'selfenrollrequests';
                   4507:     my ($stucounts,$idx,$classlist) = &get_student_counts($cdom,$cnum);
                   4508:     my %requesthash = &Apache::lonnet::dump($namespace,$cdom,$cnum);
                   4509:     my $coursedesc = $env{'course.'.$cid.'.description'};
                   4510:     my $chome = &Apache::lonnet::homeserver($cnum,$cdom);
                   4511:     my $hostname = &Apache::lonnet::hostname($chome);
                   4512:     my $protocol = $Apache::lonnet::protocol{$chome};
                   4513:     $protocol = 'http' if ($protocol ne 'https');
1.280     raeburn  4514:     my (@existing,@missingreq,@invalidusers,@limitexceeded,@enrolled,
                   4515:         @enrollerrors,@warn_approves,@warn_rejects);
1.277     raeburn  4516:     my $now = time;
                   4517:     my $sender = $env{'user.name'}.':'.$env{'user.domain'};
                   4518:     my $approvedmsg = [{
                   4519:                         mt => 'Your request for enrollment has been approved.',
                   4520:                       },
                   4521:                       {
                   4522:                         mt => 'Visit [_1], to log-in and access the course',
                   4523:                         args => [$protocol.'://'.$hostname],
                   4524:                       }];
                   4525:                       
                   4526:     my $rejectedmsg =  [{
                   4527:                          mt => 'Your request for enrollment has not been approved.',
                   4528:                        }];
                   4529:     foreach my $item (sort {$a <=> $b} @approvals) {
                   4530:         my ($num,$uname,$udom,$usec) = split(/:/,$item);
                   4531:         my $uhome = &Apache::lonnet::homeserver($uname,$udom);
                   4532:         if ($uhome ne 'no_host') {
                   4533:             if (exists($requesthash{$uname.':'.$udom})) {
                   4534:                
                   4535:                 if (exists($classlist->{$uname.':'.$udom})) {
                   4536:                     if (ref($classlist->{$uname.':'.$udom}) eq 'ARRAY') {
                   4537:                         if (($classlist->{$uname.':'.$udom}->[$idx->{'status'}] eq 'Active') ||
                   4538:                             ($classlist->{$uname.':'.$udom}->[$idx->{'status'}] eq 'Future')) {
                   4539:                             push(@existing,$uname.':'.$udom);
                   4540:                             next;
                   4541:                         }
                   4542:                     }
                   4543:                 }
                   4544:             } else {
                   4545:                 push(@missingreq,$uname.':'.$udom);
                   4546:                 next;
                   4547:             }
                   4548:             if (!grep(/^\Q$item\E$/,@rejections)) {
                   4549:                 if ($limit eq 'allstudents') {
                   4550:                     if ($stucounts->{$limit} >= $cap) {
                   4551:                         push(@limitexceeded,$uname.':'.$udom);
                   4552:                         last;
                   4553:                     }
                   4554:                 } elsif ($limit eq 'selfenrolled') {
                   4555:                     if ($stucounts->{$limit} >= $cap) {
                   4556:                         push(@limitexceeded,$uname.':'.$udom);
                   4557:                         last;
                   4558:                     }
                   4559:                 }
                   4560:                 my $result = 
                   4561:                     &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$usec,$access_end,$access_start,'selfenroll',undef,$cdom.'_'.$cnum,1);
                   4562:                 if ($result eq 'ok') {
                   4563:                     push(@enrolled,$uname.':'.$udom);
                   4564:                     $stucounts->{'allstudents'} ++;
                   4565:                     $stucounts->{'selfenrolled'} ++;
                   4566:                     &Apache::selfenroll::send_notification($uname.':'.$udom,$approvedmsg,$cid,
                   4567:                                                $coursedesc,$now,'enroller',$sender);
1.280     raeburn  4568:                     my %userrequest = (
                   4569:                         $cdom.'_'.$cnum => {
                   4570:                            timestamp   => $now,
                   4571:                            section     => $usec,
                   4572:                            adjudicator => $env{'user.name'}.':'.$env{'user.domain'},
                   4573:                            status      => 'approved',
                   4574:                        }
                   4575:                     );
                   4576:                     my $userresult = 
                   4577:                         &Apache::lonnet::put($namespace,\%userrequest,$udom,$uname);
                   4578:                     if ($userresult ne 'ok') {
                   4579:                         push(@warn_approves,$uname.':'.$udom);
                   4580:                     }
1.277     raeburn  4581:                 } else {
                   4582:                     push(@enrollerrors,$uname.':'.$udom);
                   4583:                 }
                   4584:             }
                   4585:         } else {
                   4586:             push(@invalidusers,$uname.':'.$udom);
                   4587:         }
                   4588:     }
                   4589:     my @changes = (@enrolled,@rejections);
                   4590:     if (@rejections) {
                   4591:         foreach my $user (@rejections) {
                   4592:             &Apache::selfenroll::send_notification($user,$rejectedmsg,$cid,
                   4593:                                                    $coursedesc,$now,'enroller',$sender);
1.280     raeburn  4594:             my ($uname,$udom) = split(/:/,$user);
                   4595:             my %userrequest = (
                   4596:                 $cdom.'_'.$cnum => {
                   4597:                     timestamp   => $now,
                   4598:                     adjudicator => $env{'user.name'}.':'.$env{'user.domain'}, 
                   4599:                     status      => 'rejected',
                   4600:                 }
                   4601:             );
                   4602:             my $userresult = 
                   4603:                 &Apache::lonnet::put($namespace,\%userrequest,$udom,$uname);
                   4604:             if ($userresult ne 'ok') {
                   4605:                 push(@warn_rejects,$user);
                   4606:             }
1.277     raeburn  4607:         }
                   4608:     }
                   4609:     if (@changes) {
                   4610:         my $delresult = &Apache::lonnet::del($namespace,\@changes,$cdom,$cnum);
                   4611:         if ($delresult eq 'ok') {
                   4612:             my $namelink = 
                   4613:                 &Apache::loncommon::plainname($env{'user.name'},$env{'user.domain'}).' ('.$env{'user.name'}.':'.$env{'user.domain'}.')';
                   4614:             my $chgmsg = "'Action was taken on the following enrollment requests by [_1].',$namelink";
                   4615:             my ($approvedlist,$rejectedlist);
1.279     raeburn  4616:             if (@enrolled) {
1.277     raeburn  4617:                 $approvedlist = join("\n",@enrolled);
                   4618:                 $r->print('<p>'.&mt('The following were enrolled in the course:').'<ul>');
                   4619:                 foreach my $user (@enrolled) {
                   4620:                     my ($uname,$udom) = split(/:/,$user); 
                   4621:                     my $userlink = 
                   4622:                         &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom);
                   4623:                     $r->print('<li>'.$userlink.'</li>');
                   4624:                 }
                   4625:                 $r->print('</ul></p>');
                   4626:             }
                   4627:             if (@rejections) {
                   4628:                 $rejectedlist = join("\n",@rejections);
                   4629:                 $r->print('<p>'.&mt('The following enrollment requests were rejected:').'<ul>');
                   4630:                 foreach my $user (@rejections) {
                   4631:                     $r->print('<li>'.$user.'</li>');
                   4632:                 }
                   4633:                 $r->print('</ul></p>');
                   4634:             }
                   4635:             &Apache::selfenroll::send_notification($notifylist,$chgmsg,$cid,
                   4636:                                                    $coursedesc,$now,'managers',
                   4637:                                                    $sender,$approvedlist,$rejectedlist);
                   4638:         }
                   4639:     }
                   4640:     if (@existing) {
                   4641:         $r->print('<p>'.&mt('The following enrollment requests were deleted because the user is already enrolled in the course:').'<ul>');
                   4642:         foreach my $user (@existing) {
                   4643:             $r->print('<li>'.$user.'</li>');
                   4644:         }
                   4645:         $r->print('</ul></p>');
                   4646:     }
                   4647:     if (@missingreq) {
                   4648:         $r->print('<p>'.&mt('The following enrollment requests were ignored because the request is no longer in the enrollment queue:').'<ul>');
                   4649:         foreach my $user (@missingreq) {
                   4650:             $r->print('<li>'.$user.'</li>');
                   4651:         }
                   4652:         $r->print('</ul></p>');
                   4653:     }
                   4654:     if (@invalidusers) {
                   4655:         $r->print('<p>'.&mt('The following enrollment requests were deleted because the requestor does not have a LON-CAPA account:').'<ul>');
                   4656:         foreach my $user (@invalidusers) {
                   4657:             $r->print('<li>'.$user.'</li>');
                   4658:         }
                   4659:         $r->print('</ul></p>');
                   4660:     }
                   4661:     if (@limitexceeded) {
                   4662:         $r->print('<p>'.&mt('The following enrollment requests were skipped because the enrollment limit has been reached for the course:').'<ul>');
                   4663:         foreach my $user (@limitexceeded) {
                   4664:             $r->print('<li>'.$user.'</li>');
                   4665:         }
                   4666:         $r->print('</ul></p>');
                   4667:     }
                   4668:     if (@enrollerrors) {
                   4669:         $r->print('<p>'.&mt('The following enrollment requests could not be processed because an error occurred:').'<ul>');
                   4670:         foreach my $user (@enrollerrors) {
                   4671:             $r->print('<li>'.$user.'</li>');
                   4672:         }
                   4673:         $r->print('</ul></p>');
                   4674:     }
1.280     raeburn  4675:     if (@warn_approves) {
                   4676:         $r->print('<p>'.&mt("For the following users, an error occurred when updating the user's own self-enroll requests record:").'<ul>');
                   4677:         foreach my $user (@warn_approves) {
                   4678:             $r->print('<li>'.$user.'</li>');
                   4679:         }
                   4680:         $r->print('</ul></p>');
                   4681:     }
                   4682:     if (@warn_rejects) {
                   4683:         $r->print('<p>'.&mt("For the following users, an error occurred when updating the user's own self-enroll requests record:").'<ul>');
                   4684:         foreach my $user (@warn_rejects) {
                   4685:             $r->print('<li>'.$user.'</li>');
                   4686:         }
                   4687:         $r->print('</ul></p>');
                   4688:     }
1.277     raeburn  4689:     return;
                   4690: }
                   4691: 
                   4692: sub get_student_counts {
                   4693:     my ($cdom,$cnum) = @_;
                   4694:     my (%idx,%stucounts);
                   4695:     my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cnum);
                   4696:     $idx{'type'} = &Apache::loncoursedata::CL_TYPE();
                   4697:     $idx{'status'} = &Apache::loncoursedata::CL_STATUS();
                   4698:     while (my ($student,$data) = each(%$classlist)) {
                   4699:         if (($data->[$idx{'status'}] eq 'Active') ||
                   4700:             ($data->[$idx{'status'}] eq 'Future')) {
                   4701:             if ($data->[$idx{'type'}] eq 'selfenroll') {
                   4702:                 $stucounts{'selfenroll'} ++;
                   4703:             }
                   4704:             $stucounts{'allstudents'} ++;
                   4705:         }
                   4706:     }
                   4707:     return (\%stucounts,\%idx,$classlist);
                   4708: }
                   4709: 
1.256     raeburn  4710: sub visible_in_cat {
                   4711:     my ($cdom,$cnum) = @_;
                   4712:     my %domconf = &Apache::lonnet::get_dom('configuration',['coursecategories'],$cdom);
                   4713:     my ($cathash,%settable,@vismsgs,$cansetvis);
                   4714:     my %visactions = &Apache::lonlocal::texthash(
                   4715:                    vis => 'Your course currently appears in the Course Catalog for this domain.',
                   4716:                    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.',
                   4717:                    miss => 'Your course does not currently appear in the Course Catalog for this domain.',
                   4718:                    yous => 'You should remedy this if you plan to allow self-enrollment, otherwise students will have difficulty finding your course.',
                   4719:                    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.',
1.282     schafran 4720:                    make => 'Make any changes to self-enrollment settings below, click "Save", then take action to include the course in the Catalog:',
1.256     raeburn  4721:                    take => 'Take the following action to ensure the course appears in the Catalog:',
                   4722:                    dc_unhide  => 'Ask a domain coordinator to change the "Exclude from course catalog" setting.',
                   4723:                    dc_addinst => 'Ask a domain coordinator to enable display the catalog of "Official courses (with institutional codes)".',
                   4724:                    dc_instcode => 'Ask a domain coordinator to assign an institutional code (if this is an official course).',
                   4725:                    dc_catalog  => 'Ask a domain coordinator to enable or create at least one course category in the domain.',
                   4726:                    dc_categories => 'Ask a domain coordinator to create a hierarchy of categories and sub categories for courses in the domain.',
                   4727:                    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',
                   4728:                    dc_addcat => 'Ask a domain coordinator to assign a category to the course.',
                   4729:     );
1.261     raeburn  4730:     $visactions{'unhide'} = &mt('Use [_1]Set course environment[_2] to change the "Exclude from course catalog" setting.','"<a href="/adm/parmset?action=crsenv">','</a>"');
                   4731:     $visactions{'chgcat'} = &mt('Use [_1]Set course environment[_2] to change the category assigned to the course, as the one currently assigned is no longer used in the domain.','"<a href="/adm/parmset?action=crsenv">','</a>"');
                   4732:     $visactions{'addcat'} = &mt('Use [_1]Set course environment[_2] to assign a category to the course.','"<a href="/adm/parmset?action=crsenv">','</a>"');
1.256     raeburn  4733:     if (ref($domconf{'coursecategories'}) eq 'HASH') {
                   4734:         if ($domconf{'coursecategories'}{'togglecats'} eq 'crs') {
                   4735:             $settable{'togglecats'} = 1;
                   4736:         }
                   4737:         if ($domconf{'coursecategories'}{'categorize'} eq 'crs') {
                   4738:             $settable{'categorize'} = 1;
                   4739:         }
                   4740:         $cathash = $domconf{'coursecategories'}{'cats'};
                   4741:     }
1.260     raeburn  4742:     if ($settable{'togglecats'} && $settable{'categorize'}) {
1.256     raeburn  4743:         $cansetvis = &mt('You are able to both assign a course category and choose to exclude this course from the catalog.');   
                   4744:     } elsif ($settable{'togglecats'}) {
                   4745:         $cansetvis = &mt('You are able to choose to exclude this course from the catalog, but only a Domain Coordinator may assign a course category.'); 
1.260     raeburn  4746:     } elsif ($settable{'categorize'}) {
1.256     raeburn  4747:         $cansetvis = &mt('You may assign a course category, but only a Domain Coordinator may choose to exclude this course from the catalog.');  
                   4748:     } else {
                   4749:         $cansetvis = &mt('Only a Domain Coordinator may assign a course category or choose to exclude this course from the catalog.'); 
                   4750:     }
                   4751:      
                   4752:     my %currsettings =
                   4753:         &Apache::lonnet::get('environment',['hidefromcat','categories','internal.coursecode'],
                   4754:                              $cdom,$cnum);
                   4755:     my $visible = 0;
                   4756:     if ($currsettings{'internal.coursecode'} ne '') {
                   4757:         if (ref($domconf{'coursecategories'}) eq 'HASH') {
                   4758:             $cathash = $domconf{'coursecategories'}{'cats'};
                   4759:             if (ref($cathash) eq 'HASH') {
                   4760:                 if ($cathash->{'instcode::0'} eq '') {
                   4761:                     push(@vismsgs,'dc_addinst'); 
                   4762:                 } else {
                   4763:                     $visible = 1;
                   4764:                 }
                   4765:             } else {
                   4766:                 $visible = 1;
                   4767:             }
                   4768:         } else {
                   4769:             $visible = 1;
                   4770:         }
                   4771:     } else {
                   4772:         if (ref($cathash) eq 'HASH') {
                   4773:             if ($cathash->{'instcode::0'} ne '') {
                   4774:                 push(@vismsgs,'dc_instcode');
                   4775:             }
                   4776:         } else {
                   4777:             push(@vismsgs,'dc_instcode');
                   4778:         }
                   4779:     }
                   4780:     if ($currsettings{'categories'} ne '') {
                   4781:         my $cathash;
                   4782:         if (ref($domconf{'coursecategories'}) eq 'HASH') {
                   4783:             $cathash = $domconf{'coursecategories'}{'cats'};
                   4784:             if (ref($cathash) eq 'HASH') {
                   4785:                 if (keys(%{$cathash}) == 0) {
                   4786:                     push(@vismsgs,'dc_catalog');
                   4787:                 } elsif ((keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} ne '')) {
                   4788:                     push(@vismsgs,'dc_categories');
                   4789:                 } else {
                   4790:                     my @currcategories = split('&',$currsettings{'categories'});
                   4791:                     my $matched = 0;
                   4792:                     foreach my $cat (@currcategories) {
                   4793:                         if ($cathash->{$cat} ne '') {
                   4794:                             $visible = 1;
                   4795:                             $matched = 1;
                   4796:                             last;
                   4797:                         }
                   4798:                     }
                   4799:                     if (!$matched) {
1.260     raeburn  4800:                         if ($settable{'categorize'}) { 
1.256     raeburn  4801:                             push(@vismsgs,'chgcat');
                   4802:                         } else {
                   4803:                             push(@vismsgs,'dc_chgcat');
                   4804:                         }
                   4805:                     }
                   4806:                 }
                   4807:             }
                   4808:         }
                   4809:     } else {
                   4810:         if (ref($cathash) eq 'HASH') {
                   4811:             if ((keys(%{$cathash}) > 1) || 
                   4812:                 (keys(%{$cathash}) == 1) && ($cathash->{'instcode::0'} eq '')) {
1.260     raeburn  4813:                 if ($settable{'categorize'}) {
1.256     raeburn  4814:                     push(@vismsgs,'addcat');
                   4815:                 } else {
                   4816:                     push(@vismsgs,'dc_addcat');
                   4817:                 }
                   4818:             }
                   4819:         }
                   4820:     }
                   4821:     if ($currsettings{'hidefromcat'} eq 'yes') {
                   4822:         $visible = 0;
                   4823:         if ($settable{'togglecats'}) {
                   4824:             unshift(@vismsgs,'unhide');
                   4825:         } else {
                   4826:             unshift(@vismsgs,'dc_unhide')
                   4827:         }
                   4828:     }
                   4829:     return ($visible,$cansetvis,\@vismsgs,\%visactions);
                   4830: }
                   4831: 
1.241     raeburn  4832: sub new_selfenroll_dom_row {
                   4833:     my ($newdom,$num) = @_;
                   4834:     my $domdesc = &Apache::lonnet::domain($newdom);
                   4835:     my $output;
                   4836:     if ($domdesc ne '') {
                   4837:         $output .= &Apache::loncommon::start_data_table_row()
                   4838:                    .'<td valign="top"><span class="LC_nobreak">'.&mt('Domain:').'&nbsp;<b>'.$domdesc
                   4839:                    .' ('.$newdom.')</b><input type="hidden" name="selfenroll_dom_'.$num
1.249     raeburn  4840:                    .'" value="'.$newdom.'" /></span><br />'
                   4841:                    .'<span class="LC_nobreak"><label><input type="checkbox" '
                   4842:                    .'name="selfenroll_activate" value="'.$num.'" '
                   4843:                    .'onchange="javascript:update_types('
                   4844:                    ."'selfenroll_activate','$num'".');" />'
                   4845:                    .&mt('Activate').'</label></span></td>';
1.241     raeburn  4846:         my @currinsttypes;
                   4847:         $output .= '<td>'.&mt('User types:').'<br />'
                   4848:                    .&selfenroll_inst_types($num,$newdom,\@currinsttypes).'</td>'
                   4849:                    .&Apache::loncommon::end_data_table_row();
                   4850:     }
                   4851:     return $output;
                   4852: }
                   4853: 
                   4854: sub selfenroll_inst_types {
                   4855:     my ($num,$currdom,$currinsttypes) = @_;
                   4856:     my $output;
                   4857:     my $numinrow = 4;
                   4858:     my $count = 0;
                   4859:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($currdom);
1.247     raeburn  4860:     my $othervalue = 'any';
1.241     raeburn  4861:     if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
1.251     raeburn  4862:         if (keys(%{$usertypes}) > 0) {
1.247     raeburn  4863:             $othervalue = 'other';
                   4864:         }
1.241     raeburn  4865:         $output .= '<table><tr>';
                   4866:         foreach my $type (@{$types}) {
                   4867:             if (($count > 0) && ($count%$numinrow == 0)) {
                   4868:                 $output .= '</tr><tr>';
                   4869:             }
                   4870:             if (defined($usertypes->{$type})) {
1.257     raeburn  4871:                 my $esc_type = &escape($type);
1.241     raeburn  4872:                 $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.
1.257     raeburn  4873:                            $esc_type.'" ';
1.241     raeburn  4874:                 if (ref($currinsttypes) eq 'ARRAY') {
                   4875:                     if (@{$currinsttypes} > 0) {
1.249     raeburn  4876:                         if (grep(/^any$/,@{$currinsttypes})) {
                   4877:                             $output .= 'checked="checked"';
1.257     raeburn  4878:                         } elsif (grep(/^\Q$esc_type\E$/,@{$currinsttypes})) {
1.241     raeburn  4879:                             $output .= 'checked="checked"';
                   4880:                         }
1.249     raeburn  4881:                     } else {
                   4882:                         $output .= 'checked="checked"';
1.241     raeburn  4883:                     }
                   4884:                 }
                   4885:                 $output .= ' name="selfenroll_types_'.$num.'" />'.$usertypes->{$type}.'</label></span></td>';
                   4886:             }
                   4887:             $count ++;
                   4888:         }
                   4889:         if (($count > 0) && ($count%$numinrow == 0)) {
                   4890:             $output .= '</tr><tr>';
                   4891:         }
1.249     raeburn  4892:         $output .= '<td><span class="LC_nobreak"><label><input type = "checkbox" value="'.$othervalue.'"';
1.241     raeburn  4893:         if (ref($currinsttypes) eq 'ARRAY') {
                   4894:             if (@{$currinsttypes} > 0) {
1.249     raeburn  4895:                 if (grep(/^any$/,@{$currinsttypes})) { 
                   4896:                     $output .= ' checked="checked"';
                   4897:                 } elsif ($othervalue eq 'other') {
                   4898:                     if (grep(/^\Q$othervalue\E$/,@{$currinsttypes})) {
                   4899:                         $output .= ' checked="checked"';
                   4900:                     }
1.241     raeburn  4901:                 }
1.249     raeburn  4902:             } else {
                   4903:                 $output .= ' checked="checked"';
1.241     raeburn  4904:             }
1.249     raeburn  4905:         } else {
                   4906:             $output .= ' checked="checked"';
1.241     raeburn  4907:         }
                   4908:         $output .= ' name="selfenroll_types_'.$num.'" />'.$othertitle.'</label></span></td></tr></table>';
                   4909:     }
                   4910:     return $output;
                   4911: }
                   4912: 
1.237     raeburn  4913: sub selfenroll_date_forms {
                   4914:     my ($startform,$endform) = @_;
                   4915:     my $output .= &Apache::lonhtmlcommon::start_pick_box()."\n".
1.244     bisitz   4916:                   &Apache::lonhtmlcommon::row_title(&mt('Start date'),
1.237     raeburn  4917:                                                     'LC_oddrow_value')."\n".
                   4918:                   $startform."\n".
                   4919:                   &Apache::lonhtmlcommon::row_closure(1).
1.244     bisitz   4920:                   &Apache::lonhtmlcommon::row_title(&mt('End date'),
1.237     raeburn  4921:                                                    'LC_oddrow_value')."\n".
                   4922:                   $endform."\n".
                   4923:                   &Apache::lonhtmlcommon::row_closure(1).
                   4924:                   &Apache::lonhtmlcommon::end_pick_box();
                   4925:     return $output;
                   4926: }
                   4927: 
1.239     raeburn  4928: sub print_userchangelogs_display {
                   4929:     my ($r,$context,$permission) = @_;
                   4930:     my $formname = 'roleslog';
                   4931:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4932:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4933:     my %roleslog=&Apache::lonnet::dump('nohist_rolelog',$cdom,$cnum);
                   4934:     if ((keys(%roleslog))[0]=~/^error\:/) { undef(%roleslog); }
                   4935: 
                   4936:     $r->print('<form action="/adm/createuser" method="post" name="'.$formname.'">');
                   4937:     my %saveable_parameters = ('show' => 'scalar',);
                   4938:     &Apache::loncommon::store_course_settings('roles_log',
                   4939:                                               \%saveable_parameters);
                   4940:     &Apache::loncommon::restore_course_settings('roles_log',
                   4941:                                                 \%saveable_parameters);
                   4942:     # set defaults
                   4943:     my $now = time();
                   4944:     my $defstart = $now - (7*24*3600); #7 days ago 
                   4945:     my %defaults = (
                   4946:                      page               => '1',
                   4947:                      show               => '10',
                   4948:                      role               => 'any',
                   4949:                      chgcontext         => 'any',
                   4950:                      rolelog_start_date => $defstart,
                   4951:                      rolelog_end_date   => $now,
                   4952:                    );
                   4953:     my $more_records = 0;
                   4954: 
                   4955:     # set current
                   4956:     my %curr;
                   4957:     foreach my $item ('show','page','role','chgcontext') {
                   4958:         $curr{$item} = $env{'form.'.$item};
                   4959:     }
                   4960:     my ($startdate,$enddate) = 
                   4961:         &Apache::lonuserutils::get_dates_from_form('rolelog_start_date','rolelog_end_date');
                   4962:     $curr{'rolelog_start_date'} = $startdate;
                   4963:     $curr{'rolelog_end_date'} = $enddate;
                   4964:     foreach my $key (keys(%defaults)) {
                   4965:         if ($curr{$key} eq '') {
                   4966:             $curr{$key} = $defaults{$key};
                   4967:         }
                   4968:     }
1.248     raeburn  4969:     my (%whodunit,%changed,$version);
                   4970:     ($version) = ($r->dir_config('lonVersion') =~ /^([\d\.]+)\-/);
                   4971:     $r->print(&role_display_filter($formname,$cdom,$cnum,\%curr,$version));
1.239     raeburn  4972:     my $showntablehdr = 0;
                   4973:     my $tablehdr = &Apache::loncommon::start_data_table().
                   4974:                    &Apache::loncommon::start_data_table_header_row().
                   4975:                    '<th>&nbsp;</th><th>'.&mt('When').'</th><th>'.&mt('Who made the change').
                   4976:                    '</th><th>'.&mt('Changed User').'</th><th>'.&mt('Role').'</th><th>'.&mt('Section').'</th><th>'.
                   4977:                    &mt('Context').'</th><th>'.&mt('Start').'</th><th>'.&mt('End').'</th>'.
                   4978:                    &Apache::loncommon::end_data_table_header_row();
                   4979:     my ($minshown,$maxshown);
1.255     raeburn  4980:     $minshown = 1;
1.239     raeburn  4981:     my $count = 0;
                   4982:     if ($curr{'show'} ne &mt('all')) { 
                   4983:         $maxshown = $curr{'page'} * $curr{'show'};
                   4984:         if ($curr{'page'} > 1) {
                   4985:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
                   4986:         }
                   4987:     }
                   4988:     foreach my $id (sort { $roleslog{$b}{'exe_time'}<=>$roleslog{$a}{'exe_time'} } (keys(%roleslog))) {
                   4989:         next if (($roleslog{$id}{'exe_time'} < $curr{'rolelog_start_date'}) ||
                   4990:                  ($roleslog{$id}{'exe_time'} > $curr{'rolelog_end_date'}));
                   4991:         if ($curr{'show'} ne &mt('all')) {
                   4992:             if ($count >= $curr{'page'} * $curr{'show'}) {
                   4993:                 $more_records = 1;
                   4994:                 last;
                   4995:             }
                   4996:         }
                   4997:         if ($curr{'role'} ne 'any') {
                   4998:             next if ($roleslog{$id}{'logentry'}{'role'} ne $curr{'role'}); 
                   4999:         }
                   5000:         if ($curr{'chgcontext'} ne 'any') {
                   5001:             if ($curr{'chgcontext'} eq 'selfenroll') {
                   5002:                 next if (!$roleslog{$id}{'logentry'}{'selfenroll'});
                   5003:             } else {
                   5004:                 next if ($roleslog{$id}{'logentry'}{'context'} ne $curr{'chgcontext'});
                   5005:             }
                   5006:         }
                   5007:         $count ++;
                   5008:         next if ($count < $minshown);
                   5009:         if (!$showntablehdr) {
                   5010:             $r->print($tablehdr);
                   5011:             $showntablehdr = 1;
                   5012:         }
                   5013:         if ($whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} eq '') {
                   5014:             $whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}} =
                   5015:                 &Apache::loncommon::plainname($roleslog{$id}{'exe_uname'},$roleslog{$id}{'exe_udom'});
                   5016:         }
                   5017:         if ($changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} eq '') {
                   5018:             $changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}} =
                   5019:                 &Apache::loncommon::plainname($roleslog{$id}{'uname'},$roleslog{$id}{'udom'});
                   5020:         }
                   5021:         my $sec = $roleslog{$id}{'logentry'}{'section'};
                   5022:         if ($sec eq '') {
                   5023:             $sec = &mt('None');
                   5024:         }
                   5025:         my ($rolestart,$roleend);
                   5026:         if ($roleslog{$id}{'delflag'}) {
                   5027:             $rolestart = &mt('deleted');
                   5028:             $roleend = &mt('deleted');
                   5029:         } else {
                   5030:             $rolestart = $roleslog{$id}{'logentry'}{'start'};
                   5031:             $roleend = $roleslog{$id}{'logentry'}{'end'};
                   5032:             if ($rolestart eq '' || $rolestart == 0) {
                   5033:                 $rolestart = &mt('No start date'); 
                   5034:             } else {
                   5035:                 $rolestart = &Apache::lonlocal::locallocaltime($rolestart);
                   5036:             }
                   5037:             if ($roleend eq '' || $roleend == 0) { 
                   5038:                 $roleend = &mt('No end date');
                   5039:             } else {
                   5040:                 $roleend = &Apache::lonlocal::locallocaltime($roleend);
                   5041:             }
                   5042:         }
                   5043:         my $chgcontext = $roleslog{$id}{'logentry'}{'context'};
                   5044:         if ($roleslog{$id}{'logentry'}{'selfenroll'}) {
                   5045:             $chgcontext = 'selfenroll';
                   5046:         }
                   5047:         my %lt = &rolechg_contexts();
                   5048:         if ($chgcontext ne '' && $lt{$chgcontext} ne '') {
                   5049:             $chgcontext = $lt{$chgcontext};
                   5050:         }
                   5051:         $r->print(&Apache::loncommon::start_data_table_row().'<td>'.$count.'</td><td>'.&Apache::lonlocal::locallocaltime($roleslog{$id}{'exe_time'}).'</td><td>'.$whodunit{$roleslog{$id}{'exe_uname'}.':'.$roleslog{$id}{'exe_udom'}}.'</td><td>'.$changed{$roleslog{$id}{'uname'}.':'.$roleslog{$id}{'udom'}}.'</td><td>'.&Apache::lonnet::plaintext($roleslog{$id}{'logentry'}{'role'}).'</td><td>'.$sec.'</td><td>'.$chgcontext.'</td><td>'.$rolestart.'</td><td>'.$roleend.'</td>'.&Apache::loncommon::end_data_table_row()."\n");
                   5052:     }
                   5053:     if ($showntablehdr) {
                   5054:         $r->print(&Apache::loncommon::end_data_table().'<br />');
                   5055:         if (($curr{'page'} > 1) || ($more_records)) {
                   5056:             $r->print('<table><tr>');
                   5057:             if ($curr{'page'} > 1) {
                   5058:                 $r->print('<td><a href="javascript:chgPage('."'previous'".');">'.&mt('Previous [_1] changes',$curr{'show'}).'</a></td>');
                   5059:             }
                   5060:             if ($more_records) {
                   5061:                 $r->print('<td><a href="javascript:chgPage('."'next'".');">'.&mt('Next [_1] changes',$curr{'show'}).'</a></td>');
                   5062:             }
                   5063:             $r->print('</tr></table>');
                   5064:             $r->print(<<"ENDSCRIPT");
                   5065: <script type="text/javascript">
                   5066: function chgPage(caller) {
                   5067:     if (caller == 'previous') {
                   5068:         document.$formname.page.value --;
                   5069:     }
                   5070:     if (caller == 'next') {
                   5071:         document.$formname.page.value ++;
                   5072:     }
                   5073:     document.$formname.submit(); 
                   5074:     return;
                   5075: }
                   5076: </script>
                   5077: ENDSCRIPT
                   5078:         }
                   5079:     } else {
                   5080:         $r->print(&mt('There are no records to display'));
                   5081:     }
                   5082:     $r->print('<input type="hidden" name="page" value="'.$curr{'page'}.'" />'.
                   5083:               '<input type="hidden" name="action" value="changelogs" /></form>');
                   5084:     return;
                   5085: }
                   5086: 
                   5087: sub role_display_filter {
1.248     raeburn  5088:     my ($formname,$cdom,$cnum,$curr,$version) = @_;
1.239     raeburn  5089:     my $context = 'course';
                   5090:     my $nolink = 1;
                   5091:     my $output = '<table><tr><td valign="top">'.
                   5092:                  '<span class="LC_nobreak"><b>'.&mt('Changes/page:').'</b><br />'.
                   5093:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},undef,
                   5094:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
                   5095:                  '</td><td>&nbsp;&nbsp;</td>';
                   5096:     my $startform =
                   5097:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_start_date',
                   5098:                                             $curr->{'rolelog_start_date'},undef,
                   5099:                                             undef,undef,undef,undef,undef,undef,$nolink);
                   5100:     my $endform =
                   5101:         &Apache::lonhtmlcommon::date_setter($formname,'rolelog_end_date',
                   5102:                                             $curr->{'rolelog_end_date'},undef,
                   5103:                                             undef,undef,undef,undef,undef,undef,$nolink);
                   5104:     my %lt = &rolechg_contexts();
                   5105:     $output .= '<td valign="top"><b>'.&mt('Window during which changes occurred:').'</b><br /><table><tr><td>'.&mt('After:').
                   5106:                '</td><td>'.$startform.'</td></tr><tr><td>'.&mt('Before:').'</td><td>'.
                   5107:                $endform.'</td></tr></table></td><td>&nbsp;&nbsp;</td>'.
                   5108:                '<td valign="top"><b>'.&mt('Role:').'</b><br />'.
                   5109:                '<select name="role"><option value="any"';
                   5110:     if ($curr->{'role'} eq 'any') {
                   5111:         $output .= ' selected="selected"';
                   5112:     }
                   5113:     $output .=  '>'.&mt('Any').'</option>'."\n";
                   5114:     my @roles = &Apache::lonuserutils::course_roles($context,undef,1);
                   5115:     foreach my $role (@roles) {
                   5116:         my $plrole;
                   5117:         if ($role eq 'cr') {
                   5118:             $plrole = &mt('Custom Role');
                   5119:         } else {
                   5120:             $plrole=&Apache::lonnet::plaintext($role);
                   5121:         }
                   5122:         my $selstr = '';
                   5123:         if ($role eq $curr->{'role'}) {
                   5124:             $selstr = ' selected="selected"';
                   5125:         }
                   5126:         $output .= '  <option value="'.$role.'"'.$selstr.'>'.$plrole.'</option>';
                   5127:     }
                   5128:     $output .= '</select></td><td>&nbsp;&nbsp;</td><td valign="top"><b>'.
                   5129:                &mt('Context:').'</b><br /><select name="chgcontext">';
                   5130:     foreach my $chgtype ('any','auto','updatenow','createcourse','course','domain','selfenroll') {
                   5131:         my $selstr = '';
                   5132:         if ($curr->{'chgcontext'} eq $chgtype) {
                   5133:             $output .= $selstr = ' selected="selected"';
                   5134:         }
                   5135:         if (($chgtype eq 'auto') || ($chgtype eq 'updatenow')) {
                   5136:             next if (!&Apache::lonnet::auto_run($cnum,$cdom));
                   5137:         }
                   5138:         $output .= '<option value="'.$chgtype.'"'.$selstr.'>'.$lt{$chgtype}.'</option>'."\n";
1.248     raeburn  5139:     }
1.239     raeburn  5140:     $output .= '</select></td><td>&nbsp;&nbsp;</td><td valign="middle"><input type="submit" value="'.
1.248     raeburn  5141:                &mt('Update Display').'" /></tr></table>'.
                   5142:                '<span class="LC_roleslog_note">'.
                   5143:                &mt('[_1]Note:[_2] Only changes made from servers running LON-CAPA 2.6.99.0 or later are displayed.');
                   5144:     if ($version) {
                   5145:         $output .= ' '.&mt('This server is version [_3].','<b>','</b>',$version);    }
1.295.2.3! raeburn  5146:     $output .= '</span><hr /><br />';
1.239     raeburn  5147:     return $output;
                   5148: }
                   5149: 
                   5150: sub rolechg_contexts {
                   5151:     my %lt = &Apache::lonlocal::texthash (
                   5152:                                              any          => 'Any',
                   5153:                                              auto         => 'Automated enrollment',
                   5154:                                              updatenow    => 'Roster Update',
                   5155:                                              createcourse => 'Course Creation',
                   5156:                                              course       => 'User Management in course',
                   5157:                                              domain       => 'User Management in domain',
                   5158:                                              selfenroll   => 'Self-enrolled', 
                   5159:                                          );
                   5160:     return %lt;
                   5161: }
                   5162: 
1.27      matthew  5163: #-------------------------------------------------- functions for &phase_two
1.160     raeburn  5164: sub user_search_result {
1.221     raeburn  5165:     my ($context,$srch) = @_;
1.160     raeburn  5166:     my %allhomes;
                   5167:     my %inst_matches;
                   5168:     my %srch_results;
1.181     raeburn  5169:     my ($response,$currstate,$forcenewuser,$dirsrchres);
1.183     raeburn  5170:     $srch->{'srchterm'} =~ s/\s+/ /g;
1.176     raeburn  5171:     if ($srch->{'srchby'} !~ /^(uname|lastname|lastfirst)$/) {
1.160     raeburn  5172:         $response = &mt('Invalid search.');
                   5173:     }
                   5174:     if ($srch->{'srchin'} !~ /^(crs|dom|alc|instd)$/) {
                   5175:         $response = &mt('Invalid search.');
                   5176:     }
1.177     raeburn  5177:     if ($srch->{'srchtype'} !~ /^(exact|contains|begins)$/) {
1.160     raeburn  5178:         $response = &mt('Invalid search.');
                   5179:     }
                   5180:     if ($srch->{'srchterm'} eq '') {
                   5181:         $response = &mt('You must enter a search term.');
                   5182:     }
1.183     raeburn  5183:     if ($srch->{'srchterm'} =~ /^\s+$/) {
                   5184:         $response = &mt('Your search term must contain more than just spaces.');
                   5185:     }
1.160     raeburn  5186:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'instd')) {
                   5187:         if (($srch->{'srchdomain'} eq '') || 
1.163     albertel 5188: 	    ! (&Apache::lonnet::domain($srch->{'srchdomain'}))) {
1.160     raeburn  5189:             $response = &mt('You must specify a valid domain when searching in a domain or institutional directory.')
                   5190:         }
                   5191:     }
                   5192:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs') ||
                   5193:         ($srch->{'srchin'} eq 'alc')) {
1.176     raeburn  5194:         if ($srch->{'srchby'} eq 'uname') {
1.243     raeburn  5195:             my $unamecheck = $srch->{'srchterm'};
                   5196:             if ($srch->{'srchtype'} eq 'contains') {
                   5197:                 if ($unamecheck !~ /^\w/) {
                   5198:                     $unamecheck = 'a'.$unamecheck; 
                   5199:                 }
                   5200:             }
                   5201:             if ($unamecheck !~ /^$match_username$/) {
1.176     raeburn  5202:                 $response = &mt('You must specify a valid username. Only the following are allowed: letters numbers - . @');
                   5203:             }
1.160     raeburn  5204:         }
                   5205:     }
1.180     raeburn  5206:     if ($response ne '') {
                   5207:         $response = '<span class="LC_warning">'.$response.'</span>';
                   5208:     }
1.160     raeburn  5209:     if ($srch->{'srchin'} eq 'instd') {
                   5210:         my $instd_chk = &directorysrch_check($srch);
                   5211:         if ($instd_chk ne 'ok') {
1.180     raeburn  5212:             $response = '<span class="LC_warning">'.$instd_chk.'</span>'.
                   5213:                         '<br />'.&mt('You may want to search in the LON-CAPA domain instead of the institutional directory.').'<br /><br />';
1.160     raeburn  5214:         }
                   5215:     }
                   5216:     if ($response ne '') {
1.180     raeburn  5217:         return ($currstate,$response);
1.160     raeburn  5218:     }
                   5219:     if ($srch->{'srchby'} eq 'uname') {
                   5220:         if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs')) {
                   5221:             if ($env{'form.forcenew'}) {
                   5222:                 if ($srch->{'srchdomain'} ne $env{'request.role.domain'}) {
                   5223:                     my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
                   5224:                     if ($uhome eq 'no_host') {
                   5225:                         my $domdesc = &Apache::lonnet::domain($env{'request.role.domain'},'description');
1.180     raeburn  5226:                         my $showdom = &display_domain_info($env{'request.role.domain'});
                   5227:                         $response = &mt('New users can only be created in the domain to which your current role belongs - [_1].',$showdom);
1.160     raeburn  5228:                     } else {
1.179     raeburn  5229:                         $currstate = 'modify';
1.160     raeburn  5230:                     }
                   5231:                 } else {
1.179     raeburn  5232:                     $currstate = 'modify';
1.160     raeburn  5233:                 }
                   5234:             } else {
                   5235:                 if ($srch->{'srchin'} eq 'dom') {
1.162     raeburn  5236:                     if ($srch->{'srchtype'} eq 'exact') {
                   5237:                         my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
                   5238:                         if ($uhome eq 'no_host') {
1.179     raeburn  5239:                             ($currstate,$response,$forcenewuser) =
1.221     raeburn  5240:                                 &build_search_response($context,$srch,%srch_results);
1.162     raeburn  5241:                         } else {
1.179     raeburn  5242:                             $currstate = 'modify';
1.162     raeburn  5243:                         }
                   5244:                     } else {
                   5245:                         %srch_results = &Apache::lonnet::usersearch($srch);
1.179     raeburn  5246:                         ($currstate,$response,$forcenewuser) =
1.221     raeburn  5247:                             &build_search_response($context,$srch,%srch_results);
1.160     raeburn  5248:                     }
                   5249:                 } else {
1.167     albertel 5250:                     my $courseusers = &get_courseusers();
1.162     raeburn  5251:                     if ($srch->{'srchtype'} eq 'exact') {
1.167     albertel 5252:                         if (exists($courseusers->{$srch->{'srchterm'}.':'.$srch->{'srchdomain'}})) {
1.179     raeburn  5253:                             $currstate = 'modify';
1.162     raeburn  5254:                         } else {
1.179     raeburn  5255:                             ($currstate,$response,$forcenewuser) =
1.221     raeburn  5256:                                 &build_search_response($context,$srch,%srch_results);
1.162     raeburn  5257:                         }
1.160     raeburn  5258:                     } else {
1.167     albertel 5259:                         foreach my $user (keys(%$courseusers)) {
1.162     raeburn  5260:                             my ($cuname,$cudomain) = split(/:/,$user);
                   5261:                             if ($cudomain eq $srch->{'srchdomain'}) {
1.177     raeburn  5262:                                 my $matched = 0;
                   5263:                                 if ($srch->{'srchtype'} eq 'begins') {
                   5264:                                     if ($cuname =~ /^\Q$srch->{'srchterm'}\E/i) {
                   5265:                                         $matched = 1;
                   5266:                                     }
                   5267:                                 } else {
                   5268:                                     if ($cuname =~ /\Q$srch->{'srchterm'}\E/i) {
                   5269:                                         $matched = 1;
                   5270:                                     }
                   5271:                                 }
                   5272:                                 if ($matched) {
1.167     albertel 5273:                                     $srch_results{$user} = 
                   5274: 					{&Apache::lonnet::get('environment',
                   5275: 							     ['firstname',
                   5276: 							      'lastname',
1.194     albertel 5277: 							      'permanentemail'],
                   5278: 							      $cudomain,$cuname)};
1.162     raeburn  5279:                                 }
                   5280:                             }
                   5281:                         }
1.179     raeburn  5282:                         ($currstate,$response,$forcenewuser) =
1.221     raeburn  5283:                             &build_search_response($context,$srch,%srch_results);
1.160     raeburn  5284:                     }
                   5285:                 }
                   5286:             }
                   5287:         } elsif ($srch->{'srchin'} eq 'alc') {
1.179     raeburn  5288:             $currstate = 'query';
1.160     raeburn  5289:         } elsif ($srch->{'srchin'} eq 'instd') {
1.181     raeburn  5290:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch);
                   5291:             if ($dirsrchres eq 'ok') {
                   5292:                 ($currstate,$response,$forcenewuser) = 
1.221     raeburn  5293:                     &build_search_response($context,$srch,%srch_results);
1.181     raeburn  5294:             } else {
                   5295:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
                   5296:                 $response = '<span class="LC_warning">'.
                   5297:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
                   5298:                     '</span><br />'.
                   5299:                     &mt('You may want to search in the LON-CAPA domain instead of the institutional directory.').
                   5300:                     '<br /><br />'; 
                   5301:             }
1.160     raeburn  5302:         }
                   5303:     } else {
                   5304:         if ($srch->{'srchin'} eq 'dom') {
                   5305:             %srch_results = &Apache::lonnet::usersearch($srch);
1.179     raeburn  5306:             ($currstate,$response,$forcenewuser) = 
1.221     raeburn  5307:                 &build_search_response($context,$srch,%srch_results); 
1.160     raeburn  5308:         } elsif ($srch->{'srchin'} eq 'crs') {
1.167     albertel 5309:             my $courseusers = &get_courseusers(); 
                   5310:             foreach my $user (keys(%$courseusers)) {
1.160     raeburn  5311:                 my ($uname,$udom) = split(/:/,$user);
                   5312:                 my %names = &Apache::loncommon::getnames($uname,$udom);
                   5313:                 my %emails = &Apache::loncommon::getemails($uname,$udom);
                   5314:                 if ($srch->{'srchby'} eq 'lastname') {
                   5315:                     if ((($srch->{'srchtype'} eq 'exact') && 
                   5316:                          ($names{'lastname'} eq $srch->{'srchterm'})) || 
1.177     raeburn  5317:                         (($srch->{'srchtype'} eq 'begins') &&
                   5318:                          ($names{'lastname'} =~ /^\Q$srch->{'srchterm'}\E/i)) ||
1.160     raeburn  5319:                         (($srch->{'srchtype'} eq 'contains') &&
                   5320:                          ($names{'lastname'} =~ /\Q$srch->{'srchterm'}\E/i))) {
                   5321:                         $srch_results{$user} = {firstname => $names{'firstname'},
                   5322:                                             lastname => $names{'lastname'},
                   5323:                                             permanentemail => $emails{'permanentemail'},
                   5324:                                            };
                   5325:                     }
                   5326:                 } elsif ($srch->{'srchby'} eq 'lastfirst') {
                   5327:                     my ($srchlast,$srchfirst) = split(/,/,$srch->{'srchterm'});
1.177     raeburn  5328:                     $srchlast =~ s/\s+$//;
                   5329:                     $srchfirst =~ s/^\s+//;
1.160     raeburn  5330:                     if ($srch->{'srchtype'} eq 'exact') {
                   5331:                         if (($names{'lastname'} eq $srchlast) &&
                   5332:                             ($names{'firstname'} eq $srchfirst)) {
                   5333:                             $srch_results{$user} = {firstname => $names{'firstname'},
                   5334:                                                 lastname => $names{'lastname'},
                   5335:                                                 permanentemail => $emails{'permanentemail'},
                   5336: 
                   5337:                                            };
                   5338:                         }
1.177     raeburn  5339:                     } elsif ($srch->{'srchtype'} eq 'begins') {
                   5340:                         if (($names{'lastname'} =~ /^\Q$srchlast\E/i) &&
                   5341:                             ($names{'firstname'} =~ /^\Q$srchfirst\E/i)) {
                   5342:                             $srch_results{$user} = {firstname => $names{'firstname'},
                   5343:                                                 lastname => $names{'lastname'},
                   5344:                                                 permanentemail => $emails{'permanentemail'},
                   5345:                                                };
                   5346:                         }
                   5347:                     } else {
1.160     raeburn  5348:                         if (($names{'lastname'} =~ /\Q$srchlast\E/i) && 
                   5349:                             ($names{'firstname'} =~ /\Q$srchfirst\E/i)) {
                   5350:                             $srch_results{$user} = {firstname => $names{'firstname'},
                   5351:                                                 lastname => $names{'lastname'},
                   5352:                                                 permanentemail => $emails{'permanentemail'},
                   5353:                                                };
                   5354:                         }
                   5355:                     }
                   5356:                 }
                   5357:             }
1.179     raeburn  5358:             ($currstate,$response,$forcenewuser) = 
1.221     raeburn  5359:                 &build_search_response($context,$srch,%srch_results); 
1.160     raeburn  5360:         } elsif ($srch->{'srchin'} eq 'alc') {
1.179     raeburn  5361:             $currstate = 'query';
1.160     raeburn  5362:         } elsif ($srch->{'srchin'} eq 'instd') {
1.181     raeburn  5363:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch); 
                   5364:             if ($dirsrchres eq 'ok') {
                   5365:                 ($currstate,$response,$forcenewuser) = 
1.221     raeburn  5366:                     &build_search_response($context,$srch,%srch_results);
1.181     raeburn  5367:             } else {
                   5368:                 my $showdom = &display_domain_info($srch->{'srchdomain'});                $response = '<span class="LC_warning">'.
                   5369:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
                   5370:                     '</span><br />'.
                   5371:                     &mt('You may want to search in the LON-CAPA domain instead of the institutional directory.').
                   5372:                     '<br /><br />';
                   5373:             }
1.160     raeburn  5374:         }
                   5375:     }
1.179     raeburn  5376:     return ($currstate,$response,$forcenewuser,\%srch_results);
1.160     raeburn  5377: }
                   5378: 
                   5379: sub directorysrch_check {
                   5380:     my ($srch) = @_;
                   5381:     my $can_search = 0;
                   5382:     my $response;
                   5383:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
                   5384:                                              ['directorysrch'],$srch->{'srchdomain'});
1.180     raeburn  5385:     my $showdom = &display_domain_info($srch->{'srchdomain'});
1.160     raeburn  5386:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
                   5387:         if (!$dom_inst_srch{'directorysrch'}{'available'}) {
1.180     raeburn  5388:             return &mt('Institutional directory search is not available in domain: [_1]',$showdom); 
1.160     raeburn  5389:         }
                   5390:         if ($dom_inst_srch{'directorysrch'}{'localonly'}) {
                   5391:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
1.180     raeburn  5392:                 return &mt('Institutional directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom); 
1.160     raeburn  5393:             }
                   5394:             my @usertypes = split(/:/,$env{'environment.inststatus'});
                   5395:             if (!@usertypes) {
                   5396:                 push(@usertypes,'default');
                   5397:             }
                   5398:             if (ref($dom_inst_srch{'directorysrch'}{'cansearch'}) eq 'ARRAY') {
                   5399:                 foreach my $type (@usertypes) {
                   5400:                     if (grep(/^\Q$type\E$/,@{$dom_inst_srch{'directorysrch'}{'cansearch'}})) {
                   5401:                         $can_search = 1;
                   5402:                         last;
                   5403:                     }
                   5404:                 }
                   5405:             }
                   5406:             if (!$can_search) {
                   5407:                 my ($insttypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($srch->{'srchdomain'});
                   5408:                 my @longtypes; 
                   5409:                 foreach my $item (@usertypes) {
1.229     raeburn  5410:                     if (defined($insttypes->{$item})) { 
                   5411:                         push (@longtypes,$insttypes->{$item});
                   5412:                     } elsif ($item eq 'default') {
                   5413:                         push (@longtypes,&mt('other')); 
                   5414:                     }
1.160     raeburn  5415:                 }
                   5416:                 my $insttype_str = join(', ',@longtypes); 
1.180     raeburn  5417:                 return &mt('Institutional directory search in domain: [_1] is not available to your user type: ',$showdom).$insttype_str;
1.229     raeburn  5418:             }
1.160     raeburn  5419:         } else {
                   5420:             $can_search = 1;
                   5421:         }
                   5422:     } else {
1.180     raeburn  5423:         return &mt('Institutional directory search has not been configured for domain: [_1]',$showdom);
1.160     raeburn  5424:     }
                   5425:     my %longtext = &Apache::lonlocal::texthash (
1.167     albertel 5426:                        uname     => 'username',
1.160     raeburn  5427:                        lastfirst => 'last name, first name',
1.167     albertel 5428:                        lastname  => 'last name',
1.172     raeburn  5429:                        contains  => 'contains',
1.178     raeburn  5430:                        exact     => 'as exact match to',
                   5431:                        begins    => 'begins with',
1.160     raeburn  5432:                    );
                   5433:     if ($can_search) {
                   5434:         if (ref($dom_inst_srch{'directorysrch'}{'searchby'}) eq 'ARRAY') {
                   5435:             if (!grep(/^\Q$srch->{'srchby'}\E$/,@{$dom_inst_srch{'directorysrch'}{'searchby'}})) {
1.180     raeburn  5436:                 return &mt('Institutional directory search in domain: [_1] is not available for searching by "[_2]"',$showdom,$longtext{$srch->{'srchby'}});
1.160     raeburn  5437:             }
                   5438:         } else {
1.180     raeburn  5439:             return &mt('Institutional directory search in domain: [_1] is not available.', $showdom);
1.160     raeburn  5440:         }
                   5441:     }
                   5442:     if ($can_search) {
1.178     raeburn  5443:         if (ref($dom_inst_srch{'directorysrch'}{'searchtypes'}) eq 'ARRAY') {
                   5444:             if (grep(/^\Q$srch->{'srchtype'}\E/,@{$dom_inst_srch{'directorysrch'}{'searchtypes'}})) {
                   5445:                 return 'ok';
                   5446:             } else {
1.180     raeburn  5447:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
1.178     raeburn  5448:             }
                   5449:         } else {
                   5450:             if ((($dom_inst_srch{'directorysrch'}{'searchtypes'} eq 'specify') &&
                   5451:                  ($srch->{'srchtype'} eq 'exact' || $srch->{'srchtype'} eq 'contains')) ||
                   5452:                 ($dom_inst_srch{'directorysrch'}{'searchtypes'} eq $srch->{'srchtype'})) {
                   5453:                 return 'ok';
                   5454:             } else {
1.180     raeburn  5455:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
1.178     raeburn  5456:             }
1.160     raeburn  5457:         }
                   5458:     }
                   5459: }
                   5460: 
                   5461: sub get_courseusers {
                   5462:     my %advhash;
1.167     albertel 5463:     my $classlist = &Apache::loncoursedata::get_classlist();
1.160     raeburn  5464:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles();
                   5465:     foreach my $role (sort(keys(%coursepersonnel))) {
                   5466:         foreach my $user (split(/\,/,$coursepersonnel{$role})) {
1.167     albertel 5467: 	    if (!exists($classlist->{$user})) {
                   5468: 		$classlist->{$user} = [];
                   5469: 	    }
1.160     raeburn  5470:         }
                   5471:     }
1.167     albertel 5472:     return $classlist;
1.160     raeburn  5473: }
                   5474: 
                   5475: sub build_search_response {
1.221     raeburn  5476:     my ($context,$srch,%srch_results) = @_;
1.179     raeburn  5477:     my ($currstate,$response,$forcenewuser);
1.160     raeburn  5478:     my %names = (
                   5479:           'uname' => 'username',
                   5480:           'lastname' => 'last name',
                   5481:           'lastfirst' => 'last name, first name',
                   5482:           'crs' => 'this course',
1.180     raeburn  5483:           'dom' => 'LON-CAPA domain: ',
                   5484:           'instd' => 'the institutional directory for domain: ',
1.160     raeburn  5485:     );
                   5486: 
                   5487:     my %single = (
1.180     raeburn  5488:                    begins   => 'A match',
1.160     raeburn  5489:                    contains => 'A match',
1.180     raeburn  5490:                    exact    => 'An exact match',
1.160     raeburn  5491:                  );
                   5492:     my %nomatch = (
1.180     raeburn  5493:                    begins   => 'No match',
1.160     raeburn  5494:                    contains => 'No match',
1.180     raeburn  5495:                    exact    => 'No exact match',
1.160     raeburn  5496:                   );
                   5497:     if (keys(%srch_results) > 1) {
1.179     raeburn  5498:         $currstate = 'select';
1.160     raeburn  5499:     } else {
                   5500:         if (keys(%srch_results) == 1) {
1.179     raeburn  5501:             $currstate = 'modify';
1.180     raeburn  5502:             $response = &mt("$single{$srch->{'srchtype'}} was found for the $names{$srch->{'srchby'}} ([_1]) in $names{$srch->{'srchin'}}.",$srch->{'srchterm'});
                   5503:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
                   5504:                 $response .= &display_domain_info($srch->{'srchdomain'});
                   5505:             }
1.160     raeburn  5506:         } else {
1.180     raeburn  5507:             $response = '<span class="LC_warning">'.&mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} ([_1]) in $names{$srch->{'srchin'}}",$srch->{'srchterm'});
                   5508:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
                   5509:                 $response .= &display_domain_info($srch->{'srchdomain'});
                   5510:             }
                   5511:             $response .= '</span>';
1.160     raeburn  5512:             if ($srch->{'srchin'} ne 'alc') {
                   5513:                 $forcenewuser = 1;
                   5514:                 my $cansrchinst = 0; 
                   5515:                 if ($srch->{'srchdomain'}) {
                   5516:                     my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$srch->{'srchdomain'});
                   5517:                     if (ref($domconfig{'directorysrch'}) eq 'HASH') {
                   5518:                         if ($domconfig{'directorysrch'}{'available'}) {
                   5519:                             $cansrchinst = 1;
                   5520:                         } 
                   5521:                     }
                   5522:                 }
1.180     raeburn  5523:                 if ((($srch->{'srchby'} eq 'lastfirst') || 
                   5524:                      ($srch->{'srchby'} eq 'lastname')) &&
                   5525:                     ($srch->{'srchin'} eq 'dom')) {
                   5526:                     if ($cansrchinst) {
                   5527:                         $response .= '<br />'.&mt('You may want to broaden your search to a search of the institutional directory for the domain.');
1.160     raeburn  5528:                     }
                   5529:                 }
1.180     raeburn  5530:                 if ($srch->{'srchin'} eq 'crs') {
                   5531:                     $response .= '<br />'.&mt('You may want to broaden your search to the selected LON-CAPA domain.');
                   5532:                 }
                   5533:             }
                   5534:             if (!($srch->{'srchby'} eq 'uname' && $srch->{'srchin'} eq 'dom' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchdomain'} eq $env{'request.role.domain'})) {
1.221     raeburn  5535:                 my $cancreate =
                   5536:                     &Apache::lonuserutils::can_create_user($env{'request.role.domain'},$context);
                   5537:                 if ($cancreate) {
                   5538:                     my $showdom = &display_domain_info($env{'request.role.domain'}); 
1.266     bisitz   5539:                     $response .= '<br /><br />'
                   5540:                                 .'<b>'.&mt('To add a new user:').'</b>'
                   5541:                                 .'<br />'
                   5542:                                 .&mt("(You can only create new users in your current role's domain - [_1])"
                   5543:                                     ,'<span class="LC_cusr_emph">'.$env{'request.role.domain'}.'</span>')
                   5544:                                 .'<ul><li>'
                   5545:                                 .&mt("Set 'Domain/institution to search' to: [_1]",'<span class="LC_cusr_emph">'.$showdom.'</span>')
                   5546:                                 .'</li><li>'
                   5547:                                 .&mt("Set 'Search criteria' to: [_1]username is ..... in selected LON-CAPA domain[_2]",'<span class="LC_cusr_emph">','</span>')
                   5548:                                 .'</li><li>'
                   5549:                                 .&mt('Provide the proposed username')
                   5550:                                 .'</li><li>'
                   5551:                                 .&mt("Click 'Search'")
                   5552:                                 .'</li></ul><br />';
1.221     raeburn  5553:                 } else {
                   5554:                     my $helplink = ' href="javascript:helpMenu('."'display'".')"';
1.266     bisitz   5555:                     $response .= '<br /><br />'
                   5556:                                 .&mt("You are not authorized to create new users in your current role's domain - [_1]."
                   5557:                                     ,'<span class="LC_cusr_emph">'.$env{'request.role.domain'}.'</span>')
                   5558:                                 .'<br />'
1.292     bisitz   5559:                                 .&mt('Please contact the [_1]helpdesk[_2] if you need to create a new user.'
1.266     bisitz   5560:                                     ,' <a'.$helplink.'>'
                   5561:                                     ,'</a>')
                   5562:                                 .'<br /><br />';
1.221     raeburn  5563:                 }
1.160     raeburn  5564:             }
                   5565:         }
                   5566:     }
1.179     raeburn  5567:     return ($currstate,$response,$forcenewuser);
1.160     raeburn  5568: }
                   5569: 
1.180     raeburn  5570: sub display_domain_info {
                   5571:     my ($dom) = @_;
                   5572:     my $output = $dom;
                   5573:     if ($dom ne '') { 
                   5574:         my $domdesc = &Apache::lonnet::domain($dom,'description');
                   5575:         if ($domdesc ne '') {
                   5576:             $output .= ' <span class="LC_cusr_emph">('.$domdesc.')</span>';
                   5577:         }
                   5578:     }
                   5579:     return $output;
                   5580: }
                   5581: 
1.160     raeburn  5582: sub crumb_utilities {
                   5583:     my %elements = (
                   5584:        crtuser => {
                   5585:            srchterm => 'text',
1.172     raeburn  5586:            srchin => 'selectbox',
1.160     raeburn  5587:            srchby => 'selectbox',
                   5588:            srchtype => 'selectbox',
                   5589:            srchdomain => 'selectbox',
                   5590:        },
1.207     raeburn  5591:        crtusername => {
                   5592:            srchterm => 'text',
                   5593:            srchdomain => 'selectbox',
                   5594:        },
1.160     raeburn  5595:        docustom => {
                   5596:            rolename => 'selectbox',
                   5597:            newrolename => 'textbox',
                   5598:        },
1.179     raeburn  5599:        studentform => {
                   5600:            srchterm => 'text',
                   5601:            srchin => 'selectbox',
                   5602:            srchby => 'selectbox',
                   5603:            srchtype => 'selectbox',
                   5604:            srchdomain => 'selectbox',
                   5605:        },
1.160     raeburn  5606:     );
                   5607: 
                   5608:     my $jsback .= qq|
                   5609: function backPage(formname,prevphase,prevstate) {
1.211     raeburn  5610:     if (typeof prevphase == 'undefined') {
                   5611:         formname.phase.value = '';
                   5612:     }
                   5613:     else {  
                   5614:         formname.phase.value = prevphase;
                   5615:     }
                   5616:     if (typeof prevstate == 'undefined') {
                   5617:         formname.currstate.value = '';
                   5618:     }
                   5619:     else {
                   5620:         formname.currstate.value = prevstate;
                   5621:     }
1.160     raeburn  5622:     formname.submit();
                   5623: }
                   5624: |;
                   5625:     return ($jsback,\%elements);
                   5626: }
                   5627: 
1.26      matthew  5628: sub course_level_table {
1.89      raeburn  5629:     my (%inccourses) = @_;
1.26      matthew  5630:     my $table = '';
1.62      www      5631: # Custom Roles?
                   5632: 
1.190     raeburn  5633:     my %customroles=&Apache::lonuserutils::my_custom_roles();
1.89      raeburn  5634:     my %lt=&Apache::lonlocal::texthash(
                   5635:             'exs'  => "Existing sections",
                   5636:             'new'  => "Define new section",
                   5637:             'ssd'  => "Set Start Date",
                   5638:             'sed'  => "Set End Date",
1.131     raeburn  5639:             'crl'  => "Course Level",
1.89      raeburn  5640:             'act'  => "Activate",
                   5641:             'rol'  => "Role",
                   5642:             'ext'  => "Extent",
1.113     raeburn  5643:             'grs'  => "Section",
1.89      raeburn  5644:             'sta'  => "Start",
                   5645:             'end'  => "End"
                   5646:     );
1.62      www      5647: 
1.135     raeburn  5648:     foreach my $protectedcourse (sort( keys(%inccourses))) {
                   5649: 	my $thiscourse=$protectedcourse;
1.26      matthew  5650: 	$thiscourse=~s:_:/:g;
                   5651: 	my %coursedata=&Apache::lonnet::coursedescription($thiscourse);
                   5652: 	my $area=$coursedata{'description'};
1.119     raeburn  5653:         my $type=$coursedata{'type'};
1.135     raeburn  5654: 	if (!defined($area)) { $area=&mt('Unavailable course').': '.$protectedcourse; }
1.89      raeburn  5655: 	my ($domain,$cnum)=split(/\//,$thiscourse);
1.115     albertel 5656:         my %sections_count;
1.101     albertel 5657:         if (defined($env{'request.course.id'})) {
                   5658:             if ($env{'request.course.id'} eq $domain.'_'.$cnum) {
1.115     albertel 5659:                 %sections_count = 
                   5660: 		    &Apache::loncommon::get_sections($domain,$cnum);
1.92      raeburn  5661:             }
                   5662:         }
1.213     raeburn  5663:         my @roles = &Apache::lonuserutils::roles_by_context('course');
                   5664: 	foreach my $role (@roles) {
1.221     raeburn  5665:             my $plrole=&Apache::lonnet::plaintext($role);
1.135     raeburn  5666: 	    if (&Apache::lonnet::allowed('c'.$role,$thiscourse)) {
1.221     raeburn  5667:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
                   5668:                                             $plrole,\%sections_count,\%lt);    
                   5669:             } elsif ($env{'request.course.sec'} ne '') {
                   5670:                 if (&Apache::lonnet::allowed('c'.$role,$thiscourse.'/'.
                   5671:                                              $env{'request.course.sec'})) {
                   5672:                     $table .= &course_level_row($protectedcourse,$role,$area,$domain,
                   5673:                                                 $plrole,\%sections_count,\%lt);
1.26      matthew  5674:                 }
                   5675:             }
                   5676:         }
1.221     raeburn  5677:         if (&Apache::lonnet::allowed('ccr',$thiscourse)) {
                   5678:             foreach my $cust (sort keys %customroles) {
                   5679:                 my $role = 'cr_cr_'.$env{'user.domain'}.'_'.$env{'user.name'}.'_'.$cust;
                   5680:                 $table .= &course_level_row($protectedcourse,$role,$area,$domain,
                   5681:                                             $cust,\%sections_count,\%lt);
                   5682:             }
1.62      www      5683: 	}
1.26      matthew  5684:     }
                   5685:     return '' if ($table eq ''); # return nothing if there is nothing 
                   5686:                                  # in the table
1.188     raeburn  5687:     my $result;
                   5688:     if (!$env{'request.course.id'}) {
                   5689:         $result = '<h4>'.$lt{'crl'}.'</h4>'."\n";
                   5690:     }
                   5691:     $result .= 
1.136     raeburn  5692: &Apache::loncommon::start_data_table().
                   5693: &Apache::loncommon::start_data_table_header_row().
                   5694: '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th><th>'.$lt{'ext'}.'</th>
                   5695: <th>'.$lt{'grs'}.'</th><th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'.
                   5696: &Apache::loncommon::end_data_table_header_row().
                   5697: $table.
                   5698: &Apache::loncommon::end_data_table();
1.26      matthew  5699:     return $result;
                   5700: }
1.88      raeburn  5701: 
1.221     raeburn  5702: sub course_level_row {
                   5703:     my ($protectedcourse,$role,$area,$domain,$plrole,$sections_count,$lt) = @_;
1.222     raeburn  5704:     my $row = &Apache::loncommon::start_data_table_row().
                   5705:               ' <td><input type="checkbox" name="act_'.
                   5706:               $protectedcourse.'_'.$role.'" /></td>'."\n".
                   5707:               ' <td>'.$plrole.'</td>'."\n".
                   5708:               ' <td>'.$area.'<br />Domain: '.$domain.'</td>'."\n";
1.221     raeburn  5709:     if ($role eq 'cc') {
1.222     raeburn  5710:         $row .= '<td>&nbsp;</td>';
1.221     raeburn  5711:     } elsif ($env{'request.course.sec'} ne '') {
1.222     raeburn  5712:         $row .= ' <td><input type="hidden" value="'.
                   5713:                 $env{'request.course.sec'}.'" '.
                   5714:                 'name="sec_'.$protectedcourse.'_'.$role.'" />'.
                   5715:                 $env{'request.course.sec'}.'</td>';
1.221     raeburn  5716:     } else {
                   5717:         if (ref($sections_count) eq 'HASH') {
                   5718:             my $currsec = 
                   5719:                 &Apache::lonuserutils::course_sections($sections_count,
                   5720:                                                        $protectedcourse.'_'.$role);
1.222     raeburn  5721:             $row .= '<td><table class="LC_createuser">'."\n".
                   5722:                     '<tr class="LC_section_row">'."\n".
                   5723:                     ' <td valign="top">'.$lt->{'exs'}.'<br />'.
                   5724:                        $currsec.'</td>'."\n".
                   5725:                      ' <td>&nbsp;&nbsp;</td>'."\n".
                   5726:                      ' <td valign="top">&nbsp;'.$lt->{'new'}.'<br />'.
1.221     raeburn  5727:                      '<input type="text" name="newsec_'.$protectedcourse.'_'.$role.
                   5728:                      '" value="" />'.
                   5729:                      '<input type="hidden" '.
                   5730:                      'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n".
1.222     raeburn  5731:                      '</tr></table></td>'."\n";
1.221     raeburn  5732:         } else {
1.222     raeburn  5733:             $row .= '<td><input type="text" size="10" '.
                   5734:                       'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'."\n";
1.221     raeburn  5735:         }
                   5736:     }
1.222     raeburn  5737:     $row .= <<ENDTIMEENTRY;
                   5738: <td><input type="hidden" name="start_$protectedcourse\_$role" value="" />
1.221     raeburn  5739: <a href=
                   5740: "javascript:pjump('date_start','Start Date $plrole',document.cu.start_$protectedcourse\_$role.value,'start_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'ssd'}</a></td>
1.222     raeburn  5741: <td><input type="hidden" name="end_$protectedcourse\_$role" value="" />
1.221     raeburn  5742: <a href=
                   5743: "javascript:pjump('date_end','End Date $plrole',document.cu.end_$protectedcourse\_$role.value,'end_$protectedcourse\_$role','cu.pres','dateset')">$lt->{'sed'}</a></td>
                   5744: ENDTIMEENTRY
1.222     raeburn  5745:     $row .= &Apache::loncommon::end_data_table_row();
                   5746:     return $row;
1.221     raeburn  5747: }
                   5748: 
1.88      raeburn  5749: sub course_level_dc {
                   5750:     my ($dcdom) = @_;
1.190     raeburn  5751:     my %customroles=&Apache::lonuserutils::my_custom_roles();
1.213     raeburn  5752:     my @roles = &Apache::lonuserutils::roles_by_context('course');
1.88      raeburn  5753:     my $hiddenitems = '<input type="hidden" name="dcdomain" value="'.$dcdom.'" />'.
                   5754:                       '<input type="hidden" name="origdom" value="'.$dcdom.'" />'.
1.133     raeburn  5755:                       '<input type="hidden" name="dccourse" value="" />';
1.88      raeburn  5756:     my $courseform='<b>'.&Apache::loncommon::selectcourse_link
1.131     raeburn  5757:             ('cu','dccourse','dcdomain','coursedesc',undef,undef,'Course').'</b>';
                   5758:     my $cb_jscript = &Apache::loncommon::coursebrowser_javascript($dcdom,'currsec','cu');
1.88      raeburn  5759:     my %lt=&Apache::lonlocal::texthash(
                   5760:                     'rol'  => "Role",
1.113     raeburn  5761:                     'grs'  => "Section",
1.88      raeburn  5762:                     'exs'  => "Existing sections",
                   5763:                     'new'  => "Define new section", 
                   5764:                     'sta'  => "Start",
                   5765:                     'end'  => "End",
                   5766:                     'ssd'  => "Set Start Date",
                   5767:                     'sed'  => "Set End Date"
                   5768:                   );
1.131     raeburn  5769:     my $header = '<h4>'.&mt('Course Level').'</h4>'.
1.136     raeburn  5770:                  &Apache::loncommon::start_data_table().
                   5771:                  &Apache::loncommon::start_data_table_header_row().
1.143     raeburn  5772:                  '<th>'.$courseform.'</th><th>'.$lt{'rol'}.'</th><th>'.$lt{'grs'}.'</th><th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'.
1.136     raeburn  5773:                  &Apache::loncommon::end_data_table_header_row();
1.143     raeburn  5774:     my $otheritems = &Apache::loncommon::start_data_table_row()."\n".
1.131     raeburn  5775:                      '<td><input type="text" name="coursedesc" value="" onFocus="this.blur();opencrsbrowser('."'cu','dccourse','dcdomain','coursedesc',''".')" /></td>'."\n".
1.88      raeburn  5776:                      '<td><select name="role">'."\n";
1.213     raeburn  5777:     foreach my $role (@roles) {
1.135     raeburn  5778:         my $plrole=&Apache::lonnet::plaintext($role);
                   5779:         $otheritems .= '  <option value="'.$role.'">'.$plrole;
1.88      raeburn  5780:     }
                   5781:     if ( keys %customroles > 0) {
1.135     raeburn  5782:         foreach my $cust (sort keys %customroles) {
1.101     albertel 5783:             my $custrole='cr_cr_'.$env{'user.domain'}.
1.135     raeburn  5784:                     '_'.$env{'user.name'}.'_'.$cust;
                   5785:             $otheritems .= '  <option value="'.$custrole.'">'.$cust;
1.88      raeburn  5786:         }
                   5787:     }
                   5788:     $otheritems .= '</select></td><td>'.
                   5789:                      '<table border="0" cellspacing="0" cellpadding="0">'.
                   5790:                      '<tr><td valign="top"><b>'.$lt{'exs'}.'</b><br /><select name="currsec">'.
                   5791:                      ' <option value=""><--'.&mt('Pick course first').'</select></td>'.
                   5792:                      '<td>&nbsp;&nbsp;</td>'.
                   5793:                      '<td valign="top">&nbsp;<b>'.$lt{'new'}.'</b><br />'.
1.113     raeburn  5794:                      '<input type="text" name="newsec" value="" />'.
1.237     raeburn  5795:                      '<input type="hidden" name="section" value="" />'.
1.113     raeburn  5796:                      '<input type="hidden" name="groups" value="" /></td>'.
1.88      raeburn  5797:                      '</tr></table></td>';
                   5798:     $otheritems .= <<ENDTIMEENTRY;
1.169     albertel 5799: <td><input type="hidden" name="start" value='' />
1.88      raeburn  5800: <a href=
                   5801: "javascript:pjump('date_start','Start Date',document.cu.start.value,'start','cu.pres','dateset')">$lt{'ssd'}</a></td>
1.169     albertel 5802: <td><input type="hidden" name="end" value='' />
1.88      raeburn  5803: <a href=
                   5804: "javascript:pjump('date_end','End Date',document.cu.end.value,'end','cu.pres','dateset')">$lt{'sed'}</a></td>
                   5805: ENDTIMEENTRY
1.136     raeburn  5806:     $otheritems .= &Apache::loncommon::end_data_table_row().
                   5807:                    &Apache::loncommon::end_data_table()."\n";
1.88      raeburn  5808:     return $cb_jscript.$header.$hiddenitems.$otheritems;
                   5809: }
                   5810: 
1.237     raeburn  5811: sub update_selfenroll_config {
1.241     raeburn  5812:     my ($r,$context,$permission) = @_;
1.237     raeburn  5813:     my ($row,$lt) = &get_selfenroll_titles();
1.241     raeburn  5814:     my %curr_groups = &Apache::longroup::coursegroups();
1.237     raeburn  5815:     my (%changes,%warning);
                   5816:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5817:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.241     raeburn  5818:     my $curr_types;
1.237     raeburn  5819:     if (ref($row) eq 'ARRAY') {
                   5820:         foreach my $item (@{$row}) {
                   5821:             if ($item eq 'enroll_dates') {
                   5822:                 my (%currenrolldate,%newenrolldate);
                   5823:                 foreach my $type ('start','end') {
                   5824:                     $currenrolldate{$type} = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_'.$type.'_date'};
                   5825:                     $newenrolldate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_date');
                   5826:                     if ($newenrolldate{$type} ne $currenrolldate{$type}) {
                   5827:                         $changes{'internal.selfenroll_'.$type.'_date'} = $newenrolldate{$type};
                   5828:                     }
                   5829:                 }
                   5830:             } elsif ($item eq 'access_dates') {
                   5831:                 my (%currdate,%newdate);
                   5832:                 foreach my $type ('start','end') {
                   5833:                     $currdate{$type} = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_'.$type.'_access'};
                   5834:                     $newdate{$type} = &Apache::lonhtmlcommon::get_date_from_form('selfenroll_'.$type.'_access');
                   5835:                     if ($newdate{$type} ne $currdate{$type}) {
                   5836:                         $changes{'internal.selfenroll_'.$type.'_access'} = $newdate{$type};
                   5837:                     }
                   5838:                 }
1.241     raeburn  5839:             } elsif ($item eq 'types') {
                   5840:                 $curr_types =
                   5841:                     $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_'.$item};
                   5842:                 if ($env{'form.selfenroll_all'}) {
                   5843:                     if ($curr_types ne '*') {
                   5844:                         $changes{'internal.selfenroll_types'} = '*';
                   5845:                     } else {
                   5846:                         next;
                   5847:                     }
                   5848:                 } else {
1.249     raeburn  5849:                     my %currdoms;
1.241     raeburn  5850:                     my @entries = split(/;/,$curr_types);
                   5851:                     my @deletedoms = &Apache::loncommon::get_env_multiple('form.selfenroll_delete');
1.249     raeburn  5852:                     my @activations = &Apache::loncommon::get_env_multiple('form.selfenroll_activate');
1.241     raeburn  5853:                     my $newnum = 0;
1.249     raeburn  5854:                     my @latesttypes;
                   5855:                     foreach my $num (@activations) {
                   5856:                         my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$num);
                   5857:                         if (@types > 0) {
1.241     raeburn  5858:                             @types = sort(@types);
                   5859:                             my $typestr = join(',',@types);
1.249     raeburn  5860:                             my $typedom = $env{'form.selfenroll_dom_'.$num};
                   5861:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
                   5862:                             $currdoms{$typedom} = 1;
1.241     raeburn  5863:                             $newnum ++;
                   5864:                         }
                   5865:                     }
1.249     raeburn  5866:                     for (my $j=0; $j<$env{'form.selfenroll_types_total'}; $j++) {                        if ((!grep(/^$j$/,@deletedoms)) && (!grep(/^$j$/,@activations))) {
                   5867:                             my @types = &Apache::loncommon::get_env_multiple('form.selfenroll_types_'.$j);
                   5868:                             if (@types > 0) {
                   5869:                                 @types = sort(@types);
                   5870:                                 my $typestr = join(',',@types);
                   5871:                                 my $typedom = $env{'form.selfenroll_dom_'.$j};
                   5872:                                 $latesttypes[$newnum] = $typedom.':'.$typestr;
                   5873:                                 $currdoms{$typedom} = 1;
                   5874:                                 $newnum ++;
                   5875:                             }
                   5876:                         }
                   5877:                     }
                   5878:                     if ($env{'form.selfenroll_newdom'} ne '') {
                   5879:                         my $typedom = $env{'form.selfenroll_newdom'};
                   5880:                         if ((!defined($currdoms{$typedom})) && 
                   5881:                             (&Apache::lonnet::domain($typedom) ne '')) {
                   5882:                             my $typestr;
                   5883:                             my ($othertitle,$usertypes,$types) = 
                   5884:                                 &Apache::loncommon::sorted_inst_types($typedom);
                   5885:                             my $othervalue = 'any';
                   5886:                             if ((ref($types) eq 'ARRAY') && (ref($usertypes) eq 'HASH')) {
                   5887:                                 if (@{$types} > 0) {
1.257     raeburn  5888:                                     my @esc_types = map { &escape($_); } @{$types};
1.249     raeburn  5889:                                     $othervalue = 'other';
1.258     raeburn  5890:                                     $typestr = join(',',(@esc_types,$othervalue));
1.249     raeburn  5891:                                 }
                   5892:                                 $typestr = $othervalue;
                   5893:                             } else {
                   5894:                                 $typestr = $othervalue;
                   5895:                             } 
                   5896:                             $latesttypes[$newnum] = $typedom.':'.$typestr;
                   5897:                             $newnum ++ ;
                   5898:                         }
                   5899:                     }
1.241     raeburn  5900:                     my $selfenroll_types = join(';',@latesttypes);
                   5901:                     if ($selfenroll_types ne $curr_types) {
                   5902:                         $changes{'internal.selfenroll_types'} = $selfenroll_types;
                   5903:                     }
                   5904:                 }
1.276     raeburn  5905:             } elsif ($item eq 'limit') {
                   5906:                 my $newlimit = $env{'form.selfenroll_limit'};
                   5907:                 my $newcap = $env{'form.selfenroll_cap'};
                   5908:                 $newcap =~s/\s+//g;
                   5909:                 my $currlimit =  $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_limit'};
                   5910:                 $currlimit = 'none' if ($currlimit eq '');
                   5911:                 my $currcap = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_cap'};
                   5912:                 if ($newlimit ne $currlimit) {
                   5913:                     if ($newlimit ne 'none') {
                   5914:                         if ($newcap =~ /^\d+$/) {
                   5915:                             if ($newcap ne $currcap) {
                   5916:                                 $changes{'internal.selfenroll_cap'} = $newcap;
                   5917:                             }
                   5918:                             $changes{'internal.selfenroll_limit'} = $newlimit;
                   5919:                         } else {
                   5920:                             $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.&mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.'); 
                   5921:                         }
                   5922:                     } elsif ($currcap ne '') {
                   5923:                         $changes{'internal.selfenroll_cap'} = '';
                   5924:                         $changes{'internal.selfenroll_limit'} = $newlimit; 
                   5925:                     }
                   5926:                 } elsif ($currlimit ne 'none') {
                   5927:                     if ($newcap =~ /^\d+$/) {
                   5928:                         if ($newcap ne $currcap) {
                   5929:                             $changes{'internal.selfenroll_cap'} = $newcap;
                   5930:                         }
                   5931:                     } else {
                   5932:                         $warning{$item} = &mt('Maximum enrollment setting unchanged.').'<br />'.&mt('The value provided was invalid - it must be a positive integer if enrollment is being limited.');
                   5933:                     }
                   5934:                 }
                   5935:             } elsif ($item eq 'approval') {
                   5936:                 my (@currnotified,@newnotified);
                   5937:                 my $currapproval = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_approval'};
                   5938:                 my $currnotifylist = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_notifylist'};
                   5939:                 if ($currnotifylist ne '') {
                   5940:                     @currnotified = split(/,/,$currnotifylist);
                   5941:                     @currnotified = sort(@currnotified);
                   5942:                 }
                   5943:                 my $newapproval = $env{'form.selfenroll_approval'};
                   5944:                 @newnotified = &Apache::loncommon::get_env_multiple('form.selfenroll_notify');
                   5945:                 @newnotified = sort(@newnotified);
                   5946:                 if ($newapproval ne $currapproval) {
                   5947:                     $changes{'internal.selfenroll_approval'} = $newapproval;
                   5948:                     if (!$newapproval) {
                   5949:                         if ($currnotifylist ne '') {
                   5950:                             $changes{'internal.selfenroll_notifylist'} = '';
                   5951:                         }
                   5952:                     } else {
                   5953:                         my @differences =  
1.295     raeburn  5954:                             &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
1.276     raeburn  5955:                         if (@differences > 0) {
                   5956:                             if (@newnotified > 0) {
                   5957:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
                   5958:                             } else {
                   5959:                                 $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
                   5960:                             }
                   5961:                         }
                   5962:                     }
                   5963:                 } else {
1.295     raeburn  5964:                     my @differences = &Apache::loncommon::compare_arrays(\@currnotified,\@newnotified);
1.276     raeburn  5965:                     if (@differences > 0) {
                   5966:                         if (@newnotified > 0) {
                   5967:                             $changes{'internal.selfenroll_notifylist'} = join(',',@newnotified);
                   5968:                         } else {
                   5969:                             $changes{'internal.selfenroll_notifylist'} = '';
                   5970:                         }
                   5971:                     }
                   5972:                 }
1.237     raeburn  5973:             } else {
                   5974:                 my $curr_val = 
                   5975:                     $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_'.$item};
                   5976:                 my $newval = $env{'form.selfenroll_'.$item};
                   5977:                 if ($item eq 'section') {
                   5978:                     $newval = $env{'form.sections'};
1.241     raeburn  5979:                     if (defined($curr_groups{$newval})) {
1.237     raeburn  5980:                         $newval = $curr_val;
                   5981:                         $warning{$item} = &mt('Section for self-enrolled users unchanged as the proposed section is a group').'<br />'.&mt('Group names and section names must be distinct');
                   5982:                     } elsif ($newval eq 'all') {
                   5983:                         $newval = $curr_val;
1.274     bisitz   5984:                         $warning{$item} = &mt('Section for self-enrolled users unchanged, as "all" is a reserved section name.');
1.237     raeburn  5985:                     }
                   5986:                     if ($newval eq '') {
                   5987:                         $newval = 'none';
                   5988:                     }
                   5989:                 }
                   5990:                 if ($newval ne $curr_val) {
                   5991:                     $changes{'internal.selfenroll_'.$item} = $newval;
                   5992:                 }
1.241     raeburn  5993:             }
1.237     raeburn  5994:         }
                   5995:         if (keys(%warning) > 0) {
                   5996:             foreach my $item (@{$row}) {
                   5997:                 if (exists($warning{$item})) {
                   5998:                     $r->print($warning{$item}.'<br />');
                   5999:                 }
                   6000:             } 
                   6001:         }
                   6002:         if (keys(%changes) > 0) {
                   6003:             my $putresult = &Apache::lonnet::put('environment',\%changes,$cdom,$cnum);
                   6004:             if ($putresult eq 'ok') {
                   6005:                 if ((exists($changes{'internal.selfenroll_types'})) ||
                   6006:                     (exists($changes{'internal.selfenroll_start_date'}))  ||
                   6007:                     (exists($changes{'internal.selfenroll_end_date'}))) {
                   6008:                     my %crsinfo = &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',
                   6009:                                                                 $cnum,undef,undef,'Course');
                   6010:                     my $chome = &Apache::lonnet::homeserver($cnum,$cdom);
                   6011:                     if (ref($crsinfo{$env{'request.course.id'}}) eq 'HASH') {
                   6012:                         foreach my $item ('selfenroll_types','selfenroll_start_date','selfenroll_end_date') {
                   6013:                             if (exists($changes{'internal.'.$item})) {
                   6014:                                 $crsinfo{$env{'request.course.id'}}{$item} = 
                   6015:                                     $changes{'internal.'.$item};
                   6016:                             }
                   6017:                         }
                   6018:                         my $crsputresult =
                   6019:                             &Apache::lonnet::courseidput($cdom,\%crsinfo,
                   6020:                                                          $chome,'notime');
                   6021:                     }
                   6022:                 }
                   6023:                 $r->print(&mt('The following changes were made to self-enrollment settings:').'<ul>');
                   6024:                 foreach my $item (@{$row}) {
                   6025:                     my $title = $item;
                   6026:                     if (ref($lt) eq 'HASH') {
                   6027:                         $title = $lt->{$item};
                   6028:                     }
                   6029:                     if ($item eq 'enroll_dates') {
                   6030:                         foreach my $type ('start','end') {
                   6031:                             if (exists($changes{'internal.selfenroll_'.$type.'_date'})) {
                   6032:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_date'});
1.244     bisitz   6033:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
1.237     raeburn  6034:                                           $title,$type,$newdate).'</li>');
                   6035:                             }
                   6036:                         }
                   6037:                     } elsif ($item eq 'access_dates') {
                   6038:                         foreach my $type ('start','end') {
                   6039:                             if (exists($changes{'internal.selfenroll_'.$type.'_access'})) {
                   6040:                                 my $newdate = &Apache::lonlocal::locallocaltime($changes{'internal.selfenroll_'.$type.'_access'});
1.244     bisitz   6041:                                 $r->print('<li>'.&mt('[_1]: "[_2]" set to "[_3]".',
1.237     raeburn  6042:                                           $title,$type,$newdate).'</li>');
                   6043:                             }
                   6044:                         }
1.276     raeburn  6045:                     } elsif ($item eq 'limit') {
                   6046:                         if ((exists($changes{'internal.selfenroll_limit'})) ||
                   6047:                             (exists($changes{'internal.selfenroll_cap'}))) {
                   6048:                             my ($newval,$newcap);
                   6049:                             if ($changes{'internal.selfenroll_cap'} ne '') {
                   6050:                                 $newcap = $changes{'internal.selfenroll_cap'}
                   6051:                             } else {
                   6052:                                 $newcap = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_cap'};
                   6053:                             }
                   6054:                             if ($changes{'internal.selfenroll_limit'} eq 'none') {
                   6055:                                 $newval = &mt('No limit');
                   6056:                             } elsif ($changes{'internal.selfenroll_limit'} eq 
                   6057:                                      'allstudents') {
                   6058:                                 $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
                   6059:                             } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
                   6060:                                 $newval = &mt('New self-enrollment no longer allowed when total number of self-enrolled students reaches [_1].',$newcap);
                   6061:                             } else {
                   6062:                                 my $currlimit =  $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_limit'};
                   6063:                                 if ($currlimit eq 'allstudents') {
                   6064:                                     $newval = &mt('New self-enrollment no longer allowed when total (all students) reaches [_1].',$newcap);
                   6065:                                 } elsif ($changes{'internal.selfenroll_limit'} eq 'selfenrolled') {
                   6066:                                     $newval =  &mt('New self-enrollment no longer allowed when total umber of self-enrolled students reaches [_1].',$newcap);
                   6067:                                 }
                   6068:                             }
                   6069:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
                   6070:                         }
                   6071:                     } elsif ($item eq 'approval') {
                   6072:                         if ((exists($changes{'internal.selfenroll_approval'})) ||
                   6073:                             (exists($changes{'internal.selfenroll_notifylist'}))) {
                   6074:                             my ($newval,$newnotify);
                   6075:                             if (exists($changes{'internal.selfenroll_notifylist'})) {
                   6076:                                 $newnotify = $changes{'internal.selfenroll_notifylist'};
                   6077:                             } else {   
                   6078:                                 $newnotify = $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_notifylist'};
                   6079:                             }
                   6080:                             if ($changes{'internal.selfenroll_approval'}) {
                   6081:                                 $newval = &mt('Yes');
                   6082:                             } elsif ($changes{'internal.selfenroll_approval'} eq '0') {
                   6083:                                 $newval = &mt('No');
                   6084:                             } else {
                   6085:                                 my $currapproval = 
                   6086:                                     $env{'course.'.$env{'request.course.id'}.'.internal.selfenroll_approval'};
                   6087:                                 if ($currapproval) {
                   6088:                                     $newval = &mt('Yes');
                   6089:                                 } else {
                   6090:                                     $newval = &mt('No');
                   6091:                                 }
                   6092:                             }
                   6093:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval));
                   6094:                             if ($newnotify) {
1.277     raeburn  6095:                                 $r->print('<br />'.&mt('The following will be notified when an enrollment request needs approval, or has been approved: [_1].',$newnotify));
1.276     raeburn  6096:                             } else {
1.277     raeburn  6097:                                 $r->print('<br />'.&mt('No notifications sent when an enrollment request needs approval, or has been approved.'));
1.276     raeburn  6098:                             }
                   6099:                             $r->print('</li>'."\n");
                   6100:                         }
1.237     raeburn  6101:                     } else {
                   6102:                         if (exists($changes{'internal.selfenroll_'.$item})) {
1.241     raeburn  6103:                             my $newval = $changes{'internal.selfenroll_'.$item};
                   6104:                             if ($item eq 'types') {
                   6105:                                 if ($newval eq '') {
                   6106:                                     $newval = &mt('None');
                   6107:                                 } elsif ($newval eq '*') {
                   6108:                                     $newval = &mt('Any user in any domain');
                   6109:                                 }
1.245     raeburn  6110:                             } elsif ($item eq 'registered') {
                   6111:                                 if ($newval eq '1') {
                   6112:                                     $newval = &mt('Yes');
                   6113:                                 } elsif ($newval eq '0') {
                   6114:                                     $newval = &mt('No');
                   6115:                                 }
1.241     raeburn  6116:                             }
1.244     bisitz   6117:                             $r->print('<li>'.&mt('"[_1]" set to "[_2]".',$title,$newval).'</li>'."\n");
1.237     raeburn  6118:                         }
                   6119:                     }
                   6120:                 }
                   6121:                 $r->print('</ul>');
                   6122:                 my %newenvhash;
                   6123:                 foreach my $key (keys(%changes)) {
                   6124:                     $newenvhash{'course.'.$env{'request.course.id'}.'.'.$key} = $changes{$key};
                   6125:                 }
1.238     raeburn  6126:                 &Apache::lonnet::appenv(\%newenvhash);
1.237     raeburn  6127:             } else {
                   6128:                 $r->print(&mt('An error occurred when saving changes to self-enrollment settings in this course.').'<br />'.&mt('The error was: [_1].',$putresult));
                   6129:             }
                   6130:         } else {
1.249     raeburn  6131:             $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
1.237     raeburn  6132:         }
                   6133:     } else {
1.249     raeburn  6134:         $r->print(&mt('No changes were made to the existing self-enrollment settings in this course.'));
1.241     raeburn  6135:     }
1.256     raeburn  6136:     my ($visible,$cansetvis,$vismsgs,$visactions) = &visible_in_cat($cdom,$cnum);
                   6137:     if (ref($visactions) eq 'HASH') {
                   6138:         if (!$visible) {
                   6139:             $r->print('<br />'.$visactions->{'miss'}.'<br />'.$visactions->{'yous'}.
                   6140:                       '<br />');
                   6141:             if (ref($vismsgs) eq 'ARRAY') {
                   6142:                 $r->print('<br />'.$visactions->{'take'}.'<ul>');
                   6143:                 foreach my $item (@{$vismsgs}) {
                   6144:                     $r->print('<li>'.$visactions->{$item}.'</li>');
                   6145:                 }
                   6146:                 $r->print('</ul>');
                   6147:             }
                   6148:             $r->print($cansetvis);
                   6149:         }
                   6150:     } 
1.237     raeburn  6151:     return;
                   6152: }
                   6153: 
                   6154: sub get_selfenroll_titles {
1.276     raeburn  6155:     my @row = ('types','registered','enroll_dates','access_dates','section',
                   6156:                'approval','limit');
1.237     raeburn  6157:     my %lt = &Apache::lonlocal::texthash (
                   6158:                 types        => 'Users allowed to self-enroll in this course',
1.245     raeburn  6159:                 registered   => 'Restrict self-enrollment to students officially registered for the course',
1.237     raeburn  6160:                 enroll_dates => 'Dates self-enrollment available',
1.256     raeburn  6161:                 access_dates => 'Course access dates assigned to self-enrolling users',
                   6162:                 section      => 'Section assigned to self-enrolling users',
1.276     raeburn  6163:                 approval     => 'Self-enrollment requests need approval?',
                   6164:                 limit        => 'Enrollment limit',
1.237     raeburn  6165:              );
                   6166:     return (\@row,\%lt);
                   6167: }
                   6168: 
1.27      matthew  6169: #---------------------------------------------- end functions for &phase_two
1.29      matthew  6170: 
                   6171: #--------------------------------- functions for &phase_two and &phase_three
                   6172: 
                   6173: #--------------------------end of functions for &phase_two and &phase_three
1.1       www      6174: 
                   6175: 1;
                   6176: __END__
1.2       www      6177: 
                   6178: 

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>