Diff for /loncom/interface/selfenroll.pm between versions 1.5 and 1.20

version 1.5, 2008/06/23 15:52:52 version 1.20, 2009/05/24 00:05:04
Line 33  use Apache::Constants qw(:common); Line 33  use Apache::Constants qw(:common);
 use Apache::lonnet;  use Apache::lonnet;
 use Apache::loncommon;  use Apache::loncommon;
 use Apache::lonlocal;  use Apache::lonlocal;
   use Apache::createaccount;
 use LONCAPA qw(:DEFAULT :match);  use LONCAPA qw(:DEFAULT :match);
   
 sub handler {  sub handler {
Line 44  sub handler { Line 45  sub handler {
     }      }
     my $handle = &Apache::lonnet::check_for_valid_session($r);      my $handle = &Apache::lonnet::check_for_valid_session($r);
     my $lonidsdir=$r->dir_config('lonIDsDir');      my $lonidsdir=$r->dir_config('lonIDsDir');
       my $lonhost = $r->dir_config('lonHostID');
     if ($handle ne '') {      if ($handle ne '') {
         &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle);          &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle);
     }      }
     &Apache::lonacc::get_posted_cgi($r);      &Apache::lonacc::get_posted_cgi($r);
     &Apache::lonlocal::get_language_handle($r);      &Apache::lonlocal::get_language_handle($r);
     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['cid']);      &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['courseid']);
     my ($coursechk,$cid) = &validate_course_id($env{'form.cid'});      my $js = &Apache::createaccount::catreturn_js();
     my $start_page =      my ($coursechk,$courseid) = &validate_course_id($env{'form.courseid'});
         &Apache::loncommon::start_page('Self-enroll in a LON-CAPA course','',  
                                        {'no_inline_link'   => 1,});  
     $r->print($start_page);  
     &Apache::lonhtmlcommon::clear_breadcrumbs();  
     &Apache::lonhtmlcommon::add_breadcrumb  
     ({href=>"/adm/selfenroll?cid=$cid",  
       text=>"Self-enroll"});  
     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Self-enroll in course'));  
     if ($coursechk ne 'ok') {      if ($coursechk ne 'ok') {
         $r->print(&mt('Invalid domain or course number'));          &page_header($r,$courseid,$js);
         $r->print(&Apache::loncommon::end_page());          $r->print('<h3>'.&mt('Self-enrollment error').'</h3>'.
                     '<span class="LC_error">'.
                     &mt('Invalid domain or course number').'</span>');
           &page_footer($r);
         return OK;          return OK;
     }      }
     my ($cdom,$cnum,$canenroll,$selfenroll_types,$selfenroll_registered,  
         @cancreate,$knownuser,$selfenroll_access_start,$selfenroll_access_end,  
         $selfenroll_section,%curr_role,%coursehash);  
     my $now = time;      my $now = time;
     %coursehash = &Apache::lonnet::coursedescription($cid);      if ($env{'form.phase'} eq 'login') {
     $cdom = $coursehash{'domain'};          $js .= "\n".&Apache::createaccount::javascript_setforms($now);
     $cnum = $coursehash{'num'};      }
       my %coursehash = &Apache::lonnet::coursedescription($courseid);
       my $cdom = $coursehash{'domain'};
       my $cnum = $coursehash{'num'};
       my $desc = $coursehash{'description'};
       &page_header($r,$courseid,$js,$desc);
       my $include = $r->dir_config('lonIncludes');
       if ($env{'form.phase'} eq 'login') {
           my $jsh=Apache::File->new($include."/londes.js");
           $r->print(<$jsh>);
       }
       my ($canenroll,$selfenroll_types,$selfenroll_registered,@cancreate,
           $knownuser,$selfenroll_access_start,$selfenroll_access_end,
           $selfenroll_section,$selfenroll_future,%curr_role,$cdomdesc,
           $selfenroll_approval,$selfenroll_limit,$selfenroll_cap,
           $selfenroll_notifylist,$owner);
     $selfenroll_types = $coursehash{'internal.selfenroll_types'};      $selfenroll_types = $coursehash{'internal.selfenroll_types'};
     $selfenroll_registered =  $coursehash{'internal.selfenroll_registered'};      $selfenroll_registered =  $coursehash{'internal.selfenroll_registered'};
     $selfenroll_section = $coursehash{'internal.selfenroll_section'};      $selfenroll_section = $coursehash{'internal.selfenroll_section'};
     $selfenroll_access_start =  $coursehash{'internal.selfenroll_start_access'};      $selfenroll_access_start =  $coursehash{'internal.selfenroll_start_access'};
     $selfenroll_access_end =  $coursehash{'internal.selfenroll_end_access'};      $selfenroll_access_end =  $coursehash{'internal.selfenroll_end_access'};
       $selfenroll_limit =  $coursehash{'internal.selfenroll_limit'};
       $selfenroll_cap = $coursehash{'internal.selfenroll_cap'};
       $selfenroll_approval = $coursehash{'internal.selfenroll_approval'};
       $selfenroll_notifylist = $coursehash{'internal.selfenroll_notifylist'};
       $owner = $coursehash{'internal.courseowner'};
       my $nospace;
     if ($selfenroll_types ne '') {      if ($selfenroll_types ne '') {
         my $start = $coursehash{'internal.selfenroll_start_date'};          my $start = $coursehash{'internal.selfenroll_start_date'};
         my $end = $coursehash{'internal.selfenroll_end_date'};          my $end = $coursehash{'internal.selfenroll_end_date'};
         if (($start > 0 && $start < $now) && ($end > 0 && $end > $now)) {          if (($start > 0 && $start < $now) && (($end == 0) || ($end > 0 && $end > $now))) {
             $canenroll = 1;              if (($selfenroll_limit eq 'allstudents') || 
                   ($selfenroll_limit eq 'selfenroll')) {
                   $nospace = 
                       &enrollment_limit_check($selfenroll_limit,$selfenroll_cap,
                                               $cdom,$cnum);
                   if (!$nospace) {
                       $canenroll = 1; 
                   }
               } else {
                   $canenroll = 1;
               }
           } elsif (($end == 0) || ($end > 0 && $end > $now)) {
               if ($start > $now) {
                   if (($selfenroll_limit eq 'allstudents') ||
                       ($selfenroll_limit eq 'selfenroll')) {
                       $nospace = 
                           &enrollment_limit_check($selfenroll_limit,$cdom,$cnum);
                   }
                   if (!$nospace) {
                       $selfenroll_future = &Apache::lonlocal::locallocaltime($start);
                   }
               }
         }          }
     }      }
       $knownuser = &user_is_known();
     if (!$canenroll) {      if (!$canenroll) {
         $r->print(&mt('Self-enrollment is not currently available for this course.').'<br /><br />');          $r->print('<h3>'.&mt('Self-enrollment unavailable').'</h3><span class="LC_warning">'.
                     &mt('Self-enrollment is not currently available for this course.').
                     '</span><br /><br />');
           if ($nospace) {
               if ($selfenroll_limit eq 'allstudents') {
                   $r->print(&mt('The enrollment limit of [quant,_1,student] has been reached.',$selfenroll_cap));
               } else {
                   $r->print(&mt('The enrollment limit of [quant,_1,self-enrolled student] has been reached.',$selfenroll_cap));
   
               }
           } 
           if ($selfenroll_types ne '') {
               if ($selfenroll_future ne '') {
                   if ($selfenroll_types eq '*') {
                       $r->print(&mt('Self-enrollment will become available starting [_1], and will be available to all LON-CAPA users.',$selfenroll_future).'<br />');
                   } else {
                       my ($enrolltypes,$longtypes,$alldoms);
                       if ($knownuser) {
                           &get_selfenroll_filters($selfenroll_types,$env{'user.domain'});
                           my $domdesc = &Apache::lonnet::domain($env{'user.domain'},'description');
                           if (ref($enrolltypes) eq 'HASH') {
                               if (ref($enrolltypes->{$env{'user.domain'}}) eq 'ARRAY') {
                                   if (grep(/^any$/,@{$enrolltypes->{$env{'user.domain'}}})) {
                                       $r->print(&mt('Self-enrollment will become available starting [_1], and will be available to all LON-CAPA users at your institution ([_2]).',
                                                 $selfenroll_future,$domdesc).'<br />');
   
                                   } else {
                                       if (&user_can_selfenroll($env{'user.domain'},
                                                           $env{'user.name'},
                                                           $enrolltypes->{$env{'user.domain'}})) {
                                           $r->print(&mt('Self-enrollment will become available starting [_1]; please enroll at that time.',$selfenroll_future)); 
                                       } else {
                                           $r->print(&mt('Although self-enrollment will become available starting [_1], you are ineligible for enrollment.',$selfenroll_future).'<br />');
                                           $r->print(&print_selfenroll_types($longtypes,$env{'user.domain'}));
                                       }
                                   }
                               }
                           } 
                       } else {
                           $r->print(&mt('Self-enrollment will become available starting [_1].',
                                         $selfenroll_future).'<br />');
                           $r->print(&print_selfenroll_types($longtypes));
                       }
                   }
               } 
           }
     }      }
     $knownuser = &user_is_known();  
     if ($knownuser) {      if ($knownuser) {
         foreach my $key (keys(%env)) {          foreach my $key (keys(%env)) {
             if ($key =~ m-^user\.role\.st\./$cdom/$cnum/?(\w*)$-) {              if ($key =~ m-^user\.role\.st\./$cdom/$cnum/?(\w*)$-) {
                 my $sec = $1;                  my $sec = $1;
                 if ($sec eq '') {  
                     $sec = &mt('none');  
                 }   
                 my ($start,$end) = split(/\./,$env{$key});                  my ($start,$end) = split(/\./,$env{$key});
                 my $status = 'active';                  my $status = 'active';
                 if (($end) && ($end<=$now)) {                  if (($end) && ($end<=$now)) {
Line 106  sub handler { Line 184  sub handler {
                 if ($status eq 'active' || $status eq 'future') {                  if ($status eq 'active' || $status eq 'future') {
                      $curr_role{'status'} = $status;                       $curr_role{'status'} = $status;
                      $curr_role{'section'} = $sec;                       $curr_role{'section'} = $sec;
                        if ($curr_role{'section'} eq '') {
                            $curr_role{'section'} = &mt('none'); 
                        }
                      $curr_role{'start'} = &Apache::lonlocal::locallocaltime($start);                       $curr_role{'start'} = &Apache::lonlocal::locallocaltime($start);
                      $curr_role{'role'} = 'st./'.$cdom.'/'.$cnum;                       $curr_role{'role'} = 'st./'.$cdom.'/'.$cnum;
                      if ($sec ne '') {                       if ($sec ne '') {
Line 119  sub handler { Line 200  sub handler {
         if (keys(%curr_role)) {          if (keys(%curr_role)) {
             $r->print(&has_role(%curr_role));              $r->print(&has_role(%curr_role));
         }          }
         $r->print(&Apache::loncommon::end_page());          &page_footer($r);
         return OK;          return OK;
     }      }
     @cancreate = &can_create($cdom);      @cancreate = &can_create($cdom);
     my ($login_path,$firsturl,$create_path,$sso_url,$missing_formitem);      my ($form,$login_path,$firsturl,$create_path,$sso_url,$missing_formitem);
       $form = 'logmein';
     $login_path = '/adm/login';      $login_path = '/adm/login';
     $firsturl= '/adm/selfenroll?cid='.$cid;      $firsturl= '/adm/selfenroll?courseid='.$courseid;
     $create_path = '/adm/createaccount';      $create_path = '/adm/createaccount';
     $sso_url = $r->dir_config('lonSSOReloginServer');      $sso_url = $r->dir_config('lonSSOReloginServer');
     if ($sso_url eq '') {      if ($sso_url eq '') {
         $sso_url = $login_path;          $sso_url = $login_path;
     }      }
     my $missing_formitem = &mt('The link to the requested page could not be followed.')."\\n".&mt('The placeholder for the courseID is absent.');      $missing_formitem = &mt('The link to the requested page could not be followed.')."\\n".&mt('The placeholder for the courseID is absent.');
     if ($knownuser) {      if ($knownuser) {
         if (keys(%curr_role)) {          if (keys(%curr_role)) {
             $r->print(&has_role(%curr_role));              $r->print('<h3>'.&mt('Self-enrollment unavailable').'</h3>'.
                         '<span class="LC_warning">'.&has_role(%curr_role).'</span>');
               &page_footer($r);
             return OK;              return OK;
         }          }
         &process_self_enroll($r,$cdom,$cnum,$selfenroll_types,$selfenroll_registered,          &process_self_enroll($r,$cdom,$cnum,$selfenroll_types,$selfenroll_registered,
                              $selfenroll_access_start,$selfenroll_access_end,                               $selfenroll_access_start,$selfenroll_access_end,
                              $selfenroll_section,$now);                               $selfenroll_section,$now,$selfenroll_approval,
                                $selfenroll_notifylist,$owner);
       } elsif ($env{'form.phase'} eq 'login') {
           my $submit_text = &mt('Log in');
           $r->print('<h3>'.&mt('Log-in to LON-CAPA').'</h3>');
           my $udom = &Apache::lonnet::default_login_domain();
           $r->print(&Apache::createaccount::login_box($now,$lonhost,$courseid,
                                              $submit_text,$udom,'selfenroll'));
           $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>'));
           &page_footer($r);
           return OK;
     } elsif (@cancreate > 0) {      } elsif (@cancreate > 0) {
         $r->print(<<END);          $r->print(<<END);
 <script type="text/javascript">  <script type="text/javascript">
 function setPath(formaction,item,arg) {  function setPath(formname,formaction,item,arg) {
     document.forms.logmein.action = formaction;      var formidx = getFormByName(formname);
     var itemid = getIndexByName("setting");      if (formidx > -1) {
     if (itemid > -1) {          if (formaction != '') {
         document.logmein.elements[itemid].name = item;              document.forms[formidx].action = formaction;
         document.logmein.elements[itemid].value = arg;          }
         document.logmein.submit();          var itemid = getIndexByName(formidx,'setting');
     } else {          if (itemid > -1) {
         alert("$missing_formitem");              document.forms[formidx].elements[itemid].name = item;
               document.forms[formidx].elements[itemid].value = arg;
               document.forms[formidx].submit();
           } else {
               alert("$missing_formitem");
           }
     }      }
     return;      return;
 }  }
   
 function getIndexByName(item) {  
     for (var i=0;i<document.logmein.elements.length;i++) {  
         if (document.logmein.elements[i].name == item) {  
             return i;  
         }  
     }  
     return -1;  
 }  
 </script>  </script>
 END  END
         $r->print(&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('."'$login_path','firsturl','$firsturl'".')">','</a>').'</li>');          $r->print('<h3>'.&mt('LON-CAPA account required').'</h3>'.
                     &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>');
         if (@cancreate > 1) {          if (@cancreate > 1) {
             $r->print('<li>'.&mt('Otherwise:').'<br />');              $r->print('<li>'.&mt('Otherwise:').'<br />');
             my $count = 0;              my $count = 0;
Line 176  END Line 268  END
                 }                  }
                 if (grep(/^$type$/,@cancreate)) {                  if (grep(/^$type$/,@cancreate)) {
                     if ($type eq 'sso') {                      if ($type eq 'sso') {
                         $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('."'$sso_url','firsturl','$firsturl'".')">','</a>'));                          $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>'));
                     } elsif ($type eq 'login') {                      } elsif ($type eq 'login') {
                         $r->print('&nbsp;&nbsp;'.&mt('if you have an institutional login, [_1]create an account[_2]','<a href="javascript:setPath('."'$create_path','courseid','$cid'".')">','</a>'));                          $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>'));
                     } elsif ($type eq 'email') {                      } elsif ($type eq 'email') {
                         $r->print('&nbsp;&nbsp;'.&mt('you can use an e-mail address to [_1]create an account[_2]','<a href="javascript:setPath('."'$create_path','courseid','$cid'".')">','</a>'));                          $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>'));
                     }                      }
                     $count ++;                      $count ++;
                 }                  }
Line 188  END Line 280  END
             $r->print('.<br />');              $r->print('.<br />');
         } else {          } else {
             if ($cancreate[0] eq 'login') {              if ($cancreate[0] eq 'login') {
                 $r->print('<li>'.&mt('Otherwise, if you have an institutional login, [_1]create an account[_2].','<a href="javascript:setPath('."'$create_path','courseid','$cid'".')">','</a>'));                  $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>'));
             } elsif ($cancreate[0] eq 'email') {              } elsif ($cancreate[0] eq 'email') {
                 $r->print('<li>'.&mt('Otherwise, you will use an e-mail address to [_1]create an account[_2].','<a href="javascript:setPath('."'$create_path','courseid','$cid'".')">','</a>'));                  $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>'));
             } elsif ($cancreate[0] eq 'sso') {              } elsif ($cancreate[0] eq 'sso') {
                 $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('."'$sso_url','firsturl','$firsturl'".')">','</a>'));                  $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>'));
             }              }
         }          }
         if ($selfenroll_types eq '*') {          if ($selfenroll_types eq '*') {
             $r->print('<br />'.&mt('You will have an opportunity to self enroll in the course once the account has been created.').'</li></ul>');              $r->print('<br />'.&mt('You will be able to self enroll in this course once the account has been created.').'</li></ul>');
         } else {          } else {
             $r->print('</li></ul>');              $r->print('</li></ul>');
             my ($enrolltypes,$longtypes,$alldoms) =               my ($enrolltypes,$longtypes,$alldoms) = 
                 &get_selfenroll_filters($selfenroll_types,$cdom);                  &get_selfenroll_filters($selfenroll_types);
             $r->print(&print_selfenroll_types($longtypes,$cdom));              $r->print(&print_selfenroll_types($longtypes));
         }          }
     } else {      } else {
         $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 is not permitted when self-enrolling.','<a href="'.$login_path.'">','</a>'));          my $cdomdesc = &Apache::lonnet::domain($cdom,'description');
           $r->print('<h3>'.&mt('LON-CAPA account required').'</h3>');
           $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));
         if ($selfenroll_types ne '*') {          if ($selfenroll_types ne '*') {
             my ($enrolltypes,$longtypes,$alldoms) =              my ($enrolltypes,$longtypes,$alldoms) =
                 &get_selfenroll_filters($selfenroll_types);                  &get_selfenroll_filters($selfenroll_types);
             $r->print('<br /><br />'.&print_selfenroll_types($longtypes));              $r->print('<br />'.&print_selfenroll_types($longtypes));
         }          }
           my $displayurl = &escape($firsturl);
           $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));
     }      }
     $r->print('<form name ="logmein" method="post" action="">'."\n".      $r->print("\n".'<form name="'.$form.'" method="post" action="">'."\n".
                 '<input type="hidden" name="courseid" value="'.$courseid.'" />'."\n".
               '<input type="hidden" name="setting" value=""/>'."\n".                '<input type="hidden" name="setting" value=""/>'."\n".
               '</form>'."\n".                &Apache::lonhtmlcommon::echo_form_input(['backto','courseid','context','phase'])."\n".
               &Apache::loncommon::end_page());                '</form>'."\n");
                 &page_footer($r);
     return OK;      return OK;
 }  }
   
   sub enrollment_limit_check {
       my ($selfenroll_limit,$selfenroll_cap,$cdom,$cnum) = @_;
       my $nospace = 0;
       my (%idx,%stucount);
       my $classlist = &Apache::loncoursedata::get_classlist($cdom,$cnum);
       $idx{'type'} = &Apache::loncoursedata::CL_TYPE();
       $idx{'status'} = &Apache::loncoursedata::CL_STATUS();
       while (my ($student,$data) = each(%$classlist)) {
           if (($data->[$idx{'status'}] eq 'Active') ||
               ($data->[$idx{'status'}] eq 'Future')) {
               if ($data->[$idx{'type'}] eq 'selfenroll') {
                   $stucount{'selfenroll'} ++;
               }
               $stucount{'allstudents'} ++;
           }
       }
       if ($stucount{$selfenroll_limit} >= $selfenroll_cap) {
           $nospace = 1;
       }
       return $nospace;
   }
   
   sub page_header {
       my ($r,$courseid,$js,$desc) = @_;
       my $start_page =
           &Apache::loncommon::start_page('Self-enroll in a LON-CAPA course',$js,
                                          {'no_inline_link'   => 1,});
       $r->print($start_page);
       &Apache::lonhtmlcommon::clear_breadcrumbs();
       &Apache::createaccount::selfenroll_crumbs($r,$courseid,$desc);
       $r->print(&Apache::lonhtmlcommon::breadcrumbs('Self-enroll in course'));
       return;
   }
   
   sub page_footer {
       my ($r) = @_;
       $r->print('<form name="backupcrumbs" method="post" action="/adm/coursecatalog">'."\n".
                 &Apache::lonhtmlcommon::echo_form_input(['backto','courseid','phase','context']).
                 '</form>'.&Apache::loncommon::end_page());
       return;
   }
   
 sub validate_course_id {  sub validate_course_id {
     my ($cid) = @_;      my ($courseid) = @_;
     my ($cdom,$cnum) = ($env{'form.cid'} =~ /^($match_domain)_($match_courseid)$/);      my ($cdom,$cnum) = ($env{'form.courseid'} =~ /^($match_domain)_($match_courseid)$/);
     if ($cdom ne '' && $cnum ne '') {      if ($cdom ne '' && $cnum ne '') {
         if (&Apache::lonnet::is_course($cdom,$cnum)) {          if (&Apache::lonnet::is_course($cdom,$cnum)) {
             return ('ok',$cid);              return ('ok',$courseid);
         }          }
     }       } 
     return;      return;
Line 264  sub has_role { Line 404  sub has_role {
     my $output;      my $output;
     if ($curr_role{'status'} eq 'active') {      if ($curr_role{'status'} eq 'active') {
           my $rolelink = &jump_to_role($curr_role{'role'});            my $rolelink = &jump_to_role($curr_role{'role'});
           $output = &mt('You currently have an active role (section: "[_1]") in this course.',$curr_role{'section'}).' '.$rolelink;            $output = &mt('You already have an active student role (section: "[_1]") in this course.',$curr_role{'section'}).'<br />'.$rolelink;
     } elsif ($curr_role{'status'} eq 'future') {      } elsif ($curr_role{'status'} eq 'future') {
         $output = &mt('You have a role (section: "[_1]") in this course which will become active [_2].',$curr_role{'section'},$curr_role{'start'});          $output = &mt('You have a student role (section: "[_1]") in this course which will become active [_2].',$curr_role{'section'},$curr_role{'start'});
     }      }
     return $output;      return $output;
 }  }
   
 sub process_self_enroll {  sub process_self_enroll {
     my ($r,$cdom,$cnum,$selfenroll_types,$selfenroll_registered,      my ($r,$cdom,$cnum,$selfenroll_types,$selfenroll_registered,
         $selfenroll_access_start,$selfenroll_access_end,$selfenroll_section,$now) = @_;          $selfenroll_access_start,$selfenroll_access_end,$selfenroll_section,
           $now,$selfenroll_approval,$selfenroll_notifylist,$owner) = @_;
     my $udom = $env{'user.domain'};      my $udom = $env{'user.domain'};
     my $uname = $env{'user.name'};      my $uname = $env{'user.name'};
     my @info = ['inststatus'];  
     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,@info);  
     my ($enrolltypes,$longtypes,$alldoms) =   
         &get_selfenroll_filters($selfenroll_types,$udom);  
     my @inststatuses = &unescape(split(/:/,$userhash{'inststatus'}));  
     if (@inststatuses == 0) {  
         push(@inststatuses,'other');  
     }  
     my $selfenroll = 0;      my $selfenroll = 0;
     if ($alldoms) {      my ($enrolltypes,$longtypes,$alldoms);
       if ($selfenroll_types eq '*') {
         $selfenroll = 1;          $selfenroll = 1;
     } elsif (ref($enrolltypes) eq 'HASH') {      } else {
         if (ref($enrolltypes->{$udom}) eq 'ARRAY') {          ($enrolltypes,$longtypes,$alldoms) =
             if (grep(/^any$/,@{$enrolltypes->{$udom}})) {              &get_selfenroll_filters($selfenroll_types,$udom);
                 $selfenroll = 1;          if ($alldoms) {
             } else {              $selfenroll = 1;
                 foreach my $type (@inststatuses) {          } elsif (ref($enrolltypes) eq 'HASH') {
                     if (grep(/^\Q$type\E$/,@{$enrolltypes->{$udom}})) {              if (ref($enrolltypes->{$udom}) eq 'ARRAY') {
                         $selfenroll = 1;                  if (grep(/^any$/,@{$enrolltypes->{$udom}})) {
                         last;                      $selfenroll = 1;
                     }                  } else {
                       $selfenroll = &user_can_selfenroll($udom,$uname,$enrolltypes->{$udom});
                 }                  }
             }              }
         }          }
Line 310  sub process_self_enroll { Line 445  sub process_self_enroll {
             my ($registered,$instsec,$message) = &check_registered($cdom,$cnum);              my ($registered,$instsec,$message) = &check_registered($cdom,$cnum);
             $usec = $instsec;              $usec = $instsec;
             if (!$registered) {              if (!$registered) {
                 $r->print(&mt('Self-enrollment is restricted to officially registered students.').'<br />');                  $r->print('<h3>'.&mt('Self-enrollment unavailable').'</h3>'.&mt('Self-enrollment is restricted to students officially registered for this course.').'<br />');
                 if ($message) {                  if ($message) {
                     $r->print($message);                      $r->print($message);
                 } else {                  } else {
Line 319  sub process_self_enroll { Line 454  sub process_self_enroll {
                 return;                   return; 
             }               } 
         }          }
         my $enrollresult =           if ($selfenroll_approval) {
             &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,              my $outcome = 
                     undef,undef,$usec,$selfenroll_access_end,$selfenroll_access_start,                    'manual',undef,$cdom.'_'.$cnum,$selfenroll);                  &store_selfenroll_request($udom,$uname,$usec,$cdom,$cnum,
         if ($enrollresult eq 'ok') {                                            $selfenroll_notifylist,$owner);
             my (%userroles,%newrole,%newgroups);              $r->print($outcome);
             my $role = 'st';          } else {
             my $area = '/'.$cdom.'/'.$cnum;              my $enrollresult = 
             my $spec = $role.'.'.$area;                  &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,
             if ($usec ne '') {                          undef,undef,$usec,$selfenroll_access_end,$selfenroll_access_start,
                 $spec .= '/'.$usec;                         'selfenroll',undef,$cdom.'_'.$cnum,$selfenroll);
                 $area .= '/'.$usec;              if ($enrollresult eq 'ok') {
             }                  my (%userroles,%newrole,%newgroups);
             &Apache::lonnet::standard_roleprivs(\%newrole,$role,$cdom,$spec,$cnum,                  my $role = 'st';
                                                 $area);                  my $area = '/'.$cdom.'/'.$cnum;
             &Apache::lonnet::set_userprivs(\%userroles,\%newrole,%newgroups);                  my $spec = $role.'.'.$area;
             $userroles{'user.role.'.$spec} = $selfenroll_access_start.'.'.$selfenroll_access_end;                  if ($usec ne '') {
             &Apache::lonnet::appenv(\%userroles,[$role]);                      $spec .= '/'.$usec;
             if ($selfenroll_access_end && $selfenroll_access_end <= $now) {                      $area .= '/'.$usec;
                 $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.'));                  }
             } else {                  &Apache::lonnet::standard_roleprivs(\%newrole,$role,$cdom,$spec,$cnum,
                 $r->print(&mt('Self-enrollment in this course was successful.').'<br />');                                                      $area);
                 my $showstart = &Apache::lonlocal::locallocaltime($selfenroll_access_start);                  &Apache::lonnet::set_userprivs(\%userroles,\%newrole,%newgroups);
                 my $showend = &Apache::lonlocal::locallocaltime($selfenroll_access_end);                  $userroles{'user.role.'.$spec} = $selfenroll_access_start.'.'.$selfenroll_access_end;
                 if ($selfenroll_access_start && $selfenroll_access_start >$now) {                  &Apache::lonnet::appenv(\%userroles,[$role,'cm']);
                     $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));                  $r->print('<h3>'.&mt('Enrollment process complete').'</h3>');
                   if ($selfenroll_access_end && $selfenroll_access_end <= $now) {
                       $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.'));
                 } else {                  } else {
                     my $newrole = 'st./'.$cdom.'/'.$cnum;                      $r->print(&mt('Self-enrollment in this course was successful.').'<br />');
                     if ($usec ne '') {                      my $showstart = &Apache::lonlocal::locallocaltime($selfenroll_access_start);
                         $newrole .= '/'.$usec;                      my $showend = &Apache::lonlocal::locallocaltime($selfenroll_access_end);
                       if ($selfenroll_access_start && $selfenroll_access_start >$now) {
                           $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));
                       } else {
                           my $newrole = 'st./'.$cdom.'/'.$cnum;
                           if ($usec ne '') {
                               $newrole .= '/'.$usec;
                           }
                           my $rolelink = &jump_to_role($newrole);
                           $r->print(&mt('Your new role is available immediately, and will provide access to the course until [_1].',$showend).'<br /><br />'."\n".
                                    $rolelink); 
                     }                      }
                     my $rolelink = &jump_to_role($newrole);  
                     $r->print(&mt('Your new role is available immediately, and will provide access to the course until [_1].',$showend).'<br /><br />'."\n".  
                              $rolelink);   
                 }                  }
             }              } else {
         } else {                  $r->print('<h3>'.&mt('Enrollment incomplete').'</h3>'.
             $r->print(&mt('Self-enrollment in this course failed.'));                            &mt('Self-enrollment in this course failed.'));
             if ($enrollresult ne '') {                  if ($enrollresult ne '') {
                 $r->print('<span class="LC_error">'.$enrollresult.'</span>');                      $r->print('<span class="LC_error">'.$enrollresult.'</span>');
                   }
             }              }
         }          }
     } else {      } else {
         $r->print(&mt('You are not permitted to enroll yourself in this course.').'<br />');          $r->print('<h3>'.&mt('Self-enrollment unavailable').'</h3>'.
                     &mt('You are not permitted to enroll yourself in this course.').'<br />');
         $r->print(&print_selfenroll_types($longtypes));          $r->print(&print_selfenroll_types($longtypes));
     }      }
     return;      return;
 }  }
   
   sub user_can_selfenroll {
       my ($udom,$uname,$domenrolltypes) = @_;
       my $selfenroll = 0;
       my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'inststatus');
       my @inststatuses;
       if ($userhash{'inststatus'} eq '') {
           push(@inststatuses,'other');
       } else {
           @inststatuses = split(':',$userhash{'inststatus'});
       }
       foreach my $type (@inststatuses) {
           if (ref($domenrolltypes) eq 'ARRAY') {
               if (grep(/^\Q$type\E$/,@{$domenrolltypes})) {
                   $selfenroll = 1;
                   last;
               }
           }
       }
       return $selfenroll;
   }
   
   sub store_selfenroll_request {
       my ($udom,$uname,$usec,$cdom,$cnum,$selfenroll_notifylist,$owner) = @_;
       my $namespace = 'selfenrollrequests';
       my $output;
       my $now = time;
       my %existing = 
           &Apache::lonnet::get($namespace,[$uname.':'.$udom],$cdom,$cnum);
       if ($existing{$uname.':'.$udom}) {
           my ($timestamp,$sec) = split(/:/,$existing{$uname.':'.$udom});
           $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));
       } else {
           my %selfenroll = (
                               $uname.':'.$udom => $now.':'.$usec,
                            );
           my $putresult = &Apache::lonnet::put($namespace,\%selfenroll,$cdom,$cnum);
           if ($putresult eq 'ok') {
               my %userenroll = (
                                  $cdom.'_'.$cnum =>  {
                                                         timestamp => $now,
                                                         section   => $usec,
                                                         status    => 'request', 
                                                      });
               my $warning;
               my $userresult = &Apache::lonnet::put($namespace,\%userenroll,$udom,$uname);
               if ($userresult ne 'ok') {
                   $warning = &mt('An error occurred saving a personal record of your request.');
               }
               $output = &mt('Your request for self-enrollment has been recorded.').'<br />'.
                         &mt('A message will be sent to your LON-CAPA account when the course coordinator takes action on your request.').'<br />'.
                         &mt('To access your LON-CAPA message, go to the Main Menu and click on "Send and Receive Messages".').'<br />';
               my %emails = &Apache::loncommon::getemails($uname,$udom);
               if (($emails{'permanentemail'} ne '') || ($emails{'notification'} ne '')) {
                   my $address = $emails{'permanentemail'};
                   if ($address eq '') {
                       $address = $emails{'notification'};
                   }
                   $output.= &mt('An e-mail will also be sent to: [_1] when this occurs.',$address).'<br />';
               }
               if ($warning) { 
                   $output .= '<span class="LC_warning">'.$warning.'</span><br />';
               }
     
               if ($selfenroll_notifylist) {
                   my $fullname = &Apache::loncommon::plainname($uname,$udom);
                   my %courseinfo = &Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   my $coursedesc = $courseinfo{'description'};
                   &send_notification($selfenroll_notifylist,$fullname,$cdom.
                                      '_'.$cnum,$coursedesc,$now,'request',$owner);
               }
           } else {
               $output = '<span class="LC_error">'.&mt('An error occurred when recording your request.').'</span>';
   
           }
       }
       return $output;
   }
   
   sub send_notification {
       my ($notifylist,$textstr,$cid,$coursedesc,$timestamp,$context,$sender,
           $approvedlist,$rejectedlist) = @_;
   # FIXME locallocaltime needs to be able to take $sender_lh as an argument
   #       so this can be localized to the recipients date display format/time zone 
       $timestamp =&Apache::lonlocal::locallocaltime($timestamp);
       my $msgcc;
       my ($rawsubj,@rawmsg,$subject,$message,$namelink);
       $namelink = &Apache::loncommon::aboutmewrapper(
                   &Apache::loncommon::plainname($env{'user.name'},$env{'user.domain'}));
       if ($context eq 'managers') {
           $rawsubj = 'Self-enrollment requests processed';
           push(@rawmsg,{
                         mt => 'Enrollment requests in the following course: [_1] have been processed.',
                         args => ["\n$coursedesc\n"],
                        });
       } elsif ($context eq 'enroller') {
           $rawsubj = 'Enrollment request';
           push(@rawmsg,{
                         mt  => 'Your request for enrollment in the following course: [_1], requested on [_2], has been reviewed by a Course Coordinator.',
                         args => ["\n$coursedesc\n","$timestamp\n"],
   
                        });
           if (ref($textstr) eq 'ARRAY') {
               push(@rawmsg,@{$textstr});
           }
       } else {
           $rawsubj = 'Self-enrollment request';
           push(@rawmsg,{
                         mt  => 'Enrollment in the following course: [_1] was requested by [_2] on [_3].',
                         args => ["\n$coursedesc\n",$textstr,$timestamp],
                        },
                        {
                         mt =>'As Course Coordinator, use: [_1]Main Menu -> Manage Course Users -> Enrollment Requests[_1] to display a list of pending enrollment requests,[_1] which you can either approve or reject.',
                         args => ["\n"],
                        });
       }
       my @to_notify = split(/,/,$notifylist);
       my $numsent = 0;
       my @recusers;
       my @recudoms;
       foreach my $cc (@to_notify) {
           my ($ccname,$ccdom) = split(/:/,$cc);
           if (!exists($msgcc->{$ccname.':'.$ccdom})) {
               push(@recusers,$ccname);
               push(@recudoms,$ccdom);
               $msgcc->{$ccname.':'.$ccdom}='';
               $numsent ++;
           }
       }
       my %reciphash = (
                        cc => $msgcc,
       );
       my ($uname,$udom);
       if ($sender =~ /:/) {
           ($uname,$udom) = split(/:/,$sender);
       } else {
           $uname = $sender;
           my %courseinfo = &Apache::lonnet::coursedescription($cid);
           $udom = $courseinfo{'num'};
       }
       my %sentmessage;
       my $stamp = time;
       my $msgcount = &Apache::lonmsg::get_uniq();
       my $sender_lh = &Apache::loncommon::user_lang($uname,$udom,$cid);
       $subject = &Apache::lonlocal::mt_user($sender_lh,$rawsubj);
       $message = '';
       foreach my $item (@rawmsg) {
           if (ref($item) eq 'HASH') {
               $message .= &Apache::lonlocal::mt_user($sender_lh,$item->{mt},@{$item->{args}})."\n";
           }
       }
       &Apache::lonmsg::process_sent_mail($subject,'',$numsent,$stamp,$uname,$udom,$msgcount,$cid,$$,$message,\@recusers,\@recudoms);
       my ($recipid,$recipstatus) =
           &Apache::lonmsg::store_recipients($subject,$uname,$udom,\%reciphash);
       foreach my $recip (sort(keys(%{$msgcc}))) {
           my ($ccname,$ccdom) = split(/:/,$recip);
           my $recip_lh = &Apache::loncommon::user_lang($ccname,$ccdom,$cid);
           my $subject = &Apache::lonlocal::mt_user($sender_lh,$rawsubj);
           my $message = '';
           foreach my $item (@rawmsg) {
               if (ref($item) eq 'HASH') {
                   $message .= &Apache::lonlocal::mt_user($sender_lh,$item->{mt},
                                                          @{$item->{args}})."\n";
               }
           }
           if ($context eq 'managers') {
               if ($approvedlist) {
                   $message .= "\n\n".&Apache::lonlocal::mt_user($sender_lh,'Approved enrollments:')."\n".$approvedlist;
               }
               if ($rejectedlist) {
                   $message .= "\n\n".&Apache::lonlocal::mt_user($sender_lh,'Rejected enrollments:')."\n".$rejectedlist;
               }
           }
           my $status = &Apache::lonmsg::user_normal_msg($ccname,$ccdom,$subject,$message,undef,undef,undef,1,\%sentmessage,undef,undef,undef,1,$recipid);
       }
   }
   
 sub jump_to_role {  sub jump_to_role {
     my ($role) = @_;      my ($role) = @_;
     my $output = <<"END";      my $output = <<"END";
Line 379  function SelectRole() { Line 701  function SelectRole() {
 END  END
     $output .= '<a href="javascript:SelectRole()">'."\n".       $output .= '<a href="javascript:SelectRole()">'."\n". 
                &mt('Enter course now').'</a>'."\n".                 &mt('Enter course now').'</a>'."\n".
                '<form name="rolechoice" action="/adm/roles">'."\n".                 '<form name="rolechoice" action="/adm/roles" method="post">'."\n".
                '<input type="hidden" name="selectrole" value="" />'."\n".                 '<input type="hidden" name="selectrole" value="" />'."\n".
                '<input type="hidden" name="'.$role.'" value="1" />'."\n".                 '<input type="hidden" name="'.$role.'" value="1" />'."\n".
                '</form>';                 '</form>';
Line 402  sub get_selfenroll_filters { Line 724  sub get_selfenroll_filters {
         if ($selfdom =~ /^$match_domain$/) {          if ($selfdom =~ /^$match_domain$/) {
             if (&Apache::lonnet::domain($selfdom) ne '') {              if (&Apache::lonnet::domain($selfdom) ne '') {
                 my @types = split(/,/,$type_str);                  my @types = split(/,/,$type_str);
                   my @unesc_types = map { &unescape($_); } @types;
                 my ($othertitle,$usertypes,$types) =                  my ($othertitle,$usertypes,$types) =
                     &Apache::loncommon::sorted_inst_types($selfdom);                      &Apache::loncommon::sorted_inst_types($selfdom);
                 if (ref($usertypes) eq 'HASH') {                  if (ref($usertypes) eq 'HASH') {
                     $usertypes->{'any'} = &mt('any');                      my $anytype = 1;
                     $usertypes->{'other'} = &mt('other');                      foreach my $key (keys(%{$usertypes})) {
                     @{$enrolltypes{$selfdom}} = @types;                          if (!grep(/^\Q$key\E$/,@unesc_types)) {
                     @{$longtypes{$selfdom}} = map {$usertypes->{$_}} @types;                              $anytype = 0;
                               last;
                           }
                       }
                       if ($anytype) {
                           if (!(grep(/^other$/,@types))) {
                               $anytype = 0;
                           }
                       }
                       $usertypes->{'any'} = &mt('Any users');
                       $usertypes->{'other'} = &mt('Others');
                       my @showtypes;
                       if ($anytype) {
                           @{$enrolltypes{$selfdom}} = ('any');
                           @showtypes =  ('any');
                       } else {
                           @{$enrolltypes{$selfdom}} = @types;
                           @showtypes = @unesc_types;
                       }
                       @{$longtypes{$selfdom}} = 
                           map {$usertypes->{$_}} @showtypes;
                 }                  }
             }              }
         }          }
Line 420  sub print_selfenroll_types { Line 763  sub print_selfenroll_types {
     my ($longtypes,$domain) = @_;      my ($longtypes,$domain) = @_;
     my $output;      my $output;
     if (ref($longtypes) eq 'HASH') {      if (ref($longtypes) eq 'HASH') {
         if (keys(%{$longtypes}) > 0) {          if ($domain ne '') {
             if ($domain ne '') {              my $domdesc = &Apache::lonnet::domain($domain,'description');
                 if (ref($longtypes->{$domain}) eq 'ARRAY') {              if (ref($longtypes->{$domain}) eq 'ARRAY') {
                     if (grep(/^any$/,@{$longtypes->{$domain}})) {                  if (grep(/^any$/,@{$longtypes->{$domain}})) {
                         $output = &mt('Self-enrollment in this course is only available to users in domain "[_1]".',$domain);                      $output = &mt('Self-enrollment in this course is available to any user affiliated with [_1].',$domdesc);
                     } else {                  } else {
                         my $status_str = join(', ',@{$longtypes->{$domain}});                      my $status_str = join(', ',@{$longtypes->{$domain}});
                         $output = &mt('Self-enrollment in this course is only available to users in domain "[_1]" who have the following status: "[_2]".',$domain,$status_str);                      $output = &mt('Self-enrollment in this course is only available to users affiliated with [_1] who have the following status: "[_2]".',$domdesc,$status_str);
                     }  
                 }                  }
             } else {              } else {
                 $output = &mt('Self-enrollment in this course is only available to users in the following domains (with the following status):').' <ul>';                  $output = &mt('Self-enrollment is not currently available for this course for users affiliated with [_1].',$domdesc);
                 foreach my $selfdom (sort(keys(%{$longtypes}))) {              }
                     if (ref($longtypes->{$selfdom}) eq 'ARRAY') {          } elsif (keys(%{$longtypes}) > 0) {
                         $output .= '<li>'.$selfdom.': '.join(', ',@{$longtypes->{$selfdom}}).'</li>';              $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";
                     }              foreach my $selfdom (sort(keys(%{$longtypes}))) {
                   my $selfdomdesc = &Apache::lonnet::domain($selfdom,'description');
                   if (ref($longtypes->{$selfdom}) eq 'ARRAY') {
                       $output .= '<li>'.$selfdomdesc.': '.join(', ',@{$longtypes->{$selfdom}}).'</li>'."\n";
                 }                  }
                 $output .= '</ul>';  
             }              }
               $output .= '</ul>'."\n";
         } else {          } else {
             $output = &mt('Self-enrollment is not currently available for this course.');              $output = &mt('Self-enrollment is not currently available for this course.');
         }          }

Removed from v.1.5  
changed lines
  Added in v.1.20


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