File:  [LON-CAPA] / loncom / interface / createaccount.pm
Revision 1.40.2.5.2.2: download - view: text, annotated - select for diffs
Wed Feb 8 19:08:41 2012 UTC (12 years, 4 months ago) by raeburn
Branches: loncapaMITrelate_1
Diff to branchpoint 1.40.2.5: preferred, unified
- Customization for MITrelate.
  - Custom wording for createaccount page.

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