File:  [LON-CAPA] / loncom / interface / lonrequestcourse.pm
Revision 1.103: download - view: text, annotated - select for diffs
Fri Mar 23 01:01:21 2018 UTC (6 years, 2 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6754 LON-CAPA as LTI Provider
  - Creation of new LON-CAPA user account available from an LTI Consumer.
  - Creation of new LON-CAPA course available from an LTI Consumer.
  - Self-enrollment in a LON-CAPA course available from an LTI Consumer.

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

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