File:  [LON-CAPA] / loncom / interface / createaccount.pm
Revision 1.40.2.5.2.12: download - view: text, annotated - select for diffs
Thu Mar 1 01:11:29 2012 UTC (12 years, 5 months ago) by raeburn
Branches: loncapaMITrelate_1
Diff to branchpoint 1.40.2.5: preferred, unified
- Customization for MITrelate.
- Remove duplicate line.

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

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