File:  [LON-CAPA] / loncom / interface / createaccount.pm
Revision 1.4: download - view: text, annotated - select for diffs
Mon Mar 24 05:15:14 2008 UTC (16 years, 2 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Functionality for requesting user information from a user authenticated by a domain's default authentication (must be either Kerberos of localauth) moved to new &username_check() subroutine.
- Remove $reqtime - not used
- Add missing space in message displayed when token information is incomplete.

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

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