File:  [LON-CAPA] / loncom / interface / createaccount.pm
Revision 1.40.2.5.2.17: download - view: text, annotated - select for diffs
Tue May 1 16:09:26 2012 UTC (12 years, 1 month ago) by raeburn
Branches: loncapaMITrelate_1
Diff to branchpoint 1.40.2.5: preferred, unified
- Customization for MITrelate.
  - Different sections assigned to existing users and new users who sign-up
    for Summer course, so demographic survey is only shown to new users.

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

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