File:  [LON-CAPA] / loncom / interface / loncreateuser.pm
Revision 1.166: download - view: text, annotated - select for diffs
Thu Aug 2 01:02:56 2007 UTC (16 years, 11 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- Felicia suggested wording changes

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

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