File:  [LON-CAPA] / loncom / interface / createaccount.pm
Revision 1.28: download - view: text, annotated - select for diffs
Sat Feb 7 00:59:17 2009 UTC (15 years, 4 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
Bug 5877.
 - Occasionally Authen::Captcha fails to generate an image.
 - In &create_captcha() loop the Authen::Captcha->new() call until an image is generated, or 10 attempts have been made.
 - Display an error message if no success after 10 attempts.

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

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