File:  [LON-CAPA] / loncom / interface / loncoursequeueadmin.pm
Revision 1.50: download - view: text, annotated - select for diffs
Thu Mar 26 14:16:11 2015 UTC (9 years, 1 month ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- If cloning, include courseID of course being cloned in information sent
  sent to localenroll::validate_crsreq() and locallenroll::crsreq_updates()
  (key is _LC_clonefrom) in $custominfo and $incoming hashrefs respectively.

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

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