File:  [LON-CAPA] / loncom / interface / createaccount.pm
Revision 1.40.2.5.2.13: download - view: text, annotated - select for diffs
Fri Mar 2 20:44:25 2012 UTC (12 years, 3 months ago) by raeburn
Branches: loncapaMITrelate_1
Diff to branchpoint 1.40.2.5: preferred, unified
- Customization for MITrelate
- Replace courseID for self-enrollment with courseID for Mechanics Online
  in the case where users access sign-up from a cached version of:
  http://relate.mit.edu/physicscourse

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

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