File:  [LON-CAPA] / loncom / interface / loncoursequeueadmin.pm
Revision 1.43: download - view: text, annotated - select for diffs
Wed Feb 12 20:47:40 2014 UTC (10 years, 3 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6646
  - Self-creation of user accounts with e-mail address as username.
  - User information and password requested from prospective user in a single
    web form.
  - Add routines to handle creation of user accounts and notification
    following approval by Domain Coordinator.

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

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