File:  [LON-CAPA] / loncom / interface / createaccount.pm
Revision 1.32.2.1: download - view: text, annotated - select for diffs
Mon Sep 14 15:33:48 2009 UTC (14 years, 9 months ago) by raeburn
Branches: GCI_1
Diff to branchpoint 1.32: preferred, unified
- Customization for GCI_1
- Wording changes to use GCI WebCenter
- Use Captcha::reCAPTCHA in place of Authen::Captcha

    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.32.2.1 2009/09/14 15:33:48 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 Captcha::reCAPTCHA;
   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 '') && ($handle !~ /^publicuser_\d+$/)) {
   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 for the GCI WebCenter.').'</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 type="text/javascript" language="JavaScript">
  317:     function send() {
  318:         this.document.server.elements.uname.value = this.document.client.elements.uname.value;
  319:         this.document.server.elements.udom.value = this.document.client.elements.udom.value;
  320:         uextkey=this.document.client.elements.uextkey.value;
  321:         lextkey=this.document.client.elements.lextkey.value;
  322:         initkeys();
  323: 
  324:         this.document.server.elements.upass.value
  325:             = crypted(this.document.client.elements.upass$now.value);
  326: 
  327:         this.document.client.elements.uname.value='';
  328:         this.document.client.elements.upass$now.value='';
  329: 
  330:         this.document.server.submit();
  331:         return false;
  332:     }
  333:  </script>
  334: ENDSCRIPT
  335:     return $js;
  336: }
  337: 
  338: sub javascript_checkpass {
  339:     my ($now) = @_;
  340:     my $nopass = &mt('You must enter a password.');
  341:     my $mismatchpass = &mt('The passwords you entered did not match.').'\\n'.
  342:                        &mt('Please try again.'); 
  343:     my $js = <<"ENDSCRIPT";
  344: <script type="text/javascript" language="JavaScript">
  345:     function checkpass() {
  346:         var upass = this.document.client.elements.upass$now.value;
  347:         var upasscheck = this.document.client.elements.upasscheck$now.value;
  348:         if (upass == '') {
  349:             alert("$nopass");
  350:             return false;
  351:         }
  352:         if (upass == upasscheck) {
  353:             this.document.client.elements.upasscheck$now.value='';
  354:             send();
  355:             return false;
  356:         } else {
  357:             alert("$mismatchpass");
  358:             return false;
  359:         }
  360:     }
  361: </script>
  362: ENDSCRIPT
  363:     return $js;
  364: }
  365: 
  366: sub javascript_validmail {
  367:     my %lt = &Apache::lonlocal::texthash (
  368:                email => 'The e-mail address you entered',
  369:                notv  => 'is not a valid e-mail address',
  370:     );
  371:     my $output =  "\n".'<script type="text/javascript">'."\n".
  372:                   &Apache::lonhtmlcommon::javascript_valid_email()."\n";
  373:     $output .= <<"ENDSCRIPT";
  374: function validate_email() {
  375:     field = document.createaccount.useremail;
  376:     if (validmail(field) == false) {
  377:         alert("$lt{'email'}: "+field.value+" $lt{'notv'}.");
  378:         return false;
  379:     }
  380:     return true;
  381: }
  382: ENDSCRIPT
  383:     $output .= "\n".'</script>'."\n";
  384:     return $output;
  385: }
  386: 
  387: sub print_username_form {
  388:     my ($domain,$domdesc,$cancreate,$now,$lonhost,$courseid) = @_;
  389:     my %lt = &Apache::lonlocal::texthash(
  390:                                          unam => 'username',
  391:                                          udom => 'domain',
  392:                                          uemail => 'E-mail address in LON-CAPA',
  393:                                          proc => 'Proceed');
  394:     my $output;
  395:     if (ref($cancreate) eq 'ARRAY') {
  396:         if (grep(/^login$/,@{$cancreate})) {
  397:             my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
  398:             if ((($domdefaults{'auth_def'} =~/^krb/) && ($domdefaults{'auth_arg_def'} ne '')) || ($domdefaults{'auth_def'} eq 'localauth')) {
  399:                 $output = '<div class="LC_left_float"><h3>'.&mt('Create account with a username provided by this institution').'</h3>';
  400:                 my $submit_text = &mt('Create LON-CAPA account');
  401:                 $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 />';
  402:                 $output .= &login_box($now,$lonhost,$courseid,$submit_text,
  403:                                       $domain,'createaccount').'</div>';
  404:             }
  405:         }
  406:         if (grep(/^email$/,@{$cancreate})) {
  407:             $output .= '<div class="LC_left_float"><h3>'.&mt('Create account with an e-mail address as your username').'</h3>';
  408:             my $captchaform = &create_recaptcha();
  409:             if ($captchaform) {
  410:                 my $submit_text = &mt('Request LON-CAPA account');
  411:                 my $emailform = '<input type="text" name="useremail" size="25" value="" />';
  412:                 if (grep(/^login$/,@{$cancreate})) {
  413:                     $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 />';
  414:                 } else {
  415:                     $output .= '<br />';
  416:                 }
  417:                 $output .=  '<form name="createaccount" method="post" onSubmit="return validate_email()" action="/adm/createaccount">'.
  418:                             &Apache::lonhtmlcommon::start_pick_box()."\n".
  419:                             &Apache::lonhtmlcommon::row_title(&mt('E-mail address'),
  420:                                                              'LC_pick_box_title')."\n".
  421:                             $emailform."\n".
  422:                             &Apache::lonhtmlcommon::row_closure(1).
  423:                             &Apache::lonhtmlcommon::row_title(&mt('Validation'),
  424:                                                              'LC_pick_box_title')."\n".
  425:                             $captchaform."\n".'<br /><br />';
  426:                 if ($courseid ne '') {
  427:                     $output .= '<input type="hidden" name="courseid" value="'.$courseid.'"/>'."\n"; 
  428:                 }
  429:                 $output .=  &Apache::lonhtmlcommon::row_closure(1).
  430:                             &Apache::lonhtmlcommon::row_title().'<br />'.
  431:                             '<input type="submit" name="create_with_email" value="'. 
  432:                             $submit_text.'" />'.
  433:                             &Apache::lonhtmlcommon::row_closure(1).
  434:                             &Apache::lonhtmlcommon::end_pick_box().'<br /><br />';
  435:                 if ($courseid ne '') {
  436:                     $output .= &Apache::lonhtmlcommon::echo_form_input(['courseid']);
  437:                 }
  438:                 $output .= '</form>';
  439:             } else {
  440:                 my $helpdesk = '/adm/helpdesk?origurl=%2fadm%2fcreateaccount';
  441:                 if ($courseid ne '') {
  442:                     $helpdesk .= '&courseid='.$courseid;
  443:                 }
  444:                 $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()">');
  445:             }
  446:             $output .= '</div>';
  447:         }
  448:     }
  449:     if ($output eq '') {
  450:         $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);
  451:     } else {
  452:         $output .= '<div class="LC_clear_float_footer"></div>';
  453:     }
  454:     return $output;
  455: }
  456: 
  457: sub login_box {
  458:     my ($now,$lonhost,$courseid,$submit_text,$domain,$context) = @_;
  459:     my $output;
  460:     my %titles = &Apache::lonlocal::texthash(
  461:                                               createaccount => 'Log-in ID',
  462:                                               selfenroll    => 'Username',
  463:                                             );
  464:     my ($lkey,$ukey) = &Apache::lonpreferences::des_keys();
  465:     my ($lextkey,$uextkey) = &getkeys($lkey,$ukey);
  466:     my $logtoken=Apache::lonnet::reply('tmpput:'.$ukey.$lkey.'&createaccount',
  467:                                        $lonhost);
  468:     $output = &serverform($logtoken,$lonhost,undef,$courseid,$context);
  469:     my $unameform = '<input type="text" name="uname" size="20" value="" />';
  470:     my $upassform = '<input type="password" name="upass'.$now.'" size="20" />';
  471:     $output .= '<form name="client" method="post" onsubmit="return(send());">'."\n".
  472:                &Apache::lonhtmlcommon::start_pick_box()."\n".
  473:                &Apache::lonhtmlcommon::row_title($titles{$context},
  474:                                                  'LC_pick_box_title')."\n".
  475:                $unameform."\n".
  476:                &Apache::lonhtmlcommon::row_closure(1)."\n".
  477:                &Apache::lonhtmlcommon::row_title(&mt('Password'),
  478:                                                 'LC_pick_box_title')."\n".
  479:                $upassform."\n".'<br /><br />'."\n".
  480:                '<input type="button" name="username_validation" value="'.
  481:                $submit_text.'" onclick="javascript:send()" />'."\n".
  482:                &Apache::lonhtmlcommon::row_closure(1)."\n".
  483:                &Apache::lonhtmlcommon::end_pick_box()."\n".
  484:                '<p><a href="/adm/resetpw">'.&mt('Forgot password?').'</a>'.
  485:                '</p>'."\n".
  486:                '<input type="hidden" name="lextkey" value="'.$lextkey.'">'."\n".
  487:                '<input type="hidden" name="uextkey" value="'.$uextkey.'">'."\n".
  488:                '</form>';
  489:     return $output;
  490: }
  491: 
  492: sub process_email_request {
  493:     my ($useremail,$domain,$domdesc,$contact_name,$contact_email,$cancreate,
  494:         $server,$settings,$courseid) = @_;
  495:     $useremail = $env{'form.useremail'};
  496:     my $output;
  497:     if (ref($cancreate) eq 'ARRAY') {
  498:         if (!grep(/^email$/,@{$cancreate})) {
  499:             $output = &invalid_state('noemails',$domdesc,
  500:                                      $contact_name,$contact_email);
  501:             return $output;
  502:         } elsif ($useremail !~ /^[^\@]+\@[^\@]+\.[^\@\.]+$/) {
  503:             $output = &invalid_state('baduseremail',$domdesc,
  504:                                      $contact_name,$contact_email);
  505:             return $output;
  506:         } else {
  507:             my $uhome = &Apache::lonnet::homeserver($useremail,$domain);
  508:             if ($uhome ne 'no_host') {
  509:                 $output = &invalid_state('existinguser',$domdesc,
  510:                                          $contact_name,$contact_email);
  511:                 return $output;
  512:             } else {
  513:                  my $captcha = Captcha::reCAPTCHA->new;
  514:                  my $captcha_result =
  515:                      $captcha->check_answer(
  516:                                             'PRIVATEKEY',
  517:                                             $ENV{'REMOTE_ADDR'},
  518:                                             $env{'form.recaptcha_challenge_field'},
  519:                                             $env{'form.recaptcha_response_field'},
  520:                                            ); # generate private key for IP
  521:                                               # from http://recaptcha.net/
  522:                 if (!$captcha_result->{is_valid}) {
  523:                     $output = &invalid_state('captcha',$domdesc,$contact_name,
  524:                                              $contact_email);
  525:                     return $output;
  526:                 }
  527:                 my $uhome=&Apache::lonnet::homeserver($useremail,$domain);
  528:                 if ($uhome eq 'no_host') {
  529:                     my (%rulematch,%inst_results,%curr_rules,%got_rules,%alerts);
  530:                     &call_rulecheck($useremail,$domain,\%alerts,\%rulematch,
  531:                                     \%inst_results,\%curr_rules,%got_rules,'username');
  532:                     if (ref($alerts{'username'}) eq 'HASH') {
  533:                         if (ref($alerts{'username'}{$domain}) eq 'HASH') {
  534:                             if ($alerts{'username'}{$domain}{$useremail}) {
  535:                                 $output = &invalid_state('userrules',$domdesc,
  536:                                                          $contact_name,$contact_email);
  537:                                 return $output;
  538:                             }
  539:                         }
  540:                     }
  541:                     my $format_msg = 
  542:                         &guest_format_check($useremail,$domain,$cancreate,
  543:                                             $settings);
  544:                     if ($format_msg) {
  545:                         $output = &invalid_state('userformat',$domdesc,$contact_name,
  546:                                                  $contact_email,$format_msg);
  547:                         return $output;
  548:                     }
  549:                 }
  550:             }
  551:         }
  552:         $output = &send_token($domain,$useremail,$server,$domdesc,$contact_name,
  553:                           $contact_email,$courseid);
  554:     }
  555:     return $output;
  556: }
  557: 
  558: sub call_rulecheck {
  559:     my ($uname,$udom,$alerts,$rulematch,$inst_results,$curr_rules,
  560:         $got_rules,$tocheck) = @_;
  561:     my ($checkhash,$checks);
  562:     $checkhash->{$uname.':'.$udom} = { 'newuser' => 1, };
  563:     if ($tocheck eq 'username') {
  564:         $checks = { 'username' => 1 };
  565:     }
  566:     &Apache::loncommon::user_rule_check($checkhash,$checks,
  567:            $alerts,$rulematch,$inst_results,$curr_rules,
  568:            $got_rules);
  569:     return;
  570: }
  571: 
  572: sub send_token {
  573:     my ($domain,$email,$server,$domdesc,$contact_name,$contact_email,$courseid) = @_;
  574:     my $msg = '<h3>'.&mt('Account creation status').'</h3>'.
  575:               &mt('Thank you for your request to create a new LON-CAPA account.').
  576:               '<br /><br />';
  577:     my $now = time;
  578:     my %info = ('ip'         => $ENV{'REMOTE_ADDR'},
  579:                 'time'       => $now,
  580:                 'domain'     => $domain,
  581:                 'username'   => $email,
  582:                 'courseid'   => $courseid);
  583:     my $token = &Apache::lonnet::tmpput(\%info,$server);
  584:     if ($token !~ /^error/ && $token ne 'no_such_host') {
  585:         my $esc_token = &escape($token);
  586:         my $showtime = localtime(time);
  587:         my $mailmsg = &mt('A request was submitted on [_1] for creation of a GCI WebCenter account.',$showtime).' '.
  588:              &mt('To complete this process please open a web browser and enter the following URL in the address/location box: [_1]',
  589:                  &Apache::lonnet::absolute_url().'/adm/createaccount?token='.$esc_token);
  590:         my $result = &Apache::resetpw::send_mail($domdesc,$email,$mailmsg,$contact_name,
  591:                                                  $contact_email);
  592:         if ($result eq 'ok') {
  593:             $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>');
  594:         } else {
  595:             $msg .= '<span class="LC_error">'.
  596:                     &mt('An error occurred when sending a message to the e-mail address you provided.').'</span><br />'.
  597:                     ' '.&mt('Please contact the [_1] ([_2]) for assistance.',$contact_name,$contact_email);
  598:         }
  599:     } else {
  600:         $msg .= '<span class="LC_error">'.
  601:                 &mt('An error occurred creating a token required for the account creation process.').'</span><br />'.
  602:                 ' '.&mt('Please contact the [_1] ([_2]) for assistance.',$contact_name,$contact_email);
  603:     }
  604:     return $msg;
  605: }
  606: 
  607: sub process_mailtoken {
  608:     my ($r,$token,$contact_name,$contact_email,$domain,$domdesc,$lonhost,
  609:         $include,$start_page) = @_;
  610:     my ($msg,$nostart,$noend);
  611:     my %data = &Apache::lonnet::tmpget($token);
  612:     my $now = time;
  613:     if (keys(%data) == 0) {
  614:         $msg = &mt('Sorry, the URL you provided to complete creation of a new LON-CAPA account was invalid.')
  615:                .' '.&mt('Either the token included in the URL has been deleted or the URL you provided was invalid.')
  616:                .' '.&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>');
  617:         return $msg;
  618:     }
  619:     if (($data{'time'} =~ /^\d+$/) &&
  620:         ($data{'domain'} ne '') &&
  621:         ($data{'username'}  =~ /^[^\@]+\@[^\@]+\.[^\@\.]+$/)) {
  622:         if ($now - $data{'time'} < 7200) {
  623:             if ($env{'form.phase'} eq 'createaccount') {
  624:                 my ($result,$output) = &create_account($r,$domain,$lonhost,
  625:                                                        $data{'username'},$domdesc);
  626:                 if ($result eq 'ok') {
  627:                     $msg = $output; 
  628:                     my $shownow = &Apache::lonlocal::locallocaltime($now);
  629:                     my $mailmsg = &mt('A GCI WebCenter account has been created [_1] from IP address: [_2].  If you did not perform this action or authorize it, please contact the [_3] ([_4]).',$shownow,$ENV{'REMOTE_ADDR'},$contact_name,$contact_email)."\n";
  630:                     my $mailresult = &Apache::resetpw::send_mail($domdesc,$data{'email'},
  631:                                                                  $mailmsg,$contact_name,
  632:                                                                  $contact_email);
  633:                     if ($mailresult eq 'ok') {
  634:                         $msg .= &mt('An e-mail confirming creation of your new LON-CAPA account has been sent to [_1].',$data{'username'});
  635:                     } else {
  636:                         $msg .= &mt('An error occurred when sending e-mail to [_1] confirming creation of your LON-CAPA account.',$data{'username'});
  637:                     }
  638:                     my %form = &start_session($r,$data{'username'},$domain, 
  639:                                               $lonhost,$data{'courseid'},
  640:                                               $token);
  641:                     $nostart = 1;
  642:                     $noend = 1;
  643:                 } else {
  644:                     $msg .= &mt('A problem occurred when attempting to create your new LON-CAPA account.')
  645:                            .'<br />'.$output
  646: #                           .&mt('Please contact the [_1] ([_2]) for assistance.',$contact_name,'<a href="mailto:'.$contact_email.'">'.$contact_email.'</a>');
  647:                            .&mt('Please contact the [_1] ([_2]) for assistance.',$contact_name,$contact_email);
  648:                 }
  649:                 my $delete = &Apache::lonnet::tmpdel($token);
  650:             } else {
  651:                 $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 />';
  652:                 $msg .= &print_dataentry_form($r,$domain,$lonhost,$include,$token,$now,$data{'username'},$start_page);
  653:                 $nostart = 1;
  654:             }
  655:         } else {
  656:             $msg = &mt('Sorry, the token generated when you requested creation of an account has expired.')
  657:                   .' '.&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>');
  658:             }
  659:     } else {
  660:         $msg .= &mt('Sorry, the URL generated when you requested creation of an account contained incomplete information.')
  661:                .' '.&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>');
  662:     }
  663:     return ($msg,$nostart,$noend);
  664: }
  665: 
  666: sub start_session {
  667:     my ($r,$username,$domain,$lonhost,$courseid,$token) = @_;
  668:     my %form = (
  669:                 uname => $username,
  670:                 udom  => $domain,
  671:                );
  672:     my $firsturl = '/adm/roles';
  673:     if (defined($courseid)) {
  674:         $courseid = &validate_course($courseid);
  675:         if ($courseid ne '') {
  676:             $form{'courseid'} = $courseid;
  677:             $firsturl = '/adm/selfenroll?courseid='.$courseid;
  678:         }
  679:     }
  680:     if ($r->dir_config('lonBalancer') eq 'yes') {
  681:         &Apache::lonauth::success($r,$form{'uname'},$form{'udom'},
  682:                                   $lonhost,'noredirect',undef,\%form);
  683:         if ($token ne '') { 
  684:             my $delete = &Apache::lonnet::tmpdel($token);
  685:         }
  686:         $r->internal_redirect('/adm/switchserver');
  687:     } else {
  688:         &Apache::lonauth::success($r,$form{'uname'},$form{'udom'},
  689:                                   $lonhost,$firsturl,undef,\%form);
  690:     }
  691:     return %form;
  692: }
  693: 
  694: 
  695: sub print_dataentry_form {
  696:     my ($r,$domain,$lonhost,$include,$mailtoken,$now,$username,$start_page) = @_;
  697:     my ($error,$output);
  698:     &print_header($r,$start_page);
  699:     if (open(my $jsh,"<$include/londes.js")) {
  700:         while(my $line = <$jsh>) {
  701:             $r->print($line);
  702:         }
  703:         close($jsh);
  704:         $output .= &javascript_setforms($now)."\n".&javascript_checkpass($now);
  705:         my ($lkey,$ukey) = &Apache::lonpreferences::des_keys();
  706:         my ($lextkey,$uextkey) = &getkeys($lkey,$ukey);
  707:         my $logtoken=Apache::lonnet::reply('tmpput:'.$ukey.$lkey.'&createaccount',
  708:                                            $lonhost);
  709:         my $formtag = '<form name="server" method="post" target="_top" action="/adm/createaccount">';
  710:         my ($datatable,$rowcount,$editable) =
  711:             &Apache::loncreateuser::personal_data_display($username,$domain,
  712:                                                           'email','selfcreate');
  713:         if ($rowcount) {
  714:             $output .= '<div class="LC_left_float">'.$formtag.$datatable;
  715:         } else {
  716:             $output .= $formtag;
  717:         }
  718:         $output .= <<"ENDSERVERFORM";
  719:    <input type="hidden" name="logtoken" value="$logtoken" />
  720:    <input type="hidden" name="token" value="$mailtoken" />
  721:    <input type="hidden" name="serverid" value="$lonhost" />
  722:    <input type="hidden" name="uname" value="" />
  723:    <input type="hidden" name="upass" value="" />
  724:    <input type="hidden" name="udom" value="" />
  725:    <input type="hidden" name="phase" value="createaccount" />
  726:   </form>
  727: ENDSERVERFORM
  728:         if ($rowcount) {
  729:             $output .= '</div>'.
  730:                        '<div class="LC_left_float">';
  731:         }
  732:         my $upassone = '<input type="password" name="upass'.$now.'" size="10" />';
  733:         my $upasstwo = '<input type="password" name="upasscheck'.$now.'" size="10" />';
  734:         my $submit_text = &mt('Create LON-CAPA account');
  735:         $output .= '<h3>'.&mt('Login Data').'</h3>'."\n".
  736:                    '<form name="client" method="post" '.
  737:                    'onsubmit="return checkpass();">'."\n".
  738:                    &Apache::lonhtmlcommon::start_pick_box()."\n".
  739:                    &Apache::lonhtmlcommon::row_title(&mt('Username'),
  740:                                                      'LC_pick_box_title',
  741:                                                      'LC_oddrow_value')."\n".
  742:                    $username."\n".
  743:                    &Apache::lonhtmlcommon::row_closure(1)."\n".
  744:                    &Apache::lonhtmlcommon::row_title(&mt('Password'),
  745:                                                     'LC_pick_box_title',
  746:                                                     'LC_oddrow_value')."\n".
  747:                    $upassone."\n".
  748:                    &Apache::lonhtmlcommon::row_closure(1)."\n".
  749:                    &Apache::lonhtmlcommon::row_title(&mt('Confirm password'),
  750:                                                      'LC_pick_box_title',
  751:                                                      'LC_oddrow_value')."\n".
  752:                    $upasstwo.
  753:                    &Apache::lonhtmlcommon::row_closure(1)."\n".
  754:                    &Apache::lonhtmlcommon::row_title()."\n".
  755:                    '<br /><input type="submit" name="createaccount" value="'.
  756:                    $submit_text.'" />'.
  757:                    &Apache::lonhtmlcommon::row_closure(1)."\n".
  758:                    &Apache::lonhtmlcommon::end_pick_box()."\n".
  759:                    '<input type="hidden" name="uname" value="'.$username.'" />'."\n".
  760:                    '<input type="hidden" name="udom" value="'.$domain.'" />'."\n".
  761:                    '<input type="hidden" name="lextkey" value="'.$lextkey.'" />'."\n".
  762:                    '<input type="hidden" name="uextkey" value="'.$uextkey.'" />'."\n".
  763:                    '</form>';
  764:         if ($rowcount) {
  765:             $output .= '</div>'."\n".
  766:                        '<div class="LC_clear_float_footer"></div>'."\n";
  767:         }
  768:     } else {
  769:         $output = &mt('Could not load javascript file [_1]','<tt>londes.js</tt>');
  770:     }
  771:     return $output;
  772: }
  773: 
  774: sub create_account {
  775:     my ($r,$domain,$lonhost,$username,$domdesc) = @_;
  776:     my ($retrieved,$output,$upass) = &process_credentials($env{'form.logtoken'},
  777:                                                           $env{'form.serverid'}); 
  778:     # Error messages
  779:     my $error     = '<span class="LC_error">'.&mt('Error:').' ';
  780:     my $end       = '</span><br /><br />';
  781:     my $rtnlink   = '<a href="javascript:history.back();" />'.
  782:                     &mt('Return to previous page').'</a>'.
  783:                     &Apache::loncommon::end_page();
  784:     if ($retrieved eq 'ok') {
  785:         if ($env{'form.courseid'} ne '') {
  786:             my ($result,$userchkmsg) = &check_id($username,$domain,$domdesc);
  787:             if ($result eq 'fail') {
  788:                 $output = $error.&mt('Invalid ID format').$end.
  789:                           $userchkmsg.$rtnlink;
  790:                 return ('fail',$output);
  791:             }
  792:         }
  793:     } else {
  794:         return ('fail',$error.$output.$end.$rtnlink);
  795:     }
  796:     # Call modifyuser
  797:     my $result = 
  798:         &Apache::lonnet::modifyuser($domain,$username,$env{'form.cid'},
  799:                                     'internal',$upass,$env{'form.cfirstname'},
  800:                                     $env{'form.cmiddlename'},$env{'form.clastname'},
  801:                                     $env{'form.cgeneration'},undef,undef,$username);
  802:     $output = &mt('Generating user: [_1]',$result);
  803:     my $uhome = &Apache::lonnet::homeserver($username,$domain);
  804:     $output .= '<br />'.&mt('Home server: [_1]',$uhome).' '.
  805:               &Apache::lonnet::hostname($uhome).'<br /><br />';
  806:     return ('ok',$output);
  807: }
  808: 
  809: sub username_validation {
  810:     my ($r,$username,$domain,$domdesc,$contact_name,$contact_email,$courseid,
  811:         $lonhost) = @_;
  812:     my ($retrieved,$output,$upass);
  813: 
  814:     $username= &LONCAPA::clean_username($username);
  815:     $domain = &LONCAPA::clean_domain($domain);
  816:     my $uhome = &Apache::lonnet::homeserver($username,$domain);
  817: 
  818:     ($retrieved,$output,$upass) = &process_credentials($env{'form.logtoken'},
  819:                                                        $env{'form.serverid'});
  820:     if ($retrieved ne 'ok') {
  821:         return ('fail',$output);
  822:     }
  823:     if ($uhome ne 'no_host') {
  824:         my $result = &Apache::lonnet::authenticate($username,$upass,$domain);
  825:         if ($result ne 'no_host') { 
  826:             my %form = &start_session($r,$username,$domain,$lonhost,$courseid);
  827:             $output = '<br /><br />'.&mt('A GCI WebCenter account already exists for username [_1].','<tt>'.$username.'</tt>').'<br />'.&mt('The password entered was also correct so you have been logged in.');
  828:             return ('existingaccount',$output);
  829:         } else {
  830:             $output = &login_failure_msg($courseid);
  831:         }
  832:     } else {
  833:         my $primlibserv = &Apache::lonnet::domain($domain,'primary');
  834:         my $authok;
  835:         my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
  836:         if ((($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) || ($domdefaults{'auth_def'} eq 'localauth')) {
  837:             my $checkdefauth = 1;
  838:             $authok = 
  839:                 &Apache::lonnet::reply("encrypt:auth:$domain:$username:$upass:$checkdefauth",$primlibserv);
  840:         } else {
  841:             $authok = 'non_authorized';
  842:         }
  843:         if ($authok eq 'authorized') {
  844:             $output = &username_check($username,$domain,$domdesc,$courseid,$lonhost,
  845:                                       $contact_email,$contact_name);
  846:         } else {
  847:             $output = &login_failure_msg($courseid);
  848:         }
  849:     }
  850:     return ('ok',$output);
  851: }
  852: 
  853: sub login_failure_msg {
  854:     my ($courseid) = @_;
  855:     my $url;
  856:     if ($courseid ne '') {
  857:         $url = "/adm/selfenroll?courseid=".$courseid;
  858:     } else {
  859:         $url = "/adm/createaccount";
  860:     }
  861:     my $output = '<h4>'.&mt('Authentication failed').'</h4><div class="LC_warning">'.
  862:                  &mt('Username and/or password could not be authenticated.').
  863:                  '</div>'.
  864:                  &mt('Please check the username and password.').'<br /><br />';
  865:                  '<a href="'.$url.'">'.&mt('Try again').'</a>';
  866:     return $output;
  867: }
  868: 
  869: sub username_check {
  870:     my ($username,$domain,$domdesc,$courseid,$lonhost,$contact_email,$contact_name,
  871:         $sso_logout) = @_;
  872:     my (%rulematch,%inst_results,$checkfail,$rowcount,$editable,$output,$msg,
  873:         %alerts,%curr_rules,%got_rules);
  874:     &call_rulecheck($username,$domain,\%alerts,\%rulematch,
  875:                     \%inst_results,\%curr_rules,%got_rules,'username');
  876:     if (ref($alerts{'username'}) eq 'HASH') {
  877:         if (ref($alerts{'username'}{$domain}) eq 'HASH') {
  878:             if ($alerts{'username'}{$domain}{$username}) {
  879:                 if (ref($curr_rules{$domain}) eq 'HASH') {
  880:                     $output =
  881:                         &Apache::loncommon::instrule_disallow_msg('username',$domdesc,1,
  882:                                                                   'selfcreate').
  883:                         &Apache::loncommon::user_rule_formats($domain,$domdesc,
  884:                                 $curr_rules{$domain}{'username'},'username');
  885:                 }
  886:                 $checkfail = 'username';
  887:             }
  888:         }
  889:     }
  890:     if (!$checkfail) {
  891:         $output = '<form method="post" action="/adm/createaccount">';
  892:         (my $datatable,$rowcount,$editable) = 
  893:             &Apache::loncreateuser::personal_data_display($username,$domain,1,'selfcreate',
  894:                                                          $inst_results{$username.':'.$domain});
  895:         if ($rowcount > 0) {
  896:             $output .= $datatable;
  897:         }
  898:         $output .=  '<br /><br /><input type="hidden" name="uname" value="'.$username.'" />'."\n".
  899:                     '<input type="hidden" name="udom" value="'.$domain.'" />'."\n".
  900:                     '<input type="hidden" name="phase" value="username_activation" />';
  901:         my $now = time;
  902:         my %info = ('ip'         => $ENV{'REMOTE_ADDR'},
  903:                     'time'       => $now,
  904:                     'domain'     => $domain,
  905:                     'username'   => $username);
  906:         my $authtoken = &Apache::lonnet::tmpput(\%info,$lonhost);
  907:         if ($authtoken !~ /^error/ && $authtoken ne 'no_such_host') {
  908:             $output .= '<input type="hidden" name="authtoken" value="'.&HTML::Entities::encode($authtoken,'&<>"').'" />';
  909:         } else {
  910:             $output = &mt('An error occurred when storing a token').'<br />'.
  911:                       &mt('You will not be able to proceed to the next stage of account creation').
  912:                       &linkto_email_help($contact_email,$domdesc);
  913:             $checkfail = 'authtoken';
  914:         }
  915:     }
  916:     if ($checkfail) { 
  917:         $msg = '<h4>'.&mt('Account creation unavailable').'</h4>';
  918:         if ($checkfail eq 'username') {
  919:             $msg .= '<span class="LC_warning">'.
  920:                      &mt('A LON-CAPA account may not be created with the username you use.').
  921:                      '</span><br /><br />'.$output;
  922:         } elsif ($checkfail eq 'authtoken') {
  923:             $msg .= '<span class="LC_error">'.&mt('Error creating token.').'</span>'.
  924:                     '<br />'.$output;
  925:         }
  926:         $msg .= &mt('Please contact the [_1] ([_2]) for assistance.',
  927:                 $contact_name,$contact_email).'<br /><hr />'.
  928:                 $sso_logout;
  929:         &Apache::lonnet::logthis("ERROR: failure type of '$checkfail' when performing username check to create account for authenticated user: $username, in domain $domain");
  930:     } else {
  931:         if ($courseid ne '') {
  932:             $output .= '<input type="hidden" name="courseid" value="'.$courseid.'" />';
  933:         }
  934:         $output .= '<input type="submit" name="newaccount" value="'.
  935:                    &mt('Create LON-CAPA account').'" /></form>';
  936:         if ($rowcount) {
  937:             if ($editable) {
  938:                 if ($courseid ne '') { 
  939:                     $msg = '<h4>'.&mt('User information').'</h4>';
  940:                 }
  941:                 $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 />';
  942:             } else {
  943:                  if ($courseid ne '') {
  944:                      $msg = '<h4>'.&mt('Review user information').'</h4>';
  945:                  }
  946:                  $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 />';
  947:             }
  948:         } else {
  949:             if ($courseid ne '') {
  950:                 $msg = '<h4>'.&mt('Confirmation').'</h4>';
  951:             }
  952:             $msg .= &mt('Confirm that you wish to create an account.');
  953:         }
  954:         $msg .= $output;
  955:     }
  956:     return $msg;
  957: }
  958: 
  959: sub username_activation {
  960:     my ($r,$username,$domain,$domdesc,$lonhost,$courseid) = @_;
  961:     my $output;
  962:     my $error     = '<span class="LC_error">'.&mt('Error:').' ';
  963:     my $end       = '</span><br /><br />';
  964:     my $rtnlink   = '<a href="javascript:history.back();" />'.
  965:                     &mt('Return to previous page').'</a>'.
  966:                     &Apache::loncommon::end_page();
  967:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
  968:     my %data = &Apache::lonnet::tmpget($env{'form.authtoken'});
  969:     my $now = time;
  970:     my $earlyout;
  971:     my $timeout = 300;
  972:     if (keys(%data) == 0) {
  973:         $output = &mt('Sorry, your authentication has expired.');
  974:         $earlyout = 'fail';
  975:     }
  976:     if (($data{'time'} !~ /^\d+$/) ||
  977:         ($data{'domain'} ne $domain) || 
  978:         ($data{'username'} ne $username)) {
  979:         $earlyout = 'fail';
  980:         $output = &mt('The credentials you provided could not be verified.');   
  981:     } elsif ($now - $data{'time'} > $timeout) {
  982:         $earlyout = 'fail';
  983:         $output = &mt('Sorry, your authentication has expired.');
  984:     }
  985:     if ($earlyout ne '') {
  986:         $output .= '<br />'.&mt('Please [_1]start again[_2].','<a href="/adm/createaccount">','</a>');
  987:         return($earlyout,$output);
  988:     }
  989:     if ((($domdefaults{'auth_def'} =~/^krb(4|5)$/) && 
  990:          ($domdefaults{'auth_arg_def'} ne '')) || 
  991:         ($domdefaults{'auth_def'} eq 'localauth')) {
  992:         if ($env{'form.courseid'} ne '') {
  993:             my ($result,$userchkmsg) = &check_id($username,$domain,$domdesc);
  994:             if ($result eq 'fail') {
  995:                 $output = $error.&mt('Invalid ID format').$end.
  996:                           $userchkmsg.$rtnlink;
  997:                 return ('fail',$output);
  998:             }
  999:         }
 1000:         # Call modifyuser
 1001:         my (%rulematch,%inst_results,%curr_rules,%got_rules,%alerts,%info);
 1002:         &call_rulecheck($username,$domain,\%alerts,\%rulematch,
 1003:                         \%inst_results,\%curr_rules,%got_rules);
 1004:         my @userinfo = ('firstname','middlename','lastname','generation',
 1005:                         'permanentemail','id');
 1006:         my %canmodify = 
 1007:             &Apache::loncreateuser::selfcreate_canmodify('selfcreate',$domain,
 1008:                                                          \@userinfo,\%inst_results);
 1009:         foreach my $item (@userinfo) {
 1010:             if ($canmodify{$item}) {
 1011:                 $info{$item} = $env{'form.c'.$item};
 1012:             } else {
 1013:                 $info{$item} = $inst_results{$username.':'.$domain}{$item}; 
 1014:             }
 1015:         }
 1016:         if (ref($inst_results{$username.':'.$domain}{'inststatus'}) eq 'ARRAY') {
 1017:             my @inststatuses = @{$inst_results{$username.':'.$domain}{'inststatus'}};
 1018:             $info{'inststatus'} = join(':',map { &escape($_); } @inststatuses);
 1019:         }
 1020:         my $result =
 1021:             &Apache::lonnet::modifyuser($domain,$username,$env{'form.cid'},
 1022:                           $domdefaults{'auth_def'},
 1023:                           $domdefaults{'auth_arg_def'},$info{'firstname'},
 1024:                           $info{'middlename'},$info{'lastname'},
 1025:                           $info{'generation'},undef,undef,
 1026:                           $info{'permanentemail'},$info{'inststatus'});
 1027:         if ($result eq 'ok') {
 1028:             my $delete = &Apache::lonnet::tmpdel($env{'form.authtoken'});
 1029:             $output = &mt('A LON-CAPA account has been created for username: [_1] in domain: [_2].',$username,$domain);
 1030:             my %form = &start_session($r,$username,$domain,$lonhost,$courseid);
 1031:             my $nostart = 1;
 1032:             return ('ok',$output,$nostart);
 1033:         } else {
 1034:             $output = &mt('Account creation failed for username: [_1] in domain: [_2].',$username,$domain).'<br /><span class="LC_error">'.&mt('Error: [_1]',$result).'</span>';
 1035:             return ('fail',$output);
 1036:         }
 1037:     } else {
 1038:         $output = &mt('User account creation is not available for the current default authentication type.')."\n";
 1039:         return('fail',$output);
 1040:     }
 1041: }
 1042: 
 1043: sub check_id {
 1044:     my ($username,$domain,$domdesc) = @_;
 1045:     # Check ID format
 1046:     my (%alerts,%rulematch,%inst_results,%curr_rules,%checkhash);
 1047:     my %checks = ('id' => 1);
 1048:     %{$checkhash{$username.':'.$domain}} = (
 1049:                                             'newuser' => 1,
 1050:                                             'id' => $env{'form.cid'},
 1051:                                            );
 1052:     &Apache::loncommon::user_rule_check(\%checkhash,\%checks,\%alerts,
 1053:                                         \%rulematch,\%inst_results,\%curr_rules);
 1054:     if (ref($alerts{'id'}) eq 'HASH') {
 1055:         if (ref($alerts{'id'}{$domain}) eq 'HASH') {
 1056:             if ($alerts{'id'}{$domain}{$env{'form.cid'}}) {
 1057:                 my $userchkmsg;
 1058:                 if (ref($curr_rules{$domain}) eq 'HASH') {
 1059:                     $userchkmsg  =
 1060:                         &Apache::loncommon::instrule_disallow_msg('id',
 1061:                                                            $domdesc,1).
 1062:                         &Apache::loncommon::user_rule_formats($domain,
 1063:                               $domdesc,$curr_rules{$domain}{'id'},'id');
 1064:                 }
 1065:                 return ('fail',$userchkmsg);
 1066:             }
 1067:         }
 1068:     }
 1069:     return; 
 1070: }
 1071: 
 1072: sub invalid_state {
 1073:     my ($error,$domdesc,$contact_name,$contact_email,$msgtext) = @_;
 1074:     my $msg = '<h3>'.&mt('Account creation unavailable').'</h3><span class="LC_error">';
 1075:     if ($error eq 'baduseremail') {
 1076:         $msg = &mt('The e-mail address you provided does not appear to be a valid address.');
 1077:     } elsif ($error eq 'existinguser') {
 1078:         $msg = &mt('The e-mail address you provided is already in use as a username in LON-CAPA at this institution.');
 1079:     } elsif ($error eq 'userrules') {
 1080:         $msg = &mt('Username rules at this institution do not allow the e-mail address you provided to be used as a username.');
 1081:     } elsif ($error eq 'userformat') {
 1082:         $msg = &mt('The e-mail address you provided may not be used as a username at this LON-CAPA institution.');
 1083:     } elsif ($error eq 'captcha') {
 1084:         $msg = &mt('Validation of the code your entered failed.');
 1085:     } elsif ($error eq 'noemails') {
 1086:         $msg = &mt('Creation of a new user account using an e-mail address as username is not permitted at this LON-CAPA institution.');
 1087:     }
 1088:     $msg .= '</span>';
 1089:     if ($msgtext) {
 1090:         $msg .= '<br />'.$msgtext;
 1091:     }
 1092:     $msg .= &linkto_email_help($contact_email,$domdesc);
 1093:     return $msg;
 1094: }
 1095: 
 1096: sub linkto_email_help {
 1097:     my ($contact_email,$domdesc) = @_;
 1098:     my $msg;
 1099:     if ($contact_email ne '') {
 1100:         my $escuri = &HTML::Entities::encode('/adm/createaccount','&<>"');
 1101:         $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 />';
 1102:     } else {
 1103:         $msg .= '<br />'.&mt('You may wish to send an e-mail to the server administrator: [_1] for [_2].',$Apache::lonnet::perlvar{'AdminEmail'},$domdesc).'<br />';
 1104:     }
 1105:     return $msg;
 1106: }
 1107: 
 1108: sub create_recaptcha {
 1109:     my $captcha = Captcha::reCAPTCHA->new;
 1110:     return $captcha->get_options_setter({theme => 'white'})."\n".
 1111:            $captcha->get_html('PUBLICKEY');  # generate public key for IP
 1112:                                              # from http://recaptcha.net/
 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="udom" value="" />
 1143:    <input type="hidden" name="phase" value="$phase" />
 1144:    <input type="hidden" name="courseid" value="$courseid" />
 1145:    $catalog_elements
 1146:   </form>
 1147: ENDSERVERFORM
 1148:     return $output;
 1149: }
 1150: 
 1151: sub process_credentials {
 1152:     my ($logtoken,$lonhost) = @_;
 1153:     my $tmpinfo=Apache::lonnet::reply('tmpget:'.$logtoken,$lonhost);
 1154:     my ($retrieved,$output,$upass);
 1155:     if (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost')) {
 1156:         $output = &mt('Information needed to verify your login information is missing, inaccessible or expired.')
 1157:                  .'<br />'.&mt('You may need to reload the previous page to obtain a new token.');
 1158:         return ($retrieved,$output,$upass); 
 1159:     } else {
 1160:         my $reply = &Apache::lonnet::reply('tmpdel:'.$logtoken,$lonhost);
 1161:         if ($reply eq 'ok') {
 1162:             $retrieved = 'ok';
 1163:         } else {
 1164:             $output = &mt('Session could not be opened.');
 1165:         }
 1166:     }
 1167:     my ($key,$caller)=split(/&/,$tmpinfo);
 1168:     if ($caller eq 'createaccount') {
 1169:         $upass = &Apache::lonpreferences::des_decrypt($key,$env{'form.upass'});
 1170:     } else {
 1171:         $output = &mt('Unable to retrieve your log-in information - unexpected context');
 1172:     }
 1173:     return ($retrieved,$output,$upass);
 1174: }
 1175: 
 1176: sub guest_format_check {
 1177:     my ($useremail,$domain,$cancreate,$settings) = @_;
 1178:     my ($login,$format_match,$format_msg,@user_rules);
 1179:     if (ref($settings) eq 'HASH') {
 1180:         if (ref($settings->{'email_rule'}) eq 'ARRAY') {
 1181:             push(@user_rules,@{$settings->{'email_rule'}});
 1182:         }
 1183:     }
 1184:     if (@user_rules > 0) {
 1185:         my %rule_check = 
 1186:             &Apache::lonnet::inst_rulecheck($domain,$useremail,undef,
 1187:                                             'selfcreate',\@user_rules);
 1188:         if (keys(%rule_check) > 0) {
 1189:             foreach my $item (keys(%rule_check)) {
 1190:                 if ($rule_check{$item}) {
 1191:                     $format_match = 1;   
 1192:                     last;
 1193:                 }
 1194:             }
 1195:         }
 1196:     }
 1197:     if ($format_match) {
 1198:         ($login) = ($useremail =~ /^([^\@]+)\@/);
 1199:         $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 />';
 1200:         if (ref($cancreate) eq 'ARRAY') {
 1201:             if (grep(/^login$/,@{$cancreate})) {
 1202:                 $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 />'; 
 1203:             }
 1204:         }
 1205:     }
 1206:     return $format_msg;
 1207: }
 1208: 
 1209: sub sso_logout_frag {
 1210:     my ($r,$domain) = @_;
 1211:     my $endsessionmsg;
 1212:     if (defined($r->dir_config('lonSSOUserLogoutMessageFile_'.$domain))) {
 1213:         my $msgfile = $r->dir_config('lonSSOUserLogoutMessageFile_'.$domain);
 1214:         if (-e $msgfile) {
 1215:             open(my $fh,"<$msgfile");
 1216:             $endsessionmsg = join('',<$fh>);
 1217:             close($fh);
 1218:         }
 1219:     } elsif (defined($r->dir_config('lonSSOUserLogoutMessageFile'))) {
 1220:         my $msgfile = $r->dir_config('lonSSOUserLogoutMessageFile');
 1221:         if (-e $msgfile) {     
 1222:             open(my $fh,"<$msgfile");
 1223:             $endsessionmsg = join('',<$fh>);
 1224:             close($fh);
 1225:         }
 1226:     }
 1227:     return $endsessionmsg;
 1228: }
 1229: 
 1230: sub catreturn_js {
 1231:     return  <<"ENDSCRIPT";
 1232: <script type="text/javascript">
 1233: 
 1234: function ToSelfenroll(formname) {
 1235:     var formidx = getFormByName(formname);
 1236:     if (formidx > -1) {
 1237:         document.forms[formidx].action = '/adm/selfenroll';
 1238:         numidx = getIndexByName(formidx,'phase');
 1239:         if (numidx > -1) {
 1240:             document.forms[formidx].elements[numidx].value = '';   
 1241:         }
 1242:         numidx = getIndexByName(formidx,'context');
 1243:         if (numidx > -1) {
 1244:             document.forms[formidx].elements[numidx].value = '';
 1245:         }
 1246:     }
 1247:     document.forms[formidx].submit();
 1248: }
 1249: 
 1250: function ToCatalog(formname,caller) {
 1251:     var formidx = getFormByName(formname);
 1252:     if (formidx > -1) {
 1253:         document.forms[formidx].action = '/adm/coursecatalog';
 1254:         numidx = getIndexByName(formidx,'coursenum');
 1255:         if (numidx > -1) {
 1256:             if (caller != 'details') {
 1257:                 document.forms[formidx].elements[numidx].value = '';
 1258:             }
 1259:         }
 1260:     }
 1261:     document.forms[formidx].submit();
 1262: }
 1263: 
 1264: function getIndexByName(formidx,item) {
 1265:     for (var i=0;i<document.forms[formidx].elements.length;i++) {
 1266:         if (document.forms[formidx].elements[i].name == item) {
 1267:             return i;
 1268:         }
 1269:     }
 1270:     return -1;
 1271: }
 1272: 
 1273: function getFormByName(item) {
 1274:     for (var i=0; i<document.forms.length; i++) {
 1275:         if (document.forms[i].name == item) {
 1276:             return i;
 1277:         }
 1278:     }
 1279:     return -1;
 1280: }
 1281: 
 1282: </script>
 1283: ENDSCRIPT
 1284: 
 1285: }
 1286: 
 1287: 1;

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