File:  [LON-CAPA] / loncom / interface / createaccount.pm
Revision 1.23: download - view: text, annotated - select for diffs
Thu Jul 17 20:19:43 2008 UTC (15 years, 9 months ago) by raeburn
Branches: MAIN
CVS tags: version_2_6_99_1, HEAD
- Fix typo (missing quote after cid in call to echo_form_output().
- Checking of username against institutional rules moved to &call_rulecheck() routine.
- Institutional ststus types including as final arg in call to Apache::lonnet::modifyuser().
- Sanity checking so unmodifiable fields use institutional data for the new user.

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

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