File:  [LON-CAPA] / loncom / interface / createaccount.pm
Revision 1.40.2.5.2.8: download - view: text, annotated - select for diffs
Tue Feb 14 01:06:12 2012 UTC (12 years, 3 months ago) by raeburn
Branches: loncapaMITrelate_1
Diff to branchpoint 1.40.2.5: preferred, unified
- Customization for MITrelate.
  - Missing punctuation.
  - Improve readability with bulleted list.

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

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