File:  [LON-CAPA] / loncom / interface / createaccount.pm
Revision 1.40.2.5.2.1: download - view: text, annotated - select for diffs
Mon Feb 6 02:36:29 2012 UTC (12 years, 4 months ago) by raeburn
Branches: loncapaMITrelate_1
Diff to branchpoint 1.40.2.5: preferred, unified
- Customatization for MITrelate.
  - Forward port: 1.37.2.1, 1.37.2.2, 1.37.2.3, 1.37.2.4, 1.37.2.5.

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

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