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

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

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