File:  [LON-CAPA] / loncom / interface / createaccount.pm
Revision 1.27: download - view: text, annotated - select for diffs
Wed Jan 14 13:13:59 2009 UTC (15 years, 4 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- If a user needs to create a user account to self enroll in a course, the user's domain should be the domain of the course.

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

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