File:  [LON-CAPA] / loncom / interface / loncreateuser.pm
Revision 1.188: download - view: text, annotated - select for diffs
Tue Oct 9 17:33:57 2007 UTC (16 years, 8 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Selectable authentication types displayed controlled by domain prefs
   - some fix-ups.
   - mappings between form element names and stored auth types (int -> internal: etc.)
   - verification of auth selections (verify_message() javascript used more widely).

- More code re-use for adding newuser, and modifying existing user in loncreateuser.pm

- Moving code in loncreateuser.pm out to more subroutines
- Use of <div>s with float for a more compact display
- Added some div classes to standard_css

Work in progress. Towards greater amalgamation of ENRL/CUSR functionality.

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

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