File:  [LON-CAPA] / loncom / interface / loncreateuser.pm
Revision 1.162: download - view: text, annotated - select for diffs
Mon Jul 30 00:31:27 2007 UTC (16 years, 10 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- moved a couple of javascript functions  - setSearch() and validateEntry() - from loncreateuser::print_username_entry_form() to loncommon::user_picker() to keep functionality together.

- loncreateuser now performs 'is contained in' type searches by username for domain or course.

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

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