File:  [LON-CAPA] / loncom / interface / loncoursequeueadmin.pm
Revision 1.34: download - view: text, annotated - select for diffs
Fri Jan 4 01:56:35 2013 UTC (11 years, 4 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Coding style $array[index] preferred to @array[index] when index is a
  single, scalar, value.

    1: # The LearningOnline Network
    2: # Utilities to administer domain course requests and course self-enroll requests
    3: #
    4: # $Id: loncoursequeueadmin.pm,v 1.34 2013/01/04 01:56:35 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: =pod
   31: 
   32: =head1 NAME
   33: 
   34: Apache::loncoursequeueadmin.pm
   35: 
   36: =head1 SYNOPSIS
   37: 
   38: Utilities used by domain coordinators to administer queued course creation requests,
   39: and by course coordinators for queued self-enrollment requests, and by general
   40: users to display their queued self-enrollment requests.  
   41: 
   42: This is part of the LearningOnline Network with CAPA project
   43: described at http://www.lon-capa.org.
   44: 
   45: =head1 SUBROUTINES
   46: 
   47: =over
   48: 
   49: =item send_selfserve_notification()
   50: 
   51: =item display_queued_requests()
   52: 
   53: =item build_queue_display()
   54: 
   55: =item update_request_queue()
   56: 
   57: =item get_student_counts()
   58: 
   59: =item course_creation()
   60: 
   61: =item build_batchcreatehash()
   62:  
   63: =item can_clone_course()
   64: 
   65: =item get_processtype()
   66: 
   67: =item queued_selfenrollment()
   68: 
   69: =item update_coursereq_status()
   70: 
   71: =item process_official_reqs()
   72: 
   73: =item is_active_author()
   74: 
   75: =item author_prompt()
   76: 
   77: =item reqauthor_check()
   78: 
   79: =item process_reqauthor()
   80: 
   81: =back
   82: 
   83: =cut
   84: 
   85: package Apache::loncoursequeueadmin;
   86: 
   87: use strict;
   88: use Apache::lonnet;
   89: use Apache::loncommon;
   90: use Apache::lonmsg;
   91: use Apache::lonlocal;
   92: use Apache::lonuserutils;
   93: use LONCAPA qw(:DEFAULT :match);
   94: 
   95: sub send_selfserve_notification {
   96:     my ($notifylist,$textstr,$cid,$contextdesc,$timestamp,$context,$sender,
   97:         $approvedlist,$rejectedlist,$crstype) = @_;
   98: # FIXME locallocaltime needs to be able to take $sender_lh as an argument
   99: #       so this can be localized to the recipients date display format/time zone
  100:     $timestamp =&Apache::lonlocal::locallocaltime($timestamp);
  101:     my ($msgcc,$rawsubj,@rawmsg,$subject,$message,$reviewer,$msgtxt);
  102:     my ($senderuname,$senderudom) = split(':',$sender);
  103:     if ($context eq 'coursemanagers') {
  104:         $rawsubj = 'Self-enrollment requests processed';
  105:         push(@rawmsg,{
  106:                       mt => 'Enrollment requests in the following course: [_1] have been processed.',
  107:                       args => ["\n$contextdesc"],
  108:                      });
  109:     } elsif ($context eq 'domainmanagers') {
  110:         $rawsubj = 'Course/Community requests reviewed';
  111:         push(@rawmsg,{
  112:                       mt  => 'Course/Community creation requests in the following domain: "[_1]" have been reviewed.',
  113:                       args => ["\n$contextdesc"],
  114:                      });
  115:         if (ref($textstr) eq 'ARRAY') {
  116:             push(@rawmsg,@{$textstr});
  117:         }
  118:     } elsif ($context eq 'authormanagers') {
  119:         $rawsubj = 'Authoring space requests reviewed';
  120:         push(@rawmsg,{
  121:                       mt  => 'Authoring requests in the following domain: "[_1]" have been reviewed.',
  122:                       args => ["\n$contextdesc"],
  123:                      });
  124:         if (ref($textstr) eq 'ARRAY') {
  125:             push(@rawmsg,@{$textstr});
  126:         }
  127:     } elsif ($context eq 'enroller') {
  128:         $rawsubj = 'Enrollment request';
  129:         if ($crstype eq 'community') {
  130:             $msgtxt = 'Your request for enrollment in the following community: [_1]requested on [_2]has been reviewed by a Coordinator.'
  131:         } else {
  132:             $msgtxt = 'Your request for enrollment in the following course: [_1]requested on [_2]has been reviewed by a Course Coordinator.';
  133:         } 
  134:         push(@rawmsg,{
  135:                       mt  => $msgtxt,
  136:                       args => ["\n  ".$contextdesc.",\n",$timestamp.",\n"],
  137: 
  138:                      });
  139:         if (ref($textstr) eq 'ARRAY') {
  140:             push(@rawmsg,@{$textstr});
  141:         }
  142:     } elsif ($context eq 'courserequestor') {
  143:         if ($crstype eq 'Community') {
  144:             $rawsubj = 'Community request';
  145:             $msgtxt = 'Your request for creation of the following community: [_1]requested on [_2]has been reviewed by a Domain Coordinator.';
  146:         } else {
  147:             $rawsubj = 'Course request';
  148:             $msgtxt = 'Your request for creation of the following course: [_1]requested on [_2]has been reviewed by a Domain Coordinator.';
  149:         }
  150:         push(@rawmsg,{
  151:                       mt  => $msgtxt,
  152:                       args => ["\n".$contextdesc.",\n",$timestamp.",\n"],
  153: 
  154:                      });
  155:         if (ref($textstr) eq 'ARRAY') {
  156:             push(@rawmsg,@{$textstr});
  157:         }
  158:     } elsif ($context eq 'pendingrequestor') {
  159:         if ($crstype eq 'Community') {
  160:             $rawsubj = 'Community request';
  161:         } else {
  162:             $rawsubj = 'Processed course request';
  163:         }
  164:         if (ref($textstr) eq 'ARRAY') {
  165:             push(@rawmsg,@{$textstr});
  166:         }
  167:     } elsif ($context eq 'coursereq') {
  168:         if ($crstype eq 'community') {
  169:             $rawsubj = 'Community request to review';
  170:             $msgtxt = 'Creation of the following community: [_1]was requested by [_2] on [_3].';
  171:         } else {
  172:             $rawsubj = 'Course request to review';
  173:             $msgtxt = 'Creation of the following course: [_1]was requested by [_2] on [_3].';
  174:         }
  175:         push(@rawmsg,{
  176:                       mt  => $msgtxt,
  177:                       args => ["\n  $contextdesc\n",$textstr,$timestamp],
  178:                      },
  179:                      {
  180:                       mt =>'[_1]As Domain Coordinator, use: [_2]Main Menu -> Course and community creation -> Approve or reject requests[_3]to display a list of pending requests, which you can either approve or reject.',
  181:                       args => ["\n","\n\n","\n\n"],
  182:                      });
  183:     } elsif ($context eq 'selfenrollreq') {
  184:         $rawsubj = 'Self-enrollment request';
  185:         if ($crstype eq 'community') {
  186:             $msgtxt = 'Enrollment in the following community: [_1]was requested by [_2] on [_3].'
  187:         } else {
  188:             $msgtxt = 'Enrollment in the following course: [_1]was requested by [_2] on [_3].'
  189:         }
  190:         push(@rawmsg,{
  191:                       mt  => $msgtxt,
  192:                       args => ["\n  $contextdesc\n",$textstr,$timestamp."\n"],
  193:                      });
  194:         my $directions;  
  195:         if ($crstype eq 'community') {
  196:             $directions = 'As Coordinator, use: [_1]Main Menu -> Manage Community Users -> Enrollment Requests[_2]to display a list of pending enrollment requests, which you can either approve or reject.';
  197:         } else {
  198:             $directions = 'As Course Coordinator, use: [_1]Main Menu -> Manage Course Users -> Enrollment Requests[_2]to display a list of pending enrollment requests, which you can either approve or reject.';
  199:         }
  200:         push(@rawmsg,
  201:                      {
  202:                       mt   => $directions,
  203:                       args => ["  \n\n","\n"],
  204:                      });
  205:     } elsif ($context eq 'authorreq') {
  206:         $rawsubj = 'Authoring space request to review';
  207:         $msgtxt = 'Assignment of an author role in the [_1] domain[_2]was requested by [_3] on [_4].';
  208:         push(@rawmsg,{
  209:                       mt  => $msgtxt,
  210:                       args => [$contextdesc,"\n",$textstr,$timestamp],
  211:                      },
  212:                      {
  213:                       mt =>'[_1]As Domain Coordinator, use: [_2]Main Menu -> Create users or modify the roles and privileges of users -> Authoring space reqests[_3]to display a list of pending requests, which you can either approve or reject.',
  214:                       args => ["\n","\n\n  ","\n\n"],
  215:                      });
  216: 
  217:     } elsif ($context eq 'requestauthor') {
  218:         $rawsubj = 'Authoring space request';
  219:         $msgtxt = 'Your request for an authoring space requested on [_1]has been reviewed by a Domain Coordinator.';
  220:         push(@rawmsg,{
  221:                       mt  => $msgtxt,
  222:                       args => [$timestamp."\n"],
  223:                      });
  224:         if (ref($textstr) eq 'ARRAY') {
  225:             push(@rawmsg,@{$textstr});
  226:         }
  227:     }
  228:     my @to_notify = split(/,/,$notifylist);
  229:     my $numsent = 0;
  230:     my @recusers;
  231:     my @recudoms;
  232:     foreach my $cc (@to_notify) {
  233:         my ($ccname,$ccdom) = split(/:/,$cc);
  234:         if (!exists($msgcc->{$ccname.':'.$ccdom})) {
  235:             push(@recusers,$ccname);
  236:             push(@recudoms,$ccdom);
  237:             $msgcc->{$ccname.':'.$ccdom}='';
  238:             $numsent ++;
  239:         }
  240:     }
  241:     my %reciphash = (
  242:                      cc => $msgcc,
  243:     );
  244:     my ($uname,$udom);
  245:     if ($sender =~ /:/) {
  246:         ($uname,$udom) = split(/:/,$sender);
  247:     } elsif ($context eq 'course') {
  248:         $uname = $sender;
  249:         my %courseinfo = &Apache::lonnet::coursedescription($cid);
  250:         $udom = $courseinfo{'num'};
  251:     }
  252:     my %sentmessage;
  253:     my $stamp = time;
  254:     my $msgcount = &Apache::lonmsg::get_uniq();
  255:     my $sender_lh = &Apache::loncommon::user_lang($uname,$udom,$cid);
  256:     $subject = &Apache::lonlocal::mt_user($sender_lh,$rawsubj);
  257:     $message = '';
  258:     foreach my $item (@rawmsg) {
  259:         if (ref($item) eq 'HASH') {
  260:             $message .= &Apache::lonlocal::mt_user($sender_lh,$item->{mt},@{$item->{args}})."\n";
  261:         }
  262:     }
  263:     &Apache::lonmsg::process_sent_mail($subject,'',$numsent,$stamp,$uname,$udom,$msgcount,$cid,$$,$message,\@recusers,\@recudoms,undef,undef,undef,undef,$senderuname,$senderudom);
  264:     my ($recipid,$recipstatus) = &Apache::lonmsg::store_recipients($subject,$uname,$udom,\%reciphash);
  265:     my $status;
  266:     foreach my $recip (sort(keys(%{$msgcc}))) {
  267:         my ($ccname,$ccdom) = split(/:/,$recip);
  268:         my $recip_lh = &Apache::loncommon::user_lang($ccname,$ccdom,$cid);
  269:         my $subject = &Apache::lonlocal::mt_user($sender_lh,$rawsubj);
  270:         my $message = '';
  271:         foreach my $item (@rawmsg) {
  272:             if (ref($item) eq 'HASH') {
  273:                 $message .= &Apache::lonlocal::mt_user($sender_lh,$item->{mt},
  274:                                                        @{$item->{args}})."\n";
  275:             }
  276:         }
  277:         if ($context eq 'coursemanagers') {
  278:             if ($approvedlist) {
  279:                 $message .= "\n\n".&Apache::lonlocal::mt_user($sender_lh,'Approved enrollments:')."\n".$approvedlist;
  280:             }
  281:             if ($rejectedlist) {
  282:                 $message .= "\n\n".&Apache::lonlocal::mt_user($sender_lh,'Rejected enrollments:')."\n".$rejectedlist;
  283:             }
  284:         } elsif ($context eq 'domainmanagers') {
  285:             if ($approvedlist) {
  286:                 $message .= "\n\n".&Apache::lonlocal::mt_user($sender_lh,'Approved course requests:')."\n".$approvedlist;
  287:             }
  288:             if ($rejectedlist) {
  289:                 $message .= "\n\n".&Apache::lonlocal::mt_user($sender_lh,'Rejected course requests:')."\n".$rejectedlist;
  290:             }
  291:         } elsif ($context eq 'authormanagers') {
  292:             if ($approvedlist) {
  293:                 $message .= "\n\n".&Apache::lonlocal::mt_user($sender_lh,'Approved author role requests:')."\n".$approvedlist;
  294:             }
  295:             if ($rejectedlist) {
  296:                 $message .= "\n\n".&Apache::lonlocal::mt_user($sender_lh,'Rejected author role requests:')."\n".$rejectedlist;
  297:             }
  298:         }
  299:         $status .= &Apache::lonmsg::user_normal_msg($ccname,$ccdom,$subject,$message,undef,undef,undef,1,\%sentmessage,undef,undef,undef,1,$recipid).',';
  300:     }
  301:     $status =~ s/,$//;
  302:     return ($recipstatus,$status);
  303: }
  304: 
  305: sub display_queued_requests {
  306:     my ($context,$dom,$cnum) = @_;
  307:     my ($namespace,$formaction,$nextelement,%requesthash);
  308:     if ($context eq 'course') {
  309:         $formaction = '/adm/createuser';
  310:         $namespace = 'selfenrollrequests';
  311:         %requesthash = &Apache::lonnet::dump($namespace,$dom,$cnum);
  312:         $nextelement = '<input type="hidden" name="state" value="done" />';
  313:     } elsif ($context eq 'requestauthor') {
  314:         $formaction = '/adm/createuser';
  315:         $namespace = 'requestauthorqueue';
  316:         %requesthash = &Apache::lonnet::dump_dom($namespace,$dom);
  317:         $nextelement = '<input type="hidden" name="state" value="done" />';
  318:     } else {
  319:         $formaction = '/adm/createcourse';
  320:         $namespace = 'courserequestqueue';
  321:         my $disposition = 'approval';
  322:         my $nextphase = 'requestchange';
  323:         if ($context eq 'pending') {
  324:             $disposition = 'pending';
  325:             $nextphase = 'requestvalidation';
  326:         }
  327:         %requesthash = &Apache::lonnet::dump_dom($namespace,$dom,'_'.$disposition);
  328:         $nextelement = '<input type="hidden" name="phase" value="'.$nextphase.'" />';
  329:     }
  330:     my ($output,%queue_by_date);
  331:     if (keys(%requesthash) > 0) {
  332:         $output = '<form method="post" name="changequeue" action="'.$formaction.'" />'."\n".
  333:                   '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n".
  334:                   $nextelement."\n";
  335:         foreach my $item (keys(%requesthash)) {
  336:             my ($timestamp,$entry,$pending);
  337:             if ($context eq 'course') {
  338:                 ($timestamp, my $usec) = split(/:/,$requesthash{$item});
  339:                 $entry = $item.':'.$usec;
  340:             } elsif ($context eq 'requestauthor') {
  341:                 $timestamp = $requesthash{$item};
  342:                 ($entry) = ($item =~ /^($match_username)_approval$/);
  343:             } else {
  344:                 $timestamp = $requesthash{$item}{'timestamp'};
  345:                 if (ref($requesthash{$item}) eq 'HASH') {
  346:                     my ($cnum,$disposition) = split('_',$item);
  347:                     $entry = $cnum.':'.$requesthash{$item}{'ownername'}.':'.
  348:                              $requesthash{$item}{'ownerdom'}.':';
  349:                     if ($context eq 'pending') {
  350:                         $entry .= $requesthash{$item}{'instcode'};
  351:                     } else {
  352:                         $entry .= $requesthash{$item}{'crstype'};
  353:                     }
  354:                     $entry .= ':'.$requesthash{$item}{'description'};
  355:                 }
  356:             }
  357:             if ($entry ne '') {
  358:                 if (ref($queue_by_date{$timestamp}) eq 'ARRAY') {
  359:                     push(@{$queue_by_date{$timestamp}},$entry);
  360:                 } else {
  361:                     $queue_by_date{$timestamp} = [$entry];
  362:                 }
  363:             }
  364:         }
  365:         if (keys(%queue_by_date) > 0) {
  366:             if ($context eq 'course') {
  367:                 $output .=  '<h3>'.&mt('Self-enrollment requests queued pending approval by a Coordinator').'</h3>';
  368:             } elsif ($context eq 'pending') {
  369:                 $output .= '<h3>'.&mt('Requests for official courses queued pending validation').'</h3>'.
  370:                            '<p>'.&mt('Requests are validated against institutional data to confirm that the requestor is an instructor of record.').'<br />'.
  371:                            &mt('Validation is attempted when the request is submitted.').' '.&mt('If unvalidated, the request will be held in a queue.').' '.&mt('Validation of pending requests is automatically repeated daily.').'</p>';
  372:             } elsif ($context eq 'requestauthor') {
  373:                 $output .= '<h3>'.&mt('Requests for authoring space queued pending approval by a Domain Coordinator').'</h3>';
  374:             } else {
  375:                 $output .= '<h3>'.&mt('Course/Community requests queued pending approval by a Domain Coordinator').'</h3>';
  376:             } 
  377:             $output .= &build_queue_display($dom,$context,\%queue_by_date).
  378:                        '<input type="hidden" name="queue" value="approval" />';
  379:         } else {
  380:             $output .= '<div class="LC_info">';
  381:             if ($context eq 'course') {
  382:                 $output .= &mt('There are currently no enrollment requests awaiting approval.');
  383:             } elsif ($context eq 'pending') {
  384:                 $output .= &mt('There are currently no requests for official courses awaiting validation.');
  385:             } elsif ($context eq 'requestauthor') {
  386:                 $output .= &mt('There are currently no requests for authoring space awaiting approval.');
  387:             } elsif ($context eq 'domain') {
  388:                 $output .= &mt('There are currently no course or community requests awaiting approval.');
  389:             }
  390:             $output .= '</div>'; 
  391:         }
  392:         if ($context eq 'pending') {
  393:             $output .= '<br /><input type="submit" name="validationcheck" value="'.
  394:                        &mt('Validate').'" /><br />'."\n".
  395:                        '<p>'.&mt('Any course/community requests which are successfully validated will be created immediately.').' '.&mt('Unvalidated requests will be listed for manual approval/rejection.').'</p>';
  396:         } else {
  397:             $output .= '<br /><input type="submit" name="processqueue" value="'.&mt('Save').'" />';
  398:         }
  399:         $output .= '</form>';
  400:     } else {
  401:         $output .= '<div class="LC_info">';
  402:         if ($context eq 'course') {
  403:             $output .= &mt('There are currently no enrollment requests awaiting approval.');
  404:         } elsif ($context eq 'pending') {
  405:             $output .= &mt('There are currently no requests for official courses awaiting validation.');
  406:         } else {
  407:             $output .= &mt('There are currently no course or community requests awaiting approval.');
  408:         }
  409:         $output .= '</div>';
  410:     }
  411:     return $output;
  412: }
  413: 
  414: sub build_queue_display {
  415:     my ($dom,$context,$queue) = @_;
  416:     return unless (ref($queue) eq 'HASH');
  417:     my %crstypes;
  418:     my $output =  &Apache::loncommon::start_data_table().
  419:                   &Apache::loncommon::start_data_table_header_row();
  420:     unless ($context eq 'pending') { 
  421:         $output .= '<th>'.&mt('Action').'</th>';
  422:     }
  423:     $output .= '<th>'.&mt('Requestor').'</th>';
  424:     if ($context eq 'course') {
  425:         $output .= '<th>'.&mt('Section').'</th>'.
  426:                    '<th>'.&mt('Date requested').'</th>';
  427:     } elsif ($context eq 'requestauthor') {
  428:         $output .= '<th>'.&mt('Date requested').'</th>';
  429:     } elsif ($context eq 'pending' || $context eq 'stillpending') {
  430:         $output .= '<th>'.&mt('Institutional code').'</th>'.
  431:                    '<th>'.&mt('Date requested').'</th>'.
  432:                    '<th>'.&mt('Details').'</th>';
  433:     } else {
  434:         %crstypes = &Apache::lonlocal::texthash (
  435:                         official   => 'Official course',
  436:                         unofficial => 'Unofficial course',
  437:                         community  => 'Community',
  438:                     );
  439:         $output .= '<th>'.&mt('Type').'</th>'.
  440:                    '<th>'.&mt('Date requested').'</th>'.
  441:                    '<th>'.&mt('Details').'</th>';
  442:     }
  443:     $output .= &Apache::loncommon::end_data_table_header_row();
  444:     my @sortedtimes = sort {$a <=> $b} (keys(%{$queue}));
  445:     my $count = 0;
  446:     foreach my $item (@sortedtimes) {
  447:         if (ref($queue->{$item}) eq 'ARRAY') {
  448:             foreach my $request (sort(@{$queue->{$item}})) {
  449:                 my ($row,$approve,$reject,$showtime,$showsec,$namelink,
  450:                     $detailslink,$crstype,$instcode);
  451:                 $showtime = &Apache::lonlocal::locallocaltime($item);
  452:                 if ($context eq 'course') {
  453:                     my ($puname,$pudom,$pusec) = split(/:/,$request);
  454:                     $approve = $count.':'.$puname.':'.$pudom.':'.$pusec;
  455:                     $reject = $puname.':'.$pudom;
  456:                     $showsec = $pusec;
  457:                     if ($showsec eq '') {
  458:                         $showsec = &mt('none');
  459:                     }
  460:                     $namelink = &Apache::loncommon::aboutmewrapper(
  461:                                 &Apache::loncommon::plainname($puname,$pudom),
  462:                                 $puname,$pudom);
  463:                 } elsif ($context eq 'requestauthor') {
  464:                     if (&Apache::lonnet::homeserver($request,$dom) ne 'no_host') {
  465:                         $approve = $count.':'.$request;
  466:                         $reject = $request; 
  467:                         $namelink = &Apache::loncommon::aboutmewrapper(
  468:                                     &Apache::loncommon::plainname($request,$dom),
  469:                                     $request,$dom);
  470:                     }
  471:                 } else {
  472:                     my ($cnum,$ownername,$ownerdom,$type,$cdesc);
  473:                     my $queue = 'approval'; 
  474:                     if ($context eq 'pending' || $context eq 'stillpending') {
  475:                         ($cnum,$ownername,$ownerdom,$instcode,$cdesc)=split(/:/,$request,5);
  476:                         $queue = 'pending';                        
  477:                     } else {
  478:                         ($cnum,$ownername,$ownerdom,$type,$cdesc)=split(/:/,$request,5);
  479:                         $crstype = $type;
  480:                         if (defined($crstypes{$type})) {
  481:                             $crstype = $crstypes{$type};
  482:                         }
  483:                     }
  484:                     $detailslink='<a href="javascript:opencoursereqdisplay('.
  485:                                   "'$dom','$cnum','$queue'".');">'.$cdesc.'</a>';
  486:                     $approve = $count.':'.$cnum;
  487:                     $reject = $cnum;
  488:                     $namelink = &Apache::loncommon::aboutmewrapper(
  489:                                 &Apache::loncommon::plainname($ownername,$ownerdom),
  490:                                 $ownername,$ownerdom);
  491:                 }
  492:                 unless ($context eq 'pending') {
  493:                     $row = '<td><span class="LC_nobreak"><label>'.
  494:                            '<input type="radio" value="'.$approve.'" name="'.$count.'radioreq" />'.&mt('Approve').'</label>'.
  495:                            '<label>'.('&nbsp;'x2).
  496:                            '<input type="radio" value="'.$reject.'" name="'.$count.'radioreq" />'.&mt('Reject').'</label>'.
  497:                            '<label>'.('&nbsp;'x2).
  498:                            '<input type="radio" value="'."later:".$reject.'" name="'.$count.'radioreq" checked />'.&mt('Decide Later').
  499:                            '</label></span><br /></td>';
  500:                 }
  501:                 $row .= '<td>'.$namelink.'</td>'."\n";
  502:                 if ($context eq 'course') {
  503:                     $row .= '<td>'.$showsec.'</td>'."\n".
  504:                             '<td>'.$showtime.'</td>'."\n";
  505:                 } elsif ($context eq 'requestauthor') {
  506:                     $row .= '<td>'.$showtime.'</td>'."\n";
  507:                 } else { 
  508:                     if ($context eq 'pending' || $context eq 'stillpending') {
  509:                         $row .= '<td>'.$instcode.'</td>'."\n";
  510:                     } else {
  511:                         $row .= '<td>'.$crstype.'</td>'."\n";
  512:                     }
  513:                     $row .= '<td>'.$showtime.'</td>'."\n".
  514:                             '<td>'.$detailslink.'</td>'."\n";
  515:                 }
  516:                 $output .= &Apache::loncommon::start_data_table_row()."\n".
  517:                            $row.
  518:                            &Apache::loncommon::end_data_table_row()."\n";
  519:                 $count ++;
  520:             }
  521:         }
  522:     }
  523:     $output .= &Apache::loncommon::end_data_table();
  524:     return $output;
  525: }
  526: 
  527: sub update_request_queue {
  528:     my ($context,$cdom,$cnum,$coursedesc) = @_;
  529:     my ($output,$access_start,$access_end,$limit,$cap,$notifylist,$namespace,
  530:         $stucounts,$idx,$classlist,%requesthash,$cid,$domdesc,$now,
  531:         $sender,$approvedmsg,$rejectedmsg,$beneficiary,
  532:         @existing,@missingreq,@invalidusers,@limitexceeded,@completed,
  533:         @processing_errors,@warn_approves,@warn_rejects,@approvals,@warn_dels,
  534:         @rejections,@rejectionerrors,@nopermissions,%courseroles,@toremove,
  535:         %communityroles,%domdefs,%approvalmsg,%rejectionmsg,$crstype,$queue,
  536:         $firsturl);
  537:     my $count=0;
  538:     while (my @course = &Apache::loncommon::get_env_multiple('form.'.$count.'radioreq')) {
  539:         if ($course[0] =~ /^\d+:.*/) {
  540:             push(@approvals,$course[0]);
  541:         } elsif ($course[0] =~ /^later:.*/) {
  542:             #decide later
  543:         } else {
  544:             push(@rejections,$course[0]);
  545:         }
  546:         $count+=1;
  547:     }
  548: 
  549:     $now = time;
  550:     $sender = $env{'user.name'}.':'.$env{'user.domain'};
  551:     if ($context eq 'course') {
  552:         $namespace = 'selfenrollrequests';
  553:         $beneficiary = 'enroller';
  554:         $cid = $env{'request.course.id'};
  555:         $crstype = lc(&Apache::loncommon::course_type());
  556:         $firsturl = &course_portal_url($cnum,$cdom);
  557:         %requesthash = &Apache::lonnet::dump($namespace,$cdom,$cnum);
  558:         $access_start =  $env{'course.'.$cid.'.internal.selfenroll_start_access'};
  559:         $access_end =  $env{'course.'.$cid.'.internal.selfenroll_end_access'};
  560:         $limit = $env{'course.'.$cid.'.internal.selfenroll_limit'};
  561:         $cap = $env{'course.'.$cid.'.internal.selfenroll_cap'};
  562:         $notifylist = $env{'course.'.$cid.'.internal.selfenroll_notifylist'};
  563:         ($stucounts,$idx,$classlist) = &get_student_counts($cdom,$cnum);
  564:         $approvedmsg = [{
  565:                             mt => 'Your request for enrollment has been approved.',
  566:                         },
  567:                         {
  568:                             mt   => 'Visit [_1] to log-in and access the course',
  569:                             args => [$firsturl],
  570:                         }];
  571:         $rejectedmsg =  [{
  572:                             mt => 'Your request for enrollment has not been approved.',
  573:                         }];
  574:     } elsif ($context eq 'requestauthor') {
  575:         $namespace = 'requestauthorqueue';
  576:         $beneficiary = 'requestauthor';
  577:         %requesthash = &Apache::lonnet::dump_dom($namespace,$cdom);
  578:         my %domdefs = &Apache::lonnet::get_domain_defaults($cdom);
  579:         if (ref($domdefs{'requestauthor'}) eq 'HASH') {
  580:             if (ref($domdefs{'requestauthor'}{'notify'}) eq 'HASH') {
  581:                 $notifylist = $domdefs{'requestauthor'}{'notify'}{'approval'};
  582:             }
  583:         }
  584:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
  585:         $firsturl = &course_portal_url($domconfiguser,$cdom);
  586:         $approvedmsg = [{
  587:                             mt => 'Your request for authoring space has been approved.',
  588:                         },
  589:                         {
  590:                             mt   => 'Visit [_1] to log-in and select your author role',
  591:                             args => [$firsturl],
  592:                         }];
  593:         $rejectedmsg =  [{
  594:                             mt => 'Your request for authoring space has not been approved.',
  595:                         }];
  596:         $domdesc = &Apache::lonnet::domain($cdom);
  597:     } else {
  598:         $domdesc = &Apache::lonnet::domain($cdom);
  599:         $namespace = 'courserequestqueue';
  600:         $beneficiary = 'courserequestor';
  601:         $queue = 'approval';
  602:         if ($env{'form.queue'} eq 'pending') {
  603:             $queue = 'pending';
  604:         }
  605:         %requesthash = &Apache::lonnet::dump_dom($namespace,$cdom,'_'.$queue);
  606:         my %domconfig = &Apache::lonnet::get_dom('configuration',['requestcourses'],$cdom);
  607:         if (ref($domconfig{'requestcourses'}) eq 'HASH') {
  608:             if (ref($domconfig{'requestcourses'}{'notify'}) eq 'HASH') { 
  609:                 $notifylist = $domconfig{'requestcourses'}{'notify'}{'approval'};
  610:             }
  611:         }
  612:         $approvalmsg{'course'} = 
  613:                         [{
  614:                             mt => 'Your course request has been approved.',
  615:                         },
  616:                         {
  617:                             mt   => 'Visit [_1] to log-in and access the course',
  618:                             args => [],
  619:                         }];
  620:         $rejectionmsg{'course'} =
  621:                         [{
  622:                             mt => 'Your course request has not been approved.',
  623:                         }];
  624: 
  625:         $approvalmsg{'community'} = 
  626:                         [{
  627:                             mt => 'Your community request has been approved.',
  628:                         },
  629:                         {
  630:                             mt   => 'Visit [_1] to log-in and access the community',
  631:                             args => [],
  632:                         }];
  633: 
  634:         $rejectionmsg{'community'} = 
  635:                         [{
  636:                             mt => 'Your community request has not been approved.',
  637:                         }];
  638: 
  639:         %domdefs = &Apache::lonnet::get_domain_defaults($cdom);
  640:         my @roles = &Apache::lonuserutils::roles_by_context('course');
  641:         foreach my $role (@roles) {
  642:             $courseroles{$role}=&Apache::lonnet::plaintext($role,'Course');
  643:         }
  644:         foreach my $role (@roles) {
  645:             $communityroles{$role}=&Apache::lonnet::plaintext($role,'Community');
  646:         }
  647:     }
  648:     foreach my $item (sort {$a <=> $b} @approvals) {
  649:         if ($context eq 'course') {
  650:             my ($num,$uname,$udom,$usec) = split(/:/,$item);
  651:             my $uhome = &Apache::lonnet::homeserver($uname,$udom);
  652:             if ($uhome ne 'no_host') {
  653:                 if (exists($requesthash{$uname.':'.$udom})) {
  654:                     if (exists($classlist->{$uname.':'.$udom})) {
  655:                         if (ref($classlist->{$uname.':'.$udom}) eq 'ARRAY') {
  656:                             if (($classlist->{$uname.':'.$udom}->[$idx->{'status'}] eq 'Active') ||
  657:                                 ($classlist->{$uname.':'.$udom}->[$idx->{'status'}] eq 'Future')) {
  658:                                 push(@existing,$uname.':'.$udom);
  659:                                 next;
  660:                             }
  661:                         }
  662:                     }
  663:                 } else {
  664:                     push(@missingreq,$uname.':'.$udom);
  665:                     next;
  666:                 }
  667:                 if (!grep(/^\Q$item\E$/,@rejections)) {
  668:                     if ($limit eq 'allstudents') {
  669:                         if ($stucounts->{$limit} >= $cap) {
  670:                             push(@limitexceeded,$uname.':'.$udom);
  671:                             last;
  672:                         }
  673:                     } elsif ($limit eq 'selfenrolled') {
  674:                         if ($stucounts->{$limit} >= $cap) {
  675:                             push(@limitexceeded,$uname.':'.$udom);
  676:                             last;
  677:                         }
  678:                     }
  679:                     my $result =
  680:                         &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$usec,$access_end,$access_start,'selfenroll',undef,$cdom.'_'.$cnum,1);
  681:                     if ($result eq 'ok') {
  682:                         push(@completed,$uname.':'.$udom);
  683:                         $stucounts->{'allstudents'} ++;
  684:                         $stucounts->{'selfenrolled'} ++;
  685:                         &send_selfserve_notification($uname.':'.$udom,$approvedmsg,
  686:                                        $cid,$coursedesc,$now,$beneficiary,$sender,
  687:                                        undef,undef,$crstype);
  688:                         my %userrequest = (
  689:                             $cdom.'_'.$cnum => {
  690:                                 timestamp   => $now,
  691:                                 section     => $usec,
  692:                                 adjudicator => $env{'user.name'}.':'.$env{'user.domain'},
  693:                                 status      => 'approved',
  694:                             }
  695:                         );
  696:                         my $userresult =
  697:                             &Apache::lonnet::put($namespace,\%userrequest,$udom,$uname);
  698:                         if ($userresult ne 'ok') {
  699:                             push(@warn_approves,$uname.':'.$udom);
  700:                         }
  701:                     } else {
  702:                         push(@processing_errors,$uname.':'.$udom);
  703:                     }
  704:                 }
  705:             } else {
  706:                 push(@invalidusers,$uname.':'.$udom);
  707:             }
  708:         } elsif ($context eq 'requestauthor') {
  709:             my ($num,$uname) = split(/:/,$item);
  710:             my $uhome = &Apache::lonnet::homeserver($uname,$cdom);
  711:             if ($uhome ne 'no_host') {
  712:                 my ($user_is_adv,$user_is_author) = &Apache::lonnet::is_advanced_user($cdom,$uname);
  713:                 if ($user_is_author) {
  714:                     push(@existing,$uname);
  715:                 } elsif (&Apache::lonnet::usertools_access($uname,$cdom,'requestauthor',
  716:                                                            undef,'requestauthor')) {
  717:                     if (&Apache::lonnet::allowed('cau',$cdom)) {
  718:                         if (&Apache::lonnet::assignrole($cdom,$uname,'/'.$cdom.'/','au',undef,time,undef,undef,'requestauthor') eq 'ok') {
  719:                             push(@completed,$uname);
  720:                             unless (&Apache::lonnet::del_dom($namespace,[$uname.'_approval'],$cdom) eq 'ok') {
  721:                                 push(@warn_dels,$uname);
  722:                             }
  723:                             &send_selfserve_notification($uname.':'.$cdom,
  724:                                                          $approvedmsg,undef,undef,$now,
  725:                                                          $beneficiary,$sender);
  726:                             my %userrequest = (
  727:                                 author => {
  728:                                           timestamp   => $now,
  729:                                           adjudicator => $env{'user.name'}.':'.$env{'user.domain'},
  730:                                           status      => 'approved',
  731:                                         },
  732:                                 author_status => 'approved',
  733:                             );
  734:                             my $userresult =
  735:                                 &Apache::lonnet::put('requestauthor',\%userrequest,$cdom,$uname);
  736:                             if ($userresult ne 'ok') {
  737:                                 push(@warn_approves,$item);
  738:                             }
  739:                         } else {
  740:                             push(@processing_errors,$uname);
  741:                         }
  742:                     } else {
  743:                         push(@nopermissions,$uname);
  744:                     }
  745:                 } else {
  746:                     push(@nopermissions,$uname);
  747:                 }
  748:             } else {
  749:                 push(@invalidusers,$uname.':'.$cdom);
  750:             }
  751:             push(@toremove,(@invalidusers,@nopermissions));
  752:         } else {
  753:             my ($num,$cnum) = split(':',$item);
  754:             if (ref($requesthash{$cnum.'_'.$queue}) eq 'HASH') {
  755:                 if (&Apache::lonnet::homeserver($cnum,$cdom) eq 'no_host') {
  756:                     my $ownername = $requesthash{$cnum.'_'.$queue}{'ownername'};
  757:                     my $ownerdom = $requesthash{$cnum.'_'.$queue}{'ownerdom'};
  758:                     $crstype = $requesthash{$cnum.'_'.$queue}{'crstype'};
  759:                     my $coursedesc = $requesthash{$cnum.'_'.$queue}{'description'};
  760:                     my $longroles = \%courseroles;
  761:                     if ($crstype eq 'community') {
  762:                         $longroles = \%communityroles;
  763:                     }
  764:                     my $cancreate;
  765:                     if ($cdom eq $ownerdom) {
  766:                         if (&Apache::lonnet::usertools_access($ownername,$ownerdom,$crstype,
  767:                                                               undef,'requestcourses')) {
  768:                             $cancreate = 1;
  769:                         }
  770:                     } else {
  771:                         my %userenv = &Apache::lonnet::userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.$crstype);
  772:                         if ($userenv{'reqcrsotherdom.'.$crstype}) {
  773:                             my @doms = split(',',$userenv{'reqcrsotherdom.'.$crstype});
  774:                             if (grep(/^\Q$cdom\E:/,@doms)) {
  775:                                 $cancreate = 1;
  776:                             }
  777:                         }
  778:                     }
  779:                     if ($cancreate) {
  780:                         my $requestkey = $cdom.'_'.$cnum;
  781:                         my %history = 
  782:                             &Apache::lonnet::restore($requestkey,'courserequests',
  783:                                                      $ownerdom,$ownername);
  784:                         if ((ref($history{'details'}) eq 'HASH') && 
  785:                             ($history{'disposition'} eq $queue)) {
  786:                             my ($logmsg,$newusermsg,$addresult,$enrollcount,$response,$keysmsg);
  787:                             my $result = &course_creation($cdom,$cnum,$context,$history{'details'},\$logmsg,
  788:                                                       \$newusermsg,\$addresult,\$enrollcount,
  789:                                                       \$response,\$keysmsg,\%domdefs,$longroles);
  790:                             if ($result eq 'created') {
  791:                                 if ($crstype eq 'community') {
  792:                                     $approvedmsg = $approvalmsg{'community'};
  793:                                 } else {
  794:                                     $approvedmsg = $approvalmsg{'course'};
  795:                                 }
  796:                                 my $firsturl = &course_portal_url($cnum,$cdom);
  797:                                 if (ref($approvedmsg) eq 'ARRAY') {
  798:                                     if (ref($approvedmsg->[1]) eq 'HASH') {
  799:                                         $approvedmsg->[1]->{'args'} = [$firsturl];
  800:                                     }
  801:                                 }
  802:                                 push(@completed,$cnum);
  803:                                 
  804:                                 unless (&Apache::lonnet::del_dom($namespace,[$cnum.'_'.$queue],$cdom) eq 'ok') {
  805:                                     push(@warn_dels,$cnum);
  806:                                 }
  807:                                 &send_selfserve_notification($ownername.':'.$ownerdom,
  808:                                               $approvedmsg,$cid,$coursedesc,$now,
  809:                                               $beneficiary,$sender,undef,undef,$crstype);
  810:                                 my %reqhash = (
  811:                                                 reqtime     => $history{'reqtime'},
  812:                                                 crstype     => $history{'crstype'},
  813:                                                 details     => $history{'details'},
  814:                                                 disposition => $history{'disposition'},
  815:                                                 status      => 'created',
  816:                                                 adjudicator => $env{'user.name'}.':'.
  817:                                                                $env{'user.domain'},
  818:                                               );
  819:                                 my $userresult =
  820:                                     &Apache::lonnet::store_userdata(\%reqhash,$requestkey,
  821:                                                    'courserequests',$ownerdom,$ownername);
  822:                                 if ($userresult eq 'ok') {
  823:                                     my %status = (
  824:                                                    'status:'.$cdom.':'.$cnum => 'created'
  825:                                                  );
  826:                                     my $statusresult = 
  827:                                         &Apache::lonnet::put('courserequests',\%status,
  828:                                                              $ownerdom,$ownername);
  829:                                     if ($statusresult ne 'ok') {
  830:                                         push(@warn_approves,$cnum);
  831:                                     }
  832:                                 }
  833:                                 if ($userresult ne 'ok') {
  834:                                     push(@warn_approves,$cnum);
  835:                                 }
  836:                             } else {
  837:                                 push(@processing_errors,$cnum);
  838:                             }
  839:                         } else {
  840:                             push(@processing_errors,$cnum);
  841:                         }
  842:                     } else {
  843:                         push(@nopermissions,$cnum);
  844:                     }
  845:                 } else {
  846:                     push(@existing,$cnum);
  847:                 }
  848:             } else {
  849:                 push(@missingreq,$cnum);
  850:             }
  851:         }
  852:     }
  853:     my @changes = (@completed,@rejections);
  854:     if ($context eq 'domain') {
  855:         @changes = map {$_.'_'.$queue} (@changes);
  856:     } elsif ($context eq 'requestauthor') {
  857:         @changes = map {$_.'_approval'} (@changes);
  858:     }
  859:     if (@rejections) {
  860:         foreach my $item (@rejections) {
  861:             if (($context eq 'course') || ($context eq 'requestauthor')) {
  862:                 my ($user,$uname,$udom,%userrequest,$key);
  863:                 if ($context eq 'requestauthor') {
  864:                     $uname = $item;
  865:                     $udom = $cdom;
  866:                     $user = $uname.':'.$udom;
  867:                     $key = 'author';
  868:                 } else {
  869:                     $user = $item;
  870:                     ($uname,$udom) = split(/:/,$user);
  871:                     $key = $cdom.'_'.$cnum;
  872:                 }
  873:                 &send_selfserve_notification($user,$rejectedmsg,$cid,$coursedesc,
  874:                                              $now,$beneficiary,$sender,undef,undef,
  875:                                              $crstype);
  876:                 %userrequest = (
  877:                     $key => {
  878:                         timestamp   => $now,
  879:                         adjudicator => $env{'user.name'}.':'.$env{'user.domain'},
  880:                         status      => 'rejection',
  881:                     }
  882:                 );
  883:                 if ($context eq 'requestauthor') {
  884:                     $userrequest{'author_status'} = 'rejection';  
  885:                 }
  886:                 my $userresult =
  887:                     &Apache::lonnet::put('requestauthor',\%userrequest,$udom,$uname);
  888:                 if ($userresult ne 'ok') {
  889:                     push(@warn_rejects,$item);
  890:                 }
  891:             } else {
  892:                 my $cnum = $item;
  893:                 if (ref($requesthash{$cnum.'_'.$queue}) eq 'HASH') {
  894:                     if (&Apache::lonnet::homeserver($cnum,$cdom) eq 'no_host') {
  895:                         my $requestkey = $cdom.'_'.$cnum;
  896:                         my $ownername = $requesthash{$cnum.'_'.$queue}{'ownername'};
  897:                         my $ownerdom = $requesthash{$cnum.'_'.$queue}{'ownerdom'};
  898:                         my $coursedesc = $requesthash{$cnum.'_'.$queue}{'description'};
  899:                         $crstype = $requesthash{$cnum.'_'.$queue}{'crstype'};
  900:                         if ($crstype eq 'community') {
  901:                             $rejectedmsg = $rejectionmsg{'community'};
  902:                         } else {
  903:                             $rejectedmsg = $rejectionmsg{'course'};
  904:                         }
  905:                         &send_selfserve_notification($ownername.':'.$ownerdom,$rejectedmsg,
  906:                                                      $cid,$coursedesc,$now,$beneficiary,
  907:                                                      $sender,undef,undef,$crstype);
  908:                         my %history =
  909:                             &Apache::lonnet::restore($requestkey,'courserequests',
  910:                                                      $ownerdom,$ownername);
  911:                         if ((ref($history{'details'}) eq 'HASH') &&
  912:                             ($history{'disposition'} eq $queue)) {
  913:                             my %reqhash = (
  914:                                             reqtime     => $history{'reqtime'},
  915:                                             crstype     => $history{'crstype'},
  916:                                             details     => $history{'details'},
  917:                                             disposition => $history{'disposition'},
  918:                                             status      => 'rejected',
  919:                                             adjudicator => $env{'user.name'}.':'.$env{'user.domain'},
  920:                                               );
  921:                             my $userresult =
  922:                                 &Apache::lonnet::store_userdata(\%reqhash,$requestkey,
  923:                                                 'courserequests',$ownerdom,$ownername);
  924:                             if ($userresult eq 'ok') {
  925:                                 my %status = (
  926:                                                'status:'.$cdom.':'.$cnum => 'rejected'
  927:                                              );
  928:                                 my $statusresult =
  929:                                     &Apache::lonnet::put('courserequests',\%status,
  930:                                                          $ownerdom,$ownername);
  931:                                 if ($statusresult ne 'ok') {
  932:                                     push(@warn_rejects,$cnum);
  933:                                 }
  934:                             } else {
  935:                                 push(@warn_rejects,$cnum);
  936:                             }
  937:                             unless (&Apache::lonnet::del_dom($namespace,[$cnum.'_'.$queue],$cdom) eq 'ok') {
  938:                                 push(@warn_dels,$cnum);
  939:                             }
  940:                         } else {
  941:                             push(@warn_rejects,$cnum);
  942:                         }
  943:                     } else {
  944:                         push(@existing,$cnum);
  945:                     }
  946:                 } else {
  947:                     push(@rejectionerrors,$cnum);
  948:                 }
  949:             }
  950:         }
  951:     }
  952:     if (@toremove) {
  953:         foreach my $item (@toremove) {
  954:             my %userrequest = (
  955:                 author => {
  956:                             timestamp   => $now,
  957:                             adjudicator => $env{'user.name'}.':'.$env{'user.domain'},
  958:                             status      => 'deleted',
  959:                           },
  960:                           author_status => 'deleted',
  961:             );
  962:             &Apache::lonnet::put('requestauthor',\%userrequest,$cdom,$item);
  963:         }
  964:         @toremove = map {$_.'_approval'} (@toremove);
  965:         my $delresult = &Apache::lonnet::del_dom($namespace,\@toremove,$cdom);
  966:     }
  967:     if (@changes) {
  968:         my $delresult;
  969:         if ($context eq 'course') {
  970:             $delresult = &Apache::lonnet::del($namespace,\@changes,$cdom,$cnum);
  971:         } else {
  972:             $delresult = &Apache::lonnet::del_dom($namespace,\@changes,$cdom);
  973:         }
  974:         if ($delresult eq 'ok') {
  975:             my $namelink =
  976:                 &Apache::loncommon::plainname($env{'user.name'},$env{'user.domain'}).' ('.$env{'user.name'}.':'.$env{'user.domain'}.')';
  977:             my ($chgmsg,$approvedlist,$rejectedlist);
  978:             if ($context eq 'course') {
  979:                 $chgmsg = "'Action was taken on the following enrollment requests by [_1].',$namelink";
  980:                 if (@completed) {
  981:                     $approvedlist = join("\n",@completed);
  982:                     if ($crstype eq 'community') {
  983:                         $output .= '<p>'.&mt('The following were enrolled in the community:').'<ul>';
  984:                     } else {
  985:                         $output .= '<p>'.&mt('The following were enrolled in the course:').'<ul>';
  986:                     }
  987:                     foreach my $user (@completed) {
  988:                         my ($uname,$udom) = split(/:/,$user);
  989:                         my $userlink =
  990:                             &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$udom),$uname,$udom);
  991:                         $output .= '<li>'.$userlink.'</li>';
  992:                     }
  993:                     $output .= '</ul></p>';
  994:                 }
  995:                 if (@rejections) {
  996:                     $rejectedlist = join("\n",@rejections);
  997:                     $output .= '<p>'.&mt('The following enrollment requests were rejected:').'<ul>';
  998:                     foreach my $user (@rejections) {
  999:                         $output .= '<li>'.$user.'</li>';
 1000:                     }
 1001:                     $output .= '</ul></p>';
 1002:                 }
 1003:                 if ($notifylist ne '') {
 1004:                     &send_selfserve_notification($notifylist,$chgmsg,$cid,$coursedesc,
 1005:                                                  $now,'coursemanagers',$sender,
 1006:                                                  $approvedlist,$rejectedlist,$crstype);
 1007:                 }
 1008:             } elsif ($context eq 'requestauthor') {
 1009:                 $chgmsg = "'Action was taken on the following authoring space requests by [_1].',$namelink";
 1010:                 if (@completed) {
 1011:                     $approvedlist = join("\n",@completed);
 1012:                     $output .= '<p>'.&mt('The following requests were approved:').'<ul>';
 1013:                     foreach my $uname (@completed) {
 1014:                         my $userlink =
 1015:                             &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$cdom),$uname,$cdom);
 1016:                         $output .= '<li>'.$userlink.'</li>';
 1017:                         
 1018:                     }
 1019:                     $output .= '</ul></p>';
 1020:                 }
 1021:                 if (@rejections) {
 1022:                     $rejectedlist = join("\n",@rejections);
 1023:                     $output .= '<p>'.&mt('The following requests were rejected:').'<ul>';
 1024:                     foreach my $uname (@rejections) {
 1025:                         my $userlink =
 1026:                             &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$cdom),$uname,$cdom);
 1027:                         $output .= '<li>'.$userlink.'</li>';
 1028:                     }
 1029:                     $output .= '</ul></p>';
 1030:                 }
 1031:                 if ($notifylist ne '') {
 1032:                     &send_selfserve_notification($notifylist,$chgmsg,undef,$domdesc,
 1033:                                                  $now,'authormanagers',$sender,
 1034:                                                  $approvedlist,$rejectedlist);
 1035:                 }
 1036:             } else {
 1037:                 $chgmsg = "'Action was taken on the following course and community requests by [_1].',$namelink";
 1038:                 if (@completed) {
 1039:                     $approvedlist = join("\n",@completed);
 1040:                     $output .= '<p>'.&mt('The following courses/communities were created:').'<ul>';
 1041:                     foreach my $cnum (@completed) {
 1042:                         my $showcourse;
 1043:                         if (ref($requesthash{$cnum.'_'.$queue})) {
 1044:                             $showcourse = $requesthash{$cnum.'_'.$queue}{'description'};
 1045:                         } else {
 1046:                             $showcourse = $cnum;
 1047:                         }
 1048:                         my $syllabuslink =
 1049:                             &Apache::loncommon::syllabuswrapper($showcourse,$cnum,$cdom);
 1050:                         $output .= '<li>'.$syllabuslink.'</li>';
 1051:                     }
 1052:                     $output .= '</ul></p>';
 1053:                 }
 1054:                 if (@rejections) {
 1055:                     $rejectedlist = join("\n",@rejections);
 1056:                     $output .= '<p>'.&mt('The following requests were rejected:').'<ul>';
 1057:                     foreach my $cnum (@rejections) {
 1058:                         my $showcourse;
 1059:                         if (ref($requesthash{$cnum.'_'.$queue})) {
 1060:                             $showcourse = $requesthash{$cnum.'_'.$queue}{'description'};
 1061:                         } else {
 1062:                             $showcourse = $cnum;
 1063:                         }
 1064:                         $output .= '<li>'.$showcourse.'</li>';
 1065:                     }
 1066:                     $output .= '</ul></p>';
 1067:                 }
 1068:                 if ($notifylist ne '') {
 1069:                     &send_selfserve_notification($notifylist,$chgmsg,$cid,$domdesc,
 1070:                                                  $now,'domainmanagers',$sender,
 1071:                                                  $approvedlist,$rejectedlist,$crstype);
 1072:                 }
 1073:             }
 1074:         }
 1075:     }
 1076:     if (@existing) {
 1077:         if ($context eq 'course') {
 1078:             $output .= '<p>'.&mt('The following enrollment requests were deleted because the user is already enrolled in the course:').'<ul>';
 1079:             foreach my $user (@existing) {
 1080:                 $output .= '<li>'.$user.'</li>';
 1081:             }
 1082:             $output .= '</ul></p>';
 1083:         } elsif ($context eq 'requestauthor') {
 1084:             $output .= '<p>'.&mt('Authoring space requests from the following users were deleted because one already exists:').'<ul>';
 1085:             foreach my $uname (@existing) {
 1086:                 my $userlink =
 1087:                     &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$cdom),$uname,$cdom);
 1088:                 $output .= '<li>'.$userlink.'</li>';
 1089:             }
 1090:             $output .= '</ul></p>';
 1091:         } else {
 1092:             $output .= '<p>'.&mt('The following course/community creation requests were deleted because the course or community has already been created:').'<ul>';
 1093:             foreach my $cnum (@existing) {
 1094:                 my $showcourse;
 1095:                 my %coursehash = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 1096:                 if ($coursehash{'description'} ne '') {
 1097:                     $showcourse = $coursehash{'description'};
 1098:                 } else {
 1099:                     $showcourse = $cnum;
 1100:                 }
 1101:                 $output .= '<li>'.$showcourse.'</li>';
 1102:             }
 1103:             $output .= '</ul></p>';
 1104:         }
 1105:     }
 1106:     if (@missingreq) {
 1107:         if ($context eq 'course') {
 1108:             $output .= '<p>'.&mt('The following enrollment requests were ignored because the request is no longer in the enrollment queue:').'<ul>';
 1109:             foreach my $user (@missingreq) {
 1110:                 $output .= '<li>'.$user.'</li>';
 1111:             }
 1112:             $output .= '</ul></p>';
 1113:         } elsif ($context eq 'requestauthor') {
 1114:             $output .= '<p>'.&mt('The following requests were ignored because the request is no longer in the queue:').'<ul>';
 1115:             foreach my $uname (@missingreq) {
 1116:                 my $userlink =
 1117:                     &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$cdom),$uname,$cdom);
 1118:                 $output .= '<li>'.$userlink.'</li>';
 1119:             }
 1120:             $output .= '</ul></p>';
 1121:         } else {
 1122:             $output .= '<p>'.&mt('The following course/community creation requests were ignored because the request is no longer in the queue:').'<ul>';
 1123:             foreach my $cnum (@missingreq) {
 1124:                 $output .= '<li>'.$cnum.'</li>';
 1125:             }
 1126:             $output .= '</ul></p>';
 1127:         }
 1128:     }
 1129:     if (@invalidusers) {
 1130:         if ($context eq 'course') {
 1131:             $output .= '<p>'.&mt('The following enrollment requests were deleted because the requestor does not have a LON-CAPA account:').'<ul>';
 1132:             foreach my $user (@invalidusers) {
 1133:                 $output .= '<li>'.$user.'</li>';
 1134:             }
 1135:             $output .= '</ul></p>';
 1136:         } elsif ($context eq 'requestauthor') {
 1137:             $output .= '<p>'.&mt('The following authoring space requests were deleted because the requestor does not have a LON-CAPA account:').'<ul>';
 1138:             foreach my $uname (@invalidusers) {
 1139:                 my $userlink =
 1140:                     &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$cdom),$uname,$cdom);
 1141:                 $output .= '<li>'.$userlink.'</li>';
 1142:             }
 1143:             $output .= '</ul></p>';
 1144:         }
 1145:     }
 1146:     if (@limitexceeded) {
 1147:         if ($context eq 'course') {
 1148:             $output .= '<p>'.&mt('The following enrollment requests were skipped because the enrollment limit has been reached for the course:').'<ul>';
 1149:             foreach my $user (@limitexceeded) {
 1150:                 $output .= '<li>'.$user.'</li>';
 1151:             }
 1152:             $output .= '</ul></p>';
 1153:         }
 1154:     }
 1155:     if (@nopermissions) {
 1156:         if ($context eq 'course') {
 1157:             $output .= '<p>'.&mt('The following course/community creation requests could not be processed because the owner does not have rights to create this type of course:').'<ul>';
 1158:             foreach my $cnum (@nopermissions) {
 1159:                 my $showcourse;
 1160:                 if (ref($requesthash{$cnum.'_'.$queue})) {
 1161:                     $showcourse = $requesthash{$cnum.'_'.$queue}{'description'};
 1162:                 } else {
 1163:                     $showcourse = $cnum;
 1164:                 }
 1165:                 $output .= '<li>'.$showcourse.'</li>';
 1166:             }
 1167:             $output .= '</ul></p>';
 1168:         } elsif ($context eq 'requestauthor') {
 1169:             $output .= '<p>'.&mt('The following requests could not be processed because the requestor does not have rights to request an authoring space:').'<ul>';
 1170:             foreach my $uname (@nopermissions) {
 1171:                 my $userlink =
 1172:                     &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$cdom),$uname,$cdom);
 1173:                 $output .= '<li>'.$userlink.'</li>';
 1174:             }
 1175:             $output .= '</ul></p>';
 1176:         }
 1177:     }
 1178:     if (@processing_errors) {
 1179:         if ($context eq 'course') {
 1180:             $output .= '<p>'.&mt('The following enrollment requests could not be processed because an error occurred:').'<ul>';
 1181:             foreach my $user (@processing_errors) {
 1182:                 $output .= '<li>'.$user.'</li>';
 1183:             }
 1184:             $output .= '</ul></p>';
 1185:         } elsif ($context eq 'requestauthor') {
 1186:             $output .= '<p>'.&mt('The following requests could not be processed because an error occurred:').'<ul>';
 1187:             foreach my $uname (@processing_errors) {
 1188:                 my $userlink =
 1189:                     &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$cdom),$uname,$cdom);
 1190:                 $output .= '<li>'.$userlink.'</li>';
 1191:             }
 1192:             $output .= '</ul></p>';
 1193:         } else {
 1194:             $output .= '<p>'.&mt('The following course/community creation requests could not be processed because an error occurred:').'<ul>';
 1195:             foreach my $cnum (@processing_errors) {
 1196:                 my $showcourse;
 1197:                 if (ref($requesthash{$cnum.'_'.$queue})) {
 1198:                     $showcourse = $requesthash{$cnum.'_'.$queue}{'description'};
 1199:                 } else {
 1200:                     $showcourse = $cnum;
 1201:                 }
 1202:                 $output .= '<li>'.$showcourse.'</li>';
 1203:             }
 1204:             $output .= '</ul></p>';
 1205:         }
 1206:     }
 1207:     if (@rejectionerrors) {
 1208:         $output .= '<p>'.&mt('The following course/community creation request rejections could not be fully processed because an error occurred:').'<ul>';
 1209:         foreach my $cnum (@rejectionerrors) {
 1210:             my $showcourse;
 1211:             if (ref($requesthash{$cnum.'_'.$queue})) {
 1212:                 $showcourse = $requesthash{$cnum.'_'.$queue}{'description'};
 1213:             } else {
 1214:                 $showcourse = $cnum;
 1215:             }
 1216:             $output .= '<li>'.$showcourse.'</li>';
 1217:         }
 1218:         $output .= '</ul></p>';
 1219:     }
 1220:     if (@warn_approves || @warn_rejects) {
 1221:         if ($context eq 'course') {
 1222:             $output .= '<p>'.&mt("For the following users, an error occurred when updating the user's own self-enroll requests record:").'<ul>';
 1223:             foreach my $user (@warn_approves) {
 1224:                 $output .= '<li>'.$user.'</li>';
 1225:             }
 1226:             $output .= '</ul></p>';
 1227:         } elsif ($context eq 'requestauthor') {
 1228:             $output .= '<p>'.&mt("For the following users, an error occurred when updating the user's own author request record:").'<ul>';
 1229:             foreach my $uname (@warn_approves,@warn_rejects) {
 1230:                 my $userlink =
 1231:                     &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$cdom),$uname,$cdom);
 1232:                 $output .= '<li>'.$userlink.'</li>';
 1233:             }
 1234:             $output .= '</ul></p>';
 1235:         } else {
 1236:             $output .= '<p>'.&mt("For the following course/community requests an error occurred when updating the requestor's own requests record:").'<ul>';
 1237:             foreach my $cnum (@warn_approves,@warn_rejects) {
 1238:                 my $showcourse;
 1239:                 if (ref($requesthash{$cnum.'_'.$queue})) {
 1240:                     $showcourse = $requesthash{$cnum.'_'.$queue}{'description'};
 1241:                 } else {
 1242:                     $showcourse = $cnum;
 1243:                 }
 1244:                 $output .= '<li>'.$showcourse.'</li>';
 1245:             }
 1246:             $output .= '</ul></p>';
 1247:         }
 1248:     }
 1249:     if (@warn_dels) {
 1250:         if ($context eq 'requestauthor') {
 1251:             $output .= '<p>'.&mt("For the following requests an error occurred when removing the request from the queue:").'<ul>';
 1252:             foreach my $uname (@warn_dels) {
 1253:                 my $userlink =
 1254:                     &Apache::loncommon::aboutmewrapper(&Apache::loncommon::plainname($uname,$cdom),$uname,$cdom);
 1255:                 $output .= '<li>'.$userlink.'</li>';
 1256:             }
 1257:             $output .= '</ul></p>';
 1258:         } else {
 1259:             $output .= '<p>'.&mt("For the following course/community requests an error occurred when removing requests for the following from the pending queue:").'<ul>';
 1260:             foreach my $cnum (@warn_dels) {
 1261:                 my $showcourse;
 1262:                 if (ref($requesthash{$cnum.'_'.$queue})) {
 1263:                     $showcourse = $requesthash{$cnum.'_'.$queue}{'description'};
 1264:                 } else {
 1265:                     $showcourse = $cnum;
 1266:                 }
 1267:                 $output .= '<li>'.$showcourse.'</li>';
 1268:             }
 1269:             $output .= '</ul></p>';
 1270:         }
 1271:     }
 1272:     return $output;
 1273: }
 1274: 
 1275: sub course_portal_url {
 1276:     my ($cnum,$cdom) = @_;
 1277:     my $chome = &Apache::lonnet::homeserver($cnum,$cdom);
 1278:     my $hostname = &Apache::lonnet::hostname($chome);
 1279:     my $protocol = $Apache::lonnet::protocol{$chome};
 1280:     $protocol = 'http' if ($protocol ne 'https');
 1281:     my %domdefaults = &Apache::lonnet::get_domain_defaults($cdom);
 1282:     my $firsturl;
 1283:     if ($domdefaults{'portal_def'}) {
 1284:         $firsturl = $domdefaults{'portal_def'};
 1285:     } else {
 1286:         $firsturl = $protocol.'://'.$hostname;
 1287:     }
 1288:     return $firsturl;
 1289: }
 1290: 
 1291: sub get_student_counts {
 1292:     my ($cdom,$cnum) = @_;
 1293:     my (%idx,%stucounts);
 1294:     my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cnum);
 1295:     $idx{'type'} = &Apache::loncoursedata::CL_TYPE();
 1296:     $idx{'status'} = &Apache::loncoursedata::CL_STATUS();
 1297:     while (my ($student,$data) = each(%$classlist)) {
 1298:         if (($data->[$idx{'status'}] eq 'Active') ||
 1299:             ($data->[$idx{'status'}] eq 'Future')) {
 1300:             if ($data->[$idx{'type'}] eq 'selfenroll') {
 1301:                 $stucounts{'selfenroll'} ++;
 1302:             }
 1303:             $stucounts{'allstudents'} ++;
 1304:         }
 1305:     }
 1306:     return (\%stucounts,\%idx,$classlist);
 1307: }
 1308: 
 1309: sub course_creation {
 1310:     my ($dom,$cnum,$context,$details,$logmsg,$newusermsg,$addresult,$enrollcount,$output,
 1311:         $keysmsg,$domdefs,$longroles) =  @_;
 1312:     unless ((ref($details) eq 'HASH') && (ref($domdefs) eq 'HASH') && 
 1313:             (ref($longroles) eq 'HASH')) {
 1314:         return 'error: Invalid request';
 1315:     }
 1316:     my ($result,$ownername,$ownerdom);
 1317:     my $crstype = $details->{'crstype'};
 1318:     if ($context eq 'domain') {
 1319:         $ownername = $details->{'owner'};
 1320:         $ownerdom  = $details->{'domain'};
 1321:     } else {
 1322:         $ownername = $env{'user.name'};
 1323:         $ownerdom  = $env{'user.domain'};
 1324:     }
 1325:     my $owneremail;
 1326:     my %emails = &Apache::loncommon::getemails($ownername,$ownerdom);
 1327:     foreach my $email ('permanentemail','critnotification','notification') {
 1328:         $owneremail = $emails{$email};
 1329:         last if ($owneremail ne '');
 1330:     }
 1331:     my %reqdetails = &build_batchcreatehash($dom,$context,$details,$owneremail,$domdefs);
 1332:     my $cid = &LONCAPA::batchcreatecourse::build_course($dom,$cnum,'requestcourses',
 1333:                   \%reqdetails,$longroles,$logmsg,$newusermsg,$addresult,
 1334:                   $enrollcount,$output,$keysmsg,$ownerdom,$ownername,$cnum,$crstype);
 1335:     if ($cid eq "/$dom/$cnum") {
 1336:         $result = 'created';
 1337:     } else {
 1338:         $result = 'error: '.$cid;
 1339:     }
 1340:     return $result;
 1341: }
 1342: 
 1343: sub build_batchcreatehash {
 1344:     my ($dom,$context,$details,$owneremail,$domdefs) = @_;
 1345:     my %batchhash;
 1346:     my @items = qw{owner domain coursehome clonecrs clonedom datemode dateshift enrollstart enrollend accessstart accessend sections crosslists users};
 1347:     if ((ref($details) eq 'HASH') && (ref($domdefs) eq 'HASH')) {
 1348:         my $emailenc = &escape($owneremail);
 1349:         my $owner = $details->{'owner'}.':'.$details->{'domain'};
 1350:         foreach my $item (@items) {
 1351:             $batchhash{$item} = $details->{$item};
 1352:         }
 1353:         $batchhash{'title'} = $details->{'cdescr'};
 1354:         $batchhash{'coursecode'} = $details->{'instcode'};
 1355:         $batchhash{'emailenc'} = $emailenc;
 1356:         $batchhash{'adds'} = $details->{'autoadds'};
 1357:         $batchhash{'drops'} = $details->{'autodrops'};
 1358:         $batchhash{'authtype'} = $domdefs->{'auth_def'};
 1359:         $batchhash{'authparam'} = $domdefs->{'auth_arg_def'};
 1360:         if ($details->{'crstype'} eq 'community') {
 1361:             $batchhash{'crstype'} = 'Community';
 1362:         } else {
 1363:             $batchhash{'crstype'} = 'Course';
 1364:         }
 1365:         my ($owner_firstname,$owner_lastname);
 1366:         if ($context eq 'domain') {
 1367:             my %userenv = &Apache::lonnet::userenvironment($details->{'domain'},
 1368:                                                            $details->{'owner'},
 1369:                                                            'firstname','lastname');
 1370:             $owner_firstname = $userenv{'firstname'};
 1371:             $owner_lastname = $userenv{'lastname'};
 1372:         } else {
 1373:             $owner_firstname = $env{'environment.firstname'};
 1374:             $owner_lastname = $env{'environment.lastname'};
 1375:         }
 1376:         if (ref($details->{'personnel'}) eq 'HASH') {
 1377:             %{$batchhash{'users'}} = %{$details->{'personnel'}};
 1378:             if (ref($batchhash{'users'}) eq 'HASH') {  
 1379:                 foreach my $userkey (keys(%{$batchhash{'users'}})) {
 1380:                     if (ref($batchhash{'users'}{$userkey}) eq 'HASH') {
 1381:                         if (ref($batchhash{'users'}{$userkey}{'roles'}) eq 'ARRAY') {
 1382:                             foreach my $role (@{$batchhash{'users'}{$userkey}{'roles'}}) {
 1383:                                 my $start = '';
 1384:                                 my $end = '';
 1385:                                 if ($role eq 'st') {
 1386:                                     $start = $details->{'accessstart'};
 1387:                                     $end = $details->{'accessend'};
 1388:                                 }
 1389:                                 $batchhash{'users'}{$userkey}{$role}{'start'} = $start;
 1390:                                 $batchhash{'users'}{$userkey}{$role}{'end'} = $end;
 1391:                             } 
 1392:                         }
 1393:                     }
 1394:                 }
 1395:             }
 1396:         }
 1397:         $batchhash{'users'}{$owner}{firstname} = $owner_firstname;
 1398:         $batchhash{'users'}{$owner}{lastname} = $owner_lastname;
 1399:         $batchhash{'users'}{$owner}{emailenc} = $emailenc;
 1400:         $batchhash{'users'}{$owner}{owneremail} = $owneremail;
 1401:     }
 1402:     return %batchhash;
 1403: }
 1404: 
 1405: sub can_clone_course {
 1406:     my ($uname,$udom,$clonecrs,$clonedom,$crstype) = @_;
 1407:     my $canclone;
 1408:     my $ccrole = 'cc';
 1409:     if ($crstype eq 'community') {
 1410:         $ccrole = 'co';
 1411:     }
 1412:     my %roleshash = &Apache::lonnet::get_my_roles($uname,$udom,'userroles',['active'],
 1413:                                                   [$ccrole],[$clonedom]);
 1414:     if (exists($roleshash{$clonecrs.':'.$clonedom.':'.$ccrole})) {
 1415:         $canclone = 1;
 1416:     } else {
 1417:         my %courseenv = &Apache::lonnet::userenvironment($clonedom,$clonecrs,('cloners'));
 1418:         my $cloners = $courseenv{'cloners'};
 1419:         if ($cloners ne '') {
 1420:             my @cloneable = split(',',$cloners);
 1421:             if (grep(/^\*$/,@cloneable)) {
 1422:                 $canclone = 1;
 1423:             }
 1424:             if (grep(/^\*:\Q$udom\E$/,@cloneable)) {
 1425:                 $canclone = 1;
 1426:             }
 1427:             if (grep(/^\Q$uname\E:\Q$udom\E$/,@cloneable)) {
 1428:                 $canclone = 1;
 1429:             }
 1430:         }
 1431:         unless ($canclone) {
 1432:             if (&Apache::lonnet::is_course_owner($clonedom,$clonecrs,$uname,$udom)) {
 1433:                 $canclone = 1;
 1434:             }
 1435:         }
 1436:     }
 1437:     return $canclone;
 1438: }
 1439: 
 1440: sub get_processtype {
 1441:     my ($context,$uname,$udom,$isadv,$dom,$crstype,$inststatuses,$domconfig) = @_;
 1442:     return unless ((ref($inststatuses) eq 'ARRAY') && (ref($domconfig) eq 'HASH'));
 1443:     if ($uname eq '' || $udom eq '') {
 1444:         $uname = $env{'user.name'};
 1445:         $udom = $env{'user.domain'};
 1446:         $isadv = $env{'user.adv'};
 1447:     }
 1448:     my (%userenv,%settings,$val,@options,$envkey);
 1449:     if ($context eq 'course') {
 1450:         @options = ('autolimit','validate','approval');
 1451:         $envkey = 'requestcourses.'.$crstype;
 1452:         if (ref($domconfig->{'requestcourses'}) eq 'HASH') {
 1453:             if (ref($domconfig->{'requestcourses'}->{$crstype}) eq 'HASH') {
 1454:                 %settings = %{$domconfig->{'requestcourses'}->{$crstype}};
 1455:             }
 1456:         }
 1457:     } else {
 1458:         @options = ('automatic','approval');
 1459:         $envkey = 'requestauthor';
 1460:         if (ref($domconfig->{'requestauthor'}) eq 'HASH') { 
 1461:             %settings = %{$domconfig->{'requestauthor'}};
 1462:         }
 1463:     }
 1464:     if (($dom eq $udom) || ($context eq 'requestauthor')) {
 1465:         %userenv =
 1466:             &Apache::lonnet::userenvironment($udom,$uname,$envkey,'inststatus');
 1467:         if ($userenv{$envkey}) {
 1468:             $val = $userenv{$envkey};
 1469:             @{$inststatuses} = ('_custom_');
 1470:         } else {
 1471:             my %alltasks;
 1472:             if (($isadv) && ($settings{'_LC_adv'} ne '')) {
 1473:                 $val = $settings{'_LC_adv'};
 1474:                 @{$inststatuses} = ('_LC_adv_');
 1475:             } else {
 1476:                 if ($userenv{'inststatus'} ne '') {
 1477:                     @{$inststatuses} = split(',',$userenv{'inststatus'});
 1478:                 } else {
 1479:                     @{$inststatuses} = ('default');
 1480:                 }
 1481:                 foreach my $status (@{$inststatuses}) {
 1482:                     if (exists($settings{$status})) {
 1483:                         my $value = $settings{$status};
 1484:                         next unless ($value);
 1485:                         unless (exists($alltasks{$value})) {
 1486:                             if (ref($alltasks{$value}) eq 'ARRAY') {
 1487:                                 unless(grep(/^\Q$status\E$/,@{$alltasks{$value}})) {
 1488:                                     push(@{$alltasks{$value}},$status);
 1489:                                 }
 1490:                             } else {
 1491:                                 @{$alltasks{$value}} = ($status);
 1492:                             }
 1493:                         }
 1494:                     }
 1495:                 }
 1496:                 my $maxlimit = 0;
 1497:                 if ($context eq 'course') {
 1498:                     foreach my $key (sort(keys(%alltasks))) {
 1499:                         if ($key =~ /^autolimit=(\d*)$/) {
 1500:                             if ($1 eq '') {
 1501:                                 $val ='autolimit=';
 1502:                                 last;
 1503:                             } elsif ($1 > $maxlimit) {
 1504:                                 $maxlimit = $1;
 1505:                             }
 1506:                         }
 1507:                     }
 1508:                 }
 1509:                 if (($context eq 'requestauthor') || (!$val)) {
 1510:                     if ($context eq 'course' && $maxlimit) {
 1511:                         $val = 'autolimit='.$maxlimit;
 1512:                     } else {
 1513:                         foreach my $option (@options) {
 1514:                             if ($alltasks{$option}) {
 1515:                                 $val = $option;
 1516:                                 last;
 1517:                             }
 1518:                         }
 1519:                     }
 1520:                 }
 1521:             }
 1522:         }
 1523:     } else {
 1524:         %userenv = &Apache::lonnet::userenvironment($udom,$uname,'reqcrsotherdom.'.$crstype);
 1525:         if ($userenv{'reqcrsotherdom.'.$crstype}) {
 1526:             my @doms = split(',',$userenv{'reqcrsotherdom.'.$crstype});
 1527:             my $optregex = join('|',@options);
 1528:             foreach my $item (@doms) {
 1529:                 my ($extdom,$extopt) = split(':',$item);
 1530:                 if ($extdom eq $dom) {
 1531:                     if ($extopt =~ /^($optregex)(=?\d*)$/) {
 1532:                         $val = $1.$2;
 1533:                     }
 1534:                     last;
 1535:                 }
 1536:             }
 1537:             @{$inststatuses} = ('_external_');
 1538:         }
 1539:     }
 1540:     return $val;
 1541: }
 1542: 
 1543: sub queued_selfenrollment {
 1544:     my ($notitle) = @_;
 1545:     my $output;
 1546:     my %selfenrollrequests = &Apache::lonnet::dump('selfenrollrequests');
 1547:     my %reqs_by_date;
 1548:     foreach my $item (keys(%selfenrollrequests)) {
 1549:         if (ref($selfenrollrequests{$item}) eq 'HASH') {
 1550:             if ($selfenrollrequests{$item}{'status'} eq 'request') {
 1551:                 if ($selfenrollrequests{$item}{'timestamp'}) {
 1552:                     push(@{$reqs_by_date{$selfenrollrequests{$item}{'timestamp'}}},$item);
 1553:                 }
 1554:             }
 1555:         }
 1556:     }
 1557:     if (keys(%reqs_by_date)) {
 1558:         unless ($notitle) {
 1559:             $output .= '<br /><b>'.&mt('Enrollment requests pending Course Coordinator approval').'</b><br />';
 1560:         }
 1561:         $output .= &Apache::loncommon::start_data_table().
 1562:                    &Apache::loncommon::start_data_table_header_row().
 1563:                    '<th>'.&mt('Date requested').'</th><th>'.&mt('Course title').'</th>'.
 1564:                    '<th>'.&mt('User role').'</th><th>'.&mt('Section').'</th>'.
 1565:                    &Apache::loncommon::end_data_table_header_row();
 1566:         my @sorted = sort { $a <=> $b } (keys(%reqs_by_date));
 1567:         foreach my $item (@sorted) {
 1568:             if (ref($reqs_by_date{$item}) eq 'ARRAY') {
 1569:                 foreach my $crs (@{$reqs_by_date{$item}}) {
 1570:                     my %courseinfo = &Apache::lonnet::coursedescription($crs);
 1571:                     my $usec = $selfenrollrequests{$crs}{'section'};
 1572:                     my $rolename = &Apache::lonnet::plaintext('st',$courseinfo{'type'},$crs);
 1573:                     if ($usec eq '') {
 1574:                         $usec = &mt('No section');
 1575:                     }
 1576:                     $output .= &Apache::loncommon::start_data_table_row().
 1577:                                '<td>'.&Apache::lonlocal::locallocaltime($item).'</td>'.
 1578:                                '<td>'.$courseinfo{'description'}.'</td>'.
 1579:                                '<td>'.$rolename.'</td><td>'.$usec.'</td>'.
 1580:                                &Apache::loncommon::end_data_table_row();
 1581:                 }
 1582:             }
 1583:         }
 1584:         $output .= &Apache::loncommon::end_data_table();
 1585:     }
 1586:     return $output;
 1587: }
 1588: 
 1589: sub update_coursereq_status {
 1590:     my ($reqhash,$dom,$cnum,$reqstatus,$context,$udom,$uname) = @_;
 1591:     my ($storeresult,$statusresult,$output);
 1592:     my $requestkey = $dom.'_'.$cnum;
 1593:     if ($requestkey =~ /^($match_domain)_($match_courseid)$/) {
 1594:         $storeresult = &Apache::lonnet::store_userdata($reqhash,$requestkey,
 1595:                                                        'courserequests',$udom,$uname);
 1596:         if ($storeresult eq 'ok') {
 1597:             my %status = (
 1598:                              'status:'.$dom.':'.$cnum => $reqstatus,
 1599:                          );
 1600:             $statusresult = &Apache::lonnet::put('courserequests',\%status,$udom,$uname);
 1601:         }
 1602:     } else {
 1603:         $storeresult = 'error: invalid requestkey format';
 1604:     }
 1605:     if ($storeresult ne 'ok') {
 1606:         $output = &mt('An error occurred saving a record of the details of your request: [_1].',$storeresult);
 1607:         if ($context eq 'domain') {
 1608:             $output .= "\n";  
 1609:         } else {
 1610:             $output =  '<span class="LC_warning">'.$output.'</span><br />';
 1611:         }
 1612:         &Apache::lonnet::logthis("Error saving course request - $requestkey for $uname:$udom - $storeresult");
 1613:     } elsif ($statusresult ne 'ok') {
 1614:         $output = &mt('An error occurred saving a record of the status of your request: [_1].',$statusresult);
 1615:         if ($context eq 'domain') {
 1616:             $output .= "\n";
 1617:         } else {
 1618:             $output = '<span class="LC_warning">'.$output.'</span><br />';
 1619:         }
 1620:         &Apache::lonnet::logthis("Error saving course request status for $requestkey (for $uname:$udom) - $statusresult");
 1621:     }
 1622:     return ($storeresult,$output);
 1623: }
 1624: 
 1625: sub process_official_reqs {
 1626:     my ($context,$dom,$dcname,$dcdom) = @_;
 1627:     my $reqsnamespace = 'courserequestqueue';
 1628:     my %requesthash =
 1629:         &Apache::lonnet::dump_dom($reqsnamespace,$dom,'_pending');
 1630:     my (%newcids,%longroles,%stillpending);
 1631:     my @courseroles = ('cc','in','ta','ep','ad','st');
 1632:     foreach my $role (@courseroles) {
 1633:         $longroles{$role}=&Apache::lonnet::plaintext($role);
 1634:     }
 1635:     my %domdefs = &Apache::lonnet::get_domain_defaults($dom);
 1636:     my ($output,$linefeed);
 1637:     if ($context eq 'auto') {
 1638:         $linefeed = "\n";
 1639:     } else {
 1640:         $linefeed = '<br />'."\n";
 1641:     }
 1642:     foreach my $key (keys(%requesthash)) {
 1643:         my ($cnum,$status) = split('_',$key);
 1644:         next if (&Apache::lonnet::homeserver($cnum,$dom) ne 'no_host');
 1645:         if (ref($requesthash{$key}) eq 'HASH') {
 1646:             my $ownername = $requesthash{$key}{'ownername'};
 1647:             my $ownerdom = $requesthash{$key}{'ownerdom'};
 1648:             next if (&Apache::lonnet::homeserver($ownername,$ownerdom) eq 'no_host');
 1649:             my $inststatus;
 1650:             my %userenv =
 1651:                 &Apache::lonnet::get('environment',['inststatus'],
 1652:                                      $ownerdom,$ownername);
 1653:             my ($tmp) = keys(%userenv);
 1654:             if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 1655:                 $inststatus = $userenv{'inststatus'};
 1656:             } else {
 1657:                 undef(%userenv);
 1658:             }
 1659:             my $reqkey = $dom.'_'.$cnum;
 1660:             my %history = &Apache::lonnet::restore($reqkey,'courserequests',
 1661:                                                    $ownerdom,$ownername);
 1662:             if (ref($history{'details'}) eq 'HASH') {
 1663:                 my $instcode = $history{'details'}{'instcode'};
 1664:                 my $crstype = $history{'details'}{'crstype'};
 1665:                 my $reqtime = $history{'details'}{'reqtime'};
 1666:                 my $cdescr = $history{'details'}{'cdescr'};
 1667:                 my @currsec;
 1668:                 my $sections = $history{'details'}{'sections'};
 1669:                 if (ref($sections) eq 'HASH') {
 1670:                     foreach my $i (sort(keys(%{$sections}))) {
 1671:                         if (ref($sections->{$i}) eq 'HASH') {
 1672:                             my $sec = $sections->{$i}{'inst'};
 1673:                             if (!grep(/^\Q$sec\E$/,@currsec)) {
 1674:                                 push(@currsec,$sec);
 1675:                             }
 1676:                         }
 1677:                     }
 1678:                 }
 1679:                 my $instseclist = join(',',@currsec);
 1680:                 my ($validationchk,$disposition,$reqstatus,$message,
 1681:                     $validation,$validationerror);
 1682:                 $validationchk =
 1683:                     &Apache::lonnet::auto_courserequest_validation($dom,
 1684:                         $ownername.':'.$ownerdom,$crstype,$inststatus,
 1685:                         $instcode,$instseclist);
 1686:                 if ($validationchk =~ /:/) {
 1687:                     ($validation,$message) = split(':',$validationchk);
 1688:                 } else {
 1689:                     $validation = $validationchk;
 1690:                 }
 1691:                 if ($validation =~ /^error(.*)$/) {
 1692:                     $disposition = 'approval';
 1693:                     $validationerror = $1;
 1694:                 } else {
 1695:                     $disposition = $validation;
 1696:                 }
 1697:                 $reqstatus = $disposition;
 1698:                 if ($disposition eq 'process') {
 1699:                     my ($logmsg,$newusermsg,$addresult,$enrollcount,$response,$keysmsg);
 1700:                     my $result = &course_creation($dom,$cnum,'domain',$history{'details'},\$logmsg,\$newusermsg,\$addresult,\$enrollcount,\$response,\$keysmsg,\%domdefs,\%longroles);
 1701:                     if ($result eq 'created') {
 1702:                         $disposition = 'created';
 1703:                         $reqstatus = 'created';
 1704:                         my $cid = $dom.'_'.$cnum;
 1705:                         push(@{$newcids{$instcode}},$cid);
 1706:                         if ($dcname && $dcdom) {
 1707:                             my $firsturl = &course_portal_url($cnum,$dom);
 1708:                             my $beneficiary = 'pendingrequestor';
 1709:                             my $now = time;
 1710:                             my $owner = $ownername.':'.$ownerdom;
 1711:                             my $approvedmsg =
 1712:                                 [{
 1713:                                     mt => 'Your requested course: [_1], (queued pending validation) has now been created.',
 1714:                                     args => [$cdescr],
 1715:                                  },
 1716:                                  {
 1717:                                     mt   => 'Visit [_1] to log-in and access the course.',
 1718:                                     args => [$firsturl],
 1719:                                  },
 1720:                                  {
 1721:                                     mt => 'If currently logged-in to LON-CAPA, log-out and log-in again to select your new course role.'
 1722:                                  }];
 1723:                             my $sender = $dcname.':'.$dcdom;
 1724:                             &send_selfserve_notification($owner,$approvedmsg,
 1725:                                                          $cid,$cdescr,$now,
 1726:                                                          $beneficiary,$sender,
 1727:                                                          undef,undef,$crstype);
 1728:                         }
 1729:                     }
 1730:                 } elsif ($disposition eq 'rejected') {
 1731:                     $output .= &mt('Queued course request for [_1] submitted by [_2] with status [_3] rejected when validating.',$instcode,$ownername.':'.$ownerdom,$inststatus).$linefeed;
 1732:                 } elsif ($disposition eq 'approval') {
 1733:                     $output .= &mt('Queued course request for [_1] submitted by [_2] with status [_3] switched to "approval by DC" because of validation error: [_4].',$instcode,$ownername.':'.$ownerdom,$inststatus,$validationerror).$linefeed;
 1734: 
 1735:                     my $requestid = $cnum.'_'.$disposition;
 1736:                     my $request = {
 1737:                             $requestid => {
 1738:                                             timestamp   => $reqtime,
 1739:                                             crstype     => $crstype,
 1740:                                             ownername   => $ownername,
 1741:                                             ownerdom    => $ownerdom,
 1742:                                             description => $cdescr,
 1743:                                           },
 1744:                           };
 1745:                     my $putresult = &Apache::lonnet::newput_dom('courserequestqueue',$request,$dom);
 1746:                     unless ($putresult eq 'ok') {
 1747:                         $output .= &mt("An error occurred saving the modified course request for [_1] submitted by [_2] in the domain's courserequestqueue.db.",$instcode,$ownername.':'.$ownerdom).$linefeed;
 1748:                     }
 1749:                 } elsif ($disposition eq 'pending') {
 1750:                     my $instcode = $requesthash{$key}{'instcode'};
 1751:                     my $description = $requesthash{$key}{'description'};
 1752:                     my $timestamp = $requesthash{$key}{'timestamp'};
 1753:                     my $entry = $cnum.':'.$ownername.':'.$ownerdom.':'.
 1754:                                 $instcode.':'.$description;
 1755:                     if (ref($stillpending{$timestamp}) eq 'ARRAY') {
 1756:                         push(@{$stillpending{$timestamp}},$entry);
 1757:                     } else {
 1758:                         $stillpending{$timestamp} = [$entry];
 1759:                     }
 1760:                 }
 1761:                 unless ($disposition eq 'pending') {
 1762:                     my ($statusresult,$output) =
 1763:                         &update_coursereq_status(\%requesthash,$dom,$cnum,
 1764:                                                  $reqstatus,'domain',$ownerdom,
 1765:                                                  $ownername);
 1766:                     unless (&Apache::lonnet::del_dom($reqsnamespace,[$cnum.'_pending'],$dom) eq 'ok') {
 1767:                         $output .= &mt('An error occurred when removing the request for [_1] submitted by [_2] from the pending queue.',$instcode,$ownername.':'.$ownerdom).$linefeed;
 1768:                     }
 1769:                 }
 1770:             }
 1771:         }
 1772:     }
 1773:     foreach my $key (sort(keys(%newcids))) {
 1774:         if (ref($newcids{$key}) eq 'ARRAY') {
 1775:             $output .= "created course from queued request: $key - ".join(', ',@{$newcids{$key}}).$linefeed;
 1776:             my $newcourse = &LONCAPA::escape($key.':'.$newcids{$key});
 1777:         }
 1778:     }
 1779:     unless ($context eq 'auto') {
 1780:         if (keys(%stillpending) > 0) {
 1781:             $output .= '<form method="post" name="changequeue" action="/adm/createcourse" />'."\n".
 1782:                        '<input type="hidden" name="action" value="'.$env{'form.action'}.'" />'."\n".
 1783:                        '<input type="hidden" name="phase" value="requestchange" />'.
 1784:                        '<p>'.&mt('For the following requests, the requestor could [_1]not[_2] be validated as official course personnel, so the request remains in the pending queue.','<b>','</b>').'<br />'.&mt('Requests may be left in the queue, or you can manually approve or reject them.').'</p>'.
 1785:                        &build_queue_display($dom,'stillpending',\%stillpending).
 1786:                        '<br /><input type="hidden" name="queue" value="pending" />'."\n".
 1787:                        '<input type="submit" name="processqueue" value="'.&mt('Save').'" />'.
 1788:                        '</form>';
 1789:         }
 1790:     }
 1791:     return $output;
 1792: }
 1793: 
 1794: sub is_active_author {
 1795:     if ($env{'user.role.au./'.$env{'user.domain'}.'/'} =~ /^(\d*)\.(\d*)$/) {
 1796:         if ((!$1 || $1 < time) &&
 1797:             (!$2 || $2 > time)) {
 1798:             return 1;
 1799:         }
 1800:     }
 1801: }
 1802: 
 1803: sub author_prompt {
 1804:     my ($is_active_author,$offer_author);
 1805:     if ($env{'environment.canrequest.author'}) {
 1806:         unless (&is_active_author()) {
 1807:             unless (&reqauthor_check() =~ /^approval:\d+$/) {
 1808:                 $offer_author = 1;
 1809:             }
 1810:         }
 1811:     }
 1812:     return $offer_author;
 1813: }
 1814: 
 1815: sub reqauthor_check {
 1816:     my $queued = $env{'environment.requestauthorqueued'};
 1817:     my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
 1818:                                          $env{'user.domain'},$env{'user.name'});
 1819:     my $reqstatus = $reqauthor{'author_status'};
 1820:     if (($reqstatus eq '' && $queued ne '') ||
 1821:         ($env{'environment.requestauthorqueued'} !~ /^\Q$reqstatus\E/)) {
 1822:         if (ref($reqauthor{'author'}) eq 'HASH') {
 1823:             $queued = $reqstatus.':'.$reqauthor{'author'}{'timestamp'};
 1824:         } else {
 1825:             undef($queued);
 1826:         }
 1827:         &Apache::lonnet::appenv({'environment.requestauthorqueued' => $queued});
 1828:     }
 1829:     return $queued;
 1830: }
 1831: 
 1832: sub process_reqauthor {
 1833:     my ($dispositionref,$updateref) = @_;
 1834:     if (&is_active_author()) {
 1835:         return '<span class="LC_warning">'.
 1836:                 &mt('An authoring space has already been assigned to you.').'<br />'.
 1837:                 &mt('Please select the Author role from your [_1]roles page[_2].','<a href="/adm/roles">',
 1838:                 '</a>').'</span>';
 1839:     }
 1840:     unless ($env{'environment.canrequest.author'}) {
 1841:         return '<span class="LC_warning">'.
 1842:                 &mt('You do not currently have rights to request an authoring space.').'<br />'.
 1843:                 &mt('Please contact the [_1]helpdesk[_2].','<a href="/adm/helpdesk">',
 1844:                 '</a>').'</span>';
 1845:     }
 1846:     my $queued = &reqauthor_check();
 1847:     if ($queued =~ /^approval:(\d+)$/) {
 1848:         my $timestamp = $1;
 1849:         return '<span class="LC_info">'.
 1850:                &mt('A request for authoring space submitted on [_1] is awaiting approval',
 1851:                &Apache::lonlocal::locallocaltime($timestamp)).
 1852:                '</span>';
 1853:     } elsif ($queued =~ /^approved:(\d+)$/) {
 1854:         my $timestamp = $1;   
 1855:         my %roleshash = &Apache::lonnet::get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',
 1856:                                                       ['active'],['au'],[$env{'user.domain'}]);
 1857:         if (keys(%roleshash) > 0) {
 1858:             return '<span class="LC_info">'.
 1859:                    &mt('A request for authoring space submitted on [_1] has been approved.',
 1860:                    &Apache::lonlocal::locallocaltime($timestamp)).
 1861:                    '</span>';
 1862:         }
 1863:     }
 1864:     my ($output,@inststatuses,%domconfig);
 1865:     %domconfig = &Apache::lonnet::get_dom('configuration',['requestauthor'],
 1866:                                           $env{'user.domain'});
 1867:     my $val = &get_processtype('requestauthor',$env{'user.name'},$env{'user.domain'},
 1868:                                $env{'user.adv'},$env{'user.domain'},undef,
 1869:                                \@inststatuses,\%domconfig);
 1870:     my $now = time;
 1871:     if ($val eq 'automatic') {
 1872:         my $start = $now-1;
 1873:         if (&Apache::lonnet::assignrole($env{'user.domain'},$env{'user.name'},'/'.$env{'user.domain'}.'/',
 1874:                                         'au',undef,$start,undef,undef,'requestauthor') eq 'ok') {
 1875:             $output = '<span class="LC_info">'.
 1876:                       &mt('Access to authoring space has been activated').'</span><br />';
 1877:                       &Apache::lonroles::update_session_roles();
 1878:             &Apache::lonnet::appenv({'user.update.time'  => $now});
 1879:             if (ref($updateref)) {
 1880:                 $$updateref = $now;
 1881:             }
 1882:             if (ref($dispositionref)) {
 1883:                 $$dispositionref = 'created';
 1884:             }
 1885:         } else {
 1886:             $output = '<span class="LC_info">'.
 1887:                       &mt('An error occurred while activating your access to authoring space');
 1888:         }
 1889:     } elsif ($val eq 'approval') {
 1890:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($env{'user.domain'});
 1891:         if (&Apache::lonnet::put('requestauthorqueue',{ $env{'user.name'}.'_'.$val => $now },
 1892:                                  $env{'user.domain'},$domconfiguser) eq 'ok') {
 1893:             my %userrequest = (
 1894:                 author => {
 1895:                             timestamp   => $now,
 1896:                             status      => $val,
 1897:                           },
 1898:                 author_status => $val,
 1899:             );
 1900:             my $req_notifylist;
 1901:             if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 1902:                 if (ref($domconfig{'requestauthor'}{'notify'}) eq 'HASH') {
 1903:                     my $req_notifylist = $domconfig{'requestauthor'}{'notify'}{'approval'};
 1904:                     if ($req_notifylist) {
 1905:                         my $fullname = &Apache::loncommon::plainname($env{'user.name'},
 1906:                                                                      $env{'user.domain'});
 1907:                         my $sender = $env{'user.name'}.':'.$env{'user.domain'};
 1908:                         my $domdesc = &Apache::lonnet::domain($env{'user.domain'},'description');
 1909:                         &send_selfserve_notification($req_notifylist,
 1910:                                                      "$fullname ($env{'user.name'}:$env{'user.domain'})",
 1911:                                                      undef,$domdesc,$now,'authorreq',$sender);
 1912:                     }
 1913:                 }
 1914:             }
 1915:             my $userresult =
 1916:                 &Apache::lonnet::put('requestauthor',\%userrequest,$env{'user.domain'},$env{'user.name'});
 1917:             $output = '<span class="LC_info">'.
 1918:                       &mt('Your request for authoring space has been submitted for approval.').
 1919:                       '</span>';
 1920:             &Apache::lonnet::appenv({'environment.requestauthorqueued' => $val.':'.$now});
 1921:         } else {
 1922:             $output = '<span class="LC_info">'.
 1923:                       &mt('An error occurred saving your request for authoring space.').
 1924:                       '</span>';
 1925:         }
 1926:     }
 1927:     return $output;
 1928: }
 1929: 
 1930: 1;

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