Annotation of loncom/interface/createaccount.pm, revision 1.19

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

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