File:  [LON-CAPA] / loncom / interface / lonrequestcourse.pm
Revision 1.108: download - view: text, annotated - select for diffs
Wed Feb 12 22:15:40 2020 UTC (4 years, 3 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Remove unwanted whitespace.

    1: # The LearningOnline Network
    2: # Request a course
    3: #
    4: # $Id: lonrequestcourse.pm,v 1.108 2020/02/12 22:15:40 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: =head1 NAME
   31: 
   32: Apache::lonrequestcourse.pm
   33: 
   34: =head1 SYNOPSIS
   35: 
   36: Allows users to request creation of new courses.
   37: 
   38: This is part of the LearningOnline Network with CAPA project
   39: described at http://www.lon-capa.org.
   40: 
   41: =head1 SUBROUTINES
   42: 
   43: =over
   44: 
   45: =item handler()
   46: 
   47: =item get_breadcrumbs()
   48: 
   49: =item header()
   50: 
   51: =item form_elements()
   52: 
   53: =item onload_action()
   54: 
   55: =item print_main_menu()
   56: 
   57: =item request_administration()
   58: 
   59: =item close_popup_form()
   60: 
   61: =item get_instcode()
   62: 
   63: =item print_request_form()
   64: 
   65: =item print_enrollment_menu()
   66: 
   67: =item show_invalid_crosslists()
   68: 
   69: =item inst_section_selector()
   70: 
   71: =item date_setting_table()
   72: 
   73: =item print_personnel_menu()
   74: 
   75: =item print_request_status()
   76: 
   77: =item print_request_logs()
   78: 
   79: =item print_review()
   80: 
   81: =item dates_from_form()
   82: 
   83: =item courseinfo_form()
   84: 
   85: =item clone_form()
   86: 
   87: =item clone_text()
   88: 
   89: =item coursecode_form()
   90: 
   91: =item get_course_dom()
   92: 
   93: =item display_navbuttons()
   94: 
   95: =item print_request_outcome()
   96: 
   97: =item check_autolimit()
   98: 
   99: =item retrieve_settings()
  100: 
  101: =item get_request_settings()
  102: 
  103: =item extract_instcode() 
  104: 
  105: =item generate_date_items()
  106: 
  107: =back
  108: 
  109: =cut
  110: 
  111: package Apache::lonrequestcourse;
  112: 
  113: use strict;
  114: use Apache::Constants qw(:common :http);
  115: use Apache::lonnet;
  116: use Apache::loncommon;
  117: use Apache::lonlocal;
  118: use Apache::loncoursequeueadmin;
  119: use Apache::lonuserutils;
  120: use LONCAPA qw(:DEFAULT :match);
  121: 
  122: my $registered_flush;
  123: my $registered_instcats;
  124: my $modified_dom;
  125: 
  126: sub handler {
  127:     my ($r) = @_;
  128:     &Apache::loncommon::content_type($r,'text/html');
  129:     $r->send_http_header;
  130:     if ($r->header_only) {
  131:         return OK;
  132:     }
  133: 
  134:     $registered_flush = 0;
  135:     $registered_instcats = 0;
  136:     $modified_dom = '';
  137: 
  138:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
  139:         ['action','showdom','cnum','state','crstype','queue','tabs']);
  140:     &Apache::lonhtmlcommon::clear_breadcrumbs();
  141:     my $dom = &get_course_dom();
  142:     my $action = $env{'form.action'};
  143:     my $state = $env{'form.state'};
  144:     my (%states,%stored);
  145:     my ($jscript,$uname,$udom,$result,$warning,$showcredits,$instcredits,%can_request,
  146:         %request_domains,@incdoms);
  147:     my %domdefs = &Apache::lonnet::get_domain_defaults($dom);
  148:     if ($domdefs{'officialcredits'} || $domdefs{'unofficialcredits'} || $domdefs{'textbookcredits'}) {
  149:         $showcredits = 1;
  150:     }
  151: 
  152:     my $canreq =
  153:         &Apache::lonnet::check_can_request($dom,\%can_request,\%request_domains);
  154: 
  155:     foreach my $item (keys(%request_domains)) {
  156:         if (ref($request_domains{$item}) eq 'ARRAY') {
  157:             foreach my $possdom (@{$request_domains{$item}}) {
  158:                 unless(grep(/^\Q$possdom\E$/,@incdoms)) {
  159:                     push(@incdoms,$possdom);
  160:                 }
  161:             }
  162:         }
  163:     }
  164: 
  165:     if ($canreq) {
  166:         if (($env{'form.crstype'} eq 'lti') && ($env{'request.lti.login'}) &&
  167:             ($env{'form.lti.reqrole'} eq 'cc') && ($env{'form.lti.reqcrs'}) &&
  168:             ($env{'form.lti.sourcecrs'} ne '')) {
  169:             if ($action eq 'process') {
  170:                 if ($can_request{'lti'}) {
  171:                     my %domconfig = &Apache::lonnet::get_dom('configuration',['requestcourses'],$dom);
  172:                     &process_textbook_request($r,$dom,$action,\%domdefs,\%domconfig,\%can_request,'lti');
  173:                 } else {
  174:                     $r->print(&header('Course Request','','','',{ 'only_body' => 1}).
  175:                               '<div>'.
  176:                               '<p class="LC_info">'.&mt('You do not have privileges to request creation of LTI courses.').'</p>'.
  177:                               '</div>'.
  178:                               &Apache::loncommon::end_page());
  179:                 }
  180:             }
  181:             return OK;
  182:         }
  183:         if (($env{'form.crstype'} eq 'textbook') || 
  184:             (scalar(keys(%can_request)) == 1) && ($can_request{'textbook'})) {
  185:             my %domconfig = &Apache::lonnet::get_dom('configuration',['requestcourses'],$dom);
  186:             if ($action eq 'log') {
  187:                 my $usetabs;
  188:                 if ((scalar(keys(%can_request)) == 1) && ($can_request{'textbook'})) {
  189:                     $usetabs = 1;
  190:                 } elsif ($env{'form.tabs'} eq 'on') {
  191:                     $usetabs = 1;
  192:                 }
  193:                 &Apache::lonhtmlcommon::add_breadcrumb({text=>'Course Request'});
  194:                 my $crumb = &Apache::lonhtmlcommon::breadcrumbs('Course Requests','Course_Requests');
  195:                 &print_request_logs($r,$dom,undef,undef,$crumb,$usetabs);
  196:             } elsif ($action eq 'process') {
  197:                 if ($can_request{'textbook'}) {
  198:                     &process_textbook_request($r,$dom,$action,\%domdefs,\%domconfig,\%can_request);
  199:                 } else {
  200:                     &textbook_request_disabled($r,$dom,$action,\%can_request);
  201:                 }
  202:             } elsif ($action eq 'display') {
  203:                my ($uname,$udom,$result,$warning) = &domcoord_display($dom);
  204:                if ($warning ne '') {
  205:                    my $args = { only_body => 1 };
  206:                    $r->print(&header('Course/Community Requests','','' ,'',$args).
  207:                              '<h3>'.&mt('Course/Community Request Details').'</h3>'.
  208:                              '<div class="LC_warning">'.$warning.'</div>'.
  209:                              &close_popup_form());
  210:                 } else {
  211:                     $states{'display'} = ['details'];
  212:                     my $loaditems = &onload_action($action,$state);
  213:                     my $page = 0;
  214:                     &request_administration($r,$action,$state,$page,\%states,$dom,$jscript,
  215:                                             $loaditems,'','','','','',$showcredits,'','',
  216:                                             $uname,$udom);
  217:                 }
  218:             } else {
  219:                 if ($can_request{'textbook'}) {
  220:                     &print_textbook_form($r,$dom,\@incdoms,\%domdefs,$domconfig{'requestcourses'},
  221:                                          \%can_request,'textbook');
  222:                 } else {
  223:                     &textbook_request_disabled($r,$dom,$action,\%can_request);
  224:                 }
  225:             }
  226:             return OK;
  227:         }
  228:     }
  229: 
  230:     $states{'display'} = ['details'];
  231:     $states{'view'} = ['pick_request','details','cancel','removal'];
  232:     $states{'log'} = ['display'];
  233:     $states{'new'} = ['courseinfo','enrollment','personnel','review','process'];
  234: 
  235:     if (($action eq 'new') && ($env{'form.crstype'} eq 'official')) {
  236:         unless ($env{'form.state'} eq 'crstype') {
  237:             unshift(@{$states{'new'}},'codepick');
  238:         }
  239:     }
  240: 
  241:     if (($action eq 'new') && (&Apache::loncoursequeueadmin::author_prompt())) {
  242:         if (ref($states{$action}) eq 'ARRAY') {
  243:             push(@{$states{$action}},'reqauthor');
  244:         }
  245:     }
  246: 
  247:     foreach my $key (keys(%states)) {
  248:         if (ref($states{$key}) eq 'ARRAY') {
  249:             unshift (@{$states{$key}},'crstype');
  250:         }
  251:     }
  252: 
  253:     my @invalidcrosslist;
  254:     my %trail = (
  255:                  crstype       => 'Pick Action',
  256:                  codepick      => 'Category',
  257:                  courseinfo    => 'Description',
  258:                  enrollment    => 'Access Dates',
  259:                  personnel     => 'Personnel',
  260:                  review        => 'Review',
  261:                  process       => 'Result',
  262:                  reqauthor     => 'Authoring Space Result',
  263:                  pick_request  => 'Display Summary',
  264:                  details       => 'Request Details',
  265:                  cancel        => 'Cancel Request',
  266:                  removal       => 'Outcome',
  267:                  display       => 'Request Logs',
  268:                 );
  269: 
  270:     if (($env{'form.crstype'} eq 'official') && (&Apache::lonnet::auto_run('',$dom))) {
  271:         $trail{'enrollment'} = 'Enrollment';
  272:     }
  273: 
  274:     my ($page,$crumb,$newinstcode,$codechk,$checkedcode,$description) =
  275:         &get_breadcrumbs($dom,$action,\$state,\%states,\%trail);
  276:     if ($action eq 'display') {
  277:         ($uname,$udom,$result,$warning) = &domcoord_display($dom);
  278:     } elsif ((defined($state)) && (defined($action))) {
  279:         if (($action eq 'view') && ($state eq 'details')) {
  280:             if ((defined($env{'form.showdom'})) && (defined($env{'form.cnum'}))) {
  281:                 my $result = &retrieve_settings($env{'form.showdom'},$env{'form.cnum'});
  282:             }
  283:         } elsif ($env{'form.crstype'} eq 'official') {
  284:             if (&Apache::lonnet::auto_run('',$dom)) {
  285:                 if (($action eq 'new') && (($state eq 'enrollment') || 
  286:                     ($state eq 'personnel'))) {
  287:                     my $checkcrosslist = 0;
  288:                     for (my $i=0; $i<$env{'form.crosslisttotal'}; $i++) {
  289:                         if ($env{'form.crosslist_'.$i}) {
  290:                             $checkcrosslist ++;
  291:                         }
  292:                     }
  293:                     if ($checkcrosslist) {
  294:                         my %codechk;
  295:                         my (@codetitles,%cat_titles,%cat_order,@code_order,$lastitem);
  296:                         &Apache::lonnet::auto_possible_instcodes($dom,\@codetitles,
  297:                                                                  \%cat_titles,
  298:                                                                  \%cat_order,
  299:                                                                  \@code_order);
  300:                         my $numtitles = scalar(@codetitles);
  301:                         if ($numtitles) {
  302:                             for (my $i=0; $i<$env{'form.crosslisttotal'}; $i++) {
  303:                                 if ($env{'form.crosslist_'.$i}) {
  304:                                     my $codecheck;
  305:                                     my $crosslistcode = '';
  306:                                     foreach my $item (@code_order) {
  307:                                         $crosslistcode .= $env{'form.crosslist_'.$i.'_'.$item}; 
  308:                                     }
  309:                                     if ($crosslistcode ne '') { 
  310:                                          ($codechk{$i}, my $rest) = 
  311:                                             &Apache::lonnet::auto_validate_instcode('',$dom,$crosslistcode);
  312:                                     }
  313:                                     unless ($codechk{$i} eq 'valid') {
  314:                                         $env{'form.crosslist_'.$i} = '';
  315:                                         push(@invalidcrosslist,$crosslistcode);
  316:                                     } 
  317:                                 }
  318:                             }
  319:                         }
  320:                     }
  321:                 }
  322:             }
  323:         }
  324:         (my $elements,$instcredits) = &form_elements($dom,$showcredits);
  325:         my $elementsref = {};
  326:         if ((ref($elements) eq 'HASH') && (ref($elements->{$action}) eq 'HASH')) {
  327:             if (ref($elements->{$action}{$state}) eq 'HASH') {
  328:                 $elementsref = $elements->{$action}{$state};
  329:             }
  330:         }
  331:         if (($state eq 'courseinfo') && ($env{'form.clonedom'} eq '')) {
  332:             $env{'form.clonedom'} = $dom;
  333:         }
  334:         if ($state eq 'crstype') {
  335:             $jscript = &mainmenu_javascript();
  336:         } else {
  337:             $jscript = &Apache::lonhtmlcommon::set_form_elements($elementsref,\%stored);
  338:             if ($state eq 'courseinfo') {
  339:                 $jscript .= &cloning_javascript();
  340:             } elsif ($state eq 'process') {
  341:                 $jscript .= &processing_javascript();
  342:             }
  343:         }
  344:     }
  345: 
  346:     if ($state eq 'personnel') {
  347:         $jscript .= "\n".&Apache::loncommon::userbrowser_javascript();
  348:     }
  349: 
  350:     my $loaditems = &onload_action($action,$state);
  351: 
  352:     if ($action eq 'new') {
  353:         if ($canreq) {
  354:             if ($state eq 'crstype') {
  355:                 &print_main_menu($r,\%can_request,\%states,$dom,$jscript,$loaditems,
  356:                                  $crumb,\@incdoms);
  357:             } else {
  358:                 &request_administration($r,$action,$state,$page,\%states,$dom,
  359:                                         $jscript,$loaditems,$crumb,$newinstcode,
  360:                                         $codechk,$checkedcode,$description,
  361:                                         $showcredits,$instcredits,\@invalidcrosslist);
  362:             }
  363:         } else {
  364:             $r->print(&header('Course/Community Requests').$crumb.
  365:                       '<div class="LC_warning">'.
  366:                       &mt('You do not have privileges to request creation of courses or communities.').
  367:                       '</div>'.&Apache::loncommon::end_page());
  368:         }
  369:     } elsif ($action eq 'view') {
  370:         if ($state eq 'crstype') {
  371:             &print_main_menu($r,\%can_request,\%states,$dom,$jscript,$loaditems,$crumb,\@incdoms);
  372:         } else {
  373:             &request_administration($r,$action,$state,$page,\%states,$dom,$jscript,
  374:                                     $loaditems,$crumb,'','','','',$showcredits);
  375:         }
  376:     } elsif ($action eq 'display') {
  377:         if ($warning ne '') {
  378:             my $args = { only_body => 1 };
  379:             $r->print(&header('Course/Community Requests','','' ,'',$args).$crumb.
  380:                       '<h3>'.&mt('Course/Community Request Details').'</h3>'.
  381:                       '<div class="LC_warning">'.$warning.'</div>'.
  382:                       &close_popup_form());
  383:         } else {
  384:             &request_administration($r,$action,$state,$page,\%states,$dom,$jscript,
  385:                                     $loaditems,$crumb,'','','','',$showcredits,'','',
  386:                                     $uname,$udom);
  387:         }
  388:     } elsif ($action eq 'log') {
  389:         if ($state eq 'crstype') {
  390:             &print_main_menu($r,\%can_request,\%states,$dom,$jscript,'',$crumb,\@incdoms);
  391:         } else {
  392:             $jscript .= <<ENDJS;
  393: 
  394: function backPage(formname,prevstate) {
  395:     formname.state.value = prevstate;
  396:     formname.submit();
  397: }
  398: 
  399: function setPage(formname) {
  400:     formname.page.value = '1';
  401:     return;
  402: }
  403: 
  404: ENDJS
  405:             &print_request_logs($r,$dom,$jscript,$loaditems,$crumb,\%can_request);
  406:         }
  407:     } else {
  408:         &print_main_menu($r,\%can_request,\%states,$dom,$jscript,'',$crumb,\@incdoms);
  409:     }
  410:     return OK;
  411: }
  412: 
  413: sub mainmenu_javascript {
  414:     return <<"END";
  415: function setType(courseForm) {
  416:     for (var i=0; i<courseForm.crstype.length; i++) {
  417:         if (courseForm.crstype.options[i].value == "$env{'form.crstype'}") {
  418:             courseForm.crstype.options[i].selected = true;
  419:         } else {
  420:             courseForm.crstype.options[i].selected = false;
  421:         }
  422:     }
  423: }
  424: 
  425: function setAction(courseForm) {
  426:     for (var i=0; i<courseForm.action.length; i++) {
  427:         if (courseForm.action.options[i].value == "$env{'form.action'}") {
  428:             courseForm.action.options[i].selected = true;
  429:         } else {
  430:             courseForm.action.options[i].selected = false;
  431:         }
  432:     }
  433: }
  434: END
  435: }
  436: 
  437: sub cloning_javascript {
  438:     return <<"END";
  439: function setCloneDisplay(courseForm) {
  440:     if (courseForm.cloning.length > 1) {    
  441:         for (var i=0; i<courseForm.cloning.length; i++) {
  442:             if (courseForm.cloning[i].checked) {
  443:                 if (courseForm.cloning[i].value == 1) {
  444:                     document.getElementById('cloneoptions').style.display="block";
  445:                 }
  446:             }
  447:         }
  448:     }
  449: }
  450: END
  451: }
  452: 
  453: sub processing_javascript {
  454:     return <<"END";
  455: function hideProcessing() {
  456:     if (document.getElementById('processing')) {
  457:         document.getElementById('processing').style.display="none";
  458:     }
  459: }
  460: 
  461: END
  462: }
  463: 
  464: sub get_breadcrumbs {
  465:     my ($dom,$action,$state,$states,$trail) = @_;
  466:     my ($crumb,$newinstcode,$codechk,$checkedcode,$numtitles,$description);
  467:     my $page = 0;
  468:     if ((ref($states) eq 'HASH') && (ref($trail) eq 'HASH') && (ref($state))) {
  469:         if (defined($action)) {
  470:             my $done = 0;
  471:             my $i=0;
  472:             if (ref($states->{$action}) eq 'ARRAY') {
  473:                 while ($i<@{$states->{$action}} && !$done) {
  474:                     if ($states->{$action}[$i] eq $$state) {
  475:                         $page = $i;
  476:                         $done = 1;
  477:                     }
  478:                     $i++;
  479:                 }
  480:             }
  481:             if ($env{'form.crstype'} eq 'official') {
  482:                 if ($page > 1) {
  483:                     if ($states->{$action}[$page-1] eq 'codepick') {
  484:                         if ($env{'form.instcode'} eq '') {
  485:                             ($newinstcode,$numtitles) = &get_instcode($dom);
  486:                             if ($numtitles) {
  487:                                 if ($newinstcode eq '') {
  488:                                     $$state = 'codepick';
  489:                                     $page --;
  490:                                 } else {
  491:                                     ($codechk,$description) = 
  492:                                         &Apache::lonnet::auto_validate_instcode('',
  493:                                             $dom,$newinstcode);
  494:                                     if ($codechk ne 'valid') {
  495:                                         $$state = 'codepick';
  496:                                         $page --;
  497:                                     }
  498:                                     $checkedcode = 1;
  499:                                 }
  500:                             }
  501:                         }
  502:                     }
  503:                 }
  504:             }
  505:             if (ref($states->{$action}) eq 'ARRAY') {
  506:                 for (my $i=0; $i<@{$states->{$action}}; $i++) {
  507:                     if ($$state eq $states->{$action}[$i]) {
  508:                         &Apache::lonhtmlcommon::add_breadcrumb(
  509:                            {text=>"$trail->{$$state}"});
  510:                         $crumb = &Apache::lonhtmlcommon::breadcrumbs('Course/Community Requests','Course_Requests');
  511:                         last;
  512:                     } else {
  513:                         if (($$state eq 'process') || ($$state eq 'removal') || ($$state eq 'reqauthor')) {
  514:                             &Apache::lonhtmlcommon::add_breadcrumb(
  515:                                 { href => '/adm/requestcourse',
  516:                                   text => "$trail->{$states->{$action}[$i]}",
  517:                                 }
  518:                            );
  519:                         } else {
  520:                             &Apache::lonhtmlcommon::add_breadcrumb(
  521:      { href => "javascript:backPage(document.requestcrs,'$states->{$action}[$i]')",
  522:        text => "$trail->{$states->{$action}[$i]}", }
  523:                            );
  524:                         }
  525:                     }
  526:                 }
  527:             }
  528:         } else {
  529:             &Apache::lonhtmlcommon::add_breadcrumb(
  530:                     {text=>'Pick Action'});
  531:             $crumb = &Apache::lonhtmlcommon::breadcrumbs('Course/Community Requests','Course_Requests');
  532:         }
  533:     } else {
  534:         &Apache::lonhtmlcommon::add_breadcrumb(
  535:                 {text=>'Pick Action'});
  536:         $crumb = &Apache::lonhtmlcommon::breadcrumbs('Course/Community Requests','Course_Requests');
  537:     }
  538:     return ($page,$crumb,$newinstcode,$codechk,$checkedcode,$description);
  539: }
  540: 
  541: sub header {
  542:     my ($bodytitle,$jscript,$loaditems,$jsextra,$args) = @_;
  543:     if ($jscript) {
  544:         $jscript = '<script type="text/javascript">'."\n".
  545:                    '// <![CDATA['."\n".
  546:                    $jscript."\n".'// ]]>'."\n".'</script>'."\n";
  547:     }
  548:     if ($loaditems) {
  549:         if (ref($args) eq 'HASH') {
  550:             my %loadhash = (
  551:                              'add_entries' => $loaditems,
  552:                            );
  553:             my %arghash = (%loadhash,%{$args});
  554:             $args = \%arghash;                  
  555:         } else {
  556:             $args = {'add_entries' => $loaditems,};
  557:         }
  558:     }
  559:     return &Apache::loncommon::start_page($bodytitle,$jscript.$jsextra,$args);
  560: }
  561: 
  562: sub form_elements {
  563:     my ($dom,$showcredits) = @_;
  564:     my $instcredits;
  565:     my %elements =
  566:     (
  567:         new => {
  568:             crstype => {
  569:                 crstype => 'selectbox',
  570:                 action  => 'selectbox',
  571:                 origcnum => 'hidden', 
  572:             },
  573:             courseinfo => {
  574:                 cdescr           => 'text',
  575:                 cloning          => 'radio', 
  576:                 clonecrs         => 'text',
  577:                 clonedom         => 'selectbox',
  578:                 datemode         => 'radio',
  579:                 dateshift        => 'text',
  580:             },
  581:             enrollment  => {
  582:                 accessstart_month  => 'selectbox',
  583:                 accessstart_hour   => 'selectbox',
  584:                 accessend_month    => 'selectbox',
  585:                 accessend_hour     => 'selectbox',
  586:                 accessstart_day    => 'text',
  587:                 accessstart_year   => 'text',
  588:                 accessstart_minute => 'text',
  589:                 accessstart_second => 'text',
  590:                 accessend_day      => 'text',
  591:                 accessend_year     => 'text',
  592:                 accessend_minute   => 'text',
  593:                 accessend_second   => 'text',
  594:                 no_end_date      => 'checkbox',
  595:             },
  596:             personnel => {
  597:                 addperson   => 'checkbox', 
  598:             },
  599:             review => {
  600:                 cnum => 'hidden',
  601:             },
  602:          },
  603:          view => {
  604:             crstype => {
  605:                 crstype => 'selectbox',
  606:                 action  => 'selectbox',
  607:             },
  608:          },
  609:     );
  610:     my %servers = &Apache::lonnet::get_servers($dom,'library');
  611:     my $numlib = keys(%servers);
  612:     if ($numlib > 1) {
  613:         $elements{'new'}{'courseinfo'}{'chome'} = 'selectbox';
  614:     } else {
  615:         $elements{'new'}{'courseinfo'}{'chome'} = 'hidden';
  616:     }
  617:     my (@codetitles,%cat_titles,%cat_order,@code_order,$lastitem);
  618:     &Apache::lonnet::auto_possible_instcodes($dom,\@codetitles,\%cat_titles,
  619:                                              \%cat_order,\@code_order);
  620:     my $numtitles = scalar(@codetitles);
  621:     if ($numtitles) {
  622:         my %extras;
  623:         $lastitem = pop(@codetitles);
  624:         $extras{'instcode_'.$lastitem} = 'text'; 
  625:         foreach my $item (@codetitles) {
  626:             $extras{'instcode_'.$item} = 'selectbox';   
  627:         }
  628:         $elements{'new'}{'codepick'} = \%extras;
  629:     }
  630:     if (&Apache::lonnet::auto_run('',$dom)) {
  631:         my %extras = (
  632:                        enrollstart_month  => 'selectbox',
  633:                        enrollstart_hour   => 'selectbox',
  634:                        enrollend_month    => 'selectbox',
  635:                        enrollend_hour     => 'selectbox',
  636:                        enrollstart_day    => 'text',
  637:                        enrollstart_year   => 'text',
  638:                        enrollstart_minute => 'text',
  639:                        enrollstart_second => 'text',
  640:                        enrollend_day      => 'text',
  641:                        enrollend_year     => 'text',
  642:                        enrollend_minute   => 'text',
  643:                        enrollend_second   => 'text',
  644:                        addcrosslist       => 'checkbox',
  645:                        autoadds           => 'radio',
  646:                        autodrops          => 'radio',
  647:         );
  648:         my ($instcode,$titlescount) = &get_instcode($dom);
  649:         if ($instcode) {
  650:             my @sections = &Apache::lonnet::auto_get_sections(undef,$dom,$instcode);
  651:             if (@sections) {
  652:                 $extras{'sectotal'} = 'hidden';
  653:                 if ($env{'form.sectotal'} > 0) {
  654:                     for (my $i=0; $i<$env{'form.sectotal'}; $i++) {
  655:                         $extras{'sec_'.$i} = 'radio';
  656:                         $extras{'secnum_'.$i} = 'text';
  657:                         $extras{'loncapasec_'.$i} = 'text';
  658:                     }
  659:                 }
  660:             } else {
  661:                 $extras{'addsection'} = 'checkbox';
  662:                 my $sectotal = $env{'form.sectotal'};
  663:                 if ($env{'form.addsection'}) {
  664:                     $sectotal ++;
  665:                 }
  666:                 for (my $i=0; $i<$sectotal; $i++) {
  667:                     $extras{'sec_'.$i} = 'checkbox';
  668:                     $extras{'secnum_'.$i} = 'text',
  669:                     $extras{'loncapasec_'.$i} = 'text',
  670:                 }
  671:             }
  672:             (my $outcome,my $desc,$instcredits) = 
  673:                 &Apache::lonnet::auto_validate_instcode(undef,$dom,$instcode);
  674:             if ($showcredits && $instcredits eq '') {
  675:                 $extras{'coursecredits'} = 'text';
  676:             }
  677:         } elsif (($env{'form.crstype'} eq 'unofficial') || ($env{'form.crstype'} eq 'textbook')) {
  678:             if ($showcredits) {
  679:                 $extras{'coursecredits'} = 'text';
  680:             }
  681:         }
  682:         my $crosslisttotal = $env{'form.crosslisttotal'};
  683:         if ($env{'form.addcrosslist'}) {
  684:             $crosslisttotal ++;
  685:         }
  686:         if (!$crosslisttotal) {
  687:             $crosslisttotal = 1;
  688:         }
  689:         for (my $i=0; $i<$env{'form.crosslisttotal'}; $i++) {
  690:             if ($numtitles) {
  691:                 $extras{'crosslist_'.$i.'_'.$lastitem} = 'text';
  692:             }
  693:             if (@codetitles > 0) {
  694:                 foreach my $item (@codetitles) {
  695:                     $extras{'crosslist_'.$i.'_'.$item} = 'selectbox';
  696:                 }
  697:             }
  698:             $extras{'crosslist_'.$i} = 'checkbox';
  699:             $extras{'crosslist_'.$i.'_instsec'} = 'text',
  700:             $extras{'crosslist_'.$i.'_lcsec'} = 'text',
  701:         }
  702:         my %mergedhash = (%{$elements{'new'}{'enrollment'}},%extras);
  703:         %{$elements{'new'}{'enrollment'}} = %mergedhash;
  704:     }
  705:     my %people;
  706:     my $persontotal = $env{'form.persontotal'};
  707:     if ($env{'form.addperson'}) {
  708:         $persontotal ++;
  709:     }
  710:     if ((!defined($persontotal)) || (!$persontotal)) {
  711:         $persontotal = 1;
  712:     }
  713:     for (my $i=0; $i<$persontotal; $i++) {
  714:         $people{'person_'.$i.'_uname'}     = 'text',
  715:         $people{'person_'.$i.'_dom'}       = 'selectbox',
  716:         $people{'person_'.$i.'_hidedom'}   = 'hidden',
  717:         $people{'person_'.$i.'_firstname'} = 'text',
  718:         $people{'person_'.$i.'_lastname'}  = 'text',
  719:         $people{'person_'.$i.'_emailaddr'} = 'text',
  720:         $people{'person_'.$i.'_role'}      = 'selectbox',
  721:         $people{'person_'.$i.'_sec'}       = 'selectbox',
  722:         $people{'person_'.$i.'_newsec'}    = 'text',
  723:     }
  724:     my %personnelhash = (%{$elements{'new'}{'personnel'}},%people);
  725:     %{$elements{'new'}{'personnel'}} = %personnelhash;
  726:     return (\%elements,$instcredits);;
  727: }
  728: 
  729: sub onload_action {
  730:     my ($action,$state) = @_;
  731:     my %loaditems;
  732:     if (($action eq 'new') || ($action eq 'view')) {
  733:         if ($state eq 'crstype') {
  734:             $loaditems{'onload'} = 'javascript:setAction(document.mainmenu_action);javascript:setType(document.mainmenu_coursetype)';
  735:         } else {
  736:             $loaditems{'onload'} = 'javascript:setFormElements(document.requestcrs);';
  737:         }
  738:         if ($state eq 'courseinfo') {
  739:             $loaditems{'onload'} .= 'javascript:setCloneDisplay(document.requestcrs);';
  740:         }
  741:         if ($state eq 'process') {
  742:             $loaditems{'onload'} .= 'javascript:hideProcessing();';
  743:         }
  744:     }
  745:     return \%loaditems;
  746: }
  747: 
  748: sub print_main_menu {
  749:     my ($r,$can_request,$states,$dom,$jscript,$loaditems,$crumb,$incdoms) = @_;
  750:     my ($types,$typename) = &Apache::loncommon::course_types();
  751:     my $onchange = 'this.form.submit()';
  752:     my $nextstate_setter = "\n";
  753:     if (ref($states) eq 'HASH') {
  754:         foreach my $key (keys(%{$states})) {
  755:             if (ref($states->{$key}) eq 'ARRAY') {
  756:                 $nextstate_setter .= 
  757: "             if (actionchoice == '$key') {
  758:                   nextstate = '".$states->{$key}[1]."';
  759:              }
  760: ";
  761:             }
  762:         }
  763:     }
  764: 
  765:     my $js = <<"END";
  766: 
  767: function nextPage(formname) {
  768:     var crschoice = document.mainmenu_coursetype.crstype.value;
  769:     var actionchoice = document.mainmenu_action.action.value;
  770:     if (check_can_request(crschoice,actionchoice) == true) {
  771:         if ((actionchoice == 'new') && (crschoice == 'official')) {
  772:             nextstate = 'codepick';
  773:         } else {
  774: $nextstate_setter 
  775:         }
  776:         formname.crstype.value = crschoice;
  777:         formname.action.value = actionchoice; 
  778:         formname.state.value= nextstate;
  779:         formname.submit();
  780:     }
  781:     return;
  782: }
  783: 
  784: function check_can_request(crschoice,actionchoice) {
  785:     var official = '';
  786:     var unofficial = '';
  787:     var community = '';
  788:     var textbook = '';
  789:     var placement = '';
  790: END
  791:     if (ref($can_request) eq 'HASH') {
  792:         foreach my $item (keys(%{$can_request})) {
  793:                 $js .= " 
  794:         $item = 1;
  795: ";
  796:         }
  797:     }
  798:     my %js_lt = &Apache::lonlocal::texthash(
  799:         official => 'You are not permitted to request creation of an official course in this domain.',
  800:         unofficial => 'You are not permitted to request creation of an unofficial course in this domain.',
  801:         community => 'You are not permitted to request creation of a community in this domain.',
  802:         textbook => 'You are not permitted to request creation of a textbook course in this domain',
  803:         placement => 'You are not permitted to request creation of a placement test in this domain',
  804:         all => 'You must choose a specific course type when making a new course request.',
  805:         allt => '"All types" is not allowed.',
  806:     ); 
  807:     &js_escape(\%js_lt);
  808:     $js .= <<END;
  809:     if (crschoice == 'official') {
  810:         if (official != 1) {
  811:             alert("$js_lt{'official'}");
  812:             return false;
  813:         }
  814:     } else {
  815:         if (crschoice == 'unofficial') {
  816:             if (unofficial != 1) {
  817:                 alert("$js_lt{'unofficial'}");
  818:                 return false;
  819:             }
  820:         } else {
  821:             if (crschoice == 'community') {
  822:                 if (community != 1) {
  823:                     alert("$js_lt{'community'}");
  824:                     return false;
  825:                 }
  826:             } else {
  827:                 if (crschoice == 'textbook') {
  828:                     if (textbook != 1) {
  829:                         alert("$js_lt{'textbook'}");
  830:                         return false;
  831:                     }
  832:                 } else {
  833:                     if (crschoice == 'placement') {
  834:                         if (placement != 1) {
  835:                             alert("$js_lt{'placement'}");
  836:                             return false;
  837:                         }
  838:                     } else {
  839:                         if (actionchoice == 'new') {
  840:                             alert('$js_lt{'all'}'+'\\n'+'$js_lt{'allt'}');
  841:                             return false;
  842:                         }
  843:                     }
  844:                 }
  845:             }
  846:         }
  847:     }
  848:     return true;
  849: }
  850: END
  851:     my ($pagetitle,$pageinfo,$domaintitle,$earlyout);
  852:     if (ref($can_request) eq 'HASH') {
  853:         if (($can_request->{'official'}) || ($can_request->{'unofficial'}) || ($can_request->{'textbook'}) || ($can_request->{'placement'})) {
  854:             if ($can_request->{'community'}) {
  855:                 $pagetitle = 'Course/Community Requests';
  856:                 $pageinfo = &mt('Request creation of a new course or community, or review your pending requests.');
  857:                 $domaintitle = &mt('Course/Community Domain');
  858:             } else {
  859:                 $pagetitle = 'Course Requests';
  860:                 $pageinfo = &mt('Request creation of a new course, or review your pending course requests.');
  861:                 $domaintitle = &mt('Course Domain');
  862:             }
  863:         } elsif ($can_request->{'community'}) {
  864:             $pagetitle = 'Community Requests';
  865:             $pageinfo = &mt('Request creation of a new course, or review your pending requests.');
  866:             $domaintitle = &mt('Community Domain');
  867:         } elsif ((ref($incdoms) eq 'ARRAY') && ((@{$incdoms} > 1) ||
  868:                  ((@{$incdoms} == 1) && ($incdoms->[0] ne $dom)))) {
  869:             $pagetitle = 'Course/Community Requests';
  870:             $pageinfo = &mt('You do not have rights to request creation of courses in this domain; please choose a different domain.');
  871:             $domaintitle = &mt('Course/Community Domain');
  872:         } else {
  873:             $pagetitle = 'Course/Community Requests';
  874:             $pageinfo  = &mt('You do not have rights to request creation of courses or communities.');
  875:             $earlyout = 1;
  876:         }
  877:     }
  878:     $r->print(&header($pagetitle,$js.$jscript,$loaditems).$crumb.
  879:              '<p>'.$pageinfo.'</p>');
  880:     if ($earlyout) {
  881:         $r->print(&Apache::loncommon::end_page());
  882:         return;
  883:     }
  884:     $r->print('<div>'.
  885:               &Apache::lonhtmlcommon::start_pick_box().
  886:               &Apache::lonhtmlcommon::row_title($domaintitle).
  887:               '<form name="domforcourse" method="post" action="/adm/requestcourse">'.
  888:               &Apache::loncommon::select_dom_form($dom,'showdom','',1,$onchange,$incdoms));
  889:     if (!$onchange) {
  890:         $r->print('&nbsp;<input type="submit" name="godom" value="'.
  891:                    &mt('Change').'" />');
  892:     }
  893:     unless ((ref($can_request) eq 'HASH') && (keys(%{$can_request}) > 0)) {
  894:         $r->print('</form>'.&Apache::lonhtmlcommon::row_closure(1)."\n".
  895:                   &Apache::lonhtmlcommon::end_pick_box().'</div>'."\n".
  896:                   &Apache::loncommon::end_page());
  897:         return;
  898:     }
  899:     $r->print('</form>'.&Apache::lonhtmlcommon::row_closure());
  900:     my $formname = 'requestcrs';
  901:     my $nexttext = &mt('Next');
  902:     $r->print(&Apache::lonhtmlcommon::row_title(&mt('Action')).'
  903: <form name="mainmenu_action" method="post" action=""> 
  904: <select size="1" name="action" >
  905:  <option value="new">'.&mt('New request').'</option>
  906:  <option value="view">'.&mt('View/Modify/Cancel pending requests').'</option>
  907:  <option value="log">'.&mt('View request history').'</option>
  908: </select></form>'.
  909:               &Apache::lonhtmlcommon::row_closure().
  910:               &Apache::lonhtmlcommon::row_title(&mt('Type')).'
  911: <form name="mainmenu_coursetype" method="post" action="">
  912: <select size="1" name="crstype">');
  913:     if (ref($can_request) eq 'HASH') {
  914:         if (keys(%{$can_request}) > 1) {
  915:             $r->print(' <option value="any">'.&mt('All types').'</option>');
  916:         }
  917:         if ((ref($types) eq 'ARRAY') && (ref($typename) eq 'HASH')) {
  918:             foreach my $type (@{$types}) {
  919:                 next unless($can_request->{$type});
  920:                 my $selected = '';
  921:                 if ($env{'form.crstype'} eq '') {
  922:                     if ($type eq 'official') {
  923:                         $selected = ' selected="selected"';
  924:                     }
  925:                 } else {
  926:                     if ($type eq $env{'form.crstype'}) {
  927:                         $selected = ' selected="selected"';
  928:                     }
  929:                 }
  930:                 $r->print('<option value="'.$type.'"'.$selected.'>'.&mt($typename->{$type}).
  931:                           '</option>'."\n");
  932:             }
  933:         }
  934:     }
  935:     $r->print('</select></form>'."\n".
  936:               &Apache::lonhtmlcommon::row_closure(1)."\n".
  937:               &Apache::lonhtmlcommon::end_pick_box().'</div>'."\n".
  938:               '<div><form name="'.$formname.'" method="post" action="/adm/requestcourse">'."\n".
  939:               '<input type="hidden" name="state" value="crstype" />'."\n".
  940:               '<input type="hidden" name="showdom" value="'.$dom.'" />'."\n".
  941:               '<input type="hidden" name="crstype" value="" />'."\n".
  942:               '<input type="hidden" name="action" value="" />'."\n".
  943:               '<input type="button" name="next" value="'.$nexttext.
  944:               '" onclick="javascript:nextPage(document.'.$formname.')" />'."\n".
  945:               '</form></div>');
  946:     $r->print(&Apache::loncommon::end_page());
  947:     return;
  948: }
  949: 
  950: sub request_administration {
  951:     my ($r,$action,$state,$page,$states,$dom,$jscript,$loaditems,$crumb,
  952:         $newinstcode,$codechk,$checkedcode,$description,$showcredits,
  953:         $instcredits,$invalidcrosslist,$uname,$udom) = @_;
  954:     my $js;
  955:     if (($action eq 'new') || (($action eq 'view') && ($state eq 'pick_request'))) {
  956:         $js =  <<END;
  957: 
  958: function nextPage(formname,nextstate) {
  959:     formname.state.value= nextstate;
  960:     formname.submit();
  961: }
  962: 
  963: END
  964:     }
  965:     if (($action eq 'new') || ($action eq 'view')) {
  966:         $js .= <<END;   
  967: 
  968: function backPage(formname,prevstate) {
  969:     formname.state.value = prevstate;
  970:     formname.submit();
  971: }
  972: 
  973: END
  974:     }
  975:     if ($action eq 'new') {
  976:         my $jsextra;
  977:         if (($state eq 'courseinfo') || ($state eq 'codepick')) {
  978:             $jsextra = "\n".&Apache::loncommon::coursebrowser_javascript($dom,'','','','','',
  979:                                                                          $newinstcode);
  980:         } elsif ($state eq 'enrollment') {
  981:             if (($env{'form.crstype'} eq 'official') && 
  982:                 (&Apache::lonnet::auto_run('',$dom))) {
  983:                 $js .= "\n".&section_check_javascript()."\n".&enrollment_lcsec_js();
  984:             }
  985:         } elsif ($state eq 'personnel') {
  986:             $js .= "\n".&section_check_javascript()."\n".&personnel_lcsec_js();
  987:         }
  988:         my $title;
  989:         if ($env{'form.crstype'} eq 'community') {
  990:             $title = 'Request a community';
  991:         } else {
  992:             $title = 'Request a course';
  993:         }
  994:         $r->print(&header($title,$js.$jscript,$loaditems,$jsextra).$crumb);
  995:         &print_request_form($r,$action,$state,$page,$states,$dom,$newinstcode,
  996:                             $codechk,$checkedcode,$description,$showcredits,
  997:                             $instcredits,$invalidcrosslist);
  998:     } elsif ($action eq 'view') {
  999:         my $jsextra;
 1000:         my $formname = 'requestcrs';
 1001:         my $prev = $states->{$action}[$page-1];
 1002:         my $next = $states->{$action}[$page+1];
 1003:         if ($state eq 'pick_request') {
 1004:             $next = $states->{$action}[$page+1];
 1005:             $jsextra = &viewrequest_javascript($formname,$next);
 1006:         } elsif ($state eq 'details') {
 1007:             $jsextra = &viewdetails_javascript($formname);
 1008: 
 1009:         } elsif ($state eq 'cancel') {
 1010:             $jsextra = &viewcancel_javascript($formname);
 1011:         }
 1012:         my $title;
 1013:         if ($env{'form.crstype'} eq 'community') {
 1014:             $title = 'Manage community requests';
 1015:         } else {
 1016:             $title = 'Manage course requests';
 1017:         }
 1018:         $r->print(&header($title,$js.$jscript.$jsextra,$loaditems).$crumb);
 1019:         my $form = '<form method="post" name="'.$formname.'" action="/adm/requestcourse" />';
 1020:         if ($state eq 'pick_request') {
 1021:             my $title;
 1022:             if ($env{'form.crstype'} eq 'community') {
 1023:                 $title = &mt('Pending community requests');
 1024:             } elsif ($env{'form.crstype'} eq 'official') {
 1025:                 $title = &mt('Pending requests for official courses');
 1026:             } elsif ($env{'form.crstype'} eq 'unofficial') {
 1027:                 $title = &mt('Pending requests for unofficial courses');
 1028:             } elsif ($env{'form.crstype'} eq 'textbook') {
 1029:                 $title = &mt('Pending requests for textbook courses');
 1030:             } elsif ($env{'form.crstype'} eq 'textbook') {
 1031:                 $title = &mt('Pending requests for placement tests'); 
 1032:             } else {
 1033:                 $title = &mt('Pending course/community requests'); 
 1034:             }
 1035:             $r->print('<h3>'.$title.'</h3><div>'."\n".$form."\n".
 1036:                       &print_request_status($dom,$action).'</form></div>');
 1037:         } elsif ($state eq 'details') {
 1038:             my (@codetitles,%cat_titles,%cat_order,@code_order,$instcode,$code_chk);
 1039:             my $origcnum = $env{'form.cnum'};
 1040:             if ($origcnum eq '') {
 1041:                 $origcnum = $env{'form.origcnum'};   
 1042:             }
 1043:             if ($env{'form.crstype'} eq 'official') {
 1044:                 &Apache::lonnet::auto_possible_instcodes($dom,\@codetitles,\%cat_titles,
 1045:                                                          \%cat_order,\@code_order);
 1046:             }
 1047:             my $title;
 1048:             if ($env{'form.crstype'} eq 'community') {
 1049:                 $title = &mt('Community Request Details');
 1050:             } else {
 1051:                 $title = &mt('Course Request Details');
 1052:             }
 1053:             $r->print('<h3>'.$title.'</h3><div>'."\n".$form."\n".
 1054:                       &print_review($dom,\@codetitles,\%cat_titles,\%cat_order,
 1055:                                     \@code_order,'','','','',$instcredits)."\n".
 1056:                       '<input name="origcnum" value="'.$origcnum.'" type="hidden" />'."\n");
 1057:             my @excluded = &get_excluded_elements($dom,$states,'new','review',
 1058:                                                   $showcredits);
 1059:             push(@excluded,'origcnum');
 1060:             $r->print(&Apache::lonhtmlcommon::echo_form_input(\@excluded).'</div>');
 1061:             my $other = 'modify';
 1062:             my %navtxt = &Apache::lonlocal::texthash (
 1063:                                                       prev => 'Back',
 1064:                                                       other => 'Modify Request',
 1065:                                                       next => 'Cancel Request',
 1066:                                                      );
 1067:             &display_navbuttons($r,$dom,$formname,$prev,$navtxt{'prev'},$next,
 1068:                                 $navtxt{'next'},$state,$other,$navtxt{'other'});
 1069:             $r->print('</form>');
 1070:         } elsif ($state eq 'cancel') {
 1071:             my $title;
 1072:             if ($env{'form.crstype'} eq 'community') {
 1073:                 $title = &mt('Cancel community request');
 1074:             } else {
 1075:                 $title = &mt('Cancel course request');
 1076:             }
 1077:             my ($result,$output) = &print_cancel_request($dom,$env{'form.origcnum'});
 1078:             $r->print('<h3>'.$title.'</h3><div>'."\n".$form."\n".
 1079:                       $output);
 1080:             my @excluded = &get_excluded_elements($dom,$states,'view','cancel',
 1081:                                                   $showcredits);
 1082:             $r->print(&Apache::lonhtmlcommon::echo_form_input(\@excluded).'</div>');
 1083:             my %navtxt = &Apache::lonlocal::texthash (
 1084:                                                       prev => 'Back',
 1085:                                                       next => 'Confirm Cancellation',
 1086:                                                      );
 1087:             if ($result eq 'ok') {
 1088:                 &display_navbuttons($r,$dom,$formname,$prev,$navtxt{'prev'},$next,
 1089:                                     $navtxt{'next'},$state);
 1090:             } else {
 1091:                 &display_navbuttons($r,$dom,$formname,$prev,$navtxt{'prev'},undef,
 1092:                                     '',$state);
 1093:             }
 1094:             $r->print('</form>');
 1095:         } elsif ($state eq 'removal') {
 1096:             my $cnum = $env{'form.origcnum'};
 1097:             my $statuskey = 'status:'.$dom.':'.$cnum;
 1098:             my %userreqhash = &Apache::lonnet::get('courserequests',[$statuskey],
 1099:                                                    $env{'user.domain'},$env{'user.name'});
 1100:             my $currstatus = $userreqhash{$statuskey};
 1101:             my ($result,$error); 
 1102:             if (($currstatus eq 'approval') || ($currstatus eq 'pending')) { 
 1103:                 my %status = (
 1104:                                  $statuskey => 'cancelled',
 1105:                              );
 1106:                 my $statusresult = &Apache::lonnet::put('courserequests',\%status);
 1107:                 if ($statusresult eq 'ok') {
 1108:                     my $delresult = 
 1109:                         &Apache::lonnet::del_dom('courserequestqueue',
 1110:                                                  [$cnum.'_'.$currstatus],$dom);
 1111:                     if ($delresult eq 'ok') {
 1112:                         $result = 'ok';
 1113:                     } else {
 1114:                         $error = &mt('An error occurred when updating the pending requests queue: [_1]',$delresult);
 1115:                     }
 1116:                 } else {
 1117:                     $error = &mt("An error occurred when updating the status of this request in the requestor's records: [_1]",$statusresult);
 1118:                 }
 1119:             } else {
 1120:                 $error = &mt('The current status of this request could not be verified as pending approval/institutional action.');  
 1121:             }
 1122:             $r->print('<h3>'.&mt('Request Cancellation').'</h3><div>'."\n".$form."\n".
 1123:                       '<input type="hidden" name="state" value="'.$state.'" />'."\n".
 1124:                       '<input type="hidden" name="action" value="'.$action.'" />'."\n".
 1125:                       '<input type="hidden" name="showdom" value="'.$dom.'" />'."\n".
 1126:                       '<input type="hidden" name="orignum" value="'.$cnum.'" />'."\n");
 1127:             if ($result eq 'ok') {
 1128:                 if ($env{'form.crstype'} eq 'community') {
 1129:                     $r->print(&mt('Your community request has been cancelled.'));
 1130:                 } else {
 1131:                     $r->print(&mt('Your course request has been cancelled.'));
 1132:                 }
 1133:             } else {
 1134:                 $r->print('<div class="LC_error">'.
 1135:                           &mt('The request cancellation process was not complete.').
 1136:                           '<br />'.$error.'</div>');
 1137:             }
 1138:             $r->print('</form>');
 1139:         }
 1140:     } elsif ($action eq 'display') {
 1141:         my $formname = 'requestcrs';
 1142:         my (@codetitles,%cat_titles,%cat_order,@code_order,$instcode,$code_chk);
 1143:         if ($env{'form.crstype'} eq 'official') {
 1144:             &Apache::lonnet::auto_possible_instcodes($dom,\@codetitles,\%cat_titles,
 1145:                                                      \%cat_order,\@code_order);
 1146:         }
 1147:         my ($title,$header);
 1148:         if ($env{'form.crstype'} eq 'community') {
 1149:             $title = 'Community Request';
 1150:             $header = &mt('Community Request');
 1151:         } else {
 1152:             $title = 'Course Request';
 1153:             $header = &mt('Course Request');
 1154:         }
 1155:         $r->print(&header($title,'','','',{ 'only_body' => 1}).
 1156:                   $crumb."\n".'<h3>'.$header.'</h3>'.
 1157:                   &print_review($dom,\@codetitles,\%cat_titles,\%cat_order,
 1158:                                 \@code_order,$uname,$udom,'','',$instcredits)."\n".
 1159:                   '</div>'.
 1160:                   &close_popup_form());
 1161:     }
 1162:     $r->print(&Apache::loncommon::end_page());
 1163:     return;
 1164: }
 1165: 
 1166: sub domcoord_display {
 1167:     my ($dom) = @_;
 1168:     my ($uname,$udom,$result,$warning);
 1169:     if (($dom eq $env{'request.role.domain'}) && (&Apache::lonnet::allowed('ccc',$dom))) {
 1170:         if ($env{'form.cnum'} ne '') {
 1171:             my $cnum = $env{'form.cnum'};
 1172:             my $queue = $env{'form.queue'};
 1173:             my $reqkey = $cnum.'_'.$queue;
 1174:             my $namespace = 'courserequestqueue';
 1175:             my $domconfig = &Apache::lonnet::get_domainconfiguser($dom);
 1176:             my %queued =
 1177:                 &Apache::lonnet::get($namespace,[$reqkey],$dom,$domconfig);
 1178:             if (ref($queued{$reqkey}) eq 'HASH') {
 1179:                 $uname = $queued{$reqkey}{'ownername'};
 1180:                 $udom  = $queued{$reqkey}{'ownerdom'};
 1181:                 if (($udom =~ /^$match_domain$/) && ($uname =~ /^$match_username$/)) {
 1182:                     $result = &retrieve_settings($dom,$cnum,$udom,$uname);
 1183:                 } else {
 1184:                     if ($env{'form.crstype'} eq 'community') {
 1185:                         $warning = &mt('Invalid username or domain for community requestor');
 1186:                     } else {
 1187:                         $warning = &mt('Invalid username or domain for course requestor');
 1188:                     }
 1189:                 }
 1190:             } else {
 1191:                 if ($env{'form.crstype'} eq 'community') {
 1192:                     $warning = &mt('No information was found for this community request.');
 1193:                 } else {
 1194:                     $warning = &mt('No information was found for this course request.');
 1195:                 }
 1196:             }
 1197:         } else {
 1198:             $warning = &mt('No course request ID provided.');
 1199:         }
 1200:     } else {
 1201:         if ($env{'form.crstype'} eq 'any') {
 1202:             $warning = &mt('You do not have rights to view course or community request information.');
 1203:         } elsif ($env{'form.crstype'} eq 'community') {
 1204:             $warning = &mt('You do not have rights to view community request information.');
 1205:         } else {
 1206:             $warning = &mt('You do not have rights to view course request information.');
 1207:         }
 1208:     }
 1209:     return ($uname,$udom,$result,$warning);
 1210: }
 1211: 
 1212: sub enrollment_lcsec_js {
 1213:     my %alerts = &section_check_alerts();
 1214:     my $secname = $alerts{'badsec'};
 1215:     my $secnone = $alerts{'reserved'};
 1216:     &js_escape(\$secname);
 1217:     &js_escape(\$secnone);
 1218:     my $output = '
 1219: function validateEnrollSections(formname,nextstate) {
 1220:     var badsectotal = 0;
 1221:     var reservedtotal = 0;
 1222:     var secTest = "";
 1223: ';
 1224:     for (my $i=0; $i<$env{'form.sectotal'}; $i++) {
 1225:         $output .= "
 1226:     var selSec = 0;
 1227:     for (var j=0; j<document.requestcrs.sec_".$i.".length; j++) {
 1228:         if (document.requestcrs.sec_".$i."[j].checked) {
 1229:             selSec = document.requestcrs.sec_".$i."[j].value;
 1230:         }
 1231:         if (selSec == 1) {
 1232:             secTest = validsection(document.requestcrs.loncapasec_".$i.");
 1233:             if (secTest == 'badsec') {
 1234:                 badsectotal++;
 1235:             }
 1236:             if (secTest == 'reserved') {
 1237:                 reservedtotal++;
 1238:             }
 1239:         }
 1240:     }
 1241: ";
 1242:     }
 1243:     for (my $i=0; $i<$env{'form.crosslisttotal'}; $i++) {
 1244:         $output .= "
 1245:     if (document.requestcrs.crosslist_".$i.".checked) {
 1246:         secTest = validsection(document.requestcrs.crosslist_".$i."_lcsec);
 1247:         if (secTest == 'badsec') {
 1248:             badsectotal++;
 1249:         }
 1250:         if (secTest == 'reserved') {
 1251:             reservedtotal++;
 1252:         }
 1253:     }
 1254: ";
 1255:     }
 1256:     $output .= "
 1257:     if (badsectotal>0) {
 1258:         alert('$secname');
 1259:         return false;
 1260:     }
 1261:     if (reservedtotal>0) {
 1262:         alert('$secnone');
 1263:         return false;
 1264:     }
 1265:     formname.state.value= nextstate;
 1266:     formname.submit();
 1267:     return;
 1268: }
 1269: ";
 1270:     return $output;
 1271: }
 1272: 
 1273: sub personnel_lcsec_js {
 1274:     my %alerts = &section_check_alerts();
 1275:     my $secname = $alerts{'badsec'}."\n".$alerts{'separate'};
 1276:     my $secnone = $alerts{'reserved'};
 1277:     &js_escape(\$secname);
 1278:     &js_escape(\$secnone);
 1279:     my $output = '
 1280: function validatePersonnelSections(formname,nextstate) {
 1281:     var badsectotal = 0;
 1282:     var reservedtotal = 0;
 1283:     var secTest = "";
 1284: ';
 1285:     for (my $i=0; $i<$env{'form.persontotal'}; $i++) {
 1286:         $output .= "
 1287:     if (document.requestcrs.person_".$i."_uname.value != '') {
 1288:         secTest = validsection(document.requestcrs.person_".$i."_newsec,'1');
 1289:         if (secTest == 'badsec') {
 1290:             badsectotal++; 
 1291:         }
 1292:         if (secTest == 'reserved') {
 1293:             reservedtotal++;
 1294:         }
 1295:     }
 1296: ";
 1297:     }
 1298:     $output .= "
 1299:     if (badsectotal > 0) {
 1300:         alert('$secname');
 1301:         return false;
 1302:     } else {
 1303:         if (reservedtotal > 0) {
 1304:             alert('$secnone');
 1305:             return false;
 1306:         }
 1307:     }
 1308:     formname.state.value = nextstate;
 1309:     formname.submit();
 1310:     return;
 1311: }
 1312: ";
 1313:     return $output;
 1314: }
 1315: 
 1316: sub section_check_alerts {
 1317:     my %lt = 
 1318:         &Apache::lonlocal::texthash(
 1319:             reserved => "You need to change one or more LON-CAPA section names - none is a reserved word in the system, and may not be used.",
 1320:             badsec => 'You need to change one or more LON-CAPA section names - names may only contain letters or numbers.',
 1321:             separate => 'Separate multiple sections with a comma.'
 1322:         );
 1323:     return %lt;
 1324: }
 1325: 
 1326: sub section_check_javascript {
 1327:     return <<"END";
 1328: function validsection(field,mult) {
 1329:     var str = field.value;
 1330:     var badsec=0;
 1331:     var reserved=0;
 1332:     if (window.RegExp) {
 1333:         var badsecnum=0;
 1334:         var reservednum=0;
 1335:         var pattern=/[^a-zA-Z0-9]/; 
 1336:         str = str.replace(/(^\\s*)|(\\s*\$)/gi,"");
 1337:         str = str.replace(/[ ]{2,}/gi," ");
 1338:         if (mult == '1') {
 1339:             var sections = new Array();
 1340:             sections = str.split(/\\s*[\\s,;:]\\s*/);
 1341:             var i;
 1342:             for (i=0; i<sections.length; i++) {
 1343:                 if ((sections[i] != '') && (sections[i] != undefined) && (sections[i] != null)) {
 1344:                     if (pattern.test(sections[i])) {
 1345:                         badsecnum++;
 1346:                     } else {
 1347:                         if (sections[i] == 'none') {
 1348:                             reservednum++;
 1349:                         }
 1350:                     }
 1351:                 }
 1352:             }
 1353:         } else {
 1354:             if ((str != '') && (str != undefined) && (str != null)) {
 1355:                 if (pattern.test(str)) {
 1356:                     badsecnum++;
 1357:                 } else {
 1358:                     if (str == 'none') {
 1359:                         reservednum++;
 1360:                     }
 1361:                 }
 1362:             }
 1363:         }
 1364:         if (badsecnum > 0) {
 1365:             return 'badsec';
 1366:         }
 1367:         if (reservednum > 0) {
 1368:             return 'reserved';
 1369:         }
 1370:     }
 1371:     return;
 1372: }
 1373: END
 1374: }
 1375: 
 1376: sub close_popup_form {
 1377:     my $close= &mt('Close Window');
 1378:     return << "END";
 1379: <p><form name="displayreq" action="" method="post">
 1380: <input type="button" name="closeme" value="$close" onclick="javascript:self.close();" />
 1381: </form></p>
 1382: END
 1383: }
 1384: 
 1385: sub get_instcode {
 1386:     my ($dom) = @_;
 1387:     my ($instcode,$numtitles);
 1388:     my (@codetitles,%cat_titles,%cat_order,@code_order,$instcode,$code_chk);
 1389:     &Apache::lonnet::auto_possible_instcodes($dom,\@codetitles,\%cat_titles,
 1390:                                              \%cat_order,\@code_order);
 1391:     $numtitles = scalar(@codetitles);
 1392:     if (@code_order > 0) {
 1393:         my $message;
 1394:         foreach my $item (@code_order) {
 1395:             $instcode .= $env{'form.instcode_'.$item};
 1396:         }
 1397:     }
 1398:     return ($instcode,$numtitles);
 1399: }
 1400: 
 1401: sub print_request_form {
 1402:     my ($r,$action,$state,$page,$states,$dom,$newinstcode,$codechk,$checkedcode,
 1403:         $description,$showcredits,$instcredits,$invalidcrosslist) = @_;
 1404:     my $formname = 'requestcrs';
 1405:     my ($next,$prev,$message,$output,$codepicker,$crstype);
 1406:     $prev = $states->{$action}[$page-1];
 1407:     $next = $states->{$action}[$page+1];
 1408:     my %navtxt = &Apache::lonlocal::texthash (
 1409:                                                prev => 'Back',
 1410:                                                next => 'Next',
 1411:                                              );
 1412:     $crstype = $env{'form.crstype'};
 1413:     $r->print('<br /><form name="'.$formname.'" method="post" action="/adm/requestcourse">');
 1414:     my (@codetitles,%cat_titles,%cat_order,@code_order,$instcode,$code_chk,
 1415:         @disallowed);
 1416:     if ($crstype eq 'official') {
 1417:         if ($env{'form.instcode'} ne '') {
 1418:             $instcode = $env{'form.instcode'};
 1419:         } elsif ($newinstcode ne '') {
 1420:             $instcode = $newinstcode;
 1421:         }
 1422:         if ($checkedcode) {
 1423:             if ($codechk eq 'valid') {
 1424:                 $message = '<div class="LC_info">'.
 1425:                            &mt('The chosen course category [_1] is valid.','<b>'.
 1426:                            $instcode.'</b>').
 1427:                            '<input type="hidden" name="instcode" value="'.
 1428:                            $instcode.'" /></div>';
 1429:             } else {
 1430:                 $message = '<div class="LC_warning">'.
 1431:                             &mt('No course was found matching your choice of institutional course category.');
 1432:                 if ($codechk ne '') {
 1433:                     $message .= '<br />'.$codechk;
 1434:                 }
 1435:                 $message .= '</div>';
 1436:                 $prev = 'crstype';
 1437:             }
 1438:             $r->print($message);
 1439:         }
 1440:     }
 1441:     if ($prev eq 'crstype') {
 1442:         if ($crstype eq 'official') {
 1443:             &Apache::lonnet::auto_possible_instcodes($dom,\@codetitles,\%cat_titles,
 1444:                                                      \%cat_order,\@code_order);
 1445:         }
 1446:         if (@code_order > 0) {
 1447:             $codepicker = &coursecode_form($dom,'instcode',\@codetitles,
 1448:                                            \%cat_titles,\%cat_order);
 1449:             if ($codepicker) {
 1450:                 $r->print(&mt('Specify the course to be created.').
 1451:                           '<div>'.&Apache::lonhtmlcommon::start_pick_box().
 1452:                           $codepicker.
 1453:                           &Apache::lonhtmlcommon::end_pick_box().'</div>');
 1454:             } else {
 1455:                 $next = $states->{$action}[$page+2];
 1456:                 $r->print(&courseinfo_form($dom,$formname,$crstype,$next));
 1457:             }
 1458:         } else {
 1459:             if ($crstype eq 'official') {
 1460:                 $next = $states->{$action}[$page+2];
 1461:             }
 1462:             $r->print(&courseinfo_form($dom,$formname,$crstype,$next));
 1463:         }
 1464:     } elsif ($prev eq 'codepick') {
 1465:         if ($instcode eq '') {
 1466:             $prev = $states->{$action}[$page-2];
 1467:         }
 1468:         $r->print(&courseinfo_form($dom,$formname,$crstype,$next,$description));
 1469:     } elsif ($state eq 'enrollment') {
 1470:         if ($crstype eq 'official') {
 1471:             &Apache::lonnet::auto_possible_instcodes($dom,\@codetitles,\%cat_titles,
 1472:                                                      \%cat_order,\@code_order);
 1473:         }
 1474:         $r->print(&print_enrollment_menu($formname,$instcode,$dom,\@codetitles,
 1475:                                          \%cat_titles,\%cat_order,\@code_order,
 1476:                                          $showcredits,$instcredits,$invalidcrosslist));
 1477:     } elsif ($state eq 'personnel') {
 1478:         $r->print(&print_personnel_menu($dom,$formname,$crstype,$invalidcrosslist));
 1479:     } elsif ($state eq 'review') {
 1480:         my (%alerts,%rulematch,%inst_results,%curr_rules,%got_rules,%disallowmsg);
 1481:         my $now = time;
 1482:         for (my $i=0; $i<$env{'form.persontotal'}; $i++) {
 1483:             my $personname = $env{'form.person_'.$i.'_uname'};
 1484:             my $persondom = $env{'form.person_'.$i.'_dom'};
 1485:             if (($personname =~ /^$match_username$/) && 
 1486:                 ($persondom =~ /^$match_domain$/)) {
 1487:                 if (&Apache::lonnet::domain($persondom)) {
 1488:                     my $personhome = 
 1489:                         &Apache::lonnet::homeserver($personname,$persondom);
 1490:                     if ($personhome eq 'no_host') {
 1491:                         if ($persondom ne $dom) {
 1492:                             my $skipuser = 1;
 1493:                             if ($env{'user.role.dc./'.$persondom.'/'}) {
 1494:                                 my ($start,$end) = split('.',$env{'user.role.dc./'.$persondom.'/'});
 1495:                                 if (((!$start) || ($start < $now)) && 
 1496:                                     ((!$end) || ($end > $now))) {
 1497:                                     $skipuser = 0;
 1498:                                 }
 1499:                             }
 1500:                             if ($skipuser) {
 1501:                                 push(@disallowed,$i);
 1502:                                 $disallowmsg{$i} = &mt('[_1] was excluded because new users need to be from the course domain','<tt>'.$personname.':'.$persondom.'</tt>');
 1503:                                 next;
 1504:                             }
 1505:                         }
 1506:                         my $usertype = &get_usertype($persondom,$personname,\%curr_rules,\%got_rules);
 1507:                         if (&Apache::lonuserutils::can_create_user($dom,'requestcrs',$usertype)) {
 1508:                             my ($allowed,$msg,$authtype,$authparam) = 
 1509:                                 &check_newuser_rules($persondom,$personname,
 1510:                                     \%alerts,\%rulematch,\%inst_results,
 1511:                                     \%curr_rules,\%got_rules);
 1512:                             if ($allowed) {
 1513:                                 my %domdefaults = &Apache::lonnet::get_domain_defaults($persondom);
 1514:                                 if ($usertype eq 'official') {
 1515:                                     if ($authtype eq '') {
 1516:                                         $authtype = $domdefaults{'auth_def'};
 1517:                                         $authparam = $domdefaults{'auth_arg_def'};
 1518:                                     }
 1519:                                 } elsif ($usertype eq 'unofficial') {
 1520:                                     if ($authtype eq '') {
 1521:                                         $authtype = 'internal';
 1522:                                         $authparam = '';
 1523:                                     }
 1524:                                 } else {
 1525:                                     $authtype = $domdefaults{'auth_def'};
 1526:                                     $authparam = $domdefaults{'auth_arg_def'};
 1527:                                 }
 1528:                                 if (($authtype eq '') ||
 1529:                                     (($authtype =~/^krb/) && ($authparam eq ''))) {
 1530:                                     push(@disallowed,$i);
 1531:                                     $disallowmsg{$i} = &mt('[_1] was excluded because institutional information is incomplete for this new user.','<tt>'.$personname.':'.$persondom.'</tt>');
 1532:                                     next;
 1533:                                 }
 1534:                                 if (ref($inst_results{$personname.':'.$persondom}) eq 'HASH') {
 1535:                                     if ($inst_results{$personname.':'.$persondom}{'lastname'} ne '') {
 1536:                                         $env{'form.person_'.$i.'_lastname'} = $inst_results{$personname.':'.$persondom}{'lastname'};
 1537:                                     }
 1538:                                     if ($inst_results{$personname.':'.$persondom}{'firstname'} ne '') {
 1539:                                         $env{'form.person_'.$i.'_firstname'} = $inst_results{$personname.':'.$persondom}{'firstname'};
 1540:                                     }
 1541:                                     if ($inst_results{$personname.':'.$persondom}{'permanentemail'} ne '') {
 1542:                                         $env{'form.person_'.$i.'_emailaddr'} = $inst_results{$personname.':'.$persondom}{'permanentemail'};
 1543:                                     }
 1544:                                 }
 1545:                             } else {
 1546:                                 push(@disallowed,$i);
 1547:                                 $disallowmsg{$i} = &mt('[_1] was excluded because the username violated format rules for the domain','<tt>'.$personname.':'.$persondom.'</tt>');  
 1548:                             }
 1549:                         } else {
 1550:                             push(@disallowed,$i);
 1551:                             $disallowmsg{$i} = &mt('[_1] was excluded because you may not request new users in the domain','<tt>'.$personname.':'.$persondom.'</tt>');
 1552:                         }
 1553:                     } else {
 1554:                         my %userenv = 
 1555:                             &Apache::lonnet::userenvironment($persondom,$personname,'lastname','firstname','permanentemail');
 1556:                         if ($env{'form.person_'.$i.'_lastname'} eq '') {
 1557:                             $env{'form.person_'.$i.'_lastname'} = $userenv{'lastname'};
 1558:                         }
 1559:                         if ($env{'form.person_'.$i.'_firstname'} eq '') {
 1560:                             $env{'form.person_'.$i.'_firstname'} = $userenv{'firstname'};
 1561:                         }
 1562:                         if ($env{'form.person_'.$i.'_emailaddr'} eq '') {
 1563:                             $env{'form.person_'.$i.'_emailaddr'} = $userenv{'permanentemail'};
 1564:                         }
 1565:                     }
 1566:                 } elsif ($personname ne '') {
 1567:                     push(@disallowed,$i);
 1568:                     $disallowmsg{$i} = &mt('[_1] was excluded because the domain is invalid','<tt>'.$personname.':'.$persondom.'</tt>');
 1569:                 }
 1570:             } elsif ($personname ne '') {
 1571:                 push(@disallowed,$i);
 1572:                 $disallowmsg{$i} = &mt('[_1] was excluded because the username or domain is invalid.','<tt>'.$personname.':'.$persondom.'</tt>');
 1573:             }
 1574:         }
 1575:         my $cnum;
 1576:         if ($env{'form.origcnum'} =~ /^($match_courseid)$/) {
 1577:             $cnum = $env{'form.origcnum'};
 1578:         } else {
 1579:             my $gentype = 'Course';
 1580:             if ($crstype eq 'community') {
 1581:                 $gentype = 'Community';
 1582:             }
 1583:             $cnum = &Apache::lonnet::generate_coursenum($dom,$gentype);
 1584:         }
 1585:         &Apache::lonnet::auto_possible_instcodes($dom,\@codetitles,\%cat_titles,
 1586:                                                  \%cat_order,\@code_order);
 1587:         if ($crstype eq 'community') {
 1588:             $r->print('<h3>'.&mt('Review community request details before submission').'</h3>');
 1589:         } else {
 1590:             $r->print('<h3>'.&mt('Review course request details before submission').'</h3>');
 1591:         }
 1592:         $r->print(&print_review($dom,\@codetitles,\%cat_titles,\%cat_order,\@code_order,'','',\@disallowed,\%disallowmsg,$instcredits).
 1593:                   '<input type="hidden" name="cnum" value="'.$cnum.'" />');
 1594:         my $fullname = &Apache::loncommon::plainname($env{'user.name'},
 1595:                                                      $env{'user.domain'});
 1596:         my $postprocess = &Apache::lonnet::auto_crsreq_update($dom,$cnum,$crstype,'review',$env{'user.name'},
 1597:                                                               $env{'user.domain'},$fullname,$env{'form.cdescr'});
 1598:         if (ref($postprocess) eq 'HASH') {
 1599:             if ($postprocess->{'reviewweb'}) {
 1600:                 $r->print($postprocess->{'reviewweb'});
 1601:             }
 1602:         }
 1603:         if ($crstype eq 'community') {
 1604:             $navtxt{'next'} = &mt('Submit community request');
 1605:         } else {
 1606:             $navtxt{'next'} = &mt('Submit course request');
 1607:         }
 1608:     }  elsif ($state eq 'process') {
 1609:         if ($crstype eq 'official') {
 1610:             &Apache::lonnet::auto_possible_instcodes($dom,\@codetitles,\%cat_titles,
 1611:                                                      \%cat_order,\@code_order);
 1612:         }
 1613:         my $lonhost = $r->dir_config('lonHostID');
 1614:         my ($storeresult,$result,$customized) = &print_request_outcome($r,$lonhost,$dom,\@codetitles,
 1615:                                                                       \@code_order,$instcredits);
 1616:         $r->print($result);
 1617:         if (($storeresult eq 'ok') || ($storeresult eq 'created')) {
 1618:             if ($storeresult eq 'ok') {
 1619:                 $r->print('<p><a href="/adm/requestcourse?action=view&state=details&showdom='.$dom.'&cnum='. $env{'form.cnum'}.'">'.
 1620:                           &mt('Modify this request').'</a>'.('&nbsp;'x4).
 1621:                           '<a href="/adm/requestcourse">'.&mt('Make another request').'</a></p>');
 1622:             }
 1623:             if (&Apache::loncoursequeueadmin::author_prompt()) {
 1624:                 unless ($customized) {
 1625:                     &print_author_prompt($r,$env{'form.action'},$env{'form.cnum'},$env{'form.showdom'},
 1626:                                          $env{'form.crstype'},$storeresult);
 1627:                 }
 1628:             } elsif ($storeresult eq 'created') {
 1629:                 unless ($customized) {
 1630:                     $r->print('<p><a href="/adm/requestcourse">'.&mt('Make another request').'</a></p>');
 1631:                 }
 1632:             }
 1633:         }
 1634:     } elsif ($state eq 'reqauthor') {
 1635:         my ($result,@links); 
 1636:         if ($env{'form.requestauthor'}) {
 1637:             $r->print(&Apache::loncoursequeueadmin::process_reqauthor(\$result));
 1638:             if ($result eq 'created') {
 1639:                 my $role = 'au';
 1640:                 my $spec = "$role./$env{'form.showdom'}/";
 1641:                 push(@links,&mt('Enter your Authoring Space with role: [_1]',
 1642:                                 '<a href="/adm/roles?selectrole=1&amp;'.$spec.'=1">'.
 1643:                                 &Apache::lonnet::plaintext($role).'</a>'));
 1644:             }
 1645:         }
 1646:         if (($env{'form.disposition'} eq 'created') &&
 1647:             ($env{'form.cnum'} =~ /^$match_courseid$/) &&
 1648:             ($env{'form.showdom'} =~ /^$match_domain$/)) {
 1649:             my ($spec,$area,$role,$type);
 1650:             my $role = 'cc';
 1651:             my $spec = "$role./$env{'form.showdom'}/$env{'form.cnum'}";
 1652:             my $type = 'Course';
 1653:             if ($env{'form.crstype'} eq 'community') {
 1654:                 $type = 'Community';
 1655:             }
 1656:             my $showrole = &Apache::lonnet::plaintext($role,$type);
 1657:             unshift(@links,&mt('Enter new course with role: [_1]',
 1658:                                '<a href="/adm/roles?selectrole=1&amp;'.$spec.'=1">'.$showrole.'</a>'));
 1659:         }
 1660:         if (@links > 1) {
 1661:             $r->print(&mt('New roles will be listed on your [_1]Roles[_2] page.',
 1662:                           '<a href="/adm/roles">','</a>').'&nbsp'.&mt('Choose a role:').
 1663:                        '<ul>');
 1664:             foreach my $link (@links) {
 1665:                 $r->print('<li>'.$link.'</li>');
 1666:             }
 1667:             $r->print('</ul>');
 1668:         } elsif (@links == 1) {
 1669:             $r->print('<p>'.$links[0].'</p>');
 1670:         }
 1671:     }
 1672:     my @excluded = &get_excluded_elements($dom,$states,$action,$state,$showcredits);
 1673:     if ($state eq 'personnel') {
 1674:         push(@excluded,'persontotal');
 1675:     }
 1676:     if ($state eq 'review') {
 1677:         if (@disallowed > 0) {
 1678:             my @items = qw(uname dom lastname firstname emailaddr hidedom role newsec);
 1679:             my @currsecs = &current_lc_sections();
 1680:             if (@currsecs) {
 1681:                 push(@items,'sec');
 1682:             }
 1683:             my $count = 0;
 1684:             for (my $i=0; $i<$env{'form.persontotal'}; $i++) {
 1685:                 unless ($env{'form.person_'.$i.'_uname'} eq '') {
 1686:                     if (grep(/^$i$/,@disallowed)) {
 1687:                         foreach my $item (@items) {
 1688:                             $env{'form.person_'.$i.'_'.$item} = '';
 1689:                         }
 1690:                     } else { 
 1691:                         foreach my $item (@items) {
 1692:                             $env{'form.person_'.$count.'_'.$item} = $env{'form.person_'.$i.'_'.$item};
 1693:                         }
 1694:                     }
 1695:                 }
 1696:                 $count ++;
 1697:             }
 1698:             $env{'form.persontotal'} = $count;
 1699:         }
 1700:     }
 1701:     if ($state eq 'enrollment') {
 1702:         push(@excluded,('sectotal','crosslisttotal'));
 1703:     }
 1704:     if (($state eq 'process') || ($state eq 'reqauthor')) {
 1705:         $r->print('</form>');
 1706:     } else {
 1707:         $r->print(&Apache::lonhtmlcommon::echo_form_input(\@excluded).'</form>');
 1708:         &display_navbuttons($r,$dom,$formname,$prev,$navtxt{'prev'},$next,
 1709:                             $navtxt{'next'},$state);
 1710:     }
 1711:     return;
 1712: }
 1713: 
 1714: sub print_author_prompt {
 1715:     my ($r,$action,$cnum,$showdom,$crstype,$storeresult) = @_;
 1716:     $r->print('<h3>'.&mt('Access to Authoring Space').'</h3>'.
 1717:               '<p>'.
 1718:               &mt('Although assessment items can be created directly inside a course, such items only use part of the assessment capabilities of LON-CAPA.').
 1719:               '<br />'.
 1720:               &mt('By contrast, items created in Authoring Space, then imported into a course, can use all of the features of the assessment engine.').'</p>'.
 1721:               '<p>'.&mt('Request Authoring Space access now?').
 1722:               '<span class="LC_nobreak">&nbsp;'.
 1723:               '<label><input type="radio" name="requestauthor" value="1" />'.&mt('Yes').'</label>'.
 1724:               ('&nbsp;'x2).
 1725:               '<label><input type="radio" name="requestauthor" value="0" checked="checked"/>'.&mt('No').'</label>'.
 1726:               '</span></p>'.
 1727:               '<input type="submit" name="newauthor" value="'.&mt('Submit authoring request').'" />'.
 1728:               '<input type="hidden" name="state" value="reqauthor" />'.
 1729:               '<input type="hidden" name="action" value="'.$action.'" />'.
 1730:               '<input type="hidden" name="cnum" value="'.$cnum.'" />'.
 1731:               '<input type="hidden" name="showdom" value="'.$showdom.'" />'.
 1732:               '<input type="hidden" name="crstype" value="'.$crstype.'" />'.
 1733:               '<input type="hidden" name="disposition" value="'.$storeresult.'" />'.
 1734:               '<br />');
 1735: }    
 1736: 
 1737: sub get_usertype {
 1738:     my ($persondom,$personname,$curr_rules,$got_rules) = @_;
 1739:     my ($rules,$ruleorder) =
 1740:         &Apache::lonnet::inst_userrules($persondom,'username');
 1741:     my $usertype = &Apache::lonuserutils::check_usertype($persondom,$personname,
 1742:                                                          $rules,$curr_rules,$got_rules);
 1743:     return $usertype;
 1744: }
 1745: 
 1746: sub check_newuser_rules {
 1747:     my ($persondom,$personname,$alerts,$rulematch,$inst_results,$curr_rules,
 1748:         $got_rules) = @_;
 1749:     my $allowed = 1;
 1750:     my $newuser = 1;
 1751:     my ($checkhash,$userchkmsg,$authtype,$authparam);
 1752:     my $checks = { 'username' => 1 };
 1753:     $checkhash->{$personname.':'.$persondom} = { 'newuser' => $newuser };
 1754:     &Apache::loncommon::user_rule_check($checkhash,$checks,$alerts,$rulematch,
 1755:                                         $inst_results,$curr_rules,$got_rules);
 1756:     if (ref($alerts->{'username'}) eq 'HASH') {
 1757:         if (ref($alerts->{'username'}{$persondom}) eq 'HASH') {
 1758:             my $domdesc =
 1759:                 &Apache::lonnet::domain($persondom,'description');
 1760:             if ($alerts->{'username'}{$persondom}{$personname}) {
 1761:                 if (ref($curr_rules->{$persondom}) eq 'HASH') {
 1762:                     $userchkmsg =
 1763:                         &Apache::loncommon::instrule_disallow_msg('username',
 1764:                                                                   $domdesc,1).
 1765:                         &Apache::loncommon::user_rule_formats($persondom,
 1766:                             $domdesc,$curr_rules->{$persondom}{'username'},
 1767:                             'username');
 1768:                 }
 1769:                 $allowed = 0;
 1770:             }
 1771:         }
 1772:     }
 1773:     if ($allowed) {
 1774:         if (ref($rulematch) eq 'HASH') {
 1775:             if (ref($rulematch->{$personname.':'.$persondom}) eq 'HASH') {
 1776:                 my $matchedrule = $rulematch->{$personname.':'.$persondom}{'username'};
 1777:                 my ($rules,$ruleorder) =
 1778:                     &Apache::lonnet::inst_userrules($persondom,'username');
 1779:                 if (ref($rules) eq 'HASH') {
 1780:                     if (ref($rules->{$matchedrule}) eq 'HASH') {
 1781:                         $authtype = $rules->{$matchedrule}{'authtype'};
 1782:                         $authparam = $rules->{$matchedrule}{'authparm'};
 1783:                     }
 1784:                 }
 1785:             }
 1786:         }
 1787:     }
 1788:     return ($allowed,$userchkmsg,$authtype,$authparam);
 1789: }
 1790: 
 1791: sub get_excluded_elements {
 1792:     my ($dom,$states,$action,$state,$showcredits) = @_;
 1793:     my @excluded = ('counter');
 1794:     my ($elements,$instcredits) = &form_elements($dom,$showcredits);
 1795:     if (ref($states) eq 'HASH') {
 1796:         if (ref($states->{$action}) eq 'ARRAY') {
 1797:             my @items = @{$states->{$action}};
 1798:             my $numitems = scalar(@items);
 1799:             if ($numitems) {
 1800:                 for (my $i=$numitems-1; $i>=0; $i--) {
 1801:                     if ((ref($elements) eq 'HASH') && 
 1802:                         (ref($elements->{$action}) eq 'HASH')) {
 1803:                         if (ref($elements->{$action}{$items[$i]}) eq 'HASH') {
 1804:                             foreach my $key (keys(%{$elements->{$action}{$items[$i]}})) {
 1805:                                 push(@excluded,$key);
 1806:                             }
 1807:                         }
 1808:                     }
 1809:                     last if ($items[$i] eq $state);
 1810:                 }
 1811:             }
 1812:         }
 1813:     }
 1814:     if (grep(/^instcode_/,@excluded)) {
 1815:         push(@excluded,'instcode');
 1816:     }
 1817:     return @excluded;
 1818: }
 1819: 
 1820: sub print_enrollment_menu {
 1821:     my ($formname,$instcode,$dom,$codetitles,$cat_titles,$cat_order,$code_order,
 1822:         $showcredits,$instcredits,$invalidcrosslist) =@_;
 1823:     my ($sections,$autoenroll,$access_dates,$output,$hasauto,$hascredits,
 1824:         $creditsrow,$domdefcredits);
 1825:     my $starttime = time;
 1826:     my $endtime = time+(6*30*24*60*60); # 6 months from now, approx
 1827: 
 1828:     my %accesstitles = (
 1829:                           'start' => 'Default start access',
 1830:                            'end'   => 'Default end access',
 1831:                        );
 1832:     my %enrolltitles = (
 1833:                            'start' => 'Start auto-enrollment',
 1834:                            'end'   => 'End auto-enrollment',
 1835:                        );
 1836:     if ($showcredits) {
 1837:         unless ($env{'form.crstype'} eq 'community') {
 1838:             my %domdefs = &Apache::lonnet::get_domain_defaults($dom);
 1839:             $domdefcredits = $domdefs{$env{'form.crstype'}.'credits'};
 1840:         }
 1841:     }
 1842:     if ($env{'form.crstype'} eq 'official') {
 1843:         if (&Apache::lonnet::auto_run('',$dom)) {
 1844:             $output = &show_invalid_crosslists($invalidcrosslist);
 1845:             my ($section_form,$crosslist_form);
 1846:             if ($instcode ne '') {
 1847:                 $section_form = &inst_section_selector($dom,$instcode);
 1848:                 if ($section_form eq '') {
 1849:                     my $sectotal = $env{'form.sectotal'};
 1850:                     if (!$sectotal) {
 1851:                         $sectotal = 1;
 1852:                     }
 1853:                     if ($env{'form.addsection'}) {
 1854:                         $sectotal ++;
 1855:                     }
 1856:                     for (my $i=0; $i<$sectotal; $i++) {
 1857:                         $section_form .= &sections_form($dom,$instcode,$i);
 1858:                     }
 1859:                     if ($section_form) {
 1860:                         $section_form .=
 1861:                     &Apache::lonhtmlcommon::row_title(&mt('Add another')).
 1862:                     '<input name="sectotal" type="hidden" value="'.$sectotal.'" />'.
 1863:                     '<input name="addsection" type="checkbox" value="'.$sectotal.'"'.
 1864:                     ' onclick="javascript:nextPage(document.'.$formname.",'".$env{'form.state'}.
 1865:                    "'".');" />'.&mt('Add?').&Apache::lonhtmlcommon::row_closure();
 1866:                     }
 1867:                 }
 1868:             }
 1869:             if ($section_form) {
 1870:                 $sections = &Apache::lonhtmlcommon::row_headline().
 1871:                             '<h3>'.&Apache::loncommon::help_open_topic('Course_Request_Sections').
 1872:                             '&nbsp;'.&mt('Sections for auto-enrollment').'</h3>'.
 1873:                             &Apache::lonhtmlcommon::row_closure(1).
 1874:                             $section_form;
 1875:             }
 1876:             my $crosslisttotal = $env{'form.crosslisttotal'};
 1877:             if (!$crosslisttotal) {
 1878:                 $crosslisttotal = 1;
 1879:             }
 1880:             if ($env{'form.addcrosslist'}) {
 1881:                 $crosslisttotal ++;
 1882:             }
 1883:             for (my $i=0; $i<$crosslisttotal; $i++) {
 1884:                 $crosslist_form .= &coursecode_form($dom,'crosslist',$codetitles, 
 1885:                                                   $cat_titles,$cat_order,$i);
 1886:             }
 1887:             if ($crosslist_form) { 
 1888:                 $crosslist_form .= 
 1889:                     &Apache::lonhtmlcommon::row_title(&mt('Add another')).
 1890:                     '<input name="crosslisttotal" type="hidden" value="'.$crosslisttotal.'" />'.
 1891:                     '<input name="addcrosslist" type="checkbox" value="'.$crosslisttotal.'"'.
 1892:                     ' onclick="javascript:nextPage(document.'.$formname.",'".$env{'form.state'}.
 1893:                    "'".');" />'.&mt('Add?').&Apache::lonhtmlcommon::row_closure();
 1894:                 $sections .=  &Apache::lonhtmlcommon::row_headline.
 1895:                               '<h3>'.&Apache::loncommon::help_open_topic('Course_Request_Crosslist').'&nbsp;'.&mt('Crosslisted courses for auto-enrollment').'</h3>'.
 1896:                               &Apache::lonhtmlcommon::row_closure(1).
 1897:                               $crosslist_form;
 1898:             }
 1899:             $hasauto = 1;
 1900:             $autoenroll = 
 1901:                 &Apache::lonhtmlcommon::row_title(&Apache::loncommon::help_open_topic('Course_Request_Autoadd').'&nbsp;'.&mt('Add registered students automatically')).
 1902:                 '<span class="LC_nobreak"><label>'.
 1903:                 '<input type="radio" name="autoadds" value="1">'.
 1904:                 &mt('Yes').'</label>'.('&nbsp;'x3).'<label>'.
 1905:                 '<input type="radio" name="autoadds" value="0" checked="checked">'.
 1906:                 &mt('No').'</label></span>'.
 1907:                 &Apache::lonhtmlcommon::row_closure(1).
 1908:                 &Apache::lonhtmlcommon::row_title(&Apache::loncommon::help_open_topic('Course_Request_Autodrop').'&nbsp;'.&mt('Drop unregistered students automatically')).
 1909:                 '<span class="LC_nobreak"><label>'.
 1910:                 '<input type="radio" name="autodrops" value="1">'.
 1911:                 &mt('Yes').'</label>'.('&nbsp;'x3).'<label>'.
 1912:                 '<input type="radio" name="autodrops" value="0" checked="checked">'.
 1913:                 &mt('No').'</label></span>'. 
 1914:                 &Apache::lonhtmlcommon::row_closure(1).
 1915:                 &date_setting_table($starttime,$endtime,$formname,'enroll',
 1916:                                     $hasauto,undef,%enrolltitles);
 1917:             if ($showcredits) {
 1918:                 if ($instcredits) {
 1919:                     $creditsrow = &mt('[quant,_1,credit]',$instcredits);
 1920:                 } else {
 1921:                     $creditsrow = '<span class="LC_nobreak">'.
 1922:                                   '<input type="text" size="3" name="coursecredits"'.
 1923:                                   ' value="'.$domdefcredits.'" />';
 1924:                 }
 1925:                 $hascredits = 1;
 1926:             }
 1927:         }
 1928:     } elsif (($env{'form.crstype'} eq 'unofficial') || ($env{'form.crstype'} eq 'textbook')) {
 1929:         if ($showcredits) {
 1930:             $creditsrow = '<span class="LC_nobreak">'.
 1931:                           '<input type="text" size="3" name="coursecredits"'.
 1932:                           ' value="'.$domdefcredits.'"/>';
 1933:             $hascredits = 1;
 1934:         }
 1935:     }
 1936:     my $access_dates = 
 1937:         &date_setting_table($starttime,$endtime,$formname,'access',$hasauto,
 1938:                             $hascredits,%accesstitles);
 1939:     $output .= &Apache::lonhtmlcommon::start_pick_box();
 1940:     if ($sections) {
 1941:         $output .=  $sections;
 1942:     }
 1943:     if ($autoenroll) {
 1944:         $output .= &Apache::lonhtmlcommon::row_headline('Auto-enroll').
 1945:                    '<h3>'.&mt('Auto-enrollment settings').'</h3>'.
 1946:                    &Apache::lonhtmlcommon::row_closure(1).
 1947:                    $autoenroll;
 1948:     }
 1949:     if ($access_dates) {
 1950:         my $header = &mt('Access dates for students');
 1951:         if ($env{'form.crstype'} eq 'community') {
 1952:             $header = &mt('Access dates for community members');
 1953:         }
 1954:         $output .= &Apache::lonhtmlcommon::row_headline('Access').
 1955:                    '<h3>'.$header.'</h3>'.
 1956:                    &Apache::lonhtmlcommon::row_closure(1).
 1957:                    $access_dates;
 1958:     }
 1959:     if ($creditsrow) {
 1960:         $output .= &Apache::lonhtmlcommon::row_headline('Credits').
 1961:                    '<h3>'.&mt('Credits earned by students').'</h3>'.
 1962:                    &Apache::lonhtmlcommon::row_closure(1).
 1963:                    &Apache::lonhtmlcommon::row_title(&mt('Default credits')).
 1964:                    $creditsrow.
 1965:                    &Apache::lonhtmlcommon::row_closure(1);
 1966:     }
 1967:     return '<div>'.&Apache::lonhtmlcommon::start_pick_box().$output.
 1968:            &Apache::lonhtmlcommon::end_pick_box().'</div>';
 1969: }
 1970: 
 1971: sub show_invalid_crosslists {
 1972:     my ($invalidcrosslist) = @_;
 1973:     my $output;
 1974:     if (ref($invalidcrosslist) eq 'ARRAY') {
 1975:         if (@{$invalidcrosslist} > 0) {
 1976:             $output = '<div class="LC_warning">'.
 1977:                       &mt('The following crosslisted courses were invalid:').'<ul>';
 1978:             foreach my $item (@{$invalidcrosslist}) {
 1979:                 $output .= '<li>'.$item.'</li>';
 1980:             }
 1981:             $output .= '</ul></div><br />';
 1982:         }
 1983:     }
 1984:     return $output;
 1985: }
 1986: 
 1987: 
 1988: sub inst_section_selector {
 1989:     my ($dom,$instcode) = @_;
 1990:     my @sections = &Apache::lonnet::auto_get_sections(undef,$dom,$instcode);
 1991:     my $sectotal = scalar(@sections);
 1992:     my $output;
 1993:     if ($sectotal) {
 1994:         $output .=  &Apache::lonhtmlcommon::row_title(&mt('Sections of [_1]',$instcode)).
 1995:                     &Apache::loncommon::start_data_table().
 1996:                     &Apache::loncommon::start_data_table_row().
 1997:                     '<th>'.&mt('Include?').'<input type="hidden" name="sectotal" '.
 1998:                     'value="'.$sectotal.'"  /></th>'.
 1999:                     '<th>'.&mt('Institutional Section').'</th>'.
 2000:                     '<th>'.&Apache::loncommon::help_open_topic('Course_Request_LCSection').
 2001:                           '&nbsp;'.&mt('LON-CAPA section').'</th>'.
 2002:                     &Apache::loncommon::end_data_table_row();
 2003:         for (my $i=0; $i<@sections; $i++) {
 2004:             my $colflag = $i%2;
 2005:             my $secon = ' checked="checked"';
 2006:             my $secoff = '';
 2007:             if ($env{'form.origcnum'}) {
 2008:                 $secoff = $secon;
 2009:                 $secon='';
 2010:             }
 2011:             $output .= &Apache::loncommon::start_data_table_row().
 2012:                        '<td><label><input type="radio" name="sec_'.$i.
 2013:                        '"'.$secon.' value="1" />'.&mt('Yes').'</label>'.
 2014:                        ('&nbsp;'x2).'<label><input type="radio" name="sec_'.$i.
 2015:                         '"'.$secoff.' value="0" />'.&mt('No').'</label></td>'.
 2016:                        '<td align="center">'.$sections[$i].
 2017:                        '<input type="hidden" name="secnum_'.$i.'" value="'.
 2018:                        $sections[$i].'" /></td>'.
 2019:                        '<td><input type="text" size="10" name="loncapasec_'.$i.
 2020:                        '" value="'.$sections[$i].'" /></td>'.
 2021:                        &Apache::loncommon::end_data_table_row();
 2022:         }
 2023:         $output .= &Apache::loncommon::end_data_table().
 2024:                    &Apache::lonhtmlcommon::row_closure();
 2025:     }
 2026:     return $output;
 2027: }
 2028: 
 2029: sub date_setting_table {
 2030:     my ($starttime,$endtime,$formname,$prefix,$hasauto,$hascredits,%datetitles)=@_;
 2031:     my ($perpetual,$table);
 2032:     my $startform = &Apache::lonhtmlcommon::date_setter($formname,$prefix.'start',
 2033:                                                         $starttime,'','','',1,'','','',1);
 2034:     my $endform = &Apache::lonhtmlcommon::date_setter($formname,$prefix.'end',
 2035:                                                       $endtime,'','','',1,'','','',1);
 2036:     my $closure = '';
 2037:     if ($prefix eq 'access') {
 2038:         $perpetual = ' <span class="LC_nobreak"><label>'.
 2039:                      '<input type="checkbox" name="no_end_date" />'.
 2040:                      &mt('No end date').'</label></span>';
 2041:         unless ($hascredits) {
 2042:             $closure = '1';
 2043:         }
 2044:     }
 2045: 
 2046:     my %help_item = (
 2047:                       access => {
 2048:                                   start => 'Course_Request_Access_Start', 
 2049:                                   end   => 'Course_Request_Access_End',
 2050:                                 },
 2051:                       enroll => {
 2052:                                   start => 'Course_Request_Enroll_Start',
 2053:                                   end   => 'Course_Request_Enroll_End',
 2054:                                 },
 2055:                      );
 2056:     if ($hasauto) {
 2057:         $help_item{'access'}{'start'} = 'Course_Request_RegAccess_Start';
 2058:         $help_item{'access'}{'end'}   = 'Course_Request_RegAccess_End';
 2059:     }
 2060: 
 2061:     $table = &Apache::lonhtmlcommon::row_title(&Apache::loncommon::help_open_topic($help_item{$prefix}{'start'}).
 2062:              '&nbsp;'.&mt($datetitles{'start'})).$startform.
 2063:              &Apache::lonhtmlcommon::row_closure(1).
 2064:              &Apache::lonhtmlcommon::row_title(&Apache::loncommon::help_open_topic($help_item{$prefix}{'end'}).
 2065:              '&nbsp;'.&mt($datetitles{'end'})).$endform.$perpetual.
 2066:              &Apache::lonhtmlcommon::row_closure($closure);
 2067:     return $table;
 2068: }
 2069: 
 2070: sub print_personnel_menu {
 2071:     my ($dom,$formname,$crstype,$invalidcrosslist) = @_;
 2072:     my $output;
 2073:     if ($crstype eq 'official') {
 2074:         if (&Apache::lonnet::auto_run('',$dom)) {
 2075:             $output .= &show_invalid_crosslists($invalidcrosslist);
 2076:         }  
 2077:     }
 2078:     $output .= '<div>'.&Apache::lonhtmlcommon::start_pick_box();
 2079:     my $persontotal = $env{'form.persontotal'};
 2080:     if ((!defined($persontotal)) || (!$persontotal)) {
 2081:         $persontotal = 1;
 2082:     }
 2083:     if ($env{'form.addperson'}) {
 2084:         $persontotal ++;
 2085:     }
 2086:     my @items = ('uname','dom','lastname','firstname','emailaddr','hidedom');
 2087: 
 2088:     my $type = 'Course';
 2089:     if ($crstype eq 'community') {
 2090:         $type = 'Community';
 2091:     }
 2092:     my $roleoptions;
 2093:     my @roles = &Apache::lonuserutils::roles_by_context('course','',$type);
 2094:     foreach my $role (@roles) {
 2095:         my $plrole = &Apache::lonnet::plaintext($role,$type);
 2096:         $roleoptions .= '  <option value="'.$role.'">'.$plrole.'</option>'."\n";
 2097:     }
 2098:     my %customroles=&Apache::lonuserutils::my_custom_roles();
 2099:     if (keys(%customroles) > 0) {
 2100:         foreach my $cust (sort(keys(%customroles))) {
 2101:             my $custrole="cr/$env{'user.domain'}/$env{'user.name'}/$cust";
 2102:             $roleoptions .= '  <option value="'.$custrole.'">'.$cust.'</option>'."\n";
 2103:         }
 2104:     }
 2105: 
 2106:     my @currsecs = &current_lc_sections();
 2107: 
 2108:     my ($existtitle,$existops,$existmult,$newtitle,$seccolspan);
 2109:     if (@currsecs) {
 2110:         my $existsize = scalar(@currsecs);
 2111:         if ($existsize > 3) {
 2112:             $existsize = 3;
 2113:         }
 2114:         if ($existsize > 1) {
 2115:             $existmult = ' multiple="multiple" size="'.$existsize.'" ';
 2116:         }
 2117:         @currsecs = sort { $a <=> $b } (@currsecs);
 2118:         $existtitle = &mt('Official').':&nbsp;';
 2119:         $existops = '<option value="">'.&mt('None').'</option>';
 2120:         foreach my $sec (@currsecs) {
 2121:             $existops .= '<option value="'.$sec.'">'.$sec.'</option>'."\n";
 2122:         }
 2123:         $seccolspan = ' colspan="2"';
 2124:         $newtitle = &mt('Other').':&nbsp;';
 2125:     }
 2126: 
 2127:     if ($persontotal) {
 2128:         my %lt = &Apache::lonlocal::texthash(
 2129:             community => 'Requestor is automatically assigned Coordinator role.',
 2130:             official => 'Requestor is automatically assigned Course Coordinator role.',
 2131:         );
 2132:         $lt{'unofficial'} = $lt{'official'};
 2133:         $lt{'textbook'} = $lt{'official'};
 2134:         $lt{'placement'} = $lt{'official'};
 2135:         $output .= &Apache::lonhtmlcommon::row_headline().
 2136:                   '<h3>'.&Apache::loncommon::help_open_topic('Course_Request_Personnel').'&nbsp;'.$lt{$crstype}.' '.&mt('Include other personnel?').'</h3>';
 2137:     }
 2138:     my $cansearch = 1;
 2139:     my @alldoms = &Apache::lonnet::all_domains();
 2140:     if (@alldoms == 1) {
 2141:         my %domsrch = &Apache::lonnet::get_dom('configuration',
 2142:                                                ['directorysrch'],$alldoms[0]);
 2143:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
 2144:             if ((!$domsrch{'directorysrch'}{'available'}) &&
 2145:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
 2146:                 $cansearch = 0;
 2147:             }
 2148:         }
 2149:     }
 2150:     my ($trusted,$untrusted) = &Apache::lonnet::trusted_domains('enroll',$dom);
 2151:     for (my $i=0; $i<$persontotal; $i++) {
 2152:         my @linkargs = map { 'person_'.$i.'_'.$_ } (@items);
 2153:         my $linkargstr = join("','",@linkargs);
 2154:         my $uname_form = '<input type="text" name="person_'.$i.'_uname" value="" size="20" />';
 2155:         my $onchange = 'javascript:fix_domain('."'$formname','person_".$i."_dom',".
 2156:                        "'person_".$i."_hidedom','person_".$i."_uname'".');';
 2157:         my $udom_form = &Apache::loncommon::select_dom_form($dom,'person_'.$i.'_dom','',
 2158:                                                             1,$onchange,undef,$trusted,$untrusted).
 2159:                         '<input type="hidden" name="person_'.$i.'_hidedom" value="" />';
 2160:         my %form_elems;
 2161:         foreach my $item (@items) {
 2162:             next if (($item eq 'dom') || ($item eq 'uname') || ($item eq 'hidedom'));
 2163:             $form_elems{$item} = '<input type="text" name="person_'.$i.'_'.$item.'" '.
 2164:                                  'value="" readonly="readonly" />';
 2165:         }
 2166:         my $roleselector = '<select name="person_'.$i.'_role">'."\n".
 2167:                            $roleoptions.'</select>';
 2168:         my $sectionselector;
 2169:         if (@currsecs) {
 2170:             $sectionselector = $existtitle.'<select name="person_'.$i.'_sec"'.
 2171:                                $existmult.'>'."\n".$existops.'</select>'.('&nbsp;' x3);
 2172:         }
 2173:         $sectionselector .= $newtitle.
 2174:             '<input type="text" name="person_'.$i.'_newsec" size="15" value="" />'."\n";
 2175:         my $usersrchlink;
 2176:         if ($cansearch) {
 2177:             my $usersrchlinktxt = &mt('Search for user');
 2178:             $usersrchlink = &Apache::loncommon::selectuser_link($formname,@linkargs,$dom,
 2179:                                                                 $usersrchlinktxt);
 2180:         } else {
 2181:             $usersrchlink = '&nbsp;';
 2182:         }
 2183:         my $userchklinktxt = &mt('Check username');
 2184:         my $userchklink = &Apache::loncommon::selectuser_link($formname,@linkargs,$dom,
 2185:                             $userchklinktxt,'checkusername');
 2186:         $output .= 
 2187:             &Apache::lonhtmlcommon::row_title(&mt('Additional Personnel')).
 2188:             '<table><tr><td align="center" valign="middle"><b>'.$usersrchlink.'</b></td>'."\n".
 2189:             '<td align="left" valign="top" colspan="2"><span class="LC_nobreak">'.
 2190:             &mt('Username').':&nbsp;'.$uname_form.'&nbsp;'.$userchklink.'</span><br />'."\n".
 2191:             '<span class="LC_nobreak">'.&mt('Domain').':&nbsp;'.$udom_form.'</span></td>'.
 2192:             '</tr>'."\n".'<tr>'.
 2193:             '<td align="center" valign="top">'.&mt('First Name').'<br />'.$form_elems{'firstname'}.'</td>'."\n".
 2194:             '<td align="center" valign="top">'.&mt('Last Name').'<br />'.$form_elems{'lastname'}.'</td>'."\n".
 2195:             '<td align="center" valign="top">'.&mt('E-mail').'<br />'.$form_elems{'emailaddr'}.'</td></tr>'."\n".
 2196:             '<tr><td align="center" valign="top">'.&Apache::loncommon::help_open_topic('Course_Roles').'&nbsp;'.&mt('Role').'<br />'.$roleselector.'</td>'."\n".
 2197:             '<td'.$seccolspan.' align="center" valign="top">'.
 2198:             &Apache::loncommon::help_open_topic('Course_Request_Rolesection').'&nbsp;'.&mt('LON-CAPA Section(s)').'<br />'.$sectionselector.'</td>'."\n".
 2199:             '</tr></table>'.&Apache::lonhtmlcommon::row_closure();
 2200:     }
 2201:     $output .= &Apache::lonhtmlcommon::row_title(&mt('Add another')).
 2202:                '<input name="persontotal" type="hidden" value="'.$persontotal.'" />'.
 2203:                '<input name="addperson" type="checkbox" value="'.$persontotal.'"'.
 2204:                ' onclick="javascript:nextPage(document.'.$formname.",'".$env{'form.state'}.
 2205:                "'".');" />'.&mt('Add?').&Apache::lonhtmlcommon::row_closure(1).
 2206:                &Apache::lonhtmlcommon::end_pick_box().'</div>';
 2207:     if ($crstype eq 'community') {
 2208:         $output .= '<p>'.&mt('You may also add users later, once the community has been created, by using the "Manage community users" link, accessible from the "Main Menu".').'</p>';
 2209:     } else {
 2210:         $output .= '<p>'.&mt('You may also add users later, once the course has been created, by using the "Manage course users" link, accessible from the "Main Menu".').'</p>';
 2211:     }
 2212:     return $output;
 2213: }
 2214: 
 2215: sub current_lc_sections {
 2216:     my @currsecs;
 2217:     if ($env{'form.sectotal'}) {
 2218:         for (my $i=0; $i<$env{'form.sectotal'}; $i++) {
 2219:             if ($env{'form.sec_'.$i}) { 
 2220:                 if (defined($env{'form.loncapasec_'.$i})) {
 2221:                     my $lcsec = $env{'form.loncapasec_'.$i};
 2222:                     unless (grep(/^\Q$lcsec\E$/,@currsecs)) {
 2223:                         push(@currsecs,$lcsec);
 2224:                     }
 2225:                 }
 2226:             }
 2227:         }
 2228:     }
 2229:     return @currsecs;
 2230: }
 2231: 
 2232: sub sorted_request_history {
 2233:     my ($dom,$action,$curr_req) = @_;
 2234:     my ($after,$before,$statusfilter,$crstypefilter);
 2235:     if ($env{'form.status'} ne '') {
 2236:         $statusfilter = $env{'form.status'};
 2237:     }
 2238:     if ($env{'form.crstype'} ne '') {
 2239:         $crstypefilter = $env{'form.crstype'};
 2240:     }
 2241:     if (ref($curr_req) eq 'HASH') {
 2242:         $after = $curr_req->{'requested_after_date'},
 2243:         $before = $curr_req->{'requested_before_date'};
 2244:         $statusfilter = $curr_req->{'status'};
 2245:         $crstypefilter = $curr_req->{'crstype'};
 2246:     }
 2247:     my %statusinfo = &Apache::lonnet::dump('courserequests',$env{'user.domain'},
 2248:                                            $env{'user.name'},'^status:'.$dom);
 2249:     my %queue_by_date;
 2250:     my ($types,$typenames) = &Apache::loncommon::course_types();
 2251:     foreach my $key (keys(%statusinfo)) {
 2252:         if ($action eq 'view') {
 2253:             next unless (($statusinfo{$key} eq 'approval') || ($statusinfo{$key} eq 'pending'));
 2254:         } else {
 2255:             next unless (($statusfilter eq 'any') ||
 2256:                           ($statusfilter eq $statusinfo{$key}));
 2257:         }
 2258:         (undef,my($cdom,$cnum)) = split(':',$key);
 2259:         next if ($cdom ne $dom);   
 2260:         my $requestkey = $cdom.'_'.$cnum;
 2261:         if ($requestkey =~ /^($match_domain)_($match_courseid)$/) {
 2262:             my %history = &Apache::lonnet::restore($requestkey,'courserequests',
 2263:                                                    $env{'user.domain'},$env{'user.name'});
 2264:             my $entry;
 2265:             my $reqtime = $history{'reqtime'};
 2266:             my $lastupdate = $history{'timestamp'};
 2267:             my $crstype = $history{'crstype'};
 2268:             my $disposition = $history{'disposition'};
 2269:             my $status = $history{'status'};
 2270:             my $uniquecode = $history{'code'}; 
 2271:             if ($action eq 'view') {
 2272:                 next if ((exists($history{'status'})) && ($history{'status'} eq 'created'));
 2273:             } else {
 2274:                 next if (($reqtime < $after) || ($reqtime > $before));
 2275:             }
 2276:             next unless (($crstypefilter eq 'any') || 
 2277:                          ($crstypefilter eq $crstype));
 2278:             if ($action eq 'view') {
 2279:                 next unless (($disposition eq 'approval') || 
 2280:                              ($disposition eq 'pending'));
 2281:             }
 2282:             if (ref($history{'details'}) eq 'HASH') {
 2283:                 $entry = $requestkey.':'.$crstype.':'.
 2284:                          &escape($history{'details'}{'cdescr'});
 2285:                 if ($action eq 'log') {
 2286:                     $entry .= ':'.$uniquecode.':'.$lastupdate.':';
 2287:                     if ($statusinfo{$key} ne '') {
 2288:                         $entry .= $statusinfo{$key};
 2289:                     } elsif ($status ne '') {
 2290:                         $entry .= $status;
 2291:                     } else {
 2292:                         $entry .= $disposition;
 2293:                     }
 2294:                 }
 2295:                 if ($crstype eq 'official') {
 2296:                     $entry .= ':'.&escape($history{'details'}{'instcode'}); 
 2297:                 }
 2298:             }
 2299:             if ($entry ne '') {
 2300:                 if (exists($queue_by_date{$reqtime})) {
 2301:                     if (ref($queue_by_date{$reqtime}) eq 'ARRAY') {
 2302:                         push(@{$queue_by_date{$reqtime}},$entry);
 2303:                     }
 2304:                 } else {
 2305:                     @{$queue_by_date{$reqtime}} = ($entry);
 2306:                 }
 2307:             }
 2308:         }
 2309:     }
 2310:     return %queue_by_date;
 2311: }
 2312: 
 2313: sub print_request_status {
 2314:     my ($dom,$action) = @_;
 2315:     my %queue_by_date = &sorted_request_history($dom,$action);
 2316:     my @sortedtimes = sort {$a <=> $b} (keys(%queue_by_date));
 2317:     my $formname = 'requestcrs';
 2318:     my ($types,$typenames) = &Apache::loncommon::course_types();
 2319:     my $output = '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n".
 2320: 
 2321:               '<input type="hidden" name="state" value="'.$env{'form.state'}.'" />'."\n".
 2322:               '<input type="hidden" name="crstype" value="'.$env{'form.crstype'}.'" />'."\n".
 2323:               '<input type="hidden" name="showdom" value="" />'."\n".
 2324:               '<input type="hidden" name="cnum" value="" />'."\n";
 2325:     if (@sortedtimes > 0) {
 2326:         my $desctitle;
 2327:         if ($env{'form.crstype'} eq 'any') {
 2328:             $desctitle = &mt('Course/Community Description')
 2329:         } elsif ($env{'form.crstype'} eq 'community') {
 2330:             $desctitle = &mt('Community Description')
 2331:         } else {
 2332:             $desctitle = &mt('Course Description');
 2333:         }
 2334:         $output .= &Apache::loncommon::start_data_table().
 2335:                    &Apache::loncommon::start_data_table_header_row().
 2336:                    '<th>'.&mt('Action').'</th>'.
 2337:                    '<th>'.$desctitle.'</th>'.
 2338:                    '<th>'.&mt('Domain').'</th>';
 2339:         if ($env{'form.crstype'} eq 'any') {
 2340:             $output .= '<th>'.&mt('Type').'</th>';
 2341:         }
 2342:         if (($env{'form.crstype'} eq 'any') || ($env{'form.crstype'} eq 'official')) {
 2343:             $output .= '<th>'.&mt('Institutional Code').'</th>';
 2344:         }
 2345:         $output .= '<th>'.&mt('Date requested').'</th>'.
 2346:                    &Apache::loncommon::end_data_table_header_row();
 2347:         my $count = 0;
 2348:         foreach my $item (@sortedtimes) {
 2349:             my $showtime = &Apache::lonlocal::locallocaltime($item);
 2350:             if (ref($queue_by_date{$item}) eq 'ARRAY') {
 2351:                 foreach my $request (sort(@{$queue_by_date{$item}})) {
 2352:                     my ($key,$type,$desc,$instcode) = split(':',$request);
 2353:                     my ($cdom,$cnum) = split('_',$key);
 2354:                     $output .= &Apache::loncommon::start_data_table_row().
 2355:      '<td><input type="button" value="'.&mt('Select').'" onclick="javascript:chooseRequest('."'$cdom','$cnum'".')" /></td>'.
 2356:      '<td>'.&unescape($desc).'</td>'.
 2357:      '<td>'.$cdom.'</td>';
 2358:                     if ($env{'form.crstype'} eq 'any') {
 2359:                         my $typename;
 2360:                         if (ref($typenames) eq 'HASH') {
 2361:                             $typename = &mt($typenames->{$type});
 2362:                         }
 2363:                         if ($typename eq '') {
 2364:                             $typename = &mt('Unknown type');
 2365:                         }
 2366:                         $output .= '<td>'.$typename.'</td>';
 2367:                     }
 2368:                     if (($env{'form.crstype'} eq 'any') || 
 2369:                         ($env{'form.crstype'} eq 'official')) {
 2370:                         my $showinstcode;
 2371:                         if ($type eq 'official') {
 2372:                             $showinstcode = &unescape($instcode);
 2373:                         } else {
 2374:                             $showinstcode = &mt('Not applicable');
 2375:                         }
 2376:                         $output .= '<td>'.$showinstcode.'</td>';
 2377:                     }
 2378:                     $output .= '<td>'.$showtime.'</td>'.
 2379:                                &Apache::loncommon::end_data_table_row();
 2380:                 }
 2381:             }
 2382:         }
 2383:         $output .= &Apache::loncommon::end_data_table();
 2384:     } else {
 2385:         if ($env{'form.crstype'} eq 'any') {
 2386: $output .= '<div>'.&mt('You have no matching course or community requests awaiting approval by a Domain Coordinator or held in a queue pending administrative action at your institution.').'</div>';
 2387:         } elsif ($env{'form.crstype'} eq 'community') {
 2388:             $output .= '<div>'.&mt('You have no matching community requests awaiting approval by a Domain Coordinator or held in a queue pending administrative action at your institution.').'</div>';
 2389:         } else {
 2390:             $output .= '<div>'.&mt('You have no matching course requests awaiting approval by a Domain Coordinator or held in a queue pending administrative action at your institution.').'</div>';
 2391:         }
 2392:     }
 2393:     $output .= '
 2394: <br /><input type="button" name="prev" value="'.&mt('Back').'" onclick="javascript:backPage(document.'.$formname.",'crstype'".')" />';
 2395:     return $output;
 2396: }
 2397: 
 2398: sub print_cancel_request {
 2399:     my ($dom,$cnum) = @_;
 2400:     my $requestkey = $dom.'_'.$cnum;
 2401:     my ($result,$output);
 2402:     if ($requestkey =~ /^($match_domain)_($match_courseid)$/) {
 2403:         my %history = &Apache::lonnet::restore($requestkey,'courserequests',
 2404:                                                $env{'user.domain'},$env{'user.name'});
 2405:         my $timestamp = $history{'reqtime'};
 2406:         my $crstype = $history{'crstype'};
 2407:         my $status = $history{'status'};
 2408:         if (($status eq 'cancelled') || ($status eq 'created')) { 
 2409:             if ($status eq 'cancelled') {
 2410:                 $output = &mt('This request has already been cancelled.');
 2411:             } elsif ($status eq 'created') {
 2412:                 $output = &mt('This request has already been processed, and a course created.');
 2413:             }
 2414:             $output = &mt('No further action will be taken');
 2415:         } elsif (ref($history{'details'}) eq 'HASH') {
 2416:             my ($types,$typename) = &Apache::loncommon::course_types();
 2417:             my $showtype = $crstype;
 2418:             if (defined($typename->{$crstype})) {
 2419:                 $showtype = $typename->{$crstype}; 
 2420:             }
 2421:             $output = '<p>'.&Apache::loncommon::start_data_table().
 2422:                       &Apache::loncommon::start_data_table_header_row().
 2423:                       '<th>'.&mt('Description').'</th><th>'.&mt('Requested').'</th>'.
 2424:                       '<th>'.&mt('Type').'</th>'.
 2425:                       &Apache::loncommon::end_data_table_header_row().
 2426:                       &Apache::loncommon::start_data_table_row().
 2427:                       '<td>'.$history{details}{'cdescr'}.'</td><td>'.
 2428:                       &Apache::lonlocal::locallocaltime($timestamp).'</td>'.
 2429:                       '<td>'.$showtype.'</td>'.
 2430:                       &Apache::loncommon::end_data_table_row().
 2431:                       &Apache::loncommon::end_data_table().
 2432:                       '<br /><div class="LC_warning">';
 2433:             if ($crstype eq 'community') {
 2434:                 $output .= &mt('Cancelling the request will remove it from the queue of pending community requests').'</div>';
 2435:             } else {
 2436:                 $output .= &mt('Cancelling the request will remove it from the queue of pending course requests').'</div>';
 2437:             }
 2438:             $result = 'ok';
 2439:         } else {
 2440:             $output = '<div class="LC_error">'.&mt('No record exists for the course ID').'</div>';
 2441:         }
 2442:     } else {
 2443:         $output = '<div class="LC_error">'.&mt('Invalid course ID').'</div>';
 2444:     }
 2445:     return ($result,$output);
 2446: }
 2447: 
 2448: sub viewrequest_javascript {
 2449:     my ($formname,$next) = @_;
 2450:     return <<"ENDJS";
 2451: 
 2452: function chooseRequest(cdom,cnum) {
 2453:     document.$formname.showdom.value = cdom;
 2454:     document.$formname.cnum.value = cnum;
 2455:     nextPage(document.$formname,'$next');
 2456: }
 2457: 
 2458: ENDJS
 2459: }
 2460: 
 2461: sub viewdetails_javascript {
 2462:     my ($formname) = @_;
 2463:     return << "ENDJS";
 2464: 
 2465: function nextPage(formname,nextstate) {
 2466:     if (nextstate == "modify") { 
 2467:         formname.state.value = "personnel";
 2468:         formname.action.value = "new";
 2469:     } else {
 2470:         formname.state.value = nextstate;
 2471:     }
 2472:     formname.submit();
 2473: }
 2474: 
 2475: function backPage(formname,prevstate) {
 2476:     formname.state.value = prevstate;
 2477:     formname.submit();
 2478: }
 2479: 
 2480: ENDJS
 2481: }
 2482: 
 2483: sub viewcancel_javascript {
 2484:     my $alert = &mt('Are you sure you want to cancel this request?')."\n".
 2485:                 &mt('Your request will be removed.');
 2486:     &js_escape(\$alert);
 2487:     return << "ENDJS";
 2488: function nextPage(formname,nextstate) {
 2489:     if (confirm('$alert')) {
 2490:         formname.state.value = nextstate;
 2491:         formname.submit();
 2492:     }
 2493:     return;
 2494: }
 2495: 
 2496: ENDJS
 2497: }
 2498: 
 2499: sub print_request_logs {
 2500:     my ($r,$dom,$jscript,$loaditems,$crumb,$usetabs) = @_;
 2501:     my $title;
 2502:     if ($env{'form.crstype'} eq 'community') {
 2503:         $title = 'Community Request Logs';
 2504:     } elsif ($env{'form.crstype'} eq 'any') {
 2505:         $title = 'Course/Community Request Logs';
 2506:     } else {
 2507:         $title = 'Course Request Logs';
 2508:     }
 2509:     $r->print(&header($title,$jscript,$loaditems).$crumb);
 2510:     if ($usetabs) {
 2511:         &startContentScreen($r,'textbooklogs');
 2512:     }
 2513:     my $formname = 'requestcrs';
 2514:     $r->print('<form action="/adm/requestcourse" method="post" name="'.$formname.'" onsubmit="javascript:setPage(this);">'."\n".
 2515:               '<input type="hidden" name="action" value="log" />'."\n".
 2516:               '<input type="hidden" name="state" value="display" />'."\n");
 2517:     # set defaults
 2518:     my $now = time();
 2519:     my $defstart = $now - (7*24*3600); #7 days ago
 2520:     my %defaults = (
 2521:                      page                => '1',
 2522:                      show                => '10',
 2523:                      crstype             => 'any',
 2524:                      status              => 'any',
 2525:                      requested_before_date => $now,
 2526:                      requested_after_date  => $defstart,
 2527:                    );
 2528:     my ($types,$typenames) = &Apache::loncommon::course_types();
 2529:     my $more_records = 0;
 2530:     my %curr;
 2531:     foreach my $item ('show','page','crstype','status') {
 2532:         $curr{$item} = $env{'form.'.$item};
 2533:     }
 2534:     $curr{'requested_after_date'} = &Apache::lonhtmlcommon::get_date_from_form('requested_after_date');
 2535:     $curr{'requested_before_date'} = &Apache::lonhtmlcommon::get_date_from_form('requested_before_date');
 2536:     foreach my $key (keys(%defaults)) {
 2537:         if ($curr{$key} eq '') {
 2538:             $curr{$key} = $defaults{$key};
 2539:         }
 2540:     }
 2541:     my ($statuses,$statusnames) = &reqstatus_names($curr{'crstype'});
 2542:     $r->print('<input type="hidden" name="page" value="'.$curr{'page'}.'" />'.
 2543:               &requestlog_display_filter($formname,\%curr));
 2544:     my %queue_by_date = &sorted_request_history($dom,$env{'form.action'},\%curr);
 2545:     my @sortedtimes = sort {$a <=> $b} (keys(%queue_by_date));
 2546:     my $showntablehdr = 0;
 2547:     my $tablehdr = &Apache::loncommon::start_data_table().
 2548:                    &Apache::loncommon::start_data_table_header_row().
 2549:                    '<th>&nbsp;</th><th>'.&mt('Request Date').'</th>'.
 2550:                    '<th>'.&mt('Description').'</th>';
 2551:     if ($curr{'crstype'} eq 'any') {
 2552:         $tablehdr .= '<th>'.&mt('Course Type').'</th>';
 2553:     }
 2554:     if (($curr{'crstype'} eq 'official') || ($curr{'crstype'} eq 'any')) {
 2555:         $tablehdr .= '<th>'.&mt('Institutional Code').'</th>';
 2556:     }
 2557:     my $showuniquecode;
 2558:     my %domconfig = &Apache::lonnet::get_dom('configuration',['requestcourses'],$dom);
 2559:     if (($curr{'status'} eq 'any') || ($curr{'status'} eq 'created')) {
 2560:         if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2561:             if (ref($domconfig{'requestcourses'}{'uniquecode'}) eq 'HASH') {
 2562:                 if ($curr{'crstype'} eq 'any') {
 2563:                     my @types = qw(official unofficial community textbook placement);
 2564:                     foreach my $type (@types) {
 2565:                         if ($domconfig{'requestcourses'}{'uniquecode'}{$type}) {
 2566:                             $showuniquecode = 1;
 2567:                             last;
 2568:                         }
 2569:                     }
 2570:                 } elsif ($domconfig{'requestcourses'}{'uniquecode'}{$curr{'crstype'}}) {
 2571:                     $showuniquecode = 1;
 2572:                 }
 2573:             }
 2574:         }
 2575:     }
 2576:     if ($showuniquecode) {
 2577:         $tablehdr .= '<th>'.&mt('Unique Code').'</th>';    
 2578:     }
 2579:     if ($curr{'status'} eq 'any') {
 2580:         $tablehdr .= '<th>'.&mt('Status').'</th>';
 2581:     } elsif ($curr{'status'} eq 'created') {
 2582:         $tablehdr .= '<th>'.&mt('Creation Date').'</th>';
 2583:     } elsif ($curr{'status'} eq 'cancelled') {
 2584:         $tablehdr .= '<th>'.&mt('Cancellation Date').'</th>';
 2585:     } elsif ($curr{'status'} eq 'rejected') {
 2586:         $tablehdr .= '<th>'.&mt('Rejection Date').'</th>';
 2587:     }
 2588:     $tablehdr .= &Apache::loncommon::end_data_table_header_row();
 2589:     my ($minshown,$maxshown);
 2590:     $minshown = 1;
 2591:     my $count = 0;
 2592:     if ($curr{'show'} ne &mt('all')) {
 2593:         $maxshown = $curr{'page'} * $curr{'show'};
 2594:         if ($curr{'page'} > 1) {
 2595:             $minshown = 1 + ($curr{'page'} - 1) * $curr{'show'};
 2596:         }
 2597:     }
 2598:     my $norecords;
 2599:     if (@sortedtimes > 0) {
 2600:         foreach my $item (@sortedtimes) {
 2601:             if ($curr{'show'} ne &mt('all')) {
 2602:                 if ($count >= $curr{'page'} * $curr{'show'}) {
 2603:                     $more_records = 1;
 2604:                     last;
 2605:                 }
 2606:             }
 2607:             $count ++;
 2608:             next if ($count < $minshown);
 2609:             if (!$showntablehdr) {
 2610:                 $r->print($tablehdr);
 2611:                 $showntablehdr = 1;
 2612:             }
 2613:             my $showtime = &Apache::lonlocal::locallocaltime($item);
 2614:             if (ref($queue_by_date{$item}) eq 'ARRAY') {
 2615:                 foreach my $request (sort(@{$queue_by_date{$item}})) {
 2616:                     my ($key,$crstype,$desc,$uniquecode,$timestamp,$status,$instcode) = split(':',$request);
 2617:                     my ($cdom,$cnum) = split('_',$key);
 2618:                     my $output = &Apache::loncommon::start_data_table_row().
 2619:      '<td>'.$count.'</td>'.
 2620:      '<td>'.$showtime.'</td>'.
 2621:      '<td>'.&unescape($desc).'</td>';
 2622:                     if ($curr{'crstype'} eq 'any') {
 2623:                         my $typename;
 2624:                         if (ref($typenames) eq 'HASH') {
 2625:                             $typename = &mt($typenames->{$crstype});
 2626:                         }
 2627:                         if ($typename eq '') {
 2628:                             $typename = &mt('Unknown type');
 2629:                         }
 2630:                         $output .= '<td>'.$typename.'</td>';
 2631:                     }
 2632:                     if (($curr{'crstype'} eq 'any') ||
 2633:                         ($curr{'crstype'} eq 'official')) {
 2634:                         my $showinstcode;
 2635:                         if ($crstype eq 'official') {
 2636:                             $showinstcode = &unescape($instcode);
 2637:                         } else {
 2638:                             $showinstcode = &mt('Not applicable');
 2639:                         }
 2640:                         $output .= '<td>'.$showinstcode.'</td>';
 2641:                     }
 2642:                     if ($showuniquecode) {
 2643:                         if ($status eq 'created') {
 2644:                             $output .= '<td>'.$uniquecode.'</td>';
 2645:                         } else {
 2646:                             $output .= '<td>'.&mt('Not applicable').'</td>';
 2647:                         }    
 2648:                     }
 2649:                     if ($curr{'status'} eq 'any') {
 2650:                         my $statusname = &mt('Unknown status');
 2651:                         if (ref($statusnames) eq 'HASH') {
 2652:                             if ($statusnames->{$status} ne '') {
 2653:                                 $statusname = $statusnames->{$status};
 2654:                             }
 2655:                         }
 2656:                         if (($status eq 'created') || ($status eq 'cancelled') ||
 2657:                             ($status eq 'rejected')) {
 2658:                             $statusname .= ' '.&Apache::lonlocal::locallocaltime($timestamp);
 2659:                         }
 2660:                         $output .= '<td>'.$statusname.'</td>';
 2661:                     } elsif (($status eq 'created') || ($status eq 'cancelled') ||
 2662:                              ($status eq 'rejected')) {
 2663:                          $output .= '<td>'.&Apache::lonlocal::locallocaltime($timestamp).'</td>';
 2664:                     }
 2665:                     $output .= &Apache::loncommon::end_data_table_row();
 2666:                     $r->print($output);
 2667:                 }
 2668:             }
 2669:         }
 2670:         if ($showntablehdr) {  
 2671:             $r->print(&Apache::loncommon::end_data_table());
 2672:             if (($curr{'page'} > 1) || ($more_records)) {
 2673:                 $r->print('<table><tr>');
 2674:                 if ($curr{'page'} > 1) {
 2675:                     $r->print('<td><a href="javascript:chgPage('."'previous'".');">'.&mt('Previous [_1] changes',$curr{'show'}).'</a></td>');
 2676:                 }
 2677:                 if ($more_records) {
 2678:                     $r->print('<td><a href="javascript:chgPage('."'next'".');">'.&mt('Next [_1] changes',$curr{'show'}).'</a></td>');
 2679:                 }
 2680:                 $r->print('</tr></table>');
 2681:                 $r->print(<<"ENDSCRIPT");
 2682: <script type="text/javascript">
 2683: // <![CDATA[
 2684: function chgPage(caller) {
 2685:     if (caller == 'previous') {
 2686:         document.$formname.page.value --;
 2687:     }
 2688:     if (caller == 'next') {
 2689:         document.$formname.page.value ++;
 2690:     }
 2691:     document.$formname.submit();
 2692:     return;
 2693: }
 2694: // ]]>
 2695: </script>
 2696: ENDSCRIPT
 2697:             }
 2698:         } else {
 2699:             $norecords = 1;
 2700:         }
 2701:     } else {
 2702:         $norecords = 1;
 2703:     }
 2704:     if ($norecords) {
 2705:         $r->print('<p class="LC_info">'.
 2706:                   &mt('There are no records to display').
 2707:                   '</p>');
 2708:     }
 2709:     if ($usetabs) {
 2710:         $r->print('<input type="hidden" name="tabs" value="on" />');
 2711:     }
 2712:     $r->print('</form>');
 2713:     if ($usetabs) {
 2714:         &endContentScreen($r);
 2715:     }
 2716:     $r->print(&Apache::loncommon::end_page());
 2717:     return;
 2718: }
 2719: 
 2720: sub reqstatus_names {
 2721:     my ($crstype) = @_;
 2722:     my @statuses = qw(created approval pending rejected cancelled);
 2723:     my %statusnames =
 2724:             &Apache::lonlocal::texthash (
 2725:                         created   => 'Created',
 2726:                         approval  => 'Queued pending approval',
 2727:                         pending   => 'Queued pending validation',
 2728:                         rejected  => 'Request rejected',
 2729:                         cancelled => 'Request cancelled',
 2730:             );
 2731:     if (($crstype eq 'official') || ($crstype eq 'unofficial') || ($crstype eq 'textbook') || ($crstype eq 'placement')) {
 2732:         $statusnames{'created'} = &mt('Course created');
 2733:     } elsif ($crstype eq 'community') {
 2734:         $statusnames{'created'} = &mt('Community created');
 2735:     }
 2736:     return (\@statuses,\%statusnames);
 2737: }
 2738: 
 2739: sub requestlog_display_filter {
 2740:     my ($formname,$curr) = @_;
 2741:     my $nolink = 1;
 2742:     my $output = '<table><tr><td valign="top">'.
 2743:                  '<span class="LC_nobreak"><b>'.&mt('Records/page:').'</b></span><br />'.
 2744:                  &Apache::lonmeta::selectbox('show',$curr->{'show'},undef,
 2745:                                               (&mt('all'),5,10,20,50,100,1000,10000)).
 2746:                  '</td><td>&nbsp;&nbsp;</td>';
 2747:     my $startform =
 2748:         &Apache::lonhtmlcommon::date_setter($formname,'requested_after_date',
 2749:                                             $curr->{'requested_after_date'},undef,
 2750:                                             undef,undef,undef,undef,undef,undef,$nolink);
 2751:     my $endform =
 2752:         &Apache::lonhtmlcommon::date_setter($formname,'requested_before_date',
 2753:                                             $curr->{'requested_before_date'},undef,
 2754:                                             undef,undef,undef,undef,undef,undef,$nolink);
 2755:     $output .= '<td valign="top"><b>'.&mt('Window during which course/community was requested:').'</b><br />'.
 2756:                '<table><tr><td>'.&mt('After:').
 2757:                '</td><td>'.$startform.'</td></tr>'.
 2758:                '<tr><td>'.&mt('Before:').'</td>'.
 2759:                '<td>'.$endform.'</td></tr></table>'.
 2760:                '</td>'.
 2761:                '<td>&nbsp;&nbsp;</td>';
 2762:     my ($types,$typenames) = &Apache::loncommon::course_types();
 2763:     if (ref($types) eq 'ARRAY') {
 2764:         if (@{$types} > 1) {
 2765:             $output .= '<td valign="top"><b>'.
 2766:                        &mt('Course Type:').'</b><br /><select name="crstype">';
 2767:             my $selstr = '';
 2768:             if ($curr->{'crstype'} eq 'any') {
 2769:                 $selstr = ' selected="selected"';
 2770:             }
 2771:             $output .= '<option value="any"'.$selstr.'>'.&mt('All types').'</option>'."\n";
 2772:             foreach my $crstype (@{$types}) {
 2773:                 my $selstr = '';
 2774:                 if ($curr->{'crstype'} eq $crstype) {
 2775:                     $selstr = ' selected="selected"';
 2776:                 }
 2777:                 my $typename = $crstype;
 2778:                 if (ref($typenames) eq 'HASH') {
 2779:                     if ($typenames->{$crstype} ne '') {
 2780:                         $typename = $typenames->{$crstype};
 2781:                     }
 2782:                 }
 2783:                 $output .= '<option value="'.$crstype.'"'.$selstr.'>'.$typename.'</option>'."\n";
 2784:             }
 2785:             $output .= '</select></td>';
 2786:         }
 2787:     }
 2788:     my ($statuses,$statusnames) = &reqstatus_names($curr->{'crstype'});
 2789:     if (ref($statuses) eq 'ARRAY') {
 2790:         if (@{$statuses} > 1) {
 2791:             $output .= '<td valign="top"><b>'.
 2792:                        &mt('Request Status:').'</b><br /><select name="status">';
 2793:             my $selstr = '';
 2794:             if ($curr->{'status'} eq 'any') {
 2795:                 $selstr = ' selected="selected"';
 2796:             }
 2797:             $output .= '<option value="any"'.$selstr.'>'.&mt('Any status').'</option>'."\n";
 2798:             foreach my $status (@{$statuses}) {
 2799:                 my $selstr = '';
 2800:                 if ($curr->{'status'} eq $status) {
 2801:                     $selstr = ' selected="selected"';
 2802:                 }
 2803:                 my $statusname = $status;
 2804:                 if (ref($statusnames) eq 'HASH') {
 2805:                     if ($statusnames->{$status} ne '') {
 2806:                         $statusname = $statusnames->{$status};
 2807:                     }
 2808:                 }
 2809:                 $output .= '<option value="'.$status.'"'.$selstr.'>'.$statusname.'</option>'."\n";
 2810:             }
 2811:             $output .= '</select></td>';
 2812:         }
 2813:     }
 2814:     $output .= '</tr></table>';
 2815: 
 2816:     # Update Display button
 2817:     $output .= '<p>'.
 2818:                '<input type="submit" value="'.&mt('Update Display').'" />'.
 2819:                '</p><hr />';
 2820:     return $output;
 2821: }
 2822: 
 2823: sub print_review {
 2824:     my ($dom,$codetitles,$cat_titles,$cat_order,$code_order,$uname,$udom,
 2825:         $disallowed,$disallowmsg,$instcredits) = @_;
 2826:     my ($types,$typename) = &Apache::loncommon::course_types();
 2827:     my ($owner,$ownername,$owneremail);
 2828:     if ($uname eq '' || $udom eq '') {
 2829:         $uname = $env{'user.name'};
 2830:         $udom = $env{'user.domain'};
 2831:     }
 2832:     $owner = $uname.':'.$udom;
 2833:     $ownername = &Apache::loncommon::plainname($uname,$udom,'first');
 2834:     my %emails = &Apache::loncommon::getemails($uname,$udom);
 2835:     foreach my $email ('permanentemail','critnotification','notification') {
 2836:         $owneremail = $emails{$email};
 2837:         last if ($owneremail ne '');
 2838:     }
 2839:     my ($inst_headers,$inst_values,$crstypename,$enroll_headers,$enroll_values,
 2840:         $section_headers,$section_values,$personnel_headers,$personnel_values);
 2841: 
 2842:     $crstypename = $env{'form.crstype'};
 2843:     if (ref($typename) eq 'HASH') {
 2844:         unless ($typename->{$env{'form.crstype'}} eq '') {
 2845:             $crstypename = &mt($typename->{$env{'form.crstype'}});
 2846:         }
 2847:     }
 2848:     my $category = 'Course';
 2849:     if ($env{'form.crstype'} eq 'community') {
 2850:         $category = 'Community';
 2851:     }
 2852: 
 2853:     $inst_headers = '<th>'.&mt('Description').'</th><th>'.&mt('Type').'</th>';
 2854:     $inst_values = '<td>'.$env{'form.cdescr'}.'</td><td>'.$crstypename.'</td>';
 2855: 
 2856:     my $enrollrow_title = &mt('Default Access Dates').'<br />'.
 2857:                           '('.&Apache::lonnet::plaintext('st',$category).')';
 2858:     my $instcode;
 2859:     if ($env{'form.crstype'} eq 'official') {
 2860:         if ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH')) {
 2861:             foreach my $title (@{$codetitles}) {
 2862:                 if ($env{'form.instcode_'.$title} ne '') {
 2863:                     $inst_headers .= '<th>'.$title.'</th>';
 2864:                     my $longitem = $env{'form.instcode_'.$title};
 2865:                     if (ref($cat_titles->{$title}) eq 'HASH') {
 2866:                         if ($cat_titles->{$title}{$env{'form.instcode_'.$title}} ne '') {
 2867:                             $longitem = $cat_titles->{$title}{$env{'form.instcode_'.$title}};
 2868:                         }
 2869:                     }
 2870:                     $inst_values .= '<td>'.$longitem.'</td>';
 2871:                 }
 2872:             }
 2873:         }
 2874:         if (ref($code_order) eq 'ARRAY') {
 2875:             foreach my $item (@{$code_order}) {
 2876:                 $instcode .= $env{'form.instcode_'.$item};
 2877:             }
 2878:         }
 2879:         $inst_headers .= '<th>'.&mt('Credits').'</th>';
 2880:         if ($instcredits) {
 2881:             $inst_values .= '<td>'.$instcredits.'</td>';
 2882:         } else {
 2883:             $inst_values .= '<td>'.$env{'form.coursecredits'}.'</td>';
 2884:         }
 2885:         if (&Apache::lonnet::auto_run('',$dom)) {
 2886:             $enrollrow_title = &mt('Enrollment');
 2887:             $enroll_headers = '<th>'.&mt('Automatic Adds').'</th>'.
 2888:                               '<th>'.&mt('Automatic Drops').'</th>'.
 2889:                               '<th>'.&mt('Enrollment Starts').'</th>'.
 2890:                               '<th>'.&mt('Enrollment Ends').'</th>';
 2891:             $section_headers = '<th>'.&mt('Sections').'</th>'.
 2892:                                '<th>'.&mt('Crosslistings').'</th>';
 2893: 
 2894:             my ($enrollstart,$enrollend) = &dates_from_form('enrollstart','enrollend');
 2895:             my @autoroster = (&mt('No'),&mt('Yes'));
 2896:             $enroll_values = '<td>'.$autoroster[$env{'form.autoadds'}].'</td>'.
 2897:                              '<td>'.$autoroster[$env{'form.autodrops'}].'</td>'.
 2898:                              '<td>'.&Apache::lonlocal::locallocaltime($enrollstart).'</td>'.
 2899:                              '<td>'.&Apache::lonlocal::locallocaltime($enrollend).'</td>';
 2900:             $section_values = '<td><table class="LC_innerpickbox"><tr><th>'.
 2901:                               &mt('Institutional section').'</th>'.
 2902:                               '<th>'.&mt('LON-CAPA section').'</th></tr>';
 2903:             my $secinfo;
 2904:             if ($env{'form.sectotal'} > 0) {
 2905:                 for (my $i=0; $i<$env{'form.sectotal'}; $i++) {
 2906:                     if ($env{'form.sec_'.$i}) {
 2907:                         $secinfo .= '<tr><td>'.$env{'form.secnum_'.$i}.'</td><td>';
 2908:                         if ($env{'form.loncapasec_'.$i} ne '') {
 2909:                             $secinfo .= $env{'form.loncapasec_'.$i};
 2910:                         } else {
 2911:                             $secinfo .= &mt('None');
 2912:                         }
 2913:                         $secinfo .= '</td></tr>';
 2914:                     }
 2915:                 }
 2916:             }
 2917:             if ($secinfo eq '') {
 2918:                 $secinfo = '<tr><td colspan="2">'.&mt('None').'</td></tr>';
 2919:             }
 2920:             $section_values .= $secinfo.'</table></td><td>'.
 2921:                                '<table class="LC_innerpickbox"><tr><th>'.
 2922:                                &mt('Institutional course/section').'</th>'.
 2923:                                '<th>'.&mt('LON-CAPA section').'</th></tr>';
 2924:             my $xlistinfo;
 2925:             my $crosslisttotal = $env{'form.crosslisttotal'};
 2926:             if (!$crosslisttotal) {
 2927:                 $crosslisttotal = 1;
 2928:             }
 2929:             for (my $i=0; $i<$crosslisttotal; $i++) {
 2930:                 if ($env{'form.crosslist_'.$i}) {
 2931:                     $xlistinfo .= '<tr><td>';
 2932:                     if (ref($code_order) eq 'ARRAY') {
 2933:                         if (@{$code_order} > 0) {
 2934:                             foreach my $item (@{$code_order}) {
 2935:                                 $xlistinfo .= $env{'form.crosslist_'.$i.'_'.$item};
 2936:                             }
 2937:                         }
 2938:                     }
 2939:                     $xlistinfo .= $env{'form.crosslist_'.$i.'_instsec'}.'</td><td>';
 2940:                     if ($env{'form.crosslist_'.$i.'_lcsec'}) {
 2941:                         $xlistinfo .= $env{'form.crosslist_'.$i.'_lcsec'};
 2942:                     } else {
 2943:                         $xlistinfo .= &mt('None');
 2944:                     }
 2945:                     $xlistinfo .= '</td></tr>';
 2946:                 }
 2947:             }
 2948:             if ($xlistinfo eq '') {
 2949:                 $xlistinfo = '<tr><td colspan="2">'.&mt('None').'</td></tr>';
 2950:             }
 2951:             $section_values .= $xlistinfo;
 2952:         }
 2953:         $section_values .= '</table></td>';
 2954:     } elsif (($env{'form.crstype'} eq 'unofficial') || ($env{'form.crstype'} eq 'textbook')) {
 2955:         $inst_headers .= '<th>'.&mt('Credits').'</th>';
 2956:         $inst_values .= '<td>'.$env{'form.coursecredits'}.'</td>';
 2957:     }
 2958: 
 2959:     my %ctxt = &clone_text();
 2960:     $inst_headers .= '<th>'.&mt('Clone From').'</th>';
 2961:     if (($env{'form.cloning'}) &&
 2962:         ($env{'form.clonecrs'} =~ /^$match_name$/) && 
 2963:         ($env{'form.clonedom'} =~ /^$match_domain$/)) {
 2964:         my $canclone = &Apache::loncoursequeueadmin::can_clone_course($uname,
 2965:                            $udom,$env{'form.clonecrs'},$env{'form.clonedom'},
 2966:                            $env{'form.crstype'},$dom,$instcode);
 2967:         if ($canclone) {
 2968:             my %courseenv = &Apache::lonnet::userenvironment($env{'form.clonedom'},
 2969:                               $env{'form.clonecrs'},('description','internal.coursecode'));
 2970:             if (keys(%courseenv) > 0) {
 2971:                 $inst_headers .= '<th>'.$ctxt{'dsh'}.'</th>';
 2972:                 $inst_values .= '<td>'.$courseenv{'description'}.'&nbsp;';
 2973:                 my $cloneinst = $courseenv{'internal.coursecode'};
 2974:                 if ($cloneinst ne '') {
 2975:                     $inst_values .= $cloneinst.' '.&mt('in').' '.$env{'form.clonedom'};
 2976:                 } else {
 2977:                     $inst_values .= &mt('from').' '.$env{'form.clonedom'};
 2978:                 }
 2979:                 $inst_values .= '</td><td>';
 2980:                 if ($env{'form.datemode'} eq 'preserve') {
 2981:                     $inst_values .= $ctxt{'prd'}; 
 2982:                 } elsif ($env{'form.datemode'} eq 'shift') {
 2983:                     $inst_values .= &mt('Shift dates by [_1] days',$env{'form.dateshift'});
 2984:                 } else {
 2985:                     $inst_values .= $ctxt{'ncd'};
 2986:                 }
 2987:                 $inst_values .= '</td>';
 2988:              } else {
 2989:                  $inst_values .= '<td>'.&mt('Unknown').'</td>';
 2990:              }
 2991:          } else {
 2992:              $inst_values .= '<td>'.&mt('Not permitted'),'</td>';
 2993:          }
 2994:     } else {
 2995:         $inst_values .= '<td>'.&mt('None').'</td>';
 2996:     }
 2997:     $enroll_headers .= '<th>'.&mt('Access Starts').'</th>'.
 2998:                        '<th>'.&mt('Access Ends').'</th>';
 2999:     my ($accessstart,$accessend) = &dates_from_form('accessstart','accessend');
 3000:     $enroll_values .= '<td>'.&Apache::lonlocal::locallocaltime($accessstart).'</td>';
 3001:     if ($accessend == 0) {
 3002:         $enroll_values .= '<td>'.&mt('No end date').'</td>';
 3003:     } else {
 3004:         $enroll_values .= '<td>'.&Apache::lonlocal::locallocaltime($accessend).'</td>';
 3005:     }
 3006: 
 3007:     my $container = 'Course';
 3008:     my $ccrole = 'cc';
 3009:     if ($env{'form.crstype'} eq 'community') {
 3010:         $container = 'Community';
 3011:         $ccrole = 'co';
 3012:     }
 3013: 
 3014:     $personnel_headers = '<th>'.&mt('Name').'</th><th>'.&mt('Username:Domain').
 3015:                          '</th><th>'.&mt('Role').'</th><th>'.&mt('LON-CAPA Sections').
 3016:                          '</th>';
 3017: 
 3018:     $personnel_values .= '<tr><td>'.$ownername.'</td><td>'.$owner.'</td>'.
 3019:                          '<td>'.&Apache::lonnet::plaintext($ccrole,$container).'</td>'.
 3020:                          '<td>'.&mt('None').'</td></tr>';
 3021:     for (my $i=0; $i<$env{'form.persontotal'}; $i++) {
 3022:         if ($env{'form.person_'.$i.'_uname'} ne '') {
 3023:             if (ref($disallowed) eq 'ARRAY') {
 3024:                 next if (grep(/^$i$/,@{$disallowed}));
 3025:             } 
 3026:             my @officialsecs = &Apache::loncommon::get_env_multiple('form.person_'.$i.'_sec');
 3027:             my @allsecs;
 3028:             foreach my $sec (@officialsecs) {
 3029:                 next unless ($sec =~ /\w/);
 3030:                 next if ($sec =~ /\W/);
 3031:                 next if ($sec eq 'none');
 3032:                 push(@allsecs,$sec);
 3033:             }
 3034:             my $newsec = $env{'form.person_'.$i.'_newsec'};
 3035:             $newsec =~ s/^\s+//;
 3036:             $newsec =~s/\s+$//;
 3037:             my @newsecs = split(/\s*[\s,;:]\s*/,$newsec);
 3038:             foreach my $sec (@newsecs) {
 3039:                 next unless ($sec =~ /\w/); 
 3040:                 next if ($sec =~ /\W/);
 3041:                 next if ($sec eq 'none');
 3042:                 if ($sec ne '') {
 3043:                     unless (grep(/^\Q$sec\E$/,@allsecs)) {
 3044:                         push(@allsecs,$sec); 
 3045:                     }
 3046:                 }
 3047:             }
 3048:             my $showsec;
 3049:             if (@allsecs) {
 3050:                 $showsec = join(', ',@allsecs);
 3051:             }
 3052:             if ($showsec eq '') {
 3053:                 $showsec = &mt('None');
 3054:             }
 3055:             if ($env{'form.person_'.$i.'_role'} eq $ccrole) {
 3056:                 $showsec = &mt('None');
 3057:             }
 3058:             my $role = $env{'form.person_'.$i.'_role'}; 
 3059:             $personnel_values .= 
 3060:                 '<tr><td>'.$env{'form.person_'.$i.'_firstname'}.' '.
 3061:                 $env{'form.person_'.$i.'_lastname'}.'</td>'.
 3062:                 '<td>'.$env{'form.person_'.$i.'_uname'}.':'.
 3063:                 $env{'form.person_'.$i.'_dom'}.'</td>'.
 3064:                 '<td>'.&Apache::lonnet::plaintext($role,$container).'</td>'.
 3065:                 '<td>'.$showsec.'</td></tr>';
 3066:         }
 3067:     }
 3068:     my $output;
 3069:     if (ref($disallowed) eq 'ARRAY') {
 3070:         if (@{$disallowed} > 0) {
 3071:             if (ref($disallowmsg) eq 'HASH') {
 3072:                 $output = '<p class="LC_warning">'.
 3073:                           &mt('Not all requested personnel could be included.').'<ul>'; 
 3074:                 foreach my $item (@{$disallowed}) {
 3075:                     $output .= '<li>'.$disallowmsg->{$item}.'</li>';
 3076:                 }
 3077:                 $output .= '</ul></p>';
 3078:             }
 3079:         }
 3080:     }
 3081:     $output .=    '<div>'.&Apache::lonhtmlcommon::start_pick_box().
 3082:                   &Apache::lonhtmlcommon::row_title(&mt('Owner')).
 3083:                   '<table class="LC_innerpickbox"><tr>'.
 3084:                   '<th>'.&mt('Name').'</th>'.
 3085:                   '<th>'.&mt('Username:Domain').'</th>'.
 3086:                   '<th>'.&mt('E-mail address').'</th>'.
 3087:                   '</tr><tr>'."\n".
 3088:                   '<td>'.$ownername.'</td><td>'.$owner.'</td>'.
 3089:                   '<td>'.$owneremail.'</td>'.
 3090:                   '</tr></table>'."\n".
 3091:                   &Apache::lonhtmlcommon::row_closure().
 3092:                   &Apache::lonhtmlcommon::row_title(&mt('Description')).
 3093:                   '<table class="LC_innerpickbox"><tr>'.$inst_headers.'</tr>'."\n".
 3094:                   '<tr>'.$inst_values.'</tr></table>'."\n".
 3095:                   &Apache::lonhtmlcommon::row_closure().
 3096:                   &Apache::lonhtmlcommon::row_title($enrollrow_title).
 3097:                   '<table class="LC_innerpickbox"><tr>'.$enroll_headers.'</tr>'."\n".
 3098:                   '<tr>'.$enroll_values.'</tr></table>'."\n".
 3099:                   &Apache::lonhtmlcommon::row_closure();
 3100:     if ($section_headers ne '') {
 3101:         $output .= &Apache::lonhtmlcommon::row_title(&mt('Sections')).
 3102:                    '<table class="LC_innerpickbox"><tr>'.$section_headers.'</tr>'."\n".
 3103:                    '<tr>'.$section_values.'</tr></table>'."\n".
 3104:                    &Apache::lonhtmlcommon::row_closure();
 3105:     }
 3106:     $output .= &Apache::lonhtmlcommon::row_title(&mt('Personnel')).
 3107:                '<table class="LC_innerpickbox"><tr>'.$personnel_headers.'</tr>'."\n".
 3108:                $personnel_values.'</table>'."\n".
 3109:                &Apache::lonhtmlcommon::row_closure(1).
 3110:                &Apache::lonhtmlcommon::end_pick_box().'</div>';
 3111:     return $output;
 3112: }
 3113: 
 3114: sub dates_from_form {
 3115:     my ($startname,$endname) = @_;
 3116:     my $startdate = &Apache::lonhtmlcommon::get_date_from_form($startname);
 3117:     my $enddate   = &Apache::lonhtmlcommon::get_date_from_form($endname);
 3118:     if ($endname eq 'accessend') {
 3119:         if (exists($env{'form.no_end_date'}) ) {
 3120:             $enddate = 0;
 3121:         }
 3122:     }
 3123:     return ($startdate,$enddate);
 3124: }
 3125: 
 3126: sub courseinfo_form {
 3127:     my ($dom,$formname,$crstype,$next,$description) = @_;
 3128:     my %js_lt = &Apache::lonlocal::texthash(
 3129:                 official => 'You must provide a (brief) course description.',
 3130:                 community => 'You must provide a (brief) community description.'
 3131:              );
 3132:     &js_escape(\%js_lt);
 3133:     $js_lt{'unofficial'} = $js_lt{'official'};
 3134:     $js_lt{'textbook'} = $js_lt{'official'};
 3135:     $js_lt{'placement'} = $js_lt{'official'};
 3136:     my $js_validate = <<"ENDJS";
 3137: <script type="text/javascript">
 3138: // <![CDATA['
 3139: 
 3140: function validateForm() {
 3141:     if ((document.$formname.cdescr.value == "")  || (document.$formname.cdescr.value == "undefined")) {
 3142:         alert('$js_lt{$crstype}');
 3143:         return;
 3144:     }
 3145:     nextPage(document.$formname,'$next');
 3146: }
 3147: 
 3148: function toggleCloning() {
 3149:     var willclone;
 3150:     if (document.$formname.cloning.length > 1) {
 3151:         for (var i=0; i<document.$formname.cloning.length; i++) {
 3152:             if (document.$formname.cloning[i].checked) {
 3153:                 willclone = document.$formname.cloning[i].value;
 3154:             }
 3155:         }
 3156:     }
 3157:     if (willclone == 1) {
 3158:         document.getElementById('cloneoptions').style.display="block";
 3159:     } else {
 3160:         document.getElementById('cloneoptions').style.display="none";
 3161:         document.$formname.clonecrs.value = '';
 3162:     }
 3163: }
 3164: 
 3165: // ]]
 3166: </script>
 3167: 
 3168: ENDJS
 3169:     my $title = &mt('Brief Course Description');
 3170:     my $clonetitle = &mt('Clone content and settings from an existing course?');
 3171:     if ($crstype eq 'community') {
 3172:         $title = &mt('Brief Community Description');
 3173:         $clonetitle = &mt('Clone content and settings from an existing community?');
 3174:     }
 3175:     my $output .= $js_validate."\n".&Apache::lonhtmlcommon::start_pick_box().
 3176:                   &Apache::lonhtmlcommon::row_headline().
 3177:                   '<h3>'.&Apache::loncommon::help_open_topic('Course_Request_Description').'&nbsp;'.$title.'</h3>'.
 3178:                   &Apache::lonhtmlcommon::row_closure(1).
 3179:                   &Apache::lonhtmlcommon::row_title(&mt('Description')).
 3180:                  '<input type="text" size="60" name="cdescr" value="'.$description.'" />';
 3181:     my ($home_server_pick,$numlib) =
 3182:         &Apache::loncommon::home_server_form_item($dom,'chome',
 3183:                                                   'default','hide');
 3184:     if ($numlib > 1) {
 3185:         $output .= &Apache::lonhtmlcommon::row_closure().
 3186:                    &Apache::lonhtmlcommon::row_title(&mt('Home Server for Course'));
 3187:     }
 3188:     $output .= $home_server_pick.
 3189:                &Apache::lonhtmlcommon::row_closure().
 3190:                &Apache::lonhtmlcommon::row_headline().
 3191:                '<h3>'.&Apache::loncommon::help_open_topic('Course_Request_Clone').'&nbsp;'.$clonetitle.
 3192:                &Apache::lonhtmlcommon::row_closure(1).
 3193:                &Apache::lonhtmlcommon::row_title(&mt('Clone?')).
 3194:                '<label><input type="radio" name="cloning" value="1" '.
 3195:                'onclick="javascript:toggleCloning()" />'.
 3196:                &mt('Yes').('&nbsp;'x2).'</label><label>'.
 3197:                '<input type="radio" name="cloning" value="0" checked="checked" '.
 3198:                'onclick="javascript:toggleCloning()" />'.&mt('No').'</label>'.
 3199:                '</h3>'.
 3200:                &Apache::lonhtmlcommon::row_closure(1).
 3201:                &Apache::lonhtmlcommon::row_headline().
 3202:                '<div id="cloneoptions" style="display: none" >'.
 3203:                &Apache::lonhtmlcommon::start_pick_box().
 3204:                &clone_form($dom,$formname,$crstype).
 3205:                &Apache::lonhtmlcommon::end_pick_box().'</div>'.
 3206:                &Apache::lonhtmlcommon::end_pick_box()."\n";
 3207:     return $output;
 3208: }
 3209: 
 3210: sub clone_form {
 3211:     my ($dom,$formname,$crstype) = @_;
 3212:     my $type = 'Course';
 3213:     if ($crstype eq 'community') {
 3214:         $type = 'Community';
 3215:     } elsif ($crstype eq 'placement') {
 3216:         $type = 'Placement'; 
 3217:     }
 3218:     my %lt = &clone_text();
 3219:     my $output .= 
 3220:         &Apache::lonhtmlcommon::row_title($lt{'dmn'}).'<label>'.
 3221:         &Apache::loncommon::select_dom_form($dom,'clonedom').'</label>'.
 3222:         &Apache::lonhtmlcommon::row_closure(1).
 3223:         &Apache::lonhtmlcommon::row_title($lt{'cid'}).'<label>'.
 3224:         '<input type="text" size="25" name="clonecrs" value="" onfocus="this.blur();opencrsbrowser('."'$formname','clonecrs','clonedom','','','','$type'".')" />'.
 3225:         '</label>&nbsp;'.
 3226:         &Apache::loncommon::selectcourse_link($formname,'clonecrs','clonedom','','','',$type).
 3227:         &Apache::lonhtmlcommon::row_closure(1).
 3228:         &Apache::lonhtmlcommon::row_title($lt{'dsh'}).'<label>'.
 3229:         '<input type="radio" name="datemode" value="delete" /> '.$lt{'ncd'}.
 3230:         '</label><br /><label>'.
 3231:         '<input type="radio" name="datemode" value="preserve" /> '.$lt{'prd'}.
 3232:         '</label><br /><label>'.
 3233:         '<input type="radio" name="datemode" value="shift" checked="checked" /> '.
 3234:         $lt{'shd'}.'</label>'.
 3235:         '<input type="text" size="5" name="dateshift" value="365" />'.
 3236:         &Apache::lonhtmlcommon::row_closure(1);
 3237:     return $output;
 3238: }
 3239: 
 3240: sub clone_text {
 3241:     return &Apache::lonlocal::texthash(
 3242:                'cid'  => 'Course ID',
 3243:                'dmn'  => 'Domain',
 3244:                'dsh'  => 'Date Shift',
 3245:                'ncd'  => 'Do not clone date parameters',
 3246:                'prd'  => 'Clone date parameters as-is',
 3247:                'shd'  => 'Shift date parameters by number of days',
 3248:         );
 3249: }
 3250: 
 3251: sub coursecode_form {
 3252:     my ($dom,$context,$codetitles,$cat_titles,$cat_order,$num) = @_;
 3253:     my $output;
 3254:     my %rowtitle = &Apache::lonlocal::texthash (
 3255:                     instcode  => 'Course Category',
 3256:                     crosslist => 'Cross Listed Course',
 3257:                    );
 3258:     my %helpitem = ( 
 3259:                      instcode => 'Course_Request_Category',
 3260:                    );
 3261:     if ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 3262:         (ref($cat_order))) {
 3263:         my ($sel,$instsec,$lcsec);
 3264:         $sel = $context;
 3265:         if ($context eq 'crosslist') {
 3266:             $sel .= '_'.$num;
 3267:             $instsec = &mt('Institutional section').'<br />'.
 3268:                        '<input type="text" size="10" name="'.$sel.'_instsec" />';
 3269:             $lcsec = &mt('LON-CAPA section').'<br />'.
 3270:                      '<input type="text" size="10" name="'.$sel.'_lcsec" />';
 3271:         }
 3272:         if (@{$codetitles} > 0) {
 3273:             my $lastitem = pop(@{$codetitles});
 3274:             my $lastinput = '<input type="text" size="5" name="'.$sel.'_'.$lastitem.'" />';
 3275:             if (@{$codetitles} > 0) {
 3276:                 my $helplink;
 3277:                 if (defined($helpitem{$context})) {
 3278:                     $helplink = &Apache::loncommon::help_open_topic($helpitem{$context}).'&nbsp;';
 3279:                 }
 3280:                 $output = &Apache::lonhtmlcommon::row_title($helplink.$rowtitle{$context}).
 3281:                           '<table><tr>';
 3282:                 if ($context eq 'crosslist') {
 3283:                     $output .= '<td>'.&mt('Include?').'<br />'.
 3284:                                '<input type="checkbox" name="'.$sel.'" value="1" /></td>';
 3285:                 }
 3286:                 foreach my $title (@{$codetitles}) {
 3287:                     if (ref($cat_order->{$title}) eq 'ARRAY') {
 3288:                         if (@{$cat_order->{$title}} > 0) {
 3289:                             $output .= '<td align="center">'.$title.'<br />'."\n".
 3290:                                        '<select name="'.$sel.'_'.$title.'">'."\n".
 3291:                                        ' <option value="" selected="selected">'.
 3292:                                        &mt('Select').'</option>'."\n";
 3293:                             foreach my $item (@{$cat_order->{$title}}) {
 3294:                                 my $longitem = $item;
 3295:                                 if (ref($cat_titles->{$title}) eq 'HASH') {
 3296:                                     if ($cat_titles->{$title}{$item} ne '') {
 3297:                                         $longitem = $cat_titles->{$title}{$item};
 3298:                                     }
 3299:                                 }
 3300:                                 $output .= '<option value="'.$item.'">'.$longitem.
 3301:                                            '</option>'."\n";
 3302:                             }
 3303:                         }
 3304:                         $output .= '</select></td>'."\n";
 3305:                     }
 3306:                 }
 3307:                 if ($context eq 'crosslist') {
 3308:                     $output .= '<td align="center">'.$lastitem.'<br />'."\n".
 3309:                                $lastinput.'</td><td align="center">'.$instsec.'</td>'.
 3310:                                '<td align="center">'.$lcsec.'</td></tr></table>';
 3311:                 } else {
 3312:                     $output .= '</tr></table>'.
 3313:                                &Apache::lonhtmlcommon::row_closure().
 3314:                                &Apache::lonhtmlcommon::row_title('Course '.$lastitem).
 3315:                                $lastinput;
 3316:                 }
 3317:             } else {
 3318:                 if ($context eq 'crosslist') {
 3319:                     $output .= &Apache::lonhtmlcommon::row_title($rowtitle{$context}).
 3320:                                '<table><tr>'.
 3321:                                '<td align="center">'.$lastitem.'<br />'.$lastinput.'</td>'.
 3322:                                '<td align="center">'.$instsec.'</td><td>'.$lcsec.'</td>'.
 3323:                                '</tr></table>';
 3324:                 } else { 
 3325:                     $output .= &Apache::lonhtmlcommon::row_title('Course '.$lastitem).
 3326:                                $lastinput;
 3327:                 }
 3328:             }
 3329:             $output .=  &Apache::lonhtmlcommon::row_closure(1);
 3330:             push(@$codetitles,$lastitem);    
 3331:         } elsif ($context eq 'crosslist') {
 3332:             $output .= &Apache::lonhtmlcommon::row_title($rowtitle{$context}).
 3333:                        '<table><tr><td align="center">'.
 3334:                        '<span class="LC_nobreak">'.&mt('Include?').
 3335:                        '<input type="checkbox" name="'.$sel.'" value="1" /></span>'.
 3336:                        '</td><td align="center">'.&mt('Institutional ID').'<br />'.
 3337:                        '<input type="text" size="10" name="'.$sel.'_instsec" />'.
 3338:                        '</td><td align="center">'.$lcsec.'</td></tr></table>'.
 3339:                        &Apache::lonhtmlcommon::row_closure(1);
 3340:         }
 3341:     }
 3342:     return $output;
 3343: }
 3344: 
 3345: sub sections_form {
 3346:     my ($dom,$instcode,$num) = @_;
 3347:     my $rowtitle;
 3348:     if ($instcode eq '') {
 3349:         $rowtitle = &mt('Sections');
 3350:     } else {
 3351:         $rowtitle = &mt('Sections of [_1]',$instcode);
 3352:     }
 3353:     return &Apache::lonhtmlcommon::row_title($rowtitle).
 3354:            '<table><tr><td align="center">'.
 3355:            '<span class="LC_nobreak">'.&mt('Include?').
 3356:            '<input type="checkbox" name="sec_'.$num.'" value="1" /></span>'.
 3357:            '</td><td align="center">'.&mt('Institutional section').'<br />'.
 3358:            '<input type="text" size="10" name="secnum_'.$num.'" />'.
 3359:            '</td><td align="center">'.&mt('LON-CAPA section').'<br />'.
 3360:            '<input type="text" size="10" name="loncapasec_'.$num.'" />'.
 3361:            '</td></tr></table>'.
 3362:            &Apache::lonhtmlcommon::row_closure(1);
 3363: }
 3364: 
 3365: sub get_course_dom {
 3366:     my $codedom = &Apache::lonnet::default_login_domain();
 3367:     if ($env{'form.showdom'} ne '') {
 3368:         if (&Apache::lonnet::domain($env{'form.showdom'}) ne '') {
 3369:             return $env{'form.showdom'};
 3370:         }
 3371:     }
 3372:     if (($env{'user.domain'} ne '') && ($env{'user.domain'} ne 'public')) {
 3373:         my ($types,$typename) = &Apache::loncommon::course_types();
 3374:         if (ref($types) eq 'ARRAY') {
 3375:             foreach my $type (@{$types}) {
 3376:                 if (&Apache::lonnet::usertools_access($env{'user.name'},
 3377:                                                       $env{'user.domain'},$type,
 3378:                                                       undef,'requestcourses')) {
 3379:                     return $env{'user.domain'};
 3380:                 }
 3381:             }
 3382:             my (@possible_doms,%willtrust);
 3383:             foreach my $type (@{$types}) {
 3384:                 my $dom_str = $env{'environment.reqcrsotherdom.'.$type};
 3385:                 if ($dom_str ne '') {
 3386:                     my @domains = split(',',$dom_str);
 3387:                     foreach my $entry (@domains) {
 3388:                         my ($extdom,$extopt) = split(':',$entry);
 3389:                         unless (exists($willtrust{$extdom})) {
 3390:                             $willtrust{$extdom} = &Apache::lonnet::will_trust('reqcrs',$env{'user.domain'},$extdom);
 3391:                         }
 3392:                         if ($willtrust{$extdom}) {
 3393:                             if ($extdom eq $env{'request.role.domain'}) {
 3394:                                 return $extdom;
 3395:                             }
 3396:                             unless(grep(/^\Q$extdom\E$/,@possible_doms)) {
 3397:                                 push(@possible_doms,$extdom);
 3398:                             }
 3399:                         }
 3400:                     }
 3401:                 }
 3402:             }
 3403:             if (@possible_doms) {
 3404:                 @possible_doms = sort(@possible_doms);
 3405:                 return $possible_doms[0];
 3406:             }
 3407:         }
 3408:         $codedom = $env{'user.domain'};
 3409:         if ($env{'request.role.domain'} ne '') {
 3410:             $codedom = $env{'request.role.domain'};
 3411:         }
 3412:     }
 3413:     return $codedom;
 3414: }
 3415: 
 3416: sub display_navbuttons {
 3417:     my ($r,$dom,$formname,$prev,$prevtext,$next,$nexttext,$state,$other,$othertext) = @_;
 3418:     $r->print('<div class="LC_navbuttons">');
 3419:     if ($prev) {
 3420:         $r->print('<input type="button" name="previous" value = "'.$prevtext.'" '.
 3421:                   'onclick="javascript:backPage('."document.$formname,'$prev'".')"/>'.
 3422:                   ('&nbsp;'x3));
 3423:     } elsif ($prevtext) {
 3424:         $r->print('<input type="button" name="previous" value = "'.$prevtext.'" '.
 3425:                   'onclick="javascript:history.back()"/>'.('&nbsp;'x3));
 3426:     }
 3427:     if ($state eq 'details') {
 3428:         $r->print(' <input type="button" name="other" value="'.$othertext.'" '.
 3429:                   'onclick="javascript:nextPage('."document.$formname,'$other'".
 3430:                   ')" />');
 3431:     }
 3432:     my $gotnext;
 3433:     if ($state eq 'courseinfo') {
 3434:         $r->print('<input type="button" name="next" value="'.$nexttext.'" '.
 3435:                   'onclick="javascript:validateForm();" />');
 3436:         $gotnext = 1;
 3437:     } elsif ($state eq 'enrollment') {
 3438:         if (($env{'form.crstype'} eq 'official') && 
 3439:             (&Apache::lonnet::auto_run('',$dom))) {
 3440:             $r->print('<input type="button" name="next" value="'.$nexttext.'" '.
 3441:                       'onclick="javascript:validateEnrollSections('."document.$formname,'$next'".');" />');
 3442:                 $gotnext = 1;
 3443:         }
 3444:     } elsif ($state eq 'personnel') {
 3445:         if ($env{'form.persontotal'} > 0) { 
 3446:             $r->print('<input type="button" name="next" value="'.$nexttext.'" '.
 3447:                       'onclick="javascript:validatePersonnelSections('."document.$formname,'$next'".');" />');
 3448:             $gotnext = 1;
 3449:         }
 3450:     }
 3451:     unless ($gotnext) {
 3452:         if ($next) {
 3453:             $r->print('
 3454:                       <input type="button" name="next" value="'.$nexttext.'" '.
 3455:       'onclick="javascript:nextPage('."document.$formname,'$next'".')" />');
 3456:         }
 3457:     }
 3458:     $r->print('</div>');
 3459: }
 3460: 
 3461: sub print_request_outcome {
 3462:     my ($r,$lonhost,$dom,$codetitles,$code_order,$instcredits) = @_;
 3463:     my ($output,$cnum,$now,$req_notifylist,$crstype,$enrollstart,$enrollend,
 3464:         %sections,%crosslistings,%personnel,@baduname,@missingdom,%domconfig,
 3465:         $uniquecode);
 3466:     my $sectotal = $env{'form.sectotal'};
 3467:     my $crosslisttotal = 0;
 3468:     $cnum = $env{'form.cnum'};
 3469:     unless ($cnum =~ /^$match_courseid$/) {
 3470:         $output = &mt('Invalid LON-CAPA course number for the new course')."\n"; 
 3471:         return $output;
 3472:     }
 3473:     $crstype = $env{'form.crstype'};
 3474:     my %domconfig = &Apache::lonnet::get_dom('configuration',['requestcourses'],$dom);
 3475:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 3476:         if (ref($domconfig{'requestcourses'}{'notify'}) eq 'HASH') {
 3477:             $req_notifylist = $domconfig{'requestcourses'}{'notify'}{'approval'};
 3478:         }
 3479:         if (ref($domconfig{'requestcourses'}{'uniquecode'}) eq 'HASH') {
 3480:             $uniquecode = $domconfig{'requestcourses'}{'uniquecode'}{$crstype};
 3481:         }
 3482:     }
 3483:     $now = time;
 3484:     my $ccrole = 'cc';
 3485:     if ($crstype eq 'community') {
 3486:         $ccrole = 'co';
 3487:     }
 3488:     my @instsections;
 3489:     if ($crstype eq 'official') {
 3490:         if (&Apache::lonnet::auto_run('',$dom)) {
 3491:             ($enrollstart,$enrollend)=&dates_from_form('enrollstart','enrollend');
 3492:         }
 3493:         for (my $i=0; $i<$env{'form.sectotal'}; $i++) {
 3494:             if ($env{'form.sec_'.$i}) {
 3495:                 if ($env{'form.secnum_'.$i} ne '') {
 3496:                     my $sec = $env{'form.secnum_'.$i};
 3497:                     $sections{$i}{'inst'} = $sec;
 3498:                     if (($sec ne '') && (!grep(/^\Q$sec\E$/,@instsections))) {
 3499:                         push(@instsections,$sec);
 3500:                     }
 3501:                     $sections{$i}{'loncapa'} = $env{'form.loncapasec_'.$i};
 3502:                     $sections{$i}{'loncapa'} =~ s/\W//g;
 3503:                     if ($sections{$i}{'loncapa'} eq 'none') {
 3504:                         $sections{$i}{'loncapa'} = '';
 3505:                     }
 3506:                 }
 3507:             }
 3508:         }
 3509:         for (my $i=0; $i<$env{'form.crosslisttotal'}; $i++) {
 3510:             if ($env{'form.crosslist_'.$i}) {
 3511:                 my $xlistinfo = '';
 3512:                 if (ref($code_order) eq 'ARRAY') {
 3513:                     if (@{$code_order} > 0) {
 3514:                         foreach my $item (@{$code_order}) {
 3515:                             $xlistinfo .= $env{'form.crosslist_'.$i.'_'.$item};
 3516:                         }
 3517:                     }
 3518:                 }
 3519:                 $crosslistings{$i}{'instcode'} = $xlistinfo;
 3520:                 if ($xlistinfo ne '') {
 3521:                     $crosslisttotal ++;
 3522:                 }
 3523:                 $crosslistings{$i}{'instsec'} = $env{'form.crosslist_'.$i.'_instsec'}; 
 3524:                 $crosslistings{$i}{'loncapa'} = $env{'form.crosslist_'.$i.'_lcsec'};
 3525:             }
 3526:         }
 3527:     } else {
 3528:         $enrollstart = '';
 3529:         $enrollend = '';
 3530:     }
 3531:     my (%alerts,%rulematch,%inst_results,%curr_rules,%got_rules,%disallowmsg,%skipped);
 3532:     for (my $i=0; $i<$env{'form.persontotal'}; $i++) {
 3533:         my $uname = $env{'form.person_'.$i.'_uname'};
 3534:         my $udom = $env{'form.person_'.$i.'_dom'};
 3535:         if (($uname =~ /^$match_username$/) && ($udom =~ /^$match_domain$/)) {
 3536:             if (&Apache::lonnet::domain($udom) ne '') {
 3537:                 unless (ref($personnel{$uname.':'.$udom}) eq 'HASH') {
 3538:                     $personnel{$uname.':'.$udom} = {
 3539:                              firstname    => $env{'form.person_'.$i.'_firstname'},
 3540:                              lastname     => $env{'form.person_'.$i.'_lastname'},
 3541:                              emailaddr    => $env{'form.person_'.$i.'_emailaddr'},
 3542:                                                    };
 3543:                     if (&Apache::lonnet::homeserver($uname,$udom) eq 'no_host') {
 3544:                         my $usertype = &get_usertype($udom,$uname,\%curr_rules,\%got_rules);
 3545:                         if (&Apache::lonuserutils::can_create_user($udom,'requestcrs',$usertype)) {
 3546:                             my ($allowed,$msg,$authtype,$authparam) =
 3547:                                 &check_newuser_rules($udom,$uname,\%alerts,\%rulematch,
 3548:                                                      \%inst_results,\%curr_rules,\%got_rules);
 3549:                             if ($allowed) {
 3550:                                 my %domdefaults = &Apache::lonnet::get_domain_defaults($udom);
 3551:                                 if ($usertype eq 'official') {
 3552:                                     if ($authtype eq '') {
 3553:                                         $authtype = $domdefaults{'auth_def'};
 3554:                                         $authparam = $domdefaults{'auth_arg_def'};
 3555:                                     } else {
 3556:                                         if ($authtype eq 'loc') {
 3557:                                             $authtype = 'localauth';
 3558:                                         } elsif ($authtype eq 'int') {
 3559:                                             $authtype = 'internal';
 3560:                                         }
 3561:                                         if ($authtype !~ /^(krb4|krb5|internal|localauth)$/) {
 3562:                                             $authtype = $domdefaults{'auth_def'};
 3563:                                             $authparam = $domdefaults{'auth_arg_def'};
 3564:                                         }
 3565:                                     }
 3566:                                 } elsif ($usertype eq 'unofficial') {
 3567:                                     if ($authtype eq '') {
 3568:                                         $authtype = 'internal';
 3569:                                         $authparam = '';
 3570:                                     }
 3571:                                 } else {
 3572:                                     $authtype = $domdefaults{'auth_def'};
 3573:                                     $authparam = $domdefaults{'auth_arg_def'};
 3574:                                 }
 3575:                                 if (($authtype eq '') ||
 3576:                                     (($authtype =~/^krb(4|5)$/) && ($authparam eq '')) ||
 3577:                                     ($authtype !~ /^(krb4|krb5|internal|localauth)$/)) {
 3578:                                     $skipped{$uname.':'.$udom} = 1;
 3579:                                     next;
 3580:                                 } else {
 3581:                                     $personnel{$uname.':'.$udom}{'authtype'} = $authtype;
 3582:                                     $personnel{$uname.':'.$udom}{'autharg'} = $authparam;
 3583:                                 }
 3584:                             } else {
 3585:                                 $skipped{$uname.':'.$udom} = 1;
 3586:                                 next;
 3587:                             }
 3588:                         } else {
 3589:                             $skipped{$uname.':'.$udom} = 1;
 3590:                             next;
 3591:                         }
 3592:                     }
 3593:                 }
 3594:                 my $role = $env{'form.person_'.$i.'_role'};
 3595:                 unless ($role eq '') {
 3596:                     if (ref($personnel{$uname.':'.$udom}{'roles'}) eq 'ARRAY') {
 3597:                         my @curr_roles = @{$personnel{$uname.':'.$udom}{'roles'}};
 3598:                         unless (grep(/^\Q$role\E$/,@curr_roles)) {
 3599:                             push(@{$personnel{$uname.':'.$udom}{'roles'}},$role);
 3600:                         }
 3601:                     } else {
 3602:                         @{$personnel{$uname.':'.$udom}{'roles'}} = ($role);
 3603:                     }
 3604:                     if ($role eq $ccrole) {
 3605:                         @{$personnel{$uname.':'.$udom}{$role}{'usec'}} = ();
 3606:                     } else {
 3607:                         my @currsec = &Apache::loncommon::get_env_multiple('form.person_'.$i.'_sec');
 3608:                         my @allsecs;
 3609:                         foreach my $sec (@currsec) {
 3610:                             next unless ($sec =~ /\w/);
 3611:                             next if ($sec =~ /\W/);
 3612:                             next if ($sec eq 'none');
 3613:                             push(@allsecs,$sec);
 3614:                         }
 3615:                         my $newsec = $env{'form.person_'.$i.'_newsec'};
 3616:                         $newsec =~ s/^\s+//;
 3617:                         $newsec =~s/\s+$//;
 3618:                         my @newsecs = split(/[\s,;]+/,$newsec);
 3619:                         foreach my $sec (@newsecs) {
 3620:                             next if ($sec =~ /\W/);
 3621:                             next if ($sec eq 'none');
 3622:                             if ($sec ne '') {
 3623:                                 unless (grep(/^\Q$sec\E$/,@allsecs)) {
 3624:                                     push(@allsecs,$sec);
 3625:                                 }
 3626:                             }
 3627:                         }
 3628:                         @{$personnel{$uname.':'.$udom}{$role}{'usec'}} = @allsecs;
 3629:                     }
 3630:                 }
 3631:             } else {
 3632:                 push(@missingdom,$uname.':'.$udom);
 3633:             }
 3634:         } else {
 3635:             push(@baduname,$uname.':'.$udom);
 3636:         }
 3637:     }
 3638:     if (keys(%skipped)) {
 3639:         foreach my $key (keys(%skipped)) {
 3640:             delete($personnel{$key}); 
 3641:         }
 3642:     }
 3643:     my ($accessstart,$accessend) = &dates_from_form('accessstart','accessend');
 3644:     my $autodrops = 0;
 3645:     if ($env{'form.autodrops'}) {
 3646:         $autodrops = $env{'form.autodrops'}; 
 3647:     }
 3648:     my $autoadds = 0;
 3649:     if ($env{'form.autoadds'}) {
 3650:         $autoadds = $env{'form.autoadds'};
 3651:     }
 3652:     my $instcode = '';
 3653:     if (exists($env{'form.instcode'})) {
 3654:         $instcode = $env{'form.instcode'};
 3655:     }
 3656:     my $credits;
 3657:     if ($instcredits) {
 3658:         $credits = $instcredits;
 3659:     } elsif (exists($env{'form.coursecredits'})) {
 3660:         $credits = $env{'form.coursecredits'};
 3661:     }
 3662:     my $clonecrs = '';
 3663:     my $clonedom = '';
 3664:     if (($env{'form.cloning'}) &&
 3665:         ($env{'form.clonecrs'} =~ /^($match_courseid)$/) && 
 3666:         ($env{'form.clonedom'} =~ /^($match_domain)$/)) {
 3667:         my $clonehome = &Apache::lonnet::homeserver($env{'form.clonecrs'},
 3668:                                                     $env{'form.clonedom'});
 3669:         if ($clonehome ne 'no_host') {  
 3670:             my $canclone =  
 3671:                 &Apache::loncoursequeueadmin::can_clone_course($env{'user.name'},
 3672:                         $env{'user.domain'},$env{'form.clonecrs'},$env{'form.clonedom'},
 3673:                         $crstype,$dom,$instcode);
 3674:             if ($canclone) {
 3675:                 $clonecrs = $env{'form.clonecrs'};
 3676:                 $clonedom = $env{'form.clonedom'};
 3677:             }
 3678:         }
 3679:     }
 3680:     my $details = {
 3681:                     owner          => $env{'user.name'},
 3682:                     domain         => $env{'user.domain'}, 
 3683:                     cdom           => $dom,
 3684:                     cnum           => $cnum,
 3685:                     coursehome     => $env{'form.chome'},
 3686:                     cdescr         => $env{'form.cdescr'},
 3687:                     crstype        => $env{'form.crstype'},
 3688:                     instcode       => $instcode,
 3689:                     defaultcredits => $credits, 
 3690:                     uniquecode     => $uniquecode,
 3691:                     clonedom       => $clonedom,
 3692:                     clonecrs       => $clonecrs,
 3693:                     datemode       => $env{'form.datemode'},
 3694:                     dateshift      => $env{'form.dateshift'},
 3695:                     sectotal       => $sectotal,
 3696:                     sections       => \%sections,
 3697:                     crosslisttotal => $crosslisttotal,
 3698:                     crosslists     => \%crosslistings,
 3699:                     autoadds       => $autoadds,
 3700:                     autodrops      => $autodrops,
 3701:                     enrollstart    => $enrollstart,
 3702:                     enrollend      => $enrollend,
 3703:                     accessstart    => $accessstart,
 3704:                     accessend      => $accessend,
 3705:                     personnel      => \%personnel,
 3706:                   };
 3707:     my ($result,$output,$customized) = &process_request($r,$lonhost,$dom,$cnum,$crstype,$now,$details,
 3708:                                                         $instcode,$req_notifylist,\@instsections,\%domconfig);
 3709:     return ($result,$output,$customized);
 3710: }
 3711: 
 3712: sub process_request {
 3713:     my ($r,$lonhost,$dom,$cnum,$crstype,$now,$details,$instcode,$req_notifylist,$instsections,
 3714:         $domconfig) = @_; 
 3715:     my (@inststatuses,$storeresult,$creationresult,$output,$customized);
 3716:     my $val = 
 3717:         &Apache::loncoursequeueadmin::get_processtype('course',$env{'user.name'},
 3718:                                                       $env{'user.domain'},$env{'user.adv'},
 3719:                                                       $dom,$crstype,\@inststatuses,$domconfig);
 3720:     if ($val eq '') {
 3721:         if ($crstype eq 'official') {
 3722:             $output = &mt('You are not permitted to request creation of official courses.');
 3723:         } elsif ($crstype eq 'unofficial') {
 3724:             $output = &mt('You are not permitted to request creation of unofficial courses.');
 3725:         } elsif ($crstype eq 'community') {
 3726:             $output = &mt('You are not permitted to request creation of communities');
 3727:         } elsif ($crstype eq 'textbook') {
 3728:             $output = &mt('You are not permitted to request creation of textbook courses');
 3729:         } elsif ($crstype eq 'placement') {
 3730:             $output = &mt('You are not permitted to request creation of placement tests');
 3731:         } else {
 3732:             $output = &mt('Unrecognized course type: [_1]',$crstype);
 3733:         }
 3734:         $storeresult = 'notpermitted'; 
 3735:     } else {
 3736:         my ($disposition,$message,$reqstatus,$coursedesc,$accessstart,$accessend,%customvalidation);
 3737:         my %reqhash = (
 3738:                         reqtime   => $now,
 3739:                         crstype   => $crstype,
 3740:                         details   => $details,
 3741:                       );
 3742:         my $requestkey = $dom.'_'.$cnum;
 3743:         my $validationerror;
 3744:         my $fullname = &Apache::loncommon::plainname($env{'user.name'},
 3745:                                                      $env{'user.domain'});
 3746:         if (ref($details) eq 'HASH') {
 3747:             $coursedesc = $details->{'cdescr'};
 3748:             $accessstart = $details->{'accessstart'};
 3749:             $accessend = $details->{'accessend'};
 3750:         }
 3751:         if ($val eq 'autolimit=') {
 3752:             $disposition = 'process';
 3753:         } elsif ($val =~ /^autolimit=(\d+)$/) {
 3754:             my $limit = $1;
 3755:             $disposition = &check_autolimit($env{'user.name'},$env{'user.domain'},
 3756:                                             $dom,$crstype,$limit,\$message);
 3757:         } elsif ($val eq 'validate') {
 3758:             my ($inststatuslist,$validationchk,$validation);
 3759:             if (ref($details) eq 'HASH') {
 3760:                 if ($details->{'clonecrs'}) {
 3761:                     $customvalidation{'_LC_clonefrom'} = $details->{'clonedom'}.'_'.$details->{'clonecrs'};
 3762:                 }
 3763:             }
 3764:             if (@inststatuses > 0) {
 3765:                 $inststatuslist = join(',',@inststatuses);
 3766:             }
 3767:             my $instseclist;
 3768:             if (ref($instsections) eq 'ARRAY') {
 3769:                 if (@{$instsections} > 0) {
 3770:                     $instseclist = join(',',@{$instsections});
 3771:                 }
 3772:             }
 3773: #
 3774: # Retrieve any custom form information used for validation 
 3775: #
 3776:             my $preprocess = &Apache::lonnet::auto_crsreq_update($dom,$cnum,$crstype,'prevalidate',$env{'user.name'},
 3777:                                                                  $env{'user.domain'},$fullname,$coursedesc);
 3778:             if (ref($preprocess) eq 'HASH') {
 3779:                 &custom_formitems($preprocess,\%customvalidation);
 3780:             }
 3781:             $validationchk = 
 3782:                 &Apache::lonnet::auto_courserequest_validation($dom,
 3783:                     $env{'user.name'}.':'.$env{'user.domain'},$crstype,
 3784:                     $inststatuslist,$instcode,$instseclist,\%customvalidation);
 3785:             if ($validationchk =~ /:/) {
 3786:                 ($validation,$message) = split(':',$validationchk);
 3787:             } else {
 3788:                 $validation = $validationchk;
 3789:             }
 3790:             if ($validation =~ /^error(.*)$/) {
 3791:                 $disposition = 'approval';
 3792:                 $validationerror = $1;
 3793:             } else {
 3794:                 $disposition = $validation;
 3795:             }
 3796:         } else {
 3797:             $disposition = 'approval';
 3798:         }
 3799:         $reqhash{'disposition'} = $disposition;
 3800:         $reqstatus = $disposition;
 3801:         my ($modified,$queued,$token,%customitems);
 3802:         unless ($disposition eq 'rejected') {
 3803:             my $inprocess = &Apache::lonnet::auto_crsreq_update($dom,$cnum,$crstype,'process',$env{'user.name'},
 3804:                                                                 $env{'user.domain'},$fullname,$coursedesc,undef,
 3805:                                                                 undef,undef,\%customvalidation);
 3806: #
 3807: # Retrieve any custom form information submitted with review page and include in request details.
 3808: #
 3809:             if (ref($inprocess) eq 'HASH') {
 3810:                 &custom_formitems($inprocess,\%customitems);
 3811:                 foreach my $key (keys(%customitems)) {
 3812:                     $reqhash{'custom'}{$key} = $customitems{$key};
 3813:                 }
 3814:             }
 3815:         }
 3816:         if ($disposition eq 'rejected') {
 3817:             if ($crstype eq 'community') {
 3818:                 $output = &mt('Your community request was rejected.');
 3819:             } else {
 3820:                 $output = &mt('Your course request was rejected.');
 3821:             }
 3822:             if ($message) {
 3823:                 $output .= '<div class="LC_warning">'.$message.'</div>';
 3824:             }
 3825:             $storeresult = 'rejected';
 3826:         } elsif ($disposition eq 'process') {
 3827:             my %domdefs = &Apache::lonnet::get_domain_defaults($dom);
 3828:             my ($logmsg,$newusermsg,$addresult,$enrollcount,$response,$keysmsg,%longroles,$code);
 3829:             my $type = 'Course';
 3830:             if ($crstype eq 'community') {
 3831:                 $type = 'Community';
 3832:             }
 3833:             my @roles = &Apache::lonuserutils::roles_by_context('course','',$type);
 3834:             foreach my $role (@roles) {
 3835:                 $longroles{$role}=&Apache::lonnet::plaintext($role,$type);
 3836:             }
 3837:             $r->print('<div id="processing" style="display:block;">'."\n".
 3838:                       &mt('Your request is being processed; this page will update when processing is complete.').
 3839:                       '</div>');
 3840:             $r->rflush();
 3841:             if (ref($details) eq 'HASH') {
 3842:                 if ($details->{'clonecrs'}) {
 3843:                     $customitems{'_LC_clonefrom'} = $details->{'clonedom'}.'_'.$details->{'clonecrs'};
 3844:                 }
 3845:             }
 3846:             $customitems{'_LC_ownerfullname'} = &Apache::loncommon::plainname($env{'user.name'},$env{'user.domain'},'first');
 3847:             my $owneremail;
 3848:             my %emails = &Apache::loncommon::getemails();
 3849:             foreach my $email ('permanentemail','critnotification','notification') {
 3850:                 $owneremail = $emails{$email};
 3851:                 last if ($owneremail ne '');
 3852:             }
 3853:             if ($owneremail ne '') {
 3854:                 $customitems{'_LC_owneremail'} = $owneremail;
 3855:             }
 3856:             $customitems{'_LC_coursedomainname'} = &Apache::lonnet::domain($dom,'description');
 3857:             $customitems{'_LC_coursedescription'} = $coursedesc;
 3858:             $customitems{'_LC_coursestartdate'} = $accessstart;
 3859:             $customitems{'_LC_courseenddate'} = $accessend;
 3860:             my ($result,$postprocess) = &Apache::loncoursequeueadmin::course_creation($dom,$cnum,
 3861:                                           'autocreate',$details,\$logmsg,\$newusermsg,\$addresult,
 3862:                                           \$enrollcount,\$response,\$keysmsg,\%domdefs,\%longroles,
 3863:                                           \$code,\%customitems);
 3864:             if (ref($postprocess) eq 'HASH') {
 3865:                 $customized = $postprocess->{'createdcustomized'};
 3866:             }
 3867:             if ($result eq 'created') {
 3868:                 $disposition = 'created';
 3869:                 $reqstatus = 'created';
 3870:                 my $role_result = &update_requestors_roles($dom,$cnum,$crstype,$details,
 3871:                                                            \%longroles);
 3872:                 if ($crstype eq 'community') {
 3873:                     $output = '<p>'.&mt('Your community request has been processed and the community has been created.');
 3874:                 } else {
 3875:                     $output = '<p>'.&mt('Your course request has been processed and the course has been created.');
 3876:                 }
 3877:                 if (($code) || ((ref($postprocess) eq 'HASH') && 
 3878:                                 (($postprocess->{'createdweb'}) || ($postprocess->{'createdmsg'})))) {
 3879:                     $output .= &notification_information($disposition,$env{'user.name'}.':'.$env{'user.domain'},
 3880:                                                          $dom,$cnum,$now,$code,$postprocess);
 3881:                 }
 3882:                 if ($code) {
 3883:                     $reqhash{'code'} = $code;
 3884:                 }
 3885:                 if (ref($postprocess) eq 'HASH') {
 3886:                     if (ref($postprocess->{'createdactions'}) eq 'HASH') {
 3887:                         if (ref($postprocess->{'createdactions'}{'environment'}) eq 'HASH') {
 3888:                             &Apache::loncoursequeueadmin::postprocess_crsenv($dom,$cnum,
 3889:                                                                              $postprocess->{'createdactions'}{'environment'});
 3890:                         }
 3891:                     }
 3892:                 }
 3893:                 unless ($customized) { 
 3894:                     $output .= '<br />'.$role_result;
 3895:                 }
 3896:                 $output .= '</p>';
 3897:                 $creationresult = 'created';
 3898:                 # Flush the course logs so reverse user roles immediately updated
 3899:                 unless ($registered_flush) {
 3900:                     my $handlers = $r->get_handlers('PerlCleanupHandler');
 3901:                     $r->set_handlers('PerlCleanupHandler' => [\&Apache::lonnet::flushcourselogs,@{$handlers}]);
 3902:                     $registered_flush=1;
 3903:                 }
 3904:                 if ($instcode ne '') {
 3905:                     &Apache::lonnet::devalidate_cache_new('instcats',$dom);
 3906:                     # Update cache of self-cataloging courses on institution's server(s).
 3907:                     if (&Apache::lonnet::shared_institution($dom)) {
 3908:                         unless ($registered_instcats) {
 3909:                             my $handlers = $r->get_handlers('PerlCleanupHandler');
 3910:                             $r->set_handlers('PerlCleanupHandler' => [\&devalidate_remote_instcats,@{$handlers}]);
 3911:                             $registered_instcats=1;
 3912:                             $modified_dom = $dom;
 3913:                         }
 3914:                     }
 3915:                 }
 3916:             } else {
 3917:                 $output = '<span class="LC_error">';
 3918:                 if ($crstype eq 'community') {
 3919:                     $output .= &mt('An error occurred when processing your community request.');
 3920:                 } else {
 3921:                     $output .= &mt('An error occurred when processing your course request.');
 3922:                 }
 3923:                 $output .= '<br />'.
 3924:                            &mt('You may want to review the request details and submit the request again.').
 3925:                           '</span>';
 3926:                 $creationresult = 'error';
 3927:             }
 3928:         } else {
 3929:             my $requestid = $cnum.'_'.$disposition;
 3930:             my $request = {
 3931:                             $requestid => {
 3932:                                             timestamp   => $now,
 3933:                                             crstype     => $crstype,
 3934:                                             ownername   => $env{'user.name'},
 3935:                                             ownerdom    => $env{'user.domain'},
 3936:                                             description => $env{'form.cdescr'},
 3937:                                             lonhost     => $lonhost,
 3938:                                           },
 3939:                           };
 3940:             if ($crstype eq 'official') {
 3941:                 $request->{$requestid}->{'instcode'} = $instcode;
 3942:             }
 3943:             my $statuskey = 'status:'.$dom.':'.$cnum;
 3944:             my %userreqhash = &Apache::lonnet::get('courserequests',[$statuskey],
 3945:                                                    $env{'user.domain'},$env{'user.name'});
 3946:             if ($userreqhash{$statuskey} ne '') {
 3947:                 $modified = 1;
 3948:                 my $uname = &Apache::lonnet::get_domainconfiguser($dom);
 3949:                 my %queuehash = &Apache::lonnet::get('courserequestqueue',
 3950:                                                      [$cnum.'_approval',
 3951:                                                       $cnum.'_pending'],$dom,$uname);
 3952:                 if (($queuehash{$cnum.'_approval'} ne '') || 
 3953:                     ($queuehash{$cnum.'_pending'} ne '')) {
 3954:                     $queued = 1;
 3955:                     if (ref($queuehash{$cnum.'_pending'}) eq 'HASH') {
 3956:                         $token = $queuehash{$cnum.'_pending'}{'token'};
 3957:                     } 
 3958:                 }
 3959:             }
 3960:             unless ($queued) {
 3961:                 if (($disposition eq 'pending') && ($crstype ne 'official')) {
 3962:                     my %reqinfo = (
 3963:                                     $cnum.':'.$dom => $now.':'.$env{'user.name'}.':'.$env{'user.domain'},
 3964:                                   );
 3965:                      $token = &Apache::lonnet::tmpput(\%reqinfo,$lonhost);
 3966:                      $request->{$requestid}->{'token'} = $token;
 3967:                 }
 3968:                 my $putresult = &Apache::lonnet::newput_dom('courserequestqueue',$request,
 3969:                                                             $dom);
 3970:                 if ($putresult eq 'ok') {
 3971:                     if ($crstype eq 'community') {
 3972:                         $output .= &mt('Your community request has been recorded.');
 3973:                     } else {
 3974:                         $output .= &mt('Your course request has been recorded.') 
 3975:                     }
 3976:                     unless ($disposition eq 'pending') { 
 3977:                         $output .= '<br />'.
 3978:                                    &notification_information($disposition,$req_notifylist,
 3979:                                                              $dom,$cnum,$now);
 3980:                     }
 3981:                 } else {
 3982:                     $reqstatus = 'domainerror';
 3983:                     $reqhash{'disposition'} = $disposition;
 3984:                     my $warning = &mt('An error occurred saving your request in the pending requests queue.');
 3985:                     $output = '<span class"LC_warning">'.$warning.'</span><br />';
 3986:                 }
 3987:             }
 3988:         }
 3989:         ($storeresult,my $updateresult) = 
 3990:             &Apache::loncoursequeueadmin::update_coursereq_status(\%reqhash,$dom,
 3991:                 $cnum,$reqstatus,'request',$env{'user.domain'},$env{'user.name'});
 3992:         if ($storeresult eq 'ok') {
 3993:             my $postprocess;
 3994:             if (($disposition eq 'approval') || ($disposition eq 'pending')) {
 3995:                 my $updateaction = $disposition;
 3996:                 if ($disposition eq 'approval') {
 3997:                     $updateaction = 'queued';
 3998:                 }
 3999:                 my $fullname = &Apache::loncommon::plainname($env{'user.name'},
 4000:                                                              $env{'user.domain'});
 4001:                 $postprocess =
 4002:                     &Apache::lonnet::auto_crsreq_update($dom,$cnum,$crstype,$updateaction,$env{'user.name'},
 4003:                                                         $env{'user.domain'},$fullname,$env{'form.cdescr'});
 4004:             }
 4005:             if ($modified && $queued) {
 4006:                 if ($crstype eq 'community') {
 4007:                     $output .= '<p>'.&mt('Your community request has been updated').'</p>';
 4008:                 } else {
 4009:                     $output .= '<p>'.&mt('Your course request has been updated').'</p>';
 4010:                 }
 4011:                 if ($disposition eq 'approval') {
 4012:                     $output .= &notification_information($disposition,$req_notifylist,$dom,$cnum,$now);
 4013:                 }
 4014:             }
 4015:             if ($disposition eq 'approval') {
 4016:                 if ((ref($postprocess) eq 'HASH') && 
 4017:                     ((ref($postprocess->{'queuedmsg'}) eq 'HASH') || ($postprocess->{'queuedweb'}))) { 
 4018:                     &notification_information($disposition,undef,$dom,$cnum,$now,undef,$postprocess);
 4019:                     $customized = $postprocess->{'createdcustomized'};
 4020:                 }
 4021:             } elsif ($disposition eq 'pending') {
 4022:                 my $pendingform;
 4023:                 if ($crstype ne 'official') {
 4024:                     $pendingform = &pending_validation_form($dom,$cnum,$crstype,$now,$token,
 4025:                                                             $lonhost,$env{'form.cdescr'});
 4026:                 }
 4027:                 if ($pendingform) {
 4028:                     $output .= $pendingform;
 4029:                 } else { 
 4030:                     $output .= &notification_information($disposition,undef,$dom,$cnum,$now,undef,$postprocess);
 4031:                 }
 4032:                 if (ref($postprocess) eq 'HASH') {
 4033:                     $customized = $postprocess->{'createdcustomized'};
 4034:                 }
 4035:             }
 4036:         }
 4037:         if ($validationerror ne '') {
 4038:             $output .= '<p class="LC_warning">'.&mt('An error occurred validating your request with institutional data sources: [_1].',$validationerror).'</p>';
 4039:         }
 4040:         if ($updateresult) {
 4041:             $output .= $updateresult;
 4042:         }
 4043:     }
 4044:     if ($creationresult ne '') {
 4045:         return ($creationresult,$output,$customized);
 4046:     } else {
 4047:         return ($storeresult,$output,$customized);
 4048:     }
 4049: }
 4050: 
 4051: sub devalidate_remote_instcats {
 4052:     if ($modified_dom ne '') {
 4053:         my %servers = &Apache::lonnet::internet_dom_servers($modified_dom);
 4054:         my %thismachine;
 4055:         map { $thismachine{$_} = 1; } &Apache::lonnet::current_machine_ids();
 4056:         if (keys(%servers)) {
 4057:             foreach my $server (keys(%servers)) {
 4058:                 next if ($thismachine{$server});
 4059:                 &Apache::lonnet::remote_devalidate_cache($server,['instcats:'.$modified_dom]);
 4060:             }
 4061:         }
 4062:         $modified_dom = '';
 4063:     }
 4064:     return;
 4065: }
 4066: 
 4067: sub custom_formitems {
 4068:     my ($preprocess,$customhash) = @_;
 4069:     return unless ((ref($preprocess) eq 'HASH') && (ref($customhash) eq 'HASH'));  
 4070:     if (ref($preprocess->{'formitems'}) eq 'HASH') {
 4071:         foreach my $key (keys(%{$preprocess->{'formitems'}})) {
 4072:             if ($preprocess->{'formitems'}->{$key} eq 'multiple') {
 4073:                 if (exists($env{'form.'.$key})) {
 4074:                     my @items = &Apache::loncommon::get_env_multiple($env{'form.'.$key});
 4075:                     foreach my $item (@items) {
 4076:                         $item =~ s/(`)/'/g;
 4077:                         $item =~ s/\$/\(\$\)/g;
 4078:                         push(@{$customhash->{$key}},$item);
 4079:                     }
 4080:                 }
 4081:             } else {
 4082:                 if (exists($env{'form.'.$key})) {
 4083:                     $customhash->{$key} = $env{'form.'.$key};
 4084:                     $customhash->{$key} =~ s/(`)/'/g;
 4085:                     $customhash->{$key} =~ s/\$/\(\$\)/g;
 4086:                 }
 4087:             }
 4088:         }
 4089:     }
 4090: }
 4091: 
 4092: sub update_requestors_roles {
 4093:     my ($dom,$cnum,$crstype,$details,$longroles) = @_;
 4094:     my $now = time;
 4095:     my ($active,$future,$numactive,$numfuture,$output);
 4096:     my $owner = $env{'user.name'}.':'.$env{'user.domain'};
 4097:     if (ref($details) eq 'HASH') {
 4098:         if (ref($details->{'personnel'}) eq 'HASH') {
 4099:             my $ccrole = 'cc';
 4100:             if ($crstype eq 'community') {
 4101:                 $ccrole = 'co';
 4102:             }
 4103:             unless (ref($details->{'personnel'}{$owner}) eq 'HASH') {
 4104:                 $details->{'personnel'}{$owner} = {
 4105:                                                     'roles' => [$ccrole],
 4106:                                                     $ccrole => { 'usec' => [] },
 4107:                                                   };
 4108:             }
 4109:             my @roles;
 4110:             if (ref($details->{'personnel'}{$owner}{'roles'}) eq 'ARRAY') {
 4111:                 @roles = sort(@{$details->{'personnel'}{$owner}{'roles'}});
 4112:                 unless (grep(/^\Q$ccrole\E$/,@roles)) {
 4113:                     push(@roles,$ccrole);
 4114:                 }
 4115:             } else {
 4116:                 @roles = ($ccrole);
 4117:             }
 4118:             foreach my $role (@roles) {
 4119:                 my $refresh=$env{'user.refresh.time'};
 4120:                 if ($refresh eq '') {
 4121:                     $refresh = $env{'user.login.time'};
 4122:                 }
 4123:                 if ($refresh eq '') {
 4124:                     $refresh = $now;
 4125:                 }
 4126:                 my $start = $refresh-1;
 4127:                 my $end = '0';
 4128:                 if ($role eq 'st') {
 4129:                     if ($details->{'accessstart'} ne '') {
 4130:                         $start = $details->{'accessstart'};
 4131:                     }
 4132:                     if ($details->{'accessend'} ne '') {
 4133:                         $end = $details->{'accessend'};
 4134:                     }
 4135:                 }
 4136:                 my @usecs;
 4137:                 if ($role ne $ccrole) {
 4138:                     if (ref($details->{'personnel'}{$owner}{$role}{'usec'}) eq 'ARRAY') {
 4139:                         @usecs = @{$details->{'personnel'}{$owner}{$role}{'usec'}};
 4140:                     }
 4141:                 } 
 4142:                 if ($role eq 'st') {
 4143:                     if (@usecs > 1) {
 4144:                         my $firstsec = $usecs[0];
 4145:                         @usecs = ($firstsec);
 4146:                     }
 4147:                 }
 4148:                 if (@usecs == 0) {
 4149:                     push(@usecs,'');
 4150:                 }
 4151:                 foreach my $usec (@usecs) {
 4152:                     my (%userroles,%newrole,%newgroups,$spec,$area);
 4153:                     my $area = '/'.$dom.'/'.$cnum;
 4154:                     my $spec = $role.'.'.$area;
 4155:                     if ($usec ne '') {
 4156:                        $spec .= '/'.$usec;
 4157:                        $area .= '/'.$usec;
 4158:                     }
 4159:                     if ($role =~ /^cr\//) {
 4160:                         &Apache::lonnet::custom_roleprivs(\%newrole,$role,$dom,
 4161:                                                           $cnum,$spec,$area);
 4162:                     } else {
 4163:                         &Apache::lonnet::standard_roleprivs(\%newrole,$role,$dom,
 4164:                                                             $spec,$cnum,$area);
 4165:                     }
 4166:                     &Apache::lonnet::set_userprivs(\%userroles,\%newrole,
 4167:                                                    \%newgroups);
 4168:                     $userroles{'user.role.'.$spec} = $start.'.'.$end;
 4169:                     &Apache::lonnet::appenv(\%userroles,[$role,'cm']);
 4170:                     if (($end == 0) || ($end > $now)) {
 4171:                         my $showrole = $role;
 4172:                         if ($role =~ /^cr\//) {
 4173:                             $showrole = &Apache::lonnet::plaintext($role,$crstype);
 4174:                         } elsif (ref($longroles) eq 'HASH') {
 4175:                             if ($longroles->{$role} ne '') {
 4176:                                 $showrole = $longroles->{$role};
 4177:                             }
 4178:                         }
 4179:                         if ($start <= $now) {
 4180:                             $active .= '<li><a href="/adm/roles?selectrole=1&'.
 4181:                                        $spec.'=1">'.$showrole;
 4182:                             if ($usec ne '') {
 4183:                                 $active .= ' - '.&mt('section:').' '.$usec; 
 4184:                             }
 4185:                             $active .= '</a></li>';
 4186:                             $numactive ++;
 4187:                         } else { 
 4188:                             $future .= '<li>'.$showrole;
 4189:                             if ($usec ne '') {
 4190:                                 $future .= ' - '.&mt('section:').' '.$usec;
 4191:                             }
 4192:                             $future .= '</li>';
 4193:                             $numfuture ++;
 4194:                         }
 4195:                     }
 4196:                 }
 4197:             }
 4198:         }
 4199:     }
 4200:     if ($active) {
 4201:         if ($numactive == 1) {
 4202:             if ($crstype eq 'Community') {
 4203:                 $output = &mt('Use the following link to enter the community:');
 4204:             } else {
 4205:                 $output = &mt('Use the following link to enter the course:'); 
 4206:             }
 4207:         } else {
 4208:             if ($crstype eq 'Community') {
 4209:                 $output = &mt('Use the following links to your new roles to enter the community:');
 4210:             } else {
 4211:                 $output = &mt('Use the following links to your new roles to enter the course:');
 4212:             }
 4213:         }
 4214:         $output .= ' <ul>'.$active.'</ul><br />';
 4215:     }
 4216:     if ($future) {
 4217:         if ($crstype eq 'Community') {
 4218:             $output .= &mt('The following community [quant,_1,role] will become available for selection from your [_2]roles page[_3], once the default student access start date - [_4] - has been reached:',$numfuture,'<a href="/adm/roles">','</a>',&Apache::lonlocal::locallocaltime($details->{'accessstart'}))
 4219:         } else {
 4220:             $output .= &mt('The following course [quant,_1,role] will become available for selection from your [_2]roles page[_3], once the default student access start date - [_4] - has been reached:',$numfuture,'<a href="/adm/roles">','</a>',&Apache::lonlocal::locallocaltime($details->{'accessstart'}));
 4221:         }
 4222:         $output .= ' <ul>'.$future.'</ul>';
 4223:     }
 4224:     return $output;
 4225: }
 4226: 
 4227: sub notification_information {
 4228:     my ($disposition,$req_notifylist,$dom,$cnum,$now,$code,$postprocess) = @_;
 4229:     my %emails = &Apache::loncommon::getemails();
 4230:     my $address;
 4231:     if (($emails{'permanentemail'} ne '') || ($emails{'notification'} ne '')) {
 4232:         $address = $emails{'permanentemail'};
 4233:         if ($address eq '') {
 4234:             $address = $emails{'notification'};
 4235:         }
 4236:     }
 4237:     my $output;
 4238:     if ($disposition eq 'approval') {
 4239:         $output .= &mt('A message will be sent to your LON-CAPA account when a domain coordinator takes action on your request.').'<br />'.
 4240:                    &mt('To access your LON-CAPA message, go to the Main Menu and click on "Send and Receive Messages".').'<br />';
 4241:         if ($address ne '') {
 4242:             $output.= &mt('An e-mail will also be sent to: [_1] when this occurs.',$address).'<br />';
 4243:         }
 4244:         if ($req_notifylist) {
 4245:             my $fullname = &Apache::loncommon::plainname($env{'user.name'},
 4246:                                                          $env{'user.domain'});
 4247:             my $sender = $env{'user.name'}.':'.$env{'user.domain'};
 4248:             &Apache::loncoursequeueadmin::send_selfserve_notification($req_notifylist,"$fullname ($env{'user.name'}:$env{'user.domain'})",
 4249:                                                                       'undef',$env{'form.cdescr'},$now,'coursereq',$sender);
 4250:         }
 4251:         if (ref($postprocess) eq 'HASH') {
 4252:             if (ref($postprocess->{'queuedmsg'}) eq 'ARRAY') {
 4253:                 if (scalar(@{$postprocess->{'queuedmsg'}}) > 0) {
 4254:                     my $recipient = $env{'user.name'}.':'.$env{'user.domain'};
 4255:                     my $sender = $recipient;
 4256:                     my $addmsg = [];
 4257:                     foreach my $item (@{$postprocess->{'queuedmsg'}}) {
 4258:                         if (ref($item) eq 'HASH') {
 4259:                             if ($item->{'mt'} ne '') {
 4260:                                 push(@{$addmsg},$item);
 4261:                             }
 4262:                         }
 4263:                     }
 4264:                     if (scalar(@{$addmsg}) > 0) {
 4265:                         &Apache::loncoursequeueadmin::send_selfserve_notification($recipient,$addmsg,undef,
 4266:                                                                                   $env{'form.cdescr'},$now,
 4267:                                                                                   'queuedcrsreq',$sender);
 4268:                     }
 4269:                 }
 4270:             }
 4271:             if ($postprocess->{'queuedweb'}) {
 4272:                 $output .= $postprocess->{'queuedweb'};
 4273:             }
 4274:         }
 4275:     } elsif ($disposition eq 'pending') {
 4276:         my $pending_default = '<div class="LC_info">'.
 4277: &mt('Your request has been placed in a queue pending administrative action.').'<br />'.
 4278: &mt("Usually this means that your institution's information systems do not list you among the instructional personnel for this course.").'<br />'.
 4279: &mt('The list of instructional personnel for the course will be automatically checked daily, and once you are listed the request will be processed.').
 4280:                        '</div>';
 4281:         if (ref($postprocess) eq 'HASH') {
 4282:             if ($postprocess->{'pendingweb'}) {
 4283:                 $output .= $postprocess->{'pendingweb'};
 4284:             } else {
 4285:                 $output .= $pending_default;
 4286:             }
 4287:         } else {
 4288:             $output .= $pending_default;
 4289:         }
 4290:     } elsif ($disposition eq 'created') {
 4291:         if (($code) || ((ref($postprocess) eq 'HASH') && 
 4292:             ((ref($postprocess->{'createdmsg'}) eq 'ARRAY') || ($postprocess->{'createdweb'})))) {
 4293:             my $addmsg = [];
 4294:             my $recipient = $env{'user.name'}.':'.$env{'user.domain'};
 4295:             my $sender = $recipient;
 4296:             if ($code) {
 4297:                 push(@{$addmsg},{
 4298:                                   mt   => 'Students can automatically select your course: "[_1]" by entering this code: [_2]',
 4299:                                   args => [$env{'form.cdescr'},$code],
 4300:                                 });
 4301:                 $output .= '<p>'.
 4302:                            &mt('Students can automatically select your course by entering this code: [_1].','<b>'.$code.'</b>').
 4303:                            '<br />'.
 4304:                            &mt('A message has been sent to your LON-CAPA account with this information.');
 4305:                 if ($address ne '') {
 4306:                     $output.= '<br />'.&mt('An e-mail has also been sent to: [_1] with this code.',$address);
 4307:                 }
 4308:                 $output .= '</p>';
 4309:             }
 4310:             if (ref($postprocess) eq 'HASH') {
 4311:                 if (ref($postprocess->{'createdmsg'}) eq 'ARRAY') {
 4312:                     foreach my $item (@{$postprocess->{'createdmsg'}}) {
 4313:                         if (ref($item) eq 'HASH') {
 4314:                             if ($item->{'mt'} ne '') {  
 4315:                                 push(@{$addmsg},$item);
 4316:                             }
 4317:                         }
 4318:                     }
 4319:                 }
 4320:                 if ($postprocess->{'createdweb'}) {
 4321:                     $output .= $postprocess->{'createdweb'}
 4322:                 }
 4323:             }
 4324:             if (scalar(@{$addmsg}) > 0) {
 4325:                 my $type = 'createdcrsreq';
 4326:                 if ($code) {
 4327:                     $type = 'uniquecode';
 4328:                 }
 4329:                 &Apache::loncoursequeueadmin::send_selfserve_notification($recipient,$addmsg,$dom.'_'.$cnum,$env{'form.cdescr'},
 4330:                                                                           $now,$type,$sender);
 4331:             }
 4332:         }
 4333:     } else {
 4334:         $output .= '<div class="LC_warning">'.
 4335:                    &mt('Your request status is: [_1].',$disposition).
 4336:                    '</div>';
 4337:     }
 4338:     return $output;
 4339: }
 4340: 
 4341: sub pending_validation_form {
 4342:     my ($cdom,$cnum,$crstype,$now,$token,$lonhost,$cdesc) = @_;
 4343:     my $output;
 4344:     my %postvalues = (
 4345:                       'owner'      => $env{'user.name'}.':'.$env{'user.domain'},
 4346:                       'course'     => $cdom.'_'.$cnum,
 4347:                       'coursetype' => $crstype,
 4348:                      );
 4349:     my %domconfig = &Apache::lonnet::get_dom('configuration',['requestcourses'],$cdom);
 4350: 
 4351:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 4352:         my ($url,$buttontext,$code,@fields);
 4353:         if (ref($domconfig{'requestcourses'}{'validation'}) eq 'HASH') {
 4354:             $postvalues{'description'} = $cdesc;
 4355:             $url = $domconfig{'requestcourses'}{'validation'}{'url'};
 4356:             if (ref($domconfig{'requestcourses'}{'validation'}{'fields'}) eq 'ARRAY') {
 4357:                 @fields = @{$domconfig{'requestcourses'}{'validation'}{'fields'}};
 4358:             }
 4359:             $buttontext = $domconfig{'requestcourses'}{'validation'}{'button'};
 4360:             $output .= $domconfig{'requestcourses'}{'validation'}{'markup'};
 4361:             if (($url =~ m{^(https?\://|/)}) && (@fields > 0)) {
 4362:                 $output .= '<form name="crsreqvalidation" action="'.$url.'" method="post">'."\n";
 4363:                 foreach my $field (@fields) {
 4364:                     if ($postvalues{$field}) {
 4365:                         $output .= '<input type="hidden" name="'.$field.'" value="'.$postvalues{$field}.'" />'."\n";
 4366:                     }
 4367:                 }
 4368:                 if ($buttontext eq '') {
 4369:                     if ($crstype eq 'community') {
 4370:                         $buttontext = &mt('Create community');
 4371:                     } else {
 4372:                         $buttontext = &mt('Create course');
 4373:                     }
 4374:                 }
 4375:                 my $hostname = &Apache::lonnet::hostname($lonhost);
 4376:                 my $protocol = $Apache::lonnet::protocol{$lonhost};
 4377:                 $protocol = 'http' if ($protocol ne 'https');
 4378:                 my $crscreator = $protocol.'://'.$hostname.'/cgi-bin/createpending.pl';
 4379:                 $output .= '<input type="hidden" name="crscreator" value="'.$crscreator.'" />'."\n".
 4380:                            '<input type="hidden" name="token" value="'.$token.'" />'."\n".
 4381:                            '<input type="submit" name="validate" value="'.$buttontext.'" />'."\n".
 4382:                            '</form>'."\n";
 4383:             }
 4384:         }
 4385:     }
 4386:     return $output;
 4387: }
 4388: 
 4389: sub check_autolimit {
 4390:     my ($uname,$udom,$dom,$crstype,$limit,$message) = @_;
 4391:     my %crsroles = &Apache::lonnet::get_my_roles($env{'user.name'},$env{'user.domain'},
 4392:                        'userroles',['active','future'],['cc','co'],[$dom]);
 4393:     my ($types,$typename) = &Apache::loncommon::course_types();
 4394:     my %requests = &Apache::lonnet::dumpstore('courserequests',$udom,$uname);
 4395:     my $count = 0;
 4396:     foreach my $key (keys(%requests)) {
 4397:         my ($cdom,$cnum) = split('_',$key);
 4398:         if (ref($requests{$key}) eq 'HASH') {
 4399:             next if ($requests{$key}{'crstype'} ne $crstype);
 4400:             if (($crstype eq 'community') && 
 4401:                 (exists($crsroles{$cnum.':'.$cdom.':co'}))) {
 4402:                 $count ++;
 4403:             } elsif ((($crstype eq 'official') || ($crstype eq 'unofficial') || ($crstype eq 'textbook') || ($crstype eq 'placement')) &&
 4404:                      (exists($crsroles{$cnum.':'.$cdom.':cc'}))) {
 4405:                 $count ++;
 4406:             }
 4407:         }
 4408:     }
 4409:     if ($count < $limit) {
 4410:         return 'process';
 4411:     } else {
 4412:         if (ref($typename) eq 'HASH') {
 4413:             if ($crstype eq 'community') {
 4414:                 $$message = &mt('Your request has not been processed because you have reached the limit for the number of communities.').
 4415:                             '<br />'.&mt("Your limit is [_1].",$limit);
 4416:             } else {
 4417:                 $$message = &mt('Your request has not been processed because you have reached the limit for the number of courses of this type.').
 4418:                             '<br />'.&mt("Your $typename->{$crstype} limit is [_1].",$limit);
 4419:             }
 4420:         }
 4421:         return 'rejected';
 4422:     }
 4423:     return;
 4424: }
 4425: 
 4426: sub retrieve_settings {
 4427:     my ($dom,$cnum,$udom,$uname) = @_;
 4428:     if ($udom eq '' || $uname eq '') {
 4429:         $udom = $env{'user.domain'};
 4430:         $uname = $env{'user.name'};
 4431:     }
 4432:     my ($result,%reqinfo) = &get_request_settings($dom,$cnum,$udom,$uname);
 4433:     if ($result eq 'ok') {
 4434:         if (($udom eq $reqinfo{'domain'}) &&  ($uname eq $reqinfo{'owner'})) {
 4435:             $env{'form.chome'} = $reqinfo{'coursehome'};
 4436:             $env{'form.cdescr'} = $reqinfo{'cdescr'};
 4437:             $env{'form.crstype'} = $reqinfo{'crstype'}; 
 4438:             &generate_date_items($reqinfo{'accessstart'},'accessstart');
 4439:             &generate_date_items($reqinfo{'accessend'},'accessend');
 4440:             if ($reqinfo{'accessend'} == 0) {
 4441:                 $env{'form.no_end_date'} = 1;
 4442:             }
 4443:             if (($reqinfo{'crstype'} eq 'official') && (&Apache::lonnet::auto_run('',$dom))) {
 4444:                 &generate_date_items($reqinfo{'enrollstart'},'enrollstart');
 4445:                 &generate_date_items($reqinfo{'enrollend'},'enrollend');
 4446:             }
 4447:             $env{'form.clonecrs'} = $reqinfo{'clonecrs'};
 4448:             $env{'form.clonedom'} = $reqinfo{'clonedom'};
 4449:             if (($reqinfo{'clonecrs'} ne '') && ($reqinfo{'clonedom'} ne '')) {
 4450:                 $env{'form.cloning'} = 1;
 4451:             }
 4452:             $env{'form.datemode'} = $reqinfo{'datemode'};
 4453:             $env{'form.dateshift'} = $reqinfo{'dateshift'};
 4454:             if ($reqinfo{'crstype'} eq 'official') {
 4455:                 $env{'form.autoadds'} = $reqinfo{'autoadds'};
 4456:                 $env{'form.autodrops'} = $reqinfo{'autodrops'};
 4457:                 if ($reqinfo{'instcode'} ne '') { 
 4458:                     $env{'form.sectotal'} = $reqinfo{'sectotal'};
 4459:                     $env{'form.crosslisttotal'} = $reqinfo{'crosslisttotal'};
 4460:                     $env{'form.instcode'} = $reqinfo{'instcode'};
 4461:                     my $crscode = { 
 4462:                                     $cnum => $reqinfo{'instcode'},
 4463:                                   };
 4464:                     &extract_instcode($dom,'instcode',$crscode,$cnum);
 4465:                     (undef,undef,my $instcredits) =
 4466:                         &Apache::lonnet::auto_validate_instcode(undef,$dom,
 4467:                                                                 $reqinfo{'instcode'});
 4468:                     if ($instcredits ne $reqinfo{'defaultcredits'}) {
 4469:                         $env{'form.coursecredits'} = $reqinfo{'defaultcredits'};
 4470:                     }
 4471:                 }
 4472:             } elsif (($reqinfo{'crstype'} eq 'unofficial') || ($reqinfo{'crstype'} eq 'textbook')) {
 4473:                 $env{'form.coursecredits'} = $reqinfo{'defaultcredits'};
 4474:             }
 4475:             my @currsec;
 4476:             if (ref($reqinfo{'sections'}) eq 'HASH') {
 4477:                 foreach my $i (sort(keys(%{$reqinfo{'sections'}}))) {
 4478:                     if (ref($reqinfo{'sections'}{$i}) eq 'HASH') {
 4479:                         my $sec = $reqinfo{'sections'}{$i}{'inst'};
 4480:                         $env{'form.secnum_'.$i} = $sec;
 4481:                         $env{'form.sec_'.$i} = '1';
 4482:                         if (!grep(/^\Q$sec\E$/,@currsec)) {
 4483:                             push(@currsec,$sec);
 4484:                         }
 4485:                         $env{'form.loncapasec_'.$i} = $reqinfo{'sections'}{$i}{'loncapa'};
 4486:                     }
 4487:                 }
 4488:             }
 4489:             if (ref($reqinfo{'crosslists'}) eq 'HASH') {
 4490:                 foreach my $i (sort(keys(%{$reqinfo{'crosslists'}}))) {
 4491:                     if (ref($reqinfo{'crosslists'}{$i}) eq 'HASH') {
 4492:                         $env{'form.crosslist_'.$i} = '1';
 4493:                         $env{'form.crosslist_'.$i.'_instsec'} = $reqinfo{'crosslists'}{$i}{'instsec'};
 4494:                         $env{'form.crosslist_'.$i.'_lcsec'} = $reqinfo{'crosslists'}{$i}{'loncapa'};
 4495:                         if ($reqinfo{'crosslists'}{$i}{'instcode'} ne '') {
 4496:                             my $key = $cnum.$i; 
 4497:                             my $crscode = {
 4498:                                               $key => $reqinfo{'crosslists'}{$i}{'instcode'},
 4499:                                           };
 4500:                             &extract_instcode($dom,'crosslist',$crscode,$key,$i);
 4501:                         }
 4502:                     }
 4503:                 }
 4504:             }
 4505:             if (ref($reqinfo{'personnel'}) eq 'HASH') {
 4506:                 my $i = 0;
 4507:                 foreach my $user (sort(keys(%{$reqinfo{'personnel'}}))) {
 4508:                     my ($uname,$udom) = split(':',$user);
 4509:                     if (ref($reqinfo{'personnel'}{$user}) eq 'HASH') {
 4510:                         if (ref($reqinfo{'personnel'}{$user}{'roles'}) eq 'ARRAY') {
 4511:                             foreach my $role (sort(@{$reqinfo{'personnel'}{$user}{'roles'}})) {
 4512:                                 $env{'form.person_'.$i.'_role'} = $role;
 4513:                                 $env{'form.person_'.$i.'_firstname'} = $reqinfo{'personnel'}{$user}{'firstname'};
 4514:                                 $env{'form.person_'.$i.'_lastname'} = $reqinfo{'personnel'}{$user}{'lastname'}; ;
 4515:                                 $env{'form.person_'.$i.'_emailaddr'} = $reqinfo{'personnel'}{$user}{'emailaddr'};
 4516:                                 $env{'form.person_'.$i.'_uname'} = $uname;
 4517:                                 $env{'form.person_'.$i.'_dom'} = $udom;
 4518:                                 if (ref($reqinfo{'personnel'}{$user}{$role}) eq 'HASH') {
 4519:                                     if (ref($reqinfo{'personnel'}{$user}{$role}{'usec'}) eq 'ARRAY') {
 4520:                                         my @usecs = @{$reqinfo{'personnel'}{$user}{$role}{'usec'}};
 4521:                                         my @newsecs;
 4522:                                         if (@usecs > 0) {
 4523:                                             foreach my $sec (@usecs) {
 4524:                                                 if (grep(/^\Q$sec\E/,@currsec)) {
 4525:                                                     $env{'form.person_'.$i.'_sec'} = $sec;
 4526:                                                 } else {
 4527:                                                     push(@newsecs,$sec);
 4528:                                                 }
 4529:                                             }
 4530:                                         }
 4531:                                         if (@newsecs > 0) {
 4532:                                             $env{'form.person_'.$i.'_newsec'} = join(',',@newsecs); 
 4533:                                         }
 4534:                                     }
 4535:                                 }
 4536:                                 $i ++;
 4537:                             }
 4538:                         }
 4539:                     }
 4540:                 }
 4541:                 $env{'form.persontotal'} = $i;
 4542:             }
 4543:         }
 4544:     }
 4545:     return $result;
 4546: }
 4547: 
 4548: sub get_request_settings {
 4549:     my ($dom,$cnum,$udom,$uname) = @_;
 4550:     my $requestkey = $dom.'_'.$cnum;
 4551:     my ($result,%reqinfo);
 4552:     if ($requestkey =~ /^($match_domain)_($match_courseid)$/) {
 4553:         my %history = &Apache::lonnet::restore($requestkey,'courserequests',$udom,$uname);
 4554:         my $disposition = $history{'disposition'};
 4555:         if (($disposition eq 'approval') || ($disposition eq 'pending')) { 
 4556:             if (ref($history{'details'}) eq 'HASH') {
 4557:                 %reqinfo = %{$history{'details'}};
 4558:                 $result = 'ok';
 4559:             } else {
 4560:                 $result = 'nothash';
 4561:             }
 4562:         } else {
 4563:             $result = 'notqueued';
 4564:         }
 4565:     } else {
 4566:         $result = 'invalid';
 4567:     }
 4568:     return ($result,%reqinfo);
 4569: }
 4570: 
 4571: sub extract_instcode {
 4572:     my ($cdom,$element,$crscode,$crskey,$counter) = @_;
 4573:     my (%codes,@codetitles,%cat_titles,%cat_order);
 4574:     if (&Apache::lonnet::auto_instcode_format('requests',$cdom,$crscode,\%codes,
 4575:                                               \@codetitles,\%cat_titles,
 4576:                                               \%cat_order) eq 'ok') {
 4577:         if (ref($codes{$crskey}) eq 'HASH') {
 4578:             if (@codetitles > 0) {
 4579:                 my $sel = $element;
 4580:                 if ($element eq 'crosslist') {
 4581:                     $sel .= '_'.$counter;
 4582:                 }
 4583:                 foreach my $title (@codetitles) {
 4584:                     $env{'form.'.$sel.'_'.$title} = $codes{$crskey}{$title};
 4585:                 }
 4586:             }
 4587:         }
 4588:     }
 4589:     return;
 4590: }
 4591: 
 4592: sub generate_date_items {
 4593:     my ($currentval,$item) = @_;
 4594:     if ($currentval =~ /\d+/) {
 4595:         my ($tzname,$sec,$min,$hour,$mday,$month,$year) = 
 4596:             &Apache::lonhtmlcommon::get_timedates($currentval);
 4597:         $env{'form.'.$item.'_day'} = $mday;
 4598:         $env{'form.'.$item.'_month'} = $month+1;
 4599:         $env{'form.'.$item.'_year'} = $year;
 4600:     }
 4601:     return;
 4602: }
 4603: 
 4604: sub print_textbook_form {
 4605:     my ($r,$dom,$incdoms,$domdefs,$settings,$can_request,$crstype,$formhash) = @_;
 4606:     my (%prefab,%ordered,%numprefab);
 4607:     if ($crstype eq '') {
 4608:         $crstype = 'textbook';
 4609:     }
 4610: #
 4611: #  Retrieve list of prefabricated courses (textbook courses and templates) cloneable by user
 4612: #
 4613:     foreach my $type ('textbooks','templates') {
 4614:         $numprefab{$type} = 0;
 4615:         if (ref($settings) eq 'HASH') {
 4616:             $prefab{$type} = $settings->{$type};
 4617:             if (ref($prefab{$type}) eq 'HASH') {
 4618:                 foreach my $item (keys(%{$prefab{$type}})) {
 4619:                     my ($clonedom,$clonecrs) = split(/_/,$item);
 4620:                     if (ref($prefab{$type}{$item}) eq 'HASH') {
 4621:                         if (&Apache::loncoursequeueadmin::can_clone_course($env{'user.name'},
 4622:                                           $env{'user.domain'},$clonecrs,$clonedom,$crstype,$dom)) {
 4623: 
 4624:                             my $num = $prefab{$type}{$item}{'order'};
 4625:                             $ordered{$type}{$num} = $item;
 4626:                             $numprefab{$type} ++;
 4627:                         }
 4628:                     }
 4629:                 }
 4630:             }
 4631:         }
 4632:     }
 4633: 
 4634: #
 4635: # Check if domain has multiple library servers
 4636: #
 4637:     my ($home_server_pick,$numlib) =
 4638:         &Apache::loncommon::home_server_form_item($dom,'chome',
 4639:                                                   'default','hide');
 4640:     if ($numlib > 1) {
 4641:         $home_server_pick = &mt('Home Server for Course').': '.$home_server_pick.'<br />';
 4642:     }
 4643: 
 4644: #
 4645: # Retrieve information about courses owned by user, or in which user has an active
 4646: # Course Coordinator role
 4647: #
 4648:     my $numcurrent;
 4649:     my %cloneable = &Apache::lonnet::courseiddump($dom,'.',1,'.',$env{'user.name'}.':'.$env{'user.domain'},
 4650:                                                   '.',undef,undef,'Course');
 4651:     my %ccroles = &Apache::lonnet::get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',
 4652:                                                 ['active'],['cc']);
 4653: 
 4654:     my $cc_clone = '';
 4655:     foreach my $role (keys(%ccroles)) {
 4656:         my ($cnum,$cdom,$rest) = split(/:/,$role,3);
 4657:         $cc_clone .= $cdom.':'.$cnum.'&';
 4658:         unless (exists($cloneable{$cdom.'_'.$cnum})) {
 4659:             my %courseinfo = &Apache::lonnet::coursedescription($cdom.'_'.$cnum,{'one_time' => 1});
 4660:             $cloneable{$cdom.'_'.$cnum} = {
 4661:                                                context => $courseinfo{'internal.creationcontext'},
 4662:                                                created => $courseinfo{'internal.created'},
 4663:                                                creator => $courseinfo{'internal.creator'},
 4664:                                                description => $courseinfo{'description'},
 4665:                                                inst_code => $courseinfo{'coursecode'},
 4666:                                                owner => $courseinfo{'internal.courseowner'},
 4667:                                                releaserequired => $courseinfo{'internal.releaserequired'},
 4668:                                                type  => $courseinfo{'type'},
 4669:                                           };
 4670:         }
 4671:     }
 4672: 
 4673:     my $numcurrent = scalar(keys(%cloneable));
 4674: 
 4675: #
 4676: # Retrieve information about courses from user's domain which user can clone, but which not owned
 4677: # or cloneable based on Course Coordinator role.
 4678: #
 4679:     my ($numdomcourses,%domcloneable);
 4680:     my %allcloneable = &Apache::lonnet::courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course',
 4681:                                                      undef,undef,undef,undef,undef,
 4682:                                                      $env{'user.name'}.':'.$env{'user.domain'},
 4683:                                                      $cc_clone,1);
 4684:     foreach my $cid (keys(%allcloneable)) {
 4685:         unless (exists($cloneable{$cid})) {
 4686:             $domcloneable{$cid} = $allcloneable{$cid};
 4687:         }
 4688:     }
 4689:     $numdomcourses = scalar(keys(%domcloneable));
 4690: 
 4691:     my $fullname = &Apache::loncommon::plainname($env{'user.name'},
 4692:                                                  $env{'user.domain'});
 4693: 
 4694: #
 4695: # Retrieve any custom form information prior to rendering page
 4696: #
 4697: 
 4698:     my $initprocess = &Apache::lonnet::auto_crsreq_update($dom,undef,$crstype,'initializereview',$env{'user.name'},
 4699:                                                          $env{'user.domain'},$fullname);
 4700:     my %custominit;
 4701:     if (ref($initprocess) eq 'HASH') {
 4702:         &custom_formitems($initprocess,\%custominit);
 4703:     }
 4704: 
 4705: #
 4706: # Retrieve any custom onload actions or javascript used for page before rendering
 4707: #
 4708: 
 4709:     my ($customonload,$customjs,$customvalidationjs);
 4710:     my $inprocess = &Apache::lonnet::auto_crsreq_update($dom,undef,$crstype,'prereview',$env{'user.name'},
 4711:                                                         $env{'user.domain'},$fullname,undef,undef,
 4712:                                                         undef,undef,\%custominit);
 4713:     if (ref($inprocess) eq 'HASH') {
 4714:         $customonload = $inprocess->{'onload'};
 4715:         $customjs = $inprocess->{'javascript'};
 4716:         $customvalidationjs = $inprocess->{'validationjs'};
 4717:     }
 4718: 
 4719:     my $postprocess = &Apache::lonnet::auto_crsreq_update($dom,undef,$crstype,'review',
 4720:                                                           $env{'user.name'},
 4721:                                                           $env{'user.domain'},$fullname,undef,undef,
 4722:                                                           undef,undef,\%custominit);
 4723: 
 4724:     my $jscript = &textbook_request_javascript(\%numprefab,$numcurrent,$numdomcourses,$customvalidationjs);
 4725:     $jscript .= $customjs;
 4726:     my (%loaditems,$args);
 4727:     $loaditems{'onload'} = 'javascript:uncheckAllRadio();'.$customonload;
 4728:     if ($crstype eq 'lti') {
 4729:        $args = { 'only_body' => 1};
 4730:     }
 4731:     $r->print(&header('Course Request',$jscript,\%loaditems,undef,$args));
 4732: 
 4733:     if (ref($can_request) eq 'HASH') {
 4734:         unless (((scalar(keys(%{$can_request})) == 1) && ($can_request->{'textbook'})) ||
 4735:                 ($crstype eq 'lti')) {
 4736:             &Apache::lonhtmlcommon::add_breadcrumb(
 4737:                 { href => '/adm/requestcourse',
 4738:                   text => 'Pick action',
 4739:                 });
 4740:         }
 4741:     }
 4742:     unless ($crstype eq 'lti') {
 4743:         &Apache::lonhtmlcommon::add_breadcrumb({text=>'Course Request'});
 4744:         $r->print(&Apache::lonhtmlcommon::breadcrumbs('Course Requests','Course_Requests'));
 4745: 
 4746:         &startContentScreen($r,'textbookrequests');
 4747: #
 4748: # Show domain selector form, if required.
 4749: #
 4750:         if (@{$incdoms} > 1) {
 4751:             my $onchange = 'this.form.submit()';
 4752:             $r->print('<form name="domforcourse" method="post" action="/adm/requestcourse">'.
 4753:                       '<div><fieldset><legend>'.&mt('Domain').'</legend>'.
 4754:                       &Apache::loncommon::select_dom_form($dom,'showdom','',1,$onchange,$incdoms).
 4755:                       '</fieldset></form>');
 4756:         }
 4757:     }
 4758: 
 4759: #
 4760: # Course request form
 4761: #
 4762: 
 4763: #
 4764: # Course Title
 4765: #
 4766:     $r->print('<form name="requestcourse" method="post" action="/adm/requestcourse" onsubmit="return validTextbookReq();">'.
 4767:               '<div>'.
 4768:               '<fieldset>'.
 4769:               '<legend>'.&mt('Course Information').'</legend>'.
 4770:               '<span class="LC_nobreak">'.&mt('Title').':&nbsp'.
 4771:               '<input type="text" size="60" name="cdescr" value="" /></span><br />'.
 4772:               $home_server_pick.'<br /></fieldset>'.
 4773:               '</div>');
 4774: 
 4775: #
 4776: # Content source selection, if more than one available
 4777: #
 4778:     if (keys(%cloneable) || keys(%ordered) || keys(%domcloneable)) {
 4779:         $r->print('<div>'. 
 4780:                   '<fieldset><legend>'.&mt('Course Content').'</legend>');
 4781:         if (keys(%ordered)) {
 4782:             if (ref($ordered{'textbooks'}) eq 'HASH') {
 4783:                 $r->print('<span class="LC_nobreak"><label>'.
 4784:                           '<input type="radio" name="cloning" value="textbook" onclick="javascript:cloneChoice();" />'.
 4785:                           &mt('Load textbook content').'</span>'.('&nbsp;'x2).' ');
 4786:             }
 4787:             if (ref($ordered{'templates'}) eq 'HASH') {
 4788:                 $r->print('<span class="LC_nobreak"><label>'.
 4789:                           '<input type="radio" name="cloning" value="template" onclick="javascript:cloneChoice();" />'.
 4790:                           &mt('Load pre-existing template').'</span>'.('&nbsp;'x2).' ');
 4791:             }
 4792:         }
 4793:         if (keys(%cloneable)) {
 4794:             $r->print('<span class="LC_nobreak"><label>'.
 4795:                       '<input type="radio" name="cloning" value="existing" onclick="javascript:cloneChoice();" />'.
 4796:                       &mt('Copy one of your courses').'</label></span>'.('&nbsp;'x2).' ');
 4797:         }
 4798:         if (keys(%domcloneable)) {
 4799:             $r->print('<span class="LC_nobreak"><label>'.
 4800:                       '<input type="radio" name="cloning" value="colleague" onclick="javascript:cloneChoice();" />'.
 4801:                       &mt("Copy a colleague's course").'</label></span>'.('&nbsp;'x2).' ');
 4802:         }
 4803:         $r->print('<span class="LC_nobreak"><label>'.
 4804:                   '<input type="radio" name="cloning" value="none" checked="checked" onclick="javascript:cloneChoice();" />'.
 4805:                   &mt('Empty course shell').'</label></span>');
 4806:     } else {
 4807:         $r->print('<input type="hidden" name="cloning" value="none" />');
 4808:     }
 4809: 
 4810: #
 4811: # Table of cloneable textbook courses
 4812: #
 4813:     if (keys(%ordered)) {
 4814:         foreach my $type ('textbooks','templates') {
 4815:             my $divid = 'showtextbook';
 4816:             my $radioid = 'book';
 4817:             if ($type eq 'templates') {
 4818:                 $divid = 'showtemplate'; 
 4819:                 $radioid = 'template';
 4820:             }
 4821:             if (ref($ordered{$type}) eq 'HASH') {
 4822:                 $r->print('<div id="'.$divid.'" style="display:none">'.
 4823:                           &Apache::loncommon::start_data_table().
 4824:                           &Apache::loncommon::start_data_table_header_row().
 4825:                           '<th>'.&mt('Title').'</th>');
 4826:                 if ($type eq 'textbooks') {
 4827:                     $r->print('<th>'.&mt('Author(s)').'</th>');
 4828:                 }
 4829:                 $r->print('<th>'.&mt('Subject').'</th>');
 4830:                 if ($type eq 'textbooks') {
 4831:                     $r->print('<th>'.&mt('Publisher').'</th>'.
 4832:                               '<th>'.&mt('Book').'</th>');
 4833:                 }
 4834:                 $r->print(&Apache::loncommon::end_data_table_header_row());
 4835:                 my @items = sort { $a <=> $b } keys(%{$ordered{$type}});
 4836:                 foreach my $num (@items) {
 4837:                     my $item = $ordered{$type}{$num};
 4838:                     my $cleantitle=&HTML::Entities::encode($prefab{$type}{$item}{'title'},'<>&"');
 4839:                     $cleantitle=~s/'/\\'/g;
 4840:                     $cleantitle =~ s/^\s+//;
 4841:                     $r->print(&Apache::loncommon::start_data_table_row().
 4842:                               '<td><label><input type="radio" name="'.$radioid.'" value="'.$item.'" />'.
 4843:                               $cleantitle.'</label></td>');
 4844:                     if ($type eq 'textbooks') {
 4845:                          $r->print('<td>'.$prefab{$type}{$item}{'author'}.'</td>');
 4846:                     }
 4847:                     $r->print('<td>'.$prefab{$type}{$item}{'subject'}.'</td>');
 4848:                     if ($type eq 'textbooks') {
 4849:                         $r->print('<td>'.$prefab{$type}{$item}{'publisher'}.'</td>'.
 4850:                                   '<td><img border="0" src="'.$prefab{$type}{$item}{'image'}.
 4851:                                   '" alt="'.$cleantitle.'" /></td>');
 4852:                     }
 4853:                     $r->print(&Apache::loncommon::end_data_table_row());
 4854:                 }
 4855:                 $r->print(&Apache::loncommon::end_data_table().
 4856:                           '</div>');
 4857:             }
 4858:         }
 4859:     }
 4860: 
 4861: #
 4862: # Table of user's current courses (owner and/or course coordinator)
 4863: #
 4864:     my %lt = &clone_text();
 4865:     if (keys(%cloneable)) {
 4866:         $r->print('<div id="showexisting" style="display:none">'.
 4867:                   &clone_selection_table($dom,'owned',\%cloneable).
 4868:                   '<p><input type="radio" name="owndatemode" value="delete" /> '.$lt{'ncd'}.
 4869:                   '</label><br /><label>'.
 4870:                   '<input type="radio" name="owndatemode" value="preserve" /> '.$lt{'prd'}.
 4871:                   '</label><br /><label>'.
 4872:                   '<input type="radio" name="owndatemode" value="shift" checked="checked" /> '.
 4873:                   $lt{'shd'}.'</label>'.
 4874:                   '<input type="text" size="5" name="owndateshift" value="365" />'.
 4875:                   '</div>');
 4876:     }
 4877: #
 4878: # Table of other cloneable courses from user's domain (exclude own courses)
 4879: #
 4880:     if (keys(%domcloneable)) {
 4881:         $r->print('<div id="showcolleague" style="display:none">'.
 4882:                   &clone_selection_table($dom,'colleague',\%domcloneable).
 4883:                   '<p><input type="radio" name="colldatemode" value="delete" /> '.$lt{'ncd'}.
 4884:                   '</label><br /><label>'.
 4885:                   '<input type="radio" name="colldatemode" value="preserve" /> '.$lt{'prd'}.
 4886:                   '</label><br /><label>'.
 4887:                   '<input type="radio" name="colldatemode" value="shift" checked="checked" /> '.
 4888:                   $lt{'shd'}.'</label>'.
 4889:                   '<input type="text" size="5" name="colldateshift" value="365" />'.
 4890:                   '</div>');
 4891:     }
 4892: 
 4893: #
 4894: # End of content selector
 4895: #
 4896:     if (keys(%cloneable) || keys(%domcloneable) || keys(%ordered)) {
 4897:         $r->print('</fieldset></div>');
 4898:     }
 4899: 
 4900:     my %accesstitles = (
 4901:                           'start' => 'Default start access',
 4902:                            'end'   => 'Default end access',
 4903:                        );
 4904:     my %help_item = (
 4905:                        start => 'Course_Request_Access_Start',
 4906:                        end   => 'Course_Request_Access_End',
 4907:                     );
 4908:     my $starttime = time;
 4909:     my $endtime = time+(6*30*24*60*60); # 6 months from now, approx
 4910:     my $startform = &Apache::lonhtmlcommon::date_setter('requestcourse','accessstart',
 4911:                                                         $starttime,'','','',1,'','','',1);
 4912:     my $endform = &Apache::lonhtmlcommon::date_setter('requestcourse','accessend',
 4913:                                                       $endtime,'','','',1,'','','',1);
 4914: #
 4915: # Set default start and end dates for student access
 4916: # 
 4917:     $r->print('<div>'.
 4918:               '<fieldset><legend>'.&mt('Student Access Dates').'</legend>'.
 4919:               &Apache::loncommon::help_open_topic($help_item{'start'}).
 4920:               '&nbsp;'.&mt($accesstitles{'start'}).$startform.'<br />'.
 4921:               &Apache::loncommon::help_open_topic($help_item{'end'}).
 4922:               '&nbsp;'.&mt($accesstitles{'end'}).$endform.'<br /></div>');
 4923: 
 4924: #
 4925: # Display any custom fields for this course type
 4926: #
 4927:     if (ref($postprocess) eq 'HASH') {
 4928:         if ($postprocess->{'reviewweb'}) {
 4929:             $r->print($postprocess->{'reviewweb'});
 4930:         }
 4931:     }
 4932: 
 4933: #
 4934: # Submit button
 4935: #
 4936:     $r->print('<input type="hidden" name="crstype" value="'.$crstype.'" />'.
 4937:               '<input type="hidden" name="action" value="process" />'.
 4938:               '<input type="submit" value="'.&mt('Create course').'" />');
 4939: 
 4940: #
 4941: # End request form
 4942: #
 4943: 
 4944:     if (($crstype eq 'lti') && (ref($formhash) eq 'HASH')) {
 4945:         foreach my $item (keys(%{$formhash})) {
 4946:             $r->print('<input type="hidden" name="'.$item.'" value="'.$formhash->{$item}.'" />'."\n");
 4947:         }
 4948:     }
 4949: 
 4950:     $r->print('</form>');
 4951:     unless ($crstype eq 'lti') {
 4952:         &endContentScreen($r);
 4953:     }
 4954:     $r->print(&Apache::loncommon::end_page());
 4955:     return;
 4956: }
 4957: 
 4958: sub clone_selection_table {
 4959:     my ($dom,$name,$cloneableref) = @_;
 4960:     return unless ((ref($cloneableref) eq 'HASH') && (($name eq 'owned') || ($name eq 'colleague')));
 4961:     my %allownernames;
 4962:     my %sortbytitle;
 4963:     my $output;
 4964:     foreach my $cid (sort(keys(%{$cloneableref}))) {
 4965:         if (ref($cloneableref->{$cid}) eq 'HASH') {
 4966:             my $cdesc = $cloneableref->{$cid}{'description'};
 4967:             $cdesc =~ s/`/'/g;
 4968:             if ($cdesc ne '') {
 4969:                 push(@{$sortbytitle{$cdesc}},$cid);
 4970:             }
 4971:         }
 4972:     }
 4973:     foreach my $title (sort(keys(%sortbytitle))) {
 4974:          if (ref($sortbytitle{$title}) eq 'ARRAY') {
 4975:             foreach my $cid (sort(@{$sortbytitle{$title}})) {
 4976:                 my $cleantitle=&HTML::Entities::encode($title,'<>&"');
 4977:                 $cleantitle=~s/'/\\'/g;
 4978:                 $cleantitle =~ s/^\s+//;
 4979:                 my ($namestr,@owners,%ownernames);
 4980:                 if ($cloneableref->{$cid}{'owner'} ne '') {
 4981:                     push(@owners,$cloneableref->{$cid}{'owner'});
 4982:                 }
 4983:                 if ($cloneableref->{$cid}{'co-owners'} ne '') {
 4984:                     foreach my $item (split(/,/,$cloneableref->{$cid}{'co-owners'})) {
 4985:                         if (($item ne '') && (!grep(/^\Q$item\E$/,@owners))) {
 4986:                             push(@owners,$item);
 4987:                         }
 4988:                     }
 4989:                 }
 4990:                 foreach my $owner (@owners) {
 4991:                     my ($ownername,$ownerdom);
 4992:                     if ($owner =~ /:/) {
 4993:                         ($ownername,$ownerdom) = split(/:/,$owner);
 4994:                     } else {
 4995:                         $ownername = $owner;
 4996:                         if ($owner ne '') {
 4997:                             $ownerdom = $dom;
 4998:                         }
 4999:                     }
 5000:                     if ($ownername ne '' && $ownerdom ne '') {
 5001:                         if (exists($allownernames{$ownername.':'.$ownerdom})) {
 5002:                             $ownernames{$ownername.':'.$ownerdom} = $allownernames{$ownername.':'.$ownerdom};
 5003:                         } else {
 5004:                             my %namehash=&Apache::loncommon::getnames($ownername,$ownerdom);
 5005:                             $ownernames{$ownername.':'.$ownerdom} = \%namehash;
 5006:                             $allownernames{$ownername.':'.$ownerdom} = $ownernames{$ownername.':'.$ownerdom};
 5007:                         }
 5008:                     }
 5009:                 }
 5010:                 my @lastnames;
 5011:                 foreach my $owner (keys(%ownernames)) {
 5012:                     if (ref($ownernames{$owner}) eq 'HASH') {
 5013:                         push(@lastnames,$ownernames{$owner}{'lastname'});
 5014:                     }
 5015:                 }
 5016:                 if (@lastnames) {
 5017:                     $namestr = join(', ',sort(@lastnames));
 5018:                 }
 5019:                 $output .= &Apache::loncommon::start_data_table_row().
 5020:                            '<td><label><input type="radio" name="'.$name.'" value="'.$cid.'" />'.
 5021:                            '&nbsp;'.$cleantitle.'</label></td>'.
 5022:                            '<td>'.$namestr.'</td>'.
 5023:                            &Apache::loncommon::end_data_table_row();
 5024:             }
 5025:         }
 5026:     }
 5027:     if ($output) {
 5028:         return &Apache::loncommon::start_data_table().
 5029:                &Apache::loncommon::start_data_table_header_row().
 5030:                '<th>'.&mt('Title').'</th>'.
 5031:                '<th>'.&mt('Owner/co-owner(s)').'</th>'.
 5032:                &Apache::loncommon::end_data_table_header_row().
 5033:                $output.
 5034:                &Apache::loncommon::end_data_table();
 5035:     }
 5036:     return;
 5037: }
 5038: 
 5039: sub process_textbook_request {
 5040:     my ($r,$dom,$action,$domdefs,$domconfig,$can_request,$crstype) = @_;
 5041:     my ($uniquecode,$req_notifylist);
 5042:     if ($crstype eq '') {
 5043:         $crstype = 'textbook';
 5044:     }
 5045:     if (ref($domconfig) eq 'HASH') {
 5046:         if (ref($domconfig->{'requestcourses'}) eq 'HASH') {
 5047:             if (ref($domconfig->{'requestcourses'}{'notify'}) eq 'HASH') {
 5048:                 $req_notifylist = $domconfig->{'requestcourses'}{'notify'}{'approval'};
 5049:             }
 5050:             if (ref($domconfig->{'requestcourses'}{'uniquecode'}) eq 'HASH') {
 5051:                 $uniquecode = $domconfig->{'requestcourses'}{'uniquecode'}{$crstype};
 5052:             }
 5053:         }
 5054:     }
 5055:     my $now = time;
 5056:     my $reqtype = $env{'form.cloning'};
 5057:     my (@inststatuses,$storeresult,$creationresult);
 5058:     my $cnum = &Apache::lonnet::generate_coursenum($dom,'Course');
 5059:     my ($clonefrom,$clonedom,$clonecrs);
 5060:     if ($reqtype eq 'textbook') {
 5061:         $clonefrom = $env{'form.book'};
 5062:     } elsif ($reqtype eq 'template') {
 5063:         $clonefrom = $env{'form.template'};
 5064:     } elsif ($reqtype eq 'existing') {
 5065:         $clonefrom = $env{'form.owned'};
 5066:     } elsif ($reqtype eq 'colleague') {
 5067:         $clonefrom = $env{'form.colleague'};
 5068:     }
 5069:     my ($accessstart,$accessend) = &dates_from_form('accessstart','accessend');
 5070:     if ($clonefrom) {
 5071:         ($clonedom,$clonecrs) = split(/_/,$clonefrom);
 5072:         if (&Apache::lonnet::homeserver($clonecrs,$clonedom) ne 'no_host') {
 5073:             my $canclone =
 5074:                 &Apache::loncoursequeueadmin::can_clone_course($env{'user.name'},
 5075:                             $env{'user.domain'},$clonecrs,$clonedom,$crstype,$dom);
 5076:             unless ($canclone) {
 5077:                 undef($clonecrs);
 5078:                 undef($clonedom);
 5079:             }
 5080:         } else {
 5081:             undef($clonecrs);
 5082:             undef($clonedom);
 5083:         }
 5084:     }
 5085:     my $js = &processing_javascript();
 5086:     my ($loaditems,$args);
 5087:     $loaditems = {
 5088:                    onload => 'javascript:hideProcessing();',
 5089:                  };
 5090:     if ($crstype eq 'lti') {
 5091:        $args = { 'only_body' => 1};
 5092:     }
 5093:     $r->print(&header('Course Creation',$js,$loaditems,undef,$args));
 5094: 
 5095:     unless ($crstype eq 'lti') {
 5096:         if (ref($can_request) eq 'HASH') {
 5097:             unless ((scalar(keys(%{$can_request})) == 1) && ($can_request->{'textbook'})) {
 5098:                 &Apache::lonhtmlcommon::add_breadcrumb(
 5099:                     { href => '/adm/requestcourse',
 5100:                       text => 'Pick action',
 5101:                     });
 5102:             }
 5103:         }
 5104:         &Apache::lonhtmlcommon::add_breadcrumb(
 5105:                                                { href => '/adm/requestcourse',
 5106:                                                  text => "Create Course",
 5107:                                                }
 5108:                                               );
 5109:         &Apache::lonhtmlcommon::add_breadcrumb({text=>'Request Processed'});
 5110:         $r->print(&Apache::lonhtmlcommon::breadcrumbs('Course Requests','Course_Requests'));
 5111:         &startContentScreen($r,'textbookrequests');
 5112:     }
 5113: 
 5114:     my $details = {
 5115:                     owner          => $env{'user.name'},
 5116:                     domain         => $env{'user.domain'},
 5117:                     cdom           => $dom,
 5118:                     cnum           => $cnum,
 5119:                     coursehome     => $env{'form.chome'},
 5120:                     cdescr         => $env{'form.cdescr'},
 5121:                     crstype        => $crstype,
 5122:                     uniquecode     => $uniquecode,
 5123:                     clonedom       => $clonedom,
 5124:                     clonecrs       => $clonecrs,
 5125:                     accessstart    => $accessstart,
 5126:                     accessend      => $accessend,
 5127:                     personnel      => {},
 5128:                   };
 5129:     if (($clonecrs ne '') && ($clonedom ne '')) {
 5130:         if ($reqtype eq 'existing') {
 5131:             $details->{datemode} = $env{'form.owndatemode'};
 5132:             if ($details->{datemode} eq 'shift') {
 5133:                 $details->{dateshift} = $env{'form.owndateshift'};
 5134:             } else {
 5135:                 $details->{dateshift} = '';
 5136:             }
 5137:         } elsif ($reqtype eq 'colleague') {
 5138:             $details->{datemode} = $env{'form.colldatemode'};
 5139:             if ($details->{datemode} eq 'shift') {
 5140:                 $details->{dateshift} = $env{'form.colldateshift'};
 5141:             } else {
 5142:                 $details->{dateshift} = '';
 5143:             }
 5144:         } elsif (($reqtype eq 'textbook') || ($reqtype eq 'template')) {
 5145:             $details->{datemode} = 'delete';
 5146:             $details->{dateshift} = '';
 5147:         }
 5148:         if ($details->{dateshift} ne '') {
 5149:             $details->{dateshift} =~ s/[^\d\.]+//g;
 5150:         }
 5151:     } else {
 5152:         $details->{datemode} = '';
 5153:         $details->{dateshift} = '';
 5154:     }
 5155:     my $lonhost = $r->dir_config('lonHostID');
 5156:     $r->rflush();
 5157:     my ($result,$output,$customized) = &process_request($r,$lonhost,$dom,$cnum,$crstype,$now,$details,
 5158:                                                         '',$req_notifylist,[],$domconfig);
 5159:     $r->print($output);
 5160:     if ($crstype eq 'lti') {
 5161:         my %consumers = &Apache::lonnet::get_dom('lticonsumers',[$env{'form.sourcecrs'}],$dom);
 5162:         if (($env{'form.lti.sourcecrs'} ne '')  && ($consumers{$env{'form.lti.sourcecrs'}} eq '') && ($cnum ne '')) {
 5163:             &Apache::lonnet::put_dom('lticonsumers',{ $env{'form.lti.sourcecrs'} => $cnum },$dom);
 5164:         }
 5165:     } elsif (&Apache::loncoursequeueadmin::author_prompt()) {
 5166:         unless ($customized) {
 5167:             &print_author_prompt($r,$action,$cnum,$dom,$crstype,$result);
 5168:         }
 5169:     } elsif ($result eq 'created') {
 5170:         unless ($customized) {
 5171:             $r->print('<p><a href="/adm/requestcourse">'.&mt('Create another course').'</a></p>');
 5172:         }
 5173:     }
 5174:     unless ($crstype eq 'lti') {
 5175:         &endContentScreen($r);
 5176:     }
 5177:     $r->print(&Apache::loncommon::end_page());
 5178: }
 5179: 
 5180: sub textbook_request_javascript {
 5181:     my ($numprefab,$numcurrent,$numcolleague,$customvalidationjs) = @_;
 5182:     return unless (ref($numprefab) eq 'HASH');
 5183:     return if (!$numprefab->{'textbooks'} && !$numprefab->{'templates'} && !$numcurrent && !$numcolleague);
 5184:     my %js_lt = &Apache::lonlocal::texthash(
 5185:                  choose    => 'Please select a content option.',
 5186:                  textbook  => 'Please select a textbook, or choose a different option.',
 5187:                  template  => 'Please select a template, or choose a different option.',        
 5188:                  existing  => 'Please select one of your existing courses to copy, or choose a different option.',
 5189:                  colleague => "Please select a colleague's course to copy, or choose a different option.", 
 5190:                  title     => 'Please enter a course title.',
 5191:              );
 5192:     &js_escape(\%js_lt);
 5193:     return <<"ENDSCRIPT";
 5194: function cloneChoice() {
 5195:     if (document.requestcourse.cloning) {
 5196:         var radioLength = document.requestcourse.cloning.length;
 5197:         if (radioLength == undefined) {
 5198:             var val = document.requestcourse.cloning.value;
 5199:             if ((val == 'textbook') || (val == 'template') || (val == 'existing') || (val == 'colleague')) {
 5200:                 var elem = document.getElementById('show'+val);
 5201:                 if (document.requestcourse.cloning.checked) {
 5202:                     elem.style.display = 'block';
 5203:                 } else {
 5204:                     uncheckRadio(val);
 5205:                     elem.style.display = 'none';
 5206:                 }
 5207:             }
 5208:         } else {
 5209:             for (var i=0; i<radioLength; i++) {
 5210:                 var val = document.requestcourse.cloning[i].value;
 5211:                 if ((val == 'textbook') || (val == 'template') || (val == 'existing') || (val == 'colleague')) {
 5212:                     var elem = document.getElementById('show'+val);
 5213:                     if (document.requestcourse.cloning[i].checked) {
 5214:                         elem.style.display = 'block';
 5215:                     }  else {
 5216:                         if (val == 'textbook') {
 5217:                             uncheckRadio('book');
 5218:                         }
 5219:                         if (val == 'template') {
 5220:                             uncheckRadio('template');
 5221:                         }
 5222:                         if (val == 'existing') {
 5223:                             uncheckRadio('owned');
 5224:                         }
 5225:                         if (val == 'colleague') {
 5226:                             uncheckRadio('colleague');
 5227:                         }
 5228:                         elem.style.display = 'none';
 5229:                     }
 5230:                 }
 5231:             }
 5232:         }
 5233:     }
 5234:     return;
 5235: }
 5236: 
 5237: function uncheckRadio(radioGroupName) {
 5238:     var group = document.getElementsByName(radioGroupName);
 5239:     var radioLength = group.length;
 5240:     if (radioLength == undefined) {
 5241:         group.checked = false;
 5242:     } else {
 5243:         for (var i=0; i<radioLength; i++) {
 5244:             group[i].checked = false;
 5245:         }
 5246:     }
 5247:     return;
 5248: }
 5249: 
 5250: function uncheckAllRadio() {
 5251:     uncheckRadio('cloning');
 5252:     var numbook = $numprefab->{'textbooks'};
 5253:     var numtemplate = $numprefab->{'templates'};
 5254:     var numcurrent = $numcurrent;
 5255:     var numcolleague = $numcolleague;
 5256:     if (numbook > 0) {
 5257:         uncheckRadio('textbook'); 
 5258:     }
 5259:     if (numtemplate > 0) {
 5260:         uncheckRadio('template');
 5261:     }
 5262:     if (numcurrent > 0) {
 5263:         uncheckRadio('existing');
 5264:     }
 5265:     if (numcolleague > 0) {
 5266:         uncheckRadio('colleague');
 5267:     }
 5268:     return;
 5269: }
 5270: 
 5271: function validTextbookReq() {
 5272:     if (document.requestcourse.cloning) {
 5273:         var cloneChoice = 0;
 5274:         var radioLength = document.requestcourse.cloning.length;
 5275:         if (radioLength == undefined) {
 5276:             if (document.requestcourse.cloning.checked == false) {
 5277:                 alert("$js_lt{'choose'}");
 5278:                 return false;
 5279:             } else {
 5280:                 cloneChoice = document.requestcourse.cloning.value;
 5281:             }
 5282:         } else {
 5283:             for (var i=0; i<radioLength; i++) {
 5284:                 if (document.requestcourse.cloning[i].checked) {
 5285:                     cloneChoice = document.requestcourse.cloning[i].value;
 5286:                     break;
 5287:                 }
 5288:             }
 5289:             if (cloneChoice == 0) {
 5290:                 alert("$js_lt{'choose'}");
 5291:                 return false;
 5292:             }
 5293:         }
 5294:         var group;
 5295:         if ((cloneChoice == 'textbook') || (cloneChoice == 'template') || (cloneChoice == 'existing') || (cloneChoice == 'colleague')) {
 5296:             var group;
 5297:             if (cloneChoice == 'textbook') {
 5298:                 group = document.getElementsByName('book');
 5299:             } else {
 5300:                 if (cloneChoice == 'template') {
 5301:                     group = document.getElementsByName('template');
 5302:                 } else {
 5303:                     if (cloneChoice == 'existing') {
 5304:                         group = document.getElementsByName('owned');
 5305:                     } else {
 5306:                         group = document.getElementsByName('colleague');
 5307:                     }
 5308:                 }
 5309:             }
 5310:             var groupLength = group.length;
 5311:             var chosen = 0;
 5312:             if (groupLength == undefined) {
 5313:                 if (group.checked) {
 5314:                     chosen = 1;
 5315:                 }
 5316:             } else {
 5317:                 for (var j=0; j<groupLength; j++) {
 5318:                     if (group[j].checked) {
 5319:                         chosen = 1;
 5320:                         break;
 5321:                     }
 5322:                 }
 5323:            }
 5324:            if (chosen == 0) {
 5325:                if (cloneChoice == 'textbook') {
 5326:                    alert("$js_lt{'textbook'}");
 5327:                } else {
 5328:                    if (cloneChoice == 'template') {
 5329:                        alert("$js_lt{'template'}");
 5330:                    } else {
 5331:                        if (cloneChoice == 'existing') {
 5332:                            alert("$js_lt{'existing'}");
 5333:                        } else {
 5334:                            alert("$js_lt{'colleague'}");
 5335:                        }
 5336:                    }
 5337:                }
 5338:                return false;
 5339:             }
 5340:         }
 5341:     }
 5342:     if (document.requestcourse.cdescr.value == '') {
 5343:         alert("$js_lt{'title'}");
 5344:         return false;
 5345:     }
 5346:     $customvalidationjs
 5347:     return true;
 5348: }
 5349:  
 5350: ENDSCRIPT
 5351: 
 5352: }
 5353: 
 5354: sub textbook_request_disabled {
 5355:     my ($r,$dom,$action,$can_request) = @_;
 5356:     if (ref($can_request) eq 'HASH') {
 5357:         if ($action eq 'process') {
 5358:             unless ((scalar(keys(%{$can_request})) == 1)) {
 5359:                 &Apache::lonhtmlcommon::add_breadcrumb(
 5360:                    { href => '/adm/requestcourse',
 5361:                      text => 'Pick action',
 5362:                    });
 5363:             }
 5364:         }
 5365:     }
 5366:     $r->print(&header('Course Request'));
 5367:     &Apache::lonhtmlcommon::add_breadcrumb({text=>'Course Request'});
 5368:     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Course Requests','Course_Requests').
 5369:               '<div>'.
 5370:               '<p class="LC_info">'.&mt('You do not have privileges to request creation of textbook courses.').'</p>');
 5371:     if (ref($can_request) eq 'HASH') {
 5372:         if (scalar(keys(%{$can_request})) > 1) {
 5373:             $r->print('<a href="/adm/requestcourse">'.&mt('Go back').'</a>');
 5374:          }
 5375:     }
 5376:     $r->print('</div>'.
 5377:               &Apache::loncommon::end_page());
 5378:     return;
 5379: }
 5380: 
 5381: sub startContentScreen {
 5382:     my ($r,$mode)=@_;
 5383:     $r->print("\n".'<ul class="LC_TabContentBigger" id="textbookreq">'."\n");
 5384:     $r->print('<li'.(($mode eq 'textbookrequests')?' class="active"':'').'><a href="/adm/requestcourse"><b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.&mt('Request a Course').'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</b></a></li>'."\n");
 5385:     $r->print('<li'.(($mode eq 'textbooklogs')?' class="active"':'').'><a href="/adm/requestcourse?action=log&amp;crstype=textbook&amp;tabs=on"><b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.&mt('Course Request History').'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</b></a></li>'."\n");
 5386:     $r->print("\n".'</ul>'."\n");
 5387:     $r->print('<div class="LC_Box" style="clear:both;margin:0;"><div id="mainbox" style="margin:0 0;padding:0 0;"><div class="LC_ContentBox" id="maincontentbox" style="display: block;">');
 5388: }
 5389: 
 5390: sub endContentScreen {
 5391:    my ($r)=@_;
 5392:    $r->print('</div></div></div>');
 5393: }
 5394:    
 5395: 1;
 5396: 

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