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

1.20      harris41    1: # The LearningOnline Network with CAPA
1.1       www         2: # Create a user
                      3: #
1.214   ! raeburn     4: # $Id: loncreateuser.pm,v 1.213 2007/12/21 12:41:25 raeburn Exp $
1.22      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.20      harris41   28: ###
                     29: 
1.1       www        30: package Apache::loncreateuser;
1.66      bowersj2   31: 
                     32: =pod
                     33: 
                     34: =head1 NAME
                     35: 
                     36: Apache::loncreateuser - handler to create users and custom roles
                     37: 
                     38: =head1 SYNOPSIS
                     39: 
                     40: Apache::loncreateuser provides an Apache handler for creating users,
                     41:     editing their login parameters, roles, and removing roles, and
                     42:     also creating and assigning custom roles.
                     43: 
                     44: =head1 OVERVIEW
                     45: 
                     46: =head2 Custom Roles
                     47: 
                     48: In LON-CAPA, roles are actually collections of privileges. "Teaching
                     49: Assistant", "Course Coordinator", and other such roles are really just
                     50: collection of privileges that are useful in many circumstances.
                     51: 
                     52: Creating custom roles can be done by the Domain Coordinator through
                     53: the Create User functionality. That screen will show all privileges
                     54: that can be assigned to users. For a complete list of privileges,
                     55: please see C</home/httpd/lonTabs/rolesplain.tab>.
                     56: 
                     57: Custom role definitions are stored in the C<roles.db> file of the role
                     58: author.
                     59: 
                     60: =cut
1.1       www        61: 
                     62: use strict;
                     63: use Apache::Constants qw(:common :http);
                     64: use Apache::lonnet;
1.54      bowersj2   65: use Apache::loncommon;
1.68      www        66: use Apache::lonlocal;
1.117     raeburn    67: use Apache::longroup;
1.190     raeburn    68: use Apache::lonuserutils;
1.139     albertel   69: use LONCAPA qw(:DEFAULT :match);
1.1       www        70: 
1.20      harris41   71: my $loginscript; # piece of javascript used in two separate instances
                     72: my $authformnop;
                     73: my $authformkrb;
                     74: my $authformint;
                     75: my $authformfsys;
                     76: my $authformloc;
                     77: 
1.94      matthew    78: sub initialize_authen_forms {
1.205     raeburn    79:     my ($dom,$curr_authtype,$mode) = @_; 
1.94      matthew    80:     my ($krbdefdom)=( $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/);
                     81:     $krbdefdom= uc($krbdefdom);
1.31      matthew    82:     my %param = ( formname => 'document.cu',
1.187     raeburn    83:                   kerb_def_dom => $krbdefdom,
                     84:                   domain => $dom,
                     85:                 );
1.188     raeburn    86:     my %abv_auth = &auth_abbrev();
1.187     raeburn    87:     if ($curr_authtype =~ /^(krb4|krb5|internal|localauth|unix):$/) {
1.188     raeburn    88:         my $long_auth = $1;
                     89:         my %abv_auth = &auth_abbrev();
                     90:         $param{'curr_authtype'} = $abv_auth{$long_auth};
                     91:         if ($long_auth =~ /^krb(4|5)$/) {
                     92:             $param{'curr_kerb_ver'} = $1;
                     93:         }
1.205     raeburn    94:         if ($mode eq 'modifyuser') {
                     95:             $param{'mode'} = $mode;
                     96:         }
1.187     raeburn    97:     }
1.48      albertel   98: # no longer static due to configurable kerberos defaults
                     99: #    $loginscript  = &Apache::loncommon::authform_header(%param);
1.31      matthew   100:     $authformnop  = &Apache::loncommon::authform_nochange(%param);
1.48      albertel  101: # no longer static due to configurable kerberos defaults
                    102: #    $authformkrb  = &Apache::loncommon::authform_kerberos(%param);
1.31      matthew   103:     $authformint  = &Apache::loncommon::authform_internal(%param);
                    104:     $authformfsys = &Apache::loncommon::authform_filesystem(%param);
                    105:     $authformloc  = &Apache::loncommon::authform_local(%param);
1.20      harris41  106: }
                    107: 
1.188     raeburn   108: sub auth_abbrev {
                    109:     my %abv_auth = (
                    110:                      krb4     => 'krb',
                    111:                      internal => 'int',
                    112:                      localuth => 'loc',
                    113:                      unix     => 'fsys',
                    114:                    );
                    115:     return %abv_auth;
                    116: }
1.43      www       117: 
1.134     raeburn   118: # ====================================================
                    119: 
                    120: sub portfolio_quota {
                    121:     my ($ccuname,$ccdomain) = @_;
                    122:     my %lt = &Apache::lonlocal::texthash(
                    123:                    'disk' => "Disk space allocated to user's portfolio files",
1.149     raeburn   124:                    'cuqu' => "Current quota",
                    125:                    'cust' => "Custom quota",
                    126:                    'defa' => "Default",
                    127:                    'chqu' => "Change quota",
1.134     raeburn   128:     );
1.149     raeburn   129:     my ($currquota,$quotatype,$inststatus,$defquota) = 
                    130:         &Apache::loncommon::get_user_quota($ccuname,$ccdomain);
                    131:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($ccdomain);
                    132:     my ($longinsttype,$showquota,$custom_on,$custom_off,$defaultinfo);
                    133:     if ($inststatus ne '') {
                    134:         if ($usertypes->{$inststatus} ne '') {
                    135:             $longinsttype = $usertypes->{$inststatus};
                    136:         }
                    137:     }
                    138:     $custom_on = ' ';
                    139:     $custom_off = ' checked="checked" ';
                    140:     my $quota_javascript = <<"END_SCRIPT";
                    141: <script type="text/javascript">
                    142: function quota_changes(caller) {
                    143:     if (caller == "custom") {
                    144:         if (document.cu.customquota[0].checked) {
                    145:             document.cu.portfolioquota.value = "";
                    146:         }
                    147:     }
                    148:     if (caller == "quota") {
                    149:         document.cu.customquota[1].checked = true;
                    150:     }
                    151: }
                    152: </script>
                    153: END_SCRIPT
                    154:     if ($quotatype eq 'custom') {
                    155:         $custom_on = $custom_off;
                    156:         $custom_off = ' ';
                    157:         $showquota = $currquota;
                    158:         if ($longinsttype eq '') {
                    159:             $defaultinfo = &mt('For this user, the default quota would be [_1]
                    160:                             Mb.',$defquota);
                    161:         } else {
                    162:             $defaultinfo = &mt("For this user, the default quota would be [_1] 
                    163:                             Mb, as determined by the user's institutional
                    164:                            affiliation ([_2]).",$defquota,$longinsttype);
                    165:         }
                    166:     } else {
                    167:         if ($longinsttype eq '') {
                    168:             $defaultinfo = &mt('For this user, the default quota is [_1]
                    169:                             Mb.',$defquota);
                    170:         } else {
                    171:             $defaultinfo = &mt("For this user, the default quota of [_1]
                    172:                             Mb, is determined by the user's institutional
                    173:                             affiliation ([_2]).",$defquota,$longinsttype);
                    174:         }
                    175:     }
                    176:     my $output = $quota_javascript.
                    177:                  '<h3>'.$lt{'disk'}.'</h3>'.
1.188     raeburn   178:                  &Apache::loncommon::start_data_table().
                    179:                  &Apache::loncommon::start_data_table_row().
                    180:                  '<td>'.$lt{'cuqu'}.': '.$currquota.'&nbsp;Mb.&nbsp;&nbsp;'.
                    181:                  $defaultinfo.'</td>'.
                    182:                  &Apache::loncommon::end_data_table_row().
                    183:                  &Apache::loncommon::start_data_table_row().
                    184:                  '<td><span class="LC_nobreak">'.$lt{'chqu'}.
1.149     raeburn   185:                  ': <label>'.
                    186:                  '<input type="radio" name="customquota" value="0" '.
                    187:                  $custom_off.' onchange="javascript:quota_changes('."'custom'".')"
                    188:                   />'.$lt{'defa'}.'&nbsp;('.$defquota.' Mb).</label>&nbsp;'.
                    189:                  '&nbsp;<label><input type="radio" name="customquota" value="1" '. 
                    190:                  $custom_on.'  onchange="javascript:quota_changes('."'custom'".')" />'.
                    191:                  $lt{'cust'}.':</label>&nbsp;'.
1.134     raeburn   192:                  '<input type="text" name="portfolioquota" size ="5" value="'.
1.149     raeburn   193:                  $showquota.'" onfocus="javascript:quota_changes('."'quota'".')" '.
1.188     raeburn   194:                  '/>&nbsp;Mb</span></td>'.
                    195:                  &Apache::loncommon::end_data_table_row().
                    196:                  &Apache::loncommon::end_data_table();
1.134     raeburn   197:     return $output;
                    198: }
                    199: 
1.2       www       200: # =================================================================== Phase one
1.1       www       201: 
1.42      matthew   202: sub print_username_entry_form {
1.207     raeburn   203:     my ($r,$context,$response,$srch,$forcenewuser) = @_;
1.101     albertel  204:     my $defdom=$env{'request.role.domain'};
1.160     raeburn   205:     my $formtoset = 'crtuser';
                    206:     if (exists($env{'form.startrolename'})) {
                    207:         $formtoset = 'docustom';
                    208:         $env{'form.rolename'} = $env{'form.startrolename'};
1.207     raeburn   209:     } elsif ($env{'form.origform'} eq 'crtusername') {
                    210:         $formtoset =  $env{'form.origform'};
1.160     raeburn   211:     }
                    212: 
                    213:     my ($jsback,$elements) = &crumb_utilities();
                    214: 
                    215:     my $jscript = &Apache::loncommon::studentbrowser_javascript()."\n".
1.165     albertel  216:         '<script type="text/javascript">'."\n".
1.160     raeburn   217:         &Apache::lonhtmlcommon::set_form_elements($elements->{$formtoset}).
1.162     raeburn   218:         '</script>'."\n";
1.160     raeburn   219: 
                    220:     my %loaditems = (
                    221:                 'onload' => "javascript:setFormElements(document.$formtoset)",
                    222:                     );
1.110     albertel  223:     my $start_page =
1.190     raeburn   224: 	&Apache::loncommon::start_page('User Management',
1.160     raeburn   225: 				       $jscript,{'add_entries' => \%loaditems,});
1.214   ! raeburn   226:     if ($env{'form.action'} eq 'custom') {
        !           227:         &Apache::lonhtmlcommon::add_breadcrumb
        !           228:           ({href=>"javascript:backPage(document.crtuser)",
        !           229:             text=>"Pick custom role",});
        !           230:     } else {
1.190     raeburn   231:         &Apache::lonhtmlcommon::add_breadcrumb
                    232:           ({href=>"javascript:backPage(document.crtuser)",
                    233:             text=>"Single user search",
                    234:             faq=>282,bug=>'Instructor Interface',});
                    235:     }
1.160     raeburn   236:     my $crumbs = &Apache::lonhtmlcommon::breadcrumbs('User Management');
1.190     raeburn   237:     my %existingroles=&Apache::lonuserutils::my_custom_roles();
1.59      www       238:     my $choice=&Apache::loncommon::select_form('make new role','rolename',
                    239: 		('make new role' => 'Generate new role ...',%existingroles));
1.71      sakharuk  240:     my %lt=&Apache::lonlocal::texthash(
1.160     raeburn   241:                     'srch' => "User Search",
                    242:                      or    => "or",
1.71      sakharuk  243: 		    'usr'  => "Username",
                    244:                     'dom'  => "Domain",
                    245:                     'ecrp' => "Edit Custom Role Privileges",
1.72      sakharuk  246:                     'nr'   => "Name of Role",
1.160     raeburn   247:                     'cre'  => "Custom Role Editor",
1.214   ! raeburn   248:                     'mod'  => "to modify user information or add/modify roles",
        !           249:                     'enrl' => "to enroll one student",
1.71      sakharuk  250: 				       );
1.122     albertel  251:     my $help = &Apache::loncommon::help_open_menu(undef,undef,282,'Instructor Interface');
1.76      www       252:     my $helpsiur=&Apache::loncommon::help_open_topic('Course_Change_Privileges');
1.213     raeburn   253:     my $helpsist=&Apache::loncommon::help_open_topic('Course_Add_Student');
1.76      www       254:     my $helpecpr=&Apache::loncommon::help_open_topic('Course_Editing_Custom_Roles');
1.160     raeburn   255:     my $sellink=&Apache::loncommon::selectstudent_link('crtuser','srchterm','srchdomain');
                    256:     if ($sellink) {
                    257:         $sellink = "$lt{'or'} ".$sellink;
                    258:     } 
1.190     raeburn   259:     $r->print($start_page."\n".$crumbs);
1.214   ! raeburn   260:     if ($env{'form.action'} eq 'custom') {
1.190     raeburn   261:         if (&Apache::lonnet::allowed('mcr','/')) {
                    262:             $r->print(<<ENDCUSTOM);
1.58      www       263: <form action="/adm/createuser" method="post" name="docustom">
1.190     raeburn   264: <input type="hidden" name="action" value="$env{'form.action'}" />
1.157     albertel  265: <input type="hidden" name="phase" value="selected_custom_edit" />
1.190     raeburn   266: <h3>$lt{'ecrp'}$helpecpr</h3>
1.72      sakharuk  267: $lt{'nr'}: $choice <input type="text" size="15" name="newrolename" /><br />
1.71      sakharuk  268: <input name="customeditor" type="submit" value="$lt{'cre'}" />
1.107     www       269: </form>
1.106     www       270: ENDCUSTOM
1.190     raeburn   271:         }
1.213     raeburn   272:     } else {
                    273:         my $actiontext = $lt{'mod'}.$helpsiur;
                    274:         if ($env{'form.action'} eq 'singlestudent') {
                    275:             $actiontext = $lt{'enrl'}.$helpsist;
                    276:         }
                    277:         $r->print("
                    278: <h3>$lt{'srch'} $sellink $actiontext</h3>");
                    279:         if ($env{'form.origform'} ne 'crtusername') {
                    280:             $r->print("\n".$response);
                    281:         }
                    282:         $r->print(&entry_form($defdom,$srch,$forcenewuser,$context,$response));
1.107     www       283:     }
1.110     albertel  284:     $r->print(&Apache::loncommon::end_page());
                    285: }
                    286: 
1.160     raeburn   287: sub entry_form {
1.214   ! raeburn   288:     my ($dom,$srch,$forcenewuser,$context,$responsemsg) = @_;
1.207     raeburn   289:     my %domconf = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
1.214   ! raeburn   290:     my $usertype;
        !           291:     if (ref($srch) eq 'HASH') {
        !           292:         if (($srch->{'srchin'} eq 'dom') &&
        !           293:             ($srch->{'srchby'} eq 'uname') &&
        !           294:             ($srch->{'srchtype'} eq 'exact') &&
        !           295:             ($srch->{'srchdomain'} ne '') &&
        !           296:             ($srch->{'srchterm'} ne '')) {
        !           297:             my ($rules,$ruleorder) =
        !           298:                 &Apache::lonnet::inst_userrules($srch->{'srchdomain'},'username');
        !           299:             $usertype = &Apache::lonuserutils::check_usertype($srch->{'srchdomain'},$srch->{'srchterm'},$rules);
        !           300:         }
1.207     raeburn   301:     }
1.214   ! raeburn   302:     my $cancreate =
        !           303:         &Apache::lonuserutils::can_create_user($dom,$context,$usertype);
1.160     raeburn   304:     my $userpicker = 
1.179     raeburn   305:        &Apache::loncommon::user_picker($dom,$srch,$forcenewuser,
1.214   ! raeburn   306:                                        'document.crtuser',$cancreate,$usertype);
1.160     raeburn   307:     my $srchbutton = &mt('Search');
1.207     raeburn   308:     my $output = <<"ENDBLOCK";
1.160     raeburn   309: <form action="/adm/createuser" method="post" name="crtuser">
1.190     raeburn   310: <input type="hidden" name="action" value="$env{'form.action'}" />
1.160     raeburn   311: <input type="hidden" name="phase" value="get_user_info" />
                    312: $userpicker
1.179     raeburn   313: <input name="userrole" type="button" value="$srchbutton" onclick="javascript:validateEntry(document.crtuser)" />
1.160     raeburn   314: </form>
1.207     raeburn   315: ENDBLOCK
1.211     raeburn   316:     if ($cancreate && $env{'form.phase'} eq '') {
1.207     raeburn   317:         my $defdom=$env{'request.role.domain'};
                    318:         my $domform = &Apache::loncommon::select_dom_form($defdom,'srchdomain');
                    319:         my $helpcrt=&Apache::loncommon::help_open_topic('Course_Change_Privileges');
                    320:         my %lt=&Apache::lonlocal::texthash(
                    321:                   'crnu' => 'Create a new user',
                    322:                   'usr'  => 'Username',
                    323:                   'dom'  => 'in domain',
                    324:                   'cra'  => 'Create user',
                    325:         );
                    326:         $output .= <<"ENDDOCUMENT";
                    327: <form action="/adm/createuser" method="post" name="crtusername">
                    328: <input type="hidden" name="action" value="$env{'form.action'}" />
                    329: <input type="hidden" name="phase" value="createnewuser" />
                    330: <input type="hidden" name="srchtype" value="exact" />
                    331: <input type="hidden" name="srchby" value="username" />
                    332: <input type="hidden" name="srchin" value="dom" />
                    333: <input type="hidden" name="forcenewuser" value="1" />
                    334: <input type="hidden" name="origform" value="crtusername" />
                    335: <h3>$lt{crnu}$helpcrt</h3>
1.214   ! raeburn   336: $responsemsg
1.207     raeburn   337: <table>
                    338:  <tr>
                    339:   <td>$lt{'usr'}:</td>
                    340:   <td><input type="text" size="15" name="srchterm" /></td>
                    341:   <td>&nbsp;$lt{'dom'}:</td><td>$domform</td>
                    342:   <td>&nbsp;<input name="userrole" type="submit" value="$lt{'cra'}" /></td>
                    343:  </tr>
                    344: </table>
                    345: </form>
1.160     raeburn   346: ENDDOCUMENT
1.207     raeburn   347:     }
1.160     raeburn   348:     return $output;
                    349: }
1.110     albertel  350: 
                    351: sub user_modification_js {
1.113     raeburn   352:     my ($pjump_def,$dc_setcourse_code,$nondc_setsection_code,$groupslist)=@_;
                    353:     
1.110     albertel  354:     return <<END;
                    355: <script type="text/javascript" language="Javascript">
                    356: 
                    357:     function pclose() {
                    358:         parmwin=window.open("/adm/rat/empty.html","LONCAPAparms",
                    359:                  "height=350,width=350,scrollbars=no,menubar=no");
                    360:         parmwin.close();
                    361:     }
                    362: 
                    363:     $pjump_def
                    364:     $dc_setcourse_code
                    365: 
                    366:     function dateset() {
                    367:         eval("document.cu."+document.cu.pres_marker.value+
                    368:             ".value=document.cu.pres_value.value");
                    369:         pclose();
                    370:     }
                    371: 
1.113     raeburn   372:     $nondc_setsection_code
                    373: 
1.110     albertel  374: </script>
                    375: END
1.2       www       376: }
                    377: 
                    378: # =================================================================== Phase two
1.160     raeburn   379: sub print_user_selection_page {
1.207     raeburn   380:     my ($r,$response,$srch,$srch_results,$operation,$srcharray,$context) = @_;
1.160     raeburn   381:     my @fields = ('username','domain','lastname','firstname','permanentemail');
                    382:     my $sortby = $env{'form.sortby'};
                    383: 
                    384:     if (!grep(/^\Q$sortby\E$/,@fields)) {
                    385:         $sortby = 'lastname';
                    386:     }
                    387: 
                    388:     my ($jsback,$elements) = &crumb_utilities();
                    389: 
                    390:     my $jscript = (<<ENDSCRIPT);
                    391: <script type="text/javascript">
                    392: function pickuser(uname,udom) {
                    393:     document.usersrchform.seluname.value=uname;
                    394:     document.usersrchform.seludom.value=udom;
                    395:     document.usersrchform.phase.value="userpicked";
                    396:     document.usersrchform.submit();
                    397: }
                    398: 
                    399: $jsback
                    400: </script>
                    401: ENDSCRIPT
                    402: 
                    403:     my %lt=&Apache::lonlocal::texthash(
1.179     raeburn   404:                                        'usrch'          => "User Search to add/modify roles",
                    405:                                        'stusrch'        => "User Search to enroll student",
                    406:                                        'usel'           => "Select a user to add/modify roles",
                    407:                                        'stusel'         => "Select a user to enroll as a student", 
1.160     raeburn   408:                                        'username'       => "username",
                    409:                                        'domain'         => "domain",
                    410:                                        'lastname'       => "last name",
                    411:                                        'firstname'      => "first name",
                    412:                                        'permanentemail' => "permanent e-mail",
                    413:                                       );
1.214   ! raeburn   414:     $r->print(&Apache::loncommon::start_page('User Management',$jscript));
1.190     raeburn   415:     if ($operation eq 'createuser') {
1.179     raeburn   416:         &Apache::lonhtmlcommon::add_breadcrumb
                    417:             ({href=>"javascript:backPage(document.usersrchform,'','')",
1.190     raeburn   418:               text=>"Create/modify user",
1.179     raeburn   419:               faq=>282,bug=>'Instructor Interface',},
                    420:              {href=>"javascript:backPage(document.usersrchform,'get_user_info','select')",
                    421:               text=>"Select User",
                    422:               faq=>282,bug=>'Instructor Interface',});
                    423:         $r->print(&Apache::lonhtmlcommon::breadcrumbs('User Management'));
                    424:         $r->print("<b>$lt{'usrch'}</b><br />");
1.207     raeburn   425:         $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context));
1.179     raeburn   426:         $r->print('<h3>'.$lt{'usel'}.'</h3>');
1.214   ! raeburn   427:     } elsif ($operation eq 'enrollstudent') {
        !           428:         &Apache::lonhtmlcommon::add_breadcrumb
        !           429:             ({href=>"javascript:backPage(document.usersrchform,'','')",
        !           430:               text=>"Create/modify student",
        !           431:               faq=>282,bug=>'Instructor Interface',},
        !           432:              {href=>"javascript:backPage(document.usersrchform,'get_user_info','select')",
        !           433:               text=>"Select Student",
        !           434:               faq=>282,bug=>'Instructor Interface',});
        !           435:         $r->print(&Apache::lonhtmlcommon::breadcrumbs('User Management'));
1.179     raeburn   436:         $r->print($jscript."<b>$lt{'stusrch'}</b><br />");
1.214   ! raeburn   437:         $r->print(&entry_form($srch->{'srchdomain'},$srch,undef,$context));
1.179     raeburn   438:         $r->print('</form><h3>'.$lt{'stusel'}.'</h3>');
                    439:     }
1.160     raeburn   440:     $r->print('<form name="usersrchform" method="post">'.
                    441:               &Apache::loncommon::start_data_table()."\n".
                    442:               &Apache::loncommon::start_data_table_header_row()."\n".
                    443:               ' <th> </th>'."\n");
                    444:     foreach my $field (@fields) {
                    445:         $r->print(' <th><a href="javascript:document.usersrchform.sortby.value='.
                    446:                   "'".$field."'".';document.usersrchform.submit();">'.
                    447:                   $lt{$field}.'</a></th>'."\n");
                    448:     }
                    449:     $r->print(&Apache::loncommon::end_data_table_header_row());
                    450: 
                    451:     my @sorted_users = sort {
1.167     albertel  452:         lc($srch_results->{$a}->{$sortby})   cmp lc($srch_results->{$b}->{$sortby})
1.160     raeburn   453:             ||
1.167     albertel  454:         lc($srch_results->{$a}->{lastname})  cmp lc($srch_results->{$b}->{lastname})
1.160     raeburn   455:             ||
                    456:         lc($srch_results->{$a}->{firstname}) cmp lc($srch_results->{$b}->{firstname})
1.167     albertel  457: 	    ||
                    458: 	lc($a) cmp lc($b)
1.160     raeburn   459:         } (keys(%$srch_results));
                    460: 
                    461:     foreach my $user (@sorted_users) {
                    462:         my ($uname,$udom) = split(/:/,$user);
                    463:         $r->print(&Apache::loncommon::start_data_table_row().
                    464:                   '<td><input type="button" name="seluser" value="'.&mt('Select').'" onclick="javascript:pickuser('."'".$uname."'".','."'".$udom."'".')" /></td>'.
                    465:                   '<td><tt>'.$uname.'</tt></td>'.
                    466:                   '<td><tt>'.$udom.'</tt></td>');
                    467:         foreach my $field ('lastname','firstname','permanentemail') {
                    468:             $r->print('<td>'.$srch_results->{$user}->{$field}.'</td>');
                    469:         }
                    470:         $r->print(&Apache::loncommon::end_data_table_row());
                    471:     }
                    472:     $r->print(&Apache::loncommon::end_data_table().'<br /><br />');
1.179     raeburn   473:     if (ref($srcharray) eq 'ARRAY') {
                    474:         foreach my $item (@{$srcharray}) {
                    475:             $r->print('<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n");
                    476:         }
                    477:     }
1.160     raeburn   478:     $r->print(' <input type="hidden" name="sortby" value="'.$sortby.'" />'."\n".
                    479:               ' <input type="hidden" name="seluname" value="" />'."\n".
                    480:               ' <input type="hidden" name="seludom" value="" />'."\n".
1.179     raeburn   481:               ' <input type="hidden" name="currstate" value="select" />'."\n".
1.190     raeburn   482:               ' <input type="hidden" name="phase" value="get_user_info" />'."\n".
1.214   ! raeburn   483:               ' <input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n");
        !           484:     $r->print($response.'</form>'.&Apache::loncommon::end_page());
1.160     raeburn   485: }
                    486: 
                    487: sub print_user_query_page {
1.179     raeburn   488:     my ($r,$caller) = @_;
1.160     raeburn   489: # FIXME - this is for a network-wide name search (similar to catalog search)
                    490: # To use frames with similar behavior to catalog/portfolio search.
                    491: # To be implemented. 
                    492:     return;
                    493: }
                    494: 
1.42      matthew   495: sub print_user_modification_page {
1.196     raeburn   496:     my ($r,$ccuname,$ccdomain,$srch,$response,$context) = @_;
1.185     raeburn   497:     if (($ccuname eq '') || ($ccdomain eq '')) {
                    498:         my $usermsg = &mt('No username and/or domain provided.'); 
1.207     raeburn   499: 	&print_username_entry_form($r,$context,$usermsg);
1.58      www       500:         return;
                    501:     }
1.213     raeburn   502:     my ($form,$formname);
                    503:     if ($env{'form.action'} eq 'singlestudent') {
                    504:         $form = 'document.enrollstudent';
                    505:         $formname = 'enrollstudent';
                    506:     } else {
                    507:         $form = 'document.cu';
                    508:         $formname = 'cu';
                    509:     }
1.188     raeburn   510:     my %abv_auth = &auth_abbrev();
1.193     raeburn   511:     my ($curr_authtype,%rulematch,%inst_results,$curr_kerb_ver,$newuser,
1.196     raeburn   512:         %alerts,%curr_rules,%got_rules);
1.185     raeburn   513:     my $uhome=&Apache::lonnet::homeserver($ccuname,$ccdomain);
                    514:     if ($uhome eq 'no_host') {
1.188     raeburn   515:         $newuser = 1;
1.193     raeburn   516:         my $checkhash;
                    517:         my $checks = { 'username' => 1 };
1.196     raeburn   518:         $checkhash->{$ccuname.':'.$ccdomain} = { 'newuser' => $newuser };
1.193     raeburn   519:         &Apache::loncommon::user_rule_check($checkhash,$checks,
1.196     raeburn   520:             \%alerts,\%rulematch,\%inst_results,\%curr_rules,\%got_rules);
                    521:         if (ref($alerts{'username'}) eq 'HASH') {
                    522:             if (ref($alerts{'username'}{$ccdomain}) eq 'HASH') {
                    523:                 my $domdesc =
1.193     raeburn   524:                     &Apache::lonnet::domain($ccdomain,'description');
1.196     raeburn   525:                 if ($alerts{'username'}{$ccdomain}{$ccuname}) {
                    526:                     my $userchkmsg;
                    527:                     if (ref($curr_rules{$ccdomain}) eq 'HASH') {  
                    528:                         $userchkmsg = 
                    529:                             &Apache::loncommon::instrule_disallow_msg('username',
1.193     raeburn   530:                                                                  $domdesc,1).
                    531:                         &Apache::loncommon::user_rule_formats($ccdomain,
                    532:                             $domdesc,$curr_rules{$ccdomain}{'username'},
                    533:                             'username');
1.196     raeburn   534:                     }
1.207     raeburn   535:                     &print_username_entry_form($r,$context,$userchkmsg);
1.196     raeburn   536:                     return;
                    537:                 } 
1.193     raeburn   538:             }
1.185     raeburn   539:         }
1.187     raeburn   540:     } else {
1.188     raeburn   541:         $newuser = 0;
                    542:         my $currentauth = 
1.187     raeburn   543:             &Apache::lonnet::queryauthenticate($ccuname,$ccdomain);
1.188     raeburn   544:         if ($currentauth =~ /^(krb4|krb5|unix|internal|localauth):/) {	
                    545:             $curr_authtype = $abv_auth{$1};
                    546:             if ($currentauth =~ /^krb(4|5)/) {
                    547:                 $curr_kerb_ver = $1;
                    548:             }
                    549:         }
1.185     raeburn   550:     }
1.160     raeburn   551:     if ($response) {
                    552:         $response = '<br />'.$response
                    553:     }
1.101     albertel  554:     my $defdom=$env{'request.role.domain'};
1.48      albertel  555: 
                    556:     my ($krbdef,$krbdefdom) =
                    557:        &Apache::loncommon::get_kerberos_defaults($defdom);
                    558: 
1.31      matthew   559:     my %param = ( formname => 'document.cu',
1.48      albertel  560:                   kerb_def_dom => $krbdefdom,
1.187     raeburn   561:                   kerb_def_auth => $krbdef,
                    562:                   curr_authtype => $curr_authtype,
1.188     raeburn   563:                   curr_kerb_ver => $curr_kerb_ver,
1.187     raeburn   564:                   domain => $ccdomain,
1.160     raeburn   565:                 );
1.31      matthew   566:     $loginscript  = &Apache::loncommon::authform_header(%param);
1.48      albertel  567:     $authformkrb  = &Apache::loncommon::authform_kerberos(%param);
1.149     raeburn   568: 
1.52      matthew   569:     my $pjump_def = &Apache::lonhtmlcommon::pjump_javascript_definition();
1.88      raeburn   570:     my $dc_setcourse_code = '';
1.119     raeburn   571:     my $nondc_setsection_code = '';                                        
                    572: 
1.112     albertel  573:     my %loaditem;
1.114     albertel  574: 
                    575:     my $groupslist;
1.117     raeburn   576:     my %curr_groups = &Apache::longroup::coursegroups();
1.114     albertel  577:     if (%curr_groups) {
1.113     raeburn   578:         $groupslist = join('","',sort(keys(%curr_groups)));
                    579:         $groupslist = '"'.$groupslist.'"';   
                    580:     }
1.114     albertel  581: 
1.139     albertel  582:     if ($env{'request.role'} =~ m-^dc\./($match_domain)/$-) {
1.88      raeburn   583:         my $dcdom = $1;
1.119     raeburn   584:         $loaditem{'onload'} = "document.cu.coursedesc.value='';";
                    585:         my @rolevals = ('st','ta','ep','in','cc');
                    586:         my (@crsroles,@grproles);
                    587:         for (my $i=0; $i<@rolevals; $i++) {
1.120     raeburn   588:             $crsroles[$i]=&Apache::lonnet::plaintext($rolevals[$i],'Course');
                    589:             $grproles[$i]=&Apache::lonnet::plaintext($rolevals[$i],'Group');
1.119     raeburn   590:         }
                    591:         my $rolevalslist = join('","',@rolevals);
                    592:         my $crsrolenameslist = join('","',@crsroles);
                    593:         my $grprolenameslist = join('","',@grproles);
                    594:         my $pickcrsfirst = '<--'.&mt('Pick course first');
                    595:         my $pickgrpfirst = '<--'.&mt('Pick group first'); 
1.88      raeburn   596:         $dc_setcourse_code = <<"ENDSCRIPT";
                    597:     function setCourse() {
                    598:         var course = document.cu.dccourse.value;
                    599:         if (course != "") {
                    600:             if (document.cu.dcdomain.value != document.cu.origdom.value) {
                    601:                 alert("You must select a course in the current domain");
                    602:                 return;
                    603:             } 
                    604:             var userrole = document.cu.role.options[document.cu.role.selectedIndex].value
1.91      raeburn   605:             var section="";
1.88      raeburn   606:             var numsections = 0;
1.116     raeburn   607:             var newsecs = new Array();
1.89      raeburn   608:             for (var i=0; i<document.cu.currsec.length; i++) {
                    609:                 if (document.cu.currsec.options[i].selected == true ) {
                    610:                     if (document.cu.currsec.options[i].value != "" && document.cu.currsec.options[i].value != null) { 
                    611:                         if (numsections == 0) {
                    612:                             section = document.cu.currsec.options[i].value
                    613:                             numsections = 1;
                    614:                         }
                    615:                         else {
                    616:                             section = section + "," +  document.cu.currsec.options[i].value
                    617:                             numsections ++;
1.88      raeburn   618:                         }
                    619:                     }
                    620:                 }
1.89      raeburn   621:             }
                    622:             if (document.cu.newsec.value != "" && document.cu.newsec.value != null) {
                    623:                 if (numsections == 0) {
                    624:                     section = document.cu.newsec.value
                    625:                 }
                    626:                 else {
                    627:                     section = section + "," +  document.cu.newsec.value
1.88      raeburn   628:                 }
1.116     raeburn   629:                 newsecs = document.cu.newsec.value.split(/,/g);
                    630:                 numsections = numsections + newsecs.length;
1.89      raeburn   631:             }
                    632:             if ((userrole == 'st') && (numsections > 1)) {
                    633:                 alert("In each course, each user may only have one student role at a time. You had selected "+numsections+" sections.\\nPlease modify your selections so they include no more than one section.")
                    634:                 return;
                    635:             }
1.116     raeburn   636:             for (var j=0; j<newsecs.length; j++) {
                    637:                 if ((newsecs[j] == 'all') || (newsecs[j] == 'none')) {
                    638:                     alert("'"+newsecs[j]+"' may not be used as the name for a section, as it is a reserved word.\\nPlease choose a different section name.");
1.113     raeburn   639:                     return;
                    640:                 }
                    641:                 if (document.cu.groups.value != '') {
                    642:                     var groups = document.cu.groups.value.split(/,/g);
                    643:                     for (var k=0; k<groups.length; k++) {
1.116     raeburn   644:                         if (newsecs[j] == groups[k]) {
                    645:                             alert("'"+newsecs[j]+"' may not be used as the name for a section, as it is the name of a course group.\\nSection names and group names must be distinct. Please choose a different section name.");
1.113     raeburn   646:                             return; 
                    647:                         }
                    648:                     }
                    649:                 }
                    650:             }
1.89      raeburn   651:             if ((userrole == 'cc') && (numsections > 0)) {
                    652:                 alert("Section designations do not apply to Course Coordinator roles.\\nA course coordinator role will be added with access to all sections.");
                    653:                 section = "";
1.88      raeburn   654:             }
1.131     raeburn   655:             var coursename = "_$dcdom"+"_"+course+"_"+userrole
1.88      raeburn   656:             var numcourse = getIndex(document.cu.dccourse);
                    657:             if (numcourse == "-1") {
                    658:                 alert("There was a problem with your course selection");
                    659:                 return
                    660:             }
1.131     raeburn   661:             else {
                    662:                 document.cu.elements[numcourse].name = "act"+coursename;
                    663:                 var numnewsec = getIndex(document.cu.newsec);
                    664:                 if (numnewsec != "-1") {
                    665:                     document.cu.elements[numnewsec].name = "sec"+coursename;
                    666:                     document.cu.elements[numnewsec].value = section;
                    667:                 }
                    668:                 var numstart = getIndex(document.cu.start);
                    669:                 if (numstart != "-1") {
                    670:                     document.cu.elements[numstart].name = "start"+coursename;
                    671:                 }
                    672:                 var numend = getIndex(document.cu.end);
                    673:                 if (numend != "-1") {
                    674:                     document.cu.elements[numend].name = "end"+coursename
                    675:                 }
1.88      raeburn   676:             }
                    677:         }
                    678:         document.cu.submit();
                    679:     }
                    680: 
                    681:     function getIndex(caller) {
                    682:         for (var i=0;i<document.cu.elements.length;i++) {
                    683:             if (document.cu.elements[i] == caller) {
                    684:                 return i;
                    685:             }
                    686:         }
                    687:         return -1;
                    688:     }
                    689: ENDSCRIPT
1.113     raeburn   690:     } else {
1.202     raeburn   691:         $nondc_setsection_code = 
1.198     raeburn   692:             &Apache::lonuserutils::setsections_javascript('cu',$groupslist);
1.88      raeburn   693:     }
1.113     raeburn   694:     my $js = &user_modification_js($pjump_def,$dc_setcourse_code,
                    695:                                    $nondc_setsection_code,$groupslist);
1.160     raeburn   696: 
                    697:     my ($jsback,$elements) = &crumb_utilities();
1.188     raeburn   698:     my $javascript_validations;
                    699:     if ((&Apache::lonnet::allowed('mau',$ccdomain)) || ($uhome eq 'no_host')) {
                    700:         my ($krbdef,$krbdefdom) =
                    701:             &Apache::loncommon::get_kerberos_defaults($ccdomain);
                    702:         $javascript_validations = 
1.190     raeburn   703:             &Apache::lonuserutils::javascript_validations('auth',$krbdefdom,undef,
1.188     raeburn   704:                                                         undef,$ccdomain);
                    705:     }
1.160     raeburn   706:     $js .= "\n".
1.188     raeburn   707:        '<script type="text/javascript">'."\n".$jsback."\n".
                    708:        $javascript_validations.'</script>';
1.110     albertel  709:     my $start_page = 
1.190     raeburn   710: 	&Apache::loncommon::start_page('User Management',
1.112     albertel  711: 				       $js,{'add_entries' => \%loaditem,});
1.160     raeburn   712:     &Apache::lonhtmlcommon::add_breadcrumb
                    713:      ({href=>"javascript:backPage(document.cu)",
1.190     raeburn   714:        text=>"Create/modify user",
1.160     raeburn   715:        faq=>282,bug=>'Instructor Interface',});
                    716: 
                    717:     if ($env{'form.phase'} eq 'userpicked') {
                    718:         &Apache::lonhtmlcommon::add_breadcrumb
                    719:      ({href=>"javascript:backPage(document.cu,'get_user_info','select')",
                    720:        text=>"Select a user",
                    721:        faq=>282,bug=>'Instructor Interface',});
                    722:     }
                    723:     &Apache::lonhtmlcommon::add_breadcrumb
                    724:       ({href=>"javascript:backPage(document.cu,'$env{'form.phase'}','modify')",
                    725:         text=>"Set user role",
                    726:         faq=>282,bug=>'Instructor Interface',});
                    727:     my $crumbs = &Apache::lonhtmlcommon::breadcrumbs('User Management');
1.3       www       728: 
1.25      matthew   729:     my $forminfo =<<"ENDFORMINFO";
                    730: <form action="/adm/createuser" method="post" name="cu">
1.190     raeburn   731: <input type="hidden" name="phase" value="update_user_data" />
1.188     raeburn   732: <input type="hidden" name="ccuname" value="$ccuname" />
                    733: <input type="hidden" name="ccdomain" value="$ccdomain" />
1.157     albertel  734: <input type="hidden" name="pres_value"  value="" />
                    735: <input type="hidden" name="pres_type"   value="" />
                    736: <input type="hidden" name="pres_marker" value="" />
1.25      matthew   737: ENDFORMINFO
1.2       www       738:     my %inccourses;
1.135     raeburn   739:     foreach my $key (keys(%env)) {
1.139     albertel  740: 	if ($key=~/^user\.priv\.cm\.\/($match_domain)\/($match_username)/) {
1.2       www       741: 	    $inccourses{$1.'_'.$2}=1;
                    742:         }
1.24      matthew   743:     }
1.2       www       744:     if ($uhome eq 'no_host') {
1.134     raeburn   745:         my $portfolioform;
                    746:         if (&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) {
                    747:             # Current user has quota modification privileges
1.188     raeburn   748:             $portfolioform = '<br />'.&portfolio_quota($ccuname,$ccdomain);
1.134     raeburn   749:         }
1.187     raeburn   750:         &initialize_authen_forms($ccdomain);
1.188     raeburn   751:         my %lt=&Apache::lonlocal::texthash(
                    752:                 'cnu'            => 'Create New User',
1.213     raeburn   753:                 'ast'            => 'as a student',
1.188     raeburn   754:                 'ind'            => 'in domain',
                    755:                 'lg'             => 'Login Data',
1.190     raeburn   756:                 'hs'             => "Home Server",
1.188     raeburn   757:         );
1.185     raeburn   758: 	$r->print(<<ENDTITLE);
1.110     albertel  759: $start_page
1.160     raeburn   760: $crumbs
                    761: $response
1.25      matthew   762: $forminfo
1.31      matthew   763: <script type="text/javascript" language="Javascript">
1.20      harris41  764: $loginscript
1.31      matthew   765: </script>
1.20      harris41  766: <input type='hidden' name='makeuser' value='1' />
1.193     raeburn   767: <h2>$lt{'cnu'} "$ccuname" $lt{'ind'} $ccdomain</h2>
1.185     raeburn   768: ENDTITLE
1.213     raeburn   769:         if ($env{'form.action'} eq 'singlestudent') {
                    770:             $r->print(' ('.$lt{'ast'}.')');
                    771:         }
                    772:         $r->print('</h2>'."\n".'<div class="LC_left_float">');
1.206     raeburn   773:         my $personal_table = 
1.210     raeburn   774:             &personal_data_display($ccuname,$ccdomain,$newuser,$context,
                    775:                                    $inst_results{$ccuname.':'.$ccdomain});
1.206     raeburn   776:         $r->print($personal_table);
1.187     raeburn   777:         my ($home_server_pick,$numlib) = 
                    778:             &Apache::loncommon::home_server_form_item($ccdomain,'hserver',
                    779:                                                       'default','hide');
                    780:         if ($numlib > 1) {
                    781:             $r->print("
1.185     raeburn   782: <br />
1.187     raeburn   783: $lt{'hs'}: $home_server_pick
                    784: <br />");
                    785:         } else {
                    786:             $r->print($home_server_pick);
                    787:         }
1.188     raeburn   788:         $r->print('</div>'."\n".'<div class="LC_left_float"><h3>'.
                    789:                   $lt{'lg'}.'</h3>');
1.185     raeburn   790:         my ($fixedauth,$varauth,$authmsg); 
1.193     raeburn   791:         if (ref($rulematch{$ccuname.':'.$ccdomain}) eq 'HASH') {
                    792:             my $matchedrule = $rulematch{$ccuname.':'.$ccdomain}{'username'};
                    793:             my ($rules,$ruleorder) = 
                    794:                 &Apache::lonnet::inst_userrules($ccdomain,'username');
1.185     raeburn   795:             if (ref($rules) eq 'HASH') {
1.193     raeburn   796:                 if (ref($rules->{$matchedrule}) eq 'HASH') {
                    797:                     my $authtype = $rules->{$matchedrule}{'authtype'};
1.185     raeburn   798:                     if ($authtype !~ /^(krb4|krb5|int|fsys|loc)$/) {
1.190     raeburn   799:                         $r->print(&Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc));
1.185     raeburn   800:                     } else { 
1.193     raeburn   801:                         my $authparm = $rules->{$matchedrule}{'authparm'};
1.185     raeburn   802:                         if ($authtype =~ /^krb(4|5)$/) {
                    803:                             my $ver = $1;
                    804:                             if ($authparm ne '') {
                    805:                                 $fixedauth = <<"KERB"; 
                    806: <input type="hidden" name="login" value="krb" />
                    807: <input type="hidden" name="krbver" value="$ver" />
                    808: <input type="hidden" name="krbarg" value="$authparm" />
                    809: KERB
1.193     raeburn   810:                                 $authmsg = $rules->{$matchedrule}{'authmsg'};    
1.185     raeburn   811:                             }
                    812:                         } else {
                    813:                             $fixedauth = 
                    814: '<input type="hidden" name="login" value="'.$authtype.'" />'."\n";
1.193     raeburn   815:                             if ($rules->{$matchedrule}{'authparmfixed'}) {
1.185     raeburn   816:                                 $fixedauth .=    
                    817: '<input type="hidden" name="'.$authtype.'arg" value="'.$authparm.'" />'."\n";
                    818:                             } else {
                    819:                                 $varauth =  
                    820: '<input type="text" name="'.$authtype.'arg" value="" />'."\n";
                    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.213     raeburn   838:         $r->print('</h2>'."\n".'<div class="LC_left_float">');
                    839:     } else { # user already exist-
1.79      albertel  840: 	my %lt=&Apache::lonlocal::texthash(
1.191     raeburn   841:                     'cup'  => "Modify existing user: ",
1.213     raeburn   842:                     'ens'  => "Enroll one student: ",
1.72      sakharuk  843:                     'id'   => "in domain",
                    844: 				       );
1.26      matthew   845: 	$r->print(<<ENDCHANGEUSER);
1.110     albertel  846: $start_page
1.160     raeburn   847: $crumbs
1.25      matthew   848: $forminfo
1.213     raeburn   849: <h2>
1.26      matthew   850: ENDCHANGEUSER
1.213     raeburn   851:         if ($env{'form.action'} eq 'singlestudent') {
                    852:             $r->print($lt{'ens'});
                    853:         } else {
                    854:             $r->print($lt{'cup'});
                    855:         }
                    856:         $r->print(' "'.$ccuname.'" '.$lt{'id'}.' "'.$ccdomain.'"</h2>'.
                    857:                   "\n".'<div class="LC_left_float">');
1.206     raeburn   858:         my ($personal_table,$showforceid) = 
1.210     raeburn   859:             &personal_data_display($ccuname,$ccdomain,$newuser,$context,
                    860:                                    $inst_results{$ccuname.':'.$ccdomain});
1.206     raeburn   861:         $r->print($personal_table);
                    862:         if ($showforceid) {
1.203     raeburn   863:             $r->print(&Apache::lonuserutils::forceid_change($context));
1.199     raeburn   864:         }
                    865:         $r->print('</div>');
1.188     raeburn   866:         my $user_auth_text = 
                    867:             &user_authentication($ccuname,$ccdomain,$krbdefdom,\%abv_auth);
                    868:         my $user_quota_text;
                    869:         if (&Apache::lonnet::allowed('mpq',$ccdomain)) {
                    870:             # Current user has quota modification privileges
                    871:             $user_quota_text = &portfolio_quota($ccuname,$ccdomain);
                    872:         } elsif (&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) {
                    873:             # Get the user's portfolio information
                    874:             my %portq = &Apache::lonnet::get('environment',['portfolioquota'],
                    875:                                              $ccdomain,$ccuname);
                    876: 
                    877:             my %lt=&Apache::lonlocal::texthash(
                    878:                 'dska'  => "Disk space allocated to user's portfolio files",
                    879:                 'youd'  => "You do not have privileges to modify the portfolio quota for this user.",
                    880:                 'ichr'  => "If a change is required, contact a domain coordinator for the domain",
                    881:             );
                    882:             $user_quota_text = <<ENDNOPORTPRIV;
                    883: <h3>$lt{'dska'}</h3>
                    884: $lt{'youd'} $lt{'ichr'}: $ccdomain
                    885: ENDNOPORTPRIV
                    886:         }
                    887:         if ($user_auth_text ne '') {
                    888:             $r->print('<div class="LC_left_float">'.$user_auth_text);
                    889:             if ($user_quota_text ne '') {
                    890:                 $r->print($user_quota_text);
                    891:             }
1.213     raeburn   892:             if ($env{'form.action'} eq 'singlestudent') {
                    893:                 $r->print(&date_sections_select($context,$newuser,$formname));
                    894:             }
1.188     raeburn   895:         } elsif ($user_quota_text ne '') {
1.213     raeburn   896:             $r->print('<div class="LC_left_float">'.$user_quota_text);
                    897:             if ($env{'form.action'} eq 'singlestudent') {
                    898:                 $r->print(&date_sections_select($context,$newuser,$formname));
                    899:             }
                    900:         } else {
                    901:             if ($env{'form.action'} eq 'singlestudent') {
                    902:                 $r->print('<div class="LC_left_float">'.
                    903:                           &date_sections_select($context,$newuser,$formname));
                    904:             }
1.188     raeburn   905:         }
1.213     raeburn   906:         $r->print('</div><div class="LC_clear_float_footer"></div>');
1.28      matthew   907:         my %rolesdump=&Apache::lonnet::dump('roles',$ccdomain,$ccuname);
1.25      matthew   908:         # Build up table of user roles to allow revocation of a role.
1.28      matthew   909:         my ($tmp) = keys(%rolesdump);
                    910:         unless ($tmp =~ /^(con_lost|error)/i) {
1.2       www       911:            my $now=time;
1.72      sakharuk  912: 	   my %lt=&Apache::lonlocal::texthash(
1.191     raeburn   913: 		    'rer'  => "Existing Roles",
1.72      sakharuk  914:                     'rev'  => "Revoke",                    
                    915:                     'del'  => "Delete",
1.81      albertel  916: 		    'ren'  => "Re-Enable",
1.72      sakharuk  917:                     'rol'  => "Role",
                    918:                     'ext'  => "Extent",
                    919:                     'sta'  => "Start",
                    920:                     'end'  => "End"
                    921: 				       );
1.89      raeburn   922:            my (%roletext,%sortrole,%roleclass,%rolepriv);
1.67      albertel  923: 	   foreach my $area (sort { my $a1=join('_',(split('_',$a))[1,0]);
                    924: 				    my $b1=join('_',(split('_',$b))[1,0]);
                    925: 				    return $a1 cmp $b1;
                    926: 				} keys(%rolesdump)) {
1.37      matthew   927:                next if ($area =~ /^rolesdef/);
1.79      albertel  928: 	       my $envkey=$area;
1.37      matthew   929:                my $role = $rolesdump{$area};
                    930:                my $thisrole=$area;
                    931:                $area =~ s/\_\w\w$//;
                    932:                my ($role_code,$role_end_time,$role_start_time) = 
                    933:                    split(/_/,$role);
1.64      www       934: # Is this a custom role? Get role owner and title.
                    935: 	       my ($croleudom,$croleuname,$croletitle)=
1.139     albertel  936: 	           ($role_code=~m{^cr/($match_domain)/($match_username)/(\w+)$});
1.37      matthew   937:                my $allowed=0;
1.53      www       938:                my $delallowed=0;
1.79      albertel  939: 	       my $sortkey=$role_code;
                    940: 	       my $class='Unknown';
1.141     albertel  941:                if ($area =~ m{^/($match_domain)/($match_courseid)} ) {
1.79      albertel  942: 		   $class='Course';
1.57      matthew   943:                    my ($coursedom,$coursedir) = ($1,$2);
1.130     albertel  944: 		   $sortkey.="\0$coursedom";
1.57      matthew   945:                    # $1.'_'.$2 is the course id (eg. 103_12345abcef103l3).
1.37      matthew   946:                    my %coursedata=
                    947:                        &Apache::lonnet::coursedescription($1.'_'.$2);
1.51      albertel  948: 		   my $carea;
                    949: 		   if (defined($coursedata{'description'})) {
1.79      albertel  950: 		       $carea=$coursedata{'description'}.
1.72      sakharuk  951:                            '<br />'.&mt('Domain').': '.$coursedom.('&nbsp;'x8).
1.57      matthew   952:      &Apache::loncommon::syllabuswrapper('Syllabus',$coursedir,$coursedom);
1.79      albertel  953: 		       $sortkey.="\0".$coursedata{'description'};
1.119     raeburn   954:                        $class=$coursedata{'type'};
1.51      albertel  955: 		   } else {
1.72      sakharuk  956: 		       $carea=&mt('Unavailable course').': '.$area;
1.86      albertel  957: 		       $sortkey.="\0".&mt('Unavailable course').': '.$area;
1.51      albertel  958: 		   }
1.130     albertel  959: 		   $sortkey.="\0$coursedir";
1.37      matthew   960:                    $inccourses{$1.'_'.$2}=1;
1.53      www       961:                    if ((&Apache::lonnet::allowed('c'.$role_code,$1.'/'.$2)) ||
                    962:                        (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
1.37      matthew   963:                        $allowed=1;
                    964:                    }
1.53      www       965:                    if ((&Apache::lonnet::allowed('dro',$1)) ||
                    966:                        (&Apache::lonnet::allowed('dro',$ccdomain))) {
                    967:                        $delallowed=1;
                    968:                    }
1.64      www       969: # - custom role. Needs more info, too
                    970: 		   if ($croletitle) {
                    971: 		       if (&Apache::lonnet::allowed('ccr',$1.'/'.$2)) {
                    972: 			   $allowed=1;
                    973: 			   $thisrole.='.'.$role_code;
                    974: 		       }
                    975: 		   }
1.37      matthew   976:                    # Compute the background color based on $area
1.141     albertel  977:                    if ($area=~m{^/($match_domain)/($match_courseid)/(\w+)}) {
1.113     raeburn   978:                        $carea.='<br />Section: '.$3;
1.87      albertel  979: 		       $sortkey.="\0$3";
1.37      matthew   980:                    }
                    981:                    $area=$carea;
                    982:                } else {
1.79      albertel  983: 		   $sortkey.="\0".$area;
1.37      matthew   984:                    # Determine if current user is able to revoke privileges
1.139     albertel  985:                    if ($area=~m{^/($match_domain)/}) {
1.53      www       986:                        if ((&Apache::lonnet::allowed('c'.$role_code,$1)) ||
                    987:                        (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
1.37      matthew   988:                            $allowed=1;
                    989:                        }
1.53      www       990:                        if (((&Apache::lonnet::allowed('dro',$1))  ||
                    991:                             (&Apache::lonnet::allowed('dro',$ccdomain))) &&
                    992:                            ($role_code ne 'dc')) {
                    993:                            $delallowed=1;
                    994:                        }
1.37      matthew   995:                    } else {
                    996:                        if (&Apache::lonnet::allowed('c'.$role_code,'/')) {
                    997:                            $allowed=1;
                    998:                        }
                    999:                    }
1.79      albertel 1000: 		   if ($role_code eq 'ca' || $role_code eq 'au') {
                   1001: 		       $class='Construction Space';
                   1002: 		   } elsif ($role_code eq 'su') {
                   1003: 		       $class='System';
                   1004: 		   } else {
                   1005: 		       $class='Domain';
                   1006: 		   }
1.37      matthew  1007:                }
1.105     www      1008:                if (($role_code eq 'ca') || ($role_code eq 'aa')) {
1.139     albertel 1009:                    $area=~m{/($match_domain)/($match_username)};
1.209     raeburn  1010: 		   if (&Apache::lonuserutils::authorpriv($2,$1)) {
1.43      www      1011: 		       $allowed=1;
                   1012:                    } else {
                   1013:                        $allowed=0;
1.37      matthew  1014:                    }
                   1015:                }
                   1016:                my $row = '';
1.137     raeburn  1017:                $row.= '<td>';
1.37      matthew  1018:                my $active=1;
                   1019:                $active=0 if (($role_end_time) && ($now>$role_end_time));
                   1020:                if (($active) && ($allowed)) {
1.157     albertel 1021:                    $row.= '<input type="checkbox" name="rev:'.$thisrole.'" />';
1.37      matthew  1022:                } else {
1.56      www      1023:                    if ($active) {
                   1024:                       $row.='&nbsp;';
                   1025: 		   } else {
1.72      sakharuk 1026:                       $row.=&mt('expired or revoked');
1.56      www      1027: 		   }
1.37      matthew  1028:                }
1.53      www      1029: 	       $row.='</td><td>';
1.81      albertel 1030:                if ($allowed && !$active) {
1.157     albertel 1031:                    $row.= '<input type="checkbox" name="ren:'.$thisrole.'" />';
1.81      albertel 1032:                } else {
                   1033:                    $row.='&nbsp;';
                   1034:                }
                   1035: 	       $row.='</td><td>';
1.53      www      1036:                if ($delallowed) {
1.157     albertel 1037:                    $row.= '<input type="checkbox" name="del:'.$thisrole.'" />';
1.53      www      1038:                } else {
                   1039:                    $row.='&nbsp;';
                   1040:                }
1.64      www      1041: 	       my $plaintext='';
1.150     banghart 1042: 	       if (!$croletitle) {
1.120     raeburn  1043:                    $plaintext=&Apache::lonnet::plaintext($role_code,$class)
1.64      www      1044: 	       } else {
                   1045: 	           $plaintext=
1.188     raeburn  1046: 		"Customrole '$croletitle'<br />defined by $croleuname\@$croleudom";
1.64      www      1047: 	       }
                   1048:                $row.= '</td><td>'.$plaintext.
1.37      matthew  1049:                       '</td><td>'.$area.
                   1050:                       '</td><td>'.($role_start_time?localtime($role_start_time)
                   1051:                                                    : '&nbsp;' ).
                   1052:                       '</td><td>'.($role_end_time  ?localtime($role_end_time)
                   1053:                                                    : '&nbsp;' )
1.137     raeburn  1054:                       ."</td>";
1.79      albertel 1055: 	       $sortrole{$sortkey}=$envkey;
                   1056: 	       $roletext{$envkey}=$row;
                   1057: 	       $roleclass{$envkey}=$class;
1.89      raeburn  1058:                $rolepriv{$envkey}=$allowed;
1.79      albertel 1059:                #$r->print($row);
1.28      matthew  1060:            } # end of foreach        (table building loop)
1.89      raeburn  1061:            my $rolesdisplay = 0;
                   1062:            my %output = ();
1.119     raeburn  1063: 	   foreach my $type ('Construction Space','Course','Group','Domain','System','Unknown') {
1.89      raeburn  1064: 	       $output{$type} = '';
1.79      albertel 1065: 	       foreach my $which (sort {uc($a) cmp uc($b)} (keys(%sortrole))) {
1.89      raeburn  1066: 		   if ( ($roleclass{$sortrole{$which}} =~ /^\Q$type\E/ ) && ($rolepriv{$sortrole{$which}}) ) { 
1.137     raeburn  1067: 		       $output{$type}.=
                   1068:                              &Apache::loncommon::start_data_table_row().
                   1069:                              $roletext{$sortrole{$which}}.
                   1070:                              &Apache::loncommon::end_data_table_row();
1.79      albertel 1071: 		   }
                   1072: 	       }
1.89      raeburn  1073: 	       unless($output{$type} eq '') {
1.137     raeburn  1074: 		   $output{$type} = '<tr class="LC_info_row">'.
                   1075: 			     "<td align='center' colspan='7'>".&mt($type)."</td></tr>".
1.89      raeburn  1076:                               $output{$type};
                   1077:                    $rolesdisplay = 1;
1.79      albertel 1078: 	       }
                   1079: 	   }
1.89      raeburn  1080:            if ($rolesdisplay == 1) {
1.137     raeburn  1081:                $r->print('
                   1082: <h3>'.$lt{'rer'}.'</h3>'.
                   1083: &Apache::loncommon::start_data_table("LC_createuser").
                   1084: &Apache::loncommon::start_data_table_header_row().
                   1085: '<th>'.$lt{'rev'}.'</th><th>'.$lt{'ren'}.'</th><th>'.$lt{'del'}.
                   1086: '</th><th>'.$lt{'rol'}.'</th><th>'.$lt{'ext'}.
                   1087: '</th><th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'.
                   1088: &Apache::loncommon::end_data_table_header_row());
1.119     raeburn  1089:                foreach my $type ('Construction Space','Course','Group','Domain','System','Unknown') {
1.89      raeburn  1090:                    if ($output{$type}) {
                   1091:                        $r->print($output{$type}."\n");
                   1092:                    }
                   1093:                }
1.137     raeburn  1094: 	       $r->print(&Apache::loncommon::end_data_table());
1.89      raeburn  1095:            }
1.28      matthew  1096:         }  # End of unless
1.25      matthew  1097:     } ## End of new user/old user logic
1.188     raeburn  1098:     my $addrolesdisplay = 0;
                   1099:     $r->print('<h3>'.&mt('Add Roles').'</h3>');
1.17      www      1100: #
                   1101: # Co-Author
                   1102: # 
1.209     raeburn  1103:     if (&Apache::lonuserutils::authorpriv($env{'user.name'},
                   1104:                                           $env{'request.role.domain'}) &&
1.101     albertel 1105:         ($env{'user.name'} ne $ccuname || $env{'user.domain'} ne $ccdomain)) {
1.44      matthew  1106:         # No sense in assigning co-author role to yourself
1.188     raeburn  1107:         $addrolesdisplay = 1;
1.101     albertel 1108: 	my $cuname=$env{'user.name'};
                   1109:         my $cudom=$env{'request.role.domain'};
1.72      sakharuk 1110: 	   my %lt=&Apache::lonlocal::texthash(
                   1111: 		    'cs'   => "Construction Space",
                   1112:                     'act'  => "Activate",                    
                   1113:                     'rol'  => "Role",
                   1114:                     'ext'  => "Extent",
                   1115:                     'sta'  => "Start",
1.80      www      1116:                     'end'  => "End",
1.72      sakharuk 1117:                     'cau'  => "Co-Author",
1.105     www      1118:                     'caa'  => "Assistant Co-Author",
1.72      sakharuk 1119:                     'ssd'  => "Set Start Date",
                   1120:                     'sed'  => "Set End Date"
                   1121: 				       );
1.135     raeburn  1122:        $r->print('<h4>'.$lt{'cs'}.'</h4>'."\n". 
                   1123:            &Apache::loncommon::start_data_table()."\n".
                   1124:            &Apache::loncommon::start_data_table_header_row()."\n".
                   1125:            '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'.
                   1126:            '<th>'.$lt{'ext'}.'</th><th>'.$lt{'sta'}.'</th>'.
                   1127:            '<th>'.$lt{'end'}.'</th>'."\n".
                   1128:            &Apache::loncommon::end_data_table_header_row()."\n".
                   1129:            &Apache::loncommon::start_data_table_row()."\n".
                   1130:            '<td>
                   1131:             <input type=checkbox name="act_'.$cudom.'_'.$cuname.'_ca" />
                   1132:            </td>
                   1133:            <td>'.$lt{'cau'}.'</td>
                   1134:            <td>'.$cudom.'_'.$cuname.'</td>
                   1135:            <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_ca" value="" />
                   1136:              <a href=
                   1137: "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>
1.169     albertel 1138: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_ca" value="" />
1.17      www      1139: <a href=
1.135     raeburn  1140: "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".
                   1141:           &Apache::loncommon::end_data_table_row()."\n".
                   1142:           &Apache::loncommon::start_data_table_row()."\n".
                   1143: '<td><input type=checkbox name="act_'.$cudom.'_'.$cuname.'_aa" /></td>
                   1144: <td>'.$lt{'caa'}.'</td>
                   1145: <td>'.$cudom.'_'.$cuname.'</td>
1.169     albertel 1146: <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_aa" value="" />
1.17      www      1147: <a href=
1.135     raeburn  1148: "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>
1.169     albertel 1149: <td><input type="hidden" name="end_'.$cudom.'_'.$cuname.'_aa" value="" />
1.105     www      1150: <a href=
1.135     raeburn  1151: "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".
                   1152:          &Apache::loncommon::end_data_table_row()."\n".
                   1153:          &Apache::loncommon::end_data_table());
1.190     raeburn  1154:     } elsif ($env{'request.role'} =~ /^au\./) {
1.209     raeburn  1155:         if (!(&Apache::lonuserutils::authorpriv($env{'user.name'},
                   1156:                                                 $env{'request.role.domain'}))) {
1.190     raeburn  1157:             $r->print('<span class="LC_error">'.
                   1158:                       &mt('You do not have privileges to assign co-author roles.').
                   1159:                       '</span>');
                   1160:         } elsif (($env{'user.name'} eq $ccuname) && 
1.188     raeburn  1161:              ($env{'user.domain'} eq $ccdomain)) {
1.190     raeburn  1162:            $r->print(&mt('Assigning yourself a co-author or assistant co-author role in your own author area in Construction Space is not permitted'));
                   1163:         }
1.17      www      1164:     }
1.8       www      1165: #
                   1166: # Domain level
                   1167: #
1.89      raeburn  1168:     my $num_domain_level = 0;
                   1169:     my $domaintext = 
                   1170:     '<h4>'.&mt('Domain Level').'</h4>'.
1.135     raeburn  1171:     &Apache::loncommon::start_data_table().
                   1172:     &Apache::loncommon::start_data_table_header_row().
                   1173:     '<th>'.&mt('Activate').'</th><th>'.&mt('Role').'</th><th>'.
                   1174:     &mt('Extent').'</th>'.
                   1175:     '<th>'.&mt('Start').'</th><th>'.&mt('End').'</th>'.
                   1176:     &Apache::loncommon::end_data_table_header_row();
1.146     albertel 1177:     foreach my $thisdomain (sort(&Apache::lonnet::all_domains())) {
1.135     raeburn  1178:         foreach my $role ('dc','li','dg','au','sc') {
                   1179:             if (&Apache::lonnet::allowed('c'.$role,$thisdomain)) {
                   1180:                my $plrole=&Apache::lonnet::plaintext($role);
1.72      sakharuk 1181: 	       my %lt=&Apache::lonlocal::texthash(
                   1182:                     'ssd'  => "Set Start Date",
                   1183:                     'sed'  => "Set End Date"
                   1184: 				       );
1.89      raeburn  1185:                $num_domain_level ++;
1.135     raeburn  1186:                $domaintext .= 
                   1187: &Apache::loncommon::start_data_table_row().
1.157     albertel 1188: '<td><input type=checkbox name="act_'.$thisdomain.'_'.$role.'" /></td>
1.135     raeburn  1189: <td>'.$plrole.'</td>
                   1190: <td>'.$thisdomain.'</td>
1.169     albertel 1191: <td><input type="hidden" name="start_'.$thisdomain.'_'.$role.'" value="" />
1.8       www      1192: <a href=
1.135     raeburn  1193: "javascript:pjump('."'date_start','Start Date $plrole',document.cu.start_$thisdomain\_$role.value,'start_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'ssd'}.'</a></td>
1.169     albertel 1194: <td><input type="hidden" name="end_'.$thisdomain.'_'.$role.'" value="" />
1.8       www      1195: <a href=
1.135     raeburn  1196: "javascript:pjump('."'date_end','End Date $plrole',document.cu.end_$thisdomain\_$role.value,'end_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'sed'}.'</a></td>'.
                   1197: &Apache::loncommon::end_data_table_row();
1.2       www      1198:             }
1.24      matthew  1199:         } 
                   1200:     }
1.135     raeburn  1201:     $domaintext.= &Apache::loncommon::end_data_table();
1.89      raeburn  1202:     if ($num_domain_level > 0) {
                   1203:         $r->print($domaintext);
1.188     raeburn  1204:         $addrolesdisplay = 1;
1.89      raeburn  1205:     }
1.8       www      1206: #
1.188     raeburn  1207: # Course level
1.8       www      1208: #
1.88      raeburn  1209: 
1.139     albertel 1210:     if ($env{'request.role'} =~ m{^dc\./($match_domain)/$}) {
1.119     raeburn  1211:         $r->print(&course_level_dc($1,'Course'));
1.188     raeburn  1212:         $r->print('<br /><input type="button" value="'.&mt('Modify User').'" onClick="setCourse()" />'."\n");
                   1213:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/$}) {
                   1214:         if ($addrolesdisplay) {
                   1215:             $r->print('<br /><input type="button" value="'.&mt('Modify User').'"');
                   1216:             if ($newuser) {
                   1217:                 $r->print(' onClick="verify_message(this.form)" \>'."\n");
                   1218:             } else {
                   1219:                 $r->print('onClick="this.form.submit()" \>'."\n"); 
                   1220:             }
                   1221:         } else {
                   1222:             $r->print('<br /><a href="javascript:backPage(document.cu)">'.
                   1223:                       &mt('Back to previous page').'</a>');
                   1224:         }
1.88      raeburn  1225:     } else {
                   1226:         $r->print(&course_level_table(%inccourses));
1.198     raeburn  1227:         $r->print('<br /><input type="button" value="'.&mt('Modify User').'" onClick="setSections(this.form)" />'."\n");
1.88      raeburn  1228:     }
1.188     raeburn  1229:     $r->print(&Apache::lonhtmlcommon::echo_form_input(['phase','userrole','ccdomain','prevphase','currstate','ccuname','ccdomain']));
1.179     raeburn  1230:     $r->print('<input type="hidden" name="currstate" value="" />');
1.160     raeburn  1231:     $r->print('<input type="hidden" name="prevphase" value="'.$env{'form.phase'}.'" />');
1.110     albertel 1232:     $r->print("</form>".&Apache::loncommon::end_page());
1.2       www      1233: }
1.1       www      1234: 
1.213     raeburn  1235: sub singleuser_breadcrumb {
                   1236:     my %breadcrumb_text;
                   1237:     if ($env{'form.action'} eq 'singlestudent') {
                   1238:         $breadcrumb_text{'search'} = 'Enroll a student';
                   1239:         $breadcrumb_text{'userpicked'} = 'Select a user',
                   1240:         $breadcrumb_text{'modify'} = 'Set section/dates',
                   1241:     } else {
                   1242:         $breadcrumb_text{'search'} = 'Create/modify user';
                   1243:         $breadcrumb_text{'userpicked'} = 'Select a user',
                   1244:         $breadcrumb_text{'modify'} = 'Set user role',
                   1245:     }
                   1246:     return %breadcrumb_text;
                   1247: }
                   1248: 
                   1249: sub date_sections_select {
                   1250:     my ($context,$newuser,$formname,$permission) = @_;
                   1251:     my $cid = $env{'request.course.id'};
                   1252:     my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity($cid);
                   1253:     my $date_table = '<h3>'.&mt('Starting and Ending Dates').'</h3>'."\n".
                   1254:         &Apache::lonuserutils::date_setting_table(undef,undef,$context,
                   1255:                                                   undef,$formname,$permission);
                   1256:     my $rowtitle = 'Section';
                   1257:     my $secbox = '<h3>'.&mt('Section').'</h3>'."\n".
                   1258:         &Apache::lonuserutils::section_picker($cdom,$cnum,'st',$rowtitle,
                   1259:                                               $permission);
                   1260:     my $output = $date_table.$secbox;
                   1261:     return $output;
                   1262: }
                   1263: 
1.188     raeburn  1264: sub user_authentication {
                   1265:     my ($ccuname,$ccdomain,$krbdefdom,$abv_auth) = @_;
                   1266:     my $currentauth=&Apache::lonnet::queryauthenticate($ccuname,$ccdomain);
                   1267:     my ($loginscript,$outcome);
                   1268:     if ($currentauth=~/^(krb)(4|5):(.*)/) {
                   1269:         my $long_auth = $1.$2;
                   1270:         my $curr_kerb_ver = $2;
                   1271:         my $krbdefdom=$3;
                   1272:         my $curr_authtype = $abv_auth->{$long_auth};
                   1273:         my %param = ( formname      => 'document.cu',
                   1274:                       kerb_def_dom  => $krbdefdom,
                   1275:                       domain        => $ccdomain,
                   1276:                       curr_authtype => $curr_authtype,
                   1277:                       curr_kerb_ver => $curr_kerb_ver,
                   1278:                           );
                   1279:         $loginscript  = &Apache::loncommon::authform_header(%param);
                   1280:     }
                   1281:     # Check for a bad authentication type
                   1282:     if ($currentauth !~ /^(krb4|krb5|unix|internal|localauth):/) {
                   1283:         # bad authentication scheme
                   1284:         my %lt=&Apache::lonlocal::texthash(
                   1285:                        'err'   => "ERROR",
                   1286:                        'uuas'  => "This user has an unrecognized authentication scheme",
                   1287:                        'adcs'  => "Please alert a domain coordinator of this situation",
                   1288:                        'sldb'  => "Please specify login data below",
                   1289:                        'ld'    => "Login Data"
                   1290:         );
                   1291:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
                   1292:             &initialize_authen_forms($ccdomain);
1.190     raeburn  1293:             my $choices = &Apache::lonuserutils::set_login($ccdomain,$authformkrb,$authformint,$authformloc);
1.188     raeburn  1294:             $outcome = <<ENDBADAUTH;
                   1295: <script type="text/javascript" language="Javascript">
                   1296: $loginscript
                   1297: </script>
                   1298: <span class="LC_error">$lt{'err'}:
                   1299: $lt{'uuas'} ($currentauth). $lt{'sldb'}.</span>
                   1300: <h3>$lt{'ld'}</h3>
                   1301: $choices
                   1302: ENDBADAUTH
                   1303:         } else {
                   1304:             # This user is not allowed to modify the user's
                   1305:             # authentication scheme, so just notify them of the problem
                   1306:             $outcome = <<ENDBADAUTH;
                   1307: <span class="LC_error"> $lt{'err'}: 
                   1308: $lt{'uuas'} ($currentauth). $lt{'adcs'}.
                   1309: </span>
                   1310: ENDBADAUTH
                   1311:         }
                   1312:     } else { # Authentication type is valid
1.205     raeburn  1313:         &initialize_authen_forms($ccdomain,$currentauth,'modifyuser');
                   1314:         my ($authformcurrent,$can_modify,@authform_others) =
1.188     raeburn  1315:             &modify_login_block($ccdomain,$currentauth);
                   1316:         if (&Apache::lonnet::allowed('mau',$ccdomain)) {
                   1317:             # Current user has login modification privileges
                   1318:             my %lt=&Apache::lonlocal::texthash (
                   1319:                            'ld'    => "Login Data",
                   1320:                            'ccld'  => "Change Current Login Data",
                   1321:                            'enld'  => "Enter New Login Data"
                   1322:                                                );
                   1323:             $outcome =
                   1324:                        '<script type="text/javascript" language="Javascript">'."\n".
                   1325:                        $loginscript."\n".
                   1326:                        '</script>'."\n".
                   1327:                        '<h3>'.$lt{'ld'}.'</h3>'.
                   1328:                        &Apache::loncommon::start_data_table().
1.205     raeburn  1329:                        &Apache::loncommon::start_data_table_row().
1.188     raeburn  1330:                        '<td>'.$authformnop;
                   1331:             if ($can_modify) {
                   1332:                 $outcome .= '</td>'."\n".
                   1333:                             &Apache::loncommon::end_data_table_row().
                   1334:                             &Apache::loncommon::start_data_table_row().
                   1335:                             '<td>'.$authformcurrent.'</td>'.
                   1336:                             &Apache::loncommon::end_data_table_row()."\n";
                   1337:             } else {
1.200     raeburn  1338:                 $outcome .= '&nbsp;('.$authformcurrent.')</td>'.
                   1339:                             &Apache::loncommon::end_data_table_row()."\n";
1.188     raeburn  1340:             }
1.205     raeburn  1341:             foreach my $item (@authform_others) { 
                   1342:                 $outcome .= &Apache::loncommon::start_data_table_row().
                   1343:                             '<td>'.$item.'</td>'.
                   1344:                             &Apache::loncommon::end_data_table_row()."\n";
1.188     raeburn  1345:             }
1.205     raeburn  1346:             $outcome .= &Apache::loncommon::end_data_table();
1.188     raeburn  1347:         } else {
                   1348:             if (&Apache::lonnet::allowed('mau',$env{'request.role.domain'})) {
                   1349:                 my %lt=&Apache::lonlocal::texthash(
                   1350:                            'ccld'  => "Change Current Login Data",
                   1351:                            'yodo'  => "You do not have privileges to modify the authentication configuration for this user.",
                   1352:                            'ifch'  => "If a change is required, contact a domain coordinator for the domain",
                   1353:                 );
                   1354:                 $outcome .= <<ENDNOPRIV;
                   1355: <h3>$lt{'ccld'}</h3>
                   1356: $lt{'yodo'} $lt{'ifch'}: $ccdomain
                   1357: ENDNOPRIV
                   1358:             }
                   1359:         }
                   1360:     }  ## End of "check for bad authentication type" logic
                   1361:     return $outcome;
                   1362: }
                   1363: 
1.187     raeburn  1364: sub modify_login_block {
                   1365:     my ($dom,$currentauth) = @_;
                   1366:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   1367:     my ($authnum,%can_assign) =
                   1368:         &Apache::loncommon::get_assignable_auth($dom);
1.205     raeburn  1369:     my ($authformcurrent,@authform_others,$show_override_msg);
1.187     raeburn  1370:     if ($currentauth=~/^krb(4|5):/) {
                   1371:         $authformcurrent=$authformkrb;
                   1372:         if ($can_assign{'int'}) {
1.205     raeburn  1373:             push(@authform_others,$authformint);
1.187     raeburn  1374:         }
                   1375:         if ($can_assign{'loc'}) {
1.205     raeburn  1376:             push(@authform_others,$authformloc);
1.187     raeburn  1377:         }
                   1378:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
                   1379:             $show_override_msg = 1;
                   1380:         }
                   1381:     } elsif ($currentauth=~/^internal:/) {
                   1382:         $authformcurrent=$authformint;
                   1383:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
1.205     raeburn  1384:             push(@authform_others,$authformkrb);
1.187     raeburn  1385:         }
                   1386:         if ($can_assign{'loc'}) {
1.205     raeburn  1387:             push(@authform_others,$authformloc);
1.187     raeburn  1388:         }
                   1389:         if ($can_assign{'int'}) {
                   1390:             $show_override_msg = 1;
                   1391:         }
                   1392:     } elsif ($currentauth=~/^unix:/) {
                   1393:         $authformcurrent=$authformfsys;
                   1394:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
1.205     raeburn  1395:             push(@authform_others,$authformkrb);
1.187     raeburn  1396:         }
                   1397:         if ($can_assign{'int'}) {
1.205     raeburn  1398:             push(@authform_others,$authformint);
1.187     raeburn  1399:         }
                   1400:         if ($can_assign{'loc'}) {
1.205     raeburn  1401:             push(@authform_others,$authformloc);
1.187     raeburn  1402:         }
                   1403:         if ($can_assign{'fsys'}) {
                   1404:             $show_override_msg = 1;
                   1405:         }
                   1406:     } elsif ($currentauth=~/^localauth:/) {
                   1407:         $authformcurrent=$authformloc;
                   1408:         if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
1.205     raeburn  1409:             push(@authform_others,$authformkrb);
1.187     raeburn  1410:         }
                   1411:         if ($can_assign{'int'}) {
1.205     raeburn  1412:             push(@authform_others,$authformint);
1.187     raeburn  1413:         }
                   1414:         if ($can_assign{'loc'}) {
                   1415:             $show_override_msg = 1;
                   1416:         }
                   1417:     }
                   1418:     if ($show_override_msg) {
1.205     raeburn  1419:         $authformcurrent = '<table><tr><td colspan="3">'.$authformcurrent.
                   1420:                            '</td></tr>'."\n".
                   1421:                            '<tr><td>&nbsp;&nbsp;&nbsp;</td>'.
                   1422:                            '<td><b>'.&mt('Currently in use').'</b></td>'.
                   1423:                            '<td align="right"><span class="LC_cusr_emph">'.
1.187     raeburn  1424:                             &mt('will override current values').
1.205     raeburn  1425:                             '</span></td></tr></table>';
1.187     raeburn  1426:     }
1.205     raeburn  1427:     return ($authformcurrent,$show_override_msg,@authform_others); 
1.187     raeburn  1428: }
                   1429: 
1.188     raeburn  1430: sub personal_data_display {
1.210     raeburn  1431:     my ($ccuname,$ccdomain,$newuser,$context,$inst_results) = @_;
1.206     raeburn  1432:     my ($output,$showforceid,%userenv,%domconfig);
1.188     raeburn  1433:     if (!$newuser) {
                   1434:         # Get the users information
                   1435:         %userenv = &Apache::lonnet::get('environment',
                   1436:                    ['firstname','middlename','lastname','generation',
                   1437:                     'permanentemail','id'],$ccdomain,$ccuname);
1.206     raeburn  1438:         %domconfig =
                   1439:             &Apache::lonnet::get_dom('configuration',['usermodification'],
                   1440:                                      $ccdomain);
1.188     raeburn  1441:     }
                   1442:     my %lt=&Apache::lonlocal::texthash(
                   1443:                 'pd'             => "Personal Data",
                   1444:                 'firstname'      => "First Name",
                   1445:                 'middlename'     => "Middle Name",
                   1446:                 'lastname'       => "Last Name",
                   1447:                 'generation'     => "Generation",
                   1448:                 'permanentemail' => "Permanent e-mail address",
                   1449:                 'id'             => "ID/Student Number",
                   1450:                 'lg'             => "Login Data"
                   1451:     );
                   1452:     my @userinfo = ('firstname','middlename','lastname','generation',
                   1453:                     'permanentemail','id');
                   1454:     my %textboxsize = (
                   1455:                        firstname      => '15',
                   1456:                        middlename     => '15',
                   1457:                        lastname       => '15',
                   1458:                        generation     => '5',
                   1459:                        permanentemail => '25',
                   1460:                        id             => '15',
                   1461:                       );
                   1462:     my $genhelp=&Apache::loncommon::help_open_topic('Generation');
                   1463:     $output = '<h3>'.$lt{'pd'}.'</h3>'.
                   1464:               &Apache::lonhtmlcommon::start_pick_box();
                   1465:     foreach my $item (@userinfo) {
                   1466:         my $rowtitle = $lt{$item};
                   1467:         if ($item eq 'generation') {
                   1468:             $rowtitle = $genhelp.$rowtitle;
                   1469:         }
                   1470:         $output .= &Apache::lonhtmlcommon::row_title($rowtitle,undef,'LC_oddrow_value')."\n";
                   1471:         if ($newuser) {
1.210     raeburn  1472:             if (ref($inst_results) eq 'HASH') {
                   1473:                 if ($inst_results->{$item} ne '') {
                   1474:                     $output .= '<input type="hidden" name="c'.$item.'" value="'.$inst_results->{$item}.'" />'.$inst_results->{$item};
                   1475:                 } else {
                   1476:                     $output .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
                   1477:                 }
1.188     raeburn  1478:             } else {
                   1479:                 $output .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
                   1480:             }
                   1481:         } else {
1.206     raeburn  1482:             my $canmodify = 0;
1.188     raeburn  1483:             if (&Apache::lonnet::allowed('mau',$ccdomain)) {
1.206     raeburn  1484:                 $canmodify = 1;
                   1485:             } else {
                   1486:                 if (ref($domconfig{'usermodification'}) eq 'HASH') {
                   1487:                     if (ref($domconfig{'usermodification'}{$context}) eq 'HASH') {
                   1488:                         foreach my $key (keys(%{$domconfig{'usermodification'}{$context}})) {
                   1489:                             if (ref($domconfig{'usermodification'}{$context}{$key}) eq 'HASH') {
                   1490:                                 if ($domconfig{'usermodification'}{$context}{$key}{$item}) { 
                   1491:                                     $canmodify = 1;
                   1492:                                     last;
                   1493:                                 }
                   1494:                             }
                   1495:                         }
                   1496:                     }
                   1497:                 } elsif ($context eq 'course') {
                   1498:                     $canmodify = 1;
                   1499:                 }
                   1500:             }
                   1501:             if ($canmodify) {
1.188     raeburn  1502:                 $output .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="'.$userenv{$item}.'" />';
                   1503:             } else {
                   1504:                 $output .= $userenv{$item};
                   1505:             }
1.206     raeburn  1506:             if ($item eq 'id') {
                   1507:                 $showforceid = $canmodify; 
                   1508:             } 
1.188     raeburn  1509:         }
                   1510:         $output .= &Apache::lonhtmlcommon::row_closure(1);
                   1511:     }
                   1512:     $output .= &Apache::lonhtmlcommon::end_pick_box();
1.206     raeburn  1513:     if (wantarray) {
                   1514:         return ($output,$showforceid);
                   1515:     } else {
                   1516:         return $output;
                   1517:     }
1.188     raeburn  1518: }
                   1519: 
1.4       www      1520: # ================================================================= Phase Three
1.42      matthew  1521: sub update_user_data {
1.206     raeburn  1522:     my ($r,$context) = @_; 
1.101     albertel 1523:     my $uhome=&Apache::lonnet::homeserver($env{'form.ccuname'},
                   1524:                                           $env{'form.ccdomain'});
1.27      matthew  1525:     # Error messages
1.188     raeburn  1526:     my $error     = '<span class="LC_error">'.&mt('Error').': ';
1.193     raeburn  1527:     my $end       = '</span><br /><br />';
                   1528:     my $rtnlink   = '<a href="javascript:backPage(document.userupdate,'.
1.188     raeburn  1529:                     "'$env{'form.prevphase'}','modify')".'" />'.
                   1530:                     &mt('Return to previous page').'</a>'.&Apache::loncommon::end_page();
1.40      www      1531:     my $title;
1.101     albertel 1532:     if (exists($env{'form.makeuser'})) {
1.40      www      1533: 	$title='Set Privileges for New User';
                   1534:     } else {
                   1535:         $title='Modify User Privileges';
                   1536:     }
1.213     raeburn  1537:     my $newuser = 0;
1.160     raeburn  1538:     my ($jsback,$elements) = &crumb_utilities();
                   1539:     my $jscript = '<script type="text/javascript">'."\n".
                   1540:                   $jsback."\n".'</script>'."\n";
1.213     raeburn  1541:     my %breadcrumb_text = &singleuser_breadcrumb();
1.160     raeburn  1542:     $r->print(&Apache::loncommon::start_page($title,$jscript));
                   1543:     &Apache::lonhtmlcommon::add_breadcrumb
                   1544:        ({href=>"javascript:backPage(document.userupdate)",
1.213     raeburn  1545:          text=>$breadcrumb_text{'search'},
1.160     raeburn  1546:          faq=>282,bug=>'Instructor Interface',});
                   1547:     if ($env{'form.prevphase'} eq 'userpicked') {
                   1548:         &Apache::lonhtmlcommon::add_breadcrumb
                   1549:            ({href=>"javascript:backPage(document.userupdate,'get_user_info','select')",
1.213     raeburn  1550:              text=>$breadcrumb_text{'userpicked'},
1.160     raeburn  1551:              faq=>282,bug=>'Instructor Interface',});
                   1552:     }
                   1553:     &Apache::lonhtmlcommon::add_breadcrumb
                   1554:        ({href=>"javascript:backPage(document.userupdate,'$env{'form.prevphase'}','modify')",
                   1555:          text=>"Set user role",
                   1556:          faq=>282,bug=>'Instructor Interface',},
                   1557:         {href=>"/adm/createuser",
                   1558:          text=>"Result",
                   1559:          faq=>282,bug=>'Instructor Interface',});
                   1560:     $r->print(&Apache::lonhtmlcommon::breadcrumbs('User Management'));
                   1561: 
1.113     raeburn  1562:     my %disallowed;
1.188     raeburn  1563:     $r->print(&update_result_form($uhome));
1.27      matthew  1564:     # Check Inputs
1.101     albertel 1565:     if (! $env{'form.ccuname'} ) {
1.193     raeburn  1566: 	$r->print($error.&mt('No login name specified').'.'.$end.$rtnlink);
1.27      matthew  1567: 	return;
                   1568:     }
1.138     albertel 1569:     if (  $env{'form.ccuname'} ne 
                   1570: 	  &LONCAPA::clean_username($env{'form.ccuname'}) ) {
1.73      sakharuk 1571: 	$r->print($error.&mt('Invalid login name').'.  '.
1.160     raeburn  1572: 		  &mt('Only letters, numbers, periods, dashes, @, and underscores are valid').'.'.
1.193     raeburn  1573: 		  $end.$rtnlink);
1.27      matthew  1574: 	return;
                   1575:     }
1.101     albertel 1576:     if (! $env{'form.ccdomain'}       ) {
1.193     raeburn  1577: 	$r->print($error.&mt('No domain specified').'.'.$end.$rtnlink);
1.27      matthew  1578: 	return;
                   1579:     }
1.138     albertel 1580:     if (  $env{'form.ccdomain'} ne
                   1581: 	  &LONCAPA::clean_domain($env{'form.ccdomain'}) ) {
1.73      sakharuk 1582: 	$r->print($error.&mt ('Invalid domain name').'.  '.
1.138     albertel 1583: 		  &mt('Only letters, numbers, periods, dashes, and underscores are valid').'.'.
1.193     raeburn  1584: 		  $end.$rtnlink);
1.27      matthew  1585: 	return;
                   1586:     }
1.101     albertel 1587:     if (! exists($env{'form.makeuser'})) {
1.29      matthew  1588:         # Modifying an existing user, so check the validity of the name
                   1589:         if ($uhome eq 'no_host') {
1.73      sakharuk 1590:             $r->print($error.&mt('Unable to determine home server for ').
1.101     albertel 1591:                       $env{'form.ccuname'}.&mt(' in domain ').
                   1592:                       $env{'form.ccdomain'}.'.');
1.29      matthew  1593:             return;
                   1594:         }
                   1595:     }
1.27      matthew  1596:     # Determine authentication method and password for the user being modified
                   1597:     my $amode='';
                   1598:     my $genpwd='';
1.101     albertel 1599:     if ($env{'form.login'} eq 'krb') {
1.41      albertel 1600: 	$amode='krb';
1.101     albertel 1601: 	$amode.=$env{'form.krbver'};
                   1602: 	$genpwd=$env{'form.krbarg'};
                   1603:     } elsif ($env{'form.login'} eq 'int') {
1.27      matthew  1604: 	$amode='internal';
1.101     albertel 1605: 	$genpwd=$env{'form.intarg'};
                   1606:     } elsif ($env{'form.login'} eq 'fsys') {
1.27      matthew  1607: 	$amode='unix';
1.101     albertel 1608: 	$genpwd=$env{'form.fsysarg'};
                   1609:     } elsif ($env{'form.login'} eq 'loc') {
1.27      matthew  1610: 	$amode='localauth';
1.101     albertel 1611: 	$genpwd=$env{'form.locarg'};
1.27      matthew  1612: 	$genpwd=" " if (!$genpwd);
1.101     albertel 1613:     } elsif (($env{'form.login'} eq 'nochange') ||
                   1614:              ($env{'form.login'} eq ''        )) { 
1.34      matthew  1615:         # There is no need to tell the user we did not change what they
                   1616:         # did not ask us to change.
1.35      matthew  1617:         # If they are creating a new user but have not specified login
                   1618:         # information this will be caught below.
1.30      matthew  1619:     } else {
1.193     raeburn  1620: 	    $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);    
1.30      matthew  1621: 	    return;
1.27      matthew  1622:     }
1.164     albertel 1623: 
                   1624: 
1.188     raeburn  1625:     $r->print('<h3>'.&mt('User [_1] in domain [_2]',
                   1626: 			 $env{'form.ccuname'}, $env{'form.ccdomain'}).'</h3>');
1.193     raeburn  1627:     my (%alerts,%rulematch,%inst_results,%curr_rules);
1.101     albertel 1628:     if ($env{'form.makeuser'}) {
1.164     albertel 1629: 	$r->print('<h3>'.&mt('Creating new account.').'</h3>');
1.27      matthew  1630:         # Check for the authentication mode and password
                   1631:         if (! $amode || ! $genpwd) {
1.193     raeburn  1632: 	    $r->print($error.&mt('Invalid login mode or password').$end.$rtnlink);    
1.27      matthew  1633: 	    return;
1.18      albertel 1634: 	}
1.29      matthew  1635:         # Determine desired host
1.101     albertel 1636:         my $desiredhost = $env{'form.hserver'};
1.29      matthew  1637:         if (lc($desiredhost) eq 'default') {
                   1638:             $desiredhost = undef;
                   1639:         } else {
1.147     albertel 1640:             my %home_servers = 
                   1641: 		&Apache::lonnet::get_servers($env{'form.ccdomain'},'library');
1.29      matthew  1642:             if (! exists($home_servers{$desiredhost})) {
1.193     raeburn  1643:                 $r->print($error.&mt('Invalid home server specified').$end.$rtnlink);
                   1644:                 return;
                   1645:             }
                   1646:         }
                   1647:         # Check ID format
                   1648:         my %checkhash;
                   1649:         my %checks = ('id' => 1);
                   1650:         %{$checkhash{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}}} = (
1.196     raeburn  1651:             'newuser' => 1, 
                   1652:             'id' => $env{'form.cid'},
1.193     raeburn  1653:         );
1.196     raeburn  1654:         if ($env{'form.cid'} ne '') {
                   1655:             &Apache::loncommon::user_rule_check(\%checkhash,\%checks,\%alerts,
                   1656:                                           \%rulematch,\%inst_results,\%curr_rules);
                   1657:             if (ref($alerts{'id'}) eq 'HASH') {
                   1658:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
                   1659:                     my $domdesc =
                   1660:                         &Apache::lonnet::domain($env{'form.ccdomain'},'description');
                   1661:                     if ($alerts{'id'}{$env{'form.ccdomain'}}{$env{'form.cid'}}) {
                   1662:                         my $userchkmsg;
                   1663:                         if (ref($curr_rules{$env{'form.ccdomain'}}) eq 'HASH') {
                   1664:                             $userchkmsg  = 
                   1665:                                 &Apache::loncommon::instrule_disallow_msg('id',
                   1666:                                                                     $domdesc,1).
                   1667:                                 &Apache::loncommon::user_rule_formats($env{'form.ccdomain'},
                   1668:                                     $domdesc,$curr_rules{$env{'form.ccdomain'}}{'id'},'id');
                   1669:                         }
                   1670:                         $r->print($error.&mt('Invalid ID format').$end.
                   1671:                                   $userchkmsg.$rtnlink);
                   1672:                         return;
                   1673:                     }
                   1674:                 }
1.29      matthew  1675:             }
                   1676:         }
1.27      matthew  1677: 	# Call modifyuser
                   1678: 	my $result = &Apache::lonnet::modifyuser
1.193     raeburn  1679: 	    ($env{'form.ccdomain'},$env{'form.ccuname'},$env{'form.cid'},
1.188     raeburn  1680:              $amode,$genpwd,$env{'form.cfirstname'},
                   1681:              $env{'form.cmiddlename'},$env{'form.clastname'},
                   1682:              $env{'form.cgeneration'},undef,$desiredhost,
                   1683:              $env{'form.cpermanentemail'});
1.77      www      1684: 	$r->print(&mt('Generating user').': '.$result);
1.101     albertel 1685:         my $home = &Apache::lonnet::homeserver($env{'form.ccuname'},
                   1686:                                                $env{'form.ccdomain'});
1.77      www      1687:         $r->print('<br />'.&mt('Home server').': '.$home.' '.
1.148     albertel 1688:                   &Apache::lonnet::hostname($home));
1.101     albertel 1689:     } elsif (($env{'form.login'} ne 'nochange') &&
                   1690:              ($env{'form.login'} ne ''        )) {
1.27      matthew  1691: 	# Modify user privileges
                   1692:         if (! $amode || ! $genpwd) {
1.193     raeburn  1693: 	    $r->print($error.'Invalid login mode or password'.$end.$rtnlink);    
1.27      matthew  1694: 	    return;
1.20      harris41 1695: 	}
1.27      matthew  1696: 	# Only allow authentification modification if the person has authority
1.101     albertel 1697: 	if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
1.20      harris41 1698: 	    $r->print('Modifying authentication: '.
1.31      matthew  1699:                       &Apache::lonnet::modifyuserauth(
1.101     albertel 1700: 		       $env{'form.ccdomain'},$env{'form.ccuname'},
1.21      harris41 1701:                        $amode,$genpwd));
1.102     albertel 1702:             $r->print('<br />'.&mt('Home server').': '.&Apache::lonnet::homeserver
1.101     albertel 1703: 		  ($env{'form.ccuname'},$env{'form.ccdomain'}));
1.4       www      1704: 	} else {
1.27      matthew  1705: 	    # Okay, this is a non-fatal error.
1.193     raeburn  1706: 	    $r->print($error.&mt('You do not have the authority to modify this users authentification information').'.'.$end);    
1.27      matthew  1707: 	}
1.28      matthew  1708:     }
                   1709:     ##
1.213     raeburn  1710:     my (@userroles,%userupdate,$cnum,$cdom,$namechanged);
                   1711:     if ($context eq 'course') {
                   1712:         ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity();
                   1713:     }
1.101     albertel 1714:     if (! $env{'form.makeuser'} ) {
1.28      matthew  1715:         # Check for need to change
                   1716:         my %userenv = &Apache::lonnet::get
1.134     raeburn  1717:             ('environment',['firstname','middlename','lastname','generation',
1.196     raeburn  1718:              'id','permanentemail','portfolioquota','inststatus'],
1.160     raeburn  1719:               $env{'form.ccdomain'},$env{'form.ccuname'});
1.28      matthew  1720:         my ($tmp) = keys(%userenv);
                   1721:         if ($tmp =~ /^(con_lost|error)/i) { 
                   1722:             %userenv = ();
                   1723:         }
1.206     raeburn  1724:         my $no_forceid_alert;
                   1725:         # Check to see if user information can be changed
                   1726:         my %domconfig =
                   1727:             &Apache::lonnet::get_dom('configuration',['usermodification'],
                   1728:                                      $env{'form.ccdomain'});
1.213     raeburn  1729:         my @statuses = ('active','future');
                   1730:         my %roles = &Apache::lonnet::get_my_roles($env{'form.ccuname'},$env{'form.ccdomain'},'userroles',\@statuses,undef,$env{'request.role.domain'});
                   1731:         my ($auname,$audom);
1.206     raeburn  1732:         if ($context eq 'course') {
                   1733:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   1734:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   1735:             if ($cnum eq '' || $cdom eq '') {
                   1736:                 my $cid = $env{'request.course.id'};
                   1737:                 my %coursehash =
                   1738:                      &Apache::lonnet::coursedescription($cid,{'one_time' => 1});
                   1739:                 $cdom = $coursehash{'domain'};
                   1740:                 $cnum = $coursehash{'num'};
                   1741:             } 
                   1742:         } elsif ($context eq 'author') {
                   1743:             $auname = $env{'user.name'};
                   1744:             $audom = $env{'user.domain'};     
                   1745:         }
                   1746:         foreach my $item (keys(%roles)) {
                   1747:             my ($rolenum,$roledom,$role) = split(/:/,$item);
                   1748:             if ($context eq 'course') {
                   1749:                 if ($cnum ne '' && $cdom ne '') {
                   1750:                     if ($rolenum eq $cnum && $roledom eq $cdom) {
                   1751:                         if (!grep(/^\Q$role\E$/,@userroles)) {
                   1752:                             push(@userroles,$role);
                   1753:                         }
                   1754:                     }
                   1755:                 }
                   1756:             } elsif ($context eq 'author') {
                   1757:                 if ($rolenum eq $auname && $roledom eq $audom) {
                   1758:                     if (!grep(/^\Q$role\E$/,@userroles)) { 
                   1759:                         push(@userroles,$role);
                   1760:                     }
                   1761:                 }
                   1762:             }
                   1763:         }
                   1764:         # Check for course or co-author roles being activated or re-enabled
                   1765:         if ($context eq 'author' || $context eq 'course') {
                   1766:             foreach my $key (keys(%env)) {
                   1767:                 if ($context eq 'author') {
                   1768:                     if ($key=~/^form\.act_\Q$audom\E_\Q$auname\E_([^_]+)/) {
                   1769:                         if (!grep(/^\Q$1\E$/,@userroles)) {
                   1770:                             push(@userroles,$1);
                   1771:                         }
                   1772:                     } elsif ($key =~/^form\.ren\:\Q$audom\E\/\Q$auname\E_([^_]+)/) {
                   1773:                         if (!grep(/^\Q$1\E$/,@userroles)) {
                   1774:                             push(@userroles,$1);
                   1775:                         }
                   1776:                     }
                   1777:                 } elsif ($context eq 'course') {
                   1778:                     if ($key=~/^form\.act_\Q$cdom\E_\Q$cnum\E_([^_]+)/) {
                   1779:                         if (!grep(/^\Q$1\E$/,@userroles)) {
                   1780:                             push(@userroles,$1);
                   1781:                         }
                   1782:                     } elsif ($key =~/^form\.ren\:\Q$cdom\E\/\Q$cnum\E(\/?\w*)_([^_]+)/) {
                   1783:                         if (!grep(/^\Q$1\E$/,@userroles)) {
                   1784:                             push(@userroles,$1);
                   1785:                         }
                   1786:                     }
                   1787:                 }
                   1788:             }
                   1789:         }
                   1790:         #Check to see if we can change personal data for the user 
                   1791:         my (@mod_disallowed,@longroles);
                   1792:         foreach my $role (@userroles) {
                   1793:             if ($role eq 'cr') {
                   1794:                 push(@longroles,'Custom');
                   1795:             } else {
                   1796:                 push(@longroles,&Apache::lonnet::plaintext($role)); 
                   1797:             }
                   1798:         }
1.196     raeburn  1799:         foreach my $item ('firstname','middlename','lastname','generation','permanentemail','id') {
1.206     raeburn  1800:             my $canmodify = 0;
                   1801:             if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
                   1802:                 $canmodify = 1;
                   1803:             } else {
                   1804:                 if ($context eq 'course' || $context eq 'author') {
                   1805:                     if (ref($domconfig{'usermodification'}) eq 'HASH') {
                   1806:                         if (ref($domconfig{'usermodification'}{$context}) eq 'HASH') {
                   1807:                             foreach my $role (@userroles) {
                   1808:                                 if (ref($domconfig{'usermodification'}{$context}{$role}) eq 'HASH') {
                   1809:                                     if ($domconfig{'usermodification'}{$context}{$role}{$item}) {
                   1810:                                         $canmodify = 1;
                   1811:                                         last;
                   1812:                                     }
                   1813:                                 }
                   1814:                             }
                   1815:                         }
                   1816:                     }
                   1817:                 } elsif ($context eq 'course') {
                   1818:                     if (grep(/^st$/,@userroles)) {
                   1819:                         $canmodify = 1;
                   1820:                     }
                   1821:                 }
                   1822:             }
1.28      matthew  1823:             # Strip leading and trailing whitespace
1.203     raeburn  1824:             $env{'form.c'.$item} =~ s/(\s+$|^\s+)//g;
1.206     raeburn  1825:             if (!$canmodify) {
1.207     raeburn  1826:                 if (defined($env{'form.c'.$item})) {
                   1827:                     if ($env{'form.c'.$item} ne $userenv{$item}) {
                   1828:                         push(@mod_disallowed,$item);
                   1829:                     }
1.206     raeburn  1830:                 }
                   1831:                 $env{'form.c'.$item} = $userenv{$item};
                   1832:             }
1.28      matthew  1833:         }
1.196     raeburn  1834:         # Check to see if we can change the ID/student number
                   1835:         my $forceid = $env{'form.forceid'};
                   1836:         my $recurseid = $env{'form.recurseid'};
                   1837:         my $newuser = 0;
                   1838:         my (%alerts,%rulematch,%idinst_results,%curr_rules,%got_rules);
1.203     raeburn  1839:         my %uidhash = &Apache::lonnet::idrget($env{'form.ccdomain'},
                   1840:                                             $env{'form.ccuname'});
                   1841:         if (($uidhash{$env{'form.ccuname'}}) && 
                   1842:             ($uidhash{$env{'form.ccuname'}}!~/error\:/) && 
                   1843:             (!$forceid)) {
                   1844:             if ($env{'form.cid'} ne $uidhash{$env{'form.ccuname'}}) {
                   1845:                 $env{'form.cid'} = $userenv{'id'};
1.206     raeburn  1846:                 $no_forceid_alert = &mt('New student/employeeID does not match existing ID for this user.').'<br />'.&mt('Change is not permitted without checking the \'Force ID change\' checkbox on the previous page.').'<br />'."\n";        
1.203     raeburn  1847:             }
                   1848:         }
                   1849:         if ($env{'form.cid'} ne $userenv{'id'}) {
1.196     raeburn  1850:             my $checkhash;
                   1851:             my $checks = { 'id' => 1 };
                   1852:             $checkhash->{$env{'form.ccuname'}.':'.$env{'form.ccdomain'}} = 
                   1853:                    { 'newuser' => $newuser,
                   1854:                      'id'  => $env{'form.cid'}, 
                   1855:                    };
                   1856:             &Apache::loncommon::user_rule_check($checkhash,$checks,
                   1857:                 \%alerts,\%rulematch,\%idinst_results,\%curr_rules,\%got_rules);
                   1858:             if (ref($alerts{'id'}) eq 'HASH') {
                   1859:                 if (ref($alerts{'id'}{$env{'form.ccdomain'}}) eq 'HASH') {
1.203     raeburn  1860:                    $env{'form.cid'} = $userenv{'id'};
1.196     raeburn  1861:                 }
                   1862:             }
                   1863:         }
1.213     raeburn  1864:         my ($quotachanged,$oldportfolioquota,$newportfolioquota,
1.204     raeburn  1865:             $inststatus,$oldisdefault,$newisdefault,$olddefquotatext,
                   1866:             $newdefquotatext);
1.149     raeburn  1867:         my ($defquota,$settingstatus) = 
                   1868:             &Apache::loncommon::default_quota($env{'form.ccdomain'},$inststatus);
1.134     raeburn  1869:         my %changeHash;
1.204     raeburn  1870:         $changeHash{'portfolioquota'} = $userenv{'portfolioquota'};
1.149     raeburn  1871:         if ($userenv{'portfolioquota'} ne '') {
1.134     raeburn  1872:             $oldportfolioquota = $userenv{'portfolioquota'};
1.149     raeburn  1873:             if ($env{'form.customquota'} == 1) {
                   1874:                 if ($env{'form.portfolioquota'} eq '') {
                   1875:                     $newportfolioquota = 0;
                   1876:                 } else {
                   1877:                     $newportfolioquota = $env{'form.portfolioquota'};
                   1878:                     $newportfolioquota =~ s/[^\d\.]//g;
                   1879:                 }
1.204     raeburn  1880:                 if ($newportfolioquota != $oldportfolioquota) {
1.149     raeburn  1881:                     $quotachanged = &quota_admin($newportfolioquota,\%changeHash);
1.134     raeburn  1882:                 }
1.149     raeburn  1883:             } else {
                   1884:                 $quotachanged = &quota_admin('',\%changeHash);
                   1885:                 $newportfolioquota = $defquota;
1.204     raeburn  1886:                 $newisdefault = 1; 
1.134     raeburn  1887:             }
                   1888:         } else {
1.204     raeburn  1889:             $oldisdefault = 1;
1.149     raeburn  1890:             $oldportfolioquota = $defquota;
                   1891:             if ($env{'form.customquota'} == 1) {
                   1892:                 if ($env{'form.portfolioquota'} eq '') {
                   1893:                     $newportfolioquota = 0;
                   1894:                 } else {
                   1895:                     $newportfolioquota = $env{'form.portfolioquota'};
                   1896:                     $newportfolioquota =~ s/[^\d\.]//g;
                   1897:                 }
                   1898:                 $quotachanged = &quota_admin($newportfolioquota,\%changeHash);
                   1899:             } else {
                   1900:                 $newportfolioquota = $defquota;
1.204     raeburn  1901:                 $newisdefault = 1;
1.149     raeburn  1902:             }
                   1903:         }
1.204     raeburn  1904:         if ($oldisdefault) {
                   1905:             $olddefquotatext = &get_defaultquota_text($settingstatus);
                   1906:         }
                   1907:         if ($newisdefault) {
                   1908:             $newdefquotatext = &get_defaultquota_text($settingstatus);
1.134     raeburn  1909:         }
1.206     raeburn  1910:         if ($env{'form.cfirstname'}  ne $userenv{'firstname'}  ||
                   1911:             $env{'form.cmiddlename'} ne $userenv{'middlename'} ||
                   1912:             $env{'form.clastname'}   ne $userenv{'lastname'}   ||
                   1913:             $env{'form.cgeneration'} ne $userenv{'generation'} ||
                   1914:             $env{'form.cid'} ne $userenv{'id'}                 ||
                   1915:             $env{'form.cpermanentemail'} ne $userenv{'permanentemail'} ) {
1.134     raeburn  1916:             $namechanged = 1;
                   1917:         }
1.204     raeburn  1918:         if ($namechanged || $quotachanged) {
1.101     albertel 1919:             $changeHash{'firstname'}  = $env{'form.cfirstname'};
                   1920:             $changeHash{'middlename'} = $env{'form.cmiddlename'};
                   1921:             $changeHash{'lastname'}   = $env{'form.clastname'};
                   1922:             $changeHash{'generation'} = $env{'form.cgeneration'};
1.196     raeburn  1923:             $changeHash{'id'}         = $env{'form.cid'};
1.174     raeburn  1924:             $changeHash{'permanentemail'} = $env{'form.cpermanentemail'};
1.204     raeburn  1925:             my ($quotachgresult,$namechgresult);
                   1926:             if ($quotachanged) {
                   1927:                 $quotachgresult = 
                   1928:                     &Apache::lonnet::put('environment',\%changeHash,
                   1929:                                   $env{'form.ccdomain'},$env{'form.ccuname'});
                   1930:             }
                   1931:             if ($namechanged) {
                   1932:             # Make the change
                   1933:                 $namechgresult =
                   1934:                     &Apache::lonnet::modifyuser($env{'form.ccdomain'},
                   1935:                         $env{'form.ccuname'},$changeHash{'id'},undef,undef,
                   1936:                         $changeHash{'firstname'},$changeHash{'middlename'},
                   1937:                         $changeHash{'lastname'},$changeHash{'generation'},
                   1938:                         $changeHash{'id'},undef,$changeHash{'permanentemail'});
                   1939:             }
                   1940:             if (($namechanged && $namechgresult eq 'ok') || 
                   1941:                 ($quotachanged && $quotachgresult eq 'ok')) {
1.28      matthew  1942:             # Tell the user we changed the name
1.73      sakharuk 1943: 		my %lt=&Apache::lonlocal::texthash(
                   1944:                              'uic'  => "User Information Changed",             
                   1945:                              'frst' => "first",
                   1946:                              'mddl' => "middle",
                   1947:                              'lst'  => "last",
                   1948: 			     'gen'  => "generation",
1.196     raeburn  1949:                              'id'   => "ID/Student number",
1.160     raeburn  1950:                              'mail' => "permanent e-mail",
1.134     raeburn  1951:                              'disk' => "disk space allocated to portfolio files",
1.73      sakharuk 1952:                              'prvs' => "Previous",
                   1953:                              'chto' => "Changed To"
                   1954: 						   );
1.201     raeburn  1955:                 $r->print('<h4>'.$lt{'uic'}.'</h4>'.
                   1956:                           &Apache::loncommon::start_data_table().
                   1957:                           &Apache::loncommon::start_data_table_header_row());
1.28      matthew  1958:                 $r->print(<<"END");
1.201     raeburn  1959:     <th>&nbsp;</th>
1.73      sakharuk 1960:     <th>$lt{'frst'}</th>
                   1961:     <th>$lt{'mddl'}</th>
                   1962:     <th>$lt{'lst'}</th>
1.134     raeburn  1963:     <th>$lt{'gen'}</th>
1.196     raeburn  1964:     <th>$lt{'id'}</th>
1.173     raeburn  1965:     <th>$lt{'mail'}</th>
1.201     raeburn  1966:     <th>$lt{'disk'}</th>
                   1967: END
                   1968:                 $r->print(&Apache::loncommon::end_data_table_header_row().
                   1969:                           &Apache::loncommon::start_data_table_row());
                   1970:                 $r->print(<<"END");
                   1971:     <td><b>$lt{'prvs'}</b></td>
1.28      matthew  1972:     <td>$userenv{'firstname'}  </td>
                   1973:     <td>$userenv{'middlename'} </td>
                   1974:     <td>$userenv{'lastname'}   </td>
1.134     raeburn  1975:     <td>$userenv{'generation'} </td>
1.196     raeburn  1976:     <td>$userenv{'id'}</td>
1.160     raeburn  1977:     <td>$userenv{'permanentemail'} </td>
1.204     raeburn  1978:     <td>$oldportfolioquota Mb $olddefquotatext </td>
1.201     raeburn  1979: END
                   1980:                 $r->print(&Apache::loncommon::end_data_table_row().
                   1981:                           &Apache::loncommon::start_data_table_row());
                   1982:                 $r->print(<<"END");
                   1983:     <td><b>$lt{'chto'}</b></td>
1.101     albertel 1984:     <td>$env{'form.cfirstname'}  </td>
                   1985:     <td>$env{'form.cmiddlename'} </td>
                   1986:     <td>$env{'form.clastname'}   </td>
1.134     raeburn  1987:     <td>$env{'form.cgeneration'} </td>
1.196     raeburn  1988:     <td>$env{'form.cid'} </td>
1.160     raeburn  1989:     <td>$env{'form.cpermanentemail'} </td>
1.204     raeburn  1990:     <td>$newportfolioquota Mb $newdefquotatext </td>
1.28      matthew  1991: END
1.201     raeburn  1992:                 $r->print(&Apache::loncommon::end_data_table_row().
1.206     raeburn  1993:                           &Apache::loncommon::end_data_table().'<br />');
1.203     raeburn  1994:                 if ($env{'form.cid'} ne $userenv{'id'}) {
                   1995:                     &Apache::lonnet::idput($env{'form.ccdomain'},
                   1996:                          ($env{'form.ccuname'} => $env{'form.cid'}));
                   1997:                     if (($recurseid) &&
                   1998:                         (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'}))) {
1.213     raeburn  1999:                         %userupdate = (
1.196     raeburn  2000:                                   lastname   => $env{'form.clasaname'},
                   2001:                                   middlename => $env{'form.cmiddlename'},
                   2002:                                   firstname  => $env{'form.cfirstname'},
                   2003:                                   generation => $env{'fora.cgeneration'},
                   2004:                                   id         => $env{'form.cid'},
                   2005:                              );
1.203     raeburn  2006:                         my $idresult = 
                   2007:                             &Apache::lonuserutils::propagate_id_change(
                   2008:                                 $env{'form.ccuname'},$env{'form.ccdomain'},
                   2009:                                 \%userupdate);
                   2010:                         $r->print('<br />'.$idresult.'<br />');
                   2011:                     }
1.196     raeburn  2012:                 }
1.149     raeburn  2013:                 if (($env{'form.ccdomain'} eq $env{'user.domain'}) && 
                   2014:                     ($env{'form.ccuname'} eq $env{'user.name'})) {
                   2015:                     my %newenvhash;
                   2016:                     foreach my $key (keys(%changeHash)) {
                   2017:                         $newenvhash{'environment.'.$key} = $changeHash{$key};
                   2018:                     }
                   2019:                     &Apache::lonnet::appenv(%newenvhash);
                   2020:                 }
1.28      matthew  2021:             } else { # error occurred
1.188     raeburn  2022:                 $r->print('<span class="LC_error">'.&mt('Unable to successfully change environment for').' '.
                   2023:                       $env{'form.ccuname'}.' '.&mt('in domain').' '.
1.206     raeburn  2024:                       $env{'form.ccdomain'}.'</span><br />');
1.28      matthew  2025:             }
1.101     albertel 2026:         }  else { # End of if ($env ... ) logic
1.204     raeburn  2027:             # They did not want to change the users name or quota but we can
                   2028:             # still tell them what the name and quota are 
1.73      sakharuk 2029: 	    my %lt=&Apache::lonlocal::texthash(
1.196     raeburn  2030:                            'id'   => "ID/Student number",
1.160     raeburn  2031:                            'mail' => "Permanent e-mail",
1.134     raeburn  2032:                            'disk' => "Disk space allocated to user's portfolio files",
1.73      sakharuk 2033: 					       );
1.134     raeburn  2034:             $r->print(<<"END");
1.196     raeburn  2035: <h4>$userenv{'firstname'} $userenv{'middlename'} $userenv{'lastname'} $userenv{'generation'}
1.28      matthew  2036: END
1.204     raeburn  2037:             if ($userenv{'permanentemail'} ne '') {
                   2038:                 $r->print('<br />['.$lt{'mail'}.': '.
                   2039:                           $userenv{'permanentemail'}.']');
1.134     raeburn  2040:             }
1.204     raeburn  2041:             $r->print('<br />['.$lt{'disk'}.': '.$oldportfolioquota.' Mb '. 
                   2042:                  $olddefquotatext.']</h4>');
1.28      matthew  2043:         }
1.206     raeburn  2044:         if (@mod_disallowed) {
                   2045:             my ($rolestr,$contextname);
                   2046:             if (@longroles > 0) {
                   2047:                 $rolestr = join(', ',@longroles);
                   2048:             } else {
                   2049:                 $rolestr = &mt('No roles');
                   2050:             }
                   2051:             if ($context eq 'course') {
                   2052:                 $contextname = &mt('course');
                   2053:             } elsif ($context eq 'author') {
                   2054:                 $contextname = &mt('co-author');
                   2055:             }
                   2056:             $r->print(&mt('The following fields were not updated: ').'<ul>');
                   2057:             my %fieldtitles = &Apache::loncommon::personal_data_fieldtitles();
                   2058:             foreach my $field (@mod_disallowed) {
                   2059:                 $r->print('<li>'.$fieldtitles{$field}.'</li>'."\n"); 
                   2060:             }
1.207     raeburn  2061:             $r->print('</ul>');
                   2062:             if (@mod_disallowed == 1) {
                   2063:                 $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));
                   2064:             } else {
                   2065:                 $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));
                   2066:             }
                   2067:             $r->print('<span class="LC_cusr_emph">'.$rolestr.'</span><br />'.
                   2068:                       &mt('Contact your <a href="[_1]">helpdesk</a> for more information.',"javascript:helpMenu('display')").'<br />');
1.206     raeburn  2069:         }
                   2070:         $r->print($no_forceid_alert.
                   2071:                   &Apache::lonuserutils::print_namespacing_alerts($env{'form.ccdomain'},\%alerts, \%curr_rules));
1.4       www      2072:     }
1.27      matthew  2073:     ##
1.4       www      2074:     my $now=time;
1.193     raeburn  2075:     my $rolechanges = 0;
1.73      sakharuk 2076:     $r->print('<h3>'.&mt('Modifying Roles').'</h3>');
1.135     raeburn  2077:     foreach my $key (keys (%env)) {
                   2078: 	next if (! $env{$key});
1.190     raeburn  2079:         next if ($key eq 'form.action');
1.27      matthew  2080: 	# Revoke roles
1.135     raeburn  2081: 	if ($key=~/^form\.rev/) {
                   2082: 	    if ($key=~/^form\.rev\:([^\_]+)\_([^\_\.]+)$/) {
1.64      www      2083: # Revoke standard role
1.170     albertel 2084: 		my ($scope,$role) = ($1,$2);
                   2085: 		my $result =
                   2086: 		    &Apache::lonnet::revokerole($env{'form.ccdomain'},
                   2087: 						$env{'form.ccuname'},
                   2088: 						$scope,$role);
                   2089: 	        $r->print(&mt('Revoking [_1] in [_2]: [_3]',
                   2090: 			      $role,$scope,'<b>'.$result.'</b>').'<br />');
                   2091: 		if ($role eq 'st') {
1.202     raeburn  2092: 		    my $result = 
1.198     raeburn  2093:                         &Apache::lonuserutils::classlist_drop($scope,
                   2094:                             $env{'form.ccuname'},$env{'form.ccdomain'},
1.202     raeburn  2095: 			    $now);
1.170     albertel 2096: 		    $r->print($result);
1.53      www      2097: 		}
1.196     raeburn  2098: 	    }
1.195     raeburn  2099: 	    if ($key=~m{^form\.rev\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}s) {
1.64      www      2100: # Revoke custom role
1.113     raeburn  2101: 		$r->print(&mt('Revoking custom role:').
1.139     albertel 2102:                       ' '.$4.' by '.$3.':'.$2.' in '.$1.': <b>'.
1.101     albertel 2103:                       &Apache::lonnet::revokecustomrole($env{'form.ccdomain'},
                   2104: 				  $env{'form.ccuname'},$1,$2,$3,$4).
1.102     albertel 2105: 		'</b><br />');
1.64      www      2106: 	    }
1.193     raeburn  2107:             $rolechanges ++;
1.135     raeburn  2108: 	} elsif ($key=~/^form\.del/) {
                   2109: 	    if ($key=~/^form\.del\:([^\_]+)\_([^\_\.]+)$/) {
1.116     raeburn  2110: # Delete standard role
1.170     albertel 2111: 		my ($scope,$role) = ($1,$2);
                   2112: 		my $result =
                   2113: 		    &Apache::lonnet::assignrole($env{'form.ccdomain'},
                   2114: 						$env{'form.ccuname'},
                   2115: 						$scope,$role,$now,0,1);
                   2116: 	        $r->print(&mt('Deleting [_1] in [_2]: [_3]',$role,$scope,
                   2117: 			      '<b>'.$result.'</b>').'<br />');
                   2118: 		if ($role eq 'st') {
1.202     raeburn  2119: 		    my $result = 
1.198     raeburn  2120:                         &Apache::lonuserutils::classlist_drop($scope,
                   2121:                             $env{'form.ccuname'},$env{'form.ccdomain'},
1.202     raeburn  2122: 			    $now);
1.170     albertel 2123: 		    $r->print($result);
1.81      albertel 2124: 		}
1.116     raeburn  2125:             }
1.139     albertel 2126: 	    if ($key=~m{^form\.del\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
1.116     raeburn  2127:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
                   2128: # Delete custom role
1.170     albertel 2129:                 $r->print(&mt('Deleting custom role [_1] by [_2]:[_3] in [_4]',
1.116     raeburn  2130:                       $rolename,$rnam,$rdom,$url).': <b>'.
                   2131:                       &Apache::lonnet::assigncustomrole($env{'form.ccdomain'},
                   2132:                          $env{'form.ccuname'},$url,$rdom,$rnam,$rolename,$now,
                   2133:                          0,1).'</b><br />');
                   2134:             }
1.193     raeburn  2135:             $rolechanges ++;
1.135     raeburn  2136: 	} elsif ($key=~/^form\.ren/) {
1.101     albertel 2137:             my $udom = $env{'form.ccdomain'};
                   2138:             my $uname = $env{'form.ccuname'};
1.116     raeburn  2139: # Re-enable standard role
1.135     raeburn  2140: 	    if ($key=~/^form\.ren\:([^\_]+)\_([^\_\.]+)$/) {
1.89      raeburn  2141:                 my $url = $1;
                   2142:                 my $role = $2;
                   2143:                 my $logmsg;
                   2144:                 my $output;
                   2145:                 if ($role eq 'st') {
1.141     albertel 2146:                     if ($url =~ m-^/($match_domain)/($match_courseid)/?(\w*)$-) {
1.129     albertel 2147:                         my $result = &Apache::loncommon::commit_studentrole(\$logmsg,$udom,$uname,$url,$role,$now,0,$1,$2,$3);
1.89      raeburn  2148:                         if (($result =~ /^error/) || ($result eq 'not_in_class') || ($result eq 'unknown_course')) {
                   2149:                             $output = "Error: $result\n";
                   2150:                         } else {
                   2151:                             $output = &mt('Assigning').' '.$role.' in '.$url.
                   2152:                                       &mt('starting').' '.localtime($now).
                   2153:                                       ': <br />'.$logmsg.'<br />'.
                   2154:                                       &mt('Add to classlist').': <b>ok</b><br />';
                   2155:                         }
                   2156:                     }
                   2157:                 } else {
1.101     albertel 2158: 		    my $result=&Apache::lonnet::assignrole($env{'form.ccdomain'},
                   2159:                                $env{'form.ccuname'},$url,$role,0,$now);
1.116     raeburn  2160: 		    $output = &mt('Re-enabling [_1] in [_2]: <b>[_3]</b>',
1.89      raeburn  2161: 			      $role,$url,$result).'<br />';
1.27      matthew  2162: 		}
1.89      raeburn  2163:                 $r->print($output);
1.113     raeburn  2164: 	    }
1.116     raeburn  2165: # Re-enable custom role
1.139     albertel 2166: 	    if ($key=~m{^form\.ren\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
1.116     raeburn  2167:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
                   2168:                 my $result = &Apache::lonnet::assigncustomrole(
                   2169:                                $env{'form.ccdomain'}, $env{'form.ccuname'},
                   2170:                                $url,$rdom,$rnam,$rolename,0,$now);
                   2171:                 $r->print(&mt('Re-enabling custom role [_1] by [_2]@[_3] in [_4] : <b>[_5]</b>',
                   2172:                           $rolename,$rnam,$rdom,$url,$result).'<br />');
                   2173:             }
1.193     raeburn  2174:             $rolechanges ++;
1.135     raeburn  2175: 	} elsif ($key=~/^form\.act/) {
1.101     albertel 2176:             my $udom = $env{'form.ccdomain'};
                   2177:             my $uname = $env{'form.ccuname'};
1.141     albertel 2178: 	    if ($key=~/^form\.act\_($match_domain)\_($match_courseid)\_cr_cr_($match_domain)_($match_username)_([^\_]+)$/) {
1.65      www      2179:                 # Activate a custom role
1.83      albertel 2180: 		my ($one,$two,$three,$four,$five)=($1,$2,$3,$4,$5);
                   2181: 		my $url='/'.$one.'/'.$two;
                   2182: 		my $full=$one.'_'.$two.'_cr_cr_'.$three.'_'.$four.'_'.$five;
1.65      www      2183: 
1.101     albertel 2184:                 my $start = ( $env{'form.start_'.$full} ?
                   2185:                               $env{'form.start_'.$full} :
1.88      raeburn  2186:                               $now );
1.101     albertel 2187:                 my $end   = ( $env{'form.end_'.$full} ?
                   2188:                               $env{'form.end_'.$full} :
1.88      raeburn  2189:                               0 );
                   2190:                                                                                      
                   2191:                 # split multiple sections
                   2192:                 my %sections = ();
1.101     albertel 2193:                 my $num_sections = &build_roles($env{'form.sec_'.$full},\%sections,$5);
1.88      raeburn  2194:                 if ($num_sections == 0) {
1.129     albertel 2195:                     $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$url,$three,$four,$five,$start,$end));
1.88      raeburn  2196:                 } else {
1.114     albertel 2197: 		    my %curr_groups =
1.117     raeburn  2198: 			&Apache::longroup::coursegroups($one,$two);
1.113     raeburn  2199:                     foreach my $sec (sort {$a cmp $b} keys %sections) {
                   2200:                         if (($sec eq 'none') || ($sec eq 'all') || 
                   2201:                             exists($curr_groups{$sec})) {
                   2202:                             $disallowed{$sec} = $url;
                   2203:                             next;
                   2204:                         }
                   2205:                         my $securl = $url.'/'.$sec;
1.129     albertel 2206: 		        $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$securl,$three,$four,$five,$start,$end));
1.88      raeburn  2207:                     }
                   2208:                 }
1.142     raeburn  2209: 	    } elsif ($key=~/^form\.act\_($match_domain)\_($match_name)\_([^\_]+)$/) {
1.27      matthew  2210: 		# Activate roles for sections with 3 id numbers
                   2211: 		# set start, end times, and the url for the class
1.83      albertel 2212: 		my ($one,$two,$three)=($1,$2,$3);
1.101     albertel 2213: 		my $start = ( $env{'form.start_'.$one.'_'.$two.'_'.$three} ? 
                   2214: 			      $env{'form.start_'.$one.'_'.$two.'_'.$three} : 
1.27      matthew  2215: 			      $now );
1.101     albertel 2216: 		my $end   = ( $env{'form.end_'.$one.'_'.$two.'_'.$three} ? 
                   2217: 			      $env{'form.end_'.$one.'_'.$two.'_'.$three} :
1.27      matthew  2218: 			      0 );
1.83      albertel 2219: 		my $url='/'.$one.'/'.$two;
1.88      raeburn  2220:                 my $type = 'three';
                   2221:                 # split multiple sections
                   2222:                 my %sections = ();
1.101     albertel 2223:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two.'_'.$three},\%sections,$three);
1.88      raeburn  2224:                 if ($num_sections == 0) {
1.129     albertel 2225:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,''));
1.88      raeburn  2226:                 } else {
1.114     albertel 2227:                     my %curr_groups = 
1.117     raeburn  2228: 			&Apache::longroup::coursegroups($one,$two);
1.88      raeburn  2229:                     my $emptysec = 0;
                   2230:                     foreach my $sec (sort {$a cmp $b} keys %sections) {
                   2231:                         $sec =~ s/\W//g;
1.113     raeburn  2232:                         if ($sec ne '') {
                   2233:                             if (($sec eq 'none') || ($sec eq 'all') || 
                   2234:                                 exists($curr_groups{$sec})) {
                   2235:                                 $disallowed{$sec} = $url;
                   2236:                                 next;
                   2237:                             }
1.88      raeburn  2238:                             my $securl = $url.'/'.$sec;
1.129     albertel 2239:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$three,$start,$end,$one,$two,$sec));
1.88      raeburn  2240:                         } else {
                   2241:                             $emptysec = 1;
                   2242:                         }
                   2243:                     }
                   2244:                     if ($emptysec) {
1.129     albertel 2245:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,''));
1.88      raeburn  2246:                     }
                   2247:                 } 
1.135     raeburn  2248: 	    } elsif ($key=~/^form\.act\_([^\_]+)\_([^\_]+)$/) {
1.27      matthew  2249: 		# Activate roles for sections with two id numbers
                   2250: 		# set start, end times, and the url for the class
1.101     albertel 2251: 		my $start = ( $env{'form.start_'.$1.'_'.$2} ? 
                   2252: 			      $env{'form.start_'.$1.'_'.$2} : 
1.27      matthew  2253: 			      $now );
1.101     albertel 2254: 		my $end   = ( $env{'form.end_'.$1.'_'.$2} ? 
                   2255: 			      $env{'form.end_'.$1.'_'.$2} :
1.27      matthew  2256: 			      0 );
                   2257: 		my $url='/'.$1.'/';
1.88      raeburn  2258:                 # split multiple sections
                   2259:                 my %sections = ();
1.101     albertel 2260:                 my $num_sections = &build_roles($env{'form.sec_'.$1.'_'.$2},\%sections,$2);
1.88      raeburn  2261:                 if ($num_sections == 0) {
1.129     albertel 2262:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$2,$start,$end,$1,undef,''));
1.88      raeburn  2263:                 } else {
                   2264:                     my $emptysec = 0;
                   2265:                     foreach my $sec (sort {$a cmp $b} keys %sections) {
                   2266:                         if ($sec ne '') {
                   2267:                             my $securl = $url.'/'.$sec;
1.129     albertel 2268:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$2,$start,$end,$1,undef,$sec));
1.88      raeburn  2269:                         } else {
                   2270:                             $emptysec = 1;
                   2271:                         }
                   2272:                     }
                   2273:                     if ($emptysec) {
1.129     albertel 2274:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$2,$start,$end,$1,undef,''));
1.88      raeburn  2275:                     }
                   2276:                 }
1.64      www      2277: 	    } else {
1.190     raeburn  2278: 		$r->print('<p><span class="LC_error">'.&mt('ERROR').': '.&mt('Unknown command').' <tt>'.$key.'</tt></span></p><br />');
1.64      www      2279:             }
1.113     raeburn  2280:             foreach my $key (sort(keys(%disallowed))) {
                   2281:                 if (($key eq 'none') || ($key eq 'all')) {  
                   2282:                     $r->print('<p>'.&mt('[_1] may not be used as the name for a section, as it is a reserved word.',$key));
                   2283:                 } else {
                   2284:                     $r->print('<p>'.&mt('[_1] may not be used as the name for a section, as it is the name of a course group.',$key));
                   2285:                 }
                   2286:                 $r->print(' '.&mt('Please <a href="javascript:history.go(-1)">go back</a> and choose a different section name.').'</p><br />');
                   2287:             }
1.193     raeburn  2288:             $rolechanges ++;
1.113     raeburn  2289: 	}
1.101     albertel 2290:     } # End of foreach (keys(%env))
1.75      www      2291: # Flush the course logs so reverse user roles immediately updated
                   2292:     &Apache::lonnet::flushcourselogs();
1.193     raeburn  2293:     if (!$rolechanges) {
                   2294:         $r->print(&mt('No roles to modify'));
                   2295:     }
1.188     raeburn  2296:     $r->print(&Apache::loncommon::end_page());
                   2297: }
                   2298: 
1.204     raeburn  2299: sub get_defaultquota_text {
                   2300:     my ($settingstatus) = @_;
                   2301:     my $defquotatext; 
                   2302:     if ($settingstatus eq '') {
                   2303:         $defquotatext = &mt('(default)');
                   2304:     } else {
                   2305:         my ($usertypes,$order) =
                   2306:             &Apache::lonnet::retrieve_inst_usertypes($env{'form.ccdomain'});
                   2307:         if ($usertypes->{$settingstatus} eq '') {
                   2308:             $defquotatext = &mt('(default)');
                   2309:         } else {
                   2310:             $defquotatext = &mt('(default for [_1])',$usertypes->{$settingstatus});
                   2311:         }
                   2312:     }
                   2313:     return $defquotatext;
                   2314: }
                   2315: 
1.188     raeburn  2316: sub update_result_form {
                   2317:     my ($uhome) = @_;
                   2318:     my $outcome = 
                   2319:     '<form name="userupdate" method="post" />'."\n";
1.160     raeburn  2320:     foreach my $item ('srchby','srchin','srchtype','srchterm','srchdomain','ccuname','ccdomain') {
1.188     raeburn  2321:         $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
1.160     raeburn  2322:     }
1.207     raeburn  2323:     if ($env{'form.origname'} ne '') {
                   2324:         $outcome .= '<input type="hidden" name="origname" value="'.$env{'form.origname'}.'" />'."\n";
                   2325:     }
1.160     raeburn  2326:     foreach my $item ('sortby','seluname','seludom') {
                   2327:         if (exists($env{'form.'.$item})) {
1.188     raeburn  2328:             $outcome .= '<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n";
1.160     raeburn  2329:         }
                   2330:     }
1.188     raeburn  2331:     if ($uhome eq 'no_host') {
                   2332:         $outcome .= '<input type="hidden" name="forcenewuser" value="1" />'."\n";
                   2333:     }
                   2334:     $outcome .= '<input type="hidden" name="phase" value="" />'."\n".
                   2335:                 '<input type ="hidden" name="currstate" value="" />'."\n".
1.190     raeburn  2336:                 '<input type ="hidden" name="action" value="singleuser" />'."\n".
1.188     raeburn  2337:                 '</form>';
                   2338:     return $outcome;
1.4       www      2339: }
                   2340: 
1.149     raeburn  2341: sub quota_admin {
                   2342:     my ($setquota,$changeHash) = @_;
                   2343:     my $quotachanged;
                   2344:     if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
                   2345:         # Current user has quota modification privileges
                   2346:         $quotachanged = 1;
                   2347:         $changeHash->{'portfolioquota'} = $setquota;
                   2348:     }
                   2349:     return $quotachanged;
                   2350: }
                   2351: 
1.88      raeburn  2352: sub build_roles {
1.89      raeburn  2353:     my ($sectionstr,$sections,$role) = @_;
1.88      raeburn  2354:     my $num_sections = 0;
                   2355:     if ($sectionstr=~ /,/) {
                   2356:         my @secnums = split/,/,$sectionstr;
1.89      raeburn  2357:         if ($role eq 'st') {
                   2358:             $secnums[0] =~ s/\W//g;
                   2359:             $$sections{$secnums[0]} = 1;
                   2360:             $num_sections = 1;
                   2361:         } else {
                   2362:             foreach my $sec (@secnums) {
                   2363:                 $sec =~ ~s/\W//g;
1.150     banghart 2364:                 if (!($sec eq "")) {
1.89      raeburn  2365:                     if (exists($$sections{$sec})) {
                   2366:                         $$sections{$sec} ++;
                   2367:                     } else {
                   2368:                         $$sections{$sec} = 1;
                   2369:                         $num_sections ++;
                   2370:                     }
1.88      raeburn  2371:                 }
                   2372:             }
                   2373:         }
                   2374:     } else {
                   2375:         $sectionstr=~s/\W//g;
                   2376:         unless ($sectionstr eq '') {
                   2377:             $$sections{$sectionstr} = 1;
                   2378:             $num_sections ++;
                   2379:         }
                   2380:     }
1.129     albertel 2381: 
1.88      raeburn  2382:     return $num_sections;
                   2383: }
                   2384: 
1.58      www      2385: # ========================================================== Custom Role Editor
                   2386: 
                   2387: sub custom_role_editor {
1.160     raeburn  2388:     my ($r) = @_;
1.101     albertel 2389:     my $rolename=$env{'form.rolename'};
1.58      www      2390: 
1.59      www      2391:     if ($rolename eq 'make new role') {
1.101     albertel 2392: 	$rolename=$env{'form.newrolename'};
1.59      www      2393:     }
                   2394: 
1.63      www      2395:     $rolename=~s/[^A-Za-z0-9]//gs;
1.58      www      2396: 
1.190     raeburn  2397:     if (!$rolename || $env{'form.phase'} eq 'pickrole') {
1.58      www      2398: 	&print_username_entry_form($r);
                   2399:         return;
                   2400:     }
1.153     banghart 2401: # ------------------------------------------------------- What can be assigned?
                   2402:     my %full=();
                   2403:     my %courselevel=();
                   2404:     my %courselevelcurrent=();
1.61      www      2405:     my $syspriv='';
                   2406:     my $dompriv='';
                   2407:     my $coursepriv='';
1.153     banghart 2408:     my $body_top;
1.150     banghart 2409:     my ($disp_dummy,$disp_roles) = &Apache::lonnet::get('roles',["st"]);
1.59      www      2410:     my ($rdummy,$roledef)=
                   2411: 			 &Apache::lonnet::get('roles',["rolesdef_$rolename"]);
1.60      www      2412: # ------------------------------------------------------- Does this role exist?
1.153     banghart 2413:     $body_top .= '<h2>';
1.59      www      2414:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
1.153     banghart 2415: 	$body_top .= &mt('Existing Role').' "';
1.61      www      2416: # ------------------------------------------------- Get current role privileges
                   2417: 	($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
1.59      www      2418:     } else {
1.153     banghart 2419: 	$body_top .= &mt('New Role').' "';
1.59      www      2420: 	$roledef='';
                   2421:     }
1.153     banghart 2422:     $body_top .= $rolename.'"</h2>';
1.135     raeburn  2423:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   2424: 	my ($priv,$restrict)=split(/\&/,$item);
1.150     banghart 2425:         if (!$restrict) { $restrict='F'; }
1.60      www      2426:         $courselevel{$priv}=$restrict;
1.61      www      2427:         if ($coursepriv=~/\:$priv/) {
                   2428: 	    $courselevelcurrent{$priv}=1;
                   2429: 	}
1.60      www      2430: 	$full{$priv}=1;
                   2431:     }
                   2432:     my %domainlevel=();
1.61      www      2433:     my %domainlevelcurrent=();
1.135     raeburn  2434:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:d'})) {
                   2435: 	my ($priv,$restrict)=split(/\&/,$item);
1.150     banghart 2436:         if (!$restrict) { $restrict='F'; }
1.60      www      2437:         $domainlevel{$priv}=$restrict;
1.61      www      2438:         if ($dompriv=~/\:$priv/) {
                   2439: 	    $domainlevelcurrent{$priv}=1;
                   2440: 	}
1.60      www      2441: 	$full{$priv}=1;
                   2442:     }
1.61      www      2443:     my %systemlevel=();
                   2444:     my %systemlevelcurrent=();
1.135     raeburn  2445:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:s'})) {
                   2446: 	my ($priv,$restrict)=split(/\&/,$item);
1.150     banghart 2447:         if (!$restrict) { $restrict='F'; }
1.61      www      2448:         $systemlevel{$priv}=$restrict;
                   2449:         if ($syspriv=~/\:$priv/) {
                   2450: 	    $systemlevelcurrent{$priv}=1;
                   2451: 	}
                   2452: 	$full{$priv}=1;
                   2453:     }
1.160     raeburn  2454:     my ($jsback,$elements) = &crumb_utilities();
1.154     banghart 2455:     my $button_code = "\n";
1.153     banghart 2456:     my $head_script = "\n";
                   2457:     $head_script .= '<script type="text/javascript">'."\n";
1.154     banghart 2458:     my @template_roles = ("cc","in","ta","ep","st");
                   2459:     foreach my $role (@template_roles) {
                   2460:         $head_script .= &make_script_template($role);
                   2461:         $button_code .= &make_button_code($role);
                   2462:     }
1.160     raeburn  2463:     $head_script .= "\n".$jsback."\n".'</script>'."\n";
1.153     banghart 2464:     $r->print(&Apache::loncommon::start_page('Custom Role Editor',$head_script));
1.160     raeburn  2465:    &Apache::lonhtmlcommon::add_breadcrumb
1.190     raeburn  2466:      ({href=>"javascript:backPage(document.form1,'pickrole','')",
                   2467:        text=>"Pick custom role",
1.160     raeburn  2468:        faq=>282,bug=>'Instructor Interface',},
                   2469:       {href=>"javascript:backPage(document.form1,'','')",
                   2470:          text=>"Edit custom role",
                   2471:          faq=>282,bug=>'Instructor Interface',});
                   2472:     $r->print(&Apache::lonhtmlcommon::breadcrumbs('User Management'));
                   2473: 
1.153     banghart 2474:     $r->print($body_top);
1.73      sakharuk 2475:     my %lt=&Apache::lonlocal::texthash(
                   2476: 		    'prv'  => "Privilege",
1.131     raeburn  2477: 		    'crl'  => "Course Level",
1.73      sakharuk 2478:                     'dml'  => "Domain Level",
1.150     banghart 2479:                     'ssl'  => "System Level");
1.152     banghart 2480:     $r->print('Select a Template<br />');
1.154     banghart 2481:     $r->print('<form action="">');
                   2482:     $r->print($button_code);
                   2483:     $r->print('</form>');
1.61      www      2484:     $r->print(<<ENDCCF);
1.160     raeburn  2485: <form name="form1" method="post">
1.61      www      2486: <input type="hidden" name="phase" value="set_custom_roles" />
                   2487: <input type="hidden" name="rolename" value="$rolename" />
                   2488: ENDCCF
1.135     raeburn  2489:     $r->print(&Apache::loncommon::start_data_table().
                   2490:               &Apache::loncommon::start_data_table_header_row(). 
                   2491: '<th>'.$lt{'prv'}.'</th><th>'.$lt{'crl'}.'</th><th>'.$lt{'dml'}.
                   2492: '</th><th>'.$lt{'ssl'}.'</th>'.
                   2493:               &Apache::loncommon::end_data_table_header_row());
1.119     raeburn  2494:     foreach my $priv (sort keys %full) {
                   2495:         my $privtext = &Apache::lonnet::plaintext($priv);
1.135     raeburn  2496:         $r->print(&Apache::loncommon::start_data_table_row().
                   2497: 	          '<td>'.$privtext.'</td><td>'.
1.150     banghart 2498:     ($courselevel{$priv}?'<input type="checkbox" name="'.$priv.'_c" '.
1.119     raeburn  2499:     ($courselevelcurrent{$priv}?'checked="1"':'').' />':'&nbsp;').
1.61      www      2500:     '</td><td>'.
1.150     banghart 2501:     ($domainlevel{$priv}?'<input type="checkbox" name="'.$priv.'_d" '.
1.119     raeburn  2502:     ($domainlevelcurrent{$priv}?'checked="1"':'').' />':'&nbsp;').
1.61      www      2503:     '</td><td>'.
1.150     banghart 2504:     ($systemlevel{$priv}?'<input type="checkbox" name="'.$priv.'_s" '.
1.119     raeburn  2505:     ($systemlevelcurrent{$priv}?'checked="1"':'').' />':'&nbsp;').
1.135     raeburn  2506:     '</td>'.
                   2507:              &Apache::loncommon::end_data_table_row());
1.60      www      2508:     }
1.135     raeburn  2509:     $r->print(&Apache::loncommon::end_data_table().
1.190     raeburn  2510:    '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'.
1.160     raeburn  2511:    '<input type="hidden" name="startrolename" value="'.$env{'form.rolename'}.
1.179     raeburn  2512:    '" />'."\n".'<input type="hidden" name="currstate" value="" />'."\n".   
1.160     raeburn  2513:    '<input type="reset" value="'.&mt("Reset").'" />'."\n".
                   2514:    '<input type="submit" value="'.&mt('Define Role').'" /></form>'.
1.110     albertel 2515: 	      &Apache::loncommon::end_page());
1.61      www      2516: }
1.153     banghart 2517: # --------------------------------------------------------
                   2518: sub make_script_template {
                   2519:     my ($role) = @_;
                   2520:     my %full_c=();
                   2521:     my %full_d=();
                   2522:     my %full_s=();
                   2523:     my $return_script;
                   2524:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   2525:         my ($priv,$restrict)=split(/\&/,$item);
                   2526:         $full_c{$priv}=1;
                   2527:     }
                   2528:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:d'})) {
                   2529:         my ($priv,$restrict)=split(/\&/,$item);
                   2530:         $full_d{$priv}=1;
                   2531:     }
1.154     banghart 2532:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:s'})) {
1.153     banghart 2533:         my ($priv,$restrict)=split(/\&/,$item);
                   2534:         $full_s{$priv}=1;
                   2535:     }
                   2536:     $return_script .= 'function set_'.$role.'() {'."\n";
                   2537:     my @temp = split(/:/,$Apache::lonnet::pr{$role.':c'});
                   2538:     my %role_c;
1.155     banghart 2539:     foreach my $priv (@temp) {
1.153     banghart 2540:         my ($priv_item, $dummy) = split(/\&/,$priv);
                   2541:         $role_c{$priv_item} = 1;
                   2542:     }
                   2543:     foreach my $priv_item (keys(%full_c)) {
                   2544:         my ($priv, $dummy) = split(/\&/,$priv_item);
                   2545:         if (exists($role_c{$priv})) {
                   2546:             $return_script .= "document.form1.$priv"."_c.checked = true;\n";
                   2547:         } else {
                   2548:             $return_script .= "document.form1.$priv"."_c.checked = false;\n";
                   2549:         }
                   2550:     }
1.154     banghart 2551:     my %role_d;
                   2552:     @temp = split(/:/,$Apache::lonnet::pr{$role.':d'});
                   2553:     foreach my $priv(@temp) {
                   2554:         my ($priv_item, $dummy) = split(/\&/,$priv);
                   2555:         $role_d{$priv_item} = 1;
                   2556:     }
                   2557:     foreach my $priv_item (keys(%full_d)) {
                   2558:         my ($priv, $dummy) = split(/\&/,$priv_item);
                   2559:         if (exists($role_d{$priv})) {
                   2560:             $return_script .= "document.form1.$priv"."_d.checked = true;\n";
                   2561:         } else {
                   2562:             $return_script .= "document.form1.$priv"."_d.checked = false;\n";
                   2563:         }
                   2564:     }
                   2565:     my %role_s;
                   2566:     @temp = split(/:/,$Apache::lonnet::pr{$role.':s'});
                   2567:     foreach my $priv(@temp) {
                   2568:         my ($priv_item, $dummy) = split(/\&/,$priv);
                   2569:         $role_s{$priv_item} = 1;
                   2570:     }
                   2571:     foreach my $priv_item (keys(%full_s)) {
1.153     banghart 2572:         my ($priv, $dummy) = split(/\&/,$priv_item);
1.154     banghart 2573:         if (exists($role_s{$priv})) {
                   2574:             $return_script .= "document.form1.$priv"."_s.checked = true;\n";
                   2575:         } else {
                   2576:             $return_script .= "document.form1.$priv"."_s.checked = false;\n";
                   2577:         }
1.153     banghart 2578:     }
                   2579:     $return_script .= '}'."\n";
1.154     banghart 2580:     return ($return_script);
                   2581: }
                   2582: # ----------------------------------------------------------
                   2583: sub make_button_code {
                   2584:     my ($role) = @_;
                   2585:     my $label = &Apache::lonnet::plaintext($role);
                   2586:     my $button_code = '<input type="button" onClick="set_'.$role.'()" value="'.$label.'" />';    
                   2587:     return ($button_code);
1.153     banghart 2588: }
1.61      www      2589: # ---------------------------------------------------------- Call to definerole
                   2590: sub set_custom_role {
1.110     albertel 2591:     my ($r) = @_;
1.101     albertel 2592:     my $rolename=$env{'form.rolename'};
1.63      www      2593:     $rolename=~s/[^A-Za-z0-9]//gs;
1.150     banghart 2594:     if (!$rolename) {
1.190     raeburn  2595: 	&custom_role_editor($r);
1.61      www      2596:         return;
                   2597:     }
1.160     raeburn  2598:     my ($jsback,$elements) = &crumb_utilities();
                   2599:     my $jscript = '<script type="text/javascript">'.$jsback."\n".'</script>';
                   2600: 
                   2601:     $r->print(&Apache::loncommon::start_page('Save Custom Role'),$jscript);
                   2602:     &Apache::lonhtmlcommon::add_breadcrumb
1.190     raeburn  2603:         ({href=>"javascript:backPage(document.customresult,'pickrole','')",
                   2604:           text=>"Pick custom role",
1.160     raeburn  2605:           faq=>282,bug=>'Instructor Interface',},
                   2606:          {href=>"javascript:backPage(document.customresult,'selected_custom_edit','')",
                   2607:           text=>"Edit custom role",
                   2608:           faq=>282,bug=>'Instructor Interface',},
                   2609:          {href=>"javascript:backPage(document.customresult,'set_custom_roles','')",
                   2610:           text=>"Result",
                   2611:           faq=>282,bug=>'Instructor Interface',});
                   2612:     $r->print(&Apache::lonhtmlcommon::breadcrumbs('User Management'));
                   2613: 
1.61      www      2614:     my ($rdummy,$roledef)=
1.110     albertel 2615: 	&Apache::lonnet::get('roles',["rolesdef_$rolename"]);
                   2616: 
1.61      www      2617: # ------------------------------------------------------- Does this role exist?
1.188     raeburn  2618:     $r->print('<h3>');
1.61      www      2619:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
1.73      sakharuk 2620: 	$r->print(&mt('Existing Role').' "');
1.61      www      2621:     } else {
1.73      sakharuk 2622: 	$r->print(&mt('New Role').' "');
1.61      www      2623: 	$roledef='';
                   2624:     }
1.188     raeburn  2625:     $r->print($rolename.'"</h3>');
1.61      www      2626: # ------------------------------------------------------- What can be assigned?
                   2627:     my $sysrole='';
                   2628:     my $domrole='';
                   2629:     my $courole='';
                   2630: 
1.135     raeburn  2631:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   2632: 	my ($priv,$restrict)=split(/\&/,$item);
1.150     banghart 2633:         if (!$restrict) { $restrict=''; }
                   2634:         if ($env{'form.'.$priv.'_c'}) {
1.135     raeburn  2635: 	    $courole.=':'.$item;
1.61      www      2636: 	}
                   2637:     }
                   2638: 
1.135     raeburn  2639:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:d'})) {
                   2640: 	my ($priv,$restrict)=split(/\&/,$item);
1.150     banghart 2641:         if (!$restrict) { $restrict=''; }
                   2642:         if ($env{'form.'.$priv.'_d'}) {
1.135     raeburn  2643: 	    $domrole.=':'.$item;
1.61      www      2644: 	}
                   2645:     }
                   2646: 
1.135     raeburn  2647:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:s'})) {
                   2648: 	my ($priv,$restrict)=split(/\&/,$item);
1.150     banghart 2649:         if (!$restrict) { $restrict=''; }
                   2650:         if ($env{'form.'.$priv.'_s'}) {
1.135     raeburn  2651: 	    $sysrole.=':'.$item;
1.61      www      2652: 	}
                   2653:     }
1.63      www      2654:     $r->print('<br />Defining Role: '.
1.61      www      2655: 	   &Apache::lonnet::definerole($rolename,$sysrole,$domrole,$courole));
1.101     albertel 2656:     if ($env{'request.course.id'}) {
                   2657:         my $url='/'.$env{'request.course.id'};
1.63      www      2658:         $url=~s/\_/\//g;
1.73      sakharuk 2659: 	$r->print('<br />'.&mt('Assigning Role to Self').': '.
1.101     albertel 2660: 	      &Apache::lonnet::assigncustomrole($env{'user.domain'},
                   2661: 						$env{'user.name'},
1.63      www      2662: 						$url,
1.101     albertel 2663: 						$env{'user.domain'},
                   2664: 						$env{'user.name'},
1.63      www      2665: 						$rolename));
                   2666:     }
1.190     raeburn  2667:     $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  2668:     $r->print(&Apache::lonhtmlcommon::echo_form_input([]).'</form>');
1.110     albertel 2669:     $r->print(&Apache::loncommon::end_page());
1.58      www      2670: }
                   2671: 
1.2       www      2672: # ================================================================ Main Handler
                   2673: sub handler {
                   2674:     my $r = shift;
                   2675:     if ($r->header_only) {
1.68      www      2676:        &Apache::loncommon::content_type($r,'text/html');
1.2       www      2677:        $r->send_http_header;
                   2678:        return OK;
                   2679:     }
1.190     raeburn  2680:     my $context;
                   2681:     if ($env{'request.course.id'}) {
                   2682:         $context = 'course';
                   2683:     } elsif ($env{'request.role'} =~ /^au\./) {
1.206     raeburn  2684:         $context = 'author';
1.190     raeburn  2685:     } else {
                   2686:         $context = 'domain';
                   2687:     }
                   2688:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
1.202     raeburn  2689:         ['action','state','callingform','roletype','showrole','bulkaction']);
1.190     raeburn  2690:     &Apache::lonhtmlcommon::clear_breadcrumbs();
1.202     raeburn  2691:     if ($env{'form.action'} ne 'dateselect') {
                   2692:         &Apache::lonhtmlcommon::add_breadcrumb
                   2693:             ({href=>"/adm/createuser",
                   2694:               text=>"User Management"});
                   2695:     }
1.209     raeburn  2696:     my ($permission,$allowed) = 
                   2697:         &Apache::lonuserutils::get_permission($context);
1.190     raeburn  2698:     if (!$allowed) {
                   2699:         $env{'user.error.msg'}=
                   2700:             "/adm/createuser:cst:0:0:Cannot create/modify user data ".
                   2701:                                  "or view user status.";
                   2702:         return HTTP_NOT_ACCEPTABLE;
                   2703:     }
                   2704: 
                   2705:     &Apache::loncommon::content_type($r,'text/html');
                   2706:     $r->send_http_header;
                   2707: 
                   2708:     # Main switch on form.action and form.state, as appropriate
                   2709:     if (! exists($env{'form.action'})) {
                   2710:         $r->print(&header());
                   2711:         $r->print(&Apache::lonhtmlcommon::breadcrumbs('User Management'));
1.208     raeburn  2712:         $r->print(&print_main_menu($permission,$context));
1.190     raeburn  2713:         $r->print(&Apache::loncommon::end_page());
                   2714:     } elsif ($env{'form.action'} eq 'upload' && $permission->{'cusr'}) {
                   2715:         $r->print(&header());
                   2716:         &Apache::lonhtmlcommon::add_breadcrumb
                   2717:             ({href=>'/adm/createuser?action=upload&state=',
                   2718:               text=>"Upload Users List"});
                   2719:         $r->print(&Apache::lonhtmlcommon::breadcrumbs('Upload Users List',
                   2720:                                                    'User_Management_Upload'));
                   2721:         $r->print('<form name="studentform" method="post" '.
                   2722:                   'enctype="multipart/form-data" '.
                   2723:                   ' action="/adm/createuser">'."\n");
                   2724:         if (! exists($env{'form.state'})) {
                   2725:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
                   2726:         } elsif ($env{'form.state'} eq 'got_file') {
                   2727:             &Apache::lonuserutils::print_upload_manager_form($r,$context);
                   2728:         } elsif ($env{'form.state'} eq 'enrolling') {
                   2729:             if ($env{'form.datatoken'}) {
                   2730:                 &Apache::lonuserutils::upfile_drop_add($r,$context);
                   2731:             }
                   2732:         } else {
                   2733:             &Apache::lonuserutils::print_first_users_upload_form($r,$context);
                   2734:         }
                   2735:         $r->print('</form>'.&Apache::loncommon::end_page());
1.213     raeburn  2736:     } elsif ((($env{'form.action'} eq 'singleuser') || ($env{'form.action'}
                   2737:              eq 'singlestudent')) && ($permission->{'cusr'})) {
1.190     raeburn  2738:         my $phase = $env{'form.phase'};
                   2739:         my @search = ('srchterm','srchby','srchin','srchtype','srchdomain');
1.192     albertel 2740: 	&Apache::loncreateuser::restore_prev_selections();
                   2741: 	my $srch;
                   2742: 	foreach my $item (@search) {
                   2743: 	    $srch->{$item} = $env{'form.'.$item};
                   2744: 	}
1.190     raeburn  2745: 
1.207     raeburn  2746:         if (($phase eq 'get_user_info') || ($phase eq 'userpicked') ||
                   2747:             ($phase eq 'createnewuser')) {
                   2748:             if ($env{'form.phase'} eq 'createnewuser') {
                   2749:                 my $response;
                   2750:                 if ($env{'form.srchterm'} !~ /^$match_username$/) {
                   2751:                     my $response = &mt('You must specify a valid username. Only the following are allowed: letters numbers - . @');
                   2752:                     &print_username_entry_form($r,$context,$response,$srch);
                   2753:                 } else {
                   2754:                     my $ccuname =&LONCAPA::clean_username($srch->{'srchterm'});
                   2755:                     my $ccdomain=&LONCAPA::clean_domain($srch->{'srchdomain'});
                   2756:                     &print_user_modification_page($r,$ccuname,$ccdomain,
                   2757:                                                   $srch,$response,$context);
                   2758:                 }
                   2759:             } elsif ($env{'form.phase'} eq 'get_user_info') {
1.190     raeburn  2760:                 my ($currstate,$response,$forcenewuser,$results) = 
                   2761:                     &user_search_result($srch);
                   2762:                 if ($env{'form.currstate'} eq 'modify') {
                   2763:                     $currstate = $env{'form.currstate'};
                   2764:                 }
                   2765:                 if ($currstate eq 'select') {
1.214   ! raeburn  2766:                     my $operation; 
        !          2767:                     if ($env{'form.action'} eq 'singleuser') {
        !          2768:                         $operation = 'createuser';
        !          2769:                     } elsif ($env{'form.action'} eq 'singlestudent') {
        !          2770:                         $operation = 'enrollstudent';
        !          2771:                     }
1.190     raeburn  2772:                     &print_user_selection_page($r,$response,$srch,$results,
1.214   ! raeburn  2773:                                                $operation,\@search,$context);
1.190     raeburn  2774:                 } elsif ($currstate eq 'modify') {
                   2775:                     my ($ccuname,$ccdomain);
                   2776:                     if (($srch->{'srchby'} eq 'uname') && 
                   2777:                         ($srch->{'srchtype'} eq 'exact')) {
                   2778:                         $ccuname = $srch->{'srchterm'};
                   2779:                         $ccdomain= $srch->{'srchdomain'};
                   2780:                     } else {
                   2781:                         my @matchedunames = keys(%{$results});
                   2782:                         ($ccuname,$ccdomain) = split(/:/,$matchedunames[0]);
                   2783:                     }
                   2784:                     $ccuname =&LONCAPA::clean_username($ccuname);
                   2785:                     $ccdomain=&LONCAPA::clean_domain($ccdomain);
                   2786:                     if ($env{'form.forcenewuser'}) {
                   2787:                         $response = '';
                   2788:                     }
                   2789:                     &print_user_modification_page($r,$ccuname,$ccdomain,
1.196     raeburn  2790:                                                   $srch,$response,$context);
1.190     raeburn  2791:                 } elsif ($currstate eq 'query') {
                   2792:                     &print_user_query_page($r,'createuser');
                   2793:                 } else {
1.207     raeburn  2794:                     &print_username_entry_form($r,$context,$response,$srch,
1.190     raeburn  2795:                                                $forcenewuser);
                   2796:                 }
                   2797:             } elsif ($env{'form.phase'} eq 'userpicked') {
                   2798:                 my $ccuname = &LONCAPA::clean_username($env{'form.seluname'});
                   2799:                 my $ccdomain = &LONCAPA::clean_domain($env{'form.seludom'});
1.196     raeburn  2800:                 &print_user_modification_page($r,$ccuname,$ccdomain,$srch,'',
                   2801:                                               $context);
1.190     raeburn  2802:             }
                   2803:         } elsif ($env{'form.phase'} eq 'update_user_data') {
1.206     raeburn  2804:             &update_user_data($r,$context);
1.190     raeburn  2805:         } else {
1.207     raeburn  2806:             &print_username_entry_form($r,$context,undef,$srch);
1.190     raeburn  2807:         }
                   2808:     } elsif ($env{'form.action'} eq 'custom' && $permission->{'custom'}) {
                   2809:         if ($env{'form.phase'} eq 'set_custom_roles') {
                   2810:             &set_custom_role($r);
                   2811:         } else {
                   2812:             &custom_role_editor($r);
                   2813:         }
1.207     raeburn  2814:     } elsif (($env{'form.action'} eq 'listusers') && 
                   2815:              ($permission->{'view'} || $permission->{'cusr'})) {
1.202     raeburn  2816:         if ($env{'form.phase'} eq 'bulkchange') {
                   2817:             &Apache::lonhtmlcommon::add_breadcrumb
                   2818:                 ({href=>'backPage(document.studentform)',
                   2819:                   text=>"List Users"});
                   2820:             my $setting = $env{'form.roletype'};
                   2821:             my $choice = $env{'form.bulkaction'};
                   2822:             $r->print(&header());
                   2823:             $r->print(&Apache::lonhtmlcommon::breadcrumbs("List Users",
                   2824:                                                           'User_Management_List'));
                   2825:             if ($permission->{'cusr'}) {
                   2826:                 &Apache::lonuserutils::update_user_list($r,$context,$setting,$choice);
                   2827:             }
                   2828:         } else {
                   2829:             &Apache::lonhtmlcommon::add_breadcrumb
                   2830:                 ({href=>'/adm/createuser?action=listusers',
                   2831:                   text=>"List Users"});
                   2832:             my ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles);
                   2833:             my $formname = 'studentform';
                   2834:             if ($context eq 'domain' && $env{'form.roletype'} eq 'course') {
                   2835:                 ($cb_jscript,$jscript,$totcodes,$codetitles,$idlist,$idlist_titles) = 
                   2836:                     &Apache::lonuserutils::courses_selector($env{'request.role.domain'},
                   2837:                                                             $formname);
                   2838:                 $jscript .= &verify_user_display();
                   2839:                 my $js = &add_script($jscript).$cb_jscript;
                   2840:                 my $loadcode = 
                   2841:                     &Apache::lonuserutils::course_selector_loadcode($formname);
                   2842:                 if ($loadcode ne '') {
                   2843:                     $r->print(&header($js,{'onload' => $loadcode,}));
                   2844:                 } else {
                   2845:                     $r->print(&header($js));
                   2846:                 }
1.191     raeburn  2847:             } else {
1.202     raeburn  2848:                 $r->print(&header(&add_script(&verify_user_display())));
1.191     raeburn  2849:             }
1.202     raeburn  2850:             $r->print(&Apache::lonhtmlcommon::breadcrumbs("List Users",
                   2851:                                                           'User_Management_List'));
                   2852:             &Apache::lonuserutils::print_userlist($r,undef,$permission,$context,
                   2853:                          $formname,$totcodes,$codetitles,$idlist,$idlist_titles);
                   2854:             $r->print(&Apache::loncommon::end_page());
1.191     raeburn  2855:         }
1.213     raeburn  2856:     } elsif ($env{'form.action'} eq 'drop' && $permission->{'cusr'}) {
                   2857:         $r->print(&header());
                   2858:         &Apache::lonhtmlcommon::add_breadcrumb
                   2859:             ({href=>'/adm/createuser?action=drop',
                   2860:               text=>"Drop Students"});
                   2861:         if (!exists($env{'form.state'})) {
                   2862:             $r->print(&Apache::lonhtmlcommon::breadcrumbs('Drop Students',
                   2863:                                                           'Course_Drop_Student'));
                   2864: 
                   2865:             &Apache::lonuserutils::print_drop_menu($r,$context,$permission);
                   2866:         } elsif ($env{'form.state'} eq 'done') {
                   2867:             &Apache::lonhtmlcommon::add_breadcrumb
                   2868:             ({href=>'/adm/createuser?action=drop',
                   2869:               text=>"Result"});
                   2870:             $r->print(&Apache::lonhtmlcommon::breadcrumbs('Drop Students',
                   2871:                                                           'Course_Drop_Student'));
                   2872:             &Apache::lonuserutils::update_user_list($r,$context,undef,
                   2873:                                                     $env{'form.action'});
                   2874:         }
                   2875:         $r->print(&Apache::loncommon::end_page());
1.202     raeburn  2876:     } elsif ($env{'form.action'} eq 'dateselect') {
                   2877:         if ($permission->{'cusr'}) {
                   2878:             $r->print(&header(undef,undef,{'no_nav_bar' => 1}).
                   2879:                       &Apache::lonuserutils::date_section_selector($context).
                   2880:                       &Apache::loncommon::end_page());
                   2881:         } else {
                   2882:             $r->print(&header().
                   2883:                      '<span class="LC_error">'.&mt('You do not have permission to modify dates or sections for users').'</span>'. 
                   2884:                      &Apache::loncommon::end_page());
                   2885:         }
1.190     raeburn  2886:     } else {
                   2887:         $r->print(&header());
1.202     raeburn  2888:         $r->print(&Apache::lonhtmlcommon::breadcrumbs('User Management'));
1.207     raeburn  2889:         $r->print(&print_main_menu($permission,$context));
1.190     raeburn  2890:         $r->print(&Apache::loncommon::end_page());
                   2891:     }
                   2892:     return OK;
                   2893: }
                   2894: 
                   2895: sub header {
1.202     raeburn  2896:     my ($jscript,$loaditems,$args) = @_;
1.190     raeburn  2897:     my $start_page;
                   2898:     if (ref($loaditems) eq 'HASH') {
1.202     raeburn  2899:         $start_page=&Apache::loncommon::start_page('User Management',$jscript,{'add_entries' => $loaditems});
1.190     raeburn  2900:     } else {
1.202     raeburn  2901:         $start_page=&Apache::loncommon::start_page('User Management',$jscript,$args);
1.190     raeburn  2902:     }
                   2903:     return $start_page;
                   2904: }
1.2       www      2905: 
1.191     raeburn  2906: sub add_script {
                   2907:     my ($js) = @_;
                   2908:     return '<script type="text/javascript">'."\n".$js."\n".'</script>';
                   2909: }
                   2910: 
1.202     raeburn  2911: sub verify_user_display {
                   2912:     my $output = <<"END";
                   2913: 
                   2914: function display_update() {
                   2915:     document.studentform.action.value = 'listusers';
                   2916:     document.studentform.phase.value = 'display';
                   2917:     document.studentform.submit();
                   2918: }
                   2919: 
                   2920: END
                   2921:     return $output;
                   2922: 
                   2923: }
                   2924: 
1.190     raeburn  2925: ###############################################################
                   2926: ###############################################################
                   2927: #  Menu Phase One
                   2928: sub print_main_menu {
1.208     raeburn  2929:     my ($permission,$context) = @_;
                   2930:     my %links = (
                   2931:                        domain => {
                   2932:                                    upload => 'Upload a File of Users',
                   2933:                                    singleuser => 'Add/Manage a Single User',
                   2934:                                    listusers => 'Manage Multiple Users',
                   2935:                                  },
                   2936:                        author => {
                   2937:                                    upload => 'Upload a File of Co-authors',
                   2938:                                    singleuser => 'Add/Manage a Single Co-author',
                   2939:                                    listusers => 'Display Co-authors and Manage Multiple Users',
                   2940:                                  },
                   2941:                        course => {
                   2942:                                    upload => 'Upload a File of Course Users',
                   2943:                                    singleuser => 'Add/Manage a Single Course User',
                   2944:                                    listusers => 'Display Class Lists and Manage Multiple Users',
                   2945:                                  },
                   2946:                      );
1.190     raeburn  2947:     my @menu =
                   2948:         (
1.208     raeburn  2949:           { text => $links{$context}{'upload'},
1.190     raeburn  2950:             help => 'User_Management_Upload',
                   2951:             action => 'upload',
                   2952:             permission => $permission->{'cusr'},
                   2953:             },
1.208     raeburn  2954:           { text => $links{$context}{'singleuser'}, 
1.190     raeburn  2955:             help => 'User_Management_Single_User',
                   2956:             action => 'singleuser',
                   2957:             permission => $permission->{'cusr'},
                   2958:             },
1.208     raeburn  2959:           { text => $links{$context}{'listusers'},
1.191     raeburn  2960:             help => 'User_Management_List',
                   2961:             action => 'listusers',
1.208     raeburn  2962:             permission => ($permission->{'view'} || $permission->{'cusr'}),
1.190     raeburn  2963:           },
                   2964:         );
1.208     raeburn  2965:     if ($context eq 'domain' || $context eq 'course') {
                   2966:         my $customlink =  { text => 'Edit Custom Roles',
                   2967:                             help => 'Custom_Role_Edit',
                   2968:                             action => 'custom',
                   2969:                             permission => $permission->{'custom'},
                   2970:                           };
                   2971:         push(@menu,$customlink);
                   2972:     }
                   2973:     if ($context eq 'course') {
1.213     raeburn  2974:         my ($cnum,$cdom) = &Apache::lonuserutils::get_course_identity();
                   2975:         my @courselinks =
1.208     raeburn  2976:             (
1.213     raeburn  2977:               { text => 'Enroll a Single Student',
                   2978:                  help => 'Course_Single_Student',
                   2979:                  action => 'singlestudent',
                   2980:                  permission => $permission->{'cusr'},
                   2981:                  },
                   2982:               { text => 'Drop Students',
                   2983:                 help => 'Course_Drop_Student',
                   2984:                 action => 'drop',
                   2985:                 permission => $permission->{'cusr'},
                   2986:               });
                   2987:         if (!exists($permission->{'cusr_section'})) {
                   2988:             push(@courselinks,
                   2989:                { text => 'Automated Student Enrollment Manager',
1.208     raeburn  2990:                  permission => (&Apache::lonnet::auto_run($cnum,$cdom)
                   2991:                                 && $permission->{'cusr'}),
                   2992:                  url  => '/adm/populate',
1.213     raeburn  2993:                  });
                   2994:         }
                   2995:         push(@courselinks,
1.208     raeburn  2996:                { text => 'Manage Course Groups',
                   2997:                  help => 'Course_Manage_Group',
                   2998:                  permission => $permission->{'grp_manage'},
                   2999:                  url => '/adm/coursegroups?refpage=cusr',
1.213     raeburn  3000:                });
1.208     raeburn  3001:         push(@menu,@courselinks);
                   3002:     }
1.190     raeburn  3003:     my $menu_html = '';
                   3004:     foreach my $menu_item (@menu) {
                   3005:         next if (! $menu_item->{'permission'});
                   3006:         $menu_html.='<p>';
                   3007:         $menu_html.='<font size="+1">';
                   3008:         if (exists($menu_item->{'url'})) {
                   3009:             $menu_html.=qq{<a href="$menu_item->{'url'}">};
                   3010:         } else {
                   3011:             $menu_html.=
                   3012:                 qq{<a href="/adm/createuser?action=$menu_item->{'action'}">};
                   3013:         }
                   3014:         $menu_html.= &mt($menu_item->{'text'}).'</a></font>';
                   3015:         if (exists($menu_item->{'help'})) {
                   3016:             $menu_html.=
                   3017:                 &Apache::loncommon::help_open_topic($menu_item->{'help'});
                   3018:         }
                   3019:         $menu_html.='</p>';
                   3020:     }
                   3021:     return $menu_html;
                   3022: }
                   3023: 
1.189     albertel 3024: sub restore_prev_selections {
                   3025:     my %saveable_parameters = ('srchby'   => 'scalar',
                   3026: 			       'srchin'   => 'scalar',
                   3027: 			       'srchtype' => 'scalar',
                   3028: 			       );
                   3029:     &Apache::loncommon::store_settings('user','user_picker',
                   3030: 				       \%saveable_parameters);
                   3031:     &Apache::loncommon::restore_settings('user','user_picker',
                   3032: 					 \%saveable_parameters);
                   3033: }
                   3034: 
1.27      matthew  3035: #-------------------------------------------------- functions for &phase_two
1.160     raeburn  3036: sub user_search_result {
                   3037:     my ($srch) = @_;
                   3038:     my %allhomes;
                   3039:     my %inst_matches;
                   3040:     my %srch_results;
1.181     raeburn  3041:     my ($response,$currstate,$forcenewuser,$dirsrchres);
1.183     raeburn  3042:     $srch->{'srchterm'} =~ s/\s+/ /g;
1.176     raeburn  3043:     if ($srch->{'srchby'} !~ /^(uname|lastname|lastfirst)$/) {
1.160     raeburn  3044:         $response = &mt('Invalid search.');
                   3045:     }
                   3046:     if ($srch->{'srchin'} !~ /^(crs|dom|alc|instd)$/) {
                   3047:         $response = &mt('Invalid search.');
                   3048:     }
1.177     raeburn  3049:     if ($srch->{'srchtype'} !~ /^(exact|contains|begins)$/) {
1.160     raeburn  3050:         $response = &mt('Invalid search.');
                   3051:     }
                   3052:     if ($srch->{'srchterm'} eq '') {
                   3053:         $response = &mt('You must enter a search term.');
                   3054:     }
1.183     raeburn  3055:     if ($srch->{'srchterm'} =~ /^\s+$/) {
                   3056:         $response = &mt('Your search term must contain more than just spaces.');
                   3057:     }
1.160     raeburn  3058:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'instd')) {
                   3059:         if (($srch->{'srchdomain'} eq '') || 
1.163     albertel 3060: 	    ! (&Apache::lonnet::domain($srch->{'srchdomain'}))) {
1.160     raeburn  3061:             $response = &mt('You must specify a valid domain when searching in a domain or institutional directory.')
                   3062:         }
                   3063:     }
                   3064:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs') ||
                   3065:         ($srch->{'srchin'} eq 'alc')) {
1.176     raeburn  3066:         if ($srch->{'srchby'} eq 'uname') {
                   3067:             if ($srch->{'srchterm'} !~ /^$match_username$/) {
                   3068:                 $response = &mt('You must specify a valid username. Only the following are allowed: letters numbers - . @');
                   3069:             }
1.160     raeburn  3070:         }
                   3071:     }
1.180     raeburn  3072:     if ($response ne '') {
                   3073:         $response = '<span class="LC_warning">'.$response.'</span>';
                   3074:     }
1.160     raeburn  3075:     if ($srch->{'srchin'} eq 'instd') {
                   3076:         my $instd_chk = &directorysrch_check($srch);
                   3077:         if ($instd_chk ne 'ok') {
1.180     raeburn  3078:             $response = '<span class="LC_warning">'.$instd_chk.'</span>'.
                   3079:                         '<br />'.&mt('You may want to search in the LON-CAPA domain instead of the institutional directory.').'<br /><br />';
1.160     raeburn  3080:         }
                   3081:     }
                   3082:     if ($response ne '') {
1.180     raeburn  3083:         return ($currstate,$response);
1.160     raeburn  3084:     }
                   3085:     if ($srch->{'srchby'} eq 'uname') {
                   3086:         if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs')) {
                   3087:             if ($env{'form.forcenew'}) {
                   3088:                 if ($srch->{'srchdomain'} ne $env{'request.role.domain'}) {
                   3089:                     my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
                   3090:                     if ($uhome eq 'no_host') {
                   3091:                         my $domdesc = &Apache::lonnet::domain($env{'request.role.domain'},'description');
1.180     raeburn  3092:                         my $showdom = &display_domain_info($env{'request.role.domain'});
                   3093:                         $response = &mt('New users can only be created in the domain to which your current role belongs - [_1].',$showdom);
1.160     raeburn  3094:                     } else {
1.179     raeburn  3095:                         $currstate = 'modify';
1.160     raeburn  3096:                     }
                   3097:                 } else {
1.179     raeburn  3098:                     $currstate = 'modify';
1.160     raeburn  3099:                 }
                   3100:             } else {
                   3101:                 if ($srch->{'srchin'} eq 'dom') {
1.162     raeburn  3102:                     if ($srch->{'srchtype'} eq 'exact') {
                   3103:                         my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
                   3104:                         if ($uhome eq 'no_host') {
1.179     raeburn  3105:                             ($currstate,$response,$forcenewuser) =
1.162     raeburn  3106:                                 &build_search_response($srch,%srch_results);
                   3107:                         } else {
1.179     raeburn  3108:                             $currstate = 'modify';
1.162     raeburn  3109:                         }
                   3110:                     } else {
                   3111:                         %srch_results = &Apache::lonnet::usersearch($srch);
1.179     raeburn  3112:                         ($currstate,$response,$forcenewuser) =
1.160     raeburn  3113:                             &build_search_response($srch,%srch_results);
                   3114:                     }
                   3115:                 } else {
1.167     albertel 3116:                     my $courseusers = &get_courseusers();
1.162     raeburn  3117:                     if ($srch->{'srchtype'} eq 'exact') {
1.167     albertel 3118:                         if (exists($courseusers->{$srch->{'srchterm'}.':'.$srch->{'srchdomain'}})) {
1.179     raeburn  3119:                             $currstate = 'modify';
1.162     raeburn  3120:                         } else {
1.179     raeburn  3121:                             ($currstate,$response,$forcenewuser) =
1.162     raeburn  3122:                                 &build_search_response($srch,%srch_results);
                   3123:                         }
1.160     raeburn  3124:                     } else {
1.167     albertel 3125:                         foreach my $user (keys(%$courseusers)) {
1.162     raeburn  3126:                             my ($cuname,$cudomain) = split(/:/,$user);
                   3127:                             if ($cudomain eq $srch->{'srchdomain'}) {
1.177     raeburn  3128:                                 my $matched = 0;
                   3129:                                 if ($srch->{'srchtype'} eq 'begins') {
                   3130:                                     if ($cuname =~ /^\Q$srch->{'srchterm'}\E/i) {
                   3131:                                         $matched = 1;
                   3132:                                     }
                   3133:                                 } else {
                   3134:                                     if ($cuname =~ /\Q$srch->{'srchterm'}\E/i) {
                   3135:                                         $matched = 1;
                   3136:                                     }
                   3137:                                 }
                   3138:                                 if ($matched) {
1.167     albertel 3139:                                     $srch_results{$user} = 
                   3140: 					{&Apache::lonnet::get('environment',
                   3141: 							     ['firstname',
                   3142: 							      'lastname',
1.194     albertel 3143: 							      'permanentemail'],
                   3144: 							      $cudomain,$cuname)};
1.162     raeburn  3145:                                 }
                   3146:                             }
                   3147:                         }
1.179     raeburn  3148:                         ($currstate,$response,$forcenewuser) =
1.160     raeburn  3149:                             &build_search_response($srch,%srch_results);
                   3150:                     }
                   3151:                 }
                   3152:             }
                   3153:         } elsif ($srch->{'srchin'} eq 'alc') {
1.179     raeburn  3154:             $currstate = 'query';
1.160     raeburn  3155:         } elsif ($srch->{'srchin'} eq 'instd') {
1.181     raeburn  3156:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch);
                   3157:             if ($dirsrchres eq 'ok') {
                   3158:                 ($currstate,$response,$forcenewuser) = 
                   3159:                     &build_search_response($srch,%srch_results);
                   3160:             } else {
                   3161:                 my $showdom = &display_domain_info($srch->{'srchdomain'});
                   3162:                 $response = '<span class="LC_warning">'.
                   3163:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
                   3164:                     '</span><br />'.
                   3165:                     &mt('You may want to search in the LON-CAPA domain instead of the institutional directory.').
                   3166:                     '<br /><br />'; 
                   3167:             }
1.160     raeburn  3168:         }
                   3169:     } else {
                   3170:         if ($srch->{'srchin'} eq 'dom') {
                   3171:             %srch_results = &Apache::lonnet::usersearch($srch);
1.179     raeburn  3172:             ($currstate,$response,$forcenewuser) = 
1.160     raeburn  3173:                 &build_search_response($srch,%srch_results); 
                   3174:         } elsif ($srch->{'srchin'} eq 'crs') {
1.167     albertel 3175:             my $courseusers = &get_courseusers(); 
                   3176:             foreach my $user (keys(%$courseusers)) {
1.160     raeburn  3177:                 my ($uname,$udom) = split(/:/,$user);
                   3178:                 my %names = &Apache::loncommon::getnames($uname,$udom);
                   3179:                 my %emails = &Apache::loncommon::getemails($uname,$udom);
                   3180:                 if ($srch->{'srchby'} eq 'lastname') {
                   3181:                     if ((($srch->{'srchtype'} eq 'exact') && 
                   3182:                          ($names{'lastname'} eq $srch->{'srchterm'})) || 
1.177     raeburn  3183:                         (($srch->{'srchtype'} eq 'begins') &&
                   3184:                          ($names{'lastname'} =~ /^\Q$srch->{'srchterm'}\E/i)) ||
1.160     raeburn  3185:                         (($srch->{'srchtype'} eq 'contains') &&
                   3186:                          ($names{'lastname'} =~ /\Q$srch->{'srchterm'}\E/i))) {
                   3187:                         $srch_results{$user} = {firstname => $names{'firstname'},
                   3188:                                             lastname => $names{'lastname'},
                   3189:                                             permanentemail => $emails{'permanentemail'},
                   3190:                                            };
                   3191:                     }
                   3192:                 } elsif ($srch->{'srchby'} eq 'lastfirst') {
                   3193:                     my ($srchlast,$srchfirst) = split(/,/,$srch->{'srchterm'});
1.177     raeburn  3194:                     $srchlast =~ s/\s+$//;
                   3195:                     $srchfirst =~ s/^\s+//;
1.160     raeburn  3196:                     if ($srch->{'srchtype'} eq 'exact') {
                   3197:                         if (($names{'lastname'} eq $srchlast) &&
                   3198:                             ($names{'firstname'} eq $srchfirst)) {
                   3199:                             $srch_results{$user} = {firstname => $names{'firstname'},
                   3200:                                                 lastname => $names{'lastname'},
                   3201:                                                 permanentemail => $emails{'permanentemail'},
                   3202: 
                   3203:                                            };
                   3204:                         }
1.177     raeburn  3205:                     } elsif ($srch->{'srchtype'} eq 'begins') {
                   3206:                         if (($names{'lastname'} =~ /^\Q$srchlast\E/i) &&
                   3207:                             ($names{'firstname'} =~ /^\Q$srchfirst\E/i)) {
                   3208:                             $srch_results{$user} = {firstname => $names{'firstname'},
                   3209:                                                 lastname => $names{'lastname'},
                   3210:                                                 permanentemail => $emails{'permanentemail'},
                   3211:                                                };
                   3212:                         }
                   3213:                     } else {
1.160     raeburn  3214:                         if (($names{'lastname'} =~ /\Q$srchlast\E/i) && 
                   3215:                             ($names{'firstname'} =~ /\Q$srchfirst\E/i)) {
                   3216:                             $srch_results{$user} = {firstname => $names{'firstname'},
                   3217:                                                 lastname => $names{'lastname'},
                   3218:                                                 permanentemail => $emails{'permanentemail'},
                   3219:                                                };
                   3220:                         }
                   3221:                     }
                   3222:                 }
                   3223:             }
1.179     raeburn  3224:             ($currstate,$response,$forcenewuser) = 
1.160     raeburn  3225:                 &build_search_response($srch,%srch_results); 
                   3226:         } elsif ($srch->{'srchin'} eq 'alc') {
1.179     raeburn  3227:             $currstate = 'query';
1.160     raeburn  3228:         } elsif ($srch->{'srchin'} eq 'instd') {
1.181     raeburn  3229:             ($dirsrchres,%srch_results) = &Apache::lonnet::inst_directory_query($srch); 
                   3230:             if ($dirsrchres eq 'ok') {
                   3231:                 ($currstate,$response,$forcenewuser) = 
                   3232:                     &build_search_response($srch,%srch_results);
                   3233:             } else {
                   3234:                 my $showdom = &display_domain_info($srch->{'srchdomain'});                $response = '<span class="LC_warning">'.
                   3235:                     &mt('Institutional directory search is not available in domain: [_1]',$showdom).
                   3236:                     '</span><br />'.
                   3237:                     &mt('You may want to search in the LON-CAPA domain instead of the institutional directory.').
                   3238:                     '<br /><br />';
                   3239:             }
1.160     raeburn  3240:         }
                   3241:     }
1.179     raeburn  3242:     return ($currstate,$response,$forcenewuser,\%srch_results);
1.160     raeburn  3243: }
                   3244: 
                   3245: sub directorysrch_check {
                   3246:     my ($srch) = @_;
                   3247:     my $can_search = 0;
                   3248:     my $response;
                   3249:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
                   3250:                                              ['directorysrch'],$srch->{'srchdomain'});
1.180     raeburn  3251:     my $showdom = &display_domain_info($srch->{'srchdomain'});
1.160     raeburn  3252:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
                   3253:         if (!$dom_inst_srch{'directorysrch'}{'available'}) {
1.180     raeburn  3254:             return &mt('Institutional directory search is not available in domain: [_1]',$showdom); 
1.160     raeburn  3255:         }
                   3256:         if ($dom_inst_srch{'directorysrch'}{'localonly'}) {
                   3257:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
1.180     raeburn  3258:                 return &mt('Institutional directory search in domain: [_1] is only allowed for users with a current role in the domain.',$showdom); 
1.160     raeburn  3259:             }
                   3260:             my @usertypes = split(/:/,$env{'environment.inststatus'});
                   3261:             if (!@usertypes) {
                   3262:                 push(@usertypes,'default');
                   3263:             }
                   3264:             if (ref($dom_inst_srch{'directorysrch'}{'cansearch'}) eq 'ARRAY') {
                   3265:                 foreach my $type (@usertypes) {
                   3266:                     if (grep(/^\Q$type\E$/,@{$dom_inst_srch{'directorysrch'}{'cansearch'}})) {
                   3267:                         $can_search = 1;
                   3268:                         last;
                   3269:                     }
                   3270:                 }
                   3271:             }
                   3272:             if (!$can_search) {
                   3273:                 my ($insttypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($srch->{'srchdomain'});
                   3274:                 my @longtypes; 
                   3275:                 foreach my $item (@usertypes) {
                   3276:                     push (@longtypes,$insttypes->{$item});
                   3277:                 }
                   3278:                 my $insttype_str = join(', ',@longtypes); 
1.180     raeburn  3279:                 return &mt('Institutional directory search in domain: [_1] is not available to your user type: ',$showdom).$insttype_str;
1.160     raeburn  3280:             } 
                   3281:         } else {
                   3282:             $can_search = 1;
                   3283:         }
                   3284:     } else {
1.180     raeburn  3285:         return &mt('Institutional directory search has not been configured for domain: [_1]',$showdom);
1.160     raeburn  3286:     }
                   3287:     my %longtext = &Apache::lonlocal::texthash (
1.167     albertel 3288:                        uname     => 'username',
1.160     raeburn  3289:                        lastfirst => 'last name, first name',
1.167     albertel 3290:                        lastname  => 'last name',
1.172     raeburn  3291:                        contains  => 'contains',
1.178     raeburn  3292:                        exact     => 'as exact match to',
                   3293:                        begins    => 'begins with',
1.160     raeburn  3294:                    );
                   3295:     if ($can_search) {
                   3296:         if (ref($dom_inst_srch{'directorysrch'}{'searchby'}) eq 'ARRAY') {
                   3297:             if (!grep(/^\Q$srch->{'srchby'}\E$/,@{$dom_inst_srch{'directorysrch'}{'searchby'}})) {
1.180     raeburn  3298:                 return &mt('Institutional directory search in domain: [_1] is not available for searching by "[_2]"',$showdom,$longtext{$srch->{'srchby'}});
1.160     raeburn  3299:             }
                   3300:         } else {
1.180     raeburn  3301:             return &mt('Institutional directory search in domain: [_1] is not available.', $showdom);
1.160     raeburn  3302:         }
                   3303:     }
                   3304:     if ($can_search) {
1.178     raeburn  3305:         if (ref($dom_inst_srch{'directorysrch'}{'searchtypes'}) eq 'ARRAY') {
                   3306:             if (grep(/^\Q$srch->{'srchtype'}\E/,@{$dom_inst_srch{'directorysrch'}{'searchtypes'}})) {
                   3307:                 return 'ok';
                   3308:             } else {
1.180     raeburn  3309:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
1.178     raeburn  3310:             }
                   3311:         } else {
                   3312:             if ((($dom_inst_srch{'directorysrch'}{'searchtypes'} eq 'specify') &&
                   3313:                  ($srch->{'srchtype'} eq 'exact' || $srch->{'srchtype'} eq 'contains')) ||
                   3314:                 ($dom_inst_srch{'directorysrch'}{'searchtypes'} eq $srch->{'srchtype'})) {
                   3315:                 return 'ok';
                   3316:             } else {
1.180     raeburn  3317:                 return &mt('Institutional directory search in domain [_1] is not available for the requested search type: "[_2]"',$showdom,$longtext{$srch->{'srchtype'}});
1.178     raeburn  3318:             }
1.160     raeburn  3319:         }
                   3320:     }
                   3321: }
                   3322: 
                   3323: sub get_courseusers {
                   3324:     my %advhash;
1.167     albertel 3325:     my $classlist = &Apache::loncoursedata::get_classlist();
1.160     raeburn  3326:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles();
                   3327:     foreach my $role (sort(keys(%coursepersonnel))) {
                   3328:         foreach my $user (split(/\,/,$coursepersonnel{$role})) {
1.167     albertel 3329: 	    if (!exists($classlist->{$user})) {
                   3330: 		$classlist->{$user} = [];
                   3331: 	    }
1.160     raeburn  3332:         }
                   3333:     }
1.167     albertel 3334:     return $classlist;
1.160     raeburn  3335: }
                   3336: 
                   3337: sub build_search_response {
                   3338:     my ($srch,%srch_results) = @_;
1.179     raeburn  3339:     my ($currstate,$response,$forcenewuser);
1.160     raeburn  3340:     my %names = (
                   3341:           'uname' => 'username',
                   3342:           'lastname' => 'last name',
                   3343:           'lastfirst' => 'last name, first name',
                   3344:           'crs' => 'this course',
1.180     raeburn  3345:           'dom' => 'LON-CAPA domain: ',
                   3346:           'instd' => 'the institutional directory for domain: ',
1.160     raeburn  3347:     );
                   3348: 
                   3349:     my %single = (
1.180     raeburn  3350:                    begins   => 'A match',
1.160     raeburn  3351:                    contains => 'A match',
1.180     raeburn  3352:                    exact    => 'An exact match',
1.160     raeburn  3353:                  );
                   3354:     my %nomatch = (
1.180     raeburn  3355:                    begins   => 'No match',
1.160     raeburn  3356:                    contains => 'No match',
1.180     raeburn  3357:                    exact    => 'No exact match',
1.160     raeburn  3358:                   );
                   3359:     if (keys(%srch_results) > 1) {
1.179     raeburn  3360:         $currstate = 'select';
1.160     raeburn  3361:     } else {
                   3362:         if (keys(%srch_results) == 1) {
1.179     raeburn  3363:             $currstate = 'modify';
1.180     raeburn  3364:             $response = &mt("$single{$srch->{'srchtype'}} was found for the $names{$srch->{'srchby'}} ([_1]) in $names{$srch->{'srchin'}}.",$srch->{'srchterm'});
                   3365:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
                   3366:                 $response .= &display_domain_info($srch->{'srchdomain'});
                   3367:             }
1.160     raeburn  3368:         } else {
1.180     raeburn  3369:             $response = '<span class="LC_warning">'.&mt("$nomatch{$srch->{'srchtype'}} found for the $names{$srch->{'srchby'}} ([_1]) in $names{$srch->{'srchin'}}",$srch->{'srchterm'});
                   3370:             if ($srch->{'srchin'} eq 'dom' || $srch->{'srchin'} eq 'instd') {
                   3371:                 $response .= &display_domain_info($srch->{'srchdomain'});
                   3372:             }
                   3373:             $response .= '</span>';
1.160     raeburn  3374:             if ($srch->{'srchin'} ne 'alc') {
                   3375:                 $forcenewuser = 1;
                   3376:                 my $cansrchinst = 0; 
                   3377:                 if ($srch->{'srchdomain'}) {
                   3378:                     my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$srch->{'srchdomain'});
                   3379:                     if (ref($domconfig{'directorysrch'}) eq 'HASH') {
                   3380:                         if ($domconfig{'directorysrch'}{'available'}) {
                   3381:                             $cansrchinst = 1;
                   3382:                         } 
                   3383:                     }
                   3384:                 }
1.180     raeburn  3385:                 if ((($srch->{'srchby'} eq 'lastfirst') || 
                   3386:                      ($srch->{'srchby'} eq 'lastname')) &&
                   3387:                     ($srch->{'srchin'} eq 'dom')) {
                   3388:                     if ($cansrchinst) {
                   3389:                         $response .= '<br />'.&mt('You may want to broaden your search to a search of the institutional directory for the domain.');
1.160     raeburn  3390:                     }
                   3391:                 }
1.180     raeburn  3392:                 if ($srch->{'srchin'} eq 'crs') {
                   3393:                     $response .= '<br />'.&mt('You may want to broaden your search to the selected LON-CAPA domain.');
                   3394:                 }
                   3395:             }
                   3396:             if (!($srch->{'srchby'} eq 'uname' && $srch->{'srchin'} eq 'dom' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchdomain'} eq $env{'request.role.domain'})) {
1.182     raeburn  3397:                 my $showdom = &display_domain_info($env{'request.role.domain'}); 
                   3398:                 $response .= '<br /><br />'.&mt("<b>To add a new user</b> (you can only create new users in your current role's domain - <span class=\"LC_cusr_emph\">[_1]</span>):",$env{'request.role.domain'}).'<ul><li>'.&mt("Set 'Domain/institution to search' to: <span class=\"LC_cusr_emph\">[_1]</span>",$showdom).'<li>'.&mt("Set 'Search criteria' to: <span class=\"LC_cusr_emph\">'username is ...... in selected LON-CAPA domain'").'</span></li><li>'.&mt('Provide the proposed username').'</li><li>'.&mt('Search').'</li></ul><br />';
1.160     raeburn  3399:             }
                   3400:         }
                   3401:     }
1.179     raeburn  3402:     return ($currstate,$response,$forcenewuser);
1.160     raeburn  3403: }
                   3404: 
1.180     raeburn  3405: sub display_domain_info {
                   3406:     my ($dom) = @_;
                   3407:     my $output = $dom;
                   3408:     if ($dom ne '') { 
                   3409:         my $domdesc = &Apache::lonnet::domain($dom,'description');
                   3410:         if ($domdesc ne '') {
                   3411:             $output .= ' <span class="LC_cusr_emph">('.$domdesc.')</span>';
                   3412:         }
                   3413:     }
                   3414:     return $output;
                   3415: }
                   3416: 
1.160     raeburn  3417: sub crumb_utilities {
                   3418:     my %elements = (
                   3419:        crtuser => {
                   3420:            srchterm => 'text',
1.172     raeburn  3421:            srchin => 'selectbox',
1.160     raeburn  3422:            srchby => 'selectbox',
                   3423:            srchtype => 'selectbox',
                   3424:            srchdomain => 'selectbox',
                   3425:        },
1.207     raeburn  3426:        crtusername => {
                   3427:            srchterm => 'text',
                   3428:            srchdomain => 'selectbox',
                   3429:        },
1.160     raeburn  3430:        docustom => {
                   3431:            rolename => 'selectbox',
                   3432:            newrolename => 'textbox',
                   3433:        },
1.179     raeburn  3434:        studentform => {
                   3435:            srchterm => 'text',
                   3436:            srchin => 'selectbox',
                   3437:            srchby => 'selectbox',
                   3438:            srchtype => 'selectbox',
                   3439:            srchdomain => 'selectbox',
                   3440:        },
1.160     raeburn  3441:     );
                   3442: 
                   3443:     my $jsback .= qq|
                   3444: function backPage(formname,prevphase,prevstate) {
1.211     raeburn  3445:     if (typeof prevphase == 'undefined') {
                   3446:         formname.phase.value = '';
                   3447:     }
                   3448:     else {  
                   3449:         formname.phase.value = prevphase;
                   3450:     }
                   3451:     if (typeof prevstate == 'undefined') {
                   3452:         formname.currstate.value = '';
                   3453:     }
                   3454:     else {
                   3455:         formname.currstate.value = prevstate;
                   3456:     }
1.160     raeburn  3457:     formname.submit();
                   3458: }
                   3459: |;
                   3460:     return ($jsback,\%elements);
                   3461: }
                   3462: 
1.26      matthew  3463: sub course_level_table {
1.89      raeburn  3464:     my (%inccourses) = @_;
1.26      matthew  3465:     my $table = '';
1.62      www      3466: # Custom Roles?
                   3467: 
1.190     raeburn  3468:     my %customroles=&Apache::lonuserutils::my_custom_roles();
1.89      raeburn  3469:     my %lt=&Apache::lonlocal::texthash(
                   3470:             'exs'  => "Existing sections",
                   3471:             'new'  => "Define new section",
                   3472:             'ssd'  => "Set Start Date",
                   3473:             'sed'  => "Set End Date",
1.131     raeburn  3474:             'crl'  => "Course Level",
1.89      raeburn  3475:             'act'  => "Activate",
                   3476:             'rol'  => "Role",
                   3477:             'ext'  => "Extent",
1.113     raeburn  3478:             'grs'  => "Section",
1.89      raeburn  3479:             'sta'  => "Start",
                   3480:             'end'  => "End"
                   3481:     );
1.62      www      3482: 
1.135     raeburn  3483:     foreach my $protectedcourse (sort( keys(%inccourses))) {
                   3484: 	my $thiscourse=$protectedcourse;
1.26      matthew  3485: 	$thiscourse=~s:_:/:g;
                   3486: 	my %coursedata=&Apache::lonnet::coursedescription($thiscourse);
                   3487: 	my $area=$coursedata{'description'};
1.119     raeburn  3488:         my $type=$coursedata{'type'};
1.135     raeburn  3489: 	if (!defined($area)) { $area=&mt('Unavailable course').': '.$protectedcourse; }
1.89      raeburn  3490: 	my ($domain,$cnum)=split(/\//,$thiscourse);
1.115     albertel 3491:         my %sections_count;
1.101     albertel 3492:         if (defined($env{'request.course.id'})) {
                   3493:             if ($env{'request.course.id'} eq $domain.'_'.$cnum) {
1.115     albertel 3494:                 %sections_count = 
                   3495: 		    &Apache::loncommon::get_sections($domain,$cnum);
1.92      raeburn  3496:             }
                   3497:         }
1.213     raeburn  3498:         my @roles = &Apache::lonuserutils::roles_by_context('course');
                   3499: 	foreach my $role (@roles) {
1.135     raeburn  3500: 	    if (&Apache::lonnet::allowed('c'.$role,$thiscourse)) {
                   3501: 		my $plrole=&Apache::lonnet::plaintext($role);
1.136     raeburn  3502: 		$table .= &Apache::loncommon::start_data_table_row().
1.157     albertel 3503: '<td><input type="checkbox" name="act_'.$protectedcourse.'_'.$role.'" /></td>
1.136     raeburn  3504: <td>'.$plrole.'</td>
                   3505: <td>'.$area.'<br />Domain: '.$domain.'</td>'."\n";
1.135     raeburn  3506: 	        if ($role ne 'cc') {
1.115     albertel 3507:                     if (%sections_count) {
1.202     raeburn  3508:                         my $currsec = 
1.198     raeburn  3509:                             &Apache::lonuserutils::course_sections(\%sections_count,
1.202     raeburn  3510:                                                         $protectedcourse.'_'.$role);
1.89      raeburn  3511:                         $table .= 
1.137     raeburn  3512:                     '<td><table class="LC_createuser">'.
                   3513:                      '<tr class="LC_section_row">
                   3514:                         <td valign="top">'.$lt{'exs'}.'<br />'.
1.89      raeburn  3515:                         $currsec.'</td>'.
                   3516:                      '<td>&nbsp;&nbsp;</td>'.
                   3517:                      '<td valign="top">&nbsp;'.$lt{'new'}.'<br />'.
1.157     albertel 3518:                      '<input type="text" name="newsec_'.$protectedcourse.'_'.$role.'" value="" />'.
1.89      raeburn  3519:                      '<input type="hidden" '.
1.157     albertel 3520:                      'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'.
1.89      raeburn  3521:                      '</tr></table></td>';
                   3522:                     } else {
                   3523:                         $table .= '<td><input type="text" size="10" '.
1.157     albertel 3524:                      'name="sec_'.$protectedcourse.'_'.$role.'" /></td>';
1.89      raeburn  3525:                     }
1.26      matthew  3526:                 } else { 
1.89      raeburn  3527: 		    $table .= '<td>&nbsp</td>';
1.26      matthew  3528:                 }
                   3529: 		$table .= <<ENDTIMEENTRY;
1.169     albertel 3530: <td><input type="hidden" name="start_$protectedcourse\_$role" value='' />
1.26      matthew  3531: <a href=
1.135     raeburn  3532: "javascript:pjump('date_start','Start Date $plrole',document.cu.start_$protectedcourse\_$role.value,'start_$protectedcourse\_$role','cu.pres','dateset')">$lt{'ssd'}</a></td>
1.169     albertel 3533: <td><input type="hidden" name="end_$protectedcourse\_$role" value='' />
1.26      matthew  3534: <a href=
1.135     raeburn  3535: "javascript:pjump('date_end','End Date $plrole',document.cu.end_$protectedcourse\_$role.value,'end_$protectedcourse\_$role','cu.pres','dateset')">$lt{'sed'}</a></td>
1.26      matthew  3536: ENDTIMEENTRY
1.136     raeburn  3537:                 $table.= &Apache::loncommon::end_data_table_row();
1.26      matthew  3538:             }
                   3539:         }
1.135     raeburn  3540:         foreach my $cust (sort keys %customroles) {
1.65      www      3541: 	    if (&Apache::lonnet::allowed('ccr',$thiscourse)) {
1.135     raeburn  3542: 		my $plrole=$cust;
1.101     albertel 3543:                 my $customrole=$protectedcourse.'_cr_cr_'.$env{'user.domain'}.
                   3544: 		    '_'.$env{'user.name'}.'_'.$plrole;
1.136     raeburn  3545: 		$table .= &Apache::loncommon::start_data_table_row().
1.157     albertel 3546: '<td><input type="checkbox" name="act_'.$customrole.'" /></td>
1.136     raeburn  3547: <td>'.$plrole.'</td>
                   3548: <td>'.$area.'</td>'."\n";
1.115     albertel 3549:                 if (%sections_count) {
1.202     raeburn  3550:                     my $currsec = 
1.198     raeburn  3551:                         &Apache::lonuserutils::course_sections(\%sections_count,
                   3552:                                                                $customrole);
1.89      raeburn  3553:                     $table.=
1.188     raeburn  3554:                    '<td><table class="LC_createuser">'.
                   3555:                    '<tr class="LC_section_row"><td valign="top">'.
                   3556:                    $lt{'exs'}.'<br />'.$currsec.'</td>'.
1.89      raeburn  3557:                    '<td>&nbsp;&nbsp;</td>'.
                   3558:                    '<td valign="top">&nbsp;'.$lt{'new'}.'<br />'.
                   3559:                    '<input type="text" name="newsec_'.$customrole.'" value="" /></td>'.
                   3560:                    '<input type="hidden" '.
1.157     albertel 3561:                    'name="sec_'.$customrole.'" /></td>'.
1.89      raeburn  3562:                    '</tr></table></td>';
                   3563:                 } else {
                   3564:                     $table .= '<td><input type="text" size="10" '.
1.157     albertel 3565:                      'name="sec_'.$customrole.'" /></td>';
1.89      raeburn  3566:                 }
                   3567:                 $table .= <<ENDENTRY;
1.169     albertel 3568: <td><input type="hidden" name="start_$customrole" value='' />
1.62      www      3569: <a href=
1.73      sakharuk 3570: "javascript:pjump('date_start','Start Date $plrole',document.cu.start_$customrole.value,'start_$customrole','cu.pres','dateset')">$lt{'ssd'}</a></td>
1.169     albertel 3571: <td><input type="hidden" name="end_$customrole" value='' />
1.62      www      3572: <a href=
1.136     raeburn  3573: "javascript:pjump('date_end','End Date $plrole',document.cu.end_$customrole.value,'end_$customrole','cu.pres','dateset')">$lt{'sed'}</a></td>
1.62      www      3574: ENDENTRY
1.136     raeburn  3575:                $table .= &Apache::loncommon::end_data_table_row();
1.65      www      3576:            }
1.62      www      3577: 	}
1.26      matthew  3578:     }
                   3579:     return '' if ($table eq ''); # return nothing if there is nothing 
                   3580:                                  # in the table
1.188     raeburn  3581:     my $result;
                   3582:     if (!$env{'request.course.id'}) {
                   3583:         $result = '<h4>'.$lt{'crl'}.'</h4>'."\n";
                   3584:     }
                   3585:     $result .= 
1.136     raeburn  3586: &Apache::loncommon::start_data_table().
                   3587: &Apache::loncommon::start_data_table_header_row().
                   3588: '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th><th>'.$lt{'ext'}.'</th>
                   3589: <th>'.$lt{'grs'}.'</th><th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'.
                   3590: &Apache::loncommon::end_data_table_header_row().
                   3591: $table.
                   3592: &Apache::loncommon::end_data_table();
1.26      matthew  3593:     return $result;
                   3594: }
1.88      raeburn  3595: 
                   3596: sub course_level_dc {
                   3597:     my ($dcdom) = @_;
1.190     raeburn  3598:     my %customroles=&Apache::lonuserutils::my_custom_roles();
1.213     raeburn  3599:     my @roles = &Apache::lonuserutils::roles_by_context('course');
1.88      raeburn  3600:     my $hiddenitems = '<input type="hidden" name="dcdomain" value="'.$dcdom.'" />'.
                   3601:                       '<input type="hidden" name="origdom" value="'.$dcdom.'" />'.
1.133     raeburn  3602:                       '<input type="hidden" name="dccourse" value="" />';
1.88      raeburn  3603:     my $courseform='<b>'.&Apache::loncommon::selectcourse_link
1.131     raeburn  3604:             ('cu','dccourse','dcdomain','coursedesc',undef,undef,'Course').'</b>';
                   3605:     my $cb_jscript = &Apache::loncommon::coursebrowser_javascript($dcdom,'currsec','cu');
1.88      raeburn  3606:     my %lt=&Apache::lonlocal::texthash(
                   3607:                     'rol'  => "Role",
1.113     raeburn  3608:                     'grs'  => "Section",
1.88      raeburn  3609:                     'exs'  => "Existing sections",
                   3610:                     'new'  => "Define new section", 
                   3611:                     'sta'  => "Start",
                   3612:                     'end'  => "End",
                   3613:                     'ssd'  => "Set Start Date",
                   3614:                     'sed'  => "Set End Date"
                   3615:                   );
1.131     raeburn  3616:     my $header = '<h4>'.&mt('Course Level').'</h4>'.
1.136     raeburn  3617:                  &Apache::loncommon::start_data_table().
                   3618:                  &Apache::loncommon::start_data_table_header_row().
1.143     raeburn  3619:                  '<th>'.$courseform.'</th><th>'.$lt{'rol'}.'</th><th>'.$lt{'grs'}.'</th><th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'.
1.136     raeburn  3620:                  &Apache::loncommon::end_data_table_header_row();
1.143     raeburn  3621:     my $otheritems = &Apache::loncommon::start_data_table_row()."\n".
1.131     raeburn  3622:                      '<td><input type="text" name="coursedesc" value="" onFocus="this.blur();opencrsbrowser('."'cu','dccourse','dcdomain','coursedesc',''".')" /></td>'."\n".
1.88      raeburn  3623:                      '<td><select name="role">'."\n";
1.213     raeburn  3624:     foreach my $role (@roles) {
1.135     raeburn  3625:         my $plrole=&Apache::lonnet::plaintext($role);
                   3626:         $otheritems .= '  <option value="'.$role.'">'.$plrole;
1.88      raeburn  3627:     }
                   3628:     if ( keys %customroles > 0) {
1.135     raeburn  3629:         foreach my $cust (sort keys %customroles) {
1.101     albertel 3630:             my $custrole='cr_cr_'.$env{'user.domain'}.
1.135     raeburn  3631:                     '_'.$env{'user.name'}.'_'.$cust;
                   3632:             $otheritems .= '  <option value="'.$custrole.'">'.$cust;
1.88      raeburn  3633:         }
                   3634:     }
                   3635:     $otheritems .= '</select></td><td>'.
                   3636:                      '<table border="0" cellspacing="0" cellpadding="0">'.
                   3637:                      '<tr><td valign="top"><b>'.$lt{'exs'}.'</b><br /><select name="currsec">'.
                   3638:                      ' <option value=""><--'.&mt('Pick course first').'</select></td>'.
                   3639:                      '<td>&nbsp;&nbsp;</td>'.
                   3640:                      '<td valign="top">&nbsp;<b>'.$lt{'new'}.'</b><br />'.
1.113     raeburn  3641:                      '<input type="text" name="newsec" value="" />'.
                   3642:                      '<input type="hidden" name="groups" value="" /></td>'.
1.88      raeburn  3643:                      '</tr></table></td>';
                   3644:     $otheritems .= <<ENDTIMEENTRY;
1.169     albertel 3645: <td><input type="hidden" name="start" value='' />
1.88      raeburn  3646: <a href=
                   3647: "javascript:pjump('date_start','Start Date',document.cu.start.value,'start','cu.pres','dateset')">$lt{'ssd'}</a></td>
1.169     albertel 3648: <td><input type="hidden" name="end" value='' />
1.88      raeburn  3649: <a href=
                   3650: "javascript:pjump('date_end','End Date',document.cu.end.value,'end','cu.pres','dateset')">$lt{'sed'}</a></td>
                   3651: ENDTIMEENTRY
1.136     raeburn  3652:     $otheritems .= &Apache::loncommon::end_data_table_row().
                   3653:                    &Apache::loncommon::end_data_table()."\n";
1.88      raeburn  3654:     return $cb_jscript.$header.$hiddenitems.$otheritems;
                   3655: }
                   3656: 
1.27      matthew  3657: #---------------------------------------------- end functions for &phase_two
1.29      matthew  3658: 
                   3659: #--------------------------------- functions for &phase_two and &phase_three
                   3660: 
                   3661: #--------------------------end of functions for &phase_two and &phase_three
1.1       www      3662: 
                   3663: 1;
                   3664: __END__
1.2       www      3665: 
                   3666: 

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