File:  [LON-CAPA] / loncom / interface / loncreateuser.pm
Revision 1.179: download - view: text, annotated - select for diffs
Sun Aug 26 21:09:43 2007 UTC (16 years, 9 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
"Enroll a single student" in Enrollment Manager now uses the same user search interface as "Set Individual User Roles" in Create Users, Change User Privileges.

loncommon.pm
- &user_picker() takes an additional argument ($caller) to indicate the name of the form which will contain the user search - either: document.crtuser for CUSR or document.studentform for ENRL.
- javascript function: validateEntry() now takes an argument - callingForm, which similarly contains the name of the form (document.crtuser or document.studentform.

loncreateuser.pm
- &print_user_selection_page() takes two additional arguments: $context,$srcharray.
  - $context is 'createuser' or 'enrollstudent', depending on caller of form.   - $srcharray is a reference to an array of search items - ('srchterm','srchby','srchin','srchtype','srchdomain').
  - The call to lonhtmlcommon::echo_form_input() in print_user_selection_page() is replaced with printing of form input for elements in @{$srcharray} because of the possibility that this page could be reached coming back from the user modification page.
  - form element: 'state' renamed 'currstate' to avoid collision with 'state' which is already used in ENRL.
  - entry for studentform added to &crumb_utilities() so setFormElements() works for ENRL usage.

londropadd.pm
- &single_user_entry_form() added to display user search in "Enroll a single student" interface.
- user information fields filled in for new username is data available in institutional search.
- breadcrumbs code allows return to intermediate steps in multi-screen single student enrollment.

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

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