File:  [LON-CAPA] / loncom / interface / createaccount.pm
Revision 1.51: download - view: text, annotated - select for diffs
Fri May 18 04:31:05 2012 UTC (12 years ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Changes to: &create_account() third arg: $lonhost eliminated (not used).
  - now returns third item - $uhome (lonHostID of new user's home server).
- Changes to calls to &start_session() - fourth arg is now $uhome
  (lonHostID of new user's home server) instead of lonHostID of server
  hosting session.
- Changes to calls to &Apache::lonauth::success() pass $uhome as fourth arg
  instead of $lonhost.

    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.51 2012/05/18 04:31:05 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 = &create_captcha();
  386:             if ($captchaform) {
  387:                 my $submit_text = &mt('Request LON-CAPA account');
  388:                 my $emailform = '<input type="text" name="useremail" size="25" value="" />';
  389:                 if (grep(/^login$/,@{$cancreate})) {
  390:                     $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 />';
  391:                 } else {
  392:                     $output .= '<br />';
  393:                 }
  394:                 $output .=  '<form name="createaccount" method="post" onsubmit="return validate_email()" action="/adm/createaccount">'.
  395:                             &Apache::lonhtmlcommon::start_pick_box()."\n".
  396:                             &Apache::lonhtmlcommon::row_title(&mt('E-mail address'),
  397:                                                              'LC_pick_box_title')."\n".
  398:                             $emailform."\n".
  399:                             &Apache::lonhtmlcommon::row_closure(1).
  400:                             &Apache::lonhtmlcommon::row_title(&mt('Validation'),
  401:                                                              'LC_pick_box_title')."\n".
  402:                             $captchaform."\n".'<br /><br />';
  403:                 if ($courseid ne '') {
  404:                     $output .= '<input type="hidden" name="courseid" value="'.$courseid.'"/>'."\n"; 
  405:                 }
  406:                 $output .=  &Apache::lonhtmlcommon::row_closure(1).
  407:                             &Apache::lonhtmlcommon::row_title().'<br />'.
  408:                             '<input type="submit" name="create_with_email" value="'. 
  409:                             $submit_text.'" />'.
  410:                             &Apache::lonhtmlcommon::row_closure(1).
  411:                             &Apache::lonhtmlcommon::end_pick_box().'<br /><br />';
  412:                 if ($courseid ne '') {
  413:                     $output .= &Apache::lonhtmlcommon::echo_form_input(['courseid']);
  414:                 }
  415:                 $output .= '</form>';
  416:             } else {
  417:                 my $helpdesk = '/adm/helpdesk?origurl=%2fadm%2fcreateaccount';
  418:                 if ($courseid ne '') {
  419:                     $helpdesk .= '&courseid='.$courseid;
  420:                 }
  421:                 $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()">');
  422:             }
  423:             $output .= '</div>';
  424:         }
  425:     }
  426:     if ($output eq '') {
  427:         $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);
  428:     } else {
  429:         $output .= '<div class="LC_clear_float_footer"></div>';
  430:     }
  431:     return $output;
  432: }
  433: 
  434: sub login_box {
  435:     my ($now,$lonhost,$courseid,$submit_text,$domain,$context) = @_;
  436:     my $output;
  437:     my %titles = &Apache::lonlocal::texthash(
  438:                                               createaccount => 'Log-in ID',
  439:                                               selfenroll    => 'Username',
  440:                                             );
  441:     my ($lkey,$ukey) = &Apache::lonpreferences::des_keys();
  442:     my ($lextkey,$uextkey) = &getkeys($lkey,$ukey);
  443:     my $logtoken=Apache::lonnet::reply('tmpput:'.$ukey.$lkey.'&createaccount:createaccount',
  444:                                        $lonhost);
  445:     $output = &serverform($logtoken,$lonhost,undef,$courseid,$context);
  446:     my $unameform = '<input type="text" name="uname" size="20" value="" />';
  447:     my $upassform = '<input type="password" name="upass'.$now.'" size="20" />';
  448:     $output .= '<form name="client" method="post" action="" onsubmit="return(send());">'."\n".
  449:                &Apache::lonhtmlcommon::start_pick_box()."\n".
  450:                &Apache::lonhtmlcommon::row_title($titles{$context},
  451:                                                  'LC_pick_box_title')."\n".
  452:                $unameform."\n".
  453:                &Apache::lonhtmlcommon::row_closure(1)."\n".
  454:                &Apache::lonhtmlcommon::row_title(&mt('Password'),
  455:                                                 'LC_pick_box_title')."\n".
  456:                $upassform;
  457:     if ($context eq 'selfenroll') {
  458:         my $udomform = '<input type="text" name="udom" size="10" value="'.
  459:                         $domain.'" />';
  460:         $output .= &Apache::lonhtmlcommon::row_closure(1)."\n".
  461:                    &Apache::lonhtmlcommon::row_title(&mt('Domain'),
  462:                                                      'LC_pick_box_title')."\n".
  463:                    $udomform."\n";
  464:     } else {
  465:         $output .= '<input type="hidden" name="udom" value="'.$domain.'" />';
  466:     }
  467:     $output .= &Apache::lonhtmlcommon::row_closure(1).
  468:                &Apache::lonhtmlcommon::row_title().
  469:                '<br /><input type="submit" name="username_validation" value="'.
  470:                $submit_text.'" />'."\n";
  471:     if ($context eq 'selfenroll') {
  472:         $output .= '<br /><br /><table width="100%"><tr><td align="right">'.
  473:                    '<span class="LC_fontsize_medium">'.
  474:                    '<a href="/adm/resetpw">'.&mt('Forgot password?').'</a>'.
  475:                    '</span></td></tr></table>'."\n";
  476:     }
  477:     $output .= &Apache::lonhtmlcommon::row_closure(1)."\n".
  478:                &Apache::lonhtmlcommon::end_pick_box().'<br />'."\n";
  479:     $output .= '<input type="hidden" name="lextkey" value="'.$lextkey.'" />'."\n".
  480:                '<input type="hidden" name="uextkey" value="'.$uextkey.'" />'."\n".
  481:                '</form>';
  482:     return $output;
  483: }
  484: 
  485: sub process_email_request {
  486:     my ($useremail,$domain,$domdesc,$contact_name,$contact_email,$cancreate,
  487:         $server,$settings,$courseid) = @_;
  488:     $useremail = $env{'form.useremail'};
  489:     my $output;
  490:     if (ref($cancreate) eq 'ARRAY') {
  491:         if (!grep(/^email$/,@{$cancreate})) {
  492:             $output = &invalid_state('noemails',$domdesc,
  493:                                      $contact_name,$contact_email);
  494:             return $output;
  495:         } elsif ($useremail !~ /^[^\@]+\@[^\@]+\.[^\@\.]+$/) {
  496:             $output = &invalid_state('baduseremail',$domdesc,
  497:                                      $contact_name,$contact_email);
  498:             return $output;
  499:         } else {
  500:             my $uhome = &Apache::lonnet::homeserver($useremail,$domain);
  501:             if ($uhome ne 'no_host') {
  502:                 $output = &invalid_state('existinguser',$domdesc,
  503:                                          $contact_name,$contact_email);
  504:                 return $output;
  505:             } else {
  506:                 my $code = $env{'form.code'};
  507:                 my $md5sum = $env{'form.crypt'};
  508:                 my %captcha_params = &captcha_settings();
  509:                 my $captcha = Authen::Captcha->new(
  510:                                   output_folder => $captcha_params{'output_dir'},
  511:                                   data_folder   => $captcha_params{'db_dir'},
  512:                                  );
  513:                 my $captcha_chk = $captcha->check_code($code,$md5sum);
  514:                 my %captcha_hash = (
  515:                                   0       => 'Code not checked (file error)',
  516:                                   -1      => 'Failed: code expired',
  517:                                   -2      => 'Failed: invalid code (not in database)',
  518:                                   -3      => 'Failed: invalid code (code does not match crypt)',
  519:                                    );
  520:                 if ($captcha_chk != 1) {
  521:                     $output = &invalid_state('captcha',$domdesc,$contact_name,
  522:                                              $contact_email,$captcha_hash{$captcha_chk});
  523:                     return $output;
  524:                 }
  525:                 my $uhome=&Apache::lonnet::homeserver($useremail,$domain);
  526:                 if ($uhome eq 'no_host') {
  527:                     my (%rulematch,%inst_results,%curr_rules,%got_rules,%alerts);
  528:                     &call_rulecheck($useremail,$domain,\%alerts,\%rulematch,
  529:                                     \%inst_results,\%curr_rules,\%got_rules,'username');
  530:                     if (ref($alerts{'username'}) eq 'HASH') {
  531:                         if (ref($alerts{'username'}{$domain}) eq 'HASH') {
  532:                             if ($alerts{'username'}{$domain}{$useremail}) {
  533:                                 $output = &invalid_state('userrules',$domdesc,
  534:                                                          $contact_name,$contact_email);
  535:                                 return $output;
  536:                             }
  537:                         }
  538:                     }
  539:                     my $format_msg = 
  540:                         &guest_format_check($useremail,$domain,$cancreate,
  541:                                             $settings);
  542:                     if ($format_msg) {
  543:                         $output = &invalid_state('userformat',$domdesc,$contact_name,
  544:                                                  $contact_email,$format_msg);
  545:                         return $output;
  546:                     }
  547:                 }
  548:             }
  549:         }
  550:         $output = &send_token($domain,$useremail,$server,$domdesc,$contact_name,
  551:                           $contact_email,$courseid);
  552:     }
  553:     return $output;
  554: }
  555: 
  556: sub call_rulecheck {
  557:     my ($uname,$udom,$alerts,$rulematch,$inst_results,$curr_rules,
  558:         $got_rules,$tocheck) = @_;
  559:     my ($checkhash,$checks);
  560:     $checkhash->{$uname.':'.$udom} = { 'newuser' => 1, };
  561:     if ($tocheck eq 'username') {
  562:         $checks = { 'username' => 1 };
  563:     }
  564:     &Apache::loncommon::user_rule_check($checkhash,$checks,
  565:            $alerts,$rulematch,$inst_results,$curr_rules,
  566:            $got_rules);
  567:     return;
  568: }
  569: 
  570: sub send_token {
  571:     my ($domain,$email,$server,$domdesc,$contact_name,$contact_email,$courseid) = @_;
  572:     my $msg = '<h3>'.&mt('Account creation status').'</h3>'.
  573:               &mt('Thank you for your request to create a new LON-CAPA account.').
  574:               '<br /><br />';
  575:     my $now = time;
  576:     my %info = ('ip'         => $ENV{'REMOTE_ADDR'},
  577:                 'time'       => $now,
  578:                 'domain'     => $domain,
  579:                 'username'   => $email,
  580:                 'courseid'   => $courseid);
  581:     my $token = &Apache::lonnet::tmpput(\%info,$server,'createaccount');
  582:     if ($token !~ /^error/ && $token ne 'no_such_host') {
  583:         my $esc_token = &escape($token);
  584:         my $showtime = localtime(time);
  585:         my $mailmsg = &mt('A request was submitted on [_1] for creation of a LON-CAPA account at the following institution: [_2].',$showtime,$domdesc).' '.
  586:              &mt('To complete this process please open a web browser and enter the following URL in the address/location box: [_1]',
  587:                  &Apache::lonnet::absolute_url().'/adm/createaccount?token='.$esc_token);
  588:         my $result = &Apache::resetpw::send_mail($domdesc,$email,$mailmsg,$contact_name,
  589:                                                  $contact_email);
  590:         if ($result eq 'ok') {
  591:             $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>');
  592:         } else {
  593:             $msg .= '<span class="LC_error">'.
  594:                     &mt('An error occurred when sending a message to the e-mail address you provided.').'</span><br />'.
  595:                     ' '.&mt('Please contact the [_1] ([_2]) for assistance.',$contact_name,$contact_email);
  596:         }
  597:     } else {
  598:         $msg .= '<span class="LC_error">'.
  599:                 &mt('An error occurred creating a token required for the account creation process.').'</span><br />'.
  600:                 ' '.&mt('Please contact the [_1] ([_2]) for assistance.',$contact_name,$contact_email);
  601:     }
  602:     return $msg;
  603: }
  604: 
  605: sub process_mailtoken {
  606:     my ($r,$token,$contact_name,$contact_email,$domain,$domdesc,$lonhost,
  607:         $include,$start_page) = @_;
  608:     my ($msg,$nostart,$noend);
  609:     my %data = &Apache::lonnet::tmpget($token);
  610:     my $now = time;
  611:     if (keys(%data) == 0) {
  612:         $msg = &mt('Sorry, the URL you provided to complete creation of a new LON-CAPA account was invalid.')
  613:                .' '.&mt('Either the token included in the URL has been deleted or the URL you provided was invalid.')
  614:                .' '.&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>');
  615:         return $msg;
  616:     }
  617:     if (($data{'time'} =~ /^\d+$/) &&
  618:         ($data{'domain'} ne '') &&
  619:         ($data{'username'}  =~ /^[^\@]+\@[^\@]+\.[^\@\.]+$/)) {
  620:         if ($now - $data{'time'} < 7200) {
  621:             if ($env{'form.phase'} eq 'createaccount') {
  622:                 my ($result,$output,$uhome) = 
  623:                     &create_account($r,$domain,$data{'username'},$domdesc);
  624:                 if ($result eq 'ok') {
  625:                     $msg = $output; 
  626:                     my $shownow = &Apache::lonlocal::locallocaltime($now);
  627:                     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";
  628:                     my $mailresult = &Apache::resetpw::send_mail($domdesc,$data{'email'},
  629:                                                                  $mailmsg,$contact_name,
  630:                                                                  $contact_email);
  631:                     if ($mailresult eq 'ok') {
  632:                         $msg .= &mt('An e-mail confirming creation of your new LON-CAPA account has been sent to [_1].',$data{'username'});
  633:                     } else {
  634:                         $msg .= &mt('An error occurred when sending e-mail to [_1] confirming creation of your LON-CAPA account.',$data{'username'});
  635:                     }
  636:                     &start_session($r,$data{'username'},$domain,$uhome,
  637:                                    $data{'courseid'},$token);
  638:                     $nostart = 1;
  639:                     $noend = 1;
  640:                 } else {
  641:                     $msg .= &mt('A problem occurred when attempting to create your new LON-CAPA account.')
  642:                            .'<br />'.$output
  643: #                           .&mt('Please contact the [_1] ([_2]) for assistance.',$contact_name,'<a href="mailto:'.$contact_email.'">'.$contact_email.'</a>');
  644:                            .&mt('Please contact the [_1] ([_2]) for assistance.',$contact_name,$contact_email);
  645:                 }
  646:                 my $delete = &Apache::lonnet::tmpdel($token);
  647:             } else {
  648:                 $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 />';
  649:                 $msg .= &print_dataentry_form($r,$domain,$lonhost,$include,$token,$now,$data{'username'},$start_page);
  650:                 $nostart = 1;
  651:             }
  652:         } else {
  653:             $msg = &mt('Sorry, the token generated when you requested creation of an account has expired.')
  654:                   .' '.&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>');
  655:             }
  656:     } else {
  657:         $msg .= &mt('Sorry, the URL generated when you requested creation of an account contained incomplete information.')
  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:     return ($msg,$nostart,$noend);
  661: }
  662: 
  663: sub start_session {
  664:     my ($r,$username,$domain,$uhome,$courseid,$token) = @_;
  665: 
  666:     if ($r->dir_config('lonBalancer') eq 'yes') {
  667:         Apache::lonauth::success($r, $username, $domain, $uhome,
  668:             'noredirect', undef, {});
  669: 
  670:         Apache::lonnet::tmpdel($token) if $token;
  671: 
  672:         $r->internal_redirect('/adm/switchserver');
  673:     } else {
  674:         $courseid = Apache::lonnet::is_course($courseid); 
  675: 
  676:         Apache::lonauth::success($r, $username, $domain, $uhome,
  677:             ($courseid ? "/adm/selfenroll?courseid=$courseid" : '/adm/roles'),
  678:             undef, {}); 
  679:     }
  680: 
  681:     return;
  682: }
  683: 
  684: #
  685: # The screen that the user gets to create his or her account
  686: # Desired username, desired password, etc
  687: # Stores token to store DES-key and stage during creation session
  688: #
  689: sub print_dataentry_form {
  690:     my ($r,$domain,$lonhost,$include,$mailtoken,$now,$username,$start_page) = @_;
  691:     my ($error,$output);
  692:     &print_header($r,$start_page);
  693:     if (open(my $jsh,"<$include/londes.js")) {
  694:         while(my $line = <$jsh>) {
  695:             $r->print($line);
  696:         }
  697:         close($jsh);
  698:         $output .= &javascript_setforms($now)."\n".&javascript_checkpass($now);
  699:         my ($lkey,$ukey) = &Apache::lonpreferences::des_keys();
  700:         my ($lextkey,$uextkey) = &getkeys($lkey,$ukey);
  701:         my $logtoken=Apache::lonnet::reply('tmpput:'.$ukey.$lkey.'&createaccount:createaccount',
  702:                                            $lonhost);
  703:         my $formtag = '<form name="server" method="post" target="_top" action="/adm/createaccount">';
  704:         my ($datatable,$rowcount) =
  705:             &Apache::loncreateuser::personal_data_display($username,$domain,
  706:                                                           'email','selfcreate');
  707:         if ($rowcount) {
  708:             $output .= '<div class="LC_left_float">'.$formtag.$datatable;
  709:         } else {
  710:             $output .= $formtag;
  711:         }
  712:         $output .= <<"ENDSERVERFORM";
  713:    <input type="hidden" name="logtoken" value="$logtoken" />
  714:    <input type="hidden" name="token" value="$mailtoken" />
  715:    <input type="hidden" name="serverid" value="$lonhost" />
  716:    <input type="hidden" name="uname" value="" />
  717:    <input type="hidden" name="upass" value="" />
  718:    <input type="hidden" name="udom" value="" />
  719:    <input type="hidden" name="phase" value="createaccount" />
  720:   </form>
  721: ENDSERVERFORM
  722:         if ($rowcount) {
  723:             $output .= '</div>'.
  724:                        '<div class="LC_left_float">';
  725:         }
  726:         my $upassone = '<input type="password" name="upass'.$now.'" size="10" />';
  727:         my $upasstwo = '<input type="password" name="upasscheck'.$now.'" size="10" />';
  728:         my $submit_text = &mt('Create LON-CAPA account');
  729:         $output .= '<h3>'.&mt('Login Data').'</h3>'."\n".
  730:                    '<form name="client" method="post" action="" '.
  731:                    'onsubmit="return checkpass();">'."\n".
  732:                    &Apache::lonhtmlcommon::start_pick_box()."\n".
  733:                    &Apache::lonhtmlcommon::row_title(&mt('Username'),
  734:                                                      'LC_pick_box_title',
  735:                                                      'LC_oddrow_value')."\n".
  736:                    $username."\n".
  737:                    &Apache::lonhtmlcommon::row_closure(1)."\n".
  738:                    &Apache::lonhtmlcommon::row_title(&mt('Password'),
  739:                                                     'LC_pick_box_title',
  740:                                                     'LC_oddrow_value')."\n".
  741:                    $upassone."\n".
  742:                    &Apache::lonhtmlcommon::row_closure(1)."\n".
  743:                    &Apache::lonhtmlcommon::row_title(&mt('Confirm password'),
  744:                                                      'LC_pick_box_title',
  745:                                                      'LC_oddrow_value')."\n".
  746:                    $upasstwo.
  747:                    &Apache::lonhtmlcommon::row_closure(1)."\n".
  748:                    &Apache::lonhtmlcommon::row_title()."\n".
  749:                    '<br /><input type="submit" name="createaccount" value="'.
  750:                    $submit_text.'" />'.
  751:                    &Apache::lonhtmlcommon::row_closure(1)."\n".
  752:                    &Apache::lonhtmlcommon::end_pick_box()."\n".
  753:                    '<input type="hidden" name="uname" value="'.$username.'" />'."\n".
  754:                    '<input type="hidden" name="udom" value="'.$domain.'" />'."\n".
  755:                    '<input type="hidden" name="lextkey" value="'.$lextkey.'" />'."\n".
  756:                    '<input type="hidden" name="uextkey" value="'.$uextkey.'" />'."\n".
  757:                    '</form>';
  758:         if ($rowcount) {
  759:             $output .= '</div>'."\n".
  760:                        '<div class="LC_clear_float_footer"></div>'."\n";
  761:         }
  762:     } else {
  763:         $output = &mt('Could not load javascript file [_1]','<tt>londes.js</tt>');
  764:     }
  765:     return $output;
  766: }
  767: 
  768: #
  769: # Retrieve rules for generating accounts from domain configuration
  770: # Can the user make a new account or just self-enroll?
  771: 
  772: sub get_creation_controls {
  773:     my ($domain,$usercreation) = @_;
  774:     my (@cancreate,@statustocreate);
  775:     if (ref($usercreation) eq 'HASH') {
  776:         if (ref($usercreation->{'cancreate'}) eq 'HASH') {
  777:             if (ref($usercreation->{'cancreate'}{'statustocreate'}) eq 'ARRAY') {
  778:                 @statustocreate = @{$usercreation->{'cancreate'}{'statustocreate'}};
  779:                 if (@statustocreate == 0) {
  780:                     my ($othertitle,$usertypes,$types) =
  781:                         &Apache::loncommon::sorted_inst_types($domain);
  782:                     if (ref($types) eq 'ARRAY') {
  783:                         if (@{$types} == 0) {
  784:                             @statustocreate = ('default');
  785:                         }
  786:                     } else {
  787:                         @statustocreate = ('default');
  788:                     }
  789:                 }
  790:             } else {
  791:                 @statustocreate = ('default');
  792:                 my ($othertitle,$usertypes,$types) =
  793:                     &Apache::loncommon::sorted_inst_types($domain);
  794:                 if (ref($types) eq 'ARRAY') {
  795:                     push(@statustocreate,@{$types});
  796:                 }
  797:             }
  798:             if (ref($usercreation->{'cancreate'}{'selfcreate'}) eq 'ARRAY') {
  799:                 @cancreate = @{$usercreation->{'cancreate'}{'selfcreate'}};
  800:             } elsif (($usercreation->{'cancreate'}{'selfcreate'} ne 'none') &&
  801:                      ($usercreation->{'cancreate'}{'selfcreate'} ne '')) {
  802:                 @cancreate = ($usercreation->{'cancreate'}{'selfcreate'});
  803:             }
  804:         }
  805:     }
  806:     return (\@cancreate,\@statustocreate);
  807: }
  808: 
  809: sub create_account {
  810:     my ($r,$domain,$username,$domdesc) = @_;
  811: # Get the token info
  812:     my ($retrieved,$output,$upass) = &process_credentials($env{'form.logtoken'},
  813:                                                           $env{'form.serverid'}); 
  814: # $retrieved is 'ok' if things worked
  815: # $output is user error output
  816: # $upass is the decrypted password
  817:     # Error messages
  818:     my $error     = '<span class="LC_error">'.&mt('Error:').' ';
  819:     my $end       = '</span><br /><br />';
  820:     my $rtnlink   = '<a href="javascript:history.back();" />'.
  821:                     &mt('Return to previous page').'</a>'.
  822:                     &Apache::loncommon::end_page();
  823:     if ($retrieved eq 'ok') {
  824:         if ($env{'form.courseid'} ne '') {
  825: # See if we are allowed to use this username per domain rules (number of characters, etc)
  826:             my ($result,$userchkmsg) = &check_id($username,$domain,$domdesc);
  827:             if ($result eq 'fail') {
  828:                 $output = $error.&mt('Invalid ID format').$end.
  829:                           $userchkmsg.$rtnlink;
  830:                 return ('fail',$output);
  831:             }
  832:         }
  833:     } else {
  834:         return ('fail',$error.$output.$end.$rtnlink);
  835:     }
  836:     # Yes! We can do this. Valid token, valid username format
  837:     # Create an internally authenticated account with password $upass 
  838:     # if the account does not exist yet
  839:     # Assign student/staff number $env{'form.cid'}, first name, last name, etc
  840:     my $result = 
  841:         &Apache::lonnet::modifyuser($domain,$username,$env{'form.cid'},
  842:                                     'internal',$upass,$env{'form.cfirstname'},
  843:                                     $env{'form.cmiddlename'},$env{'form.clastname'},
  844:                                     $env{'form.cgeneration'},undef,undef,$username);
  845:     $output = &mt('Generating user: [_1]',$result);
  846:     # Now that the user exists, we can have a homeserver
  847:     my $uhome = &Apache::lonnet::homeserver($username,$domain);
  848:     $output .= '<br />'.&mt('Home server: [_1]',$uhome).' '.
  849:               &Apache::lonnet::hostname($uhome).'<br /><br />';
  850:     return ('ok',$output,$uhome);
  851: }
  852: 
  853: sub username_validation {
  854:     my ($r,$username,$domain,$domdesc,$contact_name,$contact_email,$courseid,
  855:         $lonhost,$statustocreate) = @_;
  856: # $username,$domain: for the user who needs to be validated
  857: # $domdesc: full name of the domain (for error messages)
  858: # $contact_name, $contact_email: name and email for user assistance (for error messages in &username_check
  859: # $courseid: ID of the course that the user should be validated for, goes into start_session
  860: # $statustocreate: -> inststatus in username_check ('faculty', 'staff', 'student', ...)
  861:  
  862:     my ($retrieved,$output,$upass);
  863: 
  864:     $username= &LONCAPA::clean_username($username);
  865:     $domain = &LONCAPA::clean_domain($domain);
  866:     my $uhome = &Apache::lonnet::homeserver($username,$domain);
  867: 
  868:     ($retrieved,$output,$upass) = &process_credentials($env{'form.logtoken'},
  869:                                                        $env{'form.serverid'});
  870:     if ($retrieved ne 'ok') {
  871:         return ('fail',$output);
  872:     }
  873:     if ($uhome ne 'no_host') {
  874:         my $result = &Apache::lonnet::authenticate($username,$upass,$domain);
  875:         if ($result ne 'no_host') { 
  876:             &start_session($r,$username,$domain,$uhome,$courseid);
  877:             $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.');
  878:             return ('existingaccount',$output);
  879:         } else {
  880:             $output = &login_failure_msg($courseid);
  881:         }
  882:     } else {
  883:         my $primlibserv = &Apache::lonnet::domain($domain,'primary');
  884:         my $authok;
  885:         my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
  886:         if ((($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) || ($domdefaults{'auth_def'} eq 'localauth')) {
  887:             my $checkdefauth = 1;
  888:             $authok = 
  889:                 &Apache::lonnet::reply("encrypt:auth:$domain:$username:$upass:$checkdefauth",$primlibserv);
  890:         } else {
  891:             $authok = 'non_authorized';
  892:         }
  893:         if ($authok eq 'authorized') {
  894:             $output = &username_check($username,$domain,$domdesc,$courseid,$lonhost,
  895:                                       $contact_email,$contact_name,undef,
  896:                                       $statustocreate);
  897:         } else {
  898:             $output = &login_failure_msg($courseid);
  899:         }
  900:     }
  901:     return ('ok',$output);
  902: }
  903: 
  904: sub login_failure_msg {
  905:     my ($courseid) = @_;
  906:     my $url;
  907:     if ($courseid ne '') {
  908:         $url = "/adm/selfenroll?courseid=".$courseid;
  909:     } else {
  910:         $url = "/adm/createaccount";
  911:     }
  912:     my $output = '<h4>'.&mt('Authentication failed').'</h4><div class="LC_warning">'.
  913:                  &mt('Username and/or password could not be authenticated.').
  914:                  '</div>'.
  915:                  &mt('Please check the username and password.').'<br /><br />';
  916:                  '<a href="'.$url.'">'.&mt('Try again').'</a>';
  917:     return $output;
  918: }
  919: 
  920: sub username_check {
  921:     my ($username,$domain,$domdesc,$courseid,$lonhost,$contact_email,
  922:         $contact_name,$sso_logout,$statustocreate) = @_;
  923:     my (%rulematch,%inst_results,$checkfail,$rowcount,$editable,$output,$msg,
  924:         %alerts,%curr_rules,%got_rules);
  925:     &call_rulecheck($username,$domain,\%alerts,\%rulematch,
  926:                     \%inst_results,\%curr_rules,\%got_rules,'username');
  927:     if (ref($alerts{'username'}) eq 'HASH') {
  928:         if (ref($alerts{'username'}{$domain}) eq 'HASH') {
  929:             if ($alerts{'username'}{$domain}{$username}) {
  930:                 if (ref($curr_rules{$domain}) eq 'HASH') {
  931:                     $output =
  932:                         &Apache::loncommon::instrule_disallow_msg('username',$domdesc,1,
  933:                                                                   'selfcreate').
  934:                         &Apache::loncommon::user_rule_formats($domain,$domdesc,
  935:                                 $curr_rules{$domain}{'username'},'username');
  936:                 }
  937:                 $checkfail = 'username';
  938:             }
  939:         }
  940:     }
  941:     if (!$checkfail) {
  942:         if (ref($statustocreate) eq 'ARRAY') {
  943:             $checkfail = 'inststatus';
  944:             if (ref($inst_results{$username.':'.$domain}{inststatus}) eq 'ARRAY') {
  945:                 foreach my $inststatus (@{$inst_results{$username.':'.$domain}{inststatus}}) {
  946:                     if (grep(/^\Q$inststatus\E$/,@{$statustocreate})) {
  947:                         undef($checkfail);
  948:                         last;
  949:                     }
  950:                 }
  951:             } elsif (grep(/^default$/,@{$statustocreate})) {
  952:                 undef($checkfail);
  953:             }
  954:         }
  955:     }
  956:     if (!$checkfail) {
  957:         $output = '<form method="post" action="/adm/createaccount">';
  958:         (my $datatable,$rowcount,$editable) = 
  959:             &Apache::loncreateuser::personal_data_display($username,$domain,1,'selfcreate',
  960:                                                          $inst_results{$username.':'.$domain});
  961:         if ($rowcount > 0) {
  962:             $output .= $datatable;
  963:         }
  964:         $output .=  '<br /><br /><input type="hidden" name="uname" value="'.$username.'" />'."\n".
  965:                     '<input type="hidden" name="udom" value="'.$domain.'" />'."\n".
  966:                     '<input type="hidden" name="phase" value="username_activation" />';
  967:         my $now = time;
  968:         my %info = ('ip'         => $ENV{'REMOTE_ADDR'},
  969:                     'time'       => $now,
  970:                     'domain'     => $domain,
  971:                     'username'   => $username);
  972:         my $authtoken = &Apache::lonnet::tmpput(\%info,$lonhost,'createaccount');
  973:         if ($authtoken !~ /^error/ && $authtoken ne 'no_such_host') {
  974:             $output .= '<input type="hidden" name="authtoken" value="'.&HTML::Entities::encode($authtoken,'&<>"').'" />';
  975:         } else {
  976:             $output = &mt('An error occurred when storing a token').'<br />'.
  977:                       &mt('You will not be able to proceed to the next stage of account creation').
  978:                       &linkto_email_help($contact_email,$domdesc);
  979:             $checkfail = 'authtoken';
  980:         }
  981:     }
  982:     if ($checkfail) { 
  983:         $msg = '<br /><h4>'.&mt('Account creation unavailable').'</h4>';
  984:         if ($checkfail eq 'username') {
  985:             $msg .= '<span class="LC_warning">'.
  986:                      &mt('A LON-CAPA account may not be created with the username you use.').
  987:                      '</span><br /><br />'.$output;
  988:         } elsif ($checkfail eq 'authtoken') {
  989:             $msg .= '<span class="LC_error">'.&mt('Error creating token.').'</span>'.
  990:                     '<br />'.$output;
  991:         } elsif ($checkfail eq 'inststatus') {
  992:             $msg .= '<span class="LC_warning">'.
  993:                      &mt('You are not permitted to create a LON-CAPA account.').
  994:                      '</span><br /><br />'.$output;
  995:         }
  996:         $msg .= &mt('Please contact the [_1] ([_2]) for assistance.',
  997:                 $contact_name,$contact_email).'<br /><hr />'.
  998:                 $sso_logout;
  999:         &Apache::lonnet::logthis("ERROR: failure type of '$checkfail' when performing username check to create account for authenticated user: $username, in domain $domain");
 1000:     } else {
 1001:         if ($courseid ne '') {
 1002:             $output .= '<input type="hidden" name="courseid" value="'.$courseid.'" />';
 1003:         }
 1004:         $output .= '<input type="submit" name="newaccount" value="'.
 1005:                    &mt('Create LON-CAPA account').'" /></form>';
 1006:         if ($rowcount) {
 1007:             if ($editable) {
 1008:                 if ($courseid ne '') { 
 1009:                     $msg = '<br /><h4>'.&mt('User information').'</h4>';
 1010:                 }
 1011:                 $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 />';
 1012:             } else {
 1013:                  if ($courseid ne '') {
 1014:                      $msg = '<h4>'.&mt('Review user information').'</h4>';
 1015:                  }
 1016:                  $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 />';
 1017:             }
 1018:         } else {
 1019:             if ($courseid ne '') {
 1020:                 $msg = '<h4>'.&mt('Confirmation').'</h4>';
 1021:             }
 1022:             $msg .= &mt('Confirm that you wish to create an account.');
 1023:         }
 1024:         $msg .= $output;
 1025:     }
 1026:     return $msg;
 1027: }
 1028: 
 1029: sub username_activation {
 1030:     my ($r,$username,$domain,$domdesc,$courseid) = @_;
 1031:     my $output;
 1032:     my $error     = '<span class="LC_error">'.&mt('Error:').' ';
 1033:     my $end       = '</span><br /><br />';
 1034:     my $rtnlink   = '<a href="javascript:history.back();" />'.
 1035:                     &mt('Return to previous page').'</a>'.
 1036:                     &Apache::loncommon::end_page();
 1037:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 1038:     my %data = &Apache::lonnet::tmpget($env{'form.authtoken'});
 1039:     my $now = time;
 1040:     my $earlyout;
 1041:     my $timeout = 300;
 1042:     if (keys(%data) == 0) {
 1043:         $output = &mt('Sorry, your authentication has expired.');
 1044:         $earlyout = 'fail';
 1045:     }
 1046:     if (($data{'time'} !~ /^\d+$/) ||
 1047:         ($data{'domain'} ne $domain) || 
 1048:         ($data{'username'} ne $username)) {
 1049:         $earlyout = 'fail';
 1050:         $output = &mt('The credentials you provided could not be verified.');   
 1051:     } elsif ($now - $data{'time'} > $timeout) {
 1052:         $earlyout = 'fail';
 1053:         $output = &mt('Sorry, your authentication has expired.');
 1054:     }
 1055:     if ($earlyout ne '') {
 1056:         $output .= '<br />'.&mt('Please [_1]start again[_2].','<a href="/adm/createaccount">','</a>');
 1057:         return($earlyout,$output);
 1058:     }
 1059:     if ((($domdefaults{'auth_def'} =~/^krb(4|5)$/) && 
 1060:          ($domdefaults{'auth_arg_def'} ne '')) || 
 1061:         ($domdefaults{'auth_def'} eq 'localauth')) {
 1062:         if ($env{'form.courseid'} ne '') {
 1063:             my ($result,$userchkmsg) = &check_id($username,$domain,$domdesc);
 1064:             if ($result eq 'fail') {
 1065:                 $output = $error.&mt('Invalid ID format').$end.
 1066:                           $userchkmsg.$rtnlink;
 1067:                 return ('fail',$output);
 1068:             }
 1069:         }
 1070:         # Call modifyuser
 1071:         my (%rulematch,%inst_results,%curr_rules,%got_rules,%alerts,%info);
 1072:         &call_rulecheck($username,$domain,\%alerts,\%rulematch,
 1073:                         \%inst_results,\%curr_rules,\%got_rules);
 1074:         my @userinfo = ('firstname','middlename','lastname','generation',
 1075:                         'permanentemail','id');
 1076:         my %canmodify = 
 1077:             &Apache::loncreateuser::selfcreate_canmodify('selfcreate',$domain,
 1078:                                                          \@userinfo,\%inst_results);
 1079:         foreach my $item (@userinfo) {
 1080:             if ($canmodify{$item}) {
 1081:                 $info{$item} = $env{'form.c'.$item};
 1082:             } else {
 1083:                 $info{$item} = $inst_results{$username.':'.$domain}{$item}; 
 1084:             }
 1085:         }
 1086:         if (ref($inst_results{$username.':'.$domain}{'inststatus'}) eq 'ARRAY') {
 1087:             my @inststatuses = @{$inst_results{$username.':'.$domain}{'inststatus'}};
 1088:             $info{'inststatus'} = join(':',map { &escape($_); } @inststatuses);
 1089:         }
 1090:         my $result =
 1091:             &Apache::lonnet::modifyuser($domain,$username,$env{'form.cid'},
 1092:                           $domdefaults{'auth_def'},
 1093:                           $domdefaults{'auth_arg_def'},$info{'firstname'},
 1094:                           $info{'middlename'},$info{'lastname'},
 1095:                           $info{'generation'},undef,undef,
 1096:                           $info{'permanentemail'},$info{'inststatus'});
 1097:         if ($result eq 'ok') {
 1098:             my $delete = &Apache::lonnet::tmpdel($env{'form.authtoken'});
 1099:             $output = &mt('A LON-CAPA account has been created for username: [_1] in domain: [_2].',$username,$domain);
 1100:             my $uhome=&Apache::lonnet::homeserver($username,$domain,'true');
 1101:             &start_session($r,$username,$domain,$uhome,$courseid);
 1102:             my $nostart = 1;
 1103:             return ('ok',$output,$nostart);
 1104:         } else {
 1105:             $output = &mt('Account creation failed for username: [_1] in domain: [_2].',$username,$domain).'<br /><span class="LC_error">'.&mt('Error: [_1]',$result).'</span>';
 1106:             return ('fail',$output);
 1107:         }
 1108:     } else {
 1109:         $output = &mt('User account creation is not available for the current default authentication type.')."\n";
 1110:         return('fail',$output);
 1111:     }
 1112: }
 1113: 
 1114: sub check_id {
 1115:     my ($username,$domain,$domdesc) = @_;
 1116:     # Check ID format
 1117:     # Is $username in an okay format for $domain 
 1118:     # (right number of characters, special characters, etc - follow domain rules)?
 1119:     # $domdesc is just used for user error messages
 1120:     my (%alerts,%rulematch,%inst_results,%curr_rules,%checkhash);
 1121:     my %checks = ('id' => 1);
 1122:     %{$checkhash{$username.':'.$domain}} = (
 1123:                                             'newuser' => 1,
 1124:                                             'id' => $env{'form.cid'},
 1125:                                            );
 1126:     &Apache::loncommon::user_rule_check(\%checkhash,\%checks,\%alerts,
 1127:                                         \%rulematch,\%inst_results,\%curr_rules);
 1128:     if (ref($alerts{'id'}) eq 'HASH') {
 1129:         if (ref($alerts{'id'}{$domain}) eq 'HASH') {
 1130:             if ($alerts{'id'}{$domain}{$env{'form.cid'}}) {
 1131:                 my $userchkmsg;
 1132:                 if (ref($curr_rules{$domain}) eq 'HASH') {
 1133:                     $userchkmsg  =
 1134:                         &Apache::loncommon::instrule_disallow_msg('id',
 1135:                                                            $domdesc,1).
 1136:                         &Apache::loncommon::user_rule_formats($domain,
 1137:                               $domdesc,$curr_rules{$domain}{'id'},'id');
 1138:                 }
 1139:                 return ('fail',$userchkmsg);
 1140:             }
 1141:         }
 1142:     }
 1143:     return; 
 1144: }
 1145: 
 1146: sub invalid_state {
 1147:     my ($error,$domdesc,$contact_name,$contact_email,$msgtext) = @_;
 1148:     my $msg = '<h3>'.&mt('Account creation unavailable').'</h3><span class="LC_error">';
 1149:     if ($error eq 'baduseremail') {
 1150:         $msg .= &mt('The e-mail address you provided does not appear to be a valid address.');
 1151:     } elsif ($error eq 'existinguser') {
 1152:         $msg .= &mt('The e-mail address you provided is already in use as a username in LON-CAPA at this institution.');
 1153:     } elsif ($error eq 'userrules') {
 1154:         $msg .= &mt('Username rules at this institution do not allow the e-mail address you provided to be used as a username.');
 1155:     } elsif ($error eq 'userformat') {
 1156:         $msg .= &mt('The e-mail address you provided may not be used as a username at this LON-CAPA institution.');
 1157:     } elsif ($error eq 'captcha') {
 1158:         $msg .= &mt('Validation of the code you entered failed.');
 1159:     } elsif ($error eq 'noemails') {
 1160:         $msg .= &mt('Creation of a new user account using an e-mail address as username is not permitted at this LON-CAPA institution.');
 1161:     }
 1162:     $msg .= '</span>';
 1163:     if ($msgtext) {
 1164:         $msg .= '<br />'.$msgtext;
 1165:     }
 1166:     $msg .= &linkto_email_help($contact_email,$domdesc,$error);
 1167:     return $msg;
 1168: }
 1169: 
 1170: sub linkto_email_help {
 1171:     my ($contact_email,$domdesc,$error) = @_;
 1172:     my $msg;
 1173:     my $href = '/adm/helpdesk';
 1174:     if ($contact_email ne '') {
 1175:         my $escuri = &HTML::Entities::encode('/adm/createaccount','&<>"');
 1176:         $href .= '?origurl='.$escuri;
 1177:         if ($error eq 'existinguser') {
 1178:             my $escemail = &HTML::Entities::encode($env{'form.useremail'});
 1179:             $href .= '&useremail='.$escemail.'&useraccount='.$escemail;
 1180:         }
 1181:         $msg .= '<br />'.&mt('You may wish to contact the [_1]LON-CAPA helpdesk[_2] for [_3].','<a href="'.$href.'">','</a>',$domdesc).'<br />';
 1182:     } else {
 1183:         $msg .= '<br />'.&mt('You may wish to send an e-mail to the server administrator: [_1] for [_2].',$Apache::lonnet::perlvar{'AdminEmail'},$domdesc).'<br />';
 1184:     }
 1185:     return $msg;
 1186: }
 1187: 
 1188: sub create_captcha {
 1189:     my ($output_dir,$db_dir) = @_;
 1190:     my %captcha_params = &captcha_settings();
 1191:     my ($output,$maxtries,$tries) = ('',10,0);
 1192:     while ($tries < $maxtries) {
 1193:         $tries ++;
 1194:         my $captcha = Authen::Captcha->new (
 1195:                                            output_folder => $captcha_params{'output_dir'},
 1196:                                            data_folder   => $captcha_params{'db_dir'},
 1197:                                           );
 1198:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
 1199: 
 1200:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
 1201:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
 1202:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
 1203:                      '<input type="text" size="5" name="code" value="" /><br />'.
 1204:                      '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" />';
 1205:             last;
 1206:         }
 1207:     }
 1208:     return $output;
 1209: }
 1210: 
 1211: sub captcha_settings {
 1212:     my %captcha_params = ( 
 1213:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
 1214:                            www_output_dir => "/captchaspool",
 1215:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
 1216:                            numchars       => '5',
 1217:                          );
 1218:     return %captcha_params;
 1219: }
 1220: 
 1221: sub getkeys {
 1222:     my ($lkey,$ukey) = @_;
 1223:     my $lextkey=hex($lkey);
 1224:     if ($lextkey>2147483647) { $lextkey-=4294967296; }
 1225: 
 1226:     my $uextkey=hex($ukey);
 1227:     if ($uextkey>2147483647) { $uextkey-=4294967296; }
 1228:     return ($lextkey,$uextkey);
 1229: }
 1230: 
 1231: sub serverform {
 1232:     my ($logtoken,$lonhost,$mailtoken,$courseid,$context) = @_;
 1233:     my $phase = 'username_validation';
 1234:     my $catalog_elements;
 1235:     if ($context eq 'selfenroll') {
 1236:         $phase = 'selfenroll_login';
 1237:     }
 1238:     if ($courseid ne '') {
 1239:         $catalog_elements = &Apache::lonhtmlcommon::echo_form_input(['courseid','phase']);
 1240:     } 
 1241:     my $output = <<ENDSERVERFORM;
 1242:   <form name="server" method="post" action="/adm/createaccount">
 1243:    <input type="hidden" name="logtoken" value="$logtoken" />
 1244:    <input type="hidden" name="token" value="$mailtoken" />
 1245:    <input type="hidden" name="serverid" value="$lonhost" />
 1246:    <input type="hidden" name="uname" value="" />
 1247:    <input type="hidden" name="upass" value="" />
 1248:    <input type="hidden" name="udom" value="" />
 1249:    <input type="hidden" name="phase" value="$phase" />
 1250:    <input type="hidden" name="courseid" value="$courseid" />
 1251:    $catalog_elements
 1252:   </form>
 1253: ENDSERVERFORM
 1254:     return $output;
 1255: }
 1256: 
 1257: sub process_credentials {
 1258: #
 1259: # Fetches the information from the logtoken via tmpget
 1260: # Token contains the DES-key and the stage of the process (would only be "createaccount")
 1261: # $lonhost in this routine is *not* necessarily the machine that this runs on,
 1262: # but $env{'form.serverid'}, the machine that issued the token. 
 1263: #
 1264:     my ($logtoken,$lonhost) = @_;
 1265:     my $tmpinfo=Apache::lonnet::reply('tmpget:'.$logtoken,$lonhost);
 1266:     my ($retrieved,$output,$upass);
 1267:     if (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost')) {
 1268:         $output = &mt('Information needed to verify your login information is missing, inaccessible or expired.')
 1269:                  .'<br />'.&mt('You may need to reload the previous page to obtain a new token.');
 1270:         return ($retrieved,$output,$upass); 
 1271:     } else {
 1272:         my $reply = &Apache::lonnet::reply('tmpdel:'.$logtoken,$lonhost);
 1273:         if ($reply eq 'ok') {
 1274:             $retrieved = 'ok';
 1275:         } else {
 1276:             $output = &mt('Session could not be opened.');
 1277:         }
 1278:     }
 1279:     my ($key,$caller)=split(/&/,$tmpinfo);
 1280:     if ($caller eq 'createaccount') {
 1281:         $upass = &Apache::lonpreferences::des_decrypt($key,$env{'form.upass'});
 1282:     } else {
 1283:         $output = &mt('Unable to retrieve your log-in information - unexpected context');
 1284:     }
 1285: # $retrieved is 'ok' if retrieved okay
 1286: # $output is screen output for the user
 1287: # $upass is $env{'form.upass'}, decrypted with the DES-key, if stage was 'createaccount'
 1288: 
 1289:     return ($retrieved,$output,$upass);
 1290: }
 1291: 
 1292: sub guest_format_check {
 1293:     my ($useremail,$domain,$cancreate,$settings) = @_;
 1294:     my ($login,$format_match,$format_msg,@user_rules);
 1295:     if (ref($settings) eq 'HASH') {
 1296:         if (ref($settings->{'email_rule'}) eq 'ARRAY') {
 1297:             push(@user_rules,@{$settings->{'email_rule'}});
 1298:         }
 1299:     }
 1300:     if (@user_rules > 0) {
 1301:         my %rule_check = 
 1302:             &Apache::lonnet::inst_rulecheck($domain,$useremail,undef,
 1303:                                             'selfcreate',\@user_rules);
 1304:         if (keys(%rule_check) > 0) {
 1305:             foreach my $item (keys(%rule_check)) {
 1306:                 if ($rule_check{$item}) {
 1307:                     $format_match = 1;   
 1308:                     last;
 1309:                 }
 1310:             }
 1311:         }
 1312:     }
 1313:     if ($format_match) {
 1314:         ($login) = ($useremail =~ /^([^\@]+)\@/);
 1315:         $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 />';
 1316:         if (ref($cancreate) eq 'ARRAY') {
 1317:             if (grep(/^login$/,@{$cancreate})) {
 1318:                 $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 />'; 
 1319:             }
 1320:         }
 1321:     }
 1322:     return $format_msg;
 1323: }
 1324: 
 1325: sub sso_logout_frag {
 1326:     my ($r,$domain) = @_;
 1327:     my $endsessionmsg;
 1328:     if (defined($r->dir_config('lonSSOUserLogoutMessageFile_'.$domain))) {
 1329:         my $msgfile = $r->dir_config('lonSSOUserLogoutMessageFile_'.$domain);
 1330:         if (-e $msgfile) {
 1331:             open(my $fh,"<$msgfile");
 1332:             $endsessionmsg = join('',<$fh>);
 1333:             close($fh);
 1334:         }
 1335:     } elsif (defined($r->dir_config('lonSSOUserLogoutMessageFile'))) {
 1336:         my $msgfile = $r->dir_config('lonSSOUserLogoutMessageFile');
 1337:         if (-e $msgfile) {     
 1338:             open(my $fh,"<$msgfile");
 1339:             $endsessionmsg = join('',<$fh>);
 1340:             close($fh);
 1341:         }
 1342:     }
 1343:     return $endsessionmsg;
 1344: }
 1345: 
 1346: sub catreturn_js {
 1347:     return  <<"ENDSCRIPT";
 1348: <script type="text/javascript">
 1349: 
 1350: function ToSelfenroll(formname) {
 1351:     var formidx = getFormByName(formname);
 1352:     if (formidx > -1) {
 1353:         document.forms[formidx].action = '/adm/selfenroll';
 1354:         numidx = getIndexByName(formidx,'phase');
 1355:         if (numidx > -1) {
 1356:             document.forms[formidx].elements[numidx].value = '';   
 1357:         }
 1358:         numidx = getIndexByName(formidx,'context');
 1359:         if (numidx > -1) {
 1360:             document.forms[formidx].elements[numidx].value = '';
 1361:         }
 1362:     }
 1363:     document.forms[formidx].submit();
 1364: }
 1365: 
 1366: function ToCatalog(formname,caller) {
 1367:     var formidx = getFormByName(formname);
 1368:     if (formidx > -1) {
 1369:         document.forms[formidx].action = '/adm/coursecatalog';
 1370:         numidx = getIndexByName(formidx,'coursenum');
 1371:         if (numidx > -1) {
 1372:             if (caller != 'details') {
 1373:                 document.forms[formidx].elements[numidx].value = '';
 1374:             }
 1375:         }
 1376:     }
 1377:     document.forms[formidx].submit();
 1378: }
 1379: 
 1380: function getIndexByName(formidx,item) {
 1381:     for (var i=0;i<document.forms[formidx].elements.length;i++) {
 1382:         if (document.forms[formidx].elements[i].name == item) {
 1383:             return i;
 1384:         }
 1385:     }
 1386:     return -1;
 1387: }
 1388: 
 1389: function getFormByName(item) {
 1390:     for (var i=0; i<document.forms.length; i++) {
 1391:         if (document.forms[i].name == item) {
 1392:             return i;
 1393:         }
 1394:     }
 1395:     return -1;
 1396: }
 1397: 
 1398: </script>
 1399: ENDSCRIPT
 1400: 
 1401: }
 1402: 
 1403: 1;

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