File:  [LON-CAPA] / loncom / interface / createaccount.pm
Revision 1.47: download - view: text, annotated - select for diffs
Thu Sep 29 13:34:32 2011 UTC (12 years, 7 months ago) by raeburn
Branches: MAIN
CVS tags: language_hyphenation_merge, language_hyphenation, HEAD, BZ4492-merge, BZ4492-feature_horizontal_radioresponse
- Bug 6514.
  Self-creation for institutional/SSO auth in domains with no defined
  usertypes needs default.

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

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