File:  [LON-CAPA] / loncom / interface / createaccount.pm
Revision 1.29: download - view: text, annotated - select for diffs
Thu Mar 12 13:41:11 2009 UTC (15 years, 3 months ago) by bisitz
Branches: MAIN
CVS tags: HEAD
Added "Forgot password?" link to simple login screen, e.g. used for self-enrollment

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

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