File:  [LON-CAPA] / loncom / interface / createaccount.pm
Revision 1.40.2.5: download - view: text, annotated - select for diffs
Thu Sep 29 14:16:14 2011 UTC (12 years, 7 months ago) by raeburn
Branches: version_2_10_X
CVS tags: version_2_10_1, loncapaMITrelate_1
- Backport 1.46.

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

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