Annotation of loncom/interface/selfenroll.pm, revision 1.15

1.1       raeburn     1: # The LearningOnline Network
                      2: # Allow users to self-enroll in a course
                      3: #
1.15    ! raeburn     4: # $Id: selfenroll.pm,v 1.14 2008/07/30 16:25:35 raeburn Exp $
1.1       raeburn     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: package Apache::selfenroll;
                     30: 
                     31: use strict;
                     32: use Apache::Constants qw(:common);
                     33: use Apache::lonnet;
                     34: use Apache::loncommon;
                     35: use Apache::lonlocal;
1.10      raeburn    36: use Apache::createaccount;
1.1       raeburn    37: use LONCAPA qw(:DEFAULT :match);
                     38: 
                     39: sub handler {
                     40:     my $r = shift;
                     41:     &Apache::loncommon::content_type($r,'text/html');
                     42:     $r->send_http_header;
                     43:     if ($r->header_only) {
                     44:         return OK;
                     45:     }
                     46:     my $handle = &Apache::lonnet::check_for_valid_session($r);
                     47:     my $lonidsdir=$r->dir_config('lonIDsDir');
1.10      raeburn    48:     my $lonhost = $r->dir_config('lonHostID');
1.1       raeburn    49:     if ($handle ne '') {
                     50:         &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle);
                     51:     }
                     52:     &Apache::lonacc::get_posted_cgi($r);
                     53:     &Apache::lonlocal::get_language_handle($r);
1.12      raeburn    54:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['courseid']);
                     55:     my $js = &Apache::createaccount::catreturn_js();
                     56:     my ($coursechk,$courseid) = &validate_course_id($env{'form.courseid'});
1.1       raeburn    57:     if ($coursechk ne 'ok') {
1.12      raeburn    58:         &page_header($r,$courseid,$js);
1.9       raeburn    59:         $r->print('<h3>'.&mt('Self-enrollment error').'</h3>'.
1.10      raeburn    60:                   '<span class="LC_error">'.
                     61:                   &mt('Invalid domain or course number').'</span>');
1.12      raeburn    62:         &page_footer($r);
1.1       raeburn    63:         return OK;
                     64:     }
1.10      raeburn    65:     my $now = time;
                     66:     if ($env{'form.phase'} eq 'login') {
1.12      raeburn    67:         $js .= "\n".&Apache::createaccount::javascript_setforms($now);
1.10      raeburn    68:     }
1.12      raeburn    69:     my %coursehash = &Apache::lonnet::coursedescription($courseid);
                     70:     my $cdom = $coursehash{'domain'};
                     71:     my $cnum = $coursehash{'num'};
                     72:     my $desc = $coursehash{'description'};
                     73:     &page_header($r,$courseid,$js,$desc);
1.10      raeburn    74:     my $include = $r->dir_config('lonIncludes');
                     75:     if ($env{'form.phase'} eq 'login') {
                     76:         my $jsh=Apache::File->new($include."/londes.js");
                     77:         $r->print(<$jsh>);
                     78:     }
1.12      raeburn    79:     my ($canenroll,$selfenroll_types,$selfenroll_registered,@cancreate,
                     80:         $knownuser,$selfenroll_access_start,$selfenroll_access_end,
1.15    ! raeburn    81:         $selfenroll_section,$selfenroll_future,%curr_role,$cdomdesc,
        !            82:         $selfenroll_approval,$selfenroll_limit,$selfenroll_cap,
        !            83:         $selfenroll_notifylist,$owner);
1.1       raeburn    84:     $selfenroll_types = $coursehash{'internal.selfenroll_types'};
                     85:     $selfenroll_registered =  $coursehash{'internal.selfenroll_registered'};
                     86:     $selfenroll_section = $coursehash{'internal.selfenroll_section'};
                     87:     $selfenroll_access_start =  $coursehash{'internal.selfenroll_start_access'};
                     88:     $selfenroll_access_end =  $coursehash{'internal.selfenroll_end_access'};
1.15    ! raeburn    89:     $selfenroll_limit =  $coursehash{'internal.selfenroll_limit'};
        !            90:     $selfenroll_cap = $coursehash{'internal.selfenroll_cap'};
        !            91:     $selfenroll_approval = $coursehash{'internal.selfenroll_approval'};
        !            92:     $selfenroll_notifylist = $coursehash{'internal.selfenroll_notifylist'};
        !            93:     $owner = $coursehash{'internal.courseowner'};
        !            94:     my $nospace;
1.1       raeburn    95:     if ($selfenroll_types ne '') {
                     96:         my $start = $coursehash{'internal.selfenroll_start_date'};
                     97:         my $end = $coursehash{'internal.selfenroll_end_date'};
1.9       raeburn    98:         if (($start > 0 && $start < $now) && (($end == 0) || ($end > 0 && $end > $now))) {
1.15    ! raeburn    99:             if (($selfenroll_limit eq 'allstudents') || 
        !           100:                 ($selfenroll_limit eq 'selfenroll')) {
        !           101:                 $nospace = 
        !           102:                     &enrollment_limit_check($selfenroll_limit,$selfenroll_cap,
        !           103:                                             $cdom,$cnum);
        !           104:                 if (!$nospace) {
        !           105:                     $canenroll = 1; 
        !           106:                 }
        !           107:             } else {
        !           108:                 $canenroll = 1;
        !           109:             }
1.9       raeburn   110:         } elsif (($end == 0) || ($end > 0 && $end > $now)) {
                    111:             if ($start > $now) {
1.15    ! raeburn   112:                 if (($selfenroll_limit eq 'allstudents') ||
        !           113:                     ($selfenroll_limit eq 'selfenroll')) {
        !           114:                     $nospace = 
        !           115:                         &enrollment_limit_check($selfenroll_limit,$cdom,$cnum);
        !           116:                 }
        !           117:                 if (!$nospace) {
        !           118:                     $selfenroll_future = &Apache::lonlocal::locallocaltime($start);
        !           119:                 }
1.9       raeburn   120:             }
1.1       raeburn   121:         }
                    122:     }
1.9       raeburn   123:     $knownuser = &user_is_known();
1.1       raeburn   124:     if (!$canenroll) {
1.9       raeburn   125:         $r->print('<h3>'.&mt('Self-enrollment unavailable').'</h3><span class="LC_warning">'.
                    126:                   &mt('Self-enrollment is not currently available for this course.').
                    127:                   '</span><br /><br />');
1.15    ! raeburn   128:         if ($nospace) {
        !           129:             if ($selfenroll_limit eq 'allstudents') {
        !           130:                 $r->print(&mt('The enrollment limit of [quant,_1,student] has been reached.',$selfenroll_cap));
        !           131:             } else {
        !           132:                 $r->print(&mt('The enrollment limit of [quant,_1,self-enrolled student] has been reached.',$selfenroll_cap));
        !           133: 
        !           134:             }
        !           135:         } 
1.9       raeburn   136:         if ($selfenroll_types ne '') {
                    137:             if ($selfenroll_future ne '') {
                    138:                 if ($selfenroll_types eq '*') {
                    139:                     $r->print(&mt('Self-enrollment will become available starting [_1], and will be available to all LON-CAPA users.',$selfenroll_future).'<br />');
                    140:                 } else {
                    141:                     my ($enrolltypes,$longtypes,$alldoms);
                    142:                     if ($knownuser) {
                    143:                         &get_selfenroll_filters($selfenroll_types,$env{'user.domain'});
                    144:                         my $domdesc = &Apache::lonnet::domain($env{'user.domain'},'description');
                    145:                         if (ref($enrolltypes) eq 'HASH') {
                    146:                             if (ref($enrolltypes->{$env{'user.domain'}}) eq 'ARRAY') {
                    147:                                 if (grep(/^any$/,@{$enrolltypes->{$env{'user.domain'}}})) {
                    148:                                     $r->print(&mt('Self-enrollment will become available starting [_1], and will be available to all LON-CAPA users at your institution ([_2]).',
                    149:                                               $selfenroll_future,$domdesc).'<br />');
                    150: 
                    151:                                 } else {
                    152:                                     if (&user_can_selfenroll($env{'user.domain'},
                    153:                                                         $env{'user.name'},
                    154:                                                         $enrolltypes->{$env{'user.domain'}})) {
                    155:                                         $r->print(&mt('Self-enrollment will become available starting [_1]; please enroll at that time.',$selfenroll_future)); 
                    156:                                     } else {
                    157:                                         $r->print(&mt('Although self-enrollment will become available starting [_1], you are ineligible for enrollment.',$selfenroll_future).'<br />');
                    158:                                         $r->print(&print_selfenroll_types($longtypes,$env{'user.domain'}));
                    159:                                     }
                    160:                                 }
                    161:                             }
                    162:                         } 
                    163:                     } else {
                    164:                         $r->print(&mt('Self-enrollment will become available starting [_1].',
                    165:                                       $selfenroll_future).'<br />');
                    166:                         $r->print(&print_selfenroll_types($longtypes));
                    167:                     }
                    168:                 }
                    169:             } 
                    170:         }
1.1       raeburn   171:     }
                    172:     if ($knownuser) {
                    173:         foreach my $key (keys(%env)) {
                    174:             if ($key =~ m-^user\.role\.st\./$cdom/$cnum/?(\w*)$-) {
                    175:                 my $sec = $1;
                    176:                 my ($start,$end) = split(/\./,$env{$key});
                    177:                 my $status = 'active';
                    178:                 if (($end) && ($end<=$now)) {
                    179:                     $status = 'previous';
                    180:                 }
                    181:                 if (($start) && ($now<$start)) {
                    182:                     $status = 'future';
                    183:                 }
                    184:                 if ($status eq 'active' || $status eq 'future') {
                    185:                      $curr_role{'status'} = $status;
                    186:                      $curr_role{'section'} = $sec;
1.7       raeburn   187:                      if ($curr_role{'section'} eq '') {
                    188:                          $curr_role{'section'} = &mt('none'); 
                    189:                      }
1.1       raeburn   190:                      $curr_role{'start'} = &Apache::lonlocal::locallocaltime($start);
                    191:                      $curr_role{'role'} = 'st./'.$cdom.'/'.$cnum;
                    192:                      if ($sec ne '') {
                    193:                          $curr_role{'role'} .= '/'.$sec; 
                    194:                      }
                    195:                 }
                    196:             }
                    197:         }
                    198:     }
                    199:     if (!$canenroll) {
                    200:         if (keys(%curr_role)) {
                    201:             $r->print(&has_role(%curr_role));
                    202:         }
1.12      raeburn   203:         &page_footer($r);
1.1       raeburn   204:         return OK;
                    205:     }
1.3       raeburn   206:     @cancreate = &can_create($cdom);
1.12      raeburn   207:     my ($form,$login_path,$firsturl,$create_path,$sso_url,$missing_formitem);
                    208:     $form = 'logmein';
1.1       raeburn   209:     $login_path = '/adm/login';
1.12      raeburn   210:     $firsturl= '/adm/selfenroll?courseid='.$courseid;
1.1       raeburn   211:     $create_path = '/adm/createaccount';
                    212:     $sso_url = $r->dir_config('lonSSOReloginServer');
                    213:     if ($sso_url eq '') {
                    214:         $sso_url = $login_path;
                    215:     }
1.11      raeburn   216:     $missing_formitem = &mt('The link to the requested page could not be followed.')."\\n".&mt('The placeholder for the courseID is absent.');
1.1       raeburn   217:     if ($knownuser) {
                    218:         if (keys(%curr_role)) {
1.9       raeburn   219:             $r->print('<h3>'.&mt('Self-enrollment unavailable').'</h3>'.
                    220:                       '<span class="LC_warning">'.&has_role(%curr_role).'</span>');
1.12      raeburn   221:             &page_footer($r);
1.1       raeburn   222:             return OK;
                    223:         }
                    224:         &process_self_enroll($r,$cdom,$cnum,$selfenroll_types,$selfenroll_registered,
                    225:                              $selfenroll_access_start,$selfenroll_access_end,
1.15    ! raeburn   226:                              $selfenroll_section,$now,$selfenroll_approval,
        !           227:                              $selfenroll_notifylist,$owner);
1.10      raeburn   228:     } elsif ($env{'form.phase'} eq 'login') {
                    229:         my $submit_text = &mt('Log in');
                    230:         $r->print('<h3>'.&mt('Log-in to LON-CAPA').'</h3>');
                    231:         my $udom = &Apache::lonnet::default_login_domain();
1.12      raeburn   232:         $r->print(&Apache::createaccount::login_box($now,$lonhost,$courseid,
1.10      raeburn   233:                                            $submit_text,$udom,'selfenroll'));
1.12      raeburn   234:         $r->print(&mt('You will be able to self-enroll in the course you selected ([_1]) after you have successfully logged in.','<b>'.$desc.'</b>'));
                    235:         &page_footer($r);
1.10      raeburn   236:         return OK;
1.3       raeburn   237:     } elsif (@cancreate > 0) {
1.1       raeburn   238:         $r->print(<<END);
                    239: <script type="text/javascript">
1.12      raeburn   240: function setPath(formname,formaction,item,arg) {
                    241:     var formidx = getFormByName(formname);
                    242:     if (formidx > -1) {
                    243:         if (formaction != '') {
                    244:             document.forms[formidx].action = formaction;
                    245:         }
                    246:         var itemid = getIndexByName(formidx,'setting');
                    247:         if (itemid > -1) {
                    248:             document.forms[formidx].elements[itemid].name = item;
                    249:             document.forms[formidx].elements[itemid].value = arg;
                    250:             document.forms[formidx].submit();
                    251:         } else {
                    252:             alert("$missing_formitem");
                    253:         }
1.1       raeburn   254:     }
                    255:     return;
                    256: }
                    257: 
                    258: </script>
                    259: END
1.9       raeburn   260:         $r->print('<h3>'.&mt('LON-CAPA account required').'</h3>'.
1.12      raeburn   261:                   &mt('You need to be logged into LON-CAPA to self-enroll in a course.').'<ul><li>'.&mt('If you have an account in LON-CAPA, [_1]log-in[_2].','<a href="javascript:setPath('."'$form','','phase','login'".')">','</a>').'</li>');
1.3       raeburn   262:         if (@cancreate > 1) {
                    263:             $r->print('<li>'.&mt('Otherwise:').'<br />');
                    264:             my $count = 0;
                    265:             foreach my $type ('sso','login','email') { 
1.4       raeburn   266:                 if (($count > 0) && ($count <@cancreate)) {
1.3       raeburn   267:                     $r->print('&nbsp;, '.&mt('or').'<br />');
                    268:                 }
                    269:                 if (grep(/^$type$/,@cancreate)) {
                    270:                     if ($type eq 'sso') {
1.12      raeburn   271:                         $r->print('&nbsp;&nbsp;'.&mt("if you have an institutional log-in, use your institution's [_1]single sign on page[_2] to log-in, then create an account",'<a href="javascript:setPath('."'$form','$sso_url','firsturl','$firsturl'".')">','</a>'));
1.3       raeburn   272:                     } elsif ($type eq 'login') {
1.12      raeburn   273:                         $r->print('&nbsp;&nbsp;'.&mt('if you have an institutional login, [_1]create an account[_2]','<a href="javascript:setPath('."'$form','$create_path','context','selfenroll_create'".')">','</a>'));
1.3       raeburn   274:                     } elsif ($type eq 'email') {
1.12      raeburn   275:                         $r->print('&nbsp;&nbsp;'.&mt('you can use an e-mail address to [_1]create an account[_2]','<a href="javascript:setPath('."'$form','$create_path','context','selfenroll_create'".')">','</a>'));
1.3       raeburn   276:                     }
                    277:                     $count ++;
                    278:                 }
                    279:             }
                    280:             $r->print('.<br />');
                    281:         } else {
                    282:             if ($cancreate[0] eq 'login') {
1.12      raeburn   283:                 $r->print('<li>'.&mt('Otherwise, if you have an institutional login, [_1]create an account[_2].','<a href="javascript:setPath('."'$form','$create_path','context','selfenroll_create'".')">','</a>'));
1.3       raeburn   284:             } elsif ($cancreate[0] eq 'email') {
1.12      raeburn   285:                 $r->print('<li>'.&mt('Otherwise, you will use an e-mail address to [_1]create an account[_2].','<a href="javascript:setPath('."'$form','$create_path','context','selfenroll_create'".')">','</a>'));
1.3       raeburn   286:             } elsif ($cancreate[0] eq 'sso') {
1.12      raeburn   287:                 $r->print('<li>'.&mt("Otherwise, use your institution's [_1]single sign on page[_2] to log-in, then create an account.",'<a href="javascript:setPath('."'$form','$sso_url','firsturl','$firsturl'".')">','</a>'));
1.3       raeburn   288:             }
1.1       raeburn   289:         }
                    290:         if ($selfenroll_types eq '*') {
1.9       raeburn   291:             $r->print('<br />'.&mt('You will be able to self enroll in this course once the account has been created.').'</li></ul>');
1.1       raeburn   292:         } else {
                    293:             $r->print('</li></ul>');
                    294:             my ($enrolltypes,$longtypes,$alldoms) = 
1.9       raeburn   295:                 &get_selfenroll_filters($selfenroll_types);
                    296:             $r->print(&print_selfenroll_types($longtypes));
1.1       raeburn   297:         }
                    298:     } else {
1.9       raeburn   299:         my $cdomdesc = &Apache::lonnet::domain($cdom,'description');
                    300:         $r->print('<h3>'.&mt('LON-CAPA account required').'</h3>');
                    301:         $r->print(&mt('You must [_1]log-in[_2] to LON-CAPA with an existing account to be able to enroll in this course, as account creation at this institution ([_3]) is not permitted when self-enrolling.','<a href="'.$login_path.'">','</a>',$cdomdesc));
1.1       raeburn   302:         if ($selfenroll_types ne '*') {
                    303:             my ($enrolltypes,$longtypes,$alldoms) =
                    304:                 &get_selfenroll_filters($selfenroll_types);
1.9       raeburn   305:             $r->print('<br />'.&print_selfenroll_types($longtypes));
1.1       raeburn   306:         }
1.9       raeburn   307:         my $displayurl = &escape($firsturl);
                    308:         $r->print(&mt('Submit a request to the LON-CAPA [_1]helpdesk[_2] for [_3] if you require assistance.','<a href="/adm/helpdesk?origurl='.$displayurl.'">','</a>',$cdomdesc));
1.1       raeburn   309:     }
1.12      raeburn   310:     $r->print("\n".'<form name="'.$form.'" method="post" action="">'."\n".
                    311:               '<input type="hidden" name="courseid" value="'.$courseid.'" />'."\n".
1.1       raeburn   312:               '<input type="hidden" name="setting" value=""/>'."\n".
1.12      raeburn   313:               &Apache::lonhtmlcommon::echo_form_input(['backto','courseid','context','phase'])."\n".
                    314:               '</form>'."\n");
                    315:               &page_footer($r);
1.1       raeburn   316:     return OK;
                    317: }
                    318: 
1.15    ! raeburn   319: sub enrollment_limit_check {
        !           320:     my ($selfenroll_limit,$selfenroll_cap,$cdom,$cnum) = @_;
        !           321:     my $nospace = 0;
        !           322:     my (%idx,%stucount);
        !           323:     my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cnum);
        !           324:     $idx{'type'} = &Apache::loncoursedata::CL_TYPE();
        !           325:     $idx{'status'} = &Apache::loncoursedata::CL_STATUS();
        !           326:     while (my ($student,$data) = each(%$classlist)) {
        !           327:         if (($data->[$idx{'status'}] eq 'Active') ||
        !           328:             ($data->[$idx{'status'}] eq 'Future')) {
        !           329:             if ($data->[$idx{'type'}] eq 'selfenroll') {
        !           330:                 $stucount{'selfenroll'} ++;
        !           331:             }
        !           332:             $stucount{'allstudents'} ++;
        !           333:         }
        !           334:     }
        !           335:     if ($stucount{$selfenroll_limit} >= $selfenroll_cap) {
        !           336:         $nospace = 1;
        !           337:     }
        !           338:     return $nospace;
        !           339: }
        !           340: 
1.10      raeburn   341: sub page_header {
1.12      raeburn   342:     my ($r,$courseid,$js,$desc) = @_;
1.10      raeburn   343:     my $start_page =
                    344:         &Apache::loncommon::start_page('Self-enroll in a LON-CAPA course',$js,
                    345:                                        {'no_inline_link'   => 1,});
                    346:     $r->print($start_page);
                    347:     &Apache::lonhtmlcommon::clear_breadcrumbs();
1.12      raeburn   348:     &Apache::createaccount::selfenroll_crumbs($r,$courseid,$desc);
1.10      raeburn   349:     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Self-enroll in course'));
                    350:     return;
                    351: }
                    352: 
1.12      raeburn   353: sub page_footer {
                    354:     my ($r) = @_;
                    355:     $r->print('<form name="backupcrumbs" method="post" action="/adm/coursecatalog">'."\n".
                    356:               &Apache::lonhtmlcommon::echo_form_input(['backto','courseid','phase','context']).
                    357:               '</form>'.&Apache::loncommon::end_page());
                    358:     return;
                    359: }
                    360: 
1.1       raeburn   361: sub validate_course_id {
1.12      raeburn   362:     my ($courseid) = @_;
                    363:     my ($cdom,$cnum) = ($env{'form.courseid'} =~ /^($match_domain)_($match_courseid)$/);
1.1       raeburn   364:     if ($cdom ne '' && $cnum ne '') {
                    365:         if (&Apache::lonnet::is_course($cdom,$cnum)) {
1.12      raeburn   366:             return ('ok',$courseid);
1.1       raeburn   367:         }
                    368:     } 
                    369:     return;
                    370: }
                    371: 
                    372: sub user_is_known {
                    373:     my $known = 0;
                    374:     if ($env{'user.name'} ne '' && $env{'user.name'} ne 'public'
                    375:         && $env{'user.domain'} ne '' && $env{'user.domain'} ne 'public') {
                    376:         $known = 1;
                    377:     }
                    378:     return $known;
                    379: }
                    380: 
                    381: sub can_create {
                    382:     my ($cdom) = @_;
1.3       raeburn   383:     my @cancreate;
1.1       raeburn   384:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$cdom);
                    385:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                    386:         if (ref($domconfig{'usercreation'}{'cancreate'}) eq 'HASH') {
                    387:             if ($domconfig{'usercreation'}{'cancreate'}{'selfcreate'} ne 'none') {
1.3       raeburn   388:                 if (ref($domconfig{'usercreation'}{'cancreate'}{'selfcreate'}) eq 'ARRAY') {
                    389:                     @cancreate = @{$domconfig{'usercreation'}{'cancreate'}{'selfcreate'}};
                    390:                 } else {
                    391:                     if (($domconfig{'usercreation'}{'cancreate'}{'selfcreate'} ne 'none') && 
                    392:                         ($domconfig{'usercreation'}{'cancreate'}{'selfcreate'} ne '')) {
                    393:                         @cancreate = ($domconfig{'usercreation'}{'cancreate'}{'selfcreate'});
                    394:                     }
                    395:                 }
1.1       raeburn   396:             }
                    397:         }
                    398:     }
1.3       raeburn   399:     return @cancreate;
1.1       raeburn   400: }
                    401: 
                    402: sub has_role {
                    403:     my (%curr_role) = @_;
                    404:     my $output;
                    405:     if ($curr_role{'status'} eq 'active') {
                    406:           my $rolelink = &jump_to_role($curr_role{'role'});
1.9       raeburn   407:           $output = &mt('You already have an active student role (section: "[_1]") in this course.',$curr_role{'section'}).'<br>'.$rolelink;
1.1       raeburn   408:     } elsif ($curr_role{'status'} eq 'future') {
1.9       raeburn   409:         $output = &mt('You have a student role (section: "[_1]") in this course which will become active [_2].',$curr_role{'section'},$curr_role{'start'});
1.1       raeburn   410:     }
                    411:     return $output;
                    412: }
                    413: 
                    414: sub process_self_enroll {
                    415:     my ($r,$cdom,$cnum,$selfenroll_types,$selfenroll_registered,
1.15    ! raeburn   416:         $selfenroll_access_start,$selfenroll_access_end,$selfenroll_section,
        !           417:         $now,$selfenroll_approval,$selfenroll_notifylist,$owner) = @_;
1.1       raeburn   418:     my $udom = $env{'user.domain'};
                    419:     my $uname = $env{'user.name'};
                    420:     my $selfenroll = 0;
1.9       raeburn   421:     my ($enrolltypes,$longtypes,$alldoms);
                    422:     if ($selfenroll_types eq '*') {
1.1       raeburn   423:         $selfenroll = 1;
1.9       raeburn   424:     } else {
                    425:         ($enrolltypes,$longtypes,$alldoms) =
                    426:             &get_selfenroll_filters($selfenroll_types,$udom);
                    427:         if ($alldoms) {
                    428:             $selfenroll = 1;
                    429:         } elsif (ref($enrolltypes) eq 'HASH') {
                    430:             if (ref($enrolltypes->{$udom}) eq 'ARRAY') {
                    431:                 if (grep(/^any$/,@{$enrolltypes->{$udom}})) {
                    432:                     $selfenroll = 1;
                    433:                 } else {
                    434:                     $selfenroll = &user_can_selfenroll($udom,$uname,$enrolltypes->{$udom});
1.1       raeburn   435:                 }
                    436:             }
                    437:         }
                    438:     }
                    439:     if ($selfenroll) {
                    440:         my $usec = $selfenroll_section;
                    441:         if ($selfenroll_section eq 'none') {
                    442:             $usec = '';
                    443:         }
                    444:         if ($selfenroll_registered) {
                    445:             my ($registered,$instsec,$message) = &check_registered($cdom,$cnum);
                    446:             $usec = $instsec;
                    447:             if (!$registered) {
1.9       raeburn   448:                 $r->print('<h3>'.&mt('Self-enrollment unavailable').'</h3>'.&mt('Self-enrollment is restricted to students officially registered for this course.').'<br />');
1.1       raeburn   449:                 if ($message) {
                    450:                     $r->print($message);
                    451:                 } else {
                    452:                     $r->print(&mt('As you are not currently registered for this course, self-enrollment is unavailable.'));
                    453:                 }
                    454:                 return; 
                    455:             } 
                    456:         }
1.15    ! raeburn   457:         if ($selfenroll_approval) {
        !           458:             my $outcome = 
        !           459:                 &store_selfenroll_request($udom,$uname,$usec,$cdom,$cnum,
        !           460:                                           $selfenroll_notifylist,$owner);
        !           461:             $r->print($outcome);
        !           462:         } else {
        !           463:             my $enrollresult = 
        !           464:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,
        !           465:                         undef,undef,$usec,$selfenroll_access_end,$selfenroll_access_start,
        !           466:                        'selfenroll',undef,$cdom.'_'.$cnum,$selfenroll);
        !           467:             if ($enrollresult eq 'ok') {
        !           468:                 my (%userroles,%newrole,%newgroups);
        !           469:                 my $role = 'st';
        !           470:                 my $area = '/'.$cdom.'/'.$cnum;
        !           471:                 my $spec = $role.'.'.$area;
        !           472:                 if ($usec ne '') {
        !           473:                     $spec .= '/'.$usec;
        !           474:                     $area .= '/'.$usec;
        !           475:                 }
        !           476:                 &Apache::lonnet::standard_roleprivs(\%newrole,$role,$cdom,$spec,$cnum,
        !           477:                                                     $area);
        !           478:                 &Apache::lonnet::set_userprivs(\%userroles,\%newrole,%newgroups);
        !           479:                 $userroles{'user.role.'.$spec} = $selfenroll_access_start.'.'.$selfenroll_access_end;
        !           480:                 &Apache::lonnet::appenv(\%userroles,[$role,'cm']);
        !           481:                 $r->print('<h3>'.&mt('Enrollment process complete').'</h3>');
        !           482:                 if ($selfenroll_access_end && $selfenroll_access_end <= $now) {
        !           483:                     $r->print(&mt('The end date for access to this course for users who self-enroll has passed.').'<br />'.&mt('Consequently, although a new role was created for you in the course, it is an inactive role which does not provide access to the course.'));
1.1       raeburn   484:                 } else {
1.15    ! raeburn   485:                     $r->print(&mt('Self-enrollment in this course was successful.').'<br />');
        !           486:                     my $showstart = &Apache::lonlocal::locallocaltime($selfenroll_access_start);
        !           487:                     my $showend = &Apache::lonlocal::locallocaltime($selfenroll_access_end);
        !           488:                     if ($selfenroll_access_start && $selfenroll_access_start >$now) {
        !           489:                         $r->print(&mt('The start date for access to this course for users who self-enroll has yet to be reached.').'<br />'.&mt('Consequently, although a new role was created for you in the course, you will not be able to select this role until [_1].',$showstart));
        !           490:                     } else {
        !           491:                         my $newrole = 'st./'.$cdom.'/'.$cnum;
        !           492:                         if ($usec ne '') {
        !           493:                             $newrole .= '/'.$usec;
        !           494:                         }
        !           495:                         my $rolelink = &jump_to_role($newrole);
        !           496:                         $r->print(&mt('Your new role is available immediately, and will provide access to the course until [_1].',$showend).'<br /><br />'."\n".
        !           497:                                  $rolelink); 
1.1       raeburn   498:                     }
                    499:                 }
1.15    ! raeburn   500:             } else {
        !           501:                 $r->print('<h3>'.&mt('Enrollment incomplete').'</h3>'.
        !           502:                           &mt('Self-enrollment in this course failed.'));
        !           503:                 if ($enrollresult ne '') {
        !           504:                     $r->print('<span class="LC_error">'.$enrollresult.'</span>');
        !           505:                 }
1.1       raeburn   506:             }
                    507:         }
                    508:     } else {
1.9       raeburn   509:         $r->print('<h3>'.&mt('Self-enrollment unavailable').'</h3>'.
                    510:                   &mt('You are not permitted to enroll yourself in this course.').'<br />');
1.1       raeburn   511:         $r->print(&print_selfenroll_types($longtypes));
                    512:     }
                    513:     return;
                    514: }
                    515: 
1.9       raeburn   516: sub user_can_selfenroll {
                    517:     my ($udom,$uname,$domenrolltypes) = @_;
                    518:     my $selfenroll = 0;
1.13      raeburn   519:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'inststatus');
1.9       raeburn   520:     my @inststatuses;
                    521:     if ($userhash{'inststatus'} eq '') {
                    522:         push(@inststatuses,'other');
                    523:     } else {
1.13      raeburn   524:         @inststatuses = split(':',$userhash{'inststatus'});
1.9       raeburn   525:     }
                    526:     foreach my $type (@inststatuses) {
                    527:         if (ref($domenrolltypes) eq 'ARRAY') {
                    528:             if (grep(/^\Q$type\E$/,@{$domenrolltypes})) {
                    529:                 $selfenroll = 1;
                    530:                 last;
                    531:             }
                    532:         }
                    533:     }
                    534:     return $selfenroll;
                    535: }
                    536: 
1.15    ! raeburn   537: sub store_selfenroll_request {
        !           538:     my ($udom,$uname,$usec,$cdom,$cnum,$selfenroll_notifylist,$owner) = @_;
        !           539:     my $namespace = 'selfenrollrequests';
        !           540:     my $output;
        !           541:     my $now = time;
        !           542:     my %existing = 
        !           543:         &Apache::lonnet::get($namespace,[$uname.':'.$udom],$cdom,$cnum);
        !           544:     if ($existing{$uname.':'.$udom}) {
        !           545:         my ($timestamp,$sec) = split(/:/,$existing{$uname.':'.$udom});
        !           546:         $output = &mt('A self-enrollment request already exists for you for this course.').'<br />'.&mt('Your earlier request was submitted: [_1] and remains in a queue awaiting action by a Course Coordinator.',&Apache::lonlocal::locallocaltime($timestamp));
        !           547:     } else {
        !           548:         my %selfenroll = (
        !           549:                             $uname.':'.$udom => $now.':'.$usec,
        !           550:                          );
        !           551:         my $putresult = &Apache::lonnet::put($namespace,\%selfenroll,$cdom,$cnum);
        !           552:         if ($putresult eq 'ok') {
        !           553:             $output = &mt('Your request for self-enrollment has been recorded.').'<br />'.
        !           554:                       &mt('A message will be sent to your LON-CAPA account when the course coordinator takes action on your request').'<br />';
        !           555:             my %emails = &Apache::loncommon::getemails($uname,$udom);
        !           556:             if (($emails{'permanentemail'} ne '') || ($emails{'notification'} ne '')) {
        !           557:                 my $address = $emails{'permanentemail'};
        !           558:                 if ($address eq '') {
        !           559:                     $address = $emails{'notification'};
        !           560:                 }
        !           561:                 $output.= &mt('An e-mail will also be sent to: [_1] when this occurs.',$address);
        !           562:             }
        !           563:             if ($selfenroll_notifylist) {
        !           564:                 my $fullname = &Apache::loncommon::plainname($uname,$udom);
        !           565:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'_'.$cnum);
        !           566:                 my $coursedesc = $courseinfo{'description'};
        !           567:                 &send_notification($selfenroll_notifylist,$fullname,$cdom.
        !           568:                                    '_'.$cnum,$coursedesc,$now,'request',$owner);
        !           569:             }
        !           570:         } else {
        !           571:             $output = '<span class="LC_error">'.&mt('An error occurred when recording your request.').'</span>';
        !           572: 
        !           573:         }
        !           574:     }
        !           575:     return $output;
        !           576: }
        !           577: 
        !           578: sub send_notification {
        !           579:     my ($notifylist,$textstr,$cid,$coursedesc,$timestamp,$context,$sender,
        !           580:         $approvedlist,$rejectedlist) = @_;
        !           581: # FIXME locallocaltime needs to be able to take $sender_lh as an argument
        !           582: #       so this can be localized to the recipients date display format/time zone 
        !           583:     $timestamp =&Apache::lonlocal::locallocaltime($timestamp);
        !           584:     my $msgcc;
        !           585:     my ($rawsubj,@rawmsg,$subject,$message,$namelink);
        !           586:     $namelink = &Apache::loncommon::aboutmewrapper(
        !           587:                 &Apache::loncommon::plainname($env{'user.name'},$env{'user.domain'}));
        !           588:     if ($context eq 'managers') {
        !           589:         $rawsubj = 'Self-enrollment requests processed';
        !           590:         push(@rawmsg,{
        !           591:                       mt => 'Enrollment requests in the following course: [_1] have been processed.',
        !           592:                       args => [$coursedesc],
        !           593:                      });
        !           594:     } elsif ($context eq 'enroller') {
        !           595:         $rawsubj = 'Enrollment request';
        !           596:         push(@rawmsg,{
        !           597:                       mt  => 'Your request for enrollment in the following course: [_1], requested on [_2], has been reviewed by a Course Coordinator.',
        !           598:                       args => [$coursedesc,$timestamp],
        !           599:                      });
        !           600:         if (ref($textstr) eq 'ARRAY') {
        !           601:             push(@rawmsg,@{$textstr});
        !           602:         }
        !           603:     } else {
        !           604:         $rawsubj = 'Self-enrollment request';
        !           605:         push(@rawmsg,{
        !           606:                       mt  => 'Enrollment in the following course: [_1] was requested by [_2] on [_3].',
        !           607:                       args => [$coursedesc,$textstr,$timestamp],
        !           608:                      },
        !           609:                      {
        !           610:                       mt =>'As Course Coordinator, use Main Menu -> Manage Couse Users -> "Enrollment Requests" to display a list of pending enrollment requests which you can either approve or reject.'
        !           611:                      });
        !           612:     }
        !           613:     my @to_notify = split(/,/,$notifylist);
        !           614:     my $numsent = 0;
        !           615:     my @recusers;
        !           616:     my @recudoms;
        !           617:     foreach my $cc (@to_notify) {
        !           618:         my ($ccname,$ccdom) = split(/:/,$cc);
        !           619:         if (!exists($msgcc->{$ccname.':'.$ccdom})) {
        !           620:             push(@recusers,$ccname);
        !           621:             push(@recudoms,$ccdom);
        !           622:             $msgcc->{$ccname.':'.$ccdom}='';
        !           623:             $numsent ++;
        !           624:         }
        !           625:     }
        !           626:     my %reciphash = (
        !           627:                      cc => $msgcc,
        !           628:     );
        !           629:     my ($uname,$udom);
        !           630:     if ($sender =~ /:/) {
        !           631:         ($uname,$udom) = split(/:/,$sender);
        !           632:     } else {
        !           633:         $uname = $sender;
        !           634:         my %courseinfo = &Apache::lonnet::coursedescription($cid);
        !           635:         $udom = $courseinfo{'num'};
        !           636:     }
        !           637:     my %sentmessage;
        !           638:     my $stamp = time;
        !           639:     my $msgcount = &Apache::lonmsg::get_uniq();
        !           640:     my $sender_lh = &Apache::loncommon::user_lang($uname,$udom,$cid);
        !           641:     $subject = &Apache::lonlocal::mt_user($sender_lh,$rawsubj);
        !           642:     $message = '';
        !           643:     foreach my $item (@rawmsg) {
        !           644:         if (ref($item) eq 'HASH') {
        !           645:             $message .= &Apache::lonlocal::mt_user($sender_lh,$item->{mt},@{$item->{args}})."\n";
        !           646:         }
        !           647:     }
        !           648:     &Apache::lonmsg::process_sent_mail($subject,'',$numsent,$stamp,$uname,$udom,$msgcount,$cid,$$,$message,\@recusers,\@recudoms);
        !           649:     my ($recipid,$recipstatus) =
        !           650:         &Apache::lonmsg::store_recipients($subject,$uname,$udom,\%reciphash);
        !           651:     foreach my $recip (sort(keys(%{$msgcc}))) {
        !           652:         my ($ccname,$ccdom) = split(/:/,$recip);
        !           653:         my $recip_lh = &Apache::loncommon::user_lang($ccname,$ccdom,$cid);
        !           654:         my $subject = &Apache::lonlocal::mt_user($sender_lh,$rawsubj);
        !           655:         my $message = '';
        !           656:         foreach my $item (@rawmsg) {
        !           657:             if (ref($item) eq 'HASH') {
        !           658:                 $message .= &Apache::lonlocal::mt_user($sender_lh,$item->{mt},
        !           659:                                                        @{$item->{args}})."\n";
        !           660:             }
        !           661:         }
        !           662:         if ($context eq 'managers') {
        !           663:             if ($approvedlist) {
        !           664:                 $message .= "\n\n".&Apache::lonlocal::mt_user($sender_lh,'Approved enrollments:')."\n".$approvedlist;
        !           665:             }
        !           666:             if ($rejectedlist) {
        !           667:                 $message .= "\n\n".&Apache::lonlocal::mt_user($sender_lh,'Rejected enrollments:')."\n".$rejectedlist;
        !           668:             }
        !           669:         }
        !           670:         my $status = &Apache::lonmsg::user_normal_msg($ccname,$ccdom,$subject,$message,undef,undef,undef,1,\%sentmessage,undef,undef,undef,1,$recipid);
        !           671:     }
        !           672: }
        !           673: 
1.1       raeburn   674: sub jump_to_role {
                    675:     my ($role) = @_;
                    676:     my $output = <<"END";
                    677: <script type="text/javascript">
                    678: function SelectRole() {
                    679:     document.rolechoice.selectrole.value = '1';
                    680:     document.rolechoice.submit();
                    681: }
                    682: </script>
                    683: END
                    684:     $output .= '<a href="javascript:SelectRole()">'."\n". 
                    685:                &mt('Enter course now').'</a>'."\n".
1.9       raeburn   686:                '<form name="rolechoice" action="/adm/roles" method="post">'."\n".
1.1       raeburn   687:                '<input type="hidden" name="selectrole" value="" />'."\n".
                    688:                '<input type="hidden" name="'.$role.'" value="1" />'."\n".
                    689:                '</form>';
                    690:     return $output;
                    691: }
                    692: 
                    693: sub get_selfenroll_filters {
                    694:     my ($selfenroll_types,$domain) = @_;
                    695:     my (%enrolltypes,%longtypes,$alldoms);
                    696:     my @selfenrolldoms = split(/;/,$selfenroll_types);
                    697:     foreach my $item (@selfenrolldoms) {
                    698:         my ($selfdom,$type_str) = split(/:/,$item);
                    699:         if ($selfdom eq '*') {
                    700:             $alldoms = 1;
                    701:             last;
                    702:         }
                    703:         if ($domain ne '') {
                    704:             next if ($selfdom ne $domain);
                    705:         }
                    706:         if ($selfdom =~ /^$match_domain$/) {
                    707:             if (&Apache::lonnet::domain($selfdom) ne '') {
                    708:                 my @types = split(/,/,$type_str);
1.13      raeburn   709:                 my @unesc_types = map { &unescape($_); } @types;
1.1       raeburn   710:                 my ($othertitle,$usertypes,$types) =
                    711:                     &Apache::loncommon::sorted_inst_types($selfdom);
                    712:                 if (ref($usertypes) eq 'HASH') {
1.9       raeburn   713:                     my $anytype = 1;
                    714:                     foreach my $key (keys(%{$usertypes})) {
1.13      raeburn   715:                         if (!grep(/^\Q$key\E$/,@unesc_types)) {
1.9       raeburn   716:                             $anytype = 0;
                    717:                             last;
                    718:                         }
                    719:                     }
                    720:                     if ($anytype) {
                    721:                         if (!(grep(/^other$/,@types))) {
                    722:                             $anytype = 0;
                    723:                         }
                    724:                     }
                    725:                     $usertypes->{'any'} = &mt('Any users');
                    726:                     $usertypes->{'other'} = &mt('Others');
1.13      raeburn   727:                     my @showtypes;
1.9       raeburn   728:                     if ($anytype) {
                    729:                         @{$enrolltypes{$selfdom}} = ('any');
1.13      raeburn   730:                         @showtypes =  ('any');
1.9       raeburn   731:                     } else {
                    732:                         @{$enrolltypes{$selfdom}} = @types;
1.13      raeburn   733:                         @showtypes = @unesc_types;
1.9       raeburn   734:                     }
                    735:                     @{$longtypes{$selfdom}} = 
1.13      raeburn   736:                         map {$usertypes->{$_}} @showtypes;
1.1       raeburn   737:                 }
                    738:             }
                    739:         }
                    740:     }
                    741:     return (\%enrolltypes,\%longtypes,$alldoms);
                    742: }
                    743: 
                    744: sub print_selfenroll_types {
                    745:     my ($longtypes,$domain) = @_;
                    746:     my $output;
                    747:     if (ref($longtypes) eq 'HASH') {
1.9       raeburn   748:         if ($domain ne '') {
                    749:             my $domdesc = &Apache::lonnet::domain($domain,'description');
                    750:             if (ref($longtypes->{$domain}) eq 'ARRAY') {
                    751:                 if (grep(/^any$/,@{$longtypes->{$domain}})) {
                    752:                     $output = &mt('Self-enrollment in this course is available to any user affiliated with [_1].',$domdesc);
                    753:                 } else {
                    754:                     my $status_str = join(', ',@{$longtypes->{$domain}});
                    755:                     $output = &mt('Self-enrollment in this course is only available to users affiliated with [_1] who have the following status: "[_2]".',$domdesc,$status_str);
1.1       raeburn   756:                 }
                    757:             } else {
1.9       raeburn   758:                 $output = &mt('Self-enrollment is not currently available for this course for users affiliated with [_1].',$domdesc);
                    759:             }
                    760:         } elsif (keys(%{$longtypes}) > 0) {
1.12      raeburn   761:             $output = &mt('Self-enrollment in this course is only available to users affiliated with the following institutions, and who have the required status:').' <ul>'."\n";
1.9       raeburn   762:             foreach my $selfdom (sort(keys(%{$longtypes}))) {
                    763:                 my $selfdomdesc = &Apache::lonnet::domain($selfdom,'description');
                    764:                 if (ref($longtypes->{$selfdom}) eq 'ARRAY') {
1.12      raeburn   765:                     $output .= '<li>'.$selfdomdesc.': '.join(', ',@{$longtypes->{$selfdom}}).'</li>'."\n";
1.1       raeburn   766:                 }
                    767:             }
1.12      raeburn   768:             $output .= '</ul>'."\n";
1.1       raeburn   769:         } else {
1.5       bisitz    770:             $output = &mt('Self-enrollment is not currently available for this course.');
1.1       raeburn   771:         }
                    772:     }
                    773:     return $output;
                    774: }
                    775: 
                    776: sub check_registered {
                    777:     my ($cdom,$cnum) = @_;
                    778:     my ($registered,$instsec,$message);
                    779:     my %settings = &Apache::lonnet::get('environment',['internal.coursecode',
                    780:                                         'internal.sectionnums',
                    781:                                         'internal.crosslistings'],$cdom,$cnum);
                    782:     my (@allcourses,%LC_code,%affiliates,%reply);
                    783:     &Apache::loncommon::get_institutional_codes(\%settings,\@allcourses,\%LC_code);
                    784:     if (@allcourses > 0) {
                    785:         @{$affiliates{$cnum}} = @allcourses;
                    786:         my $outcome = &Apache::lonnet::fetch_enrollment_query('updatenow',\%affiliates,\%reply,$cdom,$cnum);
                    787:         if ($outcome eq 'ok') {
                    788:             if ($reply{$cnum} > 0) {
                    789:                 foreach my $class (@allcourses) {
                    790:                     my %enrolled;
                    791:                     my $dir = $Apache::lonnet::perlvar{'lonDaemons'};
                    792:                     my %place = &LONCAPA::Enrollment::place_hash();
                    793:                     &LONCAPA::Enrollment::parse_classlist($dir,$cdom,$cnum,$class,
                    794:                              \%place,$LC_code{$class},\%enrolled);
                    795:                     if (defined($enrolled{$env{'user.name'}})) {
                    796:                         $registered = 1;
                    797:                         $instsec = $LC_code{$class};
                    798:                         last;
                    799:                     }
                    800:                 }
                    801:             } else {
                    802:                 $message = &mt('Your registration status could not be verified.');
                    803:             }
                    804:         } else {
                    805:              $message = &mt('Your registration status could not determined, because a problem occurred retrieving data.');
                    806:         }
                    807:     } else {
                    808:         $message = &mt('As no institutional course sections are currently associated with this course, your registration status is undetermined.'); 
                    809:     }
                    810:     return ($registered,$instsec,$message);
                    811: }
                    812: 
                    813: 1;
                    814: 

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