File:  [LON-CAPA] / loncom / interface / createaccount.pm
Revision 1.40.2.3: download - view: text, annotated - select for diffs
Fri Dec 24 20:36:11 2010 UTC (13 years, 4 months ago) by raeburn
Branches: version_2_10_X
CVS tags: version_2_10_0_RC2, version_2_10_0
- Backport 1.43, 1.44, 1.45.

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

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