File:  [LON-CAPA] / loncom / interface / createaccount.pm
Revision 1.52: download - view: text, annotated - select for diffs
Sat Aug 25 04:34:44 2012 UTC (11 years, 9 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Validation of human (CAPTCHA).
  - self creation of account (e-mail address as username).
  - choice of CAPTCHA:  original (Authen::CAPTCHA) or newer reCAPTCHA (requires)
    DC to create account with http://www.google.com/recaptcha/, or not used.
  - Routines to generate CAPTCHA input and validate response moved to loncommon.pm
    to facilitate re-use.
  - Domain configuration for self-creation of accounts allows DC to choose which
    CAPTCHA option to use.
- CPAN module: Captcha::reCAPTCHA now needed. rpm being added to msu/testing repos,
  and dependency included in LONCAPA-prerequisites 1-21.

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

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