File:  [LON-CAPA] / loncom / interface / createaccount.pm
Revision 1.22: download - view: text, annotated - select for diffs
Thu Jul 17 12:10:05 2008 UTC (15 years, 10 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Breadcrumbs added to facilitate retreat to earlier pages during account creation process.
- &catreturn_js() added to provide javascript functions used in breadcrumb trail to jump back to
  course catalog or first self-enrollment screen, when account creation occuring in context of self-rnrollment
- &print_footer() added to provide backupcrumbs form where coursecatalog search terms are stored so breadcrumb links can jump back to entry point from course catalog in self-enroll context.
- &selfenroll_crumbs() added to provide additional breadcrumbs in selfe-ennroll context.
- &login_failure_msg() added to put messages displayed when authentication fails in one place, with a link back to try again.
- form element cid renamed courseid (and $cid renamed $courseid) to avoid confusing this with the cid form element used for entering a studentID in loncreateuser:personal_data_display().

    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.22 2008/07/17 12:10:05 raeburn Exp $
    7: #
    8: # Copyright Michigan State University Board of Trustees
    9: #
   10: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
   11: #
   12: # LON-CAPA is free software; you can redistribute it and/or modify
   13: # it under the terms of the GNU General Public License as published by
   14: # the Free Software Foundation; either version 2 of the License, or
   15: # (at your option) any later version.
   16: #
   17: # LON-CAPA is distributed in the hope that it will be useful,
   18: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   19: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   20: # GNU General Public License for more details.
   21: #
   22: # You should have received a copy of the GNU General Public License
   23: # along with LON-CAPA; if not, write to the Free Software
   24: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   25: #
   26: # /home/httpd/html/adm/gpl.txt
   27: #
   28: # http://www.lon-capa.org/
   29: #
   30: #
   31: package Apache::createaccount;
   32: 
   33: use strict;
   34: use Apache::Constants qw(:common);
   35: use Apache::lonacc;
   36: use Apache::lonnet;
   37: use Apache::loncommon;
   38: use Apache::lonhtmlcommon;
   39: use Apache::lonlocal;
   40: use Apache::lonauth;
   41: use Apache::resetpw;
   42: use Authen::Captcha;
   43: use DynaLoader; # for Crypt::DES version
   44: use Crypt::DES;
   45: use LONCAPA qw(:DEFAULT :match);
   46: use HTML::Entities;
   47: 
   48: sub handler {
   49:     my $r = shift;
   50:     &Apache::loncommon::content_type($r,'text/html');
   51:     $r->send_http_header;
   52:     if ($r->header_only) {
   53:         return OK;
   54:     }
   55: 
   56:     my $domain;
   57: 
   58:     my $sso_username = $r->subprocess_env->get('REDIRECT_SSOUserUnknown');
   59:     my $sso_domain = $r->subprocess_env->get('REDIRECT_SSOUserDomain');
   60: 
   61:     if ($sso_username ne '' && $sso_domain ne '') {
   62:         $domain = $sso_domain; 
   63:     } else { 
   64:         $domain = &Apache::lonnet::default_login_domain();
   65:     }
   66:     my $domdesc = &Apache::lonnet::domain($domain,'description');
   67:     my $contact_name = &mt('LON-CAPA helpdesk');
   68:     my $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};
   69:     my $contacts =
   70:         &Apache::loncommon::build_recipient_list(undef,'helpdeskmail',
   71:                                                  $domain,$origmail);
   72:     my ($contact_email) = split(',',$contacts);
   73:     my $lonhost = $r->dir_config('lonHostID');
   74:     my $include = $r->dir_config('lonIncludes');
   75:     my $start_page;
   76: 
   77:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['token','courseid']);
   78:     &Apache::lonacc::get_posted_cgi($r);
   79:     &Apache::lonlocal::get_language_handle($r);
   80: 
   81:     my $handle = &Apache::lonnet::check_for_valid_session($r);
   82:     if ($handle ne '') {
   83:         $start_page =
   84:             &Apache::loncommon::start_page('Already logged in');
   85:         my $end_page =
   86:             &Apache::loncommon::end_page();
   87:         $r->print($start_page."\n".'<h2>'.&mt('You are already logged in').'</h2>'.
   88:                   '<p>'.&mt('Please either [_1]continue the current session[_2] or [_3]logout[_4].','<a href="/adm/roles">','</a>','<a href="/adm/logout">','</a>').
   89:                   '</p><p><a href="/adm/loginproblems.html">'.&mt('Login problems?').'</a></p>'.$end_page);
   90:         return OK;
   91:     }
   92: 
   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 (%rulematch,%inst_results,%curr_rules,%got_rules,%alerts);
  521:                 my $uhome=&Apache::lonnet::homeserver($useremail,$domain);
  522:                 if ($uhome eq 'no_host') {
  523:                     my $checkhash;
  524:                     my $checks = { 'username' => 1 };
  525:                     $checkhash->{$useremail.':'.$domain} = { 'newuser' => 1, };
  526:                     &Apache::loncommon::user_rule_check($checkhash,$checks,
  527:                           \%alerts,\%rulematch,\%inst_results,\%curr_rules,
  528:                           \%got_rules);
  529:                     if (ref($alerts{'useremail'}) eq 'HASH') {
  530:                         if (ref($alerts{'useremail'}{$domain}) eq 'HASH') {
  531:                             if ($alerts{'username'}{$domain}{$useremail}) {
  532:                                 $output = &invalid_state('userrules',$domdesc,
  533:                                                          $contact_name,$contact_email);
  534:                                 return $output;
  535:                             }
  536:                         }
  537:                     }
  538:                     my $format_msg = 
  539:                         &guest_format_check($useremail,$domain,$cancreate,
  540:                                             $settings);
  541:                     if ($format_msg) {
  542:                         $output = &invalid_state('userformat',$domdesc,$contact_name,
  543:                                                  $contact_email,$format_msg);
  544:                         return $output;
  545:                     }
  546:                 }
  547:             }
  548:         }
  549:         $output = &send_token($domain,$useremail,$server,$domdesc,$contact_name,
  550:                           $contact_email,$courseid);
  551:     }
  552:     return $output;
  553: }
  554: 
  555: sub send_token {
  556:     my ($domain,$email,$server,$domdesc,$contact_name,$contact_email,$courseid) = @_;
  557:     my $msg = '<h3>'.&mt('Account creation status').'</h3>'.
  558:               &mt('Thank you for your request to create a new LON-CAPA account.').
  559:               '<br /><br />';
  560:     my $now = time;
  561:     my %info = ('ip'         => $ENV{'REMOTE_ADDR'},
  562:                 'time'       => $now,
  563:                 'domain'     => $domain,
  564:                 'username'   => $email,
  565:                 'courseid'   => $courseid);
  566:     my $token = &Apache::lonnet::tmpput(\%info,$server);
  567:     if ($token !~ /^error/ && $token ne 'no_such_host') {
  568:         my $esc_token = &escape($token);
  569:         my $mailmsg = &mt('A request was submitted on [_1] for creation of a LON-CAPA account at the following institution: [_2].',localtime(time),$domdesc).' '.
  570:              &mt('To complete this process please open a web browser and enter the following'
  571:                 .' URL in the address/location box: [_1]'
  572:                 ,&Apache::lonnet::absolute_url().'/adm/createaccount?token='.$esc_token);
  573:         my $result = &Apache::resetpw::send_mail($domdesc,$email,$mailmsg,$contact_name,
  574:                                                  $contact_email);
  575:         if ($result eq 'ok') {
  576:             $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>');
  577:         } else {
  578:             $msg .= '<span class="LC_error">'.
  579:                     &mt('An error occurred when sending a message to the e-mail address you provided.').'</span><br />'.
  580:                     ' '.&mt('Please contact the [_1] ([_2]) for assistance.',$contact_name,$contact_email);
  581:         }
  582:     } else {
  583:         $msg .= '<span class="LC_error">'.
  584:                 &mt('An error occurred creating a token required for the account creation process.').'</span><br />'.
  585:                 ' '.&mt('Please contact the [_1] ([_2]) for assistance.',$contact_name,$contact_email);
  586:     }
  587:     return $msg;
  588: }
  589: 
  590: sub process_mailtoken {
  591:     my ($r,$token,$contact_name,$contact_email,$domain,$domdesc,$lonhost,
  592:         $include,$start_page) = @_;
  593:     my ($msg,$nostart,$noend);
  594:     my %data = &Apache::lonnet::tmpget($token);
  595:     my $now = time;
  596:     if (keys(%data) == 0) {
  597:         $msg = &mt('Sorry, the URL you provided to complete creation of a new LON-CAPA account was invalid.')
  598:                .' '.&mt('Either the token included in the URL has been deleted or the URL you provided was invalid.')
  599:                .' '.&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>');
  600:         return $msg;
  601:     }
  602:     if (($data{'time'} =~ /^\d+$/) &&
  603:         ($data{'domain'} ne '') &&
  604:         ($data{'username'}  =~ /^[^\@]+\@[^\@]+\.[^\@\.]+$/)) {
  605:         if ($now - $data{'time'} < 7200) {
  606:             if ($env{'form.phase'} eq 'createaccount') {
  607:                 my ($result,$output) = &create_account($r,$domain,$lonhost,
  608:                                                        $data{'username'},$domdesc);
  609:                 if ($result eq 'ok') {
  610:                     $msg = $output; 
  611:                     my $shownow = &Apache::lonlocal::locallocaltime($now);
  612:                     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";
  613:                     my $mailresult = &Apache::resetpw::send_mail($domdesc,$data{'email'},
  614:                                                                  $mailmsg,$contact_name,
  615:                                                                  $contact_email);
  616:                     if ($mailresult eq 'ok') {
  617:                         $msg .= &mt('An e-mail confirming creation of your new LON-CAPA account has been sent to [_1].',$data{'username'});
  618:                     } else {
  619:                         $msg .= &mt('An error occurred when sending e-mail to [_1] confirming creation of your LON-CAPA account.',$data{'username'});
  620:                     }
  621:                     my %form = &start_session($r,$data{'username'},$domain, 
  622:                                               $lonhost,$data{'courseid'},
  623:                                               $token);
  624:                     $nostart = 1;
  625:                     $noend = 1;
  626:                 } else {
  627:                     $msg .= &mt('A problem occurred when attempting to create your new LON-CAPA account.')
  628:                            .'<br />'.$output
  629: #                           .&mt('Please contact the [_1] ([_2]) for assistance.',$contact_name,'<a href="mailto:'.$contact_email.'">'.$contact_email.'</a>');
  630:                            .&mt('Please contact the [_1] ([_2]) for assistance.',$contact_name,$contact_email);
  631:                 }
  632:                 my $delete = &Apache::lonnet::tmpdel($token);
  633:             } else {
  634:                 $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 />';
  635:                 $msg .= &print_dataentry_form($r,$domain,$lonhost,$include,$token,$now,$data{'username'},$start_page);
  636:                 $nostart = 1;
  637:             }
  638:         } else {
  639:             $msg = &mt('Sorry, the token generated when you requested creation of an account has expired.')
  640:                   .' '.&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>');
  641:             }
  642:     } else {
  643:         $msg .= &mt('Sorry, the URL generated when you requested creation of an account contained incomplete information.')
  644:                .' '.&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>');
  645:     }
  646:     return ($msg,$nostart,$noend);
  647: }
  648: 
  649: sub start_session {
  650:     my ($r,$username,$domain,$lonhost,$courseid,$token) = @_;
  651:     my %form = (
  652:                 uname => $username,
  653:                 udom  => $domain,
  654:                );
  655:     my $firsturl = '/adm/roles';
  656:     if (defined($courseid)) {
  657:         $courseid = &validate_course($courseid);
  658:         if ($courseid ne '') {
  659:             $form{'courseid'} = $courseid;
  660:             $firsturl = '/adm/selfenroll?courseid='.$courseid;
  661:         }
  662:     }
  663:     if ($r->dir_config('lonBalancer') eq 'yes') {
  664:         &Apache::lonauth::success($r,$form{'uname'},$form{'udom'},
  665:                                   $lonhost,'noredirect',undef,\%form);
  666:         if ($token ne '') { 
  667:             my $delete = &Apache::lonnet::tmpdel($token);
  668:         }
  669:         $r->internal_redirect('/adm/switchserver');
  670:     } else {
  671:         &Apache::lonauth::success($r,$form{'uname'},$form{'udom'},
  672:                                   $lonhost,$firsturl,undef,\%form);
  673:     }
  674:     return %form;
  675: }
  676: 
  677: 
  678: sub print_dataentry_form {
  679:     my ($r,$domain,$lonhost,$include,$mailtoken,$now,$username,$start_page) = @_;
  680:     my ($error,$output);
  681:     &print_header($r,$start_page);
  682:     if (open(my $jsh,"<$include/londes.js")) {
  683:         while(my $line = <$jsh>) {
  684:             $r->print($line);
  685:         }
  686:         close($jsh);
  687:         $output .= &javascript_setforms($now)."\n".&javascript_checkpass($now);
  688:         my ($lkey,$ukey) = &Apache::lonpreferences::des_keys();
  689:         my ($lextkey,$uextkey) = &getkeys($lkey,$ukey);
  690:         my $logtoken=Apache::lonnet::reply('tmpput:'.$ukey.$lkey.'&createaccount',
  691:                                            $lonhost);
  692:         my @userinfo = ('firstname','middlename','lastname','generation','id',
  693:                         'permanentemail');
  694:         my %lt=&Apache::lonlocal::texthash(
  695:                     'pd'             => "Personal Data",
  696:                     'firstname'      => "First Name",
  697:                     'middlename'     => "Middle Name",
  698:                     'lastname'       => "Last Name",
  699:                     'generation'     => "Generation",
  700:                     'permanentemail' => "Permanent e-mail address",
  701:                     'id'             => "ID/Student Number",
  702:                     'lg'             => "Login Data"
  703:         );
  704:         my %textboxsize = (
  705:                            firstname      => '15',
  706:                            middlename     => '15',
  707:                            lastname       => '15',
  708:                            generation     => '5',
  709:                            id             => '15',
  710:                           );
  711:         my $genhelp=&Apache::loncommon::help_open_topic('Generation');
  712:         $output .= '<div class="LC_left_float"><h3>'.$lt{'pd'}.'</h3>'.
  713:                   '<form name="server" method="post" target="_top" action="/adm/createaccount">'.
  714:                   &Apache::lonhtmlcommon::start_pick_box();
  715:         foreach my $item (@userinfo) {
  716:             my $rowtitle = $lt{$item};
  717:             if ($item eq 'generation') {
  718:                 $rowtitle = $genhelp.$rowtitle;
  719:             }
  720:             $output .= &Apache::lonhtmlcommon::row_title($rowtitle,undef,'LC_oddrow_value')."\n";
  721:             if ($item eq 'permanentemail') {
  722:                 $output .= $username;
  723:             } else {
  724:                 $output .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
  725:             }
  726:             $output .= &Apache::lonhtmlcommon::row_closure(1);
  727:         }
  728:         $output .= &Apache::lonhtmlcommon::end_pick_box();
  729:         $output .= <<"ENDSERVERFORM";
  730:    <input type="hidden" name="logtoken" value="$logtoken" />
  731:    <input type="hidden" name="token" value="$mailtoken" />
  732:    <input type="hidden" name="serverid" value="$lonhost" />
  733:    <input type="hidden" name="uname" value="" />
  734:    <input type="hidden" name="upass" value="" />
  735:    <input type="hidden" name="phase" value="createaccount" />
  736:   </form></div>
  737: ENDSERVERFORM
  738:         my $upassone = '<input type="password" name="upass'.$now.'" size="10" />';
  739:         my $upasstwo = '<input type="password" name="upasscheck'.$now.'" size="10" />';
  740:         my $submit_text = &mt('Create LON-CAPA account');
  741:         $output .= '<div class="LC_left_float"><h3>'.$lt{'lg'}.'</h3>'."\n".
  742:                    '<form name="client" method="post" />'."\n".
  743:                    &Apache::lonhtmlcommon::start_pick_box()."\n".
  744:                    &Apache::lonhtmlcommon::row_title(&mt('Username'),
  745:                                                     'LC_pick_box_title')."\n".
  746:                    $username."\n".
  747:                    &Apache::lonhtmlcommon::row_closure(1)."\n".
  748:                    &Apache::lonhtmlcommon::row_title(&mt('Password'),
  749:                                                     'LC_pick_box_title')."\n".
  750:                    $upassone."\n".
  751:                    &Apache::lonhtmlcommon::row_closure(1)."\n".
  752:                    &Apache::lonhtmlcommon::row_title(&mt('Confirm password'),
  753:                                                 'LC_pick_box_title')."\n".
  754:                    $upasstwo."\n".
  755:                    &Apache::lonhtmlcommon::row_closure(1)."\n".
  756:                    &Apache::lonhtmlcommon::end_pick_box()."\n".
  757:                    '<input type="hidden" name="uname" value="'.$username.'">'."\n".
  758:                    '<input type="hidden" name="lextkey" value="'.$lextkey.'">'."\n".
  759:                    '<input type="hidden" name="uextkey" value="'.$uextkey.'">'."\n".
  760:                    '</form></div>'."\n".
  761:                    '<div class="LC_clear_float_footer"><br /><br />'."\n".
  762:                    '<form name="buttonform">'."\n".
  763:                    '<input type="button" name="createaccount" value="'.
  764:                    $submit_text.'" onclick="javascript:checkpass();" /></form></div>';
  765:     } else {
  766:         $output = &mt('Could not load javascript file [_1]','<tt>londes.js</tt>');
  767:     }
  768:     return $output;
  769: }
  770: 
  771: sub create_account {
  772:     my ($r,$domain,$lonhost,$username,$domdesc) = @_;
  773:     my ($retrieved,$output,$upass) = &process_credentials($env{'form.logtoken'},
  774:                                                           $env{'form.serverid'}); 
  775:     # Error messages
  776:     my $error     = '<span class="LC_error">'.&mt('Error:').' ';
  777:     my $end       = '</span><br /><br />';
  778:     my $rtnlink   = '<a href="javascript:history.back();" />'.
  779:                     &mt('Return to previous page').'</a>'.
  780:                     &Apache::loncommon::end_page();
  781:     if ($retrieved eq 'ok') {
  782:         if ($env{'form.courseid'} ne '') {
  783:             my ($result,$userchkmsg) = &check_id($username,$domain,$domdesc);
  784:             if ($result eq 'fail') {
  785:                 $output = $error.&mt('Invalid ID format').$end.
  786:                           $userchkmsg.$rtnlink;
  787:                 return ('fail',$output);
  788:             }
  789:         }
  790:     } else {
  791:         return ('fail',$error.$output.$end.$rtnlink);
  792:     }
  793:     # Call modifyuser
  794:     my $result = 
  795:         &Apache::lonnet::modifyuser($domain,$username,$env{'form.cid'},
  796:                                     'internal',$upass,$env{'form.cfirstname'},
  797:                                     $env{'form.cmiddlename'},$env{'form.clastname'},
  798:                                     $env{'form.cgeneration'},undef,undef,$username);
  799:     $output = &mt('Generating user: [_1]',$result);
  800:     my $uhome = &Apache::lonnet::homeserver($username,$domain);
  801:     $output .= '<br />'.&mt('Home server: [_1]',$uhome).' '.
  802:               &Apache::lonnet::hostname($uhome).'<br /><br />';
  803:     return ('ok',$output);
  804: }
  805: 
  806: sub username_validation {
  807:     my ($r,$username,$domain,$domdesc,$contact_name,$contact_email,$courseid,
  808:         $lonhost) = @_;
  809:     my ($retrieved,$output,$upass);
  810: 
  811:     $username= &LONCAPA::clean_username($username);
  812:     $domain = &LONCAPA::clean_domain($domain);
  813:     my $uhome = &Apache::lonnet::homeserver($username,$domain);
  814: 
  815:     ($retrieved,$output,$upass) = &process_credentials($env{'form.logtoken'},
  816:                                                        $env{'form.serverid'});
  817:     if ($retrieved ne 'ok') {
  818:         return ('fail',$output);
  819:     }
  820:     if ($uhome ne 'no_host') {
  821:         my $result = &Apache::lonnet::authenticate($username,$upass,$domain);
  822:         if ($result ne 'no_host') { 
  823:             my %form = &start_session($r,$username,$domain,$lonhost,$courseid);
  824:             $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.');
  825:             return ('existingaccount',$output);
  826:         } else {
  827:             $output = &login_failure_msg($courseid);
  828:         }
  829:     } else {
  830:         my $primlibserv = &Apache::lonnet::domain($domain,'primary');
  831:         my $authok;
  832:         my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
  833:         if ((($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) || ($domdefaults{'auth_def'} eq 'localauth')) {
  834:             my $checkdefauth = 1;
  835:             $authok = 
  836:                 &Apache::lonnet::reply("encrypt:auth:$domain:$username:$upass:$checkdefauth",$primlibserv);
  837:         } else {
  838:             $authok = 'non_authorized';
  839:         }
  840:         if ($authok eq 'authorized') {
  841:             $output = &username_check($username,$domain,$domdesc,$courseid,$lonhost,
  842:                                       $contact_email,$contact_name);
  843:         } else {
  844:             $output = &login_failure_msg($courseid);
  845:         }
  846:     }
  847:     return ('ok',$output);
  848: }
  849: 
  850: sub login_failure_msg {
  851:     my ($courseid) = @_;
  852:     my $url;
  853:     if ($courseid ne '') {
  854:         $url = "/adm/selfenroll?courseid=".$courseid;
  855:     } else {
  856:         $url = "/adm/createaccount";
  857:     }
  858:     my $output = '<h4>'.&mt('Authentication failed').'</h4><div class="LC_warning">'.
  859:                  &mt('Username and/or password could not be authenticated.').
  860:                  '</div>'.
  861:                  &mt('Please check the username and password.').'<br /><br />';
  862:                  '<a href="'.$url.'">'.&mt('Try again').'</a>';
  863:     return $output;
  864: }
  865: 
  866: sub username_check {
  867:     my ($username,$domain,$domdesc,$courseid,$lonhost,$contact_email,$contact_name,
  868:         $sso_logout) = @_;
  869:     my (%rulematch,%inst_results,$newuser,$checkfail,$rowcount,$editable,$output,$msg,
  870:         %alerts,%curr_rules,%got_rules);
  871:     $newuser = 1;
  872:     my $checkhash;
  873:     my $checks = { 'username' => 1 };
  874:     $checkhash->{$username.':'.$domain} = { 'newuser' => $newuser };
  875:     &Apache::loncommon::user_rule_check($checkhash,$checks,\%alerts,\%rulematch,
  876:                                         \%inst_results,\%curr_rules,\%got_rules);
  877:     if (ref($alerts{'username'}) eq 'HASH') {
  878:         if (ref($alerts{'username'}{$domain}) eq 'HASH') {
  879:             if ($alerts{'username'}{$domain}{$username}) {
  880:                 if (ref($curr_rules{$domain}) eq 'HASH') {
  881:                     $output =
  882:                         &Apache::loncommon::instrule_disallow_msg('username',$domdesc,1,
  883:                                                                   'selfcreate').
  884:                         &Apache::loncommon::user_rule_formats($domain,$domdesc,
  885:                                 $curr_rules{$domain}{'username'},'username');
  886:                 }
  887:                 $checkfail = 'username';
  888:             }
  889:         }
  890:     }
  891:     if (!$checkfail) {
  892:         $output = '<form method="post" action="/adm/createaccount">';
  893:         (my $datatable,$rowcount,$editable) = 
  894:             &Apache::loncreateuser::personal_data_display($username,$domain,1,'selfcreate',
  895:                                                          $inst_results{$username.':'.$domain});
  896:         if ($rowcount > 0) {
  897:             $output .= $datatable;
  898:         }
  899:         $output .=  '<br /><br /><input type="hidden" name="uname" value="'.$username.'" />'."\n".
  900:                     '<input type="hidden" name="udom" value="'.$domain.'" />'."\n".
  901:                     '<input type="hidden" name="phase" value="username_activation" />';
  902:         my $now = time;
  903:         my %info = ('ip'         => $ENV{'REMOTE_ADDR'},
  904:                     'time'       => $now,
  905:                     'domain'     => $domain,
  906:                     'username'   => $username);
  907:         my $authtoken = &Apache::lonnet::tmpput(\%info,$lonhost);
  908:         if ($authtoken !~ /^error/ && $authtoken ne 'no_such_host') {
  909:             $output .= '<input type="hidden" name="authtoken" value="'.&HTML::Entities::encode($authtoken,'&<>"').'" />';
  910:         } else {
  911:             $output = &mt('An error occurred when storing a token').'<br />'.
  912:                       &mt('You will not be able to proceed to the next stage of account creation').
  913:                       &linkto_email_help($contact_email,$domdesc);
  914:             $checkfail = 'authtoken';
  915:         }
  916:     }
  917:     if ($checkfail) { 
  918:         $msg = '<h4>'.&mt('Account creation unavailable').'</h4>';
  919:         if ($checkfail eq 'username') {
  920:             $msg .= '<span class="LC_warning">'.
  921:                      &mt('A LON-CAPA account may not be created with the username you use.').
  922:                      '</span><br /><br />'.$output;
  923:         } elsif ($checkfail eq 'authtoken') {
  924:             $msg .= '<span class="LC_error">'.&mt('Error creating token.').'</span>'.
  925:                     '<br />'.$output;
  926:         }
  927:         $msg .= &mt('Please contact the [_1] ([_2]) for assistance.',
  928:                 $contact_name,$contact_email).'<br /><hr />'.
  929:                 $sso_logout;
  930:         &Apache::lonnet::logthis("ERROR: failure type of '$checkfail' when performing username check to create account for authenticated user: $username, in domain $domain");
  931:     } else {
  932:         if ($courseid ne '') {
  933:             $output .= '<input type="hidden" name="courseid" value="'.$courseid.'" />';
  934:         }
  935:         $output .= '<input type="submit" name="newaccount" value="'.
  936:                    &mt('Create LON-CAPA account').'" /></form>';
  937:         if ($rowcount) {
  938:             if ($editable) {
  939:                 if ($courseid ne '') { 
  940:                     $msg = '<h4>'.&mt('User information').'</h4>';
  941:                 }
  942:                 $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 />';
  943:             } else {
  944:                  if ($courseid ne '') {
  945:                      $msg = '<h4>'.&mt('Review user information').'</h4>';
  946:                  }
  947:                  $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 />';
  948:             }
  949:         } else {
  950:             if ($courseid ne '') {
  951:                 $msg = '<h4>'.&mt('Confirmation').'</h4>';
  952:             }
  953:             $msg .= &mt('Confirm that you wish to create an account.');
  954:         }
  955:         $msg .= $output;
  956:     }
  957:     return $msg;
  958: }
  959: 
  960: sub username_activation {
  961:     my ($r,$username,$domain,$domdesc,$lonhost,$courseid) = @_;
  962:     my $output;
  963:     my $error     = '<span class="LC_error">'.&mt('Error:').' ';
  964:     my $end       = '</span><br /><br />';
  965:     my $rtnlink   = '<a href="javascript:history.back();" />'.
  966:                     &mt('Return to previous page').'</a>'.
  967:                     &Apache::loncommon::end_page();
  968:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
  969:     my %data = &Apache::lonnet::tmpget($env{'form.authtoken'});
  970:     my $now = time;
  971:     my $earlyout;
  972:     my $timeout = 300;
  973:     if (keys(%data) == 0) {
  974:         $output = &mt('Sorry, your authentication has expired.');
  975:         $earlyout = 'fail';
  976:     }
  977:     if (($data{'time'} !~ /^\d+$/) ||
  978:         ($data{'domain'} ne $domain) || 
  979:         ($data{'username'} ne $username)) {
  980:         $earlyout = 'fail';
  981:         $output = &mt('The credentials you provided could not be verified.');   
  982:     } elsif ($now - $data{'time'} > $timeout) {
  983:         $earlyout = 'fail';
  984:         $output = &mt('Sorry, your authentication has expired.');
  985:     }
  986:     if ($earlyout ne '') {
  987:         $output .= '<br />'.&mt('Please [_1]start again[_2].','<a href="/adm/createaccount">','</a>');
  988:         return($earlyout,$output);
  989:     }
  990:     if ((($domdefaults{'auth_def'} =~/^krb(4|5)$/) && 
  991:          ($domdefaults{'auth_arg_def'} ne '')) || 
  992:         ($domdefaults{'auth_def'} eq 'localauth')) {
  993:         if ($env{'form.courseid'} ne '') {
  994:             my ($result,$userchkmsg) = &check_id($username,$domain,$domdesc);
  995:             if ($result eq 'fail') {
  996:                 $output = $error.&mt('Invalid ID format').$end.
  997:                           $userchkmsg.$rtnlink;
  998:                 return ('fail',$output);
  999:             }
 1000:         }
 1001:         # Call modifyuser
 1002:         my $result =
 1003:             &Apache::lonnet::modifyuser($domain,$username,$env{'form.courseid'},
 1004:                           $domdefaults{'auth_def'},
 1005:                           $domdefaults{'auth_arg_def'},$env{'form.cfirstname'},
 1006:                           $env{'form.cmiddlename'},$env{'form.clastname'},
 1007:                           $env{'form.cgeneration'},undef,undef,
 1008:                           $env{'form.cpermanentemail'});
 1009:         if ($result eq 'ok') {
 1010:             my $delete = &Apache::lonnet::tmpdel($env{'form.authtoken'});
 1011:             $output = &mt('A LON-CAPA account has been created for username: [_1] in domain: [_2].',$username,$domain);
 1012:             my %form = &start_session($r,$username,$domain,$lonhost,$courseid);
 1013:             my $nostart = 1;
 1014:             return ('ok',$output,$nostart);
 1015:         } else {
 1016:             $output = &mt('Account creation failed for username: [_1] in domain: [_2].',$username,$domain).'<br /><span class="LC_error">'.&mt('Error: [_1]',$result).'</span>';
 1017:             return ('fail',$output);
 1018:         }
 1019:     } else {
 1020:         $output = &mt('User account creation is not available for the current default authentication type.')."\n";
 1021:         return('fail',$output);
 1022:     }
 1023: }
 1024: 
 1025: sub check_id {
 1026:     my ($username,$domain,$domdesc) = @_;
 1027:     # Check ID format
 1028:     my (%alerts,%rulematch,%inst_results,%curr_rules,%checkhash);
 1029:     my %checks = ('id' => 1);
 1030:     %{$checkhash{$username.':'.$domain}} = (
 1031:                                             'newuser' => 1,
 1032:                                             'id' => $env{'form.cid'},
 1033:                                            );
 1034:     &Apache::loncommon::user_rule_check(\%checkhash,\%checks,\%alerts,
 1035:                                         \%rulematch,\%inst_results,\%curr_rules);
 1036:     if (ref($alerts{'id'}) eq 'HASH') {
 1037:         if (ref($alerts{'id'}{$domain}) eq 'HASH') {
 1038:             if ($alerts{'id'}{$domain}{$env{'form.cid'}}) {
 1039:                 my $userchkmsg;
 1040:                 if (ref($curr_rules{$domain}) eq 'HASH') {
 1041:                     $userchkmsg  =
 1042:                         &Apache::loncommon::instrule_disallow_msg('id',
 1043:                                                            $domdesc,1).
 1044:                         &Apache::loncommon::user_rule_formats($domain,
 1045:                               $domdesc,$curr_rules{$domain}{'id'},'id');
 1046:                 }
 1047:                 return ('fail',$userchkmsg);
 1048:             }
 1049:         }
 1050:     }
 1051:     return; 
 1052: }
 1053: 
 1054: sub invalid_state {
 1055:     my ($error,$domdesc,$contact_name,$contact_email,$msgtext) = @_;
 1056:     my $msg = '<h3>'.&mt('Account creation unavailable').'</h3><span class="LC_error">';
 1057:     if ($error eq 'baduseremail') {
 1058:         $msg = &mt('The e-mail address you provided does not appear to be a valid address.');
 1059:     } elsif ($error eq 'existinguser') {
 1060:         $msg = &mt('The e-mail address you provided is already in use as a username in LON-CAPA at this institution.');
 1061:     } elsif ($error eq 'userrules') {
 1062:         $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.');
 1063:     } elsif ($error eq 'userformat') {
 1064:         $msg = &mt('The e-mail address you provided may not be used as a username at this LON-CAPA institution.');
 1065:     } elsif ($error eq 'captcha') {
 1066:         $msg = &mt('Validation of the code your entered failed.');
 1067:     } elsif ($error eq 'noemails') {
 1068:         $msg = &mt('Creation of a new user account using an e-mail address as username is not permitted at this LON-CAPA institution.');
 1069:     }
 1070:     $msg .= '</span>';
 1071:     if ($msgtext) {
 1072:         $msg .= '<br />'.$msgtext;
 1073:     }
 1074:     $msg .= &linkto_email_help($contact_email,$domdesc);
 1075:     return $msg;
 1076: }
 1077: 
 1078: sub linkto_email_help {
 1079:     my ($contact_email,$domdesc) = @_;
 1080:     my $msg;
 1081:     if ($contact_email ne '') {
 1082:         my $escuri = &HTML::Entities::encode('/adm/createaccount','&<>"');
 1083:         $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 />';
 1084:     } else {
 1085:         $msg .= '<br />'.&mt('You may wish to send an e-mail to the server administrator: [_1] for [_2].',$Apache::lonnet::perlvar{'AdminEmail'},$domdesc).'<br />';
 1086:     }
 1087:     return $msg;
 1088: }
 1089: 
 1090: sub create_captcha {
 1091:     my ($output_dir,$db_dir) = @_;
 1092:     my %captcha_params = &captcha_settings();
 1093:     my $captcha = Authen::Captcha->new(
 1094:                                        output_folder => $captcha_params{'output_dir'},
 1095:                                        data_folder   => $captcha_params{'db_dir'},
 1096:                                       );
 1097:     my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
 1098:     my $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
 1099:                  &mt('Type in the letters/numbers shown below').'&nbsp;'.
 1100:                  '<input type="text" size="5" name="code" value="" /><br />'.
 1101:                  '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png">';
 1102:     return $output;
 1103: }
 1104: 
 1105: sub captcha_settings {
 1106:     my %captcha_params = ( 
 1107:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
 1108:                            www_output_dir => "/captchaspool",
 1109:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
 1110:                            numchars       => '5',
 1111:                          );
 1112:     return %captcha_params;
 1113: }
 1114: 
 1115: sub getkeys {
 1116:     my ($lkey,$ukey) = @_;
 1117:     my $lextkey=hex($lkey);
 1118:     if ($lextkey>2147483647) { $lextkey-=4294967296; }
 1119: 
 1120:     my $uextkey=hex($ukey);
 1121:     if ($uextkey>2147483647) { $uextkey-=4294967296; }
 1122:     return ($lextkey,$uextkey);
 1123: }
 1124: 
 1125: sub serverform {
 1126:     my ($logtoken,$lonhost,$mailtoken,$courseid,$context) = @_;
 1127:     my $phase = 'username_validation';
 1128:     my $catalog_elements;
 1129:     if ($context eq 'selfenroll') {
 1130:         $phase = 'selfenroll_login';
 1131:     }
 1132:     if ($courseid ne '') {
 1133:         $catalog_elements = &Apache::lonhtmlcommon::echo_form_input(['courseid','phase']);
 1134:     } 
 1135:     my $output = <<ENDSERVERFORM;
 1136:   <form name="server" method="post" action="/adm/createaccount">
 1137:    <input type="hidden" name="logtoken" value="$logtoken" />
 1138:    <input type="hidden" name="token" value="$mailtoken" />
 1139:    <input type="hidden" name="serverid" value="$lonhost" />
 1140:    <input type="hidden" name="uname" value="" />
 1141:    <input type="hidden" name="upass" value="" />
 1142:    <input type="hidden" name="phase" value="$phase" />
 1143:    <input type="hidden" name="courseid" value="$courseid" />
 1144:    $catalog_elements
 1145:   </form>
 1146: ENDSERVERFORM
 1147:     return $output;
 1148: }
 1149: 
 1150: sub process_credentials {
 1151:     my ($logtoken,$lonhost) = @_;
 1152:     my $tmpinfo=Apache::lonnet::reply('tmpget:'.$logtoken,$lonhost);
 1153:     my ($retrieved,$output,$upass);
 1154:     if (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost')) {
 1155:         $output = &mt('Information needed to verify your login information is missing, inaccessible or expired.')
 1156:                  .'<br />'.&mt('You may need to reload the previous page to obtain a new token.');
 1157:         return ($retrieved,$output,$upass); 
 1158:     } else {
 1159:         my $reply = &Apache::lonnet::reply('tmpdel:'.$logtoken,$lonhost);
 1160:         if ($reply eq 'ok') {
 1161:             $retrieved = 'ok';
 1162:         } else {
 1163:             $output = &mt('Session could not be opened.');
 1164:         }
 1165:     }
 1166:     my ($key,$caller)=split(/&/,$tmpinfo);
 1167:     if ($caller eq 'createaccount') {
 1168:         $upass = &Apache::lonpreferences::des_decrypt($key,$env{'form.upass'});
 1169:     } else {
 1170:         $output = &mt('Unable to retrieve your log-in information - unexpected context');
 1171:     }
 1172:     return ($retrieved,$output,$upass);
 1173: }
 1174: 
 1175: sub guest_format_check {
 1176:     my ($useremail,$domain,$cancreate,$settings) = @_;
 1177:     my ($login,$format_match,$format_msg,@user_rules);
 1178:     if (ref($settings) eq 'HASH') {
 1179:         if (ref($settings->{'email_rule'}) eq 'ARRAY') {
 1180:             push(@user_rules,@{$settings->{'email_rule'}});
 1181:         }
 1182:     }
 1183:     if (@user_rules > 0) {
 1184:         my %rule_check = 
 1185:             &Apache::lonnet::inst_rulecheck($domain,$useremail,undef,
 1186:                                             'selfcreate',\@user_rules);
 1187:         if (keys(%rule_check) > 0) {
 1188:             foreach my $item (keys(%rule_check)) {
 1189:                 if ($rule_check{$item}) {
 1190:                     $format_match = 1;   
 1191:                     last;
 1192:                 }
 1193:             }
 1194:         }
 1195:     }
 1196:     if ($format_match) {
 1197:         ($login) = ($useremail =~ /^([^\@]+)\@/);
 1198:         $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 />';
 1199:         if (ref($cancreate) eq 'ARRAY') {
 1200:             if (grep(/^login$/,@{$cancreate})) {
 1201:                 $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 />'; 
 1202:             }
 1203:         }
 1204:     }
 1205:     return $format_msg;
 1206: }
 1207: 
 1208: sub sso_logout_frag {
 1209:     my ($r,$domain) = @_;
 1210:     my $endsessionmsg;
 1211:     if (defined($r->dir_config('lonSSOUserLogoutMessageFile_'.$domain))) {
 1212:         my $msgfile = $r->dir_config('lonSSOUserLogoutMessageFile_'.$domain);
 1213:         if (-e $msgfile) {
 1214:             open(my $fh,"<$msgfile");
 1215:             $endsessionmsg = join('',<$fh>);
 1216:             close($fh);
 1217:         }
 1218:     } elsif (defined($r->dir_config('lonSSOUserLogoutMessageFile'))) {
 1219:         my $msgfile = $r->dir_config('lonSSOUserLogoutMessageFile');
 1220:         if (-e $msgfile) {     
 1221:             open(my $fh,"<$msgfile");
 1222:             $endsessionmsg = join('',<$fh>);
 1223:             close($fh);
 1224:         }
 1225:     }
 1226:     return $endsessionmsg;
 1227: }
 1228: 
 1229: sub catreturn_js {
 1230:     return  <<"ENDSCRIPT";
 1231: <script type="text/javascript">
 1232: 
 1233: function ToSelfenroll(formname) {
 1234:     var formidx = getFormByName(formname);
 1235:     if (formidx > -1) {
 1236:         document.forms[formidx].action = '/adm/selfenroll';
 1237:         numidx = getIndexByName(formidx,'phase');
 1238:         if (numidx > -1) {
 1239:             document.forms[formidx].elements[numidx].value = '';   
 1240:         }
 1241:         numidx = getIndexByName(formidx,'context');
 1242:         if (numidx > -1) {
 1243:             document.forms[formidx].elements[numidx].value = '';
 1244:         }
 1245:     }
 1246:     document.forms[formidx].submit();
 1247: }
 1248: 
 1249: function ToCatalog(formname,caller) {
 1250:     var formidx = getFormByName(formname);
 1251:     if (formidx > -1) {
 1252:         document.forms[formidx].action = '/adm/coursecatalog';
 1253:         numidx = getIndexByName(formidx,'coursenum');
 1254:         if (numidx > -1) {
 1255:             if (caller != 'details') {
 1256:                 document.forms[formidx].elements[numidx].value = '';
 1257:             }
 1258:         }
 1259:     }
 1260:     document.forms[formidx].submit();
 1261: }
 1262: 
 1263: function getIndexByName(formidx,item) {
 1264:     for (var i=0;i<document.forms[formidx].elements.length;i++) {
 1265:         if (document.forms[formidx].elements[i].name == item) {
 1266:             return i;
 1267:         }
 1268:     }
 1269:     return -1;
 1270: }
 1271: 
 1272: function getFormByName(item) {
 1273:     for (var i=0; i<document.forms.length; i++) {
 1274:         if (document.forms[i].name == item) {
 1275:             return i;
 1276:         }
 1277:     }
 1278:     return -1;
 1279: }
 1280: 
 1281: </script>
 1282: ENDSCRIPT
 1283: 
 1284: }
 1285: 
 1286: 1;

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