File:  [LON-CAPA] / loncom / interface / createaccount.pm
Revision 1.15: download - view: text, annotated - select for diffs
Thu Jul 10 00:18:05 2008 UTC (15 years, 11 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Contact e-mail address should be for domain in whihc user is creating the account, not the default domain of the server hosting the session.
- Set contact e-mail address to the first address in the comma-separated list from loncommon::build_recipient_list().
- Added "Account creation unavailable" where username_check() reported failure for uauthenticated SSO users creating LON-CAPA accounts.

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

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