File:  [LON-CAPA] / loncom / interface / loncreateuser.pm
Revision 1.161: download - view: text, annotated - select for diffs
Sun Jul 29 04:32:44 2007 UTC (16 years, 10 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
Populating entry form for a new user with institutional data.
- check that institutional search is available
- data returned from lonnet::inst_directory_query() is a hash of a hash.
- correct username and domain in search when new user is a result of a single match as well as when user was picked from a list of matches.

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

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