File:  [LON-CAPA] / loncom / interface / createaccount.pm
Revision 1.40: download - view: text, annotated - select for diffs
Mon Aug 16 14:23:50 2010 UTC (13 years, 9 months ago) by raeburn
Branches: MAIN
CVS tags: version_2_10_X, HEAD
- pass %got_rules to &call_rulecheck() by reference.

    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 2010/08/16 14:23:50 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',
  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" 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);
  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',
  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" '.
  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:             } else {
  799:                 @statustocreate = ('default');
  800:                 my ($othertitle,$usertypes,$types) =
  801:                     &Apache::loncommon::sorted_inst_types($domain);
  802:                 if (ref($types) eq 'ARRAY') {
  803:                     push(@statustocreate,@{$types});
  804:                 }
  805:             }
  806:             if (ref($usercreation->{'cancreate'}{'selfcreate'}) eq 'ARRAY') {
  807:                 @cancreate = @{$usercreation->{'cancreate'}{'selfcreate'}};
  808:             } elsif (($usercreation->{'cancreate'}{'selfcreate'} ne 'none') &&
  809:                      ($usercreation->{'cancreate'}{'selfcreate'} ne '')) {
  810:                 @cancreate = ($usercreation->{'cancreate'}{'selfcreate'});
  811:             }
  812:         }
  813:     }
  814:     return (\@cancreate,\@statustocreate);
  815: }
  816: 
  817: sub create_account {
  818:     my ($r,$domain,$lonhost,$username,$domdesc) = @_;
  819:     my ($retrieved,$output,$upass) = &process_credentials($env{'form.logtoken'},
  820:                                                           $env{'form.serverid'}); 
  821:     # Error messages
  822:     my $error     = '<span class="LC_error">'.&mt('Error:').' ';
  823:     my $end       = '</span><br /><br />';
  824:     my $rtnlink   = '<a href="javascript:history.back();" />'.
  825:                     &mt('Return to previous page').'</a>'.
  826:                     &Apache::loncommon::end_page();
  827:     if ($retrieved eq 'ok') {
  828:         if ($env{'form.courseid'} ne '') {
  829:             my ($result,$userchkmsg) = &check_id($username,$domain,$domdesc);
  830:             if ($result eq 'fail') {
  831:                 $output = $error.&mt('Invalid ID format').$end.
  832:                           $userchkmsg.$rtnlink;
  833:                 return ('fail',$output);
  834:             }
  835:         }
  836:     } else {
  837:         return ('fail',$error.$output.$end.$rtnlink);
  838:     }
  839:     # Call modifyuser
  840:     my $result = 
  841:         &Apache::lonnet::modifyuser($domain,$username,$env{'form.cid'},
  842:                                     'internal',$upass,$env{'form.cfirstname'},
  843:                                     $env{'form.cmiddlename'},$env{'form.clastname'},
  844:                                     $env{'form.cgeneration'},undef,undef,$username);
  845:     $output = &mt('Generating user: [_1]',$result);
  846:     my $uhome = &Apache::lonnet::homeserver($username,$domain);
  847:     $output .= '<br />'.&mt('Home server: [_1]',$uhome).' '.
  848:               &Apache::lonnet::hostname($uhome).'<br /><br />';
  849:     return ('ok',$output);
  850: }
  851: 
  852: sub username_validation {
  853:     my ($r,$username,$domain,$domdesc,$contact_name,$contact_email,$courseid,
  854:         $lonhost,$statustocreate) = @_;
  855:     my ($retrieved,$output,$upass);
  856: 
  857:     $username= &LONCAPA::clean_username($username);
  858:     $domain = &LONCAPA::clean_domain($domain);
  859:     my $uhome = &Apache::lonnet::homeserver($username,$domain);
  860: 
  861:     ($retrieved,$output,$upass) = &process_credentials($env{'form.logtoken'},
  862:                                                        $env{'form.serverid'});
  863:     if ($retrieved ne 'ok') {
  864:         return ('fail',$output);
  865:     }
  866:     if ($uhome ne 'no_host') {
  867:         my $result = &Apache::lonnet::authenticate($username,$upass,$domain);
  868:         if ($result ne 'no_host') { 
  869:             my %form = &start_session($r,$username,$domain,$lonhost,$courseid);
  870:             $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.');
  871:             return ('existingaccount',$output);
  872:         } else {
  873:             $output = &login_failure_msg($courseid);
  874:         }
  875:     } else {
  876:         my $primlibserv = &Apache::lonnet::domain($domain,'primary');
  877:         my $authok;
  878:         my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
  879:         if ((($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) || ($domdefaults{'auth_def'} eq 'localauth')) {
  880:             my $checkdefauth = 1;
  881:             $authok = 
  882:                 &Apache::lonnet::reply("encrypt:auth:$domain:$username:$upass:$checkdefauth",$primlibserv);
  883:         } else {
  884:             $authok = 'non_authorized';
  885:         }
  886:         if ($authok eq 'authorized') {
  887:             $output = &username_check($username,$domain,$domdesc,$courseid,$lonhost,
  888:                                       $contact_email,$contact_name,undef,
  889:                                       $statustocreate);
  890:         } else {
  891:             $output = &login_failure_msg($courseid);
  892:         }
  893:     }
  894:     return ('ok',$output);
  895: }
  896: 
  897: sub login_failure_msg {
  898:     my ($courseid) = @_;
  899:     my $url;
  900:     if ($courseid ne '') {
  901:         $url = "/adm/selfenroll?courseid=".$courseid;
  902:     } else {
  903:         $url = "/adm/createaccount";
  904:     }
  905:     my $output = '<h4>'.&mt('Authentication failed').'</h4><div class="LC_warning">'.
  906:                  &mt('Username and/or password could not be authenticated.').
  907:                  '</div>'.
  908:                  &mt('Please check the username and password.').'<br /><br />';
  909:                  '<a href="'.$url.'">'.&mt('Try again').'</a>';
  910:     return $output;
  911: }
  912: 
  913: sub username_check {
  914:     my ($username,$domain,$domdesc,$courseid,$lonhost,$contact_email,
  915:         $contact_name,$sso_logout,$statustocreate) = @_;
  916:     my (%rulematch,%inst_results,$checkfail,$rowcount,$editable,$output,$msg,
  917:         %alerts,%curr_rules,%got_rules);
  918:     &call_rulecheck($username,$domain,\%alerts,\%rulematch,
  919:                     \%inst_results,\%curr_rules,\%got_rules,'username');
  920:     if (ref($alerts{'username'}) eq 'HASH') {
  921:         if (ref($alerts{'username'}{$domain}) eq 'HASH') {
  922:             if ($alerts{'username'}{$domain}{$username}) {
  923:                 if (ref($curr_rules{$domain}) eq 'HASH') {
  924:                     $output =
  925:                         &Apache::loncommon::instrule_disallow_msg('username',$domdesc,1,
  926:                                                                   'selfcreate').
  927:                         &Apache::loncommon::user_rule_formats($domain,$domdesc,
  928:                                 $curr_rules{$domain}{'username'},'username');
  929:                 }
  930:                 $checkfail = 'username';
  931:             }
  932:         }
  933:     }
  934:     if (!$checkfail) {
  935:         if (ref($statustocreate) eq 'ARRAY') {
  936:             $checkfail = 'inststatus';
  937:             if (ref($inst_results{$username.':'.$domain}{inststatus}) eq 'ARRAY') {
  938:                 foreach my $inststatus (@{$inst_results{$username.':'.$domain}{inststatus}}) {
  939:                     if (grep(/^\Q$inststatus\E$/,@{$statustocreate})) {
  940:                         undef($checkfail);
  941:                         last;
  942:                     }
  943:                 }
  944:             } elsif (grep(/^default$/,@{$statustocreate})) {
  945:                 undef($checkfail);
  946:             }
  947:         }
  948:     }
  949:     if (!$checkfail) {
  950:         $output = '<form method="post" action="/adm/createaccount">';
  951:         (my $datatable,$rowcount,$editable) = 
  952:             &Apache::loncreateuser::personal_data_display($username,$domain,1,'selfcreate',
  953:                                                          $inst_results{$username.':'.$domain});
  954:         if ($rowcount > 0) {
  955:             $output .= $datatable;
  956:         }
  957:         $output .=  '<br /><br /><input type="hidden" name="uname" value="'.$username.'" />'."\n".
  958:                     '<input type="hidden" name="udom" value="'.$domain.'" />'."\n".
  959:                     '<input type="hidden" name="phase" value="username_activation" />';
  960:         my $now = time;
  961:         my %info = ('ip'         => $ENV{'REMOTE_ADDR'},
  962:                     'time'       => $now,
  963:                     'domain'     => $domain,
  964:                     'username'   => $username);
  965:         my $authtoken = &Apache::lonnet::tmpput(\%info,$lonhost);
  966:         if ($authtoken !~ /^error/ && $authtoken ne 'no_such_host') {
  967:             $output .= '<input type="hidden" name="authtoken" value="'.&HTML::Entities::encode($authtoken,'&<>"').'" />';
  968:         } else {
  969:             $output = &mt('An error occurred when storing a token').'<br />'.
  970:                       &mt('You will not be able to proceed to the next stage of account creation').
  971:                       &linkto_email_help($contact_email,$domdesc);
  972:             $checkfail = 'authtoken';
  973:         }
  974:     }
  975:     if ($checkfail) { 
  976:         $msg = '<h4>'.&mt('Account creation unavailable').'</h4>';
  977:         if ($checkfail eq 'username') {
  978:             $msg .= '<span class="LC_warning">'.
  979:                      &mt('A LON-CAPA account may not be created with the username you use.').
  980:                      '</span><br /><br />'.$output;
  981:         } elsif ($checkfail eq 'authtoken') {
  982:             $msg .= '<span class="LC_error">'.&mt('Error creating token.').'</span>'.
  983:                     '<br />'.$output;
  984:         } elsif ($checkfail eq 'inststatus') {
  985:             $msg .= '<span class="LC_warning">'.
  986:                      &mt('You are not permitted to create a LON-CAPA account.').
  987:                      '</span><br /><br />'.$output;
  988:         }
  989:         $msg .= &mt('Please contact the [_1] ([_2]) for assistance.',
  990:                 $contact_name,$contact_email).'<br /><hr />'.
  991:                 $sso_logout;
  992:         &Apache::lonnet::logthis("ERROR: failure type of '$checkfail' when performing username check to create account for authenticated user: $username, in domain $domain");
  993:     } else {
  994:         if ($courseid ne '') {
  995:             $output .= '<input type="hidden" name="courseid" value="'.$courseid.'" />';
  996:         }
  997:         $output .= '<input type="submit" name="newaccount" value="'.
  998:                    &mt('Create LON-CAPA account').'" /></form>';
  999:         if ($rowcount) {
 1000:             if ($editable) {
 1001:                 if ($courseid ne '') { 
 1002:                     $msg = '<h4>'.&mt('User information').'</h4>';
 1003:                 }
 1004:                 $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 />';
 1005:             } else {
 1006:                  if ($courseid ne '') {
 1007:                      $msg = '<h4>'.&mt('Review user information').'</h4>';
 1008:                  }
 1009:                  $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 />';
 1010:             }
 1011:         } else {
 1012:             if ($courseid ne '') {
 1013:                 $msg = '<h4>'.&mt('Confirmation').'</h4>';
 1014:             }
 1015:             $msg .= &mt('Confirm that you wish to create an account.');
 1016:         }
 1017:         $msg .= $output;
 1018:     }
 1019:     return $msg;
 1020: }
 1021: 
 1022: sub username_activation {
 1023:     my ($r,$username,$domain,$domdesc,$lonhost,$courseid) = @_;
 1024:     my $output;
 1025:     my $error     = '<span class="LC_error">'.&mt('Error:').' ';
 1026:     my $end       = '</span><br /><br />';
 1027:     my $rtnlink   = '<a href="javascript:history.back();" />'.
 1028:                     &mt('Return to previous page').'</a>'.
 1029:                     &Apache::loncommon::end_page();
 1030:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 1031:     my %data = &Apache::lonnet::tmpget($env{'form.authtoken'});
 1032:     my $now = time;
 1033:     my $earlyout;
 1034:     my $timeout = 300;
 1035:     if (keys(%data) == 0) {
 1036:         $output = &mt('Sorry, your authentication has expired.');
 1037:         $earlyout = 'fail';
 1038:     }
 1039:     if (($data{'time'} !~ /^\d+$/) ||
 1040:         ($data{'domain'} ne $domain) || 
 1041:         ($data{'username'} ne $username)) {
 1042:         $earlyout = 'fail';
 1043:         $output = &mt('The credentials you provided could not be verified.');   
 1044:     } elsif ($now - $data{'time'} > $timeout) {
 1045:         $earlyout = 'fail';
 1046:         $output = &mt('Sorry, your authentication has expired.');
 1047:     }
 1048:     if ($earlyout ne '') {
 1049:         $output .= '<br />'.&mt('Please [_1]start again[_2].','<a href="/adm/createaccount">','</a>');
 1050:         return($earlyout,$output);
 1051:     }
 1052:     if ((($domdefaults{'auth_def'} =~/^krb(4|5)$/) && 
 1053:          ($domdefaults{'auth_arg_def'} ne '')) || 
 1054:         ($domdefaults{'auth_def'} eq 'localauth')) {
 1055:         if ($env{'form.courseid'} ne '') {
 1056:             my ($result,$userchkmsg) = &check_id($username,$domain,$domdesc);
 1057:             if ($result eq 'fail') {
 1058:                 $output = $error.&mt('Invalid ID format').$end.
 1059:                           $userchkmsg.$rtnlink;
 1060:                 return ('fail',$output);
 1061:             }
 1062:         }
 1063:         # Call modifyuser
 1064:         my (%rulematch,%inst_results,%curr_rules,%got_rules,%alerts,%info);
 1065:         &call_rulecheck($username,$domain,\%alerts,\%rulematch,
 1066:                         \%inst_results,\%curr_rules,\%got_rules);
 1067:         my @userinfo = ('firstname','middlename','lastname','generation',
 1068:                         'permanentemail','id');
 1069:         my %canmodify = 
 1070:             &Apache::loncreateuser::selfcreate_canmodify('selfcreate',$domain,
 1071:                                                          \@userinfo,\%inst_results);
 1072:         foreach my $item (@userinfo) {
 1073:             if ($canmodify{$item}) {
 1074:                 $info{$item} = $env{'form.c'.$item};
 1075:             } else {
 1076:                 $info{$item} = $inst_results{$username.':'.$domain}{$item}; 
 1077:             }
 1078:         }
 1079:         if (ref($inst_results{$username.':'.$domain}{'inststatus'}) eq 'ARRAY') {
 1080:             my @inststatuses = @{$inst_results{$username.':'.$domain}{'inststatus'}};
 1081:             $info{'inststatus'} = join(':',map { &escape($_); } @inststatuses);
 1082:         }
 1083:         my $result =
 1084:             &Apache::lonnet::modifyuser($domain,$username,$env{'form.cid'},
 1085:                           $domdefaults{'auth_def'},
 1086:                           $domdefaults{'auth_arg_def'},$info{'firstname'},
 1087:                           $info{'middlename'},$info{'lastname'},
 1088:                           $info{'generation'},undef,undef,
 1089:                           $info{'permanentemail'},$info{'inststatus'});
 1090:         if ($result eq 'ok') {
 1091:             my $delete = &Apache::lonnet::tmpdel($env{'form.authtoken'});
 1092:             $output = &mt('A LON-CAPA account has been created for username: [_1] in domain: [_2].',$username,$domain);
 1093:             my %form = &start_session($r,$username,$domain,$lonhost,$courseid);
 1094:             my $nostart = 1;
 1095:             return ('ok',$output,$nostart);
 1096:         } else {
 1097:             $output = &mt('Account creation failed for username: [_1] in domain: [_2].',$username,$domain).'<br /><span class="LC_error">'.&mt('Error: [_1]',$result).'</span>';
 1098:             return ('fail',$output);
 1099:         }
 1100:     } else {
 1101:         $output = &mt('User account creation is not available for the current default authentication type.')."\n";
 1102:         return('fail',$output);
 1103:     }
 1104: }
 1105: 
 1106: sub check_id {
 1107:     my ($username,$domain,$domdesc) = @_;
 1108:     # Check ID format
 1109:     my (%alerts,%rulematch,%inst_results,%curr_rules,%checkhash);
 1110:     my %checks = ('id' => 1);
 1111:     %{$checkhash{$username.':'.$domain}} = (
 1112:                                             'newuser' => 1,
 1113:                                             'id' => $env{'form.cid'},
 1114:                                            );
 1115:     &Apache::loncommon::user_rule_check(\%checkhash,\%checks,\%alerts,
 1116:                                         \%rulematch,\%inst_results,\%curr_rules);
 1117:     if (ref($alerts{'id'}) eq 'HASH') {
 1118:         if (ref($alerts{'id'}{$domain}) eq 'HASH') {
 1119:             if ($alerts{'id'}{$domain}{$env{'form.cid'}}) {
 1120:                 my $userchkmsg;
 1121:                 if (ref($curr_rules{$domain}) eq 'HASH') {
 1122:                     $userchkmsg  =
 1123:                         &Apache::loncommon::instrule_disallow_msg('id',
 1124:                                                            $domdesc,1).
 1125:                         &Apache::loncommon::user_rule_formats($domain,
 1126:                               $domdesc,$curr_rules{$domain}{'id'},'id');
 1127:                 }
 1128:                 return ('fail',$userchkmsg);
 1129:             }
 1130:         }
 1131:     }
 1132:     return; 
 1133: }
 1134: 
 1135: sub invalid_state {
 1136:     my ($error,$domdesc,$contact_name,$contact_email,$msgtext) = @_;
 1137:     my $msg = '<h3>'.&mt('Account creation unavailable').'</h3><span class="LC_error">';
 1138:     if ($error eq 'baduseremail') {
 1139:         $msg = &mt('The e-mail address you provided does not appear to be a valid address.');
 1140:     } elsif ($error eq 'existinguser') {
 1141:         $msg = &mt('The e-mail address you provided is already in use as a username in LON-CAPA at this institution.');
 1142:     } elsif ($error eq 'userrules') {
 1143:         $msg = &mt('Username rules at this institution do not allow the e-mail address you provided to be used as a username.');
 1144:     } elsif ($error eq 'userformat') {
 1145:         $msg = &mt('The e-mail address you provided may not be used as a username at this LON-CAPA institution.');
 1146:     } elsif ($error eq 'captcha') {
 1147:         $msg = &mt('Validation of the code your entered failed.');
 1148:     } elsif ($error eq 'noemails') {
 1149:         $msg = &mt('Creation of a new user account using an e-mail address as username is not permitted at this LON-CAPA institution.');
 1150:     }
 1151:     $msg .= '</span>';
 1152:     if ($msgtext) {
 1153:         $msg .= '<br />'.$msgtext;
 1154:     }
 1155:     $msg .= &linkto_email_help($contact_email,$domdesc);
 1156:     return $msg;
 1157: }
 1158: 
 1159: sub linkto_email_help {
 1160:     my ($contact_email,$domdesc) = @_;
 1161:     my $msg;
 1162:     if ($contact_email ne '') {
 1163:         my $escuri = &HTML::Entities::encode('/adm/createaccount','&<>"');
 1164:         $msg .= '<br />'.&mt('You may wish to contact the [_1]LON-CAPA helpdesk[_2] for [_3].','<a href="/adm/helpdesk?origurl='.$escuri.'">','</a>',$domdesc).'<br />';
 1165:     } else {
 1166:         $msg .= '<br />'.&mt('You may wish to send an e-mail to the server administrator: [_1] for [_2].',$Apache::lonnet::perlvar{'AdminEmail'},$domdesc).'<br />';
 1167:     }
 1168:     return $msg;
 1169: }
 1170: 
 1171: sub create_captcha {
 1172:     my ($output_dir,$db_dir) = @_;
 1173:     my %captcha_params = &captcha_settings();
 1174:     my ($output,$maxtries,$tries) = ('',10,0);
 1175:     while ($tries < $maxtries) {
 1176:         $tries ++;
 1177:         my $captcha = Authen::Captcha->new (
 1178:                                            output_folder => $captcha_params{'output_dir'},
 1179:                                            data_folder   => $captcha_params{'db_dir'},
 1180:                                           );
 1181:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
 1182: 
 1183:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
 1184:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
 1185:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
 1186:                      '<input type="text" size="5" name="code" value="" /><br />'.
 1187:                      '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" />';
 1188:             last;
 1189:         }
 1190:     }
 1191:     return $output;
 1192: }
 1193: 
 1194: sub captcha_settings {
 1195:     my %captcha_params = ( 
 1196:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
 1197:                            www_output_dir => "/captchaspool",
 1198:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
 1199:                            numchars       => '5',
 1200:                          );
 1201:     return %captcha_params;
 1202: }
 1203: 
 1204: sub getkeys {
 1205:     my ($lkey,$ukey) = @_;
 1206:     my $lextkey=hex($lkey);
 1207:     if ($lextkey>2147483647) { $lextkey-=4294967296; }
 1208: 
 1209:     my $uextkey=hex($ukey);
 1210:     if ($uextkey>2147483647) { $uextkey-=4294967296; }
 1211:     return ($lextkey,$uextkey);
 1212: }
 1213: 
 1214: sub serverform {
 1215:     my ($logtoken,$lonhost,$mailtoken,$courseid,$context) = @_;
 1216:     my $phase = 'username_validation';
 1217:     my $catalog_elements;
 1218:     if ($context eq 'selfenroll') {
 1219:         $phase = 'selfenroll_login';
 1220:     }
 1221:     if ($courseid ne '') {
 1222:         $catalog_elements = &Apache::lonhtmlcommon::echo_form_input(['courseid','phase']);
 1223:     } 
 1224:     my $output = <<ENDSERVERFORM;
 1225:   <form name="server" method="post" action="/adm/createaccount">
 1226:    <input type="hidden" name="logtoken" value="$logtoken" />
 1227:    <input type="hidden" name="token" value="$mailtoken" />
 1228:    <input type="hidden" name="serverid" value="$lonhost" />
 1229:    <input type="hidden" name="uname" value="" />
 1230:    <input type="hidden" name="upass" value="" />
 1231:    <input type="hidden" name="udom" value="" />
 1232:    <input type="hidden" name="phase" value="$phase" />
 1233:    <input type="hidden" name="courseid" value="$courseid" />
 1234:    $catalog_elements
 1235:   </form>
 1236: ENDSERVERFORM
 1237:     return $output;
 1238: }
 1239: 
 1240: sub process_credentials {
 1241:     my ($logtoken,$lonhost) = @_;
 1242:     my $tmpinfo=Apache::lonnet::reply('tmpget:'.$logtoken,$lonhost);
 1243:     my ($retrieved,$output,$upass);
 1244:     if (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost')) {
 1245:         $output = &mt('Information needed to verify your login information is missing, inaccessible or expired.')
 1246:                  .'<br />'.&mt('You may need to reload the previous page to obtain a new token.');
 1247:         return ($retrieved,$output,$upass); 
 1248:     } else {
 1249:         my $reply = &Apache::lonnet::reply('tmpdel:'.$logtoken,$lonhost);
 1250:         if ($reply eq 'ok') {
 1251:             $retrieved = 'ok';
 1252:         } else {
 1253:             $output = &mt('Session could not be opened.');
 1254:         }
 1255:     }
 1256:     my ($key,$caller)=split(/&/,$tmpinfo);
 1257:     if ($caller eq 'createaccount') {
 1258:         $upass = &Apache::lonpreferences::des_decrypt($key,$env{'form.upass'});
 1259:     } else {
 1260:         $output = &mt('Unable to retrieve your log-in information - unexpected context');
 1261:     }
 1262:     return ($retrieved,$output,$upass);
 1263: }
 1264: 
 1265: sub guest_format_check {
 1266:     my ($useremail,$domain,$cancreate,$settings) = @_;
 1267:     my ($login,$format_match,$format_msg,@user_rules);
 1268:     if (ref($settings) eq 'HASH') {
 1269:         if (ref($settings->{'email_rule'}) eq 'ARRAY') {
 1270:             push(@user_rules,@{$settings->{'email_rule'}});
 1271:         }
 1272:     }
 1273:     if (@user_rules > 0) {
 1274:         my %rule_check = 
 1275:             &Apache::lonnet::inst_rulecheck($domain,$useremail,undef,
 1276:                                             'selfcreate',\@user_rules);
 1277:         if (keys(%rule_check) > 0) {
 1278:             foreach my $item (keys(%rule_check)) {
 1279:                 if ($rule_check{$item}) {
 1280:                     $format_match = 1;   
 1281:                     last;
 1282:                 }
 1283:             }
 1284:         }
 1285:     }
 1286:     if ($format_match) {
 1287:         ($login) = ($useremail =~ /^([^\@]+)\@/);
 1288:         $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 />';
 1289:         if (ref($cancreate) eq 'ARRAY') {
 1290:             if (grep(/^login$/,@{$cancreate})) {
 1291:                 $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 />'; 
 1292:             }
 1293:         }
 1294:     }
 1295:     return $format_msg;
 1296: }
 1297: 
 1298: sub sso_logout_frag {
 1299:     my ($r,$domain) = @_;
 1300:     my $endsessionmsg;
 1301:     if (defined($r->dir_config('lonSSOUserLogoutMessageFile_'.$domain))) {
 1302:         my $msgfile = $r->dir_config('lonSSOUserLogoutMessageFile_'.$domain);
 1303:         if (-e $msgfile) {
 1304:             open(my $fh,"<$msgfile");
 1305:             $endsessionmsg = join('',<$fh>);
 1306:             close($fh);
 1307:         }
 1308:     } elsif (defined($r->dir_config('lonSSOUserLogoutMessageFile'))) {
 1309:         my $msgfile = $r->dir_config('lonSSOUserLogoutMessageFile');
 1310:         if (-e $msgfile) {     
 1311:             open(my $fh,"<$msgfile");
 1312:             $endsessionmsg = join('',<$fh>);
 1313:             close($fh);
 1314:         }
 1315:     }
 1316:     return $endsessionmsg;
 1317: }
 1318: 
 1319: sub catreturn_js {
 1320:     return  <<"ENDSCRIPT";
 1321: <script type="text/javascript">
 1322: 
 1323: function ToSelfenroll(formname) {
 1324:     var formidx = getFormByName(formname);
 1325:     if (formidx > -1) {
 1326:         document.forms[formidx].action = '/adm/selfenroll';
 1327:         numidx = getIndexByName(formidx,'phase');
 1328:         if (numidx > -1) {
 1329:             document.forms[formidx].elements[numidx].value = '';   
 1330:         }
 1331:         numidx = getIndexByName(formidx,'context');
 1332:         if (numidx > -1) {
 1333:             document.forms[formidx].elements[numidx].value = '';
 1334:         }
 1335:     }
 1336:     document.forms[formidx].submit();
 1337: }
 1338: 
 1339: function ToCatalog(formname,caller) {
 1340:     var formidx = getFormByName(formname);
 1341:     if (formidx > -1) {
 1342:         document.forms[formidx].action = '/adm/coursecatalog';
 1343:         numidx = getIndexByName(formidx,'coursenum');
 1344:         if (numidx > -1) {
 1345:             if (caller != 'details') {
 1346:                 document.forms[formidx].elements[numidx].value = '';
 1347:             }
 1348:         }
 1349:     }
 1350:     document.forms[formidx].submit();
 1351: }
 1352: 
 1353: function getIndexByName(formidx,item) {
 1354:     for (var i=0;i<document.forms[formidx].elements.length;i++) {
 1355:         if (document.forms[formidx].elements[i].name == item) {
 1356:             return i;
 1357:         }
 1358:     }
 1359:     return -1;
 1360: }
 1361: 
 1362: function getFormByName(item) {
 1363:     for (var i=0; i<document.forms.length; i++) {
 1364:         if (document.forms[i].name == item) {
 1365:             return i;
 1366:         }
 1367:     }
 1368:     return -1;
 1369: }
 1370: 
 1371: </script>
 1372: ENDSCRIPT
 1373: 
 1374: }
 1375: 
 1376: 1;

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