File:  [LON-CAPA] / loncom / interface / createaccount.pm
Revision 1.34: download - view: text, annotated - select for diffs
Sat Apr 4 21:47:40 2009 UTC (15 years, 2 months ago) by bisitz
Branches: MAIN
CVS tags: HEAD
XHTML conform tags (input, br, hr)

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

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