File:  [LON-CAPA] / loncom / interface / loncreateuser.pm
Revision 1.160: download - view: text, annotated - select for diffs
Sat Jul 28 21:38:29 2007 UTC (16 years, 10 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
loncommon.pm
- added user_picker() routine to generate user interface for adding/mdofiying users.
  - search by username; last name; last name, first name
  - search in course, domain or institutional directory
  - search for 'exact match' or 'contains search string'

loncreateuser.pm
- use new user search interface
- search in course searches all course users (not just students)
- if multiple matches found, can pick the single user to modify (table can be sorted by username, last name etc.)
- if no matches found, can indicate new user should be created
- if institutional data are available, these will appear in new user data input form
- added breadcrumbs
- permanent email can be set/modified from CUSR

Future work:
- enroll single student (londropadd) should employ loncommon::user_picker() interface.
- allow search of multiple domains at one time using search catalog-type frames-based interface. (FIXME included).

    1: # The LearningOnline Network with CAPA
    2: # Create a user
    3: #
    4: # $Id: loncreateuser.pm,v 1.160 2007/07/28 21:38:29 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 $instsrch = { 
  766:                          srchin => 'instd',
  767:                          srchterm => $env{'form.seluname'},
  768:                          srchdomain => $env{'form.seludom'},
  769:                          srchby => 'uname',
  770:                          srchtype => 'exact',
  771:                        };
  772:         my %inst_results;
  773:         if (directorysrch_check($instsrch) eq 'ok') {
  774:             %inst_results = &Apache::lonnet::inst_directory_query($instsrch);
  775:         }
  776:         my $home_server_list=
  777:             '<option value="default" selected>default</option>'."\n".
  778:                 &Apache::loncommon::home_server_option_list($ccdomain);
  779:         
  780: 	my %lt=&Apache::lonlocal::texthash(
  781:                     'cnu'  => "Create New User",
  782:                     'nu'   => "New User",
  783:                     'id'   => "in domain",
  784:                     'pd'   => "Personal Data",
  785:                     'fn'   => "First Name",
  786:                     'mn'   => "Middle Name",
  787:                     'ln'   => "Last Name",
  788:                     'gen'  => "Generation",
  789:                     'mail' => "Permanent e-mail address",
  790:                     'idsn' => "ID/Student Number",
  791:                     'hs'   => "Home Server",
  792:                     'lg'   => "Login Data"
  793: 				       );
  794:         my $portfolioform;
  795:         if (&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) {
  796:             # Current user has quota modification privileges
  797:             $portfolioform = &portfolio_quota($ccuname,$ccdomain);
  798:         }
  799: 	my $genhelp=&Apache::loncommon::help_open_topic('Generation');
  800:         &initialize_authen_forms();
  801: 	$r->print(<<ENDNEWUSER);
  802: $start_page
  803: $crumbs
  804: <h1>$lt{'cnu'}</h1>
  805: $response
  806: $forminfo
  807: <h2>$lt{'nu'} "$ccuname" $lt{'id'} $ccdomain</h2>
  808: <script type="text/javascript" language="Javascript">
  809: $loginscript
  810: </script>
  811: <input type='hidden' name='makeuser' value='1' />
  812: <h3>$lt{'pd'}</h3>
  813: <p>
  814: <table>
  815: <tr><td>$lt{'fn'}  </td>
  816:     <td><input type="text" name="cfirst" size="15" value="$inst_results{'firstname'}" /></td></tr>
  817: <tr><td>$lt{'mn'} </td> 
  818:     <td><input type="text" name="cmiddle" size="15" value="$inst_results{'middlename'}" /></td></tr>
  819: <tr><td>$lt{'ln'}   </td>
  820:     <td><input type="text" name="clast" size="15" value="$inst_results{'lastname'}" /></td></tr>
  821: <tr><td>$lt{'gen'}$genhelp</td>
  822:     <td><input type="text" name="cgen" size="5" value="$inst_results{'generation'}" /></td></tr>
  823: <tr><td>$lt{'mail'}</td>
  824:     <td><input type="text" name="cemail" size="20" value="$inst_results{'permanentemail'}" /></td></tr>
  825: </table>
  826: $lt{'idsn'} <input type="text" name="cstid" size="15" value="$inst_results{'id'}" /></p>
  827: $lt{'hs'}: <select name="hserver" size="1"> $home_server_list </select>
  828: <hr />
  829: <h3>$lt{'lg'}</h3>
  830: <p>$generalrule </p>
  831: <p>$authformkrb </p>
  832: <p>$authformint </p>
  833: <p>$authformfsys</p>
  834: <p>$authformloc </p>
  835: <hr />
  836: $portfolioform
  837: ENDNEWUSER
  838:     } else { # user already exists
  839: 	my %lt=&Apache::lonlocal::texthash(
  840:                     'cup'  => "Change User Privileges",
  841:                     'usr'  => "User",                    
  842:                     'id'   => "in domain",
  843:                     'fn'   => "first name",
  844:                     'mn'   => "middle name",
  845:                     'ln'   => "last name",
  846:                     'gen'  => "generation",
  847:                     'email' => "permanent e-mail",
  848: 				       );
  849: 	$r->print(<<ENDCHANGEUSER);
  850: $start_page
  851: $crumbs
  852: <h1>$lt{'cup'}</h1>
  853: $forminfo
  854: <h2>$lt{'usr'} "$ccuname" $lt{'id'} "$ccdomain"</h2>
  855: ENDCHANGEUSER
  856:         # Get the users information
  857:         my %userenv = 
  858:             &Apache::lonnet::get('environment',
  859:                 ['firstname','middlename','lastname','generation',
  860:                  'permanentemail','portfolioquota'],$ccdomain,$ccuname);
  861:         my %rolesdump=&Apache::lonnet::dump('roles',$ccdomain,$ccuname);
  862:         $r->print('
  863: <hr />'.
  864:                   &Apache::loncommon::start_data_table().
  865:                   &Apache::loncommon::start_data_table_header_row().
  866: '<th>'.$lt{'fn'}.'</th><th>'.$lt{'mn'}.'</th><th>'.$lt{'ln'}.'</th><th>'.$lt{'gen'}.'</th><th>'.$lt{'email'}.'</th>'.
  867:                   &Apache::loncommon::end_data_table_header_row().
  868:                   &Apache::loncommon::start_data_table_row());
  869:         foreach my $item ('firstname','middlename','lastname','generation','permenanentemail') {
  870:            if (&Apache::lonnet::allowed('mau',$ccdomain)) {
  871:               $r->print(<<"END");
  872: <td><input type="text" name="c$item" value="$userenv{$item}" size="15" /></td>
  873: END
  874:            } else {
  875:                $r->print('<td>'.$userenv{$item}.'</td>');
  876:            }
  877:         }
  878:         $r->print(&Apache::loncommon::end_data_table_row().
  879:                   &Apache::loncommon::end_data_table());
  880:         # Build up table of user roles to allow revocation of a role.
  881:         my ($tmp) = keys(%rolesdump);
  882:         unless ($tmp =~ /^(con_lost|error)/i) {
  883:            my $now=time;
  884: 	   my %lt=&Apache::lonlocal::texthash(
  885: 		    'rer'  => "Revoke Existing Roles",
  886:                     'rev'  => "Revoke",                    
  887:                     'del'  => "Delete",
  888: 		    'ren'  => "Re-Enable",
  889:                     'rol'  => "Role",
  890:                     'ext'  => "Extent",
  891:                     'sta'  => "Start",
  892:                     'end'  => "End"
  893: 				       );
  894:            my (%roletext,%sortrole,%roleclass,%rolepriv);
  895: 	   foreach my $area (sort { my $a1=join('_',(split('_',$a))[1,0]);
  896: 				    my $b1=join('_',(split('_',$b))[1,0]);
  897: 				    return $a1 cmp $b1;
  898: 				} keys(%rolesdump)) {
  899:                next if ($area =~ /^rolesdef/);
  900: 	       my $envkey=$area;
  901:                my $role = $rolesdump{$area};
  902:                my $thisrole=$area;
  903:                $area =~ s/\_\w\w$//;
  904:                my ($role_code,$role_end_time,$role_start_time) = 
  905:                    split(/_/,$role);
  906: # Is this a custom role? Get role owner and title.
  907: 	       my ($croleudom,$croleuname,$croletitle)=
  908: 	           ($role_code=~m{^cr/($match_domain)/($match_username)/(\w+)$});
  909:                my $allowed=0;
  910:                my $delallowed=0;
  911: 	       my $sortkey=$role_code;
  912: 	       my $class='Unknown';
  913:                if ($area =~ m{^/($match_domain)/($match_courseid)} ) {
  914: 		   $class='Course';
  915:                    my ($coursedom,$coursedir) = ($1,$2);
  916: 		   $sortkey.="\0$coursedom";
  917:                    # $1.'_'.$2 is the course id (eg. 103_12345abcef103l3).
  918:                    my %coursedata=
  919:                        &Apache::lonnet::coursedescription($1.'_'.$2);
  920: 		   my $carea;
  921: 		   if (defined($coursedata{'description'})) {
  922: 		       $carea=$coursedata{'description'}.
  923:                            '<br />'.&mt('Domain').': '.$coursedom.('&nbsp;'x8).
  924:      &Apache::loncommon::syllabuswrapper('Syllabus',$coursedir,$coursedom);
  925: 		       $sortkey.="\0".$coursedata{'description'};
  926:                        $class=$coursedata{'type'};
  927: 		   } else {
  928: 		       $carea=&mt('Unavailable course').': '.$area;
  929: 		       $sortkey.="\0".&mt('Unavailable course').': '.$area;
  930: 		   }
  931: 		   $sortkey.="\0$coursedir";
  932:                    $inccourses{$1.'_'.$2}=1;
  933:                    if ((&Apache::lonnet::allowed('c'.$role_code,$1.'/'.$2)) ||
  934:                        (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
  935:                        $allowed=1;
  936:                    }
  937:                    if ((&Apache::lonnet::allowed('dro',$1)) ||
  938:                        (&Apache::lonnet::allowed('dro',$ccdomain))) {
  939:                        $delallowed=1;
  940:                    }
  941: # - custom role. Needs more info, too
  942: 		   if ($croletitle) {
  943: 		       if (&Apache::lonnet::allowed('ccr',$1.'/'.$2)) {
  944: 			   $allowed=1;
  945: 			   $thisrole.='.'.$role_code;
  946: 		       }
  947: 		   }
  948:                    # Compute the background color based on $area
  949:                    if ($area=~m{^/($match_domain)/($match_courseid)/(\w+)}) {
  950:                        $carea.='<br />Section: '.$3;
  951: 		       $sortkey.="\0$3";
  952:                    }
  953:                    $area=$carea;
  954:                } else {
  955: 		   $sortkey.="\0".$area;
  956:                    # Determine if current user is able to revoke privileges
  957:                    if ($area=~m{^/($match_domain)/}) {
  958:                        if ((&Apache::lonnet::allowed('c'.$role_code,$1)) ||
  959:                        (&Apache::lonnet::allowed('c'.$role_code,$ccdomain))) {
  960:                            $allowed=1;
  961:                        }
  962:                        if (((&Apache::lonnet::allowed('dro',$1))  ||
  963:                             (&Apache::lonnet::allowed('dro',$ccdomain))) &&
  964:                            ($role_code ne 'dc')) {
  965:                            $delallowed=1;
  966:                        }
  967:                    } else {
  968:                        if (&Apache::lonnet::allowed('c'.$role_code,'/')) {
  969:                            $allowed=1;
  970:                        }
  971:                    }
  972: 		   if ($role_code eq 'ca' || $role_code eq 'au') {
  973: 		       $class='Construction Space';
  974: 		   } elsif ($role_code eq 'su') {
  975: 		       $class='System';
  976: 		   } else {
  977: 		       $class='Domain';
  978: 		   }
  979:                }
  980:                if (($role_code eq 'ca') || ($role_code eq 'aa')) {
  981:                    $area=~m{/($match_domain)/($match_username)};
  982: 		   if (&authorpriv($2,$1)) {
  983: 		       $allowed=1;
  984:                    } else {
  985:                        $allowed=0;
  986:                    }
  987:                }
  988:                my $row = '';
  989:                $row.= '<td>';
  990:                my $active=1;
  991:                $active=0 if (($role_end_time) && ($now>$role_end_time));
  992:                if (($active) && ($allowed)) {
  993:                    $row.= '<input type="checkbox" name="rev:'.$thisrole.'" />';
  994:                } else {
  995:                    if ($active) {
  996:                       $row.='&nbsp;';
  997: 		   } else {
  998:                       $row.=&mt('expired or revoked');
  999: 		   }
 1000:                }
 1001: 	       $row.='</td><td>';
 1002:                if ($allowed && !$active) {
 1003:                    $row.= '<input type="checkbox" name="ren:'.$thisrole.'" />';
 1004:                } else {
 1005:                    $row.='&nbsp;';
 1006:                }
 1007: 	       $row.='</td><td>';
 1008:                if ($delallowed) {
 1009:                    $row.= '<input type="checkbox" name="del:'.$thisrole.'" />';
 1010:                } else {
 1011:                    $row.='&nbsp;';
 1012:                }
 1013: 	       my $plaintext='';
 1014: 	       if (!$croletitle) {
 1015:                    $plaintext=&Apache::lonnet::plaintext($role_code,$class)
 1016: 	       } else {
 1017: 	           $plaintext=
 1018: 		"Customrole '$croletitle' defined by $croleuname\@$croleudom";
 1019: 	       }
 1020:                $row.= '</td><td>'.$plaintext.
 1021:                       '</td><td>'.$area.
 1022:                       '</td><td>'.($role_start_time?localtime($role_start_time)
 1023:                                                    : '&nbsp;' ).
 1024:                       '</td><td>'.($role_end_time  ?localtime($role_end_time)
 1025:                                                    : '&nbsp;' )
 1026:                       ."</td>";
 1027: 	       $sortrole{$sortkey}=$envkey;
 1028: 	       $roletext{$envkey}=$row;
 1029: 	       $roleclass{$envkey}=$class;
 1030:                $rolepriv{$envkey}=$allowed;
 1031:                #$r->print($row);
 1032:            } # end of foreach        (table building loop)
 1033:            my $rolesdisplay = 0;
 1034:            my %output = ();
 1035: 	   foreach my $type ('Construction Space','Course','Group','Domain','System','Unknown') {
 1036: 	       $output{$type} = '';
 1037: 	       foreach my $which (sort {uc($a) cmp uc($b)} (keys(%sortrole))) {
 1038: 		   if ( ($roleclass{$sortrole{$which}} =~ /^\Q$type\E/ ) && ($rolepriv{$sortrole{$which}}) ) { 
 1039: 		       $output{$type}.=
 1040:                              &Apache::loncommon::start_data_table_row().
 1041:                              $roletext{$sortrole{$which}}.
 1042:                              &Apache::loncommon::end_data_table_row();
 1043: 		   }
 1044: 	       }
 1045: 	       unless($output{$type} eq '') {
 1046: 		   $output{$type} = '<tr class="LC_info_row">'.
 1047: 			     "<td align='center' colspan='7'>".&mt($type)."</td></tr>".
 1048:                               $output{$type};
 1049:                    $rolesdisplay = 1;
 1050: 	       }
 1051: 	   }
 1052:            if ($rolesdisplay == 1) {
 1053:                $r->print('
 1054: <hr />
 1055: <h3>'.$lt{'rer'}.'</h3>'.
 1056: &Apache::loncommon::start_data_table("LC_createuser").
 1057: &Apache::loncommon::start_data_table_header_row().
 1058: '<th>'.$lt{'rev'}.'</th><th>'.$lt{'ren'}.'</th><th>'.$lt{'del'}.
 1059: '</th><th>'.$lt{'rol'}.'</th><th>'.$lt{'ext'}.
 1060: '</th><th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'.
 1061: &Apache::loncommon::end_data_table_header_row());
 1062:                foreach my $type ('Construction Space','Course','Group','Domain','System','Unknown') {
 1063:                    if ($output{$type}) {
 1064:                        $r->print($output{$type}."\n");
 1065:                    }
 1066:                }
 1067: 	       $r->print(&Apache::loncommon::end_data_table());
 1068:            }
 1069:         }  # End of unless
 1070: 	my $currentauth=&Apache::lonnet::queryauthenticate($ccuname,$ccdomain);
 1071: 	if ($currentauth=~/^krb(4|5):/) {
 1072: 	    $currentauth=~/^krb(4|5):(.*)/;
 1073: 	    my $krbdefdom=$2;
 1074:             my %param = ( formname => 'document.cu',
 1075:                           kerb_def_dom => $krbdefdom 
 1076:                           );
 1077:             $loginscript  = &Apache::loncommon::authform_header(%param);
 1078: 	}
 1079: 	# Check for a bad authentication type
 1080:         unless ($currentauth=~/^krb(4|5):/ or
 1081: 		$currentauth=~/^unix:/ or
 1082: 		$currentauth=~/^internal:/ or
 1083: 		$currentauth=~/^localauth:/
 1084: 		) { # bad authentication scheme
 1085: 	    if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 1086:                 &initialize_authen_forms();
 1087: 		my %lt=&Apache::lonlocal::texthash(
 1088:                                'err'   => "ERROR",
 1089: 			       'uuas'  => "This user has an unrecognized authentication scheme",
 1090:                                'sldb'  => "Please specify login data below",
 1091:                                'ld'    => "Login Data"
 1092: 						   );
 1093: 		$r->print(<<ENDBADAUTH);
 1094: <hr />
 1095: <script type="text/javascript" language="Javascript">
 1096: $loginscript
 1097: </script>
 1098: <font color='#ff0000'>$lt{'err'}:</font>
 1099: $lt{'uuas'} ($currentauth). $lt{'sldb'}.
 1100: <h3>$lt{'ld'}</h3>
 1101: <p>$generalrule</p>
 1102: <p>$authformkrb</p>
 1103: <p>$authformint</p>
 1104: <p>$authformfsys</p>
 1105: <p>$authformloc</p>
 1106: ENDBADAUTH
 1107:             } else { 
 1108:                 # This user is not allowed to modify the user's 
 1109:                 # authentication scheme, so just notify them of the problem
 1110: 		my %lt=&Apache::lonlocal::texthash(
 1111:                                'err'   => "ERROR",
 1112: 			       'uuas'  => "This user has an unrecognized authentication scheme",
 1113:                                'adcs'  => "Please alert a domain coordinator of this situation"
 1114: 						   );
 1115: 		$r->print(<<ENDBADAUTH);
 1116: <hr />
 1117: <font color="#ff0000"> $lt{'err'}: </font>
 1118: $lt{'uuas'} ($currentauth). $lt{'adcs'}.
 1119: <hr />
 1120: ENDBADAUTH
 1121:             }
 1122:         } else { # Authentication type is valid
 1123: 	    my $authformcurrent='';
 1124: 	    my $authform_other='';
 1125:             &initialize_authen_forms();
 1126: 	    if ($currentauth=~/^krb(4|5):/) {
 1127: 		$authformcurrent=$authformkrb;
 1128: 		$authform_other="<p>$authformint</p>\n".
 1129:                     "<p>$authformfsys</p><p>$authformloc</p>";
 1130: 	    }
 1131: 	    elsif ($currentauth=~/^internal:/) {
 1132: 		$authformcurrent=$authformint;
 1133: 		$authform_other="<p>$authformkrb</p>".
 1134:                     "<p>$authformfsys</p><p>$authformloc</p>";
 1135: 	    }
 1136: 	    elsif ($currentauth=~/^unix:/) {
 1137: 		$authformcurrent=$authformfsys;
 1138: 		$authform_other="<p>$authformkrb</p>".
 1139:                     "<p>$authformint</p><p>$authformloc;</p>";
 1140: 	    }
 1141: 	    elsif ($currentauth=~/^localauth:/) {
 1142: 		$authformcurrent=$authformloc;
 1143: 		$authform_other="<p>$authformkrb</p>".
 1144:                     "<p>$authformint</p><p>$authformfsys</p>";
 1145: 	    }
 1146:             $authformcurrent.=' <i>(will override current values)</i><br />';
 1147:             if (&Apache::lonnet::allowed('mau',$ccdomain)) {
 1148: 		# Current user has login modification privileges
 1149: 		my %lt=&Apache::lonlocal::texthash(
 1150:                                'ccld'  => "Change Current Login Data",
 1151: 			       'enld'  => "Enter New Login Data"
 1152: 						   );
 1153: 		$r->print(<<ENDOTHERAUTHS);
 1154: <hr />
 1155: <script type="text/javascript" language="Javascript">
 1156: $loginscript
 1157: </script>
 1158: <h3>$lt{'ccld'}</h3>
 1159: <p>$generalrule</p>
 1160: <p>$authformnop</p>
 1161: <p>$authformcurrent</p>
 1162: <h3>$lt{'enld'}</h3>
 1163: $authform_other
 1164: ENDOTHERAUTHS
 1165:             } else {
 1166:                 if (&Apache::lonnet::allowed('mau',$env{'request.role.domain'})) {
 1167:                     my %lt=&Apache::lonlocal::texthash(
 1168:                                'ccld'  => "Change Current Login Data",
 1169:                                'yodo'  => "You do not have privileges to modify the authentication configuration for this user.",
 1170:                                'ifch'  => "If a change is required, contact a domain coordinator for the domain",
 1171:                     );
 1172:                     $r->print(<<ENDNOPRIV);
 1173: <hr />
 1174: <h3>$lt{'ccld'}</h3>
 1175: $lt{'yodo'} $lt{'ifch'}: $ccdomain 
 1176: ENDNOPRIV
 1177:                 } 
 1178:             }
 1179:             if (&Apache::lonnet::allowed('mpq',$env{'request.role.domain'})) {
 1180:                 # Current user has quota modification privileges
 1181:                 $r->print(&portfolio_quota($ccuname,$ccdomain));
 1182:             }
 1183:         }  ## End of "check for bad authentication type" logic
 1184:     } ## End of new user/old user logic
 1185:     $r->print('<hr /><h3>'.&mt('Add Roles').'</h3>');
 1186: #
 1187: # Co-Author
 1188: # 
 1189:     if (&authorpriv($env{'user.name'},$env{'request.role.domain'}) &&
 1190:         ($env{'user.name'} ne $ccuname || $env{'user.domain'} ne $ccdomain)) {
 1191:         # No sense in assigning co-author role to yourself
 1192: 	my $cuname=$env{'user.name'};
 1193:         my $cudom=$env{'request.role.domain'};
 1194: 	   my %lt=&Apache::lonlocal::texthash(
 1195: 		    'cs'   => "Construction Space",
 1196:                     'act'  => "Activate",                    
 1197:                     'rol'  => "Role",
 1198:                     'ext'  => "Extent",
 1199:                     'sta'  => "Start",
 1200:                     'end'  => "End",
 1201:                     'cau'  => "Co-Author",
 1202:                     'caa'  => "Assistant Co-Author",
 1203:                     'ssd'  => "Set Start Date",
 1204:                     'sed'  => "Set End Date"
 1205: 				       );
 1206:        $r->print('<h4>'.$lt{'cs'}.'</h4>'."\n". 
 1207:            &Apache::loncommon::start_data_table()."\n".
 1208:            &Apache::loncommon::start_data_table_header_row()."\n".
 1209:            '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th>'.
 1210:            '<th>'.$lt{'ext'}.'</th><th>'.$lt{'sta'}.'</th>'.
 1211:            '<th>'.$lt{'end'}.'</th>'."\n".
 1212:            &Apache::loncommon::end_data_table_header_row()."\n".
 1213:            &Apache::loncommon::start_data_table_row()."\n".
 1214:            '<td>
 1215:             <input type=checkbox name="act_'.$cudom.'_'.$cuname.'_ca" />
 1216:            </td>
 1217:            <td>'.$lt{'cau'}.'</td>
 1218:            <td>'.$cudom.'_'.$cuname.'</td>
 1219:            <td><input type="hidden" name="start_'.$cudom.'_'.$cuname.'_ca" value="" />
 1220:              <a href=
 1221: "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>
 1222: <td><input type=hidden name="end_'.$cudom.'_'.$cuname.'_ca" value="" />
 1223: <a href=
 1224: "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".
 1225:           &Apache::loncommon::end_data_table_row()."\n".
 1226:           &Apache::loncommon::start_data_table_row()."\n".
 1227: '<td><input type=checkbox name="act_'.$cudom.'_'.$cuname.'_aa" /></td>
 1228: <td>'.$lt{'caa'}.'</td>
 1229: <td>'.$cudom.'_'.$cuname.'</td>
 1230: <td><input type=hidden name="start_'.$cudom.'_'.$cuname.'_aa" value="" />
 1231: <a href=
 1232: "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>
 1233: <td><input type=hidden name="end_'.$cudom.'_'.$cuname.'_aa" value="" />
 1234: <a href=
 1235: "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".
 1236:          &Apache::loncommon::end_data_table_row()."\n".
 1237:          &Apache::loncommon::end_data_table());
 1238:     }
 1239: #
 1240: # Domain level
 1241: #
 1242:     my $num_domain_level = 0;
 1243:     my $domaintext = 
 1244:     '<h4>'.&mt('Domain Level').'</h4>'.
 1245:     &Apache::loncommon::start_data_table().
 1246:     &Apache::loncommon::start_data_table_header_row().
 1247:     '<th>'.&mt('Activate').'</th><th>'.&mt('Role').'</th><th>'.
 1248:     &mt('Extent').'</th>'.
 1249:     '<th>'.&mt('Start').'</th><th>'.&mt('End').'</th>'.
 1250:     &Apache::loncommon::end_data_table_header_row();
 1251:     foreach my $thisdomain (sort(&Apache::lonnet::all_domains())) {
 1252:         foreach my $role ('dc','li','dg','au','sc') {
 1253:             if (&Apache::lonnet::allowed('c'.$role,$thisdomain)) {
 1254:                my $plrole=&Apache::lonnet::plaintext($role);
 1255: 	       my %lt=&Apache::lonlocal::texthash(
 1256:                     'ssd'  => "Set Start Date",
 1257:                     'sed'  => "Set End Date"
 1258: 				       );
 1259:                $num_domain_level ++;
 1260:                $domaintext .= 
 1261: &Apache::loncommon::start_data_table_row().
 1262: '<td><input type=checkbox name="act_'.$thisdomain.'_'.$role.'" /></td>
 1263: <td>'.$plrole.'</td>
 1264: <td>'.$thisdomain.'</td>
 1265: <td><input type=hidden name="start_'.$thisdomain.'_'.$role.'" value="" />
 1266: <a href=
 1267: "javascript:pjump('."'date_start','Start Date $plrole',document.cu.start_$thisdomain\_$role.value,'start_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'ssd'}.'</a></td>
 1268: <td><input type=hidden name="end_'.$thisdomain.'_'.$role.'" value="" />
 1269: <a href=
 1270: "javascript:pjump('."'date_end','End Date $plrole',document.cu.end_$thisdomain\_$role.value,'end_$thisdomain\_$role','cu.pres','dateset'".')">'.$lt{'sed'}.'</a></td>'.
 1271: &Apache::loncommon::end_data_table_row();
 1272:             }
 1273:         } 
 1274:     }
 1275:     $domaintext.= &Apache::loncommon::end_data_table();
 1276:     if ($num_domain_level > 0) {
 1277:         $r->print($domaintext);
 1278:     }
 1279: #
 1280: # Course and group levels
 1281: #
 1282: 
 1283:     if ($env{'request.role'} =~ m{^dc\./($match_domain)/$}) {
 1284:         $r->print(&course_level_dc($1,'Course'));
 1285:         $r->print('<hr /><input type="button" value="'.&mt('Modify User').'" onClick="setCourse()" />'."\n");
 1286:     } else {
 1287:         $r->print(&course_level_table(%inccourses));
 1288:         $r->print('<hr /><input type="button" value="'.&mt('Modify User').'" onClick="setSections()" />'."\n");
 1289:     }
 1290:     $r->print(&Apache::lonhtmlcommon::echo_form_input(['phase','userrole','ccdomain','prevphase','state']));
 1291:     $r->print('<input type="hidden" name="state" value="" />');
 1292:     $r->print('<input type="hidden" name="prevphase" value="'.$env{'form.phase'}.'" />');
 1293:     $r->print("</form>".&Apache::loncommon::end_page());
 1294: }
 1295: 
 1296: # ================================================================= Phase Three
 1297: sub update_user_data {
 1298:     my ($r) = @_; 
 1299:     my $uhome=&Apache::lonnet::homeserver($env{'form.ccuname'},
 1300:                                           $env{'form.ccdomain'});
 1301:     # Error messages
 1302:     my $error     = '<font color="#ff0000">'.&mt('Error').':</font>';
 1303:     my $end       = &Apache::loncommon::end_page();
 1304: 
 1305:     my $title;
 1306:     if (exists($env{'form.makeuser'})) {
 1307: 	$title='Set Privileges for New User';
 1308:     } else {
 1309:         $title='Modify User Privileges';
 1310:     }
 1311: 
 1312:     my ($jsback,$elements) = &crumb_utilities();
 1313:     my $jscript = '<script type="text/javascript">'."\n".
 1314:                   $jsback."\n".'</script>'."\n";
 1315: 
 1316:     $r->print(&Apache::loncommon::start_page($title,$jscript));
 1317:     &Apache::lonhtmlcommon::add_breadcrumb
 1318:        ({href=>"javascript:backPage(document.userupdate)",
 1319:          text=>"User/custom role search",
 1320:          faq=>282,bug=>'Instructor Interface',});
 1321:     if ($env{'form.prevphase'} eq 'userpicked') {
 1322:         &Apache::lonhtmlcommon::add_breadcrumb
 1323:            ({href=>"javascript:backPage(document.userupdate,'get_user_info','select')",
 1324:              text=>"Select a user",
 1325:              faq=>282,bug=>'Instructor Interface',});
 1326:     }
 1327:     &Apache::lonhtmlcommon::add_breadcrumb
 1328:        ({href=>"javascript:backPage(document.userupdate,'$env{'form.prevphase'}','modify')",
 1329:          text=>"Set user role",
 1330:          faq=>282,bug=>'Instructor Interface',},
 1331:         {href=>"/adm/createuser",
 1332:          text=>"Result",
 1333:          faq=>282,bug=>'Instructor Interface',});
 1334:     $r->print(&Apache::lonhtmlcommon::breadcrumbs('User Management'));
 1335: 
 1336:     my %disallowed;
 1337:     # Check Inputs
 1338:     if (! $env{'form.ccuname'} ) {
 1339: 	$r->print($error.&mt('No login name specified').'.'.$end);
 1340: 	return;
 1341:     }
 1342:     if (  $env{'form.ccuname'} ne 
 1343: 	  &LONCAPA::clean_username($env{'form.ccuname'}) ) {
 1344: 	$r->print($error.&mt('Invalid login name').'.  '.
 1345: 		  &mt('Only letters, numbers, periods, dashes, @, and underscores are valid').'.'.
 1346: 		  $end);
 1347: 	return;
 1348:     }
 1349:     if (! $env{'form.ccdomain'}       ) {
 1350: 	$r->print($error.&mt('No domain specified').'.'.$end);
 1351: 	return;
 1352:     }
 1353:     if (  $env{'form.ccdomain'} ne
 1354: 	  &LONCAPA::clean_domain($env{'form.ccdomain'}) ) {
 1355: 	$r->print($error.&mt ('Invalid domain name').'.  '.
 1356: 		  &mt('Only letters, numbers, periods, dashes, and underscores are valid').'.'.
 1357: 		  $end);
 1358: 	return;
 1359:     }
 1360:     if (! exists($env{'form.makeuser'})) {
 1361:         # Modifying an existing user, so check the validity of the name
 1362:         if ($uhome eq 'no_host') {
 1363:             $r->print($error.&mt('Unable to determine home server for ').
 1364:                       $env{'form.ccuname'}.&mt(' in domain ').
 1365:                       $env{'form.ccdomain'}.'.');
 1366:             return;
 1367:         }
 1368:     }
 1369:     # Determine authentication method and password for the user being modified
 1370:     my $amode='';
 1371:     my $genpwd='';
 1372:     if ($env{'form.login'} eq 'krb') {
 1373: 	$amode='krb';
 1374: 	$amode.=$env{'form.krbver'};
 1375: 	$genpwd=$env{'form.krbarg'};
 1376:     } elsif ($env{'form.login'} eq 'int') {
 1377: 	$amode='internal';
 1378: 	$genpwd=$env{'form.intarg'};
 1379:     } elsif ($env{'form.login'} eq 'fsys') {
 1380: 	$amode='unix';
 1381: 	$genpwd=$env{'form.fsysarg'};
 1382:     } elsif ($env{'form.login'} eq 'loc') {
 1383: 	$amode='localauth';
 1384: 	$genpwd=$env{'form.locarg'};
 1385: 	$genpwd=" " if (!$genpwd);
 1386:     } elsif (($env{'form.login'} eq 'nochange') ||
 1387:              ($env{'form.login'} eq ''        )) { 
 1388:         # There is no need to tell the user we did not change what they
 1389:         # did not ask us to change.
 1390:         # If they are creating a new user but have not specified login
 1391:         # information this will be caught below.
 1392:     } else {
 1393: 	    $r->print($error.&mt('Invalid login mode or password').$end);    
 1394: 	    return;
 1395:     }
 1396:     if ($env{'form.makeuser'}) {
 1397:         # Create a new user
 1398: 	my %lt=&Apache::lonlocal::texthash(
 1399:                     'cru'  => "Creating user",                    
 1400:                     'id'   => "in domain"
 1401: 					   );
 1402: 	$r->print(<<ENDNEWUSERHEAD);
 1403: <h3>$lt{'cru'} "$env{'form.ccuname'}" $lt{'id'} "$env{'form.ccdomain'}"</h3>
 1404: ENDNEWUSERHEAD
 1405:         # Check for the authentication mode and password
 1406:         if (! $amode || ! $genpwd) {
 1407: 	    $r->print($error.&mt('Invalid login mode or password').$end);    
 1408: 	    return;
 1409: 	}
 1410:         # Determine desired host
 1411:         my $desiredhost = $env{'form.hserver'};
 1412:         if (lc($desiredhost) eq 'default') {
 1413:             $desiredhost = undef;
 1414:         } else {
 1415:             my %home_servers = 
 1416: 		&Apache::lonnet::get_servers($env{'form.ccdomain'},'library');
 1417:             if (! exists($home_servers{$desiredhost})) {
 1418:                 $r->print($error.&mt('Invalid home server specified'));
 1419:                 return;
 1420:             }
 1421:         }
 1422: 	# Call modifyuser
 1423: 	my $result = &Apache::lonnet::modifyuser
 1424: 	    ($env{'form.ccdomain'},$env{'form.ccuname'},$env{'form.cstid'},
 1425:              $amode,$genpwd,$env{'form.cfirst'},
 1426:              $env{'form.cmiddle'},$env{'form.clast'},$env{'form.cgen'},
 1427:              undef,$desiredhost
 1428: 	     );
 1429: 	$r->print(&mt('Generating user').': '.$result);
 1430:         my $home = &Apache::lonnet::homeserver($env{'form.ccuname'},
 1431:                                                $env{'form.ccdomain'});
 1432:         $r->print('<br />'.&mt('Home server').': '.$home.' '.
 1433:                   &Apache::lonnet::hostname($home));
 1434:     } elsif (($env{'form.login'} ne 'nochange') &&
 1435:              ($env{'form.login'} ne ''        )) {
 1436: 	# Modify user privileges
 1437:     my %lt=&Apache::lonlocal::texthash(
 1438:                     'usr'  => "User",                    
 1439:                     'id'   => "in domain"
 1440: 				       );
 1441: 	$r->print(<<ENDMODIFYUSERHEAD);
 1442: <h2>$lt{'usr'} "$env{'form.ccuname'}" $lt{'id'} "$env{'form.ccdomain'}"</h2>
 1443: ENDMODIFYUSERHEAD
 1444:         if (! $amode || ! $genpwd) {
 1445: 	    $r->print($error.'Invalid login mode or password'.$end);    
 1446: 	    return;
 1447: 	}
 1448: 	# Only allow authentification modification if the person has authority
 1449: 	if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'})) {
 1450: 	    $r->print('Modifying authentication: '.
 1451:                       &Apache::lonnet::modifyuserauth(
 1452: 		       $env{'form.ccdomain'},$env{'form.ccuname'},
 1453:                        $amode,$genpwd));
 1454:             $r->print('<br />'.&mt('Home server').': '.&Apache::lonnet::homeserver
 1455: 		  ($env{'form.ccuname'},$env{'form.ccdomain'}));
 1456: 	} else {
 1457: 	    # Okay, this is a non-fatal error.
 1458: 	    $r->print($error.&mt('You do not have the authority to modify this users authentification information').'.');    
 1459: 	}
 1460:     }
 1461:     ##
 1462:     if (! $env{'form.makeuser'} ) {
 1463:         # Check for need to change
 1464:         my %userenv = &Apache::lonnet::get
 1465:             ('environment',['firstname','middlename','lastname','generation',
 1466:              'permanentemail','portfolioquota','inststatus'],
 1467:               $env{'form.ccdomain'},$env{'form.ccuname'});
 1468:         my ($tmp) = keys(%userenv);
 1469:         if ($tmp =~ /^(con_lost|error)/i) { 
 1470:             %userenv = ();
 1471:         }
 1472:         # Check to see if we need to change user information
 1473:         foreach my $item ('firstname','middlename','lastname','generation','permanentemail') {
 1474:             # Strip leading and trailing whitespace
 1475:             $env{'form.c'.$item} =~ s/(\s+$|^\s+)//g; 
 1476:         }
 1477:         my ($quotachanged,$namechanged,$oldportfolioquota,$newportfolioquota,
 1478:             $inststatus,$isdefault,$defquotatext);
 1479:         my ($defquota,$settingstatus) = 
 1480:             &Apache::loncommon::default_quota($env{'form.ccdomain'},$inststatus);
 1481:         my %changeHash;
 1482:         if ($userenv{'portfolioquota'} ne '') {
 1483:             $oldportfolioquota = $userenv{'portfolioquota'};
 1484:             if ($env{'form.customquota'} == 1) {
 1485:                 if ($env{'form.portfolioquota'} eq '') {
 1486:                     $newportfolioquota = 0;
 1487:                 } else {
 1488:                     $newportfolioquota = $env{'form.portfolioquota'};
 1489:                     $newportfolioquota =~ s/[^\d\.]//g;
 1490:                 }
 1491:                 if ($newportfolioquota != $userenv{'portfolioquota'}) {
 1492:                     $quotachanged = &quota_admin($newportfolioquota,\%changeHash);
 1493:                 }
 1494:             } else {
 1495:                 $quotachanged = &quota_admin('',\%changeHash);
 1496:                 $newportfolioquota = $defquota;
 1497:                 $isdefault = 1; 
 1498:             }
 1499:         } else {
 1500:             $oldportfolioquota = $defquota;
 1501:             if ($env{'form.customquota'} == 1) {
 1502:                 if ($env{'form.portfolioquota'} eq '') {
 1503:                     $newportfolioquota = 0;
 1504:                 } else {
 1505:                     $newportfolioquota = $env{'form.portfolioquota'};
 1506:                     $newportfolioquota =~ s/[^\d\.]//g;
 1507:                 }
 1508:                 $quotachanged = &quota_admin($newportfolioquota,\%changeHash);
 1509:             } else {
 1510:                 $newportfolioquota = $defquota;
 1511:                 $isdefault = 1;
 1512:             }
 1513:         }
 1514:         if ($isdefault) {
 1515:             if ($settingstatus eq '') {
 1516:                 $defquotatext = &mt('(default)');
 1517:             } else {
 1518:                 my ($usertypes,$order) = 
 1519:                     &Apache::lonnet::retrieve_inst_usertypes($env{'form.ccdomain'});
 1520:                 if ($usertypes->{$settingstatus} eq '') {
 1521:                     $defquotatext = &mt('(default)');
 1522:                 } else { 
 1523:                     $defquotatext = &mt('(default for [_1])',$usertypes->{$settingstatus});
 1524:                 }
 1525:             }
 1526:         }
 1527:         if (&Apache::lonnet::allowed('mau',$env{'form.ccdomain'}) && 
 1528:             ($env{'form.cfirstname'}  ne $userenv{'firstname'}  ||
 1529:              $env{'form.cmiddlename'} ne $userenv{'middlename'} ||
 1530:              $env{'form.clastname'}   ne $userenv{'lastname'}   ||
 1531:              $env{'form.cgeneration'} ne $userenv{'generation'} ||
 1532:              $env{'form.cpermanentemail'} ne $userenv{'permanentemail'} )) {
 1533:             $namechanged = 1;
 1534:         }
 1535:         if ($namechanged) {
 1536:             # Make the change
 1537:             $changeHash{'firstname'}  = $env{'form.cfirstname'};
 1538:             $changeHash{'middlename'} = $env{'form.cmiddlename'};
 1539:             $changeHash{'lastname'}   = $env{'form.clastname'};
 1540:             $changeHash{'generation'} = $env{'form.cgeneration'};
 1541:             $changeHash{'permanentemail'} = $env{'form.permanentemail'};
 1542:             my $putresult = &Apache::lonnet::put
 1543:                 ('environment',\%changeHash,
 1544:                  $env{'form.ccdomain'},$env{'form.ccuname'});
 1545:             if ($putresult eq 'ok') {
 1546:             # Tell the user we changed the name
 1547: 		my %lt=&Apache::lonlocal::texthash(
 1548:                              'uic'  => "User Information Changed",             
 1549:                              'frst' => "first",
 1550:                              'mddl' => "middle",
 1551:                              'lst'  => "last",
 1552: 			     'gen'  => "generation",
 1553:                              'mail' => "permanent e-mail",
 1554:                              'disk' => "disk space allocated to portfolio files",
 1555:                              'prvs' => "Previous",
 1556:                              'chto' => "Changed To"
 1557: 						   );
 1558:                 $r->print(<<"END");
 1559: <table border="2">
 1560: <caption>$lt{'uic'}</caption>
 1561: <tr><th>&nbsp;</th>
 1562:     <th>$lt{'frst'}</th>
 1563:     <th>$lt{'mddl'}</th>
 1564:     <th>$lt{'lst'}</th>
 1565:     <th>$lt{'gen'}</th>
 1566:     <th>$lt{'disk'}<th></tr>
 1567: <tr><td>$lt{'prvs'}</td>
 1568:     <td>$userenv{'firstname'}  </td>
 1569:     <td>$userenv{'middlename'} </td>
 1570:     <td>$userenv{'lastname'}   </td>
 1571:     <td>$userenv{'generation'} </td>
 1572:     <td>$userenv{'permanentemail'} </td>
 1573:     <td>$oldportfolioquota Mb</td>
 1574: </tr>
 1575: <tr><td>$lt{'chto'}</td>
 1576:     <td>$env{'form.cfirstname'}  </td>
 1577:     <td>$env{'form.cmiddlename'} </td>
 1578:     <td>$env{'form.clastname'}   </td>
 1579:     <td>$env{'form.cgeneration'} </td>
 1580:     <td>$env{'form.cpermanentemail'} </td>
 1581:     <td>$newportfolioquota Mb $defquotatext </td></tr>
 1582: </table>
 1583: END
 1584:                 if (($env{'form.ccdomain'} eq $env{'user.domain'}) && 
 1585:                     ($env{'form.ccuname'} eq $env{'user.name'})) {
 1586:                     my %newenvhash;
 1587:                     foreach my $key (keys(%changeHash)) {
 1588:                         $newenvhash{'environment.'.$key} = $changeHash{$key};
 1589:                     }
 1590:                     &Apache::lonnet::appenv(%newenvhash);
 1591:                 }
 1592:             } else { # error occurred
 1593:                 $r->print("<h2>".&mt('Unable to successfully change environment for')." ".
 1594:                       $env{'form.ccuname'}." ".&mt('in domain')." ".
 1595:                       $env{'form.ccdomain'}."</h2>");
 1596:             }
 1597:         }  else { # End of if ($env ... ) logic
 1598:             my $putresult;
 1599:             if ($quotachanged) {
 1600:                 $putresult = &Apache::lonnet::put
 1601:                                  ('environment',\%changeHash,
 1602:                                   $env{'form.ccdomain'},$env{'form.ccuname'});
 1603:             }
 1604:             # They did not want to change the users name but we can
 1605:             # still tell them what the name is
 1606: 	    my %lt=&Apache::lonlocal::texthash(
 1607:                            'usr'  => "User",                    
 1608:                            'id'   => "in domain",
 1609:                            'gen'  => "Generation",
 1610:                            'mail' => "Permanent e-mail",
 1611:                            'disk' => "Disk space allocated to user's portfolio files",
 1612: 					       );
 1613:             $r->print(<<"END");
 1614: <h2>$lt{'usr'} "$env{'form.ccuname'}" $lt{'id'} "$env{'form.ccdomain'}"</h2>
 1615: <h4>$userenv{'firstname'} $userenv{'middlename'} $userenv{'lastname'} </h4>
 1616: <h4>$lt{'gen'}: $userenv{'generation'}</h4>
 1617: <h4>$lt{'mail'}: $userenv{'permanentemail'}</h4>
 1618: END
 1619:             if ($putresult eq 'ok') {
 1620:                 if ($oldportfolioquota != $newportfolioquota) {
 1621:                     $r->print('<h4>'.$lt{'disk'}.': '.$newportfolioquota.' Mb '. 
 1622:                               $defquotatext.'</h4>');
 1623:                     &Apache::lonnet::appenv('environment.portfolioquota' => $changeHash{'portfolioquota'});
 1624:                 }
 1625:             }
 1626:         }
 1627:     }
 1628:     ##
 1629:     my $now=time;
 1630:     $r->print('<h3>'.&mt('Modifying Roles').'</h3>');
 1631:     foreach my $key (keys (%env)) {
 1632: 	next if (! $env{$key});
 1633: 	# Revoke roles
 1634: 	if ($key=~/^form\.rev/) {
 1635: 	    if ($key=~/^form\.rev\:([^\_]+)\_([^\_\.]+)$/) {
 1636: # Revoke standard role
 1637: 	        $r->print(&mt('Revoking').' '.$2.' in '.$1.': <b>'.
 1638:                      &Apache::lonnet::revokerole($env{'form.ccdomain'},
 1639:                      $env{'form.ccuname'},$1,$2).'</b><br />');
 1640: 		if ($2 eq 'st') {
 1641: 		    $1=~m{^/($match_domain)/($match_courseid)};
 1642: 		    my $cid=$1.'_'.$2;
 1643: 		    my $user = $env{'form.ccuname'}.':'.$env{'form.ccdomain'};
 1644: 		    my $result = 
 1645: 			&Apache::lonnet::cput('classlist',
 1646: 					      { $user => $now },
 1647: 					      $env{'course.'.$cid.'.domain'},
 1648: 					      $env{'course.'.$cid.'.num'});
 1649: 		    $r->print(&mt('Drop from classlist: [_1]',
 1650: 				  '<b>'.$result.'</b>').'<br />');
 1651: 		}
 1652: 	    } 
 1653: 	    if ($key=~m{^form\.rev\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 1654: # Revoke custom role
 1655: 		$r->print(&mt('Revoking custom role:').
 1656:                       ' '.$4.' by '.$3.':'.$2.' in '.$1.': <b>'.
 1657:                       &Apache::lonnet::revokecustomrole($env{'form.ccdomain'},
 1658: 				  $env{'form.ccuname'},$1,$2,$3,$4).
 1659: 		'</b><br />');
 1660: 	    }
 1661: 	} elsif ($key=~/^form\.del/) {
 1662: 	    if ($key=~/^form\.del\:([^\_]+)\_([^\_\.]+)$/) {
 1663: # Delete standard role
 1664: 	        $r->print(&mt('Deleting').' '.$2.' in '.$1.': '.
 1665:                      &Apache::lonnet::assignrole($env{'form.ccdomain'},
 1666:                      $env{'form.ccuname'},$1,$2,$now,0,1).'<br />');
 1667: 		if ($2 eq 'st') {
 1668: 		    $1=~m{^/($match_domain)/($match_courseid)};
 1669: 		    my $cid=$1.'_'.$2;
 1670: 		    my $user = $env{'form.ccuname'}.':'.$env{'form.ccdomain'};
 1671: 		    my $result = 
 1672: 			&Apache::lonnet::cput('classlist',
 1673: 					      { $user => $now },
 1674: 					      $env{'course.'.$cid.'.domain'},
 1675: 					      $env{'course.'.$cid.'.num'});
 1676: 		    $r->print(&mt('Drop from classlist: [_1]',
 1677: 				  '<b>'.$result.'</b>').'<br />');
 1678: 		}
 1679:             }
 1680: 	    if ($key=~m{^form\.del\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 1681:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 1682: # Delete custom role
 1683:                 $r->print(&mt('Deleting custom role [_1] by [_2]@[_3] in [_4]',
 1684:                       $rolename,$rnam,$rdom,$url).': <b>'.
 1685:                       &Apache::lonnet::assigncustomrole($env{'form.ccdomain'},
 1686:                          $env{'form.ccuname'},$url,$rdom,$rnam,$rolename,$now,
 1687:                          0,1).'</b><br />');
 1688:             }
 1689: 	} elsif ($key=~/^form\.ren/) {
 1690:             my $udom = $env{'form.ccdomain'};
 1691:             my $uname = $env{'form.ccuname'};
 1692: # Re-enable standard role
 1693: 	    if ($key=~/^form\.ren\:([^\_]+)\_([^\_\.]+)$/) {
 1694:                 my $url = $1;
 1695:                 my $role = $2;
 1696:                 my $logmsg;
 1697:                 my $output;
 1698:                 if ($role eq 'st') {
 1699:                     if ($url =~ m-^/($match_domain)/($match_courseid)/?(\w*)$-) {
 1700:                         my $result = &Apache::loncommon::commit_studentrole(\$logmsg,$udom,$uname,$url,$role,$now,0,$1,$2,$3);
 1701:                         if (($result =~ /^error/) || ($result eq 'not_in_class') || ($result eq 'unknown_course')) {
 1702:                             $output = "Error: $result\n";
 1703:                         } else {
 1704:                             $output = &mt('Assigning').' '.$role.' in '.$url.
 1705:                                       &mt('starting').' '.localtime($now).
 1706:                                       ': <br />'.$logmsg.'<br />'.
 1707:                                       &mt('Add to classlist').': <b>ok</b><br />';
 1708:                         }
 1709:                     }
 1710:                 } else {
 1711: 		    my $result=&Apache::lonnet::assignrole($env{'form.ccdomain'},
 1712:                                $env{'form.ccuname'},$url,$role,0,$now);
 1713: 		    $output = &mt('Re-enabling [_1] in [_2]: <b>[_3]</b>',
 1714: 			      $role,$url,$result).'<br />';
 1715: 		}
 1716:                 $r->print($output);
 1717: 	    }
 1718: # Re-enable custom role
 1719: 	    if ($key=~m{^form\.ren\:([^_]+)_cr\.cr/($match_domain)/($match_username)/(\w+)$}) {
 1720:                 my ($url,$rdom,$rnam,$rolename) = ($1,$2,$3,$4);
 1721:                 my $result = &Apache::lonnet::assigncustomrole(
 1722:                                $env{'form.ccdomain'}, $env{'form.ccuname'},
 1723:                                $url,$rdom,$rnam,$rolename,0,$now);
 1724:                 $r->print(&mt('Re-enabling custom role [_1] by [_2]@[_3] in [_4] : <b>[_5]</b>',
 1725:                           $rolename,$rnam,$rdom,$url,$result).'<br />');
 1726:             }
 1727: 	} elsif ($key=~/^form\.act/) {
 1728:             my $udom = $env{'form.ccdomain'};
 1729:             my $uname = $env{'form.ccuname'};
 1730: 	    if ($key=~/^form\.act\_($match_domain)\_($match_courseid)\_cr_cr_($match_domain)_($match_username)_([^\_]+)$/) {
 1731:                 # Activate a custom role
 1732: 		my ($one,$two,$three,$four,$five)=($1,$2,$3,$4,$5);
 1733: 		my $url='/'.$one.'/'.$two;
 1734: 		my $full=$one.'_'.$two.'_cr_cr_'.$three.'_'.$four.'_'.$five;
 1735: 
 1736:                 my $start = ( $env{'form.start_'.$full} ?
 1737:                               $env{'form.start_'.$full} :
 1738:                               $now );
 1739:                 my $end   = ( $env{'form.end_'.$full} ?
 1740:                               $env{'form.end_'.$full} :
 1741:                               0 );
 1742:                                                                                      
 1743:                 # split multiple sections
 1744:                 my %sections = ();
 1745:                 my $num_sections = &build_roles($env{'form.sec_'.$full},\%sections,$5);
 1746:                 if ($num_sections == 0) {
 1747:                     $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$url,$three,$four,$five,$start,$end));
 1748:                 } else {
 1749: 		    my %curr_groups =
 1750: 			&Apache::longroup::coursegroups($one,$two);
 1751:                     foreach my $sec (sort {$a cmp $b} keys %sections) {
 1752:                         if (($sec eq 'none') || ($sec eq 'all') || 
 1753:                             exists($curr_groups{$sec})) {
 1754:                             $disallowed{$sec} = $url;
 1755:                             next;
 1756:                         }
 1757:                         my $securl = $url.'/'.$sec;
 1758: 		        $r->print(&Apache::loncommon::commit_customrole($udom,$uname,$securl,$three,$four,$five,$start,$end));
 1759:                     }
 1760:                 }
 1761: 	    } elsif ($key=~/^form\.act\_($match_domain)\_($match_name)\_([^\_]+)$/) {
 1762: 		# Activate roles for sections with 3 id numbers
 1763: 		# set start, end times, and the url for the class
 1764: 		my ($one,$two,$three)=($1,$2,$3);
 1765: 		my $start = ( $env{'form.start_'.$one.'_'.$two.'_'.$three} ? 
 1766: 			      $env{'form.start_'.$one.'_'.$two.'_'.$three} : 
 1767: 			      $now );
 1768: 		my $end   = ( $env{'form.end_'.$one.'_'.$two.'_'.$three} ? 
 1769: 			      $env{'form.end_'.$one.'_'.$two.'_'.$three} :
 1770: 			      0 );
 1771: 		my $url='/'.$one.'/'.$two;
 1772:                 my $type = 'three';
 1773:                 # split multiple sections
 1774:                 my %sections = ();
 1775:                 my $num_sections = &build_roles($env{'form.sec_'.$one.'_'.$two.'_'.$three},\%sections,$three);
 1776:                 if ($num_sections == 0) {
 1777:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,''));
 1778:                 } else {
 1779:                     my %curr_groups = 
 1780: 			&Apache::longroup::coursegroups($one,$two);
 1781:                     my $emptysec = 0;
 1782:                     foreach my $sec (sort {$a cmp $b} keys %sections) {
 1783:                         $sec =~ s/\W//g;
 1784:                         if ($sec ne '') {
 1785:                             if (($sec eq 'none') || ($sec eq 'all') || 
 1786:                                 exists($curr_groups{$sec})) {
 1787:                                 $disallowed{$sec} = $url;
 1788:                                 next;
 1789:                             }
 1790:                             my $securl = $url.'/'.$sec;
 1791:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$three,$start,$end,$one,$two,$sec));
 1792:                         } else {
 1793:                             $emptysec = 1;
 1794:                         }
 1795:                     }
 1796:                     if ($emptysec) {
 1797:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$three,$start,$end,$one,$two,''));
 1798:                     }
 1799:                 } 
 1800: 	    } elsif ($key=~/^form\.act\_([^\_]+)\_([^\_]+)$/) {
 1801: 		# Activate roles for sections with two id numbers
 1802: 		# set start, end times, and the url for the class
 1803: 		my $start = ( $env{'form.start_'.$1.'_'.$2} ? 
 1804: 			      $env{'form.start_'.$1.'_'.$2} : 
 1805: 			      $now );
 1806: 		my $end   = ( $env{'form.end_'.$1.'_'.$2} ? 
 1807: 			      $env{'form.end_'.$1.'_'.$2} :
 1808: 			      0 );
 1809: 		my $url='/'.$1.'/';
 1810:                 # split multiple sections
 1811:                 my %sections = ();
 1812:                 my $num_sections = &build_roles($env{'form.sec_'.$1.'_'.$2},\%sections,$2);
 1813:                 if ($num_sections == 0) {
 1814:                     $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$2,$start,$end,$1,undef,''));
 1815:                 } else {
 1816:                     my $emptysec = 0;
 1817:                     foreach my $sec (sort {$a cmp $b} keys %sections) {
 1818:                         if ($sec ne '') {
 1819:                             my $securl = $url.'/'.$sec;
 1820:                             $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$securl,$2,$start,$end,$1,undef,$sec));
 1821:                         } else {
 1822:                             $emptysec = 1;
 1823:                         }
 1824:                     }
 1825:                     if ($emptysec) {
 1826:                         $r->print(&Apache::loncommon::commit_standardrole($udom,$uname,$url,$2,$start,$end,$1,undef,''));
 1827:                     }
 1828:                 }
 1829: 	    } else {
 1830: 		$r->print('<p>'.&mt('ERROR').': '.&mt('Unknown command').' <tt>'.$key.'</tt></p><br />');
 1831:             }
 1832:             foreach my $key (sort(keys(%disallowed))) {
 1833:                 if (($key eq 'none') || ($key eq 'all')) {  
 1834:                     $r->print('<p>'.&mt('[_1] may not be used as the name for a section, as it is a reserved word.',$key));
 1835:                 } else {
 1836:                     $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));
 1837:                 }
 1838:                 $r->print(' '.&mt('Please <a href="javascript:history.go(-1)">go back</a> and choose a different section name.').'</p><br />');
 1839:             }
 1840: 	}
 1841:     } # End of foreach (keys(%env))
 1842: # Flush the course logs so reverse user roles immediately updated
 1843:     &Apache::lonnet::flushcourselogs();
 1844:     $r->print('<p><a href="/adm/createuser">Create/Modify Another User</a></p>');
 1845:     $r->print('<form name="userupdate" method="post" />'."\n");
 1846:     foreach my $item ('srchby','srchin','srchtype','srchterm','srchdomain','ccuname','ccdomain') {
 1847:         $r->print('<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n");
 1848:     }
 1849:     foreach my $item ('sortby','seluname','seludom') {
 1850:         if (exists($env{'form.'.$item})) {
 1851:             $r->print('<input type="hidden" name="'.$item.'" value="'.$env{'form.'.$item}.'" />'."\n");
 1852:         }
 1853:     }
 1854:     $r->print('<input type="hidden" name="phase" value="" />'."\n".
 1855:               '<input type ="hidden" name="state" value="" />'."\n".
 1856:               '</form>');
 1857:     $r->print(&Apache::loncommon::end_page());
 1858: }
 1859: 
 1860: sub quota_admin {
 1861:     my ($setquota,$changeHash) = @_;
 1862:     my $quotachanged;
 1863:     if (&Apache::lonnet::allowed('mpq',$env{'form.ccdomain'})) {
 1864:         # Current user has quota modification privileges
 1865:         $quotachanged = 1;
 1866:         $changeHash->{'portfolioquota'} = $setquota;
 1867:     }
 1868:     return $quotachanged;
 1869: }
 1870: 
 1871: sub build_roles {
 1872:     my ($sectionstr,$sections,$role) = @_;
 1873:     my $num_sections = 0;
 1874:     if ($sectionstr=~ /,/) {
 1875:         my @secnums = split/,/,$sectionstr;
 1876:         if ($role eq 'st') {
 1877:             $secnums[0] =~ s/\W//g;
 1878:             $$sections{$secnums[0]} = 1;
 1879:             $num_sections = 1;
 1880:         } else {
 1881:             foreach my $sec (@secnums) {
 1882:                 $sec =~ ~s/\W//g;
 1883:                 if (!($sec eq "")) {
 1884:                     if (exists($$sections{$sec})) {
 1885:                         $$sections{$sec} ++;
 1886:                     } else {
 1887:                         $$sections{$sec} = 1;
 1888:                         $num_sections ++;
 1889:                     }
 1890:                 }
 1891:             }
 1892:         }
 1893:     } else {
 1894:         $sectionstr=~s/\W//g;
 1895:         unless ($sectionstr eq '') {
 1896:             $$sections{$sectionstr} = 1;
 1897:             $num_sections ++;
 1898:         }
 1899:     }
 1900: 
 1901:     return $num_sections;
 1902: }
 1903: 
 1904: # ========================================================== Custom Role Editor
 1905: 
 1906: sub custom_role_editor {
 1907:     my ($r) = @_;
 1908:     my $rolename=$env{'form.rolename'};
 1909: 
 1910:     if ($rolename eq 'make new role') {
 1911: 	$rolename=$env{'form.newrolename'};
 1912:     }
 1913: 
 1914:     $rolename=~s/[^A-Za-z0-9]//gs;
 1915: 
 1916:     if (!$rolename) {
 1917: 	&print_username_entry_form($r);
 1918:         return;
 1919:     }
 1920: # ------------------------------------------------------- What can be assigned?
 1921:     my %full=();
 1922:     my %courselevel=();
 1923:     my %courselevelcurrent=();
 1924:     my $syspriv='';
 1925:     my $dompriv='';
 1926:     my $coursepriv='';
 1927:     my $body_top;
 1928:     my ($disp_dummy,$disp_roles) = &Apache::lonnet::get('roles',["st"]);
 1929:     my ($rdummy,$roledef)=
 1930: 			 &Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 1931: # ------------------------------------------------------- Does this role exist?
 1932:     $body_top .= '<h2>';
 1933:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 1934: 	$body_top .= &mt('Existing Role').' "';
 1935: # ------------------------------------------------- Get current role privileges
 1936: 	($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 1937:     } else {
 1938: 	$body_top .= &mt('New Role').' "';
 1939: 	$roledef='';
 1940:     }
 1941:     $body_top .= $rolename.'"</h2>';
 1942:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 1943: 	my ($priv,$restrict)=split(/\&/,$item);
 1944:         if (!$restrict) { $restrict='F'; }
 1945:         $courselevel{$priv}=$restrict;
 1946:         if ($coursepriv=~/\:$priv/) {
 1947: 	    $courselevelcurrent{$priv}=1;
 1948: 	}
 1949: 	$full{$priv}=1;
 1950:     }
 1951:     my %domainlevel=();
 1952:     my %domainlevelcurrent=();
 1953:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:d'})) {
 1954: 	my ($priv,$restrict)=split(/\&/,$item);
 1955:         if (!$restrict) { $restrict='F'; }
 1956:         $domainlevel{$priv}=$restrict;
 1957:         if ($dompriv=~/\:$priv/) {
 1958: 	    $domainlevelcurrent{$priv}=1;
 1959: 	}
 1960: 	$full{$priv}=1;
 1961:     }
 1962:     my %systemlevel=();
 1963:     my %systemlevelcurrent=();
 1964:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:s'})) {
 1965: 	my ($priv,$restrict)=split(/\&/,$item);
 1966:         if (!$restrict) { $restrict='F'; }
 1967:         $systemlevel{$priv}=$restrict;
 1968:         if ($syspriv=~/\:$priv/) {
 1969: 	    $systemlevelcurrent{$priv}=1;
 1970: 	}
 1971: 	$full{$priv}=1;
 1972:     }
 1973:     my ($jsback,$elements) = &crumb_utilities();
 1974:     my $button_code = "\n";
 1975:     my $head_script = "\n";
 1976:     $head_script .= '<script type="text/javascript">'."\n";
 1977:     my @template_roles = ("cc","in","ta","ep","st");
 1978:     foreach my $role (@template_roles) {
 1979:         $head_script .= &make_script_template($role);
 1980:         $button_code .= &make_button_code($role);
 1981:     }
 1982:     $head_script .= "\n".$jsback."\n".'</script>'."\n";
 1983:     $r->print(&Apache::loncommon::start_page('Custom Role Editor',$head_script));
 1984:    &Apache::lonhtmlcommon::add_breadcrumb
 1985:      ({href=>"javascript:backPage(document.form1,'','')",
 1986:        text=>"User/custom role search",
 1987:        faq=>282,bug=>'Instructor Interface',},
 1988:       {href=>"javascript:backPage(document.form1,'','')",
 1989:          text=>"Edit custom role",
 1990:          faq=>282,bug=>'Instructor Interface',});
 1991:     $r->print(&Apache::lonhtmlcommon::breadcrumbs('User Management'));
 1992: 
 1993:     $r->print($body_top);
 1994:     my %lt=&Apache::lonlocal::texthash(
 1995: 		    'prv'  => "Privilege",
 1996: 		    'crl'  => "Course Level",
 1997:                     'dml'  => "Domain Level",
 1998:                     'ssl'  => "System Level");
 1999:     $r->print('Select a Template<br />');
 2000:     $r->print('<form action="">');
 2001:     $r->print($button_code);
 2002:     $r->print('</form>');
 2003:     $r->print(<<ENDCCF);
 2004: <form name="form1" method="post">
 2005: <input type="hidden" name="phase" value="set_custom_roles" />
 2006: <input type="hidden" name="rolename" value="$rolename" />
 2007: ENDCCF
 2008:     $r->print(&Apache::loncommon::start_data_table().
 2009:               &Apache::loncommon::start_data_table_header_row(). 
 2010: '<th>'.$lt{'prv'}.'</th><th>'.$lt{'crl'}.'</th><th>'.$lt{'dml'}.
 2011: '</th><th>'.$lt{'ssl'}.'</th>'.
 2012:               &Apache::loncommon::end_data_table_header_row());
 2013:     foreach my $priv (sort keys %full) {
 2014:         my $privtext = &Apache::lonnet::plaintext($priv);
 2015:         $r->print(&Apache::loncommon::start_data_table_row().
 2016: 	          '<td>'.$privtext.'</td><td>'.
 2017:     ($courselevel{$priv}?'<input type="checkbox" name="'.$priv.'_c" '.
 2018:     ($courselevelcurrent{$priv}?'checked="1"':'').' />':'&nbsp;').
 2019:     '</td><td>'.
 2020:     ($domainlevel{$priv}?'<input type="checkbox" name="'.$priv.'_d" '.
 2021:     ($domainlevelcurrent{$priv}?'checked="1"':'').' />':'&nbsp;').
 2022:     '</td><td>'.
 2023:     ($systemlevel{$priv}?'<input type="checkbox" name="'.$priv.'_s" '.
 2024:     ($systemlevelcurrent{$priv}?'checked="1"':'').' />':'&nbsp;').
 2025:     '</td>'.
 2026:              &Apache::loncommon::end_data_table_row());
 2027:     }
 2028:     $r->print(&Apache::loncommon::end_data_table().
 2029:    '<input type="hidden" name="startrolename" value="'.$env{'form.rolename'}.
 2030:    '" />'."\n".'<input type="hidden" name="state" value="" />'."\n".   
 2031:    '<input type="reset" value="'.&mt("Reset").'" />'."\n".
 2032:    '<input type="submit" value="'.&mt('Define Role').'" /></form>'.
 2033: 	      &Apache::loncommon::end_page());
 2034: }
 2035: # --------------------------------------------------------
 2036: sub make_script_template {
 2037:     my ($role) = @_;
 2038:     my %full_c=();
 2039:     my %full_d=();
 2040:     my %full_s=();
 2041:     my $return_script;
 2042:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 2043:         my ($priv,$restrict)=split(/\&/,$item);
 2044:         $full_c{$priv}=1;
 2045:     }
 2046:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:d'})) {
 2047:         my ($priv,$restrict)=split(/\&/,$item);
 2048:         $full_d{$priv}=1;
 2049:     }
 2050:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:s'})) {
 2051:         my ($priv,$restrict)=split(/\&/,$item);
 2052:         $full_s{$priv}=1;
 2053:     }
 2054:     $return_script .= 'function set_'.$role.'() {'."\n";
 2055:     my @temp = split(/:/,$Apache::lonnet::pr{$role.':c'});
 2056:     my %role_c;
 2057:     foreach my $priv (@temp) {
 2058:         my ($priv_item, $dummy) = split(/\&/,$priv);
 2059:         $role_c{$priv_item} = 1;
 2060:     }
 2061:     foreach my $priv_item (keys(%full_c)) {
 2062:         my ($priv, $dummy) = split(/\&/,$priv_item);
 2063:         if (exists($role_c{$priv})) {
 2064:             $return_script .= "document.form1.$priv"."_c.checked = true;\n";
 2065:         } else {
 2066:             $return_script .= "document.form1.$priv"."_c.checked = false;\n";
 2067:         }
 2068:     }
 2069:     my %role_d;
 2070:     @temp = split(/:/,$Apache::lonnet::pr{$role.':d'});
 2071:     foreach my $priv(@temp) {
 2072:         my ($priv_item, $dummy) = split(/\&/,$priv);
 2073:         $role_d{$priv_item} = 1;
 2074:     }
 2075:     foreach my $priv_item (keys(%full_d)) {
 2076:         my ($priv, $dummy) = split(/\&/,$priv_item);
 2077:         if (exists($role_d{$priv})) {
 2078:             $return_script .= "document.form1.$priv"."_d.checked = true;\n";
 2079:         } else {
 2080:             $return_script .= "document.form1.$priv"."_d.checked = false;\n";
 2081:         }
 2082:     }
 2083:     my %role_s;
 2084:     @temp = split(/:/,$Apache::lonnet::pr{$role.':s'});
 2085:     foreach my $priv(@temp) {
 2086:         my ($priv_item, $dummy) = split(/\&/,$priv);
 2087:         $role_s{$priv_item} = 1;
 2088:     }
 2089:     foreach my $priv_item (keys(%full_s)) {
 2090:         my ($priv, $dummy) = split(/\&/,$priv_item);
 2091:         if (exists($role_s{$priv})) {
 2092:             $return_script .= "document.form1.$priv"."_s.checked = true;\n";
 2093:         } else {
 2094:             $return_script .= "document.form1.$priv"."_s.checked = false;\n";
 2095:         }
 2096:     }
 2097:     $return_script .= '}'."\n";
 2098:     return ($return_script);
 2099: }
 2100: # ----------------------------------------------------------
 2101: sub make_button_code {
 2102:     my ($role) = @_;
 2103:     my $label = &Apache::lonnet::plaintext($role);
 2104:     my $button_code = '<input type="button" onClick="set_'.$role.'()" value="'.$label.'" />';    
 2105:     return ($button_code);
 2106: }
 2107: # ---------------------------------------------------------- Call to definerole
 2108: sub set_custom_role {
 2109:     my ($r) = @_;
 2110: 
 2111:     my $rolename=$env{'form.rolename'};
 2112: 
 2113:     $rolename=~s/[^A-Za-z0-9]//gs;
 2114: 
 2115:     if (!$rolename) {
 2116: 	&print_username_entry_form($r);
 2117:         return;
 2118:     }
 2119: 
 2120:     my ($jsback,$elements) = &crumb_utilities();
 2121:     my $jscript = '<script type="text/javascript">'.$jsback."\n".'</script>';
 2122: 
 2123:     $r->print(&Apache::loncommon::start_page('Save Custom Role'),$jscript);
 2124:     &Apache::lonhtmlcommon::add_breadcrumb
 2125:         ({href=>"javascript:backPage(document.customresult,'','')",
 2126:           text=>"User/custom role search",
 2127:           faq=>282,bug=>'Instructor Interface',},
 2128:          {href=>"javascript:backPage(document.customresult,'selected_custom_edit','')",
 2129:           text=>"Edit custom role",
 2130:           faq=>282,bug=>'Instructor Interface',},
 2131:          {href=>"javascript:backPage(document.customresult,'set_custom_roles','')",
 2132:           text=>"Result",
 2133:           faq=>282,bug=>'Instructor Interface',});
 2134:     $r->print(&Apache::lonhtmlcommon::breadcrumbs('User Management'));
 2135: 
 2136:     my ($rdummy,$roledef)=
 2137: 	&Apache::lonnet::get('roles',["rolesdef_$rolename"]);
 2138: 
 2139: # ------------------------------------------------------- Does this role exist?
 2140:     $r->print('<h2>');
 2141:     if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 2142: 	$r->print(&mt('Existing Role').' "');
 2143:     } else {
 2144: 	$r->print(&mt('New Role').' "');
 2145: 	$roledef='';
 2146:     }
 2147:     $r->print($rolename.'"</h2>');
 2148: # ------------------------------------------------------- What can be assigned?
 2149:     my $sysrole='';
 2150:     my $domrole='';
 2151:     my $courole='';
 2152: 
 2153:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 2154: 	my ($priv,$restrict)=split(/\&/,$item);
 2155:         if (!$restrict) { $restrict=''; }
 2156:         if ($env{'form.'.$priv.'_c'}) {
 2157: 	    $courole.=':'.$item;
 2158: 	}
 2159:     }
 2160: 
 2161:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:d'})) {
 2162: 	my ($priv,$restrict)=split(/\&/,$item);
 2163:         if (!$restrict) { $restrict=''; }
 2164:         if ($env{'form.'.$priv.'_d'}) {
 2165: 	    $domrole.=':'.$item;
 2166: 	}
 2167:     }
 2168: 
 2169:     foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:s'})) {
 2170: 	my ($priv,$restrict)=split(/\&/,$item);
 2171:         if (!$restrict) { $restrict=''; }
 2172:         if ($env{'form.'.$priv.'_s'}) {
 2173: 	    $sysrole.=':'.$item;
 2174: 	}
 2175:     }
 2176:     $r->print('<br />Defining Role: '.
 2177: 	   &Apache::lonnet::definerole($rolename,$sysrole,$domrole,$courole));
 2178:     if ($env{'request.course.id'}) {
 2179:         my $url='/'.$env{'request.course.id'};
 2180:         $url=~s/\_/\//g;
 2181: 	$r->print('<br />'.&mt('Assigning Role to Self').': '.
 2182: 	      &Apache::lonnet::assigncustomrole($env{'user.domain'},
 2183: 						$env{'user.name'},
 2184: 						$url,
 2185: 						$env{'user.domain'},
 2186: 						$env{'user.name'},
 2187: 						$rolename));
 2188:     }
 2189:     $r->print('<p><a href="/adm/createuser">Create another role, or Create/Modify a user.</a></p><form name="customresult" method="post">');
 2190:     $r->print(&Apache::lonhtmlcommon::echo_form_input([]).'</form>');
 2191:     $r->print(&Apache::loncommon::end_page());
 2192: }
 2193: 
 2194: # ================================================================ Main Handler
 2195: sub handler {
 2196:     my $r = shift;
 2197: 
 2198:     if ($r->header_only) {
 2199:        &Apache::loncommon::content_type($r,'text/html');
 2200:        $r->send_http_header;
 2201:        return OK;
 2202:     }
 2203: 
 2204:     if ((&Apache::lonnet::allowed('cta',$env{'request.course.id'})) ||
 2205:         (&Apache::lonnet::allowed('cin',$env{'request.course.id'})) || 
 2206:         (&Apache::lonnet::allowed('ccr',$env{'request.course.id'})) || 
 2207:         (&Apache::lonnet::allowed('cep',$env{'request.course.id'})) ||
 2208: 	(&authorpriv($env{'user.name'},$env{'request.role.domain'})) ||
 2209:         (&Apache::lonnet::allowed('mau',$env{'request.role.domain'}))) {
 2210:        &Apache::loncommon::content_type($r,'text/html');
 2211:        $r->send_http_header;
 2212:        &Apache::lonhtmlcommon::clear_breadcrumbs();
 2213:       
 2214:        my $phase = $env{'form.phase'};
 2215:        my @search = ('srchterm','srchby','srchin','srchtype','srchdomain');
 2216: 
 2217:        if (($phase eq 'get_user_info') || ($phase eq 'userpicked')) {
 2218:            my $srch;
 2219:            foreach my $item (@search) {
 2220:                $srch->{$item} = $env{'form.'.$item};
 2221:            }
 2222:            if ($env{'form.phase'} eq 'get_user_info') {
 2223:                my ($state,$response,$forcenewuser,$results) = 
 2224:                    &user_search_result($srch);
 2225:                if ($state eq 'select') {
 2226:                    &print_user_selection_page($r,$response,$srch,$results);
 2227:                } elsif ($state eq 'modify') {
 2228:                    my ($ccuname,$ccdomain);
 2229:                    if ($srch->{'srchby'} eq 'uname') {
 2230:                        $ccuname = $srch->{'srchterm'};
 2231:                        $ccdomain= $srch->{'srchdomain'};
 2232:                    } else {
 2233:                        my @matchedunames = keys(%{$results});
 2234:                        ($ccuname,$ccdomain) = split(/:/,$matchedunames[0]);
 2235:                    }
 2236:                    $ccuname =&LONCAPA::clean_username($ccuname);
 2237:                    $ccdomain=&LONCAPA::clean_domain($ccdomain);
 2238:                    &print_user_modification_page($r,$ccuname,$ccdomain,$srch,
 2239:                                                  $response);
 2240:                } elsif ($state eq 'query') {
 2241:                    &print_user_query_page($r);
 2242:                } else {
 2243:                    &print_username_entry_form($r,$response,$srch,$forcenewuser);
 2244:                }
 2245:            } elsif ($env{'form.phase'} eq 'userpicked') {
 2246:                my $ccuname = &LONCAPA::clean_username($env{'form.seluname'});
 2247:                my $ccdomain = &LONCAPA::clean_domain($env{'form.seludom'});
 2248:                &print_user_modification_page($r,$ccuname,$ccdomain,$srch);
 2249:            }
 2250:        } elsif ($env{'form.phase'} eq 'update_user_data') {
 2251:            &update_user_data($r);
 2252:        } elsif ($env{'form.phase'} eq 'selected_custom_edit') {
 2253:            &custom_role_editor($r);
 2254:        } elsif ($env{'form.phase'} eq 'set_custom_roles') {
 2255: 	   &set_custom_role($r);
 2256:        } else {
 2257:            &print_username_entry_form($r);
 2258:        }
 2259:    } else {
 2260:       $env{'user.error.msg'}=
 2261:         "/adm/createuser:mau:0:0:Cannot modify user data";
 2262:       return HTTP_NOT_ACCEPTABLE; 
 2263:    }
 2264:    return OK;
 2265: }
 2266: 
 2267: #-------------------------------------------------- functions for &phase_two
 2268: sub user_search_result {
 2269:     my ($srch) = @_;
 2270:     my @alldomains = sort(&Apache::lonnet::all_domains());
 2271:     my %allhomes;
 2272:     my %inst_matches;
 2273:     my %srch_results;
 2274:     my ($response,$state,$forcenewuser);
 2275: 
 2276:     if ($srch->{'srchby'} !~ /^(uname|lastname|lastfirst)$/) { 
 2277:         $response = &mt('Invalid search.');
 2278:     }
 2279:     if ($srch->{'srchin'} !~ /^(crs|dom|alc|instd)$/) {
 2280:         $response = &mt('Invalid search.');
 2281:     }
 2282:     if ($srch->{'srchtype'} !~ /^(exact|contains)$/) {
 2283:         $response = &mt('Invalid search.');
 2284:     }
 2285:     if ($srch->{'srchterm'} eq '') {
 2286:         $response = &mt('You must enter a search term.');
 2287:     }
 2288:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'instd')) {
 2289:         if (($srch->{'srchdomain'} eq '') || 
 2290:             (!(grep/^\Q$srch->{'srchdomain'}\E$/,@alldomains))) {
 2291:             $response = &mt('You must specify a valid domain when searching in a domain or institutional directory.')
 2292:         }
 2293:     }
 2294:     if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs') ||
 2295:         ($srch->{'srchin'} eq 'alc')) {
 2296:         if ($srch->{'srchterm'} !~ /^$match_username$/) {
 2297:             $response = &mt('You must specify a valid username. Only the following are allowed: letters numbers - . @');
 2298:         }
 2299:     }
 2300:     if ($srch->{'srchin'} eq 'instd') {
 2301:         my $instd_chk = &directorysrch_check($srch);
 2302:         if ($instd_chk ne 'ok') {
 2303:             $response = $instd_chk;
 2304:         }
 2305:     }
 2306:     if ($response ne '') {
 2307:         return ($state,$response);
 2308:     }
 2309:     if ($srch->{'srchby'} eq 'uname') {
 2310:         if (($srch->{'srchin'} eq 'dom') || ($srch->{'srchin'} eq 'crs')) {
 2311:             if ($env{'form.forcenew'}) {
 2312:                 if ($srch->{'srchdomain'} ne $env{'request.role.domain'}) {
 2313:                     my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 2314:                     if ($uhome eq 'no_host') {
 2315:                         my $domdesc = &Apache::lonnet::domain($env{'request.role.domain'},'description');
 2316:                         $response = &mt('New users can only be created in the domain to which you current role belongs - [_1].',$env{'request.role.domain'}.' ('.$domdesc.')');
 2317:                     } else {
 2318:                         $state = 'modify';
 2319:                     }
 2320:                 } else {
 2321:                     $state = 'modify';
 2322:                 }
 2323:             } else {
 2324:                 if ($srch->{'srchin'} eq 'dom') {
 2325:                     my $uhome=&Apache::lonnet::homeserver($srch->{'srchterm'},$srch->{'srchdomain'});
 2326:                     if ($uhome eq 'no_host') {
 2327:                         ($state,$response,$forcenewuser) =
 2328:                             &build_search_response($srch,%srch_results);
 2329:                     } else {
 2330:                         $state = 'modify';
 2331:                     }
 2332:                 } else {
 2333:                     my %courseusers = &get_courseusers();
 2334:                     if (exists($courseusers{$srch->{'srchterm'}.':'.$srch->{'srchdomain'}})) {
 2335:                         $state = 'modify';
 2336:                     } else {
 2337:                         ($state,$response,$forcenewuser) =
 2338:                             &build_search_response($srch,%srch_results);
 2339:                     }
 2340:                 }
 2341:             }
 2342:         } elsif ($srch->{'srchin'} eq 'alc') {
 2343:             $state = 'query';
 2344:         } elsif ($srch->{'srchin'} eq 'instd') {
 2345:             %srch_results = &Apache::lonnet::inst_directory_query($srch);
 2346:             ($state,$response,$forcenewuser) = 
 2347:                 &build_search_response($srch,%srch_results); 
 2348:         }
 2349:     } else {
 2350:         if ($srch->{'srchin'} eq 'dom') {
 2351:             %srch_results = &Apache::lonnet::usersearch($srch);
 2352:             ($state,$response,$forcenewuser) = 
 2353:                 &build_search_response($srch,%srch_results); 
 2354:         } elsif ($srch->{'srchin'} eq 'crs') {
 2355:             my %courseusers = &get_courseusers(); 
 2356:             foreach my $user (keys(%courseusers)) {
 2357:                 my ($uname,$udom) = split(/:/,$user);
 2358:                 my %names = &Apache::loncommon::getnames($uname,$udom);
 2359:                 my %emails = &Apache::loncommon::getemails($uname,$udom);
 2360:                 if ($srch->{'srchby'} eq 'lastname') {
 2361:                     if ((($srch->{'srchtype'} eq 'exact') && 
 2362:                          ($names{'lastname'} eq $srch->{'srchterm'})) || 
 2363:                         (($srch->{'srchtype'} eq 'contains') &&
 2364:                          ($names{'lastname'} =~ /\Q$srch->{'srchterm'}\E/i))) {
 2365:                         $srch_results{$user} = {firstname => $names{'firstname'},
 2366:                                             lastname => $names{'lastname'},
 2367:                                             permanentemail => $emails{'permanentemail'},
 2368:                                            };
 2369:                     }
 2370:                 } elsif ($srch->{'srchby'} eq 'lastfirst') {
 2371:                     my ($srchlast,$srchfirst) = split(/,/,$srch->{'srchterm'});
 2372:                     if ($srch->{'srchtype'} eq 'exact') {
 2373:                         if (($names{'lastname'} eq $srchlast) &&
 2374:                             ($names{'firstname'} eq $srchfirst)) {
 2375:                             $srch_results{$user} = {firstname => $names{'firstname'},
 2376:                                                 lastname => $names{'lastname'},
 2377:                                                 permanentemail => $emails{'permanentemail'},
 2378: 
 2379:                                            };
 2380:                         }
 2381:                     } elsif ($srch->{'srchtype'} eq 'contains') {
 2382:                         if (($names{'lastname'} =~ /\Q$srchlast\E/i) && 
 2383:                             ($names{'firstname'} =~ /\Q$srchfirst\E/i)) {
 2384:                             $srch_results{$user} = {firstname => $names{'firstname'},
 2385:                                                 lastname => $names{'lastname'},
 2386:                                                 permanentemail => $emails{'permanentemail'},
 2387:                                                };
 2388:                         }
 2389:                     }
 2390:                 }
 2391:             }
 2392:             ($state,$response,$forcenewuser) = 
 2393:                 &build_search_response($srch,%srch_results); 
 2394:         } elsif ($srch->{'srchin'} eq 'alc') {
 2395:             $state = 'query';
 2396:         } elsif ($srch->{'srchin'} eq 'instd') {
 2397:             %srch_results = &Apache::lonnet::inst_directory_query($srch); 
 2398:             ($state,$response,$forcenewuser) = 
 2399:                 &build_search_response($srch,%srch_results);
 2400:         }
 2401:     }
 2402:     return ($state,$response,$forcenewuser,\%srch_results);
 2403: }
 2404: 
 2405: sub directorysrch_check {
 2406:     my ($srch) = @_;
 2407:     my $can_search = 0;
 2408:     my $response;
 2409:     my %dom_inst_srch = &Apache::lonnet::get_dom('configuration',
 2410:                                              ['directorysrch'],$srch->{'srchdomain'});
 2411:     if (ref($dom_inst_srch{'directorysrch'}) eq 'HASH') {
 2412:         if (!$dom_inst_srch{'directorysrch'}{'available'}) {
 2413:             return &mt('Directory search unavailable in domain: [_1]',$srch->{'srchdomain'}); 
 2414:         }
 2415:         if ($dom_inst_srch{'directorysrch'}{'localonly'}) {
 2416:             if ($env{'request.role.domain'} ne $srch->{'srchdomain'}) {
 2417:                 return &mt('Directory search in domain: [_1] is only allowed for users with a current role in the domain.',$srch->{'srchdomain'}); 
 2418:             }
 2419:             my @usertypes = split(/:/,$env{'environment.inststatus'});
 2420:             if (!@usertypes) {
 2421:                 push(@usertypes,'default');
 2422:             }
 2423:             if (ref($dom_inst_srch{'directorysrch'}{'cansearch'}) eq 'ARRAY') {
 2424:                 foreach my $type (@usertypes) {
 2425:                     if (grep(/^\Q$type\E$/,@{$dom_inst_srch{'directorysrch'}{'cansearch'}})) {
 2426:                         $can_search = 1;
 2427:                         last;
 2428:                     }
 2429:                 }
 2430:             }
 2431:             if (!$can_search) {
 2432:                 my ($insttypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($srch->{'srchdomain'});
 2433:                 my @longtypes; 
 2434:                 foreach my $item (@usertypes) {
 2435:                     push (@longtypes,$insttypes->{$item});
 2436:                 }
 2437:                 my $insttype_str = join(', ',@longtypes); 
 2438:                 return &mt('Directory search in domain: [_1] is unavailable to your user type: ',$srch->{'srchdomain'}).$insttype_str;
 2439:             } 
 2440:         } else {
 2441:             $can_search = 1;
 2442:         }
 2443:     } else {
 2444:         return &mt('Directory search has not been configured for domain: [_1]',$srch->{'srchdomain'});
 2445:     }
 2446:     my %longtext = &Apache::lonlocal::texthash (
 2447:                        uname => 'username',
 2448:                        lastfirst => 'last name, first name',
 2449:                        lastname => 'last name',
 2450:                        contains => 'is contained in',
 2451:                        exact => 'as exact match to'
 2452:                    );
 2453:     if ($can_search) {
 2454:         if (ref($dom_inst_srch{'directorysrch'}{'searchby'}) eq 'ARRAY') {
 2455:             if (!grep(/^\Q$srch->{'srchby'}\E$/,@{$dom_inst_srch{'directorysrch'}{'searchby'}})) {
 2456:                 return &mt('Directory search in domain: [_1] is not available for searching by [_2]',$srch->{'srchdomain'},$longtext{$srch->{'srchby'}});
 2457:             }
 2458:         } else {
 2459:             return &mt('Directory search in domain: [_1] is not available.', $srch->{'srchdomain'});
 2460:         }
 2461:     }
 2462:     if ($can_search) {
 2463:         if (($dom_inst_srch{'directorysrch'}{'searchtypes'} eq 'specify') ||
 2464:             ($dom_inst_srch{'directorysrch'}{'searchtypes'} eq $srch->{'srchtype'})) {
 2465:             return 'ok';
 2466:         } else {    
 2467:             return &mt('Directory search in domain [_1] is not available for the requested search type: [_2]',$srch->{'srchdomain'},$longtext{$srch->{'srchtype'}});
 2468:         }
 2469:     }
 2470: }
 2471: 
 2472: 
 2473: sub get_courseusers {
 2474:     my %advhash;
 2475:     my %coursepersonnel=&Apache::lonnet::get_course_adv_roles();
 2476:     foreach my $role (sort(keys(%coursepersonnel))) {
 2477:         foreach my $user (split(/\,/,$coursepersonnel{$role})) {
 2478:             $advhash{$user} = '';
 2479:         }
 2480:     }
 2481:     my $classlist = &Apache::loncoursedata::get_classlist();
 2482:     my %combined = (%advhash, %{$classlist});
 2483:     return %combined;
 2484: }
 2485: 
 2486: sub build_search_response {
 2487:     my ($srch,%srch_results) = @_;
 2488:     my ($state,$response,$forcenewuser);
 2489:     my %names = (
 2490:           'uname' => 'username',
 2491:           'lastname' => 'last name',
 2492:           'lastfirst' => 'last name, first name',
 2493:           'crs' => 'this course',
 2494:           'dom' => 'this domain',
 2495:           'instd' => "your institution's directory",
 2496:     );
 2497: 
 2498:     my %single = (
 2499:                    contains => 'A match',
 2500:                    exact => 'An exact match',
 2501:                  );
 2502:     my %nomatch = (
 2503:                    contains => 'No match',
 2504:                    exact => 'No exact match',
 2505:                   );
 2506:     if (keys(%srch_results) > 1) {
 2507:         $state = 'select';
 2508:     } else {
 2509:         if (keys(%srch_results) == 1) {
 2510:             $state = 'modify';
 2511:             $response = &mt("$single{$srch->{'srchtype'}} was found for this $names{$srch->{'srchby'}} ([_1]) in $names{$srch->{'srchin'}}.",$srch->{'srchterm'});
 2512:         } else {
 2513:             $response = &mt("$nomatch{$srch->{'srchtype'}} found for this $names{$srch->{'srchby'}} ([_1]) in $names{$srch->{'srchin'}}.",$srch->{'srchterm'});
 2514:             if ($srch->{'srchin'} ne 'alc') {
 2515:                 $forcenewuser = 1;
 2516:                 my $cansrchinst = 0; 
 2517:                 if ($srch->{'srchdomain'}) {
 2518:                     my %domconfig = &Apache::lonnet::get_dom('configuration',['directorysrch'],$srch->{'srchdomain'});
 2519:                     if (ref($domconfig{'directorysrch'}) eq 'HASH') {
 2520:                         if ($domconfig{'directorysrch'}{'available'}) {
 2521:                             $cansrchinst = 1;
 2522:                         } 
 2523:                     }
 2524:                 }
 2525:                 if (($srch->{'srchby'} eq 'lastfirst') || 
 2526:                     ($srch->{'srchby'} eq 'lastname')) {
 2527:                     if ($srch->{'srchin'} eq 'crs') {
 2528:                         $response .= '<br />'.&mt('You may want to broaden your search to the whole domain.'); 
 2529:                     } elsif ($srch->{'srchin'} eq 'dom') {
 2530:                         if ($cansrchinst) {
 2531:                             $response .= '<br />'.&mt('You may want to broaden your search to a search of the institutional directory for this domain.');
 2532:                         }
 2533:                     }
 2534:                 }
 2535:                 $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 />';
 2536:             }
 2537:         }
 2538:     }
 2539:     return ($state,$response,$forcenewuser);
 2540: }
 2541: 
 2542: sub crumb_utilities {
 2543:     my %elements = (
 2544:        crtuser => {
 2545:            srchterm => 'text',
 2546:            srchin => 'selectbox',
 2547:            srchby => 'selectbox',
 2548:            srchtype => 'selectbox',
 2549:            srchdomain => 'selectbox',
 2550:        },
 2551:        docustom => {
 2552:            rolename => 'selectbox',
 2553:            newrolename => 'textbox',
 2554:        },
 2555:     );
 2556: 
 2557:     my $jsback .= qq|
 2558: function backPage(formname,prevphase,prevstate) {
 2559:     formname.phase.value = prevphase;
 2560:     formname.state.value = prevstate;
 2561:     formname.submit();
 2562: }
 2563: |;
 2564:     return ($jsback,\%elements);
 2565: }
 2566: 
 2567: sub course_level_table {
 2568:     my (%inccourses) = @_;
 2569:     my $table = '';
 2570: # Custom Roles?
 2571: 
 2572:     my %customroles=&my_custom_roles();
 2573:     my %lt=&Apache::lonlocal::texthash(
 2574:             'exs'  => "Existing sections",
 2575:             'new'  => "Define new section",
 2576:             'ssd'  => "Set Start Date",
 2577:             'sed'  => "Set End Date",
 2578:             'crl'  => "Course Level",
 2579:             'act'  => "Activate",
 2580:             'rol'  => "Role",
 2581:             'ext'  => "Extent",
 2582:             'grs'  => "Section",
 2583:             'sta'  => "Start",
 2584:             'end'  => "End"
 2585:     );
 2586: 
 2587:     foreach my $protectedcourse (sort( keys(%inccourses))) {
 2588: 	my $thiscourse=$protectedcourse;
 2589: 	$thiscourse=~s:_:/:g;
 2590: 	my %coursedata=&Apache::lonnet::coursedescription($thiscourse);
 2591: 	my $area=$coursedata{'description'};
 2592:         my $type=$coursedata{'type'};
 2593: 	if (!defined($area)) { $area=&mt('Unavailable course').': '.$protectedcourse; }
 2594: 	my ($domain,$cnum)=split(/\//,$thiscourse);
 2595:         my %sections_count;
 2596:         if (defined($env{'request.course.id'})) {
 2597:             if ($env{'request.course.id'} eq $domain.'_'.$cnum) {
 2598:                 %sections_count = 
 2599: 		    &Apache::loncommon::get_sections($domain,$cnum);
 2600:             }
 2601:         }
 2602: 	foreach my $role ('st','ta','ep','in','cc') {
 2603: 	    if (&Apache::lonnet::allowed('c'.$role,$thiscourse)) {
 2604: 		my $plrole=&Apache::lonnet::plaintext($role);
 2605: 		$table .= &Apache::loncommon::start_data_table_row().
 2606: '<td><input type="checkbox" name="act_'.$protectedcourse.'_'.$role.'" /></td>
 2607: <td>'.$plrole.'</td>
 2608: <td>'.$area.'<br />Domain: '.$domain.'</td>'."\n";
 2609: 	        if ($role ne 'cc') {
 2610:                     if (%sections_count) {
 2611:                         my $currsec = &course_sections(\%sections_count,$protectedcourse.'_'.$role);
 2612:                         $table .= 
 2613:                     '<td><table class="LC_createuser">'.
 2614:                      '<tr class="LC_section_row">
 2615:                         <td valign="top">'.$lt{'exs'}.'<br />'.
 2616:                         $currsec.'</td>'.
 2617:                      '<td>&nbsp;&nbsp;</td>'.
 2618:                      '<td valign="top">&nbsp;'.$lt{'new'}.'<br />'.
 2619:                      '<input type="text" name="newsec_'.$protectedcourse.'_'.$role.'" value="" />'.
 2620:                      '<input type="hidden" '.
 2621:                      'name="sec_'.$protectedcourse.'_'.$role.'" /></td>'.
 2622:                      '</tr></table></td>';
 2623:                     } else {
 2624:                         $table .= '<td><input type="text" size="10" '.
 2625:                      'name="sec_'.$protectedcourse.'_'.$role.'" /></td>';
 2626:                     }
 2627:                 } else { 
 2628: 		    $table .= '<td>&nbsp</td>';
 2629:                 }
 2630: 		$table .= <<ENDTIMEENTRY;
 2631: <td><input type=hidden name="start_$protectedcourse\_$role" value='' />
 2632: <a href=
 2633: "javascript:pjump('date_start','Start Date $plrole',document.cu.start_$protectedcourse\_$role.value,'start_$protectedcourse\_$role','cu.pres','dateset')">$lt{'ssd'}</a></td>
 2634: <td><input type=hidden name="end_$protectedcourse\_$role" value='' />
 2635: <a href=
 2636: "javascript:pjump('date_end','End Date $plrole',document.cu.end_$protectedcourse\_$role.value,'end_$protectedcourse\_$role','cu.pres','dateset')">$lt{'sed'}</a></td>
 2637: ENDTIMEENTRY
 2638:                 $table.= &Apache::loncommon::end_data_table_row();
 2639:             }
 2640:         }
 2641:         foreach my $cust (sort keys %customroles) {
 2642: 	    if (&Apache::lonnet::allowed('ccr',$thiscourse)) {
 2643: 		my $plrole=$cust;
 2644:                 my $customrole=$protectedcourse.'_cr_cr_'.$env{'user.domain'}.
 2645: 		    '_'.$env{'user.name'}.'_'.$plrole;
 2646: 		$table .= &Apache::loncommon::start_data_table_row().
 2647: '<td><input type="checkbox" name="act_'.$customrole.'" /></td>
 2648: <td>'.$plrole.'</td>
 2649: <td>'.$area.'</td>'."\n";
 2650:                 if (%sections_count) {
 2651:                     my $currsec = &course_sections(\%sections_count,$customrole);
 2652:                     $table.=
 2653:                    '<td><table border="0" cellspacing="0" cellpadding="0">'.
 2654:                    '<tr><td valign="top">'.$lt{'exs'}.'<br />'.
 2655:                      $currsec.'</td>'.
 2656:                    '<td>&nbsp;&nbsp;</td>'.
 2657:                    '<td valign="top">&nbsp;'.$lt{'new'}.'<br />'.
 2658:                    '<input type="text" name="newsec_'.$customrole.'" value="" /></td>'.
 2659:                    '<input type="hidden" '.
 2660:                    'name="sec_'.$customrole.'" /></td>'.
 2661:                    '</tr></table></td>';
 2662:                 } else {
 2663:                     $table .= '<td><input type="text" size="10" '.
 2664:                      'name="sec_'.$customrole.'" /></td>';
 2665:                 }
 2666:                 $table .= <<ENDENTRY;
 2667: <td><input type=hidden name="start_$customrole" value='' />
 2668: <a href=
 2669: "javascript:pjump('date_start','Start Date $plrole',document.cu.start_$customrole.value,'start_$customrole','cu.pres','dateset')">$lt{'ssd'}</a></td>
 2670: <td><input type=hidden name="end_$customrole" value='' />
 2671: <a href=
 2672: "javascript:pjump('date_end','End Date $plrole',document.cu.end_$customrole.value,'end_$customrole','cu.pres','dateset')">$lt{'sed'}</a></td>
 2673: ENDENTRY
 2674:                $table .= &Apache::loncommon::end_data_table_row();
 2675:            }
 2676: 	}
 2677:     }
 2678:     return '' if ($table eq ''); # return nothing if there is nothing 
 2679:                                  # in the table
 2680:     my $result = '
 2681: <h4>'.$lt{'crl'}.'</h4>'.
 2682: &Apache::loncommon::start_data_table().
 2683: &Apache::loncommon::start_data_table_header_row().
 2684: '<th>'.$lt{'act'}.'</th><th>'.$lt{'rol'}.'</th><th>'.$lt{'ext'}.'</th>
 2685: <th>'.$lt{'grs'}.'</th><th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'.
 2686: &Apache::loncommon::end_data_table_header_row().
 2687: $table.
 2688: &Apache::loncommon::end_data_table();
 2689:     return $result;
 2690: }
 2691: 
 2692: sub course_sections {
 2693:     my ($sections_count,$role) = @_;
 2694:     my $output = '';
 2695:     my @sections = (sort {$a <=> $b} keys %{$sections_count});
 2696:     if (scalar(@sections) == 1) {
 2697:         $output = '<select name="currsec_'.$role.'" >'."\n".
 2698:                   '  <option value="">Select</option>'."\n".
 2699:                   '  <option value="">No section</option>'."\n".
 2700:                   '  <option value="'.$sections[0].'" >'.$sections[0].'</option>'."\n";
 2701:     } else {
 2702:         $output = '<select name="currsec_'.$role.'" ';
 2703:         my $multiple = 4;
 2704:         if (scalar(@sections) < 4) { $multiple = scalar(@sections); }
 2705:         $output .= 'multiple="multiple" size="'.$multiple.'">'."\n";
 2706:         foreach my $sec (@sections) {
 2707:             $output .= '<option value="'.$sec.'">'.$sec."</option>\n";
 2708:         }
 2709:     }
 2710:     $output .= '</select>'; 
 2711:     return $output;
 2712: }
 2713: 
 2714: sub course_level_dc {
 2715:     my ($dcdom) = @_;
 2716:     my %customroles=&my_custom_roles();
 2717:     my $hiddenitems = '<input type="hidden" name="dcdomain" value="'.$dcdom.'" />'.
 2718:                       '<input type="hidden" name="origdom" value="'.$dcdom.'" />'.
 2719:                       '<input type="hidden" name="dccourse" value="" />';
 2720:     my $courseform='<b>'.&Apache::loncommon::selectcourse_link
 2721:             ('cu','dccourse','dcdomain','coursedesc',undef,undef,'Course').'</b>';
 2722:     my $cb_jscript = &Apache::loncommon::coursebrowser_javascript($dcdom,'currsec','cu');
 2723:     my %lt=&Apache::lonlocal::texthash(
 2724:                     'rol'  => "Role",
 2725:                     'grs'  => "Section",
 2726:                     'exs'  => "Existing sections",
 2727:                     'new'  => "Define new section", 
 2728:                     'sta'  => "Start",
 2729:                     'end'  => "End",
 2730:                     'ssd'  => "Set Start Date",
 2731:                     'sed'  => "Set End Date"
 2732:                   );
 2733:     my $header = '<h4>'.&mt('Course Level').'</h4>'.
 2734:                  &Apache::loncommon::start_data_table().
 2735:                  &Apache::loncommon::start_data_table_header_row().
 2736:                  '<th>'.$courseform.'</th><th>'.$lt{'rol'}.'</th><th>'.$lt{'grs'}.'</th><th>'.$lt{'sta'}.'</th><th>'.$lt{'end'}.'</th>'.
 2737:                  &Apache::loncommon::end_data_table_header_row();
 2738:     my $otheritems = &Apache::loncommon::start_data_table_row()."\n".
 2739:                      '<td><input type="text" name="coursedesc" value="" onFocus="this.blur();opencrsbrowser('."'cu','dccourse','dcdomain','coursedesc',''".')" /></td>'."\n".
 2740:                      '<td><select name="role">'."\n";
 2741:     foreach  my $role ('st','ta','ep','in','cc') {
 2742:         my $plrole=&Apache::lonnet::plaintext($role);
 2743:         $otheritems .= '  <option value="'.$role.'">'.$plrole;
 2744:     }
 2745:     if ( keys %customroles > 0) {
 2746:         foreach my $cust (sort keys %customroles) {
 2747:             my $custrole='cr_cr_'.$env{'user.domain'}.
 2748:                     '_'.$env{'user.name'}.'_'.$cust;
 2749:             $otheritems .= '  <option value="'.$custrole.'">'.$cust;
 2750:         }
 2751:     }
 2752:     $otheritems .= '</select></td><td>'.
 2753:                      '<table border="0" cellspacing="0" cellpadding="0">'.
 2754:                      '<tr><td valign="top"><b>'.$lt{'exs'}.'</b><br /><select name="currsec">'.
 2755:                      ' <option value=""><--'.&mt('Pick course first').'</select></td>'.
 2756:                      '<td>&nbsp;&nbsp;</td>'.
 2757:                      '<td valign="top">&nbsp;<b>'.$lt{'new'}.'</b><br />'.
 2758:                      '<input type="text" name="newsec" value="" />'.
 2759:                      '<input type="hidden" name="groups" value="" /></td>'.
 2760:                      '</tr></table></td>';
 2761:     $otheritems .= <<ENDTIMEENTRY;
 2762: <td><input type=hidden name="start" value='' />
 2763: <a href=
 2764: "javascript:pjump('date_start','Start Date',document.cu.start.value,'start','cu.pres','dateset')">$lt{'ssd'}</a></td>
 2765: <td><input type=hidden name="end" value='' />
 2766: <a href=
 2767: "javascript:pjump('date_end','End Date',document.cu.end.value,'end','cu.pres','dateset')">$lt{'sed'}</a></td>
 2768: ENDTIMEENTRY
 2769:     $otheritems .= &Apache::loncommon::end_data_table_row().
 2770:                    &Apache::loncommon::end_data_table()."\n";
 2771:     return $cb_jscript.$header.$hiddenitems.$otheritems;
 2772: }
 2773: 
 2774: #---------------------------------------------- end functions for &phase_two
 2775: 
 2776: #--------------------------------- functions for &phase_two and &phase_three
 2777: 
 2778: #--------------------------end of functions for &phase_two and &phase_three
 2779: 
 2780: 1;
 2781: __END__
 2782: 
 2783: 

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