File:  [LON-CAPA] / loncom / interface / createaccount.pm
Revision 1.56: download - view: text, annotated - select for diffs
Wed Jun 5 12:46:39 2013 UTC (10 years, 11 months ago) by raeburn
Branches: MAIN
CVS tags: version_2_11_0_RC2, version_2_11_0_RC1, HEAD
- On multi-domain servers preserve information about domain in which user
  without an account is requesting creation of one, for domain where
  self-creation of accounts is permitted.

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

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