File:  [LON-CAPA] / loncom / interface / createaccount.pm
Revision 1.40.2.5.2.9: download - view: text, annotated - select for diffs
Tue Feb 14 16:04:22 2012 UTC (12 years, 3 months ago) by raeburn
Branches: loncapaMITrelate_1
Diff to branchpoint 1.40.2.5: preferred, unified
- Customization for MITrelate.
  - Customized text in e-mail sent containing link used to complete sign-up
     process.

    1: # The LearningOnline Network
    2: # Allow visitors to create a user account with the username being either an 
    3: # institutional log-in ID (institutional authentication required - localauth
    4: #  or kerberos) or an e-mail address.
    5: #
    6: # $Id: createaccount.pm,v 1.40.2.5.2.9 2012/02/14 16:04:22 raeburn Exp $
    7: #
    8: # Copyright Michigan State University Board of Trustees
    9: #
   10: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
   11: #
   12: # LON-CAPA is free software; you can redistribute it and/or modify
   13: # it under the terms of the GNU General Public License as published by
   14: # the Free Software Foundation; either version 2 of the License, or
   15: # (at your option) any later version.
   16: #
   17: # LON-CAPA is distributed in the hope that it will be useful,
   18: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   19: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   20: # GNU General Public License for more details.
   21: #
   22: # You should have received a copy of the GNU General Public License
   23: # along with LON-CAPA; if not, write to the Free Software
   24: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   25: #
   26: # /home/httpd/html/adm/gpl.txt
   27: #
   28: # http://www.lon-capa.org/
   29: #
   30: #
   31: package Apache::createaccount;
   32: 
   33: use strict;
   34: use Apache::Constants qw(:common);
   35: use Apache::lonacc;
   36: use Apache::lonnet;
   37: use Apache::loncommon;
   38: use Apache::lonhtmlcommon;
   39: use Apache::lonlocal;
   40: use Apache::lonauth;
   41: use Apache::resetpw;
   42: use Captcha::reCAPTCHA;
   43: use DynaLoader; # for Crypt::DES version
   44: use Crypt::DES;
   45: use LONCAPA qw(:DEFAULT :match);
   46: use HTML::Entities;
   47: 
   48: sub handler {
   49:     my $r = shift;
   50:     &Apache::loncommon::content_type($r,'text/html');
   51:     $r->send_http_header;
   52:     if ($r->header_only) {
   53:         return OK;
   54:     }
   55: 
   56:     my $domain;
   57: 
   58:     my $sso_username = $r->subprocess_env->get('REDIRECT_SSOUserUnknown');
   59:     my $sso_domain = $r->subprocess_env->get('REDIRECT_SSOUserDomain');
   60:     my $privkey = $r->dir_config('reCAPTCHA_PRIVATE');
   61:     my $pubkey  = $r->dir_config('reCAPTCHA_PUBLIC');
   62: 
   63:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['token','courseid']);
   64:     &Apache::lonacc::get_posted_cgi($r);
   65:     &Apache::lonlocal::get_language_handle($r);
   66: 
   67:     if ($sso_username ne '' && $sso_domain ne '') {
   68:         $domain = $sso_domain; 
   69:     } else {
   70:         $domain = &Apache::lonnet::default_login_domain();
   71:         if (defined($env{'form.courseid'})) {
   72:             if (&validate_course($env{'form.courseid'})) {
   73:                 if ($env{'form.courseid'} =~ /^($match_domain)_($match_courseid)$/) {
   74:                     $domain = $1; 
   75:                 }
   76:             }
   77:         }
   78:     }
   79:     my $domdesc = &Apache::lonnet::domain($domain,'description');
   80:     my $contact_name = &mt('LON-CAPA helpdesk');
   81:     my $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};
   82:     my $contacts =
   83:         &Apache::loncommon::build_recipient_list(undef,'helpdeskmail',
   84:                                                  $domain,$origmail);
   85:     my ($contact_email) = split(',',$contacts);
   86:     my $lonhost = $r->dir_config('lonHostID');
   87:     my $include = $r->dir_config('lonIncludes');
   88:     my $start_page;
   89: 
   90:     my $handle = &Apache::lonnet::check_for_valid_session($r);
   91:     if (($handle ne '') && ($handle !~ /^publicuser_\d+$/)) {
   92:         $start_page =
   93:             &Apache::loncommon::start_page('Already logged in');
   94:         my $end_page =
   95:             &Apache::loncommon::end_page();
   96:         $r->print($start_page."\n".'<h2>'.&mt('You are already logged in').'</h2>'.
   97:                   '<p>'.&mt('Please either [_1]continue the current session[_2] or [_3]log out[_4].','<a href="/adm/roles">','</a>','<a href="/adm/logout">','</a>').
   98:                   '</p><p><a href="/adm/loginproblems.html">'.&mt('Login problems?').'</a></p>'.$end_page);
   99:         return OK;
  100:     }
  101: 
  102:     my ($js,$courseid,$title);
  103:     if (defined($env{'form.courseid'})) {
  104:         $courseid = &validate_course($env{'form.courseid'});
  105:     }
  106:     if ($courseid ne '') {
  107:         $js = &catreturn_js();
  108:         $title = 'Self-enroll in a LON-CAPA course';
  109:     } else {
  110:         $title = 'Create a user account in LON-CAPA';
  111:     }
  112:     if ($env{'form.phase'} eq 'selfenroll_login') {
  113:         $title = 'Self-enroll in a LON-CAPA course';
  114:         if ($env{'form.udom'} ne '') {
  115:             $domain = $env{'form.udom'};
  116:         }
  117: 
  118:         my %domconfig = 
  119:             &Apache::lonnet::get_dom('configuration',['usercreation'],$domain);
  120:         my ($cancreate,$statustocreate) = 
  121:             &get_creation_controls($domain,$domconfig{'usercreation'});
  122: 
  123:         my ($result,$output) =
  124:             &username_validation($r,$env{'form.uname'},$domain,$domdesc,
  125:                                  $contact_name,$contact_email,$courseid,
  126:                                  $lonhost,$statustocreate);
  127:         if ($result eq 'existingaccount') {
  128:             $r->print($output);
  129:             &print_footer($r);
  130:             return OK;
  131:         } else {
  132:             $start_page = 
  133:                 &Apache::loncommon::start_page($title,$js,
  134:                                                {'no_inline_link'   => 1,});
  135:             &print_header($r,$start_page,$courseid);
  136:             $r->print($output);
  137:             &print_footer($r);    
  138:             return OK;
  139:         }
  140:     }
  141:     $start_page =
  142:         &Apache::loncommon::start_page($title,$js,
  143:                                        {'no_inline_link'   => 1,});
  144:     my %domconfig = 
  145:         &Apache::lonnet::get_dom('configuration',['usercreation'],$domain);
  146:     my ($cancreate,$statustocreate) = &get_creation_controls($domain,$domconfig{'usercreation'});
  147:     if (@{$cancreate} == 0) {
  148:         &print_header($r,$start_page,$courseid);
  149:         my $output = '<h3>'.&mt('Account creation unavailable').'</h3>'.
  150:                      '<span class="LC_warning">'.
  151:                      &mt('Creation of a new user account using an e-mail address or an institutional log-in ID as username is not permitted for [_1].',$domdesc).'</span><br /><br />';
  152:         $r->print($output);
  153:         &print_footer($r);
  154:         return OK;
  155:     }
  156: 
  157:     if ($sso_username ne '') {
  158:         &print_header($r,$start_page,$courseid);
  159:         my ($msg,$sso_logout);
  160:         $sso_logout = &sso_logout_frag($r,$domain);
  161:         if (grep(/^sso$/,@{$cancreate})) {
  162:             $msg = '<h3>'.&mt('Account creation').'</h3>'.
  163:                    &mt("Although your username and password were authenticated by your institution's Single Sign On system, you do not currently have a LON-CAPA account at this institution.").'<br />';
  164: 
  165:             $msg .= &username_check($sso_username,$domain,$domdesc,$courseid, 
  166:                                     $lonhost,$contact_email,$contact_name,
  167:                                     $sso_logout,$statustocreate);
  168:         } else {
  169:             $msg = '<h3>'.&mt('Account creation unavailable').'</h3>'.
  170:                    '<span class="LC_warning">'.&mt("Although your username and password were authenticated by your institution's Single Sign On system, you do not currently have a LON-CAPA account at this institution, and you are not permitted to create one.").'</span><br /><br />'.&mt('Please contact the [_1] ([_2]) for assistance.',$contact_name,$contact_email).'<hr />'.
  171:                    $sso_logout;
  172:         }
  173:         $r->print($msg);
  174:         &print_footer($r);
  175:         return OK;
  176:     }
  177: 
  178:     my ($output,$nostart,$noend);
  179:     my $token = $env{'form.token'};
  180:     if ($token) {
  181:         ($output,$nostart,$noend) = 
  182:             &process_mailtoken($r,$token,$contact_name,$contact_email,$domain,
  183:                                $domdesc,$lonhost,$include,$start_page);
  184:         if ($nostart) {
  185:             if ($noend) {
  186:                 return OK;
  187:             } else {
  188:                 $r->print($output);
  189:                 &print_footer($r);
  190:                 return OK;
  191:             }
  192:         } else {
  193:             &print_header($r,$start_page,$courseid);
  194:             $r->print($output);
  195:             &print_footer($r);
  196:             return OK;
  197:         }
  198:     }
  199: 
  200:     if ($env{'form.phase'} eq 'username_activation') {
  201:         (my $result,$output,$nostart) = 
  202:             &username_activation($r,$env{'form.uname'},$domain,$domdesc,
  203:                                  $lonhost,$courseid);
  204:         if ($result eq 'ok') {
  205:             if ($nostart) {
  206:                 return OK;
  207:             }
  208:         }
  209:         &print_header($r,$start_page,$courseid);
  210:         $r->print($output);
  211:         &print_footer($r);
  212:         return OK;
  213:     } elsif ($env{'form.phase'} eq 'username_validation') { 
  214:         (my $result,$output) = 
  215:             &username_validation($r,$env{'form.uname'},$domain,$domdesc,
  216:                                  $contact_name,$contact_email,$courseid,
  217:                                  $lonhost,$statustocreate);
  218:         if ($result eq 'existingaccount') {
  219:             $r->print($output);
  220:             &print_footer($r);
  221:             return OK;
  222:         } else {
  223:             &print_header($r,$start_page,$courseid);
  224:         }
  225:     } elsif ($env{'form.create_with_email'}) {
  226:         &print_header($r,$start_page,$courseid);
  227:         $output = &process_email_request($env{'form.useremail'},$domain,$domdesc,
  228:                                          $contact_name,$contact_email,$cancreate,
  229:                                          $lonhost,$domconfig{'usercreation'},
  230:                                          $courseid,$privkey);
  231:     } elsif (!$token) {
  232:         &print_header($r,$start_page,$courseid);
  233:         my $now=time;
  234:         if (grep(/^login$/,@{$cancreate})) {
  235:             my $jsh=Apache::File->new($include."/londes.js");
  236:             $r->print(<$jsh>);
  237:             $r->print(&javascript_setforms($now));
  238:         }
  239:         if (grep(/^email$/,@{$cancreate})) {
  240:             $r->print(&javascript_validmail());
  241:         }
  242:         $output = &print_username_form($domain,$domdesc,$cancreate,$now,$lonhost,
  243:                                        $courseid,$pubkey);
  244:     }
  245:     $r->print($output);
  246:     &print_footer($r);
  247:     return OK;
  248: }
  249: 
  250: sub get_custom_name {
  251:     my ($domain) = @_;
  252:     if ($domain eq 'relate') {
  253:         return 'Mechanics Online';
  254:     } else {
  255:         return lc($domain);
  256:     }
  257: }
  258: 
  259: sub print_header {
  260:     my ($r,$start_page,$courseid) = @_;
  261:     $r->print($start_page);
  262:     &Apache::lonhtmlcommon::clear_breadcrumbs();
  263:     if ($courseid ne '') {
  264:         my %coursehash = &Apache::lonnet::coursedescription($courseid);
  265:         &selfenroll_crumbs($r,$courseid,$coursehash{'description'});
  266:     }
  267:     &Apache::lonhtmlcommon::add_breadcrumb
  268:     ({href=>"/adm/createuser",
  269:       text=>"New username"});
  270:     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Create account'));
  271:     return;
  272: }
  273: 
  274: sub print_footer {
  275:     my ($r) = @_;
  276:     if ($env{'form.courseid'} ne '') {
  277:         $r->print('<form name="backupcrumbs" method="post" action="">'.
  278:                   &Apache::lonhtmlcommon::echo_form_input(['backto','logtoken',
  279:                       'token','serverid','uname','upass','phase','create_with_email',
  280:                       'code','useremail','crypt','cfirstname','clastname',
  281:                       'cmiddlename','cgeneration','cpermanentemail','cid']).
  282:                   '</form>');
  283:     }
  284:     $r->print(&Apache::loncommon::end_page());
  285: }
  286: 
  287: sub selfenroll_crumbs {
  288:     my ($r,$courseid,$desc) = @_;
  289:     &Apache::lonhtmlcommon::add_breadcrumb
  290:          ({href=>"javascript:ToCatalog('backupcrumbs','')",
  291:            text=>"Course/Community Catalog"});
  292:     if ($env{'form.coursenum'} ne '') {
  293:         &Apache::lonhtmlcommon::add_breadcrumb
  294:           ({href=>"javascript:ToCatalog('backupcrumbs','details')",
  295:             text=>"Course details"});
  296:     }
  297:     my $last_crumb;
  298:     if ($desc ne '') {
  299:         $last_crumb = &mt('Self-enroll in [_1]',"<span class='LC_cusr_emph'>$desc</span>");
  300:     } else {
  301:         $last_crumb = &mt('Self-enroll');
  302:     }
  303:     &Apache::lonhtmlcommon::add_breadcrumb
  304:                    ({href=>"javascript:ToSelfenroll('backupcrumbs')",
  305:                      text=>$last_crumb,
  306:                      no_mt=>"1"});
  307:     return;
  308: }
  309: 
  310: sub validate_course {
  311:     my ($courseid) = @_;
  312:     my ($cdom,$cnum) = ($courseid =~ /^($match_domain)_($match_courseid)$/);
  313:     if (($cdom ne '') && ($cnum ne '')) {
  314:         if (&Apache::lonnet::is_course($cdom,$cnum)) {
  315:             return ($courseid);
  316:         }
  317:     }
  318:     return;
  319: }
  320: 
  321: sub javascript_setforms {
  322:     my ($now) =  @_;
  323:     my $js = <<ENDSCRIPT;
  324:  <script type="text/javascript" language="JavaScript">
  325:     function send() {
  326:         this.document.server.elements.uname.value = this.document.client.elements.uname.value;
  327:         this.document.server.elements.udom.value = this.document.client.elements.udom.value;
  328:         uextkey=this.document.client.elements.uextkey.value;
  329:         lextkey=this.document.client.elements.lextkey.value;
  330:         initkeys();
  331: 
  332:         this.document.server.elements.upass.value
  333:             = crypted(this.document.client.elements.upass$now.value);
  334: 
  335:         this.document.client.elements.uname.value='';
  336:         this.document.client.elements.upass$now.value='';
  337: 
  338:         this.document.server.submit();
  339:         return false;
  340:     }
  341:  </script>
  342: ENDSCRIPT
  343:     return $js;
  344: }
  345: 
  346: sub javascript_checkpass {
  347:     my ($now) = @_;
  348:     my $nopass = &mt('You must enter a password.');
  349:     my $mismatchpass = &mt('The passwords you entered did not match.').'\\n'.
  350:                        &mt('Please try again.'); 
  351:     my $js = <<"ENDSCRIPT";
  352: <script type="text/javascript" language="JavaScript">
  353:     function checkpass() {
  354:         var upass = this.document.client.elements.upass$now.value;
  355:         var upasscheck = this.document.client.elements.upasscheck$now.value;
  356:         if (upass == '') {
  357:             alert("$nopass");
  358:             return false;
  359:         }
  360:         if (upass == upasscheck) {
  361:             this.document.client.elements.upasscheck$now.value='';
  362:             send();
  363:             return false;
  364:         } else {
  365:             alert("$mismatchpass");
  366:             return false;
  367:         }
  368:     }
  369: </script>
  370: ENDSCRIPT
  371:     return $js;
  372: }
  373: 
  374: sub javascript_validmail {
  375:     my %lt = &Apache::lonlocal::texthash (
  376:                email => 'The e-mail address you entered',
  377:                notv  => 'is not a valid e-mail address',
  378:     );
  379:     my $output =  "\n".'<script type="text/javascript">'."\n".
  380:                   &Apache::lonhtmlcommon::javascript_valid_email()."\n";
  381:     $output .= <<"ENDSCRIPT";
  382: function validate_email() {
  383:     field = document.createaccount.useremail;
  384:     if (validmail(field) == false) {
  385:         alert("$lt{'email'}: "+field.value+" $lt{'notv'}.");
  386:         return false;
  387:     } else {
  388:        var emailaddr = field.value;
  389:        var lcemail = emailaddr.toLowerCase();
  390:        if (emailaddr != lcemail) {
  391:            field.value = lcemail;
  392:            alert("Mechanics Online usernames are all lower case.\\nAccordingly your username will be "+lcemail+" once activated.");
  393:        }
  394:     }
  395:     return true;
  396: }
  397: ENDSCRIPT
  398:     $output .= "\n".'</script>'."\n";
  399:     return $output;
  400: }
  401: 
  402: sub print_username_form {
  403:     my ($domain,$domdesc,$cancreate,$now,$lonhost,$courseid,$pubkey) = @_;
  404:     my %lt = &Apache::lonlocal::texthash (
  405:         unam   => 'username',
  406:         udom   => 'domain',
  407:         uemail => 'E-mail address in LON-CAPA',
  408:         proc   => 'Proceed',
  409:         crea   => 'Create account with a username provided by this institution',
  410:         crlc   => 'Create LON-CAPA account',
  411:         type   => 'Type in your log-in ID and password to find out.',
  412:         plse   => 'Please enter a valid e-mail address below.',
  413:         inst   => 'Instructions on how to activate your account will be sent to the e-mail address you provide.',
  414:         aftr   => 'After completing the activation process you will have access to a "self test" that will help you assess your readiness for the course.',
  415:         thes   => 'The same account will be used for access to the Mechanics Online course, once it becomes available on March 1, 2012.',
  416:     );
  417:     my $output;
  418:     if (ref($cancreate) eq 'ARRAY') {
  419:         if (grep(/^login$/,@{$cancreate})) {
  420:             my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
  421:             if ((($domdefaults{'auth_def'} =~/^krb/) && ($domdefaults{'auth_arg_def'} ne '')) || ($domdefaults{'auth_def'} eq 'localauth')) {
  422:                 $output = '<div class="LC_left_float"><h3>'.$lt{'crea'}.'</h3>';
  423:                 my $submit_text = $lt{'crlc'};
  424:                 $output .= &mt('If you already have a log-in ID at this institution,[_1] you may be able to use it for LON-CAPA.','<br />').
  425:                            '<br /><br />'.$lt{'type'}.'<br /><br />';
  426:                 $output .= &login_box($now,$lonhost,$courseid,$submit_text,
  427:                                       $domain,'createaccount').'</div>';
  428:             }
  429:         }
  430:         if (grep(/^email$/,@{$cancreate})) {
  431:             $output .= '<div class="LC_left_float"><h3>'.&mt('Create account with an e-mail address as your username').'</h3>'.
  432:                         '<p class="LC_info">'.
  433:                         &mt('You are about to sign-up for the [_1]Mechanics Online[_2] course.','<em>','</em>').'<br />'.
  434:                         $lt{'plse'}.'</p><ul>'.
  435:                         '<li>'.$lt{'inst'}.'</li>'.
  436:                         '<li>'.$lt{'aftr'}.'</li>'.
  437:                         '<li>'.$lt{'thes'}.'</li></ul>';
  438:             my $captchaform = &create_recaptcha($pubkey);
  439:             if ($captchaform) {
  440:                 my $submit_text = &mt('Sign-up');
  441:                 my $emailform = '<input type="text" name="useremail" size="25" value="" />';
  442:                 if (grep(/^login$/,@{$cancreate})) {
  443:                     $output .= &mt('Provide your e-mail address to sign up for a Mechanics Online account [_1]if you do not have a log-in ID at your institution.','<br />').'<br /><br />';
  444:                 } else {
  445:                     $output .= '<br />';
  446:                 }
  447:                 $output .=  '<form name="createaccount" method="post" onsubmit="return validate_email()" action="/adm/createaccount">'.
  448:                             &Apache::lonhtmlcommon::start_pick_box()."\n".
  449:                             &Apache::lonhtmlcommon::row_title(&mt('E-mail address'),
  450:                                                              'LC_pick_box_title')."\n".
  451:                             $emailform."\n".
  452:                             &Apache::lonhtmlcommon::row_closure(1).
  453:                             &Apache::lonhtmlcommon::row_title(&mt('Validation'),
  454:                                                              'LC_pick_box_title')."\n".
  455:                             $captchaform."\n".
  456:                             &mt('If either word is hard to read, [_1] will replace them.','<image src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').'<br /><br />';
  457:                 if ($courseid ne '') {
  458:                     $output .= '<input type="hidden" name="courseid" value="'.$courseid.'"/>'."\n"; 
  459:                 }
  460:                 $output .=  &Apache::lonhtmlcommon::row_closure(1).
  461:                             &Apache::lonhtmlcommon::row_title().'<br />'.
  462:                             '<input type="submit" name="create_with_email" value="'. 
  463:                             $submit_text.'" />'.
  464:                             &Apache::lonhtmlcommon::row_closure(1).
  465:                             &Apache::lonhtmlcommon::end_pick_box().'<br /><br />';
  466:                 if ($courseid ne '') {
  467:                     $output .= &Apache::lonhtmlcommon::echo_form_input(['courseid']);
  468:                 }
  469:                 $output .= '</form>';
  470:             } else {
  471:                 my $helpdesk = '/adm/helpdesk?origurl=%2fadm%2fcreateaccount';
  472:                 if ($courseid ne '') {
  473:                     $helpdesk .= '&courseid='.$courseid;
  474:                 }
  475:                 $output .= '<span class="LC_error">'.&mt('An error occurred generating the validation code[_1] required for an e-mail address to be used as username.','<br />').'</span><br /><br />'.&mt('[_1]Contact the helpdesk[_2] or [_3]reload[_2] the page and try again.','<a href="'.$helpdesk.'">','</a>','<a href="javascript:window.location.reload()">');
  476:             }
  477:             $output .= '</div>';
  478:         }
  479:     }
  480:     if ($output eq '') {
  481:         $output = &mt('Creation of a new LON-CAPA user account using an e-mail address or an institutional log-in ID as your username is not permitted at [_1].',$domdesc);
  482:     } else {
  483:         $output .= '<div class="LC_clear_float_footer"></div>';
  484:     }
  485:     return $output;
  486: }
  487: 
  488: sub login_box {
  489:     my ($now,$lonhost,$courseid,$submit_text,$domain,$context) = @_;
  490:     my $output;
  491:     my %titles = &Apache::lonlocal::texthash(
  492:                                               createaccount => 'Log-in ID',
  493:                                               selfenroll    => 'Username',
  494:                                             );
  495:     my ($lkey,$ukey) = &Apache::lonpreferences::des_keys();
  496:     my ($lextkey,$uextkey) = &getkeys($lkey,$ukey);
  497:     my $logtoken=Apache::lonnet::reply('tmpput:'.$ukey.$lkey.'&createaccount:createaccount',
  498:                                        $lonhost);
  499:     $output = &serverform($logtoken,$lonhost,undef,$courseid,$context);
  500:     my $unameform = '<input type="text" name="uname" size="20" value="" />';
  501:     my $upassform = '<input type="password" name="upass'.$now.'" size="20" />';
  502:     $output .= '<form name="client" method="post" action="" onsubmit="return(send());">'."\n".
  503:                '<input type="hidden" name="udom" value="'.$domain.'" />'.
  504:                &Apache::lonhtmlcommon::start_pick_box()."\n".
  505:                &Apache::lonhtmlcommon::row_title($titles{$context},
  506:                                                  'LC_pick_box_title')."\n".
  507:                $unameform."\n".
  508:                &Apache::lonhtmlcommon::row_closure(1)."\n".
  509:                &Apache::lonhtmlcommon::row_title(&mt('Password'),
  510:                                                 'LC_pick_box_title')."\n".
  511:                $upassform.
  512:                &Apache::lonhtmlcommon::row_closure(1).
  513:                &Apache::lonhtmlcommon::row_title().
  514:                '<br /><input type="submit" name="username_validation" value="'.
  515:                $submit_text.'" />'."\n";
  516:     if ($context eq 'selfenroll') {
  517:         $output .= '<br /><br /><table width="100%"><tr><td align="right">'.
  518:                    '<span class="LC_fontsize_medium">'.
  519:                    '<a href="/adm/resetpw">'.&mt('Forgot password?').'</a>'.
  520:                    '</span></td></tr></table>'."\n";
  521:     }
  522:     $output .= &Apache::lonhtmlcommon::row_closure(1)."\n".
  523:                &Apache::lonhtmlcommon::end_pick_box().'<br />'."\n";
  524:     $output .= '<input type="hidden" name="lextkey" value="'.$lextkey.'" />'."\n".
  525:                '<input type="hidden" name="uextkey" value="'.$uextkey.'" />'."\n".
  526:                '</form>';
  527:     return $output;
  528: }
  529: 
  530: sub process_email_request {
  531:     my ($useremail,$domain,$domdesc,$contact_name,$contact_email,$cancreate,
  532:         $server,$settings,$courseid,$privkey) = @_;
  533:     $useremail = lc($env{'form.useremail'});
  534:     my $output;
  535:     if (ref($cancreate) eq 'ARRAY') {
  536:         if (!grep(/^email$/,@{$cancreate})) {
  537:             $output = &invalid_state('noemails',$domdesc,
  538:                                      $contact_name,$contact_email);
  539:             return $output;
  540:         } elsif ($useremail !~ /^[^\@]+\@[^\@]+\.[^\@\.]+$/) {
  541:             $output = &invalid_state('baduseremail',$domdesc,
  542:                                      $contact_name,$contact_email);
  543:             return $output;
  544:         } else {
  545:             my $uhome = &Apache::lonnet::homeserver($useremail,$domain);
  546:             if ($uhome ne 'no_host') {
  547:                 $output = &invalid_state('existinguser',$domdesc,
  548:                                          $contact_name,$contact_email,'',$useremail);
  549:                 return $output;
  550:             } else {
  551:                  my $captcha = Captcha::reCAPTCHA->new;
  552:                  my $captcha_result =
  553:                      $captcha->check_answer(
  554:                                             $privkey,
  555:                                             $ENV{'REMOTE_ADDR'},
  556:                                             $env{'form.recaptcha_challenge_field'},
  557:                                             $env{'form.recaptcha_response_field'},
  558:                                            );
  559:                 # PRIVATE key from https://www.google.com/recaptcha
  560:                 if (!$captcha_result->{is_valid}) {
  561:                     $output = &invalid_state('captcha',$domdesc,$contact_name,
  562:                                              $contact_email);
  563: 
  564:                     return $output;
  565:                 }
  566:                 my $uhome=&Apache::lonnet::homeserver($useremail,$domain);
  567:                 if ($uhome eq 'no_host') {
  568:                     my (%rulematch,%inst_results,%curr_rules,%got_rules,%alerts);
  569:                     &call_rulecheck($useremail,$domain,\%alerts,\%rulematch,
  570:                                     \%inst_results,\%curr_rules,\%got_rules,'username');
  571:                     if (ref($alerts{'username'}) eq 'HASH') {
  572:                         if (ref($alerts{'username'}{$domain}) eq 'HASH') {
  573:                             if ($alerts{'username'}{$domain}{$useremail}) {
  574:                                 $output = &invalid_state('userrules',$domdesc,
  575:                                                          $contact_name,$contact_email);
  576:                                 return $output;
  577:                             }
  578:                         }
  579:                     }
  580:                     my $format_msg = 
  581:                         &guest_format_check($useremail,$domain,$cancreate,
  582:                                             $settings);
  583:                     if ($format_msg) {
  584:                         $output = &invalid_state('userformat',$domdesc,$contact_name,
  585:                                                  $contact_email,$format_msg);
  586:                         return $output;
  587:                     }
  588:                 }
  589:             }
  590:         }
  591:         $output = &send_token($domain,$useremail,$server,$domdesc,$contact_name,
  592:                           $contact_email,$courseid);
  593:     }
  594:     return $output;
  595: }
  596: 
  597: sub call_rulecheck {
  598:     my ($uname,$udom,$alerts,$rulematch,$inst_results,$curr_rules,
  599:         $got_rules,$tocheck) = @_;
  600:     my ($checkhash,$checks);
  601:     $checkhash->{$uname.':'.$udom} = { 'newuser' => 1, };
  602:     if ($tocheck eq 'username') {
  603:         $checks = { 'username' => 1 };
  604:     }
  605:     &Apache::loncommon::user_rule_check($checkhash,$checks,
  606:            $alerts,$rulematch,$inst_results,$curr_rules,
  607:            $got_rules);
  608:     return;
  609: }
  610: 
  611: sub send_token {
  612:     my ($domain,$email,$server,$domdesc,$contact_name,$contact_email,$courseid) = @_;
  613:     my $msg = '<h3>'.&mt('Account creation status').'</h3>'.
  614:               &mt('Thank you for your request to create a new LON-CAPA account.').
  615:               '<br /><br />';
  616:     my $now = time;
  617:     my %info = ('ip'         => $ENV{'REMOTE_ADDR'},
  618:                 'time'       => $now,
  619:                 'domain'     => $domain,
  620:                 'username'   => $email,
  621:                 'courseid'   => $courseid);
  622:     my $token = &Apache::lonnet::tmpput(\%info,$server,'createaccount');
  623:     if ($token !~ /^error/ && $token ne 'no_such_host') {
  624:         my $esc_token = &escape($token);
  625:         my $mailsubj = &mt('Your Mechanics Online Course Account');
  626:         my $msgfrom  = &mt('Mechanics Online Course Staff');
  627:         my $mailmsg =  &mt('Greetings.')."\n\n".
  628:                        &mt('Thank you for your interest in our Online Mechanics Course.').
  629:                        ' '.
  630:                        &mt('In order to complete the registration process, please open the following link in your web browser:').
  631:                        "\n\n".
  632:                        &Apache::lonnet::absolute_url().'/adm/createaccount?token='.$esc_token).
  633:                        "\n\n".
  634:                        &mt('This link will take you to a sign-up page where you will be asked to provide some general information and finalize the registration process.').
  635:                        ' '.
  636:                        &mt('The course will begin on March 1st, and until that date, a self-test will be available for you to test your level of preparation for our course.').
  637:                        ' '.
  638:                        &mt('The self-test is an integral part of the course, and should be completed by the March 1st start date.').
  639:                        "\n\n".
  640:                        &mt('Best Regards,').
  641:                        "\n\n".
  642:                        &mt('RELATE Group')."\n";
  643: 
  644:         my $result = &Apache::resetpw::send_mail('MIT',$email,$mailmsg,
  645:                                                  $msgfrom,$contact_email,
  646:                                                  $mailsubj);
  647:         if ($result eq 'ok') {
  648:             $msg .= &mt('A message has been sent to the e-mail address you provided.').'<br />'.&mt('The message includes the web address for the link you will use to complete the sign-up process.').'<br />'.&mt("The link included in the message will be valid for the next [_1]two[_2] hours.",'<b>','</b>');
  649:         } else {
  650:             $msg .= '<span class="LC_error">'.
  651:                     &mt('An error occurred when sending a message to the e-mail address you provided.').'</span><br />'.
  652:                     ' '.&mt('Please contact the [_1] ([_2]) for assistance.',$contact_name,$contact_email);
  653:         }
  654:     } else {
  655:         $msg .= '<span class="LC_error">'.
  656:                 &mt('An error occurred creating a token required for the account creation process.').'</span><br />'.
  657:                 ' '.&mt('Please contact the [_1] ([_2]) for assistance.',$contact_name,$contact_email);
  658:     }
  659:     return $msg;
  660: }
  661: 
  662: sub process_mailtoken {
  663:     my ($r,$token,$contact_name,$contact_email,$domain,$domdesc,$lonhost,
  664:         $include,$start_page) = @_;
  665:     my ($msg,$nostart,$noend);
  666:     my %data = &Apache::lonnet::tmpget($token);
  667:     my $now = time;
  668:     if (keys(%data) == 0) {
  669:         $msg = &mt('Sorry, the URL you provided to complete creation of a new LON-CAPA account was invalid.')
  670:                .' '.&mt('Either the token included in the URL has been deleted or the URL you provided was invalid.')
  671:                .' '.&mt('Please submit a [_1]new request[_2] for account creation and follow the new link page included in the e-mail that will be sent to you.','<a href="/adm/createaccount">','</a>');
  672:         return $msg;
  673:     }
  674:     if (($data{'time'} =~ /^\d+$/) &&
  675:         ($data{'domain'} ne '') &&
  676:         ($data{'username'}  =~ /^[^\@]+\@[^\@]+\.[^\@\.]+$/)) {
  677:         if ($now - $data{'time'} < 7200) {
  678:             if ($env{'form.phase'} eq 'createaccount') {
  679:                 my ($result,$output) = &create_account($r,$domain,$lonhost,
  680:                                                        $data{'username'},$domdesc);
  681:                 if ($result eq 'ok') {
  682:                     $msg = $output; 
  683:                     my $shownow = &Apache::lonlocal::locallocaltime($now);
  684:                     my $mailmsg = &mt('A [_1] account has been created [_2] from IP address: [_3].  If you did not perform this action or authorize it, please contact the [_4] ([_5]).',$domdesc,$shownow,$ENV{'REMOTE_ADDR'},$contact_name,$contact_email)."\n";
  685:                     my $mailresult = &Apache::resetpw::send_mail($domdesc,$data{'email'},
  686:                                                                  $mailmsg,$contact_name,
  687:                                                                  $contact_email);
  688:                     if ($mailresult eq 'ok') {
  689:                         $msg .= &mt('An e-mail confirming creation of your new LON-CAPA account has been sent to [_1].',$data{'username'});
  690:                     } else {
  691:                         $msg .= &mt('An error occurred when sending e-mail to [_1] confirming creation of your LON-CAPA account.',$data{'username'});
  692:                     }
  693:                     my %form = &start_session($r,$data{'username'},$domain, 
  694:                                               $lonhost,$data{'courseid'},
  695:                                               $token);
  696:                     $nostart = 1;
  697:                     $noend = 1;
  698:                 } else {
  699:                     $msg .= &mt('A problem occurred when attempting to create your new LON-CAPA account.')
  700:                            .'<br />'.$output
  701: #                           .&mt('Please contact the [_1] ([_2]) for assistance.',$contact_name,'<a href="mailto:'.$contact_email.'">'.$contact_email.'</a>');
  702:                            .&mt('Please contact the [_1] ([_2]) for assistance.',$contact_name,$contact_email);
  703:                 }
  704:                 my $delete = &Apache::lonnet::tmpdel($token);
  705:             } else {
  706:                 $msg .= &mt('Please provide user information and a password for your new account.').'<br />'.&mt('Your password, which must contain at least seven characters, will be sent to the LON-CAPA server in an encrypted form.').'<br />';
  707:                 $msg .= &print_dataentry_form($r,$domain,$lonhost,$include,$token,$now,$data{'username'},$start_page);
  708:                 $nostart = 1;
  709:             }
  710:         } else {
  711:             $msg = &mt('Sorry, the token generated when you requested creation of an account has expired.')
  712:                   .' '.&mt('Please submit a [_1]new request[_2] for account creation and follow the new link included in the e-mail that will be sent to you.','<a href="/adm/createaccount">','</a>');
  713:             }
  714:     } else {
  715:         $msg .= &mt('Sorry, the URL generated when you requested creation of an account contained incomplete information.')
  716:                .' '.&mt('Please submit a [_1]new request[_2] for account creation and follow the new link included in the e-mail that will be sent to you.','<a href="/adm/createaccount">','</a>');
  717:     }
  718:     return ($msg,$nostart,$noend);
  719: }
  720: 
  721: sub start_session {
  722:     my ($r,$username,$domain,$lonhost,$courseid,$token) = @_;
  723:     my %form = (
  724:                 uname => $username,
  725:                 udom  => $domain,
  726:                );
  727:     my $firsturl = '/adm/roles';
  728:     if (defined($courseid)) {
  729:         $courseid = &validate_course($courseid);
  730:         if ($courseid ne '') {
  731:             $form{'courseid'} = $courseid;
  732:             $firsturl = '/adm/selfenroll?courseid='.$courseid;
  733:         }
  734:     }
  735:     if ($r->dir_config('lonBalancer') eq 'yes') {
  736:         &Apache::lonauth::success($r,$form{'uname'},$form{'udom'},
  737:                                   $lonhost,'noredirect',undef,\%form);
  738:         if ($token ne '') { 
  739:             my $delete = &Apache::lonnet::tmpdel($token);
  740:         }
  741:         $r->internal_redirect('/adm/switchserver');
  742:     } else {
  743:         &Apache::lonauth::success($r,$form{'uname'},$form{'udom'},
  744:                                   $lonhost,$firsturl,undef,\%form);
  745:     }
  746:     return %form;
  747: }
  748: 
  749: 
  750: sub print_dataentry_form {
  751:     my ($r,$domain,$lonhost,$include,$mailtoken,$now,$username,$start_page) = @_;
  752:     my ($error,$output);
  753:     &print_header($r,$start_page);
  754:     if (open(my $jsh,"<$include/londes.js")) {
  755:         while(my $line = <$jsh>) {
  756:             $r->print($line);
  757:         }
  758:         close($jsh);
  759:         $output .= &javascript_setforms($now)."\n".&javascript_checkpass($now);
  760:         my ($lkey,$ukey) = &Apache::lonpreferences::des_keys();
  761:         my ($lextkey,$uextkey) = &getkeys($lkey,$ukey);
  762:         my $logtoken=Apache::lonnet::reply('tmpput:'.$ukey.$lkey.'&createaccount:createaccount',
  763:                                            $lonhost);
  764:         my $formtag = '<form name="server" method="post" target="_top" action="/adm/createaccount">';
  765:         my ($datatable,$rowcount) =
  766:             &Apache::loncreateuser::personal_data_display($username,$domain,
  767:                                                           'email','selfcreate');
  768:         if ($rowcount) {
  769:             $output .= '<div class="LC_left_float">'.$formtag.$datatable;
  770:         } else {
  771:             $output .= $formtag;
  772:         }
  773:         $output .= <<"ENDSERVERFORM";
  774:    <input type="hidden" name="logtoken" value="$logtoken" />
  775:    <input type="hidden" name="token" value="$mailtoken" />
  776:    <input type="hidden" name="serverid" value="$lonhost" />
  777:    <input type="hidden" name="uname" value="" />
  778:    <input type="hidden" name="upass" value="" />
  779:    <input type="hidden" name="udom" value="" />
  780:    <input type="hidden" name="phase" value="createaccount" />
  781:   </form>
  782: ENDSERVERFORM
  783:         if ($rowcount) {
  784:             $output .= '</div>'.
  785:                        '<div class="LC_left_float">';
  786:         }
  787:         my $upassone = '<input type="password" name="upass'.$now.'" size="10" />';
  788:         my $upasstwo = '<input type="password" name="upasscheck'.$now.'" size="10" />';
  789:         my $submit_text = &mt('Create LON-CAPA account');
  790:         $output .= '<h3>'.&mt('Login Data').'</h3>'."\n".
  791:                    '<form name="client" method="post" action="" '.
  792:                    'onsubmit="return checkpass();">'."\n".
  793:                    &Apache::lonhtmlcommon::start_pick_box()."\n".
  794:                    &Apache::lonhtmlcommon::row_title(&mt('Username'),
  795:                                                      'LC_pick_box_title',
  796:                                                      'LC_oddrow_value')."\n".
  797:                    $username."\n".
  798:                    &Apache::lonhtmlcommon::row_closure(1)."\n".
  799:                    &Apache::lonhtmlcommon::row_title(&mt('Password'),
  800:                                                     'LC_pick_box_title',
  801:                                                     'LC_oddrow_value')."\n".
  802:                    $upassone."\n".
  803:                    &Apache::lonhtmlcommon::row_closure(1)."\n".
  804:                    &Apache::lonhtmlcommon::row_title(&mt('Confirm password'),
  805:                                                      'LC_pick_box_title',
  806:                                                      'LC_oddrow_value')."\n".
  807:                    $upasstwo.
  808:                    &Apache::lonhtmlcommon::row_closure(1)."\n".
  809:                    &Apache::lonhtmlcommon::row_title()."\n".
  810:                    '<br /><input type="submit" name="createaccount" value="'.
  811:                    $submit_text.'" />'.
  812:                    &Apache::lonhtmlcommon::row_closure(1)."\n".
  813:                    &Apache::lonhtmlcommon::end_pick_box()."\n".
  814:                    '<input type="hidden" name="uname" value="'.$username.'" />'."\n".
  815:                    '<input type="hidden" name="udom" value="'.$domain.'" />'."\n".
  816:                    '<input type="hidden" name="lextkey" value="'.$lextkey.'" />'."\n".
  817:                    '<input type="hidden" name="uextkey" value="'.$uextkey.'" />'."\n".
  818:                    '</form>';
  819:         if ($rowcount) {
  820:             $output .= '</div>'."\n".
  821:                        '<div class="LC_clear_float_footer"></div>'."\n";
  822:         }
  823:     } else {
  824:         $output = &mt('Could not load javascript file [_1]','<tt>londes.js</tt>');
  825:     }
  826:     return $output;
  827: }
  828: 
  829: sub get_creation_controls {
  830:     my ($domain,$usercreation) = @_;
  831:     my (@cancreate,@statustocreate);
  832:     if (ref($usercreation) eq 'HASH') {
  833:         if (ref($usercreation->{'cancreate'}) eq 'HASH') {
  834:             if (ref($usercreation->{'cancreate'}{'statustocreate'}) eq 'ARRAY') {
  835:                 @statustocreate = @{$usercreation->{'cancreate'}{'statustocreate'}};
  836:                 if (@statustocreate == 0) {
  837:                     my ($othertitle,$usertypes,$types) =
  838:                         &Apache::loncommon::sorted_inst_types($domain);
  839:                     if (ref($types) eq 'ARRAY') {
  840:                         if (@{$types} == 0) {
  841:                             @statustocreate = ('default');
  842:                         }
  843:                     } else {
  844:                         @statustocreate = ('default');
  845:                     }
  846:                 }
  847:             } else {
  848:                 @statustocreate = ('default');
  849:                 my ($othertitle,$usertypes,$types) =
  850:                     &Apache::loncommon::sorted_inst_types($domain);
  851:                 if (ref($types) eq 'ARRAY') {
  852:                     push(@statustocreate,@{$types});
  853:                 }
  854:             }
  855:             if (ref($usercreation->{'cancreate'}{'selfcreate'}) eq 'ARRAY') {
  856:                 @cancreate = @{$usercreation->{'cancreate'}{'selfcreate'}};
  857:             } elsif (($usercreation->{'cancreate'}{'selfcreate'} ne 'none') &&
  858:                      ($usercreation->{'cancreate'}{'selfcreate'} ne '')) {
  859:                 @cancreate = ($usercreation->{'cancreate'}{'selfcreate'});
  860:             }
  861:         }
  862:     }
  863:     return (\@cancreate,\@statustocreate);
  864: }
  865: 
  866: sub create_account {
  867:     my ($r,$domain,$lonhost,$username,$domdesc) = @_;
  868:     my ($retrieved,$output,$upass) = &process_credentials($env{'form.logtoken'},
  869:                                                           $env{'form.serverid'}); 
  870:     # Error messages
  871:     my $error     = '<span class="LC_error">'.&mt('Error:').' ';
  872:     my $end       = '</span><br /><br />';
  873:     my $rtnlink   = '<a href="javascript:history.back();" />'.
  874:                     &mt('Return to previous page').'</a>'.
  875:                     &Apache::loncommon::end_page();
  876:     if ($retrieved eq 'ok') {
  877:         if ($env{'form.courseid'} ne '') {
  878:             my ($result,$userchkmsg) = &check_id($username,$domain,$domdesc);
  879:             if ($result eq 'fail') {
  880:                 $output = $error.&mt('Invalid ID format').$end.
  881:                           $userchkmsg.$rtnlink;
  882:                 return ('fail',$output);
  883:             }
  884:         }
  885:     } else {
  886:         return ('fail',$error.$output.$end.$rtnlink);
  887:     }
  888:     # Call modifyuser
  889:     my $result = 
  890:         &Apache::lonnet::modifyuser($domain,$username,$env{'form.cid'},
  891:                                     'internal',$upass,$env{'form.cfirstname'},
  892:                                     $env{'form.cmiddlename'},$env{'form.clastname'},
  893:                                     $env{'form.cgeneration'},undef,undef,$username);
  894:     $output = &mt('Generating user: [_1]',$result);
  895:     my $uhome = &Apache::lonnet::homeserver($username,$domain);
  896:     $output .= '<br />'.&mt('Home server: [_1]',$uhome).' '.
  897:               &Apache::lonnet::hostname($uhome).'<br /><br />';
  898:     return ('ok',$output);
  899: }
  900: 
  901: sub username_validation {
  902:     my ($r,$username,$domain,$domdesc,$contact_name,$contact_email,$courseid,
  903:         $lonhost,$statustocreate) = @_;
  904:     my ($retrieved,$output,$upass);
  905: 
  906:     $username= &LONCAPA::clean_username($username);
  907:     $domain = &LONCAPA::clean_domain($domain);
  908:     my $uhome = &Apache::lonnet::homeserver($username,$domain);
  909: 
  910:     ($retrieved,$output,$upass) = &process_credentials($env{'form.logtoken'},
  911:                                                        $env{'form.serverid'});
  912:     if ($retrieved ne 'ok') {
  913:         return ('fail',$output);
  914:     }
  915:     if ($uhome ne 'no_host') {
  916:         my $result = &Apache::lonnet::authenticate($username,$upass,$domain);
  917:         if ($result ne 'no_host') { 
  918:             my %form = &start_session($r,$username,$domain,$lonhost,$courseid);
  919:             $output = '<br /><br />'.&mt('A LON-CAPA account already exists for username [_1] at this institution ([_2]).','<tt>'.$username.'</tt>',$domdesc).'<br />'.&mt('The password entered was also correct so you have been logged in.');
  920:             return ('existingaccount',$output);
  921:         } else {
  922:             $output = &login_failure_msg($courseid);
  923:         }
  924:     } else {
  925:         my $primlibserv = &Apache::lonnet::domain($domain,'primary');
  926:         my $authok;
  927:         my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
  928:         if ((($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) || ($domdefaults{'auth_def'} eq 'localauth')) {
  929:             my $checkdefauth = 1;
  930:             $authok = 
  931:                 &Apache::lonnet::reply("encrypt:auth:$domain:$username:$upass:$checkdefauth",$primlibserv);
  932:         } else {
  933:             $authok = 'non_authorized';
  934:         }
  935:         if ($authok eq 'authorized') {
  936:             $output = &username_check($username,$domain,$domdesc,$courseid,$lonhost,
  937:                                       $contact_email,$contact_name,undef,
  938:                                       $statustocreate);
  939:         } else {
  940:             $output = &login_failure_msg($courseid);
  941:         }
  942:     }
  943:     return ('ok',$output);
  944: }
  945: 
  946: sub login_failure_msg {
  947:     my ($courseid) = @_;
  948:     my $url;
  949:     if ($courseid ne '') {
  950:         $url = "/adm/selfenroll?courseid=".$courseid;
  951:     } else {
  952:         $url = "/adm/createaccount";
  953:     }
  954:     my $output = '<h4>'.&mt('Authentication failed').'</h4><div class="LC_warning">'.
  955:                  &mt('Username and/or password could not be authenticated.').
  956:                  '</div>'.
  957:                  &mt('Please check the username and password.').'<br /><br />';
  958:                  '<a href="'.$url.'">'.&mt('Try again').'</a>';
  959:     return $output;
  960: }
  961: 
  962: sub username_check {
  963:     my ($username,$domain,$domdesc,$courseid,$lonhost,$contact_email,
  964:         $contact_name,$sso_logout,$statustocreate) = @_;
  965:     my (%rulematch,%inst_results,$checkfail,$rowcount,$editable,$output,$msg,
  966:         %alerts,%curr_rules,%got_rules);
  967:     &call_rulecheck($username,$domain,\%alerts,\%rulematch,
  968:                     \%inst_results,\%curr_rules,\%got_rules,'username');
  969:     if (ref($alerts{'username'}) eq 'HASH') {
  970:         if (ref($alerts{'username'}{$domain}) eq 'HASH') {
  971:             if ($alerts{'username'}{$domain}{$username}) {
  972:                 if (ref($curr_rules{$domain}) eq 'HASH') {
  973:                     $output =
  974:                         &Apache::loncommon::instrule_disallow_msg('username',$domdesc,1,
  975:                                                                   'selfcreate').
  976:                         &Apache::loncommon::user_rule_formats($domain,$domdesc,
  977:                                 $curr_rules{$domain}{'username'},'username');
  978:                 }
  979:                 $checkfail = 'username';
  980:             }
  981:         }
  982:     }
  983:     if (!$checkfail) {
  984:         if (ref($statustocreate) eq 'ARRAY') {
  985:             $checkfail = 'inststatus';
  986:             if (ref($inst_results{$username.':'.$domain}{inststatus}) eq 'ARRAY') {
  987:                 foreach my $inststatus (@{$inst_results{$username.':'.$domain}{inststatus}}) {
  988:                     if (grep(/^\Q$inststatus\E$/,@{$statustocreate})) {
  989:                         undef($checkfail);
  990:                         last;
  991:                     }
  992:                 }
  993:             } elsif (grep(/^default$/,@{$statustocreate})) {
  994:                 undef($checkfail);
  995:             }
  996:         }
  997:     }
  998:     if (!$checkfail) {
  999:         $output = '<form method="post" action="/adm/createaccount">';
 1000:         (my $datatable,$rowcount,$editable) = 
 1001:             &Apache::loncreateuser::personal_data_display($username,$domain,1,'selfcreate',
 1002:                                                          $inst_results{$username.':'.$domain});
 1003:         if ($rowcount > 0) {
 1004:             $output .= $datatable;
 1005:         }
 1006:         $output .=  '<br /><br /><input type="hidden" name="uname" value="'.$username.'" />'."\n".
 1007:                     '<input type="hidden" name="udom" value="'.$domain.'" />'."\n".
 1008:                     '<input type="hidden" name="phase" value="username_activation" />';
 1009:         my $now = time;
 1010:         my %info = ('ip'         => $ENV{'REMOTE_ADDR'},
 1011:                     'time'       => $now,
 1012:                     'domain'     => $domain,
 1013:                     'username'   => $username);
 1014:         my $authtoken = &Apache::lonnet::tmpput(\%info,$lonhost,'createaccount');
 1015:         if ($authtoken !~ /^error/ && $authtoken ne 'no_such_host') {
 1016:             $output .= '<input type="hidden" name="authtoken" value="'.&HTML::Entities::encode($authtoken,'&<>"').'" />';
 1017:         } else {
 1018:             $output = &mt('An error occurred when storing a token').'<br />'.
 1019:                       &mt('You will not be able to proceed to the next stage of account creation').
 1020:                       &linkto_email_help($contact_email,$domdesc);
 1021:             $checkfail = 'authtoken';
 1022:         }
 1023:     }
 1024:     if ($checkfail) { 
 1025:         $msg = '<br /><h4>'.&mt('Account creation unavailable').'</h4>';
 1026:         if ($checkfail eq 'username') {
 1027:             $msg .= '<span class="LC_warning">'.
 1028:                      &mt('A LON-CAPA account may not be created with the username you use.').
 1029:                      '</span><br /><br />'.$output;
 1030:         } elsif ($checkfail eq 'authtoken') {
 1031:             $msg .= '<span class="LC_error">'.&mt('Error creating token.').'</span>'.
 1032:                     '<br />'.$output;
 1033:         } elsif ($checkfail eq 'inststatus') {
 1034:             $msg .= '<span class="LC_warning">'.
 1035:                      &mt('You are not permitted to create a LON-CAPA account.').
 1036:                      '</span><br /><br />'.$output;
 1037:         }
 1038:         $msg .= &mt('Please contact the [_1] ([_2]) for assistance.',
 1039:                 $contact_name,$contact_email).'<br /><hr />'.
 1040:                 $sso_logout;
 1041:         &Apache::lonnet::logthis("ERROR: failure type of '$checkfail' when performing username check to create account for authenticated user: $username, in domain $domain");
 1042:     } else {
 1043:         if ($courseid ne '') {
 1044:             $output .= '<input type="hidden" name="courseid" value="'.$courseid.'" />';
 1045:         }
 1046:         $output .= '<input type="submit" name="newaccount" value="'.
 1047:                    &mt('Create LON-CAPA account').'" /></form>';
 1048:         if ($rowcount) {
 1049:             if ($editable) {
 1050:                 if ($courseid ne '') { 
 1051:                     $msg = '<br /><h4>'.&mt('User information').'</h4>';
 1052:                 }
 1053:                 $msg .= &mt('To create one, use the table below to provide information about yourself, then click the [_1]Create LON-CAPA account[_2] button.','<span class="LC_cusr_emph">','</span>').'<br />';
 1054:             } else {
 1055:                  if ($courseid ne '') {
 1056:                      $msg = '<h4>'.&mt('Review user information').'</h4>';
 1057:                  }
 1058:                  $msg .= &mt('A user account will be created with information displayed in the table below, when you click the [_1]Create LON-CAPA account[_2] button.','<span class="LC_cusr_emph">','</span>').'<br />';
 1059:             }
 1060:         } else {
 1061:             if ($courseid ne '') {
 1062:                 $msg = '<h4>'.&mt('Confirmation').'</h4>';
 1063:             }
 1064:             $msg .= &mt('Confirm that you wish to create an account.');
 1065:         }
 1066:         $msg .= $output;
 1067:     }
 1068:     return $msg;
 1069: }
 1070: 
 1071: sub username_activation {
 1072:     my ($r,$username,$domain,$domdesc,$lonhost,$courseid) = @_;
 1073:     my $output;
 1074:     my $error     = '<span class="LC_error">'.&mt('Error:').' ';
 1075:     my $end       = '</span><br /><br />';
 1076:     my $rtnlink   = '<a href="javascript:history.back();" />'.
 1077:                     &mt('Return to previous page').'</a>'.
 1078:                     &Apache::loncommon::end_page();
 1079:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 1080:     my %data = &Apache::lonnet::tmpget($env{'form.authtoken'});
 1081:     my $now = time;
 1082:     my $earlyout;
 1083:     my $timeout = 300;
 1084:     if (keys(%data) == 0) {
 1085:         $output = &mt('Sorry, your authentication has expired.');
 1086:         $earlyout = 'fail';
 1087:     }
 1088:     if (($data{'time'} !~ /^\d+$/) ||
 1089:         ($data{'domain'} ne $domain) || 
 1090:         ($data{'username'} ne $username)) {
 1091:         $earlyout = 'fail';
 1092:         $output = &mt('The credentials you provided could not be verified.');   
 1093:     } elsif ($now - $data{'time'} > $timeout) {
 1094:         $earlyout = 'fail';
 1095:         $output = &mt('Sorry, your authentication has expired.');
 1096:     }
 1097:     if ($earlyout ne '') {
 1098:         $output .= '<br />'.&mt('Please [_1]start again[_2].','<a href="/adm/createaccount">','</a>');
 1099:         return($earlyout,$output);
 1100:     }
 1101:     if ((($domdefaults{'auth_def'} =~/^krb(4|5)$/) && 
 1102:          ($domdefaults{'auth_arg_def'} ne '')) || 
 1103:         ($domdefaults{'auth_def'} eq 'localauth')) {
 1104:         if ($env{'form.courseid'} ne '') {
 1105:             my ($result,$userchkmsg) = &check_id($username,$domain,$domdesc);
 1106:             if ($result eq 'fail') {
 1107:                 $output = $error.&mt('Invalid ID format').$end.
 1108:                           $userchkmsg.$rtnlink;
 1109:                 return ('fail',$output);
 1110:             }
 1111:         }
 1112:         # Call modifyuser
 1113:         my (%rulematch,%inst_results,%curr_rules,%got_rules,%alerts,%info);
 1114:         &call_rulecheck($username,$domain,\%alerts,\%rulematch,
 1115:                         \%inst_results,\%curr_rules,\%got_rules);
 1116:         my @userinfo = ('firstname','middlename','lastname','generation',
 1117:                         'permanentemail','id');
 1118:         my %canmodify = 
 1119:             &Apache::loncreateuser::selfcreate_canmodify('selfcreate',$domain,
 1120:                                                          \@userinfo,\%inst_results);
 1121:         foreach my $item (@userinfo) {
 1122:             if ($canmodify{$item}) {
 1123:                 $info{$item} = $env{'form.c'.$item};
 1124:             } else {
 1125:                 $info{$item} = $inst_results{$username.':'.$domain}{$item}; 
 1126:             }
 1127:         }
 1128:         if (ref($inst_results{$username.':'.$domain}{'inststatus'}) eq 'ARRAY') {
 1129:             my @inststatuses = @{$inst_results{$username.':'.$domain}{'inststatus'}};
 1130:             $info{'inststatus'} = join(':',map { &escape($_); } @inststatuses);
 1131:         }
 1132:         my $result =
 1133:             &Apache::lonnet::modifyuser($domain,$username,$env{'form.cid'},
 1134:                           $domdefaults{'auth_def'},
 1135:                           $domdefaults{'auth_arg_def'},$info{'firstname'},
 1136:                           $info{'middlename'},$info{'lastname'},
 1137:                           $info{'generation'},undef,undef,
 1138:                           $info{'permanentemail'},$info{'inststatus'});
 1139:         if ($result eq 'ok') {
 1140:             my $delete = &Apache::lonnet::tmpdel($env{'form.authtoken'});
 1141:             $output = &mt('A LON-CAPA account has been created for username: [_1] in domain: [_2].',$username,$domain);
 1142:             my %form = &start_session($r,$username,$domain,$lonhost,$courseid);
 1143:             my $nostart = 1;
 1144:             return ('ok',$output,$nostart);
 1145:         } else {
 1146:             $output = &mt('Account creation failed for username: [_1] in domain: [_2].',$username,$domain).'<br /><span class="LC_error">'.&mt('Error: [_1]',$result).'</span>';
 1147:             return ('fail',$output);
 1148:         }
 1149:     } else {
 1150:         $output = &mt('User account creation is not available for the current default authentication type.')."\n";
 1151:         return('fail',$output);
 1152:     }
 1153: }
 1154: 
 1155: sub check_id {
 1156:     my ($username,$domain,$domdesc) = @_;
 1157:     # Check ID format
 1158:     my (%alerts,%rulematch,%inst_results,%curr_rules,%checkhash);
 1159:     my %checks = ('id' => 1);
 1160:     %{$checkhash{$username.':'.$domain}} = (
 1161:                                             'newuser' => 1,
 1162:                                             'id' => $env{'form.cid'},
 1163:                                            );
 1164:     &Apache::loncommon::user_rule_check(\%checkhash,\%checks,\%alerts,
 1165:                                         \%rulematch,\%inst_results,\%curr_rules);
 1166:     if (ref($alerts{'id'}) eq 'HASH') {
 1167:         if (ref($alerts{'id'}{$domain}) eq 'HASH') {
 1168:             if ($alerts{'id'}{$domain}{$env{'form.cid'}}) {
 1169:                 my $userchkmsg;
 1170:                 if (ref($curr_rules{$domain}) eq 'HASH') {
 1171:                     $userchkmsg  =
 1172:                         &Apache::loncommon::instrule_disallow_msg('id',
 1173:                                                            $domdesc,1).
 1174:                         &Apache::loncommon::user_rule_formats($domain,
 1175:                               $domdesc,$curr_rules{$domain}{'id'},'id');
 1176:                 }
 1177:                 return ('fail',$userchkmsg);
 1178:             }
 1179:         }
 1180:     }
 1181:     return; 
 1182: }
 1183: 
 1184: sub invalid_state {
 1185:     my ($error,$domdesc,$contact_name,$contact_email,$msgtext,$useremail) = @_;
 1186:     my $msg = '<h3>'.&mt('Account creation unavailable').'</h3><span class="LC_error">';
 1187:     if ($error eq 'baduseremail') {
 1188:         $msg .= &mt('The e-mail address you provided does not appear to be a valid address.');
 1189:     } elsif ($error eq 'existinguser') {
 1190:         my $uname = &HTML::Entities::encode($useremail); 
 1191:         $msg .= &mt('The e-mail address you provided is already in use as a username in LON-CAPA at this institution.').'</span><br /><br /><span class="LC_warning">'.&mt('You can either:').'<ul>'.
 1192:                 '<li>'.&mt('Return to the [_1]log-in page[_2] and enter your password.','<a href="/adm/login?username='.$uname.'">','</a>').'</li>'.
 1193:                 '<li>'.&mt('or, if you do not remember your password, visit the "[_1]Forgot your password?[_2]" page.','<a href="/adm/resetpw?uname='.$uname.'&useremail='.$uname.'&referrer=createaccount">','</a>').
 1194:                 '</li></ul>';
 1195:     } elsif ($error eq 'userrules') {
 1196:         $msg .= &mt('Username rules at this institution do not allow the e-mail address you provided to be used as a username.');
 1197:     } elsif ($error eq 'userformat') {
 1198:         $msg .= &mt('The e-mail address you provided may not be used as a username at this LON-CAPA institution.');
 1199:     } elsif ($error eq 'captcha') {
 1200:         $msg .= &mt('Validation of the code you entered failed.');
 1201:     } elsif ($error eq 'noemails') {
 1202:         $msg .= &mt('Creation of a new user account using an e-mail address as username is not permitted at this LON-CAPA institution.');
 1203:     }
 1204:     $msg .= '</span>';
 1205:     if ($msgtext) {
 1206:         $msg .= '<br />'.$msgtext;
 1207:     }
 1208:     $msg .= &linkto_email_help($contact_email,$domdesc,$error);
 1209:     return $msg;
 1210: }
 1211: 
 1212: sub linkto_email_help {
 1213:     my ($contact_email,$domdesc,$error) = @_;
 1214:     my $msg;
 1215:     my $href = '/adm/helpdesk';
 1216:     if ($contact_email ne '') {
 1217:         my $escuri = &HTML::Entities::encode('/adm/createaccount','&<>"');
 1218:         $href .= '?origurl='.$escuri;
 1219:         if ($error eq 'existinguser') {
 1220:             my $escemail = &HTML::Entities::encode($env{'form.useremail'});
 1221:             $href .= '&useremail='.$escemail.'&useraccount='.$escemail;
 1222:         }
 1223:         $msg .= '<br />'.&mt('You may wish to contact the [_1]LON-CAPA helpdesk[_2] for [_3].','<a href="'.$href.'">','</a>',$domdesc).'<br />';
 1224:     } else {
 1225:         $msg .= '<br />'.&mt('You may wish to send an e-mail to the server administrator: [_1] for [_2].',$Apache::lonnet::perlvar{'AdminEmail'},$domdesc).'<br />';
 1226:     }
 1227:     return $msg;
 1228: }
 1229: 
 1230: sub create_recaptcha {
 1231:     my ($pubkey) = @_;
 1232:     my $captcha = Captcha::reCAPTCHA->new;
 1233:     # generate PUBLICKEY from https://www.google.com/recaptcha
 1234:     return $captcha->get_options_setter({theme => 'white'})."\n".
 1235:            $captcha->get_html($pubkey);
 1236: }
 1237: 
 1238: sub getkeys {
 1239:     my ($lkey,$ukey) = @_;
 1240:     my $lextkey=hex($lkey);
 1241:     if ($lextkey>2147483647) { $lextkey-=4294967296; }
 1242: 
 1243:     my $uextkey=hex($ukey);
 1244:     if ($uextkey>2147483647) { $uextkey-=4294967296; }
 1245:     return ($lextkey,$uextkey);
 1246: }
 1247: 
 1248: sub serverform {
 1249:     my ($logtoken,$lonhost,$mailtoken,$courseid,$context) = @_;
 1250:     my $phase = 'username_validation';
 1251:     my $catalog_elements;
 1252:     if ($context eq 'selfenroll') {
 1253:         $phase = 'selfenroll_login';
 1254:     }
 1255:     if ($courseid ne '') {
 1256:         $catalog_elements = &Apache::lonhtmlcommon::echo_form_input(['courseid','phase']);
 1257:     } 
 1258:     my $output = <<ENDSERVERFORM;
 1259:   <form name="server" method="post" action="/adm/createaccount">
 1260:    <input type="hidden" name="logtoken" value="$logtoken" />
 1261:    <input type="hidden" name="token" value="$mailtoken" />
 1262:    <input type="hidden" name="serverid" value="$lonhost" />
 1263:    <input type="hidden" name="uname" value="" />
 1264:    <input type="hidden" name="upass" value="" />
 1265:    <input type="hidden" name="udom" value="" />
 1266:    <input type="hidden" name="phase" value="$phase" />
 1267:    <input type="hidden" name="courseid" value="$courseid" />
 1268:    $catalog_elements
 1269:   </form>
 1270: ENDSERVERFORM
 1271:     return $output;
 1272: }
 1273: 
 1274: sub process_credentials {
 1275:     my ($logtoken,$lonhost) = @_;
 1276:     my $tmpinfo=Apache::lonnet::reply('tmpget:'.$logtoken,$lonhost);
 1277:     my ($retrieved,$output,$upass);
 1278:     if (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost')) {
 1279:         $output = &mt('Information needed to verify your login information is missing, inaccessible or expired.')
 1280:                  .'<br />'.&mt('You may need to reload the previous page to obtain a new token.');
 1281:         return ($retrieved,$output,$upass); 
 1282:     } else {
 1283:         my $reply = &Apache::lonnet::reply('tmpdel:'.$logtoken,$lonhost);
 1284:         if ($reply eq 'ok') {
 1285:             $retrieved = 'ok';
 1286:         } else {
 1287:             $output = &mt('Session could not be opened.');
 1288:         }
 1289:     }
 1290:     my ($key,$caller)=split(/&/,$tmpinfo);
 1291:     if ($caller eq 'createaccount') {
 1292:         $upass = &Apache::lonpreferences::des_decrypt($key,$env{'form.upass'});
 1293:     } else {
 1294:         $output = &mt('Unable to retrieve your log-in information - unexpected context');
 1295:     }
 1296:     return ($retrieved,$output,$upass);
 1297: }
 1298: 
 1299: sub guest_format_check {
 1300:     my ($useremail,$domain,$cancreate,$settings) = @_;
 1301:     my ($login,$format_match,$format_msg,@user_rules);
 1302:     if (ref($settings) eq 'HASH') {
 1303:         if (ref($settings->{'email_rule'}) eq 'ARRAY') {
 1304:             push(@user_rules,@{$settings->{'email_rule'}});
 1305:         }
 1306:     }
 1307:     if (@user_rules > 0) {
 1308:         my %rule_check = 
 1309:             &Apache::lonnet::inst_rulecheck($domain,$useremail,undef,
 1310:                                             'selfcreate',\@user_rules);
 1311:         if (keys(%rule_check) > 0) {
 1312:             foreach my $item (keys(%rule_check)) {
 1313:                 if ($rule_check{$item}) {
 1314:                     $format_match = 1;   
 1315:                     last;
 1316:                 }
 1317:             }
 1318:         }
 1319:     }
 1320:     if ($format_match) {
 1321:         ($login) = ($useremail =~ /^([^\@]+)\@/);
 1322:         $format_msg = '<br />'.&mt("Your e-mail address uses the same internet domain as your institution's LON-CAPA service.").'<br />'.&mt('Creation of a LON-CAPA account with this type of e-mail address as username is not permitted.').'<br />';
 1323:         if (ref($cancreate) eq 'ARRAY') {
 1324:             if (grep(/^login$/,@{$cancreate})) {
 1325:                 $format_msg .= &mt('You should request creation of a LON-CAPA account for a log-in ID of "[_1]" at your institution instead.',$login).'<br />'; 
 1326:             }
 1327:         }
 1328:     }
 1329:     return $format_msg;
 1330: }
 1331: 
 1332: sub sso_logout_frag {
 1333:     my ($r,$domain) = @_;
 1334:     my $endsessionmsg;
 1335:     if (defined($r->dir_config('lonSSOUserLogoutMessageFile_'.$domain))) {
 1336:         my $msgfile = $r->dir_config('lonSSOUserLogoutMessageFile_'.$domain);
 1337:         if (-e $msgfile) {
 1338:             open(my $fh,"<$msgfile");
 1339:             $endsessionmsg = join('',<$fh>);
 1340:             close($fh);
 1341:         }
 1342:     } elsif (defined($r->dir_config('lonSSOUserLogoutMessageFile'))) {
 1343:         my $msgfile = $r->dir_config('lonSSOUserLogoutMessageFile');
 1344:         if (-e $msgfile) {     
 1345:             open(my $fh,"<$msgfile");
 1346:             $endsessionmsg = join('',<$fh>);
 1347:             close($fh);
 1348:         }
 1349:     }
 1350:     return $endsessionmsg;
 1351: }
 1352: 
 1353: sub catreturn_js {
 1354:     return  <<"ENDSCRIPT";
 1355: <script type="text/javascript">
 1356: 
 1357: function ToSelfenroll(formname) {
 1358:     var formidx = getFormByName(formname);
 1359:     if (formidx > -1) {
 1360:         document.forms[formidx].action = '/adm/selfenroll';
 1361:         numidx = getIndexByName(formidx,'phase');
 1362:         if (numidx > -1) {
 1363:             document.forms[formidx].elements[numidx].value = '';   
 1364:         }
 1365:         numidx = getIndexByName(formidx,'context');
 1366:         if (numidx > -1) {
 1367:             document.forms[formidx].elements[numidx].value = '';
 1368:         }
 1369:     }
 1370:     document.forms[formidx].submit();
 1371: }
 1372: 
 1373: function ToCatalog(formname,caller) {
 1374:     var formidx = getFormByName(formname);
 1375:     if (formidx > -1) {
 1376:         document.forms[formidx].action = '/adm/coursecatalog';
 1377:         numidx = getIndexByName(formidx,'coursenum');
 1378:         if (numidx > -1) {
 1379:             if (caller != 'details') {
 1380:                 document.forms[formidx].elements[numidx].value = '';
 1381:             }
 1382:         }
 1383:     }
 1384:     document.forms[formidx].submit();
 1385: }
 1386: 
 1387: function getIndexByName(formidx,item) {
 1388:     for (var i=0;i<document.forms[formidx].elements.length;i++) {
 1389:         if (document.forms[formidx].elements[i].name == item) {
 1390:             return i;
 1391:         }
 1392:     }
 1393:     return -1;
 1394: }
 1395: 
 1396: function getFormByName(item) {
 1397:     for (var i=0; i<document.forms.length; i++) {
 1398:         if (document.forms[i].name == item) {
 1399:             return i;
 1400:         }
 1401:     }
 1402:     return -1;
 1403: }
 1404: 
 1405: </script>
 1406: ENDSCRIPT
 1407: 
 1408: }
 1409: 
 1410: 1;

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