File:  [LON-CAPA] / loncom / interface / loncreateuser.pm
Revision 1.210: download - view: text, annotated - select for diffs
Fri Dec 14 17:35:52 2007 UTC (16 years, 5 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
lonnet::get_instuser returns a hash of a hash.
Pass the inst_results{user} hash for the specific user to &personal_data_display(), instead of %inst_results.

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

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>
500 Internal Server Error

Internal Server Error

The server encountered an internal error or misconfiguration and was unable to complete your request.

Please contact the server administrator at root@localhost to inform them of the time this error occurred, and the actions you performed just before this error.

More information about this error may be available in the server error log.