File:  [LON-CAPA] / loncom / interface / createaccount.pm
Revision 1.49: download - view: text, annotated - select for diffs
Thu May 17 17:41:48 2012 UTC (12 years ago) by www
Branches: MAIN
CVS tags: HEAD
Documentation

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

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