File:  [LON-CAPA] / loncom / interface / loncreateuser.pm
Revision 1.199: download - view: text, annotated - select for diffs
Wed Dec 5 17:13:34 2007 UTC (16 years, 7 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
Show "Disable ID/Student Number Safeguard and Force Change" item in interface for modification of existing user, not in interface for adding new user.

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

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