File:  [LON-CAPA] / loncom / interface / createaccount.pm
Revision 1.18: download - view: text, annotated - select for diffs
Sun Jul 13 00:51:31 2008 UTC (15 years, 11 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
Move duplicate code in lonauth.pm and createaccount.pm which handles result from createaccount::username_check() into username_check() for both log-in ID and SSO cases.
- additional args ($contact_name $sso_logout) passed to &username_check for SSO case.
- Page for user information data table customized based on availability of data fields, and whther data can be entered (according to $rowcount and $editable args returned from &loncreateuser::personal_data_display().
 - If no values are available or editable don't display table.
 - If only non-editable values are available - display table with appropriate message.
 - If one or more editable values - display table with appropriate message.
If username check reports errors (e.g., 'username' not in institutional database, or 'authtoken' - authtoken could not be set) - display appropriate error reports.

    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.18 2008/07/13 00:51:31 raeburn Exp $
    7: #
    8: # Copyright Michigan State University Board of Trustees
    9: #
   10: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
   11: #
   12: # LON-CAPA is free software; you can redistribute it and/or modify
   13: # it under the terms of the GNU General Public License as published by
   14: # the Free Software Foundation; either version 2 of the License, or
   15: # (at your option) any later version.
   16: #
   17: # LON-CAPA is distributed in the hope that it will be useful,
   18: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   19: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   20: # GNU General Public License for more details.
   21: #
   22: # You should have received a copy of the GNU General Public License
   23: # along with LON-CAPA; if not, write to the Free Software
   24: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   25: #
   26: # /home/httpd/html/adm/gpl.txt
   27: #
   28: # http://www.lon-capa.org/
   29: #
   30: #
   31: package Apache::createaccount;
   32: 
   33: use strict;
   34: use Apache::Constants qw(:common);
   35: use Apache::lonacc;
   36: use Apache::lonnet;
   37: use Apache::loncommon;
   38: use Apache::lonhtmlcommon;
   39: use Apache::lonlocal;
   40: use Apache::lonauth;
   41: use Apache::resetpw;
   42: use Authen::Captcha;
   43: use DynaLoader; # for Crypt::DES version
   44: use Crypt::DES;
   45: use LONCAPA qw(:DEFAULT :match);
   46: use HTML::Entities;
   47: 
   48: 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:     if ($sso_username ne '' && $sso_domain ne '') {
   62:         $domain = $sso_domain; 
   63:     } else { 
   64:         $domain = &Apache::lonnet::default_login_domain();
   65:     }
   66:     my $domdesc = &Apache::lonnet::domain($domain,'description');
   67:     my $contact_name = &mt('LON-CAPA helpdesk');
   68:     my $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};
   69:     my $contacts =
   70:         &Apache::loncommon::build_recipient_list(undef,'helpdeskmail',
   71:                                                  $domain,$origmail);
   72:     my ($contact_email) = split(',',$contacts);
   73:     my $lonhost = $r->dir_config('lonHostID');
   74:     my $include = $r->dir_config('lonIncludes');
   75:     my $start_page;
   76: 
   77:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['token','courseid']);
   78:     &Apache::lonacc::get_posted_cgi($r);
   79:     &Apache::lonlocal::get_language_handle($r);
   80: 
   81:     my $handle = &Apache::lonnet::check_for_valid_session($r);
   82:     if ($handle ne '') {
   83:         $start_page =
   84:             &Apache::loncommon::start_page('Already logged in');
   85:         my $end_page =
   86:             &Apache::loncommon::end_page();
   87:         $r->print($start_page."\n".'<h2>'.&mt('You are already logged in').'</h2>'.
   88:                   '<p>'.&mt('Please either [_1]continue the current session[_2] or [_3]logout[_4].','<a href="/adm/roles">','</a>','<a href="/adm/logout">','</a>').
   89:                   '</p><p><a href="/adm/loginproblems.html">'.&mt('Login problems?').'</a></p>'.$end_page);
   90:        return OK;
   91:     }
   92:     $start_page =
   93:         &Apache::loncommon::start_page('Create a user account in LON-CAPA','',
   94:                                        {'no_inline_link'   => 1,});
   95:     if ($env{'form.phase'} eq 'username_activation') {
   96:         if ($env{'form.udom'} ne '') {
   97:             $domain = $env{'form.udom'};
   98:         }
   99:     }
  100:     my @cancreate;
  101:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$domain);
  102:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
  103:         if (ref($domconfig{'usercreation'}{'cancreate'}) eq 'HASH') {
  104:             if (ref($domconfig{'usercreation'}{'cancreate'}{'selfcreate'}) eq 'ARRAY') {
  105:                 @cancreate = @{$domconfig{'usercreation'}{'cancreate'}{'selfcreate'}};
  106:             } elsif (($domconfig{'usercreation'}{'cancreate'}{'selfcreate'} ne 'none') &&
  107:                      ($domconfig{'usercreation'}{'cancreate'}{'selfcreate'} ne '')) {
  108:                 @cancreate = ($domconfig{'usercreation'}{'cancreate'}{'selfcreate'});
  109:             }
  110:         }
  111:     }
  112: 
  113:     if (@cancreate == 0) {
  114:         &print_header($r,$start_page);
  115:         my $output = '<h3>'.&mt('Account creation unavailable').'</h3>'.
  116:                      '<span class="LC_warning">'.
  117:                      &mt('Creation of a new user account using an e-mail address or an institutional log-in ID as username is not permitted at this institution ([_1]).',$domdesc).'</span><br /><br />';
  118:         $r->print($output);
  119:         $r->print(&Apache::loncommon::end_page());
  120:         return OK;
  121:     }
  122: 
  123:     my $courseid;
  124:     if (defined($env{'form.courseid'})) {
  125:         $courseid = &validate_course($env{'form.courseid'});
  126:     }
  127: 
  128:     if ($sso_username ne '') {
  129:         &print_header($r,$start_page);
  130:         my ($msg,$sso_logout);
  131:         $sso_logout = &sso_logout_frag($r,$domain);
  132:         if (grep(/^sso$/,@cancreate)) {
  133:             $msg = '<h3>'.&mt('Account creation').'</h3>'.
  134:                    &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 />';
  135: 
  136:             $msg .= &username_check($sso_username,$domain,$domdesc,$courseid, 
  137:                                     $lonhost,$contact_email,$contact_name,$sso_logout);
  138:         } else {
  139:             $msg = '<h3>'.&mt('Account creation unavailable').'</h3>'.
  140:                    '<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 />'.
  141:                    $sso_logout;
  142:         }
  143:         $r->print($msg);
  144:         $r->print(&Apache::loncommon::end_page());
  145:         return OK;
  146:     }
  147: 
  148:     my ($output,$nostart,$noend);
  149:     my $token = $env{'form.token'};
  150:     if ($token) {
  151:         ($output,$nostart,$noend) = 
  152:             &process_mailtoken($r,$token,$contact_name,$contact_email,$domain,
  153:                                $domdesc,$lonhost,$include,$start_page);
  154:         if ($nostart) {
  155:             if ($noend) {
  156:                 return OK;
  157:             } else {
  158:                 $r->print($output);
  159:                 $r->print(&Apache::loncommon::end_page());
  160:                 return OK;
  161:             }
  162:         } else {
  163:             &print_header($r,$start_page);
  164:             $r->print($output);
  165:             $r->print(&Apache::loncommon::end_page());
  166:             return OK;
  167:         }
  168:     }
  169: 
  170:     if ($env{'form.phase'} eq 'username_activation') {
  171:         (my $result,$output,$nostart) = 
  172:             &username_activation($r,$env{'form.uname'},$domain,$domdesc,
  173:                                  $lonhost,$courseid);
  174:         if ($result eq 'ok') {
  175:             if ($nostart) {
  176:                 return OK;
  177:             }
  178:         }
  179:         &print_header($r,$start_page);
  180:         $r->print($output);
  181:         $r->print(&Apache::loncommon::end_page());
  182:         return OK;
  183:     }
  184: 
  185:     &print_header($r,$start_page);
  186:     if ($env{'form.create_with_email'}) {
  187:         $output = &process_email_request($env{'form.useremail'},$domain,$domdesc,
  188:                                          $contact_name,$contact_email,\@cancreate,
  189:                                          $lonhost,$domconfig{'usercreation'},
  190:                                          $courseid);
  191:     } elsif ($env{'form.phase'} eq 'username_validation') {
  192:         $output = &username_validation($env{'form.uname'},$domain,$domdesc,
  193:                                        $contact_name,$contact_email,$courseid,
  194:                                        $lonhost);
  195:     } elsif (!$token) {
  196:         my $now=time;
  197:         if (grep(/^login$/,@cancreate)) {
  198:             my $jsh=Apache::File->new($include."/londes.js");
  199:             $r->print(<$jsh>);
  200:             $r->print(&javascript_setforms($now));
  201:         }
  202:         if (grep(/^email$/,@cancreate)) {
  203:             $r->print(&javascript_validmail());
  204:         }
  205:         $output = &print_username_form($domain,$domdesc,\@cancreate,$now,$lonhost,
  206:                                        $courseid); 
  207:     }
  208:     $r->print($output);
  209:     $r->print(&Apache::loncommon::end_page());
  210:     return OK;
  211: }
  212: 
  213: sub print_header {
  214:     my ($r,$start_page) = @_;
  215:     $r->print($start_page);
  216:     &Apache::lonhtmlcommon::clear_breadcrumbs();
  217:     &Apache::lonhtmlcommon::add_breadcrumb
  218:     ({href=>"/adm/createuser",
  219:       text=>"New username"});
  220:     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Create account'));
  221:     return;
  222: }
  223: 
  224: sub validate_course {
  225:     my ($courseid) = @_;
  226:     my ($cdom,$cnum) = ($courseid =~ /^($match_domain)_($match_courseid)$/);
  227:     if (($cdom ne '') && ($cnum ne '')) {
  228:         if (&Apache::lonnet::is_course($cdom,$cnum)) {
  229:             return ($courseid);
  230:         }
  231:     }
  232:     return;
  233: }
  234: 
  235: sub javascript_setforms {
  236:     my ($now) =  @_;
  237:     my $js = <<ENDSCRIPT;
  238:  <script language="JavaScript">
  239:     function send() {
  240:         this.document.server.elements.uname.value = this.document.client.elements.uname.value;
  241:         uextkey=this.document.client.elements.uextkey.value;
  242:         lextkey=this.document.client.elements.lextkey.value;
  243:         initkeys();
  244: 
  245:         this.document.server.elements.upass.value
  246:             = crypted(this.document.client.elements.upass$now.value);
  247: 
  248:         this.document.client.elements.uname.value='';
  249:         this.document.client.elements.upass$now.value='';
  250: 
  251:         this.document.server.submit();
  252:         return false;
  253:     }
  254:  </script>
  255: ENDSCRIPT
  256:     return $js;
  257: }
  258: 
  259: sub javascript_checkpass {
  260:     my ($now) = @_;
  261:     my $nopass = &mt('You must enter a password.');
  262:     my $mismatchpass = &mt('The passwords you entered did not match.').'\\n'.
  263:                        &mt('Please try again.'); 
  264:     my $js = <<"ENDSCRIPT";
  265: <script type="text/javascript" language="JavaScript">
  266:     function checkpass() {
  267:         var upass = this.document.client.elements.upass$now.value;
  268:         var upasscheck = this.document.client.elements.upasscheck$now.value;
  269:         if (upass == '') {
  270:             alert("$nopass");
  271:             return;
  272:         }
  273:         if (upass == upasscheck) {
  274:             this.document.client.elements.upasscheck$now.value='';
  275:             send();
  276:             return;
  277:         } else {
  278:             alert("$mismatchpass");
  279:             return;
  280:         } 
  281:     }
  282: </script>
  283: ENDSCRIPT
  284:     return $js;
  285: }
  286: 
  287: sub javascript_validmail {
  288:     my %lt = &Apache::lonlocal::texthash (
  289:                email => 'The e-mail address you entered',
  290:                notv  => 'is not a valid e-mail address',
  291:     );
  292:     my $output =  "\n".'<script type="text/javascript">'."\n".
  293:                   &Apache::lonhtmlcommon::javascript_valid_email()."\n";
  294:     $output .= <<"ENDSCRIPT";
  295: function validate_email() {
  296:     field = document.createaccount.useremail;
  297:     if (validmail(field) == false) {
  298:         alert("$lt{'email'}: "+field.value+" $lt{'notv'}.");
  299:         return false;
  300:     }
  301:     return true;
  302: }
  303: ENDSCRIPT
  304:     $output .= "\n".'</script>'."\n";
  305:     return $output;
  306: }
  307: 
  308: sub print_username_form {
  309:     my ($domain,$domdesc,$cancreate,$now,$lonhost,$courseid) = @_;
  310:     my %lt = &Apache::lonlocal::texthash(
  311:                                          unam => 'username',
  312:                                          udom => 'domain',
  313:                                          uemail => 'Email address in LON-CAPA',
  314:                                          proc => 'Proceed');
  315:     my $output;
  316:     if (ref($cancreate) eq 'ARRAY') {
  317:         if (grep(/^login$/,@{$cancreate})) {
  318:             my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
  319:             if ((($domdefaults{'auth_def'} =~/^krb/) && ($domdefaults{'auth_arg_def'} ne '')) || ($domdefaults{'auth_def'} eq 'localauth')) {
  320:                 $output = '<div class="LC_left_float"><h3>'.&mt('Create account with a username provided by this institution').'</h3>';
  321:                 $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 />';
  322:                 my ($lkey,$ukey) = &Apache::lonpreferences::des_keys();
  323:                 my ($lextkey,$uextkey) = &getkeys($lkey,$ukey);
  324:                 my $logtoken=Apache::lonnet::reply('tmpput:'.$ukey.$lkey.'&createaccount',
  325:                                                    $lonhost);
  326:                 $output .= &serverform($logtoken,$lonhost,undef,$courseid);
  327:                 my $unameform = '<input type="text" name="uname" size="10" value="" />';
  328:                 my $upassform = '<input type="password" name="upass'.$now.'" size="10" />';
  329:                 my $submit_text = &mt('Create LON-CAPA account');
  330:                 $output .= '<form name="client" method="post" action="/adm/createaccount">'."\n". 
  331:                            &Apache::lonhtmlcommon::start_pick_box()."\n".
  332:                            &Apache::lonhtmlcommon::row_title(&mt('Log-in ID'),
  333:                                                         'LC_pick_box_title')."\n".
  334:                            $unameform."\n".
  335:                            &Apache::lonhtmlcommon::row_closure(1)."\n".
  336:                            &Apache::lonhtmlcommon::row_title(&mt('Password'),
  337:                                                         'LC_pick_box_title')."\n".
  338:                            $upassform."\n".'<br /><br />'."\n".
  339:                            '<input type="button" name="username_validation" value="'.
  340:                            $submit_text.'" onclick="javascript:send()" />'."\n". 
  341:                            &Apache::lonhtmlcommon::row_closure(1)."\n".
  342:                            &Apache::lonhtmlcommon::end_pick_box().'<br /><br />'."\n".
  343:                            '<input type="hidden" name="lextkey" value="'.$lextkey.'">'."\n".
  344:                            '<input type="hidden" name="uextkey" value="'.$uextkey.'">'."\n".
  345:                            '</form></div>';
  346:             }
  347:         }
  348:         if (grep(/^email$/,@{$cancreate})) {
  349:             $output .= '<div class="LC_left_float"><h3>'.&mt('Create account with an e-mail address as your username').'</h3>';
  350:             if (grep(/^login$/,@{$cancreate})) {
  351:                 $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 />';
  352:             } else {
  353:                 $output .= '<br />';
  354:             }
  355:             my $emailform = '<input type="text" name="useremail" size="25" value="" />';
  356:             my $captchaform = &create_captcha();
  357:             my $submit_text = &mt('Request LON-CAPA account');
  358:             $output .=  '<form name="createaccount" method="post" onSubmit="return validate_email()" action="/adm/createaccount">'.
  359:                         &Apache::lonhtmlcommon::start_pick_box()."\n".
  360:                         &Apache::lonhtmlcommon::row_title(&mt('E-mail address'),
  361:                                                          'LC_pick_box_title')."\n".
  362:                         $emailform."\n".
  363:                         &Apache::lonhtmlcommon::row_closure(1).
  364:                         &Apache::lonhtmlcommon::row_title(&mt('Validation'),
  365:                                                          'LC_pick_box_title')."\n".
  366:                         $captchaform."\n".'<br /><br />';
  367:             if ($courseid ne '') {
  368:                 $output .= '<input type="hidden" name="courseid" value="'.$courseid.'"/>'."\n"; 
  369:             }
  370:             $output .= '<input type="submit" name="create_with_email" value="'. 
  371:                         $submit_text.'" />'.
  372:                         &Apache::lonhtmlcommon::row_closure(1).
  373:                         &Apache::lonhtmlcommon::end_pick_box().'<br /><br /></form>'.
  374:                         '</div>';
  375:         }
  376:     }
  377:     if ($output eq '') {
  378:         $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);
  379:     } else {
  380:         $output .= '<div class="LC_clear_float_footer"></div>';
  381:     }
  382:     return $output;
  383: }
  384: 
  385: sub process_email_request {
  386:     my ($useremail,$domain,$domdesc,$contact_name,$contact_email,$cancreate,
  387:         $server,$settings,$courseid) = @_;
  388:     my $useremail = $env{'form.useremail'};
  389:     my $output;
  390:     if (ref($cancreate) eq 'ARRAY') {
  391:         if (!grep(/^email$/,@{$cancreate})) {
  392:             $output = &invalid_state('noemails',$domdesc,
  393:                                      $contact_name,$contact_email);
  394:             return $output;
  395:         } elsif ($useremail !~ /^[^\@]+\@[^\@]+\.[^\@\.]+$/) {
  396:             $output = &invalid_state('baduseremail',$domdesc,
  397:                                      $contact_name,$contact_email);
  398:             return $output;
  399:         } else {
  400:             my $uhome = &Apache::lonnet::homeserver($useremail,$domain);
  401:             if ($uhome ne 'no_host') {
  402:                 $output = &invalid_state('existinguser',$domdesc,
  403:                                          $contact_name,$contact_email);
  404:                 return $output;
  405:             } else {
  406:                 my $code = $env{'form.code'};
  407:                 my $md5sum = $env{'form.crypt'};
  408:                 my %captcha_params = &captcha_settings();
  409:                 my $captcha = Authen::Captcha->new(
  410:                                   output_folder => $captcha_params{'output_dir'},
  411:                                   data_folder   => $captcha_params{'db_dir'},
  412:                                  );
  413:                 my $captcha_chk = $captcha->check_code($code,$md5sum);
  414:                 my %captcha_hash = (
  415:                                   0       => 'Code not checked (file error)',
  416:                                   -1      => 'Failed: code expired',
  417:                                   -2      => 'Failed: invalid code (not in database)',
  418:                                   -3      => 'Failed: invalid code (code does not match crypt)',
  419:                                    );
  420:                 if ($captcha_chk != 1) {
  421:                     $output = &invalid_state('captcha',$domdesc,$contact_name,
  422:                                              $contact_email,$captcha_hash{$captcha_chk});
  423:                     return $output;
  424:                 }
  425:                 my (%rulematch,%inst_results,%curr_rules,%got_rules,%alerts);
  426:                 my $uhome=&Apache::lonnet::homeserver($useremail,$domain);
  427:                 if ($uhome eq 'no_host') {
  428:                     my $checkhash;
  429:                     my $checks = { 'username' => 1 };
  430:                     $checkhash->{$useremail.':'.$domain} = { 'newuser' => 1, };
  431:                     &Apache::loncommon::user_rule_check($checkhash,$checks,
  432:                           \%alerts,\%rulematch,\%inst_results,\%curr_rules,
  433:                           \%got_rules);
  434:                     if (ref($alerts{'useremail'}) eq 'HASH') {
  435:                         if (ref($alerts{'useremail'}{$domain}) eq 'HASH') {
  436:                             if ($alerts{'username'}{$domain}{$useremail}) {
  437:                                 $output = &invalid_state('userrules',$domdesc,
  438:                                                          $contact_name,$contact_email);
  439:                                 return $output;
  440:                             }
  441:                         }
  442:                     }
  443:                     my $format_msg = 
  444:                         &guest_format_check($useremail,$domain,$cancreate,
  445:                                             $settings);
  446:                     if ($format_msg) {
  447:                         $output = &invalid_state('userformat',$domdesc,$contact_name,
  448:                                                  $contact_email,$format_msg);
  449:                         return $output;
  450:                     }
  451:                 }
  452:             }
  453:         }
  454:         $output = &send_token($domain,$useremail,$server,$domdesc,$contact_name,
  455:                           $contact_email,$courseid);
  456:     }
  457:     return $output;
  458: }
  459: 
  460: sub send_token {
  461:     my ($domain,$email,$server,$domdesc,$contact_name,$contact_email,$courseid) = @_;
  462:     my $msg = '<h3>'.&mt('Account creation status').'</h3>'.
  463:               &mt('Thank you for your request to create a new LON-CAPA account.').
  464:               '<br /><br />';
  465:     my $now = time;
  466:     my %info = ('ip'         => $ENV{'REMOTE_ADDR'},
  467:                 'time'       => $now,
  468:                 'domain'     => $domain,
  469:                 'username'   => $email,
  470:                 'courseid'   => $courseid);
  471:     my $token = &Apache::lonnet::tmpput(\%info,$server);
  472:     if ($token !~ /^error/ && $token ne 'no_such_host') {
  473:         my $esc_token = &escape($token);
  474:         my $mailmsg = &mt('A request was submitted on [_1] for creation of a LON-CAPA account at the following institution: [_2].',localtime(time),$domdesc).' '.
  475:              &mt('To complete this process please open a web browser and enter the following'
  476:                 .' URL in the address/location box: [_1]'
  477:                 ,&Apache::lonnet::absolute_url().'/adm/createaccount?token='.$esc_token);
  478:         my $result = &Apache::resetpw::send_mail($domdesc,$email,$mailmsg,$contact_name,
  479:                                                  $contact_email);
  480:         if ($result eq 'ok') {
  481:             $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>');
  482:         } else {
  483:             $msg .= '<span class="LC_error">'.
  484:                     &mt('An error occurred when sending a message to the e-mail address you provided.').'</span><br />'.
  485:                     ' '.&mt('Please contact the [_1] ([_2]) for assistance.',$contact_name,$contact_email);
  486:         }
  487:     } else {
  488:         $msg .= '<span class="LC_error">'.
  489:                 &mt('An error occurred creating a token required for the account creation process.').'</span><br />'.
  490:                 ' '.&mt('Please contact the [_1] ([_2]) for assistance.',$contact_name,$contact_email);
  491:     }
  492:     return $msg;
  493: }
  494: 
  495: sub process_mailtoken {
  496:     my ($r,$token,$contact_name,$contact_email,$domain,$domdesc,$lonhost,
  497:         $include,$start_page) = @_;
  498:     my ($msg,$nostart,$noend);
  499:     my %data = &Apache::lonnet::tmpget($token);
  500:     my $now = time;
  501:     if (keys(%data) == 0) {
  502:         $msg = &mt('Sorry, the URL you provided to complete creation of a new LON-CAPA account was invalid.')
  503:                .' '.&mt('Either the token included in the URL has been deleted or the URL you provided was invalid.')
  504:                .' '.&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>');
  505:         return $msg;
  506:     }
  507:     if (($data{'time'} =~ /^\d+$/) &&
  508:         ($data{'domain'} ne '') &&
  509:         ($data{'username'}  =~ /^[^\@]+\@[^\@]+\.[^\@\.]+$/)) {
  510:         if ($now - $data{'time'} < 7200) {
  511:             if ($env{'form.phase'} eq 'createaccount') {
  512:                 my ($result,$output) = &create_account($r,$domain,$lonhost,
  513:                                                        $data{'username'},$domdesc);
  514:                 if ($result eq 'ok') {
  515:                     $msg = $output; 
  516:                     my $shownow = &Apache::lonlocal::locallocaltime($now);
  517:                     my $mailmsg = &mt('A LON-CAPA account for the institution: [_1] has been created [_2] from IP address: [_3].  If you did not perform this action or authorize it, please contact the [_4] ([_5]).',$domdesc,$shownow,$ENV{'REMOTE_ADDR'},$contact_name,$contact_email)."\n";
  518:                     my $mailresult = &Apache::resetpw::send_mail($domdesc,$data{'email'},
  519:                                                                  $mailmsg,$contact_name,
  520:                                                                  $contact_email);
  521:                     if ($mailresult eq 'ok') {
  522:                         $msg .= &mt('An e-mail confirming creation of your new LON-CAPA account has been sent to [_1].',$data{'username'});
  523:                     } else {
  524:                         $msg .= &mt('An error occurred when sending e-mail to [_1] confirming creation of your LON-CAPA account.',$data{'username'});
  525:                     }
  526:                     my %form = &start_session($r,$data{'username'},$domain, 
  527:                                               $lonhost,$data{'courseid'},
  528:                                               $token);
  529:                     $nostart = 1;
  530:                     $noend = 1;
  531:                 } else {
  532:                     $msg .= &mt('A problem occurred when attempting to create your new LON-CAPA account.')
  533:                            .'<br />'.$output
  534: #                           .&mt('Please contact the [_1] ([_2]) for assistance.',$contact_name,'<a href="mailto:'.$contact_email.'">'.$contact_email.'</a>');
  535:                            .&mt('Please contact the [_1] ([_2]) for assistance.',$contact_name,$contact_email);
  536:                 }
  537:                 my $delete = &Apache::lonnet::tmpdel($token);
  538:             } else {
  539:                 $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 />';
  540:                 $msg .= &print_dataentry_form($r,$domain,$lonhost,$include,$token,$now,$data{'username'},$start_page);
  541:                 $nostart = 1;
  542:             }
  543:         } else {
  544:             $msg = &mt('Sorry, the token generated when you requested creation of an account has expired.')
  545:                   .' '.&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>');
  546:             }
  547:     } else {
  548:         $msg .= &mt('Sorry, the URL generated when you requested creation of an account contained incomplete information.')
  549:                .' '.&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>');
  550:     }
  551:     return ($msg,$nostart,$noend);
  552: }
  553: 
  554: sub start_session {
  555:     my ($r,$username,$domain,$lonhost,$courseid,$token) = @_;
  556:     my %form = (
  557:                 uname => $username,
  558:                 udom  => $domain,
  559:                );
  560:     my $firsturl = '/adm/roles';
  561:     if (defined($courseid)) {
  562:         $courseid = &validate_course($courseid);
  563:         if ($courseid ne '') {
  564:             $form{'courseid'} = $courseid;
  565:             $firsturl = '/adm/selfenroll?cid='.$courseid;
  566:         }
  567:     }
  568:     if ($r->dir_config('lonBalancer') eq 'yes') {
  569:         &Apache::lonauth::success($r,$form{'uname'},$form{'udom'},
  570:                                   $lonhost,'noredirect',undef,\%form);
  571:         my $delete = &Apache::lonnet::tmpdel($token);
  572:         $r->internal_redirect('/adm/switchserver');
  573:     } else {
  574:         &Apache::lonauth::success($r,$form{'uname'},$form{'udom'},
  575:                                   $lonhost,$firsturl,undef,\%form);
  576:     }
  577:     return %form;
  578: }
  579: 
  580: 
  581: sub print_dataentry_form {
  582:     my ($r,$domain,$lonhost,$include,$mailtoken,$now,$username,$start_page) = @_;
  583:     my ($error,$output);
  584:     &print_header($r,$start_page);
  585:     if (open(my $jsh,"<$include/londes.js")) {
  586:         while(my $line = <$jsh>) {
  587:             $r->print($line);
  588:         }
  589:         close($jsh);
  590:         $output .= &javascript_setforms($now)."\n".&javascript_checkpass($now);
  591:         my ($lkey,$ukey) = &Apache::lonpreferences::des_keys();
  592:         my ($lextkey,$uextkey) = &getkeys($lkey,$ukey);
  593:         my $logtoken=Apache::lonnet::reply('tmpput:'.$ukey.$lkey.'&createaccount',
  594:                                            $lonhost);
  595:         my @userinfo = ('firstname','middlename','lastname','generation','id',
  596:                         'permanentemail');
  597:         my %lt=&Apache::lonlocal::texthash(
  598:                     'pd'             => "Personal Data",
  599:                     'firstname'      => "First Name",
  600:                     'middlename'     => "Middle Name",
  601:                     'lastname'       => "Last Name",
  602:                     'generation'     => "Generation",
  603:                     'permanentemail' => "Permanent e-mail address",
  604:                     'id'             => "ID/Student Number",
  605:                     'lg'             => "Login Data"
  606:         );
  607:         my %textboxsize = (
  608:                            firstname      => '15',
  609:                            middlename     => '15',
  610:                            lastname       => '15',
  611:                            generation     => '5',
  612:                            id             => '15',
  613:                           );
  614:         my $genhelp=&Apache::loncommon::help_open_topic('Generation');
  615:         $output .= '<div class="LC_left_float"><h3>'.$lt{'pd'}.'</h3>'.
  616:                   '<form name="server" method="post" target="_top" action="/adm/createaccount">'.
  617:                   &Apache::lonhtmlcommon::start_pick_box();
  618:         foreach my $item (@userinfo) {
  619:             my $rowtitle = $lt{$item};
  620:             if ($item eq 'generation') {
  621:                 $rowtitle = $genhelp.$rowtitle;
  622:             }
  623:             $output .= &Apache::lonhtmlcommon::row_title($rowtitle,undef,'LC_oddrow_value')."\n";
  624:             if ($item eq 'permanentemail') {
  625:                 $output .= $username;
  626:             } else {
  627:                 $output .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
  628:             }
  629:             $output .= &Apache::lonhtmlcommon::row_closure(1);
  630:         }
  631:         $output .= &Apache::lonhtmlcommon::end_pick_box();
  632:         $output .= <<"ENDSERVERFORM";
  633:    <input type="hidden" name="logtoken" value="$logtoken" />
  634:    <input type="hidden" name="token" value="$mailtoken" />
  635:    <input type="hidden" name="serverid" value="$lonhost" />
  636:    <input type="hidden" name="uname" value="" />
  637:    <input type="hidden" name="upass" value="" />
  638:    <input type="hidden" name="phase" value="createaccount" />
  639:   </form></div>
  640: ENDSERVERFORM
  641:         my $upassone = '<input type="password" name="upass'.$now.'" size="10" />';
  642:         my $upasstwo = '<input type="password" name="upasscheck'.$now.'" size="10" />';
  643:         my $submit_text = &mt('Create LON-CAPA account');
  644:         $output .= '<div class="LC_left_float"><h3>'.$lt{'lg'}.'</h3>'."\n".
  645:                    '<form name="client" method="post" />'."\n".
  646:                    &Apache::lonhtmlcommon::start_pick_box()."\n".
  647:                    &Apache::lonhtmlcommon::row_title(&mt('Username'),
  648:                                                     'LC_pick_box_title')."\n".
  649:                    $username."\n".
  650:                    &Apache::lonhtmlcommon::row_closure(1)."\n".
  651:                    &Apache::lonhtmlcommon::row_title(&mt('Password'),
  652:                                                     'LC_pick_box_title')."\n".
  653:                    $upassone."\n".
  654:                    &Apache::lonhtmlcommon::row_closure(1)."\n".
  655:                    &Apache::lonhtmlcommon::row_title(&mt('Confirm password'),
  656:                                                 'LC_pick_box_title')."\n".
  657:                    $upasstwo."\n".
  658:                    &Apache::lonhtmlcommon::row_closure(1)."\n".
  659:                    &Apache::lonhtmlcommon::end_pick_box()."\n".
  660:                    '<input type="hidden" name="uname" value="'.$username.'">'."\n".
  661:                    '<input type="hidden" name="lextkey" value="'.$lextkey.'">'."\n".
  662:                    '<input type="hidden" name="uextkey" value="'.$uextkey.'">'."\n".
  663:                    '</form></div>'."\n".
  664:                    '<div class="LC_clear_float_footer"><br /><br />'."\n".
  665:                    '<form name="buttonform">'."\n".
  666:                    '<input type="button" name="createaccount" value="'.
  667:                    $submit_text.'" onclick="javascript:checkpass();" /></form></div>';
  668:     } else {
  669:         $output = &mt('Could not load javascript file [_1]','<tt>londes.js</tt>');
  670:     }
  671:     return $output;
  672: }
  673: 
  674: sub create_account {
  675:     my ($r,$domain,$lonhost,$username,$domdesc) = @_;
  676:     my ($retrieved,$output,$upass) = &process_credentials($env{'form.logtoken'},
  677:                                                           $env{'form.serverid'}); 
  678:     # Error messages
  679:     my $error     = '<span class="LC_error">'.&mt('Error:').' ';
  680:     my $end       = '</span><br /><br />';
  681:     my $rtnlink   = '<a href="javascript:history.back();" />'.
  682:                     &mt('Return to previous page').'</a>'.
  683:                     &Apache::loncommon::end_page();
  684:     if ($retrieved eq 'ok') {
  685:         if ($env{'form.cid'} ne '') {
  686:             my ($result,$userchkmsg) = &check_id($username,$domain,$domdesc);
  687:             if ($result eq 'fail') {
  688:                 $output = $error.&mt('Invalid ID format').$end.
  689:                           $userchkmsg.$rtnlink;
  690:                 return ('fail',$output);
  691:             }
  692:         }
  693:     } else {
  694:         return ('fail',$error.$output.$end.$rtnlink);
  695:     }
  696:     # Call modifyuser
  697:     my $result = 
  698:         &Apache::lonnet::modifyuser($domain,$username,$env{'form.cid'},
  699:                                     'internal',$upass,$env{'form.cfirstname'},
  700:                                     $env{'form.cmiddlename'},$env{'form.clastname'},
  701:                                     $env{'form.cgeneration'},undef,undef,$username);
  702:     $output = &mt('Generating user: [_1]',$result);
  703:     my $uhome = &Apache::lonnet::homeserver($username,$domain);
  704:     $output .= '<br />'.&mt('Home server: [_1]',$uhome).' '.
  705:               &Apache::lonnet::hostname($uhome).'<br /><br />';
  706:     return ('ok',$output);
  707: }
  708: 
  709: sub username_validation {
  710:     my ($username,$domain,$domdesc,$contact_name,$contact_email,$courseid,$lonhost) = @_;
  711:     my ($retrieved,$output,$upass);
  712: 
  713:     $username= &LONCAPA::clean_username($username);
  714:     $domain = &LONCAPA::clean_domain($domain);
  715:     my $uhome = &Apache::lonnet::homeserver($username,$domain);
  716: 
  717:     if ($uhome ne 'no_host') {
  718:         $output = &invalid_state('existinguser',$domdesc,
  719:                                  $contact_name,$contact_email);
  720:         return $output;
  721:     }
  722:     ($retrieved,$output,$upass) = &process_credentials($env{'form.logtoken'},
  723:                                                        $env{'form.serverid'});
  724:     if ($retrieved eq 'ok') {
  725:         my $primlibserv = &Apache::lonnet::domain($domain,'primary');
  726:         my $authok;
  727:         my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
  728:         if ((($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) || ($domdefaults{'auth_def'} eq 'localauth')) {
  729:             my $checkdefauth = 1;
  730:             $authok = 
  731:                 &Apache::lonnet::reply("encrypt:auth:$domain:$username:$upass:$checkdefauth",$primlibserv);
  732:         } else {
  733:             $authok = 'non_authorized';
  734:         }
  735:         if ($authok eq 'authorized') {
  736:             $output = &username_check($username,$domain,$domdesc,$courseid,$lonhost,
  737:                                       $contact_email,$contact_name);
  738:         } else {
  739:             $output = '<div class="LC_warning">'
  740:                      .&mt('Username and/or password could not be authenticated.')
  741:                      .'</div>'
  742:                      .&mt('Please check the username and password.'); 
  743:         }
  744:     }
  745:     return $output;
  746: }
  747: 
  748: sub username_check {
  749:     my ($username,$domain,$domdesc,$courseid,$lonhost,$contact_email,$contact_name,
  750:         $sso_logout) = @_;
  751:     my (%rulematch,%inst_results,$newuser,$checkfail,$rowcount,$editable,$output,$msg,
  752:         %alerts,%curr_rules,%got_rules);
  753:     $newuser = 1;
  754:     my $checkhash;
  755:     my $checks = { 'username' => 1 };
  756:     $checkhash->{$username.':'.$domain} = { 'newuser' => $newuser };
  757:     &Apache::loncommon::user_rule_check($checkhash,$checks,\%alerts,\%rulematch,
  758:                                         \%inst_results,\%curr_rules,\%got_rules);
  759:     if (ref($alerts{'username'}) eq 'HASH') {
  760:         if (ref($alerts{'username'}{$domain}) eq 'HASH') {
  761:             if ($alerts{'username'}{$domain}{$username}) {
  762:                 if (ref($curr_rules{$domain}) eq 'HASH') {
  763:                     $output =
  764:                         &Apache::loncommon::instrule_disallow_msg('username',$domdesc,1,
  765:                                                                   'selfcreate').
  766:                         &Apache::loncommon::user_rule_formats($domain,$domdesc,
  767:                                 $curr_rules{$domain}{'username'},'username');
  768:                 }
  769:                 $checkfail = 'username';
  770:             }
  771:         }
  772:     }
  773:     if (!$checkfail) {
  774:         $output = '<form method="post" action="/adm/createaccount">';
  775:         (my $datatable,$rowcount,$editable) = 
  776:             &Apache::loncreateuser::personal_data_display($username,$domain,1,'selfcreate',
  777:                                                          $inst_results{$username.':'.$domain});
  778:         if ($rowcount > 0) {
  779:             $output .= $datatable;
  780:         }
  781:         $output .=  '<br /><br /><input type="hidden" name="uname" value="'.$username.'" />'."\n".
  782:                     '<input type="hidden" name="udom" value="'.$domain.'" />'."\n".
  783:                     '<input type="hidden" name="phase" value="username_activation" />';
  784:         my $now = time;
  785:         my %info = ('ip'         => $ENV{'REMOTE_ADDR'},
  786:                     'time'       => $now,
  787:                     'domain'     => $domain,
  788:                     'username'   => $username);
  789:         my $authtoken = &Apache::lonnet::tmpput(\%info,$lonhost);
  790:         if ($authtoken !~ /^error/ && $authtoken ne 'no_such_host') {
  791:             $output .= '<input type="hidden" name="authtoken" value="'.&HTML::Entities::encode($authtoken,'&<>"').'" />';
  792:         } else {
  793:             $output = &mt('An error occurred when storing a token').'<br />'.
  794:                       &mt('You will not be able to proceed to the next stage of account creation').
  795:                       &linkto_email_help($contact_email,$domdesc);
  796:             $checkfail = 'authtoken';
  797:         }
  798:     }
  799:     if ($checkfail) { 
  800:         $msg = '<h4>'.&mt('Account creation unavailable').'</h4>';
  801:         if ($checkfail eq 'username') {
  802:             $msg .= '<span class="LC_warning">'.
  803:                      &mt('A LON-CAPA account may not be created with the username you use.').
  804:                      '</span><br /><br />'.$output;
  805:         } elsif ($checkfail eq 'authtoken') {
  806:             $msg .= '<span class="LC_error">'.&mt('Error creating token.').'</span>'.
  807:                     '<br />'.$output;
  808:         }
  809:         $msg .= &mt('Please contact the [_1] ([_2]) for assistance.',
  810:                 $contact_name,$contact_email).'<br /><hr />'.
  811:                 $sso_logout;
  812:         &Apache::lonnet::logthis("ERROR: failure type of '$checkfail' when performing username check to create account for authenticated user: $username, in domain $domain");
  813:     } else {
  814:         if ($courseid ne '') {
  815:             $output .= '<input type="hidden" name="courseid" value="'.$courseid.'" />';
  816:         }
  817:         $output .= '<input type="submit" name="newaccount" value="'.
  818:                    &mt('Create LON-CAPA account').'" /></form>';
  819:         if ($rowcount) {
  820:             if ($editable) {
  821:                 $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 />';
  822:             } else {
  823:                  $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 />';
  824:             }
  825:         } else {
  826:             $msg = '<br />'.&mt('Confirm that you wish to create an account.');
  827:         }
  828:         $msg .= $output;
  829:     }
  830:     return $msg;
  831: }
  832: 
  833: sub username_activation {
  834:     my ($r,$username,$domain,$domdesc,$lonhost,$courseid) = @_;
  835:     my $output;
  836:     my $error     = '<span class="LC_error">'.&mt('Error:').' ';
  837:     my $end       = '</span><br /><br />';
  838:     my $rtnlink   = '<a href="javascript:history.back();" />'.
  839:                     &mt('Return to previous page').'</a>'.
  840:                     &Apache::loncommon::end_page();
  841:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
  842:     my %data = &Apache::lonnet::tmpget($env{'form.authtoken'});
  843:     my $now = time;
  844:     my $earlyout;
  845:     my $timeout = 300;
  846:     if (keys(%data) == 0) {
  847:         $output = &mt('Sorry, your authentication has expired.');
  848:         $earlyout = 'fail';
  849:     }
  850:     if (($data{'time'} !~ /^\d+$/) ||
  851:         ($data{'domain'} ne $domain) || 
  852:         ($data{'username'} ne $username)) {
  853:         $earlyout = 'fail';
  854:         $output = &mt('The credentials you provided could not be verified.');   
  855:     } elsif ($now - $data{'time'} > $timeout) {
  856:         $earlyout = 'fail';
  857:         $output = &mt('Sorry, your authentication has expired.');
  858:     }
  859:     if ($earlyout ne '') {
  860:         $output .= '<br />'.&mt('Please [_1]start again[_2].','<a href="/adm/createaccount">','</a>');
  861:         return($earlyout,$output);
  862:     }
  863:     if ((($domdefaults{'auth_def'} =~/^krb(4|5)$/) && 
  864:          ($domdefaults{'auth_arg_def'} ne '')) || 
  865:         ($domdefaults{'auth_def'} eq 'localauth')) {
  866:         if ($env{'form.cid'} ne '') {
  867:             my ($result,$userchkmsg) = &check_id($username,$domain,$domdesc);
  868:             if ($result eq 'fail') {
  869:                 $output = $error.&mt('Invalid ID format').$end.
  870:                           $userchkmsg.$rtnlink;
  871:                 return ('fail',$output);
  872:             }
  873:         }
  874:         # Call modifyuser
  875:         my $result =
  876:             &Apache::lonnet::modifyuser($domain,$username,$env{'form.cid'},
  877:                           $domdefaults{'auth_def'},
  878:                           $domdefaults{'auth_arg_def'},$env{'form.cfirstname'},
  879:                           $env{'form.cmiddlename'},$env{'form.clastname'},
  880:                           $env{'form.cgeneration'},undef,undef,
  881:                           $env{'form.cpermanentemail'});
  882:         if ($result eq 'ok') {
  883:             my $delete = &Apache::lonnet::tmpdel($env{'form.authtoken'});
  884:             $output = &mt('A LON-CAPA account has been created for username: [_1] in domain: [_2].',$username,$domain);
  885:             my %form = &start_session($r,$username,$domain,$lonhost,$courseid);
  886:             my $nostart = 1;
  887:             return ('ok',$output,$nostart);
  888:         } else {
  889:             $output = &mt('Account creation failed for username: [_1] in domain: [_2].',$username,$domain).'<br /><span class="LC_error">'.&mt('Error: [_1]',$result).'</span>';
  890:             return ('fail',$output);
  891:         }
  892:     } else {
  893:         $output = &mt('User account creation is not available for the current default authentication type.')."\n";
  894:         return('fail',$output);
  895:     }
  896: }
  897: 
  898: sub check_id {
  899:     my ($username,$domain,$domdesc) = @_;
  900:     # Check ID format
  901:     my (%alerts,%rulematch,%inst_results,%curr_rules,%checkhash);
  902:     my %checks = ('id' => 1);
  903:     %{$checkhash{$username.':'.$domain}} = (
  904:                                             'newuser' => 1,
  905:                                             'id' => $env{'form.cid'},
  906:                                            );
  907:     &Apache::loncommon::user_rule_check(\%checkhash,\%checks,\%alerts,
  908:                                         \%rulematch,\%inst_results,\%curr_rules);
  909:     if (ref($alerts{'id'}) eq 'HASH') {
  910:         if (ref($alerts{'id'}{$domain}) eq 'HASH') {
  911:             if ($alerts{'id'}{$domain}{$env{'form.cid'}}) {
  912:                 my $userchkmsg;
  913:                 if (ref($curr_rules{$domain}) eq 'HASH') {
  914:                     $userchkmsg  =
  915:                         &Apache::loncommon::instrule_disallow_msg('id',
  916:                                                            $domdesc,1).
  917:                         &Apache::loncommon::user_rule_formats($domain,
  918:                               $domdesc,$curr_rules{$domain}{'id'},'id');
  919:                 }
  920:                 return ('fail',$userchkmsg);
  921:             }
  922:         }
  923:     }
  924:     return; 
  925: }
  926: 
  927: sub invalid_state {
  928:     my ($error,$domdesc,$contact_name,$contact_email,$msgtext) = @_;
  929:     my $msg = '<h3>'.&mt('Account creation unavailable').'</h3><span class="LC_error">';
  930:     if ($error eq 'baduseremail') {
  931:         $msg = &mt('The e-mail address you provided does not appear to be a valid address.');
  932:     } elsif ($error eq 'existinguser') {
  933:         $msg = &mt('The e-mail address you provided is already in use as a username in LON-CAPA at this institution.');
  934:     } elsif ($error eq 'userrules') {
  935:         $msg = &mt('Username rules for this LON-CAPA at this institution do not allow the e-mail address you provided to be used as a username.');
  936:     } elsif ($error eq 'userformat') {
  937:         $msg = &mt('The e-mail address you provided may not be used as a username at this LON-CAPA institution.');
  938:     } elsif ($error eq 'captcha') {
  939:         $msg = &mt('Validation of the code your entered failed.');
  940:     } elsif ($error eq 'noemails') {
  941:         $msg = &mt('Creation of a new user account using an e-mail address as username is not permitted at this LON-CAPA institution.');
  942:     }
  943:     $msg .= '</span>';
  944:     if ($msgtext) {
  945:         $msg .= '<br />'.$msgtext;
  946:     }
  947:     $msg .= &linkto_email_help($contact_email,$domdesc);
  948:     return $msg;
  949: }
  950: 
  951: sub linkto_email_help {
  952:     my ($contact_email,$domdesc) = @_;
  953:     my $msg;
  954:     if ($contact_email ne '') {
  955:         my $escuri = &HTML::Entities::encode('/adm/createaccount','&<>"');
  956:         $msg .= '<br />'.&mt('You may wish to contact the [_1]LON-CAPA helpdesk[_2] for [_3].','<a href="/adm/helpdesk?origurl='.$escuri.'">','</a>',$domdesc).'<br />';
  957:     } else {
  958:         $msg .= '<br />'.&mt('You may wish to send an e-mail to the server administrator: [_1] for [_2].',$Apache::lonnet::perlvar{'AdminEmail'},$domdesc).'<br />';
  959:     }
  960:     return $msg;
  961: }
  962: 
  963: sub create_captcha {
  964:     my ($output_dir,$db_dir) = @_;
  965:     my %captcha_params = &captcha_settings();
  966:     my $captcha = Authen::Captcha->new(
  967:                                        output_folder => $captcha_params{'output_dir'},
  968:                                        data_folder   => $captcha_params{'db_dir'},
  969:                                       );
  970:     my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
  971:     my $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
  972:                  &mt('Type in the letters/numbers shown below').'&nbsp;'.
  973:                  '<input type="text" size="5" name="code" value="" /><br />'.
  974:                  '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png">';
  975:     return $output;
  976: }
  977: 
  978: sub captcha_settings {
  979:     my %captcha_params = ( 
  980:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
  981:                            www_output_dir => "/captchaspool",
  982:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
  983:                            numchars       => '5',
  984:                          );
  985:     return %captcha_params;
  986: }
  987: 
  988: sub getkeys {
  989:     my ($lkey,$ukey) = @_;
  990:     my $lextkey=hex($lkey);
  991:     if ($lextkey>2147483647) { $lextkey-=4294967296; }
  992: 
  993:     my $uextkey=hex($ukey);
  994:     if ($uextkey>2147483647) { $uextkey-=4294967296; }
  995:     return ($lextkey,$uextkey);
  996: }
  997: 
  998: sub serverform {
  999:     my ($logtoken,$lonhost,$mailtoken,$courseid) = @_;
 1000:     my $output .= <<ENDSERVERFORM;
 1001:   <form name="server" method="post" target="_top">
 1002:    <input type="hidden" name="logtoken" value="$logtoken" />
 1003:    <input type="hidden" name="token" value="$mailtoken" />
 1004:    <input type="hidden" name="serverid" value="$lonhost" />
 1005:    <input type="hidden" name="uname" value="" />
 1006:    <input type="hidden" name="upass" value="" />
 1007:    <input type="hidden" name="phase" value="username_validation" />
 1008:    <input type="hidden" name="courseid" value="$courseid" />
 1009:   </form>
 1010: ENDSERVERFORM
 1011:     return $output;
 1012: }
 1013: 
 1014: sub process_credentials {
 1015:     my ($logtoken,$lonhost) = @_;
 1016:     my $tmpinfo=Apache::lonnet::reply('tmpget:'.$logtoken,$lonhost);
 1017:     my ($retrieved,$output,$upass);
 1018:     if (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost')) {
 1019:         $output = &mt('Information needed to verify your login information is missing, inaccessible or expired.')
 1020:                  .'<br />'.&mt('You may need to reload the previous page to obtain a new token.');
 1021:         return ($retrieved,$output,$upass); 
 1022:     } else {
 1023:         my $reply = &Apache::lonnet::reply('tmpdel:'.$logtoken,$lonhost);
 1024:         if ($reply eq 'ok') {
 1025:             $retrieved = 'ok';
 1026:         } else {
 1027:             $output = &mt('Session could not be opened.');
 1028:         }
 1029:     }
 1030:     my ($key,$caller)=split(/&/,$tmpinfo);
 1031:     if ($caller eq 'createaccount') {
 1032:         $upass = &Apache::lonpreferences::des_decrypt($key,$env{'form.upass'});
 1033:     } else {
 1034:         $output = &mt('Unable to retrieve your log-in information - unexpected context');
 1035:     }
 1036:     return ($retrieved,$output,$upass);
 1037: }
 1038: 
 1039: sub guest_format_check {
 1040:     my ($useremail,$domain,$cancreate,$settings) = @_;
 1041:     my ($login,$format_match,$format_msg,@user_rules);
 1042:     if (ref($settings) eq 'HASH') {
 1043:         if (ref($settings->{'email_rule'}) eq 'ARRAY') {
 1044:             push(@user_rules,@{$settings->{'email_rule'}});
 1045:         }
 1046:     }
 1047:     if (@user_rules > 0) {
 1048:         my %rule_check = 
 1049:             &Apache::lonnet::inst_rulecheck($domain,$useremail,undef,
 1050:                                             'selfcreate',\@user_rules);
 1051:         if (keys(%rule_check) > 0) {
 1052:             foreach my $item (keys(%rule_check)) {
 1053:                 if ($rule_check{$item}) {
 1054:                     $format_match = 1;   
 1055:                     last;
 1056:                 }
 1057:             }
 1058:         }
 1059:     }
 1060:     if ($format_match) {
 1061:         ($login) = ($useremail =~ /^([^\@]+)\@/);
 1062:         $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 />';
 1063:         if (ref($cancreate) eq 'ARRAY') {
 1064:             if (grep(/^login$/,@{$cancreate})) {
 1065:                 $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 />'; 
 1066:             }
 1067:         }
 1068:     }
 1069:     return $format_msg;
 1070: }
 1071: 
 1072: sub sso_logout_frag {
 1073:     my ($r,$domain) = @_;
 1074:     my $endsessionmsg;
 1075:     if (defined($r->dir_config('lonSSOUserLogoutMessageFile_'.$domain))) {
 1076:         my $msgfile = $r->dir_config('lonSSOUserLogoutMessageFile_'.$domain);
 1077:         if (-e $msgfile) {
 1078:             open(my $fh,"<$msgfile");
 1079:             $endsessionmsg = join('',<$fh>);
 1080:             close($fh);
 1081:         }
 1082:     } elsif (defined($r->dir_config('lonSSOUserLogoutMessageFile'))) {
 1083:         my $msgfile = $r->dir_config('lonSSOUserLogoutMessageFile');
 1084:         if (-e $msgfile) {     
 1085:             open(my $fh,"<$msgfile");
 1086:             $endsessionmsg = join('',<$fh>);
 1087:             close($fh);
 1088:         }
 1089:     }
 1090:     return $endsessionmsg;
 1091: }
 1092: 
 1093: 1;

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