File:  [LON-CAPA] / loncom / interface / createaccount.pm
Revision 1.37: download - view: text, annotated - select for diffs
Fri Oct 23 16:14:43 2009 UTC (14 years, 7 months ago) by bisitz
Branches: MAIN
CVS tags: version_2_9_X, version_2_9_99_0, version_2_9_0, version_2_8_99_1, bz6209-base, bz6209, HEAD, GCI_3
Consistent wording "Course Catalog" -> "Course/Community Catalog"

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

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