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

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

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