File:  [LON-CAPA] / loncom / interface / createaccount.pm
Revision 1.40.2.5.2.3: download - view: text, annotated - select for diffs
Sat Feb 11 23:30:16 2012 UTC (12 years, 3 months ago) by raeburn
Branches: loncapaMITrelate_1
Diff to branchpoint 1.40.2.5: preferred, unified
- Fix typo.
- Update documentation for URL to use to generate reCAPTCHA keys.

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

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