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

1.1       raeburn     1: # The LearningOnline Network
                      2: # Allow visitors to create a user account with the username being either an 
1.58      raeburn     3: # institutional log-in ID (institutional authentication required - localauth,
                      4: # kerberos, or SSO) or an e-mail address. Requests to use an e-mail address as
                      5: # username may be processed automatically, or may be queued for approval.
1.1       raeburn     6: #
1.74    ! raeburn     7: # $Id: createaccount.pm,v 1.73 2017/07/26 19:45:45 raeburn Exp $
1.1       raeburn     8: #
                      9: # Copyright Michigan State University Board of Trustees
                     10: #
                     11: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                     12: #
                     13: # LON-CAPA is free software; you can redistribute it and/or modify
                     14: # it under the terms of the GNU General Public License as published by
                     15: # the Free Software Foundation; either version 2 of the License, or
                     16: # (at your option) any later version.
                     17: #
                     18: # LON-CAPA is distributed in the hope that it will be useful,
                     19: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     20: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     21: # GNU General Public License for more details.
                     22: #
                     23: # You should have received a copy of the GNU General Public License
                     24: # along with LON-CAPA; if not, write to the Free Software
                     25: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     26: #
                     27: # /home/httpd/html/adm/gpl.txt
                     28: #
                     29: # http://www.lon-capa.org/
                     30: #
                     31: #
                     32: package Apache::createaccount;
                     33: 
                     34: use strict;
                     35: use Apache::Constants qw(:common);
                     36: use Apache::lonacc;
                     37: use Apache::lonnet;
                     38: use Apache::loncommon;
1.12      raeburn    39: use Apache::lonhtmlcommon;
1.1       raeburn    40: use Apache::lonlocal;
1.3       raeburn    41: use Apache::lonauth;
1.1       raeburn    42: use Apache::resetpw;
                     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.22      raeburn    55: 
1.5       raeburn    56:     my $domain;
1.3       raeburn    57: 
1.57      raeburn    58:     my $sso_username = $r->subprocess_env->get('SSOUserUnknown');
                     59:     my $sso_domain = $r->subprocess_env->get('SSOUserDomain');
1.5       raeburn    60: 
1.56      raeburn    61:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
1.61      raeburn    62:                                             ['token','courseid','domain','type']);
1.27      raeburn    63:     &Apache::lonacc::get_posted_cgi($r);
                     64:     &Apache::lonlocal::get_language_handle($r);
                     65: 
1.5       raeburn    66:     if ($sso_username ne '' && $sso_domain ne '') {
                     67:         $domain = $sso_domain; 
1.27      raeburn    68:     } else {
1.56      raeburn    69:         ($domain, undef) = Apache::lonnet::is_course($env{'form.courseid'});
                     70:         unless ($domain) {
                     71:             if ($env{'form.phase'} =~ /^username_(activation|validation)$/) {
                     72:                 if (($env{'form.udom'} =~ /^$match_domain$/) &&
                     73:                     (&Apache::lonnet::domain($env{'form.udom'}) ne '')) {
                     74:                     $domain = $env{'form.udom'};
                     75:                 } else {
                     76:                     $domain = &Apache::lonnet::default_login_domain();
                     77:                 }
                     78:             } elsif (($env{'form.phase'} eq '') &&
                     79:                      ($env{'form.domain'} =~ /^$match_domain$/) &&
                     80:                      (&Apache::lonnet::domain($env{'form.domain'}) ne '')) {
                     81:                 $domain = $env{'form.domain'};
                     82:             } else {
                     83:                 $domain = &Apache::lonnet::default_login_domain();
                     84:             }
                     85:         }
1.5       raeburn    86:     }
1.1       raeburn    87:     my $domdesc = &Apache::lonnet::domain($domain,'description');
                     88:     my $contact_name = &mt('LON-CAPA helpdesk');
1.15      raeburn    89:     my $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};
                     90:     my $contacts =
                     91:         &Apache::loncommon::build_recipient_list(undef,'helpdeskmail',
                     92:                                                  $domain,$origmail);
                     93:     my ($contact_email) = split(',',$contacts);
1.1       raeburn    94:     my $lonhost = $r->dir_config('lonHostID');
                     95:     my $include = $r->dir_config('lonIncludes');
1.4       raeburn    96:     my $start_page;
1.3       raeburn    97: 
                     98:     my $handle = &Apache::lonnet::check_for_valid_session($r);
1.30      raeburn    99:     if (($handle ne '') && ($handle !~ /^publicuser_\d+$/)) {
1.4       raeburn   100:         $start_page =
1.3       raeburn   101:             &Apache::loncommon::start_page('Already logged in');
                    102:         my $end_page =
                    103:             &Apache::loncommon::end_page();
                    104:         $r->print($start_page."\n".'<h2>'.&mt('You are already logged in').'</h2>'.
1.58      raeburn   105:                   '<p>'.&mt('Please either [_1]continue the current session[_2] or [_3]log out[_4].',
                    106:                             '<a href="/adm/roles">','</a>','<a href="/adm/logout">','</a>').
1.6       bisitz    107:                   '</p><p><a href="/adm/loginproblems.html">'.&mt('Login problems?').'</a></p>'.$end_page);
1.20      raeburn   108:         return OK;
                    109:     }
                    110: 
1.22      raeburn   111:     my ($js,$courseid,$title);
1.48      droeschl  112:     $courseid = Apache::lonnet::is_course($env{'form.courseid'});
1.22      raeburn   113:     if ($courseid ne '') {
                    114:         $js = &catreturn_js();
                    115:         $title = 'Self-enroll in a LON-CAPA course';
                    116:     } else {
                    117:         $title = 'Create a user account in LON-CAPA';
                    118:     }
1.20      raeburn   119:     if ($env{'form.phase'} eq 'selfenroll_login') {
1.22      raeburn   120:         $title = 'Self-enroll in a LON-CAPA course';
1.4       raeburn   121:         if ($env{'form.udom'} ne '') {
                    122:             $domain = $env{'form.udom'};
                    123:         }
1.35      raeburn   124: 
                    125:         my %domconfig = 
                    126:             &Apache::lonnet::get_dom('configuration',['usercreation'],$domain);
1.73      raeburn   127:         my ($cancreate,$statustocreate) = 
1.35      raeburn   128:             &get_creation_controls($domain,$domconfig{'usercreation'});
                    129: 
1.20      raeburn   130:         my ($result,$output) =
                    131:             &username_validation($r,$env{'form.uname'},$domain,$domdesc,
                    132:                                  $contact_name,$contact_email,$courseid,
1.35      raeburn   133:                                  $lonhost,$statustocreate);
1.58      raeburn   134:         if ($result eq 'redirect') {
                    135:             $r->internal_redirect('/adm/switchserver');
                    136:             return OK;
                    137:         } elsif ($result eq 'existingaccount') {
1.20      raeburn   138:             $r->print($output);
1.22      raeburn   139:             &print_footer($r);
1.20      raeburn   140:             return OK;
                    141:         } else {
1.51      raeburn   142:             $start_page = &Apache::loncommon::start_page($title,$js); 
1.22      raeburn   143:             &print_header($r,$start_page,$courseid);
                    144:             $r->print($output);
                    145:             &print_footer($r);    
1.20      raeburn   146:             return OK;
                    147:         }
1.4       raeburn   148:     }
1.3       raeburn   149: 
1.73      raeburn   150:     my %domconfig =
1.35      raeburn   151:         &Apache::lonnet::get_dom('configuration',['usercreation'],$domain);
1.73      raeburn   152:     my ($cancreate,$statustocreate,$statusforemail,$emailusername,
1.74    ! raeburn   153:         $emailoptions,$verification,$emaildomain,$types,$usertypes,$othertitle) =
1.58      raeburn   154:         &get_creation_controls($domain,$domconfig{'usercreation'});
1.73      raeburn   155:     my ($additems,$pagetitle);
                    156:     if (ref($cancreate) eq 'ARRAY') {
                    157:         unless (($env{'form.token'}) || ($sso_username ne '') || ($env{'form.phase'}) ||
                    158:                 ($env{'form.create_with_email'})) {
                    159:             if ((grep(/^email$/,@{$cancreate})) && (ref($statusforemail) eq 'ARRAY')) {
                    160:                 my $usertype = &get_usertype($domain);
1.74    ! raeburn   161:                 if ((($usertype eq '') || (!grep(/^\Q$usertype\E$/,@{$statusforemail}))) && 
        !           162:                     (@{$statusforemail} > 0)) {
1.73      raeburn   163:                     $js .= &setelements_js($statusforemail,$types,$usertypes,$othertitle);
                    164:                     $additems = {'add_entries' => { 'onload' => "setElements();"} };
1.74    ! raeburn   165:                     if ((@{$cancreate} == 1) && (@{$statusforemail} > 0)) {
1.73      raeburn   166:                         $pagetitle = 'Select affiliation';
                    167:                     }
1.74    ! raeburn   168:                 } else {
        !           169:                     $js .= &username_js();
1.73      raeburn   170:                 }
                    171:             }
                    172:         }
                    173:     }
                    174:     $start_page = &Apache::loncommon::start_page($title,$js,$additems);
1.35      raeburn   175:     if (@{$cancreate} == 0) {
1.73      raeburn   176:         &print_header($r,$start_page,$courseid,$pagetitle);
1.14      raeburn   177:         my $output = '<h3>'.&mt('Account creation unavailable').'</h3>'.
                    178:                      '<span class="LC_warning">'.
1.73      raeburn   179:                      &mt('Creation of a new user account using an institutional log-in ID or e-mail verification is not permitted for: [_1].',$domdesc).
1.58      raeburn   180:                      '</span><br /><br />';
1.3       raeburn   181:         $r->print($output);
1.22      raeburn   182:         &print_footer($r);
1.3       raeburn   183:         return OK;
                    184:     }
                    185: 
1.5       raeburn   186:     if ($sso_username ne '') {
1.22      raeburn   187:         &print_header($r,$start_page,$courseid);
1.18      raeburn   188:         my ($msg,$sso_logout);
                    189:         $sso_logout = &sso_logout_frag($r,$domain);
1.35      raeburn   190:         if (grep(/^sso$/,@{$cancreate})) {
1.14      raeburn   191:             $msg = '<h3>'.&mt('Account creation').'</h3>'.
1.17      raeburn   192:                    &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 />';
1.65      raeburn   193:             my $shibenv;
                    194:             if (($r->dir_config('lonOtherAuthen') eq 'yes') && 
                    195:                 ($r->dir_config('lonOtherAuthenType') eq 'Shibboleth')) {
                    196:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
                    197:                     if (ref($domconfig{'usercreation'}{'cancreate'}) eq 'HASH') {
                    198:                         if (ref($domconfig{'usercreation'}{'cancreate'}{'shibenv'}) eq 'HASH') {
                    199:                             my @possfields = ('firstname','middlename','lastname','generation',
                    200:                                               'permanentemail','id');
                    201:                             $shibenv= {};
                    202:                             foreach my $key (keys(%{$domconfig{'usercreation'}{'cancreate'}{'shibenv'}})) {
                    203:                                 if ($key eq 'inststatus') {
                    204:                                     if (ref($usertypes) eq 'HASH') {
                    205:                                         if ($domconfig{'usercreation'}{'cancreate'}{'shibenv'}{$key} ne '') {
                    206:                                             if (exists($usertypes->{$domconfig{'usercreation'}{'cancreate'}{'shibenv'}{$key}})) {
                    207:                                                 $shibenv->{$key} = $domconfig{'usercreation'}{'cancreate'}{'shibenv'}{$key};
                    208:                                              }
                    209:                                         }
                    210:                                     }
                    211:                                 } elsif (grep(/^\Q$key\E/,@possfields)) {
                    212:                                     if ($domconfig{'usercreation'}{'cancreate'}{'shibenv'}{$key} ne '') {
                    213:                                         $shibenv->{$key} = $domconfig{'usercreation'}{'cancreate'}{'shibenv'}{$key};
                    214:                                     }
                    215:                                 }
                    216:                             }
                    217:                         }
                    218:                     }
                    219:                 }
                    220:             }
1.18      raeburn   221:             $msg .= &username_check($sso_username,$domain,$domdesc,$courseid, 
1.35      raeburn   222:                                     $lonhost,$contact_email,$contact_name,
1.65      raeburn   223:                                     $sso_logout,$statustocreate,$shibenv);
1.5       raeburn   224:         } else {
1.17      raeburn   225:             $msg = '<h3>'.&mt('Account creation unavailable').'</h3>'.
                    226:                    '<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   227:                    $sso_logout;
1.5       raeburn   228:         }
1.17      raeburn   229:         $r->print($msg);
1.22      raeburn   230:         &print_footer($r);
1.5       raeburn   231:         return OK;
                    232:     }
                    233: 
1.58      raeburn   234:     my ($output,$nostart,$noend,$redirect);
1.3       raeburn   235:     my $token = $env{'form.token'};
                    236:     if ($token) {
1.58      raeburn   237:         ($output,$nostart,$noend,$redirect) = 
1.3       raeburn   238:             &process_mailtoken($r,$token,$contact_name,$contact_email,$domain,
1.58      raeburn   239:                                $domdesc,$lonhost,$include,$start_page,$cancreate,
1.73      raeburn   240:                                $domconfig{'usercreation'},$types);
1.58      raeburn   241:         if ($redirect) {
                    242:             $r->internal_redirect('/adm/switchserver');
                    243:             return OK;
                    244:         } elsif ($nostart) {
1.3       raeburn   245:             if ($noend) {
                    246:                 return OK;
                    247:             } else {
                    248:                 $r->print($output);
1.22      raeburn   249:                 &print_footer($r);
1.3       raeburn   250:                 return OK;
                    251:             }
                    252:         } else {
1.22      raeburn   253:             &print_header($r,$start_page,$courseid);
1.3       raeburn   254:             $r->print($output);
1.22      raeburn   255:             &print_footer($r);
1.3       raeburn   256:             return OK;
                    257:         }
                    258:     }
1.74    ! raeburn   259:     my ($usernameset,$condition,$excluded,$hascustom);
1.73      raeburn   260:     if ((grep(/^email$/,@{$cancreate})) && (($env{'form.create_with_email'}) ||
                    261:                                             ((!$token) && ($env{'form.phase'} eq '')))) {
                    262:         my $usertype = &get_usertype($domain);
1.74    ! raeburn   263:         if ($usertype eq '') {
        !           264:             $usertype = 'default';
        !           265:         }
1.73      raeburn   266:         if (ref($verification) eq 'HASH') {
1.74    ! raeburn   267:             if ($verification->{$usertype} =~ /^(free|first)$/) {
        !           268:                 $usernameset = $verification->{$usertype};
        !           269:             }
        !           270:         }
        !           271:         if (ref($emailoptions) eq 'HASH') {
        !           272:             if ($emailoptions->{$usertype} =~ /^(inst|noninst)$/) {
        !           273:                 my $chosen = $1;
1.73      raeburn   274:                 if (ref($emaildomain) eq 'HASH') {
1.74    ! raeburn   275:                     if (ref($emaildomain->{$usertype}) eq 'HASH') {
        !           276:                         if ($chosen eq 'inst') {
        !           277:                             $condition = $emaildomain->{$usertype}->{$chosen};
        !           278:                         } else {
        !           279:                             $excluded = $emaildomain->{$usertype}->{$chosen};
        !           280:                         }
1.73      raeburn   281:                     }
                    282:                 }
1.74    ! raeburn   283:             } elsif ($emailoptions->{$usertype} eq 'custom') {
        !           284:                 $hascustom = 1;
1.73      raeburn   285:             }
                    286:         }
                    287:     }
1.3       raeburn   288:     if ($env{'form.phase'} eq 'username_activation') {
                    289:         (my $result,$output,$nostart) = 
                    290:             &username_activation($r,$env{'form.uname'},$domain,$domdesc,
1.51      raeburn   291:                                  $courseid);
1.58      raeburn   292:         if ($result eq 'redirect') {
                    293:             $r->internal_redirect('/adm/switchserver');
                    294:             return OK; 
                    295:         } elsif ($result eq 'ok') {
1.3       raeburn   296:             if ($nostart) {
                    297:                 return OK;
                    298:             }
                    299:         }
1.22      raeburn   300:         &print_header($r,$start_page,$courseid);
1.3       raeburn   301:         $r->print($output);
1.22      raeburn   302:         &print_footer($r);
1.3       raeburn   303:         return OK;
1.19      raeburn   304:     } elsif ($env{'form.phase'} eq 'username_validation') { 
                    305:         (my $result,$output) = 
                    306:             &username_validation($r,$env{'form.uname'},$domain,$domdesc,
                    307:                                  $contact_name,$contact_email,$courseid,
1.35      raeburn   308:                                  $lonhost,$statustocreate);
1.19      raeburn   309:         if ($result eq 'existingaccount') {
                    310:             $r->print($output);
1.22      raeburn   311:             &print_footer($r);
1.19      raeburn   312:             return OK;
                    313:         } else {
1.22      raeburn   314:             &print_header($r,$start_page,$courseid);
1.19      raeburn   315:         }
                    316:     } elsif ($env{'form.create_with_email'}) {
1.22      raeburn   317:         &print_header($r,$start_page,$courseid);
1.61      raeburn   318:         my $usertype = &get_usertype($domain);
1.74    ! raeburn   319:         if ($usertype eq '') {
        !           320:             $usertype = 'default';
        !           321:         }
1.58      raeburn   322:         $output = &process_email_request($env{'form.uname'},$domain,$domdesc,
1.35      raeburn   323:                                          $contact_name,$contact_email,$cancreate,
1.3       raeburn   324:                                          $lonhost,$domconfig{'usercreation'},
1.73      raeburn   325:                                          $emailusername,$courseid,$usertype,
1.74    ! raeburn   326:                                          $usernameset,$condition,$excluded,$hascustom);
1.3       raeburn   327:     } elsif (!$token) {
1.73      raeburn   328:         &print_header($r,$start_page,$courseid,$pagetitle);
1.1       raeburn   329:         my $now=time;
1.68      raeburn   330:         if ((grep(/^login$/,@{$cancreate})) && (!grep(/^email$/,@{$cancreate}))) {
1.58      raeburn   331:             if (open(my $jsh,"<$include/londes.js")) {
                    332:                 while(my $line = <$jsh>) {
                    333:                     $r->print($line);
                    334:                 }
                    335:                 close($jsh);
                    336:                 $r->print(&javascript_setforms($now));
                    337:             }
1.1       raeburn   338:         }
1.64      raeburn   339:         if (grep(/^email$/,@{$cancreate})) {
1.74    ! raeburn   340:             $r->print(&javascript_validmail($condition));
1.12      raeburn   341:         }
1.61      raeburn   342:         my $usertype = &get_usertype($domain);
1.58      raeburn   343:         $output = &print_username_form($r,$domain,$domdesc,$cancreate,$now,$lonhost,
1.73      raeburn   344:                                        $include,$courseid,$emailusername,
                    345:                                        $statusforemail,$usernameset,$condition,
1.74    ! raeburn   346:                                        $excluded,$usertype,$types,$usertypes,$othertitle);
1.1       raeburn   347:     }
                    348:     $r->print($output);
1.22      raeburn   349:     &print_footer($r);
1.1       raeburn   350:     return OK;
                    351: }
                    352: 
1.3       raeburn   353: sub print_header {
1.73      raeburn   354:     my ($r,$start_page,$courseid,$pagetitle) = @_;
1.3       raeburn   355:     $r->print($start_page);
                    356:     &Apache::lonhtmlcommon::clear_breadcrumbs();
1.73      raeburn   357:     my $url = '/adm/createaccount';
                    358:     if ($pagetitle eq '') {
                    359:         $pagetitle = 'New username';
                    360:     }
1.22      raeburn   361:     if ($courseid ne '') {
                    362:         my %coursehash = &Apache::lonnet::coursedescription($courseid);
                    363:         &selfenroll_crumbs($r,$courseid,$coursehash{'description'});
                    364:     }
1.73      raeburn   365:     if ($env{'form.reportedtype'}) {
                    366:         &Apache::lonhtmlcommon::add_breadcrumb
                    367:         ({href=>$url,
                    368:           text=>"Select affiliation"});
                    369:     }
1.3       raeburn   370:     &Apache::lonhtmlcommon::add_breadcrumb
1.73      raeburn   371:     ({href=>$url,
                    372:       text=>$pagetitle});
1.3       raeburn   373:     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Create account'));
                    374:     return;
                    375: }
                    376: 
1.22      raeburn   377: sub print_footer {
                    378:     my ($r) = @_;
                    379:     if ($env{'form.courseid'} ne '') {
                    380:         $r->print('<form name="backupcrumbs" method="post" action="">'.
                    381:                   &Apache::lonhtmlcommon::echo_form_input(['backto','logtoken',
                    382:                       'token','serverid','uname','upass','phase','create_with_email',
1.72      raeburn   383:                       'code','crypt','cfirstname','clastname','g-recaptcha-response',
1.59      raeburn   384:                       'recaptcha_challenge_field','recaptcha_response_field',
1.23      raeburn   385:                       'cmiddlename','cgeneration','cpermanentemail','cid']).
1.22      raeburn   386:                   '</form>');
                    387:     }
                    388:     $r->print(&Apache::loncommon::end_page());
                    389: }
                    390: 
1.61      raeburn   391: sub get_usertype {
                    392:     my ($domain) = @_;
1.73      raeburn   393:     my $usertype;
1.61      raeburn   394:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($domain);
                    395:     if (ref($types) eq 'ARRAY') {
                    396:         push(@{$types},'default');
                    397:         my $posstype = $env{'form.type'};
                    398:         $posstype =~ s/^\s+|\s$//g;
                    399:         if (grep(/^\Q$posstype\E$/,@{$types})) {
                    400:             $usertype = $posstype;
                    401:         }
                    402:     }
                    403:     return $usertype;
                    404: }
                    405: 
1.22      raeburn   406: sub selfenroll_crumbs {
                    407:     my ($r,$courseid,$desc) = @_;
                    408:     &Apache::lonhtmlcommon::add_breadcrumb
                    409:          ({href=>"javascript:ToCatalog('backupcrumbs','')",
1.37      bisitz    410:            text=>"Course/Community Catalog"});
1.22      raeburn   411:     if ($env{'form.coursenum'} ne '') {
                    412:         &Apache::lonhtmlcommon::add_breadcrumb
                    413:           ({href=>"javascript:ToCatalog('backupcrumbs','details')",
                    414:             text=>"Course details"});
                    415:     }
                    416:     my $last_crumb;
                    417:     if ($desc ne '') {
1.62      raeburn   418:         $last_crumb = &mt("Self-enroll in [_1]","'$desc'");
1.22      raeburn   419:     } else {
                    420:         $last_crumb = &mt('Self-enroll');
                    421:     }
                    422:     &Apache::lonhtmlcommon::add_breadcrumb
                    423:                    ({href=>"javascript:ToSelfenroll('backupcrumbs')",
                    424:                      text=>$last_crumb,
                    425:                      no_mt=>"1"});
                    426:     return;
                    427: }
                    428: 
1.1       raeburn   429: sub javascript_setforms {
1.74    ! raeburn   430:     my ($now,$emailusername,$captcha,$usertype,$recaptchaversion,$usernameset,$condition,$excluded) =  @_;
1.61      raeburn   431:     my ($setuserinfo,@required,$requiredchk);
1.58      raeburn   432:     if (ref($emailusername) eq 'HASH') {
1.61      raeburn   433:         if (ref($emailusername->{$usertype}) eq 'HASH') {  
                    434:             foreach my $key (sort(keys(%{$emailusername->{$usertype}}))) {
                    435:                 if ($emailusername->{$usertype}{$key} eq 'required') {
                    436:                     push(@required,$key); 
                    437:                 }
                    438:                 $setuserinfo .= '                    server.elements.'.$key.'.value=client.elements.'.$key.'.value;'."\n";
                    439:             }
                    440:             $setuserinfo .= '                    server.elements.type.value=client.elements.type.value;'."\n"; 
1.58      raeburn   441:         }
1.59      raeburn   442:         if ($captcha eq 'original') {
1.61      raeburn   443:             $setuserinfo .= '                    server.elements.code.value=client.elements.code.value;'."\n".
                    444:                             '                    server.elements.crypt.value=client.elements.crypt.value;'."\n";
1.59      raeburn   445:         } elsif ($captcha eq 'recaptcha') {
1.72      raeburn   446:             if ($recaptchaversion ne '2') {
                    447:                 $setuserinfo .=
1.61      raeburn   448:                 '                    server.elements.recaptcha_challenge_field.value=client.elements.recaptcha_challenge_field.value;'."\n".
                    449:                 '                    server.elements.recaptcha_response_field.value=client.elements.recaptcha_response_field.value;'."\n";
1.72      raeburn   450:             }
1.59      raeburn   451:         }
1.74    ! raeburn   452:         if ($usernameset eq 'free') {
1.73      raeburn   453:             $setuserinfo .=
                    454:                 '                    server.elements.username.value=client.elements.username.value;'."\n";
                    455:         }
1.58      raeburn   456:     }
1.61      raeburn   457:     if (@required) {
                    458:         my $missprompt = &mt('One or more required fields are currently blank.');
1.70      damieng   459:         &js_escape(\$missprompt);
1.61      raeburn   460:         my $reqstr = join("','",@required);
                    461:         $requiredchk = <<"ENDCHK";
                    462:                 var requiredfields = new Array('$reqstr');
                    463:                 missing = 0; 
                    464:                 for (var i=0; i<requiredfields.length; i++) {
                    465:                     try {
                    466:                         eval("client.elements."+requiredfields[i]+".value");
                    467:                     }
                    468:                     catch(err) {
                    469:                         continue;
                    470:                     }
                    471:                     if (eval("client.elements."+requiredfields[i]+".value") == '') {
                    472:                         missing ++;
                    473:                     }
                    474:                 }
                    475:                 if (missing > 0) {
                    476:                     alert("$missprompt");
                    477:                     return false;
                    478:                 }
                    479: 
                    480: ENDCHK
                    481:     }
1.1       raeburn   482:     my $js = <<ENDSCRIPT;
1.58      raeburn   483: <script type="text/javascript">
                    484: // <![CDATA[
                    485:     function send(one,two,context) {
                    486:         var server;
                    487:         var client;
                    488:         if (document.forms[one]) {
                    489:             server = document.forms[one];
                    490:             if (document.forms[two]) {
                    491:                 client = document.forms[two];
1.61      raeburn   492: $requiredchk
1.58      raeburn   493:                 server.elements.uname.value = client.elements.uname.value;
                    494:                 server.elements.udom.value = client.elements.udom.value;
1.1       raeburn   495: 
1.58      raeburn   496:                 uextkey=client.elements.uextkey.value;
                    497:                 lextkey=client.elements.lextkey.value;
                    498:                 initkeys();
                    499:                 server.elements.upass.value
1.71      raeburn   500:                     = getCrypted(client.elements.upass$now.value);
1.58      raeburn   501:                 client.elements.uname.value='';
                    502:                 client.elements.upass$now.value='';
1.60      raeburn   503:                 if (context == 'email') {
1.61      raeburn   504: $setuserinfo
1.60      raeburn   505:                     client.elements.upasscheck$now.value='';
                    506:                 }
1.58      raeburn   507:                 server.submit();
                    508:             }
                    509:         }
1.1       raeburn   510:         return false;
                    511:     }
1.71      raeburn   512: 
1.58      raeburn   513: // ]]>
                    514: </script>
1.1       raeburn   515: ENDSCRIPT
1.72      raeburn   516:     if (($captcha eq 'recaptcha') && ($recaptchaversion eq '2')) {
                    517:         $js .= "\n".'<script src="https://www.google.com/recaptcha/api.js"></script>'."\n";
                    518:     }
1.1       raeburn   519:     return $js;
                    520: }
                    521: 
                    522: sub javascript_checkpass {
1.58      raeburn   523:     my ($now,$context) = @_;
1.7       bisitz    524:     my $nopass = &mt('You must enter a password.');
1.70      damieng   525:     my $mismatchpass = &mt('The passwords you entered did not match.')."\n".
1.1       raeburn   526:                        &mt('Please try again.'); 
1.70      damieng   527:     &js_escape(\$nopass);
                    528:     &js_escape(\$mismatchpass);
1.1       raeburn   529:     my $js = <<"ENDSCRIPT";
1.58      raeburn   530: <script type="text/javascript">
                    531: // <![CDATA[
                    532:     function checkpass(one,two) {
                    533:         var client;
                    534:         if (document.forms[two]) {
                    535:             client = document.forms[two]; 
                    536:             var upass = client.elements.upass$now.value;
                    537:             var upasscheck = client.elements.upasscheck$now.value;
                    538:             if (upass == '') {
                    539:                 alert("$nopass");
                    540:                 return false;
                    541:             }
                    542:             if (upass == upasscheck) {
                    543:                 client.elements.upasscheck$now.value='';
                    544:                 if (validate_email(client)) {
                    545:                     send(one,two,'$context');
                    546:                 } 
                    547:                 return false;
                    548:             } else {
                    549:                 alert("$mismatchpass");
                    550:                 return false;
                    551:             }
1.32      raeburn   552:         }
1.58      raeburn   553:         return false; 
1.1       raeburn   554:     }
1.58      raeburn   555: // ]]>
1.1       raeburn   556: </script>
                    557: ENDSCRIPT
                    558:     return $js;
                    559: }
                    560: 
1.12      raeburn   561: sub javascript_validmail {
1.74    ! raeburn   562:     my ($condition) = @_;
1.70      damieng   563:     my %js_lt = &Apache::lonlocal::texthash (
1.12      raeburn   564:                email => 'The e-mail address you entered',
                    565:                notv  => 'is not a valid e-mail address',
1.74    ! raeburn   566:                avae  => 'A valid e-mail address is not formed when the value you entered',
        !           567:                isco  => 'is combined with the required domain',
1.12      raeburn   568:     );
                    569:     my $output =  "\n".'<script type="text/javascript">'."\n".
1.58      raeburn   570:                   '// <![CDATA['."\n".
1.12      raeburn   571:                   &Apache::lonhtmlcommon::javascript_valid_email()."\n";
1.70      damieng   572:     &js_escape(\%js_lt);
1.12      raeburn   573:     $output .= <<"ENDSCRIPT";
1.58      raeburn   574: function validate_email(client) {
                    575:     field = client.uname;
1.74    ! raeburn   576:     var condition = '$condition';
        !           577:     if (validmail(field,condition) == false) {
        !           578:         if ((condition != undefined) && (condition != '')) {
        !           579:             alert("$js_lt{'avae'}: "+field.value+" $js_lt{'isco'}: "+condition);
        !           580:         } else {
        !           581:             alert("$js_lt{'email'}: "+field.value+" $js_lt{'notv'}.");
        !           582:         }
1.12      raeburn   583:         return false;
                    584:     }
                    585:     return true;
                    586: }
                    587: ENDSCRIPT
1.58      raeburn   588:     $output .= "\n".'// ]]>'."\n".'</script>'."\n";
1.12      raeburn   589:     return $output;
                    590: }
                    591: 
1.1       raeburn   592: sub print_username_form {
1.68      raeburn   593:     my ($r,$domain,$domdesc,$cancreate,$now,$lonhost,$include,$courseid,$emailusername,
1.74    ! raeburn   594:         $statusforemail,$usernameset,$condition,$excluded,$usertype,$types,$usertypes,
1.73      raeburn   595:         $othertitle) = @_;
1.59      raeburn   596:     my %lt = &Apache::lonlocal::texthash (
                    597:                                          crac => 'Create account with a username provided by this institution',
                    598:                                          clca => 'Create LON-CAPA account',
                    599:                                          type => 'Type in your log-in ID and password to find out.',
                    600:                                          plse => 'Please provide a password for your new account.',
                    601:                                          info => 'Please provide user information and a password for your new account.',
                    602:                                          yopw => 'Your password will be encrypted when sent (and stored).',
1.73      raeburn   603:                                          crae => 'Create account using e-mail address verification',
1.59      raeburn   604:                                          );
1.1       raeburn   605:     my $output;
1.5       raeburn   606:     if (ref($cancreate) eq 'ARRAY') {
                    607:         if (grep(/^login$/,@{$cancreate})) {
                    608:             my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                    609:             if ((($domdefaults{'auth_def'} =~/^krb/) && ($domdefaults{'auth_arg_def'} ne '')) || ($domdefaults{'auth_def'} eq 'localauth')) {
1.59      raeburn   610:                 $output = '<div class="LC_left_float"><h3>'.$lt{'crac'}.'</h3>';
                    611:                 $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 />').
1.58      raeburn   612:                            '<br /><br />'.
1.59      raeburn   613:                            $lt{'type'}.
1.58      raeburn   614:                            '<br /><br />';
1.59      raeburn   615:                 $output .= &login_box($now,$lonhost,$courseid,$lt{'clca'},
1.22      raeburn   616:                                       $domain,'createaccount').'</div>';
1.5       raeburn   617:             }
                    618:         }
1.64      raeburn   619:         if (grep(/^email$/,@{$cancreate})) {
1.73      raeburn   620:             $output .= '<div class="LC_left_float"><h3>'.$lt{'crae'}.'</h3>';
                    621:             if ($usertype ne '') {
1.74    ! raeburn   622:                 if ((ref($statusforemail) eq 'ARRAY') && (@{$statusforemail} > 0)) {
1.73      raeburn   623:                     unless (grep(/^\Q$usertype\E$/,@{$statusforemail})) {
                    624:                         undef($usertype);
                    625:                     }
1.74    ! raeburn   626:                 } elsif ($usertype ne 'default') {
        !           627:                     undef($usertype);
1.73      raeburn   628:                 }
                    629:             }
                    630:             if (($usertype eq '') && (ref($statusforemail) eq 'ARRAY') && 
1.74    ! raeburn   631:                 (@{$statusforemail} > 0) && (ref($types) eq 'ARRAY') && (@{$types} > 0)) {
1.73      raeburn   632:                 my @posstypes = @{$types};
                    633:                 unless (grep(/^default$/,@posstypes)) {
                    634:                     push(@posstypes,'default');
                    635:                 }
                    636:                 $output .= '<p>'.&mt('Choose your affiliation at [_1]',$domdesc).'</p>'."\n".
                    637:                            '<form name="reportstatus" id="LC_reportstatus" action="" method="post" '.
                    638:                            'onsubmit="return checkVerification();"><p>';
                    639:                 foreach my $type (@posstypes) {
                    640:                     my $name;
                    641:                     if ($type eq 'default') {
                    642:                         $name = $othertitle;
                    643:                     } else {
                    644:                         $name = $type;
                    645:                         if (ref($usertypes) eq 'HASH') {
                    646:                             if (exists($usertypes->{$type})) {
                    647:                                 $name = $usertypes->{$type};
                    648:                             }
                    649:                         }
                    650:                     }
                    651:                     $output .= '<label><input type="radio" name="type" value="'.$type.'" />'.
                    652:                                $name.'</label>'.('&nbsp;'x2);
                    653:                 }
                    654:                 if ($env{'form.courseid'} =~ /^$match_domain\_$match_courseid$/) {
                    655:                     $output .= "\n".'<input type="hidden" name="courseid" value="'.$env{'form.courseid'}.'" />';
                    656:                 }
                    657:                 $output .= '</p>'."\n".'<p><input type="submit" name="reportedtype" value="'.&mt('Submit').'" /></p></form>';
1.52      raeburn   658:             } else {
1.73      raeburn   659:                 my ($captchaform,$error,$captcha,$recaptchaversion) = 
                    660:                     &Apache::loncommon::captcha_display('usercreation',$lonhost);
                    661:                 if ($error) {
                    662:                     my $helpdesk = '/adm/helpdesk?origurl=%2fadm%2fcreateaccount';
                    663:                     if ($courseid ne '') {
                    664:                         $helpdesk .= '&courseid='.$courseid;
                    665:                     }
                    666:                     $output .= '<span class="LC_error">'.
                    667:                                &mt('An error occurred generating the validation code[_1] required for use of an e-mail address to request a LON-CAPA account.','<br />').
                    668:                                '</span><br /><br />'.
                    669:                                &mt('[_1]Contact the helpdesk[_2] or [_3]reload[_2] the page and try again.',
                    670:                                    '<a href="'.$helpdesk.'">','</a>','<a href="javascript:window.location.reload()">');
1.28      raeburn   671:                 } else {
1.73      raeburn   672:                     if (grep(/^login$/,@{$cancreate})) {
                    673:                         $output .= &mt('If you do not have a log-in ID at your institution, [_1]provide your e-mail address to request a LON-CAPA account.','<br />').'<br /><br />'.
                    674:                                    $lt{'plse'}.'<br />'.
                    675:                                    $lt{'yopw'}.'<br />';
                    676:                     } else {
                    677:                         my $prompt = $lt{'plse'};
                    678:                         if (ref($emailusername) eq 'HASH') {
                    679:                             if (ref($emailusername->{$usertype}) eq 'HASH') {
                    680:                                 if (keys(%{$emailusername->{$usertype}}) > 0) {
                    681:                                     $prompt = $lt{'info'};
                    682:                                 }
1.59      raeburn   683:                             }
                    684:                         }
1.73      raeburn   685:                         $output .= $prompt.'<br />'.
                    686:                                    $lt{'yopw'}.'<br />';
1.59      raeburn   687:                     }
1.74    ! raeburn   688:                     if ($usertype eq '') {
        !           689:                         $usertype = 'default';
        !           690:                     }
1.73      raeburn   691:                     $output .= &print_dataentry_form($r,$domain,$lonhost,$include,$now,$captchaform,
                    692:                                                      $courseid,$emailusername,$captcha,$usertype,
1.74    ! raeburn   693:                                                      $recaptchaversion,$usernameset,$condition,$excluded);
1.28      raeburn   694:                 }
1.5       raeburn   695:             }
1.28      raeburn   696:             $output .= '</div>';
1.3       raeburn   697:         }
1.1       raeburn   698:     }
                    699:     if ($output eq '') {
1.73      raeburn   700:         $output = &mt('Creation of a new LON-CAPA user account using an institutional log-in ID or verification by e-mail is not permitted at [_1].',$domdesc);
1.1       raeburn   701:     } else {
                    702:         $output .= '<div class="LC_clear_float_footer"></div>';
                    703:     }
                    704:     return $output;
                    705: }
                    706: 
1.20      raeburn   707: sub login_box {
                    708:     my ($now,$lonhost,$courseid,$submit_text,$domain,$context) = @_;
                    709:     my $output;
                    710:     my %titles = &Apache::lonlocal::texthash(
                    711:                                               createaccount => 'Log-in ID',
                    712:                                               selfenroll    => 'Username',
                    713:                                             );
1.58      raeburn   714:     my ($lkey,$ukey) = &Apache::loncommon::des_keys();
1.20      raeburn   715:     my ($lextkey,$uextkey) = &getkeys($lkey,$ukey);
1.41      raeburn   716:     my $logtoken=Apache::lonnet::reply('tmpput:'.$ukey.$lkey.'&createaccount:createaccount',
1.20      raeburn   717:                                        $lonhost);
                    718:     $output = &serverform($logtoken,$lonhost,undef,$courseid,$context);
1.59      raeburn   719:     my $unameform = '<input type="text" name="uname" size="20" value="" autocomplete="off" />';
                    720:     my $upassform = '<input type="password" name="upass'.$now.'" size="20" autocomplete="off" />';
1.58      raeburn   721:     $output .= '<form name="client" method="post" action="" onsubmit="return(send('."'server','client'".'));">'."\n".
1.32      raeburn   722:                &Apache::lonhtmlcommon::start_pick_box()."\n".
                    723:                &Apache::lonhtmlcommon::row_title($titles{$context},
1.31      bisitz    724:                                                  'LC_pick_box_title')."\n".
                    725:                $unameform."\n".
                    726:                &Apache::lonhtmlcommon::row_closure(1)."\n".
                    727:                &Apache::lonhtmlcommon::row_title(&mt('Password'),
                    728:                                                 'LC_pick_box_title')."\n".
                    729:                $upassform;
1.20      raeburn   730:     if ($context eq 'selfenroll') {
1.32      raeburn   731:         my $udomform = '<input type="text" name="udom" size="10" value="'.
1.20      raeburn   732:                         $domain.'" />';
1.31      bisitz    733:         $output .= &Apache::lonhtmlcommon::row_closure(1)."\n".
                    734:                    &Apache::lonhtmlcommon::row_title(&mt('Domain'),
1.20      raeburn   735:                                                      'LC_pick_box_title')."\n".
1.31      bisitz    736:                    $udomform."\n";
1.32      raeburn   737:     } else {
                    738:         $output .= '<input type="hidden" name="udom" value="'.$domain.'" />';
1.20      raeburn   739:     }
1.32      raeburn   740:     $output .= &Apache::lonhtmlcommon::row_closure(1).
1.31      bisitz    741:                &Apache::lonhtmlcommon::row_title().
1.32      raeburn   742:                '<br /><input type="submit" name="username_validation" value="'.
                    743:                $submit_text.'" />'."\n";
                    744:     if ($context eq 'selfenroll') {
                    745:         $output .= '<br /><br /><table width="100%"><tr><td align="right">'.
                    746:                    '<span class="LC_fontsize_medium">'.
                    747:                    '<a href="/adm/resetpw">'.&mt('Forgot password?').'</a>'.
                    748:                    '</span></td></tr></table>'."\n";
                    749:     }
                    750:     $output .= &Apache::lonhtmlcommon::row_closure(1)."\n".
                    751:                &Apache::lonhtmlcommon::end_pick_box().'<br />'."\n";
1.34      bisitz    752:     $output .= '<input type="hidden" name="lextkey" value="'.$lextkey.'" />'."\n".
                    753:                '<input type="hidden" name="uextkey" value="'.$uextkey.'" />'."\n".
1.22      raeburn   754:                '</form>';
1.20      raeburn   755:     return $output;
                    756: }
                    757: 
1.1       raeburn   758: sub process_email_request {
                    759:     my ($useremail,$domain,$domdesc,$contact_name,$contact_email,$cancreate,
1.73      raeburn   760:         $server,$settings,$emailusername,$courseid,$usertype,$usernameset,
1.74    ! raeburn   761:         $condition,$excluded,$hascustom) = @_;
1.73      raeburn   762:     my ($output,$uname);
1.5       raeburn   763:     if (ref($cancreate) eq 'ARRAY') {
1.64      raeburn   764:         if (!grep(/^email$/,@{$cancreate})) {
1.5       raeburn   765:             $output = &invalid_state('noemails',$domdesc,
                    766:                                      $contact_name,$contact_email);
                    767:             return $output;
1.74    ! raeburn   768:         } elsif ((($condition ne '') && ($useremail !~ /^[^\@]+$/)) ||
        !           769:                  (($condition eq '') && ($useremail !~ /^[^\@]+\@[^\@]+\.[^\@\.]+$/))) {
1.5       raeburn   770:             $output = &invalid_state('baduseremail',$domdesc,
1.1       raeburn   771:                                      $contact_name,$contact_email);
                    772:             return $output;
                    773:         } else {
1.58      raeburn   774:             $useremail =~ s/^\s+|\s+$//g;
1.73      raeburn   775:             my $possuname;
1.74    ! raeburn   776:             if ($condition ne '') {
        !           777:                 if ($usernameset eq 'first') {
        !           778:                     $possuname = $useremail;
        !           779:                 }
        !           780:                 $useremail .= $condition;
        !           781:             } elsif ($excluded ne '') {
        !           782:                 if ($useremail =~ /^[^\@]+\Q$excluded\E$/) {
        !           783:                     $output = &invalid_state('userrules',$domdesc,
        !           784:                                      $contact_name,$contact_email);
        !           785:                     return $output;
        !           786:                 } 
        !           787:             }
        !           788:             if (($usernameset eq 'free') && ($env{'form.username'} ne '')) {
1.73      raeburn   789:                 $possuname = $env{'form.username'};
1.74    ! raeburn   790:             } elsif (($usernameset eq 'first') && ($condition eq '')) {
        !           791:                 if ($condition eq '') {
        !           792:                     ($possuname) = ($useremail =~ /^([^\@]+)\@/);
        !           793:                 }
        !           794:             }
        !           795:             if ($possuname ne '') {
1.73      raeburn   796:                 $possuname  =~ s/^\s+|\s+$//g;
1.74    ! raeburn   797:                 if ($possuname ne '') {
        !           798:                     $uname=&LONCAPA::clean_username($possuname);
        !           799:                     if ($uname ne $possuname) {
        !           800:                         $output = &invalid_state('badusername',$domdesc,
1.73      raeburn   801:                                                  $contact_name,$contact_email);
                    802:                         return $output;
                    803:                     }
                    804:                 }
1.74    ! raeburn   805:             }
        !           806:             if ($possuname eq '') {
1.73      raeburn   807:                 $uname=&LONCAPA::clean_username($useremail);
                    808:                 if ($useremail ne $uname) {
                    809:                     $output = &invalid_state('badusername',$domdesc,
                    810:                                              $contact_name,$contact_email);
                    811:                     return $output;
                    812:                 }
1.58      raeburn   813:             }
1.73      raeburn   814:             my $uhome = &Apache::lonnet::homeserver($uname,$domain);
1.5       raeburn   815:             if ($uhome ne 'no_host') {
                    816:                 $output = &invalid_state('existinguser',$domdesc,
                    817:                                          $contact_name,$contact_email);
1.1       raeburn   818:                 return $output;
1.5       raeburn   819:             } else {
1.52      raeburn   820:                 my ($captcha_chk,$captcha_error) = &Apache::loncommon::captcha_response('usercreation',$server);
1.5       raeburn   821:                 if ($captcha_chk != 1) {
                    822:                     $output = &invalid_state('captcha',$domdesc,$contact_name,
1.52      raeburn   823:                                              $contact_email,$captcha_error);
1.5       raeburn   824:                     return $output;
                    825:                 }
1.58      raeburn   826:                 my (%rulematch,%inst_results,%curr_rules,%got_rules,%alerts);
1.73      raeburn   827:                 &call_rulecheck($uname,$domain,\%alerts,\%rulematch,
1.58      raeburn   828:                                 \%inst_results,\%curr_rules,\%got_rules,'username');
                    829:                 if (ref($alerts{'username'}) eq 'HASH') {
                    830:                     if (ref($alerts{'username'}{$domain}) eq 'HASH') {
1.73      raeburn   831:                         if ($alerts{'username'}{$domain}{$uname}) {
1.58      raeburn   832:                             $output = &invalid_state('userrules',$domdesc,
                    833:                                                      $contact_name,$contact_email);
                    834:                             return $output;
1.1       raeburn   835:                         }
                    836:                     }
1.58      raeburn   837:                 }
1.74    ! raeburn   838:                 if ($hascustom) {
1.73      raeburn   839:                     my $format_msg = 
                    840:                         &guest_format_check($useremail,$domain,$cancreate,
1.74    ! raeburn   841:                                             $settings,$usertype);
1.73      raeburn   842:                     if ($format_msg) {
                    843:                         $output = &invalid_state('userformat',$domdesc,$contact_name,
                    844:                                                  $contact_email,$format_msg);
                    845:                         return $output;
                    846:                     }
1.1       raeburn   847:                 }
                    848:             }
                    849:         }
1.5       raeburn   850:         $output = &send_token($domain,$useremail,$server,$domdesc,$contact_name,
1.73      raeburn   851:                               $contact_email,$courseid,$emailusername,$usertype,
                    852:                               $uname);
1.1       raeburn   853:     }
                    854:     return $output;
                    855: }
                    856: 
1.23      raeburn   857: sub call_rulecheck {
                    858:     my ($uname,$udom,$alerts,$rulematch,$inst_results,$curr_rules,
                    859:         $got_rules,$tocheck) = @_;
                    860:     my ($checkhash,$checks);
                    861:     $checkhash->{$uname.':'.$udom} = { 'newuser' => 1, };
                    862:     if ($tocheck eq 'username') {
                    863:         $checks = { 'username' => 1 };
                    864:     }
                    865:     &Apache::loncommon::user_rule_check($checkhash,$checks,
                    866:            $alerts,$rulematch,$inst_results,$curr_rules,
                    867:            $got_rules);
                    868:     return;
                    869: }
                    870: 
1.1       raeburn   871: sub send_token {
1.61      raeburn   872:     my ($domain,$email,$server,$domdesc,$contact_name,$contact_email,$courseid,$emailusername,
1.73      raeburn   873:         $usertype,$uname) = @_;
1.14      raeburn   874:     my $msg = '<h3>'.&mt('Account creation status').'</h3>'.
                    875:               &mt('Thank you for your request to create a new LON-CAPA account.').
                    876:               '<br /><br />';
1.1       raeburn   877:     my $now = time;
1.58      raeburn   878:     $env{'form.logtoken'} =~ s/(`)//g;
                    879:     if ($env{'form.logtoken'}) {
                    880:         my $logtoken = $env{'form.logtoken'};
                    881:         my $tmpinfo=Apache::lonnet::reply('tmpget:'.$logtoken,$server);
                    882:         if (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost')) {
                    883:             $msg = &mt('Information needed to process your request is missing, inaccessible or expired.')
                    884:                   .'<br />'.&mt('Return to the previous page to try again.');
                    885:         } else {
                    886:             my $reply = &Apache::lonnet::reply('tmpdel:'.$logtoken,$server);
                    887:             unless ($reply eq 'ok') {
                    888:                 $msg .= &mt('Request could not be processed.');
                    889:             }
                    890:         }
                    891:         my %info = ('ip'         => $ENV{'REMOTE_ADDR'},
                    892:                     'time'       => $now,
                    893:                     'domain'     => $domain,
                    894:                     'username'   => $email,
                    895:                     'courseid'   => $courseid,
                    896:                     'upass'      => $env{'form.upass'},
                    897:                     'serverid'   => $env{'form.serverid'},
                    898:                     'tmpinfo'    => $tmpinfo);
1.73      raeburn   899:         if ($uname ne '') {
                    900:             $info{'username'} = $uname;
                    901:             $info{'email'} = $email;
                    902:         }
1.58      raeburn   903:         if (ref($emailusername) eq 'HASH') {
1.61      raeburn   904:             if (ref($emailusername->{$usertype}) eq 'HASH') {
                    905:                 foreach my $item (keys(%{$emailusername->{$usertype}})) {
                    906:                     $info{$item} = $env{'form.'.$item};
                    907:                     $info{$item} =~ s/(`)//g;
                    908:                 }
1.58      raeburn   909:             }
                    910:         }
1.73      raeburn   911:         if ($usertype ne '') {
                    912:            $info{'usertype'} = $usertype;
                    913:         }
1.58      raeburn   914:         my $token = &Apache::lonnet::tmpput(\%info,$server,'createaccount');
                    915:         if ($token !~ /^error/ && $token ne 'no_such_host') {
                    916:             my $esc_token = &escape($token);
                    917:             my $showtime = localtime(time);
                    918:             my $mailmsg = &mt('A request was submitted on [_1] for creation of a LON-CAPA account at the following institution: [_2].',$showtime,$domdesc).' '.
                    919:                           &mt('To complete this process please open a web browser and enter the following URL in the address/location box: [_1]',
                    920:                           &Apache::lonnet::absolute_url().'/adm/createaccount?token='.$esc_token);
                    921:             my $result = &Apache::resetpw::send_mail($domdesc,$email,$mailmsg,$contact_name,
                    922:                                                      $contact_email);
                    923:             if ($result eq 'ok') {
                    924:                 $msg .= &mt('A message has been sent to the e-mail address you provided.').'<br />'.
                    925:                         &mt('The message includes the web address for the link you will use to complete the account creation process.').'<br />'.
                    926:                         &mt("The link included in the message will be valid for the next [_1]two[_2] hours.",'<b>','</b>');
                    927:             } else {
                    928:                 $msg .= '<span class="LC_error">'.
                    929:                         &mt('An error occurred when sending a message to the e-mail address you provided.').'</span><br />'.
                    930:                         ' '.&mt('Please contact the [_1] ([_2]) for assistance.',$contact_name,$contact_email);
                    931:             }
1.1       raeburn   932:         } else {
1.14      raeburn   933:             $msg .= '<span class="LC_error">'.
1.58      raeburn   934:                     &mt('An error occurred creating a token required for the account creation process.').'</span><br />'.
1.14      raeburn   935:                     ' '.&mt('Please contact the [_1] ([_2]) for assistance.',$contact_name,$contact_email);
1.1       raeburn   936:         }
                    937:     } else {
1.58      raeburn   938:         $msg .=  $msg = &mt('Information needed to process your request is missing, inaccessible or expired.')
                    939:                 .'<br />'.&mt('Return to the previous page to try again.');
                    940: 
1.1       raeburn   941:     }
                    942:     return $msg;
                    943: }
                    944: 
                    945: sub process_mailtoken {
1.3       raeburn   946:     my ($r,$token,$contact_name,$contact_email,$domain,$domdesc,$lonhost,
1.73      raeburn   947:         $include,$start_page,$cancreate,$settings,$types) = @_;
1.58      raeburn   948:     my ($msg,$nostart,$noend,$redirect);
1.1       raeburn   949:     my %data = &Apache::lonnet::tmpget($token);
                    950:     my $now = time;
                    951:     if (keys(%data) == 0) {
1.9       raeburn   952:         $msg = &mt('Sorry, the URL you provided to complete creation of a new LON-CAPA account was invalid.')
                    953:                .' '.&mt('Either the token included in the URL has been deleted or the URL you provided was invalid.')
1.58      raeburn   954:                .' '.&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.',
                    955:                         '<a href="/adm/createaccount">','</a>');
1.1       raeburn   956:         return $msg;
                    957:     }
                    958:     if (($data{'time'} =~ /^\d+$/) &&
                    959:         ($data{'domain'} ne '') &&
1.73      raeburn   960:         ((($data{'email'} =~ /^[^\@]+\@[^\@]+\.[^\@\.]+$/) && ($data{'username'} =~ /^$match_username$/)) ||
                    961:           ($data{'username'}  =~ /^[^\@]+\@[^\@]+\.[^\@\.]+$/))) {
1.1       raeburn   962:         if ($now - $data{'time'} < 7200) {
1.58      raeburn   963: # Check if request should be queued.
                    964:             if (ref($cancreate) eq 'ARRAY') {
1.73      raeburn   965:                 my ($disposition,$usertype);
1.58      raeburn   966:                 if (grep(/^email$/,@{$cancreate})) {
1.73      raeburn   967:                     if (exists($data{'usertype'})) {
                    968:                         $usertype = $data{'usertype'};
                    969:                         my @posstypes;
                    970:                         if (ref($types) eq 'ARRAY') {
                    971:                             @posstypes = @{$types};
                    972:                             if (@posstypes) {
                    973:                                 unless (grep(/^default$/,@posstypes)) {
                    974:                                     push(@posstypes,'default');
                    975:                                 }
                    976:                             }
                    977:                             if (grep(/\Q$usertype\E/,@posstypes)) {
                    978:                                 unless ($usertype eq 'default') {
                    979:                                     $data{'inststatus'} = $usertype;
                    980:                                 }
                    981:                             } else {
1.74    ! raeburn   982:                                 $disposition = 'approval';
1.73      raeburn   983:                             }
                    984:                         }
                    985:                         delete($data{'usertype'});
                    986:                     }
1.64      raeburn   987:                     if (ref($settings) eq 'HASH') {
                    988:                         if (ref($settings->{'cancreate'}) eq 'HASH') {
                    989:                             if (ref($settings->{'cancreate'}{'selfcreateprocessing'}) eq 'HASH') {
1.74    ! raeburn   990:                                 if ($usertype ne '') {
        !           991:                                     $disposition = $settings->{'cancreate'}{'selfcreateprocessing'}{$usertype};
        !           992:                                     unless ($disposition =~ /^(approval|automatic)$/) {
        !           993:                                         $disposition = 'approval';
        !           994:                                     }
        !           995:                                 }
1.64      raeburn   996:                             }
1.58      raeburn   997:                         }
1.64      raeburn   998:                     }
                    999:                     if ($disposition eq 'approval') {
                   1000:                         $msg = &store_request($domain,$data{'username'},'approval',\%data,$settings);
                   1001:                         my $delete = &Apache::lonnet::tmpdel($token);
1.1       raeburn  1002:                     } else {
1.64      raeburn  1003:                         my ($result,$output,$uhome) = 
                   1004:                             &create_account($r,$domain,$domdesc,\%data);
                   1005:                         if ($result eq 'ok') {
                   1006:                             $msg = $output;
                   1007:                             my $shownow = &Apache::lonlocal::locallocaltime($now);
                   1008:                             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";
                   1009:                             my $mailresult = &Apache::resetpw::send_mail($domdesc,$data{'email'},
                   1010:                                                                         $mailmsg,$contact_name,
                   1011:                                                                         $contact_email);
                   1012:                             if ($mailresult eq 'ok') {
                   1013:                                 $msg .= &mt('An e-mail confirming creation of your new LON-CAPA account has been sent to [_1].',$data{'username'});
                   1014:                             } else {
                   1015:                                 $msg .= &mt('An error occurred when sending e-mail to [_1] confirming creation of your LON-CAPA account.',$data{'username'});
                   1016:                             }
                   1017:                             $redirect = &start_session($r,$data{'username'},$domain,$uhome,
                   1018:                                                        $data{'courseid'},$token);
                   1019:                             $nostart = 1;
                   1020:                             $noend = 1;
                   1021:                         } else {
                   1022:                             $msg .= &mt('A problem occurred when attempting to create your new LON-CAPA account.')
                   1023:                                    .'<br />'.$output;
                   1024:                             if (($contact_name ne '') && ($contact_email ne '')) {
                   1025:                                 $msg .= &mt('Please contact the [_1] ([_2]) for assistance.',$contact_name,$contact_email);
                   1026:                             }
1.58      raeburn  1027:                         }
1.64      raeburn  1028:                         my $delete = &Apache::lonnet::tmpdel($token);
1.1       raeburn  1029:                     }
                   1030:                 } else {
1.58      raeburn  1031:                     $msg = &invalid_state('noemails',$domdesc,$contact_name,$contact_email);
1.1       raeburn  1032:                 }
                   1033:             } else {
1.58      raeburn  1034:                 $msg = &invalid_state('noemails',$domdesc,$contact_name,$contact_email);
1.1       raeburn  1035:             }
                   1036:         } else {
1.7       bisitz   1037:             $msg = &mt('Sorry, the token generated when you requested creation of an account has expired.')
                   1038:                   .' '.&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  1039:             }
1.1       raeburn  1040:     } else {
1.7       bisitz   1041:         $msg .= &mt('Sorry, the URL generated when you requested creation of an account contained incomplete information.')
                   1042:                .' '.&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  1043:     }
1.58      raeburn  1044:     return ($msg,$nostart,$noend,$redirect);
1.3       raeburn  1045: }
                   1046: 
                   1047: sub start_session {
1.51      raeburn  1048:     my ($r,$username,$domain,$uhome,$courseid,$token) = @_;
1.69      raeburn  1049:     my ($is_balancer) = &Apache::lonnet::check_loadbalancing($username,$domain);
                   1050:     if ($is_balancer) {
1.51      raeburn  1051:         Apache::lonauth::success($r, $username, $domain, $uhome,
1.48      droeschl 1052:             'noredirect', undef, {});
                   1053: 
                   1054:         Apache::lonnet::tmpdel($token) if $token;
                   1055: 
1.58      raeburn  1056:         return 'redirect';
1.3       raeburn  1057:     } else {
1.48      droeschl 1058:         $courseid = Apache::lonnet::is_course($courseid); 
                   1059: 
1.51      raeburn  1060:         Apache::lonauth::success($r, $username, $domain, $uhome,
1.48      droeschl 1061:             ($courseid ? "/adm/selfenroll?courseid=$courseid" : '/adm/roles'),
                   1062:             undef, {}); 
1.3       raeburn  1063:     }
1.48      droeschl 1064:     return;
1.1       raeburn  1065: }
                   1066: 
1.50      www      1067: #
                   1068: # The screen that the user gets to create his or her account
                   1069: # Desired username, desired password, etc
                   1070: # Stores token to store DES-key and stage during creation session
                   1071: #
1.1       raeburn  1072: sub print_dataentry_form {
1.68      raeburn  1073:     my ($r,$domain,$lonhost,$include,$now,$captchaform,$courseid,$emailusername,$captcha,
1.74    ! raeburn  1074:         $usertype,$recaptchaversion,$usernameset,$condition,$excluded) = @_;
1.1       raeburn  1075:     my ($error,$output);
1.68      raeburn  1076:     if (open(my $jsh,"<$include/londes.js")) {
                   1077:         while(my $line = <$jsh>) {
                   1078:             $r->print($line);
                   1079:         }
                   1080:         close($jsh);
1.73      raeburn  1081:         $output = &javascript_setforms($now,$emailusername,$captcha,$usertype,$recaptchaversion,
1.74    ! raeburn  1082:                                        $usernameset,$condition,$excluded).
1.72      raeburn  1083:                   "\n".&javascript_checkpass($now,'email');
1.58      raeburn  1084:         my ($lkey,$ukey) = &Apache::loncommon::des_keys();
1.1       raeburn  1085:         my ($lextkey,$uextkey) = &getkeys($lkey,$ukey);
1.41      raeburn  1086:         my $logtoken=Apache::lonnet::reply('tmpput:'.$ukey.$lkey.'&createaccount:createaccount',
1.1       raeburn  1087:                                            $lonhost);
1.58      raeburn  1088:         $output .=
                   1089:             '<form name="createaccount" method="post" target="_top" action="/adm/createaccount">';
                   1090:         if ($courseid ne '') {
                   1091:             $output .= '<input type="hidden" name="courseid" value="'.$courseid.'"/>'."\n";
                   1092:         }
                   1093:         if (ref($emailusername) eq 'HASH') {
1.61      raeburn  1094:             if (ref($emailusername->{$usertype}) eq 'HASH') {
                   1095:                 foreach my $field (sort(keys(%{$emailusername->{$usertype}}))) {
                   1096:                     $output .= '<input type="hidden" name="'.$field.'" value="" />'."\n";
                   1097:                 }
1.58      raeburn  1098:             }
1.1       raeburn  1099:         }
1.59      raeburn  1100:         if ($captcha eq 'original') {
                   1101:             $output .= '
                   1102:    <input type="hidden" name="crypt" value="" />
                   1103:    <input type="hidden" name="code" value="" />
                   1104: ';
                   1105:         } elsif ($captcha eq 'recaptcha') {
1.72      raeburn  1106:             if ($recaptchaversion eq '2') {
                   1107:                 $output .= "$captchaform\n";
                   1108:                 undef($captchaform);
                   1109:             } else {
                   1110:                 $output .= '
1.59      raeburn  1111:    <input type="hidden" name="recaptcha_challenge_field" value="" />
                   1112:    <input type="hidden" name="recaptcha_response_field" value="" />
                   1113: ';
1.72      raeburn  1114:             }
1.59      raeburn  1115:         }
1.73      raeburn  1116:         if ($usertype ne '') {
                   1117:             $output .= '<input type="hidden" name="type" value="'.
                   1118:                        &HTML::Entities::encode($usertype,'\'<>"&').'" />'."\n";
                   1119:         }
1.74    ! raeburn  1120:         if ($usernameset eq 'free') {
1.73      raeburn  1121:             $output .= '<input type="hidden" name="username" value="" />'."\n"; 
                   1122:         }
1.1       raeburn  1123:         $output .= <<"ENDSERVERFORM";
                   1124:    <input type="hidden" name="logtoken" value="$logtoken" />
                   1125:    <input type="hidden" name="serverid" value="$lonhost" />
                   1126:    <input type="hidden" name="uname" value="" />
                   1127:    <input type="hidden" name="upass" value="" />
1.32      raeburn  1128:    <input type="hidden" name="udom" value="" />
1.1       raeburn  1129:    <input type="hidden" name="phase" value="createaccount" />
1.58      raeburn  1130:    <input type="hidden" name="create_with_email" value="1" />
1.32      raeburn  1131:   </form>
1.1       raeburn  1132: ENDSERVERFORM
1.58      raeburn  1133:         my $beginclientform = '<form name="newemail" method="post" action="" '.
                   1134:                               'onsubmit="return checkpass('."'createaccount','newemail'".');">'."\n";
                   1135:         my $endclientform = '<input type="hidden" name="udom" value="'.$domain.'" />'."\n".
                   1136:                             '<input type="hidden" name="lextkey" value="'.$lextkey.'" />'."\n".
                   1137:                             '<input type="hidden" name="uextkey" value="'.$uextkey.'" />'."\n".
1.61      raeburn  1138:                             '</form>'."\n".
                   1139:                             '<p class="LC_info">'.&mt('Fields marked [_1]*[_2] are required.','<b>','</b>').'</p>';
1.58      raeburn  1140:         my ($datatable,$rowcount) =
                   1141:             &Apache::loncreateuser::personal_data_display('',$domain,'email','selfcreate',
                   1142:                                                           '','',$now,$captchaform,
1.73      raeburn  1143:                                                           $emailusername,$usertype,
1.74    ! raeburn  1144:                                                           $usernameset,$condition,$excluded);
1.32      raeburn  1145:         if ($rowcount) {
1.58      raeburn  1146:             $output .= '<div class="LC_left_float">'.$beginclientform.$datatable.$endclientform;
                   1147:         } else {
                   1148:             $output .= $beginclientform.$endclientform;
1.32      raeburn  1149:         }
                   1150:         if ($rowcount) {
                   1151:             $output .= '</div>'."\n".
                   1152:                        '<div class="LC_clear_float_footer"></div>'."\n";
                   1153:         }
1.1       raeburn  1154:     } else {
1.7       bisitz   1155:         $output = &mt('Could not load javascript file [_1]','<tt>londes.js</tt>');
1.1       raeburn  1156:     }
1.3       raeburn  1157:     return $output;
1.1       raeburn  1158: }
                   1159: 
1.50      www      1160: #
                   1161: # Retrieve rules for generating accounts from domain configuration
                   1162: # Can the user make a new account or just self-enroll?
                   1163: 
1.35      raeburn  1164: sub get_creation_controls {
                   1165:     my ($domain,$usercreation) = @_;
1.73      raeburn  1166:     my (@cancreate,@statustocreate,@statusforemail,$emailusername,$processing,
1.74    ! raeburn  1167:         $emailoptions,$verification,$emaildomain,$othertitle,$usertypes,$types);
1.35      raeburn  1168:     if (ref($usercreation) eq 'HASH') {
                   1169:         if (ref($usercreation->{'cancreate'}) eq 'HASH') {
1.73      raeburn  1170:             ($othertitle,$usertypes,$types) =
                   1171:                 &Apache::loncommon::sorted_inst_types($domain);
1.35      raeburn  1172:             if (ref($usercreation->{'cancreate'}{'statustocreate'}) eq 'ARRAY') {
                   1173:                 @statustocreate = @{$usercreation->{'cancreate'}{'statustocreate'}};
1.47      raeburn  1174:                 if (@statustocreate == 0) {
                   1175:                     if (ref($types) eq 'ARRAY') {
                   1176:                         if (@{$types} == 0) {
                   1177:                             @statustocreate = ('default');
                   1178:                         }
                   1179:                     } else {
                   1180:                         @statustocreate = ('default');
                   1181:                     }
                   1182:                 }
1.35      raeburn  1183:             } else {
                   1184:                 @statustocreate = ('default');
                   1185:                 if (ref($types) eq 'ARRAY') {
                   1186:                     push(@statustocreate,@{$types});
                   1187:                 }
                   1188:             }
                   1189:             if (ref($usercreation->{'cancreate'}{'selfcreate'}) eq 'ARRAY') {
                   1190:                 @cancreate = @{$usercreation->{'cancreate'}{'selfcreate'}};
                   1191:             } elsif (($usercreation->{'cancreate'}{'selfcreate'} ne 'none') &&
                   1192:                      ($usercreation->{'cancreate'}{'selfcreate'} ne '')) {
                   1193:                 @cancreate = ($usercreation->{'cancreate'}{'selfcreate'});
                   1194:             }
1.73      raeburn  1195:             if (grep(/^email$/,@cancreate)) {
                   1196:                 if (ref($usercreation->{'cancreate'}{'selfcreateprocessing'}) eq 'HASH') {
                   1197:                     $processing = $usercreation->{'cancreate'}{'selfcreateprocessing'};
                   1198:                 }
1.74    ! raeburn  1199:                 if (ref($usercreation->{'cancreate'}{'emailoptions'}) eq 'HASH') {
        !          1200:                     $emailoptions = $usercreation->{'cancreate'}{'emailoptions'};
        !          1201:                 }
1.73      raeburn  1202:                 if (ref($usercreation->{'cancreate'}{'emailverified'}) eq 'HASH') {
                   1203:                     $verification = $usercreation->{'cancreate'}{'emailverified'};
                   1204:                 }
                   1205:                 if (ref($usercreation->{'cancreate'}{'emaildomain'}) eq 'HASH') {
                   1206:                     $emaildomain = $usercreation->{'cancreate'}{'emaildomain'};
                   1207:                 }
                   1208:                 if (ref($processing)) {
                   1209:                     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   1210:                     my @emailtypes;
                   1211:                     if (ref($domdefaults{'inststatusguest'}) eq 'ARRAY') {
1.74    ! raeburn  1212:                         @statusforemail = @{$domdefaults{'inststatusguest'}};
        !          1213:                         unless (@statusforemail) {
        !          1214:                             my @okcreate;
        !          1215:                             foreach my $poss (@cancreate) {
        !          1216:                                 unless ($poss eq 'email') {
        !          1217:                                      push(@okcreate,$poss);
1.73      raeburn  1218:                                 }
                   1219:                             }
1.74    ! raeburn  1220:                             @cancreate = @okcreate;
1.73      raeburn  1221:                         }
                   1222:                     }
                   1223:                 }  
                   1224:             }
1.58      raeburn  1225:             if (ref($usercreation->{'cancreate'}{'emailusername'}) eq 'HASH') {
                   1226:                 $emailusername = $usercreation->{'cancreate'}{'emailusername'};
1.59      raeburn  1227:             } else {
1.67      raeburn  1228:                 $emailusername = {
                   1229:                                     default =>  {
                   1230:                                                    'lastname' => '1',
                   1231:                                                    'firstname' => 1,
                   1232:                                                 },
                   1233:                                  };
1.58      raeburn  1234:             }
1.35      raeburn  1235:         }
                   1236:     }
1.73      raeburn  1237:     return (\@cancreate,\@statustocreate,\@statusforemail,$emailusername,
1.74    ! raeburn  1238:             $emailoptions,$verification,$emaildomain,$types,$usertypes,$othertitle);
1.35      raeburn  1239: }
                   1240: 
1.1       raeburn  1241: sub create_account {
1.58      raeburn  1242:     my ($r,$domain,$domdesc,$dataref) = @_;
                   1243:     my $error    = '<span class="LC_error">'.&mt('Error:').' ';
                   1244:     my $end      = '</span><br /><br />';
                   1245:     my $rtnlink  = '<a href="javascript:history.back();">'.
1.1       raeburn  1246:                     &mt('Return to previous page').'</a>'.
                   1247:                     &Apache::loncommon::end_page();
1.58      raeburn  1248:     my $output;
                   1249:     if (ref($dataref) eq 'HASH') {
                   1250:         my ($username,$encpass,$serverid,$courseid,$id,$firstname,$middlename,$lastname,
1.73      raeburn  1251:             $generation,$inststatus,$permanentemail);
1.58      raeburn  1252:         $username   = $dataref->{'username'};
                   1253:         $encpass    = $dataref->{'upass'};
                   1254:         $serverid   = $dataref->{'serverid'};
                   1255:         $courseid   = $dataref->{'courseid'};
                   1256:         $id         = $dataref->{'id'};
                   1257:         $firstname  = $dataref->{'firstname'};
                   1258:         $middlename = $dataref->{'middlename'};
                   1259:         $lastname   = $dataref->{'lastname'};
                   1260:         $generation = $dataref->{'generation'};
1.63      raeburn  1261:         $inststatus = $dataref->{'inststatus'};
                   1262: 
1.73      raeburn  1263:         if ($dataref->{'email'} ne '') {
                   1264:             $permanentemail = $dataref->{'email'};
                   1265:         } else {
                   1266:             $permanentemail = $dataref->{'username'};
                   1267:         }
1.58      raeburn  1268:         my $currhome = &Apache::lonnet::homeserver($username,$domain);
                   1269:         unless ($currhome eq 'no_host') {
                   1270:             $output = &mt('User account requested for username: [_1] in domain: [_2] already exists.',$username,$domain);
                   1271:             return ('fail',$error.$output.$end.$rtnlink);
                   1272:         }
                   1273: 
                   1274: # Split the logtoken to retrieve the DES key and decrypt the encypted password
                   1275: 
                   1276:         my ($key,$caller)=split(/&/,$dataref->{'tmpinfo'});
                   1277:         if ($caller eq 'createaccount') {
1.74    ! raeburn  1278:             my $upass;
        !          1279:             if ($encpass eq '') {
        !          1280:                 $output = &mt('Password retrieved was blank.');
        !          1281:                 return ('fail',$error.$output.$end.$rtnlink);
        !          1282:             } else {
        !          1283:                 $upass = &Apache::loncommon::des_decrypt($key,$encpass);
        !          1284:             }
1.58      raeburn  1285: 
                   1286: # See if we are allowed to use the proposed student/employee ID,
                   1287: # as per domain rules; if not, student/employee will be left blank.
                   1288: 
                   1289:             if ($id ne '') {
                   1290:                 my ($result,$userchkmsg) = &check_id($username,$domain,$id,$domdesc,'email');
                   1291:                 if ($result eq 'fail') {
                   1292:                     $output = $error.&mt('Invalid ID format').$end.
                   1293:                               $userchkmsg;
                   1294:                     undef($id);
                   1295:                 }
1.1       raeburn  1296:             }
1.58      raeburn  1297: 
                   1298: # Create an internally authenticated account with password $upass
                   1299: # if the user account does not already exist.
                   1300: # Assign student/employee id, first name, last name, etc.
                   1301: 
                   1302:             my $result =
                   1303:                 &Apache::lonnet::modifyuser($domain,$username,$id,
                   1304:                                             'internal',$upass,$firstname,$middlename,
1.73      raeburn  1305:                                             $lastname,$generation,undef,undef,$permanentemail);
1.58      raeburn  1306:             $output = &mt('Generating user: [_1]',$result);
                   1307: 
                   1308: # Now that the user account exists, retrieve the homeserver, and include it in the output.
                   1309: 
                   1310:             my $uhome = &Apache::lonnet::homeserver($username,$domain);
1.61      raeburn  1311:             unless (($inststatus eq 'default') || ($inststatus eq '')) {
                   1312:                 &Apache::lonnet::put('environment',{inststatus => $inststatus},$domain,$username);
                   1313:             }
1.58      raeburn  1314:             $output .= '<br />'.&mt('Home server: [_1]',$uhome).' '.
                   1315:                        &Apache::lonnet::hostname($uhome).'<br /><br />';
                   1316:             return ('ok',$output,$uhome);
                   1317:         } else {
                   1318:             $output = &mt('Unable to retrieve your account creation information - unexpected context');
                   1319:             undef($encpass);
                   1320:             return ('fail',$error.$output.$end.$rtnlink);
1.1       raeburn  1321:         }
                   1322:     } else {
1.58      raeburn  1323:         $output = &mt('Unable to retrieve information for your account request.');
1.1       raeburn  1324:         return ('fail',$error.$output.$end.$rtnlink);
                   1325:     }
                   1326: }
                   1327: 
                   1328: sub username_validation {
1.19      raeburn  1329:     my ($r,$username,$domain,$domdesc,$contact_name,$contact_email,$courseid,
1.35      raeburn  1330:         $lonhost,$statustocreate) = @_;
1.58      raeburn  1331: # $r: request object
1.49      www      1332: # $username,$domain: for the user who needs to be validated
                   1333: # $domdesc: full name of the domain (for error messages)
1.58      raeburn  1334: # $contact_name, $contact_email: name and email for user assistance (for error messages in &username_check)
                   1335: # $courseid: ID of the course if user came to username_validation via self-enroll link,
                   1336: #             passed to start_session()
                   1337: # $lonhost: LON-CAPA lonHostID
1.49      www      1338: # $statustocreate: -> inststatus in username_check ('faculty', 'staff', 'student', ...)
                   1339:  
1.58      raeburn  1340: #
                   1341: # Sanitize incoming username and domain
                   1342: #
1.1       raeburn  1343:     $username= &LONCAPA::clean_username($username);
                   1344:     $domain = &LONCAPA::clean_domain($domain);
1.58      raeburn  1345: 
                   1346: #
                   1347: # Check if LON-CAPA account already exists for $username:$domain
                   1348: #
1.1       raeburn  1349:     my $uhome = &Apache::lonnet::homeserver($username,$domain);
                   1350: 
1.58      raeburn  1351:     my $output;
                   1352: 
                   1353: # Retrieve DES key from server using logtoken
                   1354:  
                   1355:     my $tmpinfo=Apache::lonnet::reply('tmpget:'.$env{'form.logtoken'},$env{'form.serverid'});
                   1356:     if (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost')) {
                   1357:         $output = &mt('Information needed to verify your login information is missing, inaccessible or expired.')
                   1358:                  .'<br />'.&mt('You may need to reload the previous page to obtain a new token.');
                   1359:         return ('fail',$output);
                   1360:     } else {
                   1361:         my $reply = &Apache::lonnet::reply('tmpdel:'.$env{'form.logtoken'},$env{'form.serverid'});
                   1362:         unless ($reply eq 'ok') {
                   1363:             $output = &mt('Session could not be opened.');
                   1364:             return ('fail',$output); 
                   1365:         }
                   1366:     }
                   1367: 
                   1368: # Split the logtoken to retrieve the DES key and decrypt the encypted password
                   1369: 
                   1370:     my ($key,$caller)=split(/&/,$tmpinfo);
                   1371:     my $upass;
                   1372:     if ($caller eq 'createaccount') {
                   1373:         $upass = &Apache::loncommon::des_decrypt($key,$env{'form.upass'});
                   1374:     } else {
                   1375:         $output = &mt('Unable to retrieve your log-in information - unexpected context');
1.19      raeburn  1376:         return ('fail',$output);
                   1377:     }
                   1378:     if ($uhome ne 'no_host') {
                   1379:         my $result = &Apache::lonnet::authenticate($username,$upass,$domain);
                   1380:         if ($result ne 'no_host') { 
1.58      raeburn  1381:             my $redirect = &start_session($r,$username,$domain,$uhome,$courseid);
                   1382:             if ($redirect) {
                   1383:                 return ($redirect);
                   1384:             }
                   1385:             $output = '<br /><br />'.
                   1386:                       &mt('A LON-CAPA account already exists for username [_1] at this institution ([_2]).',
                   1387:                           '<tt>'.$username.'</tt>',$domdesc).'<br />'.
                   1388:                       &mt('The password entered was also correct so you have been logged in.');
1.19      raeburn  1389:             return ('existingaccount',$output);
                   1390:         } else {
1.22      raeburn  1391:             $output = &login_failure_msg($courseid);
1.19      raeburn  1392:         }
                   1393:     } else {
1.1       raeburn  1394:         my $primlibserv = &Apache::lonnet::domain($domain,'primary');
                   1395:         my $authok;
                   1396:         my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
1.58      raeburn  1397:         if ((($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) || 
                   1398:              ($domdefaults{'auth_def'} eq 'localauth')) {
1.1       raeburn  1399:             my $checkdefauth = 1;
                   1400:             $authok = 
                   1401:                 &Apache::lonnet::reply("encrypt:auth:$domain:$username:$upass:$checkdefauth",$primlibserv);
                   1402:         } else {
                   1403:             $authok = 'non_authorized';
                   1404:         }
                   1405:         if ($authok eq 'authorized') {
1.18      raeburn  1406:             $output = &username_check($username,$domain,$domdesc,$courseid,$lonhost,
1.35      raeburn  1407:                                       $contact_email,$contact_name,undef,
                   1408:                                       $statustocreate);
1.4       raeburn  1409:         } else {
1.22      raeburn  1410:             $output = &login_failure_msg($courseid);
1.4       raeburn  1411:         }
                   1412:     }
1.19      raeburn  1413:     return ('ok',$output);
1.4       raeburn  1414: }
                   1415: 
1.22      raeburn  1416: sub login_failure_msg {
                   1417:     my ($courseid) = @_;
                   1418:     my $url;
                   1419:     if ($courseid ne '') {
                   1420:         $url = "/adm/selfenroll?courseid=".$courseid;
                   1421:     } else {
                   1422:         $url = "/adm/createaccount";
                   1423:     }
                   1424:     my $output = '<h4>'.&mt('Authentication failed').'</h4><div class="LC_warning">'.
                   1425:                  &mt('Username and/or password could not be authenticated.').
                   1426:                  '</div>'.
                   1427:                  &mt('Please check the username and password.').'<br /><br />';
                   1428:                  '<a href="'.$url.'">'.&mt('Try again').'</a>';
                   1429:     return $output;
                   1430: }
                   1431: 
1.4       raeburn  1432: sub username_check {
1.35      raeburn  1433:     my ($username,$domain,$domdesc,$courseid,$lonhost,$contact_email,
1.65      raeburn  1434:         $contact_name,$sso_logout,$statustocreate,$shibenv) = @_;
1.23      raeburn  1435:     my (%rulematch,%inst_results,$checkfail,$rowcount,$editable,$output,$msg,
1.18      raeburn  1436:         %alerts,%curr_rules,%got_rules);
1.23      raeburn  1437:     &call_rulecheck($username,$domain,\%alerts,\%rulematch,
1.40      raeburn  1438:                     \%inst_results,\%curr_rules,\%got_rules,'username');
1.4       raeburn  1439:     if (ref($alerts{'username'}) eq 'HASH') {
                   1440:         if (ref($alerts{'username'}{$domain}) eq 'HASH') {
                   1441:             if ($alerts{'username'}{$domain}{$username}) {
                   1442:                 if (ref($curr_rules{$domain}) eq 'HASH') {
1.18      raeburn  1443:                     $output =
1.17      raeburn  1444:                         &Apache::loncommon::instrule_disallow_msg('username',$domdesc,1,
                   1445:                                                                   'selfcreate').
1.4       raeburn  1446:                         &Apache::loncommon::user_rule_formats($domain,$domdesc,
                   1447:                                 $curr_rules{$domain}{'username'},'username');
1.1       raeburn  1448:                 }
1.18      raeburn  1449:                 $checkfail = 'username';
1.1       raeburn  1450:             }
1.4       raeburn  1451:         }
                   1452:     }
1.18      raeburn  1453:     if (!$checkfail) {
1.35      raeburn  1454:         if (ref($statustocreate) eq 'ARRAY') {
                   1455:             $checkfail = 'inststatus';
                   1456:             if (ref($inst_results{$username.':'.$domain}{inststatus}) eq 'ARRAY') {
                   1457:                 foreach my $inststatus (@{$inst_results{$username.':'.$domain}{inststatus}}) {
                   1458:                     if (grep(/^\Q$inststatus\E$/,@{$statustocreate})) {
                   1459:                         undef($checkfail);
                   1460:                         last;
                   1461:                     }
                   1462:                 }
                   1463:             } elsif (grep(/^default$/,@{$statustocreate})) {
                   1464:                 undef($checkfail);
                   1465:             }
                   1466:         }
                   1467:     }
                   1468:     if (!$checkfail) {
1.18      raeburn  1469:         $output = '<form method="post" action="/adm/createaccount">';
1.65      raeburn  1470:         if (ref($shibenv) eq 'HASH') {
                   1471:             foreach my $key (keys(%{$shibenv})) {
1.66      raeburn  1472:                 if ($ENV{$shibenv->{$key}} ne '') {
                   1473:                     $inst_results{$username.':'.$domain}{$key} = $ENV{$shibenv->{$key}};
                   1474:                 }
1.65      raeburn  1475:             }
                   1476:         }
1.18      raeburn  1477:         (my $datatable,$rowcount,$editable) = 
                   1478:             &Apache::loncreateuser::personal_data_display($username,$domain,1,'selfcreate',
                   1479:                                                          $inst_results{$username.':'.$domain});
                   1480:         if ($rowcount > 0) {
                   1481:             $output .= $datatable;
                   1482:         }
                   1483:         $output .=  '<br /><br /><input type="hidden" name="uname" value="'.$username.'" />'."\n".
                   1484:                     '<input type="hidden" name="udom" value="'.$domain.'" />'."\n".
                   1485:                     '<input type="hidden" name="phase" value="username_activation" />';
                   1486:         my $now = time;
                   1487:         my %info = ('ip'         => $ENV{'REMOTE_ADDR'},
                   1488:                     'time'       => $now,
                   1489:                     'domain'     => $domain,
                   1490:                     'username'   => $username);
1.41      raeburn  1491:         my $authtoken = &Apache::lonnet::tmpput(\%info,$lonhost,'createaccount');
1.18      raeburn  1492:         if ($authtoken !~ /^error/ && $authtoken ne 'no_such_host') {
                   1493:             $output .= '<input type="hidden" name="authtoken" value="'.&HTML::Entities::encode($authtoken,'&<>"').'" />';
                   1494:         } else {
                   1495:             $output = &mt('An error occurred when storing a token').'<br />'.
                   1496:                       &mt('You will not be able to proceed to the next stage of account creation').
                   1497:                       &linkto_email_help($contact_email,$domdesc);
                   1498:             $checkfail = 'authtoken';
                   1499:         }
                   1500:     }
                   1501:     if ($checkfail) { 
1.47      raeburn  1502:         $msg = '<br /><h4>'.&mt('Account creation unavailable').'</h4>';
1.18      raeburn  1503:         if ($checkfail eq 'username') {
                   1504:             $msg .= '<span class="LC_warning">'.
                   1505:                      &mt('A LON-CAPA account may not be created with the username you use.').
                   1506:                      '</span><br /><br />'.$output;
                   1507:         } elsif ($checkfail eq 'authtoken') {
                   1508:             $msg .= '<span class="LC_error">'.&mt('Error creating token.').'</span>'.
                   1509:                     '<br />'.$output;
1.35      raeburn  1510:         } elsif ($checkfail eq 'inststatus') {
                   1511:             $msg .= '<span class="LC_warning">'.
                   1512:                      &mt('You are not permitted to create a LON-CAPA account.').
                   1513:                      '</span><br /><br />'.$output;
1.18      raeburn  1514:         }
                   1515:         $msg .= &mt('Please contact the [_1] ([_2]) for assistance.',
                   1516:                 $contact_name,$contact_email).'<br /><hr />'.
                   1517:                 $sso_logout;
                   1518:         &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  1519:     } else {
1.18      raeburn  1520:         if ($courseid ne '') {
                   1521:             $output .= '<input type="hidden" name="courseid" value="'.$courseid.'" />';
                   1522:         }
                   1523:         $output .= '<input type="submit" name="newaccount" value="'.
                   1524:                    &mt('Create LON-CAPA account').'" /></form>';
                   1525:         if ($rowcount) {
                   1526:             if ($editable) {
1.22      raeburn  1527:                 if ($courseid ne '') { 
1.47      raeburn  1528:                     $msg = '<br /><h4>'.&mt('User information').'</h4>';
1.22      raeburn  1529:                 }
                   1530:                 $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 />';
1.18      raeburn  1531:             } else {
1.22      raeburn  1532:                  if ($courseid ne '') {
                   1533:                      $msg = '<h4>'.&mt('Review user information').'</h4>';
                   1534:                  }
                   1535:                  $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 />';
1.18      raeburn  1536:             }
                   1537:         } else {
1.22      raeburn  1538:             if ($courseid ne '') {
                   1539:                 $msg = '<h4>'.&mt('Confirmation').'</h4>';
                   1540:             }
                   1541:             $msg .= &mt('Confirm that you wish to create an account.');
1.18      raeburn  1542:         }
                   1543:         $msg .= $output;
                   1544:     }
                   1545:     return $msg;
1.1       raeburn  1546: }
                   1547: 
                   1548: sub username_activation {
1.51      raeburn  1549:     my ($r,$username,$domain,$domdesc,$courseid) = @_;
1.1       raeburn  1550:     my $output;
1.7       bisitz   1551:     my $error     = '<span class="LC_error">'.&mt('Error:').' ';
1.1       raeburn  1552:     my $end       = '</span><br /><br />';
1.54      bisitz   1553:     my $rtnlink   = '<a href="javascript:history.back();">'.
1.1       raeburn  1554:                     &mt('Return to previous page').'</a>'.
                   1555:                     &Apache::loncommon::end_page();
                   1556:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
1.8       raeburn  1557:     my %data = &Apache::lonnet::tmpget($env{'form.authtoken'});
                   1558:     my $now = time;
                   1559:     my $earlyout;
                   1560:     my $timeout = 300;
                   1561:     if (keys(%data) == 0) {
                   1562:         $output = &mt('Sorry, your authentication has expired.');
                   1563:         $earlyout = 'fail';
                   1564:     }
                   1565:     if (($data{'time'} !~ /^\d+$/) ||
                   1566:         ($data{'domain'} ne $domain) || 
                   1567:         ($data{'username'} ne $username)) {
                   1568:         $earlyout = 'fail';
                   1569:         $output = &mt('The credentials you provided could not be verified.');   
                   1570:     } elsif ($now - $data{'time'} > $timeout) {
                   1571:         $earlyout = 'fail';
                   1572:         $output = &mt('Sorry, your authentication has expired.');
                   1573:     }
                   1574:     if ($earlyout ne '') {
1.56      raeburn  1575:         my $link = '/adm/createaccount';
                   1576:         if (&Apache::lonnet::domain($domain) ne '') {
                   1577:             $link .= "?domain=$domain"; 
                   1578:         }
                   1579:         $output .= '<br />'.&mt('Please [_1]start again[_2].',
                   1580:                                 '<a href="'.$link.'">','</a>');
1.8       raeburn  1581:         return($earlyout,$output);
                   1582:     }
1.3       raeburn  1583:     if ((($domdefaults{'auth_def'} =~/^krb(4|5)$/) && 
                   1584:          ($domdefaults{'auth_arg_def'} ne '')) || 
                   1585:         ($domdefaults{'auth_def'} eq 'localauth')) {
1.22      raeburn  1586:         if ($env{'form.courseid'} ne '') {
1.58      raeburn  1587:             my $id = $env{'form.cid'}; 
                   1588:             my ($result,$userchkmsg) = &check_id($username,$domain,$id,$domdesc,'institutional');
1.1       raeburn  1589:             if ($result eq 'fail') {
                   1590:                 $output = $error.&mt('Invalid ID format').$end.
                   1591:                           $userchkmsg.$rtnlink;
                   1592:                 return ('fail',$output);
                   1593:             }
                   1594:         }
                   1595:         # Call modifyuser
1.23      raeburn  1596:         my (%rulematch,%inst_results,%curr_rules,%got_rules,%alerts,%info);
                   1597:         &call_rulecheck($username,$domain,\%alerts,\%rulematch,
1.40      raeburn  1598:                         \%inst_results,\%curr_rules,\%got_rules);
1.23      raeburn  1599:         my @userinfo = ('firstname','middlename','lastname','generation',
                   1600:                         'permanentemail','id');
                   1601:         my %canmodify = 
                   1602:             &Apache::loncreateuser::selfcreate_canmodify('selfcreate',$domain,
                   1603:                                                          \@userinfo,\%inst_results);
                   1604:         foreach my $item (@userinfo) {
                   1605:             if ($canmodify{$item}) {
                   1606:                 $info{$item} = $env{'form.c'.$item};
                   1607:             } else {
                   1608:                 $info{$item} = $inst_results{$username.':'.$domain}{$item}; 
                   1609:             }
                   1610:         }
                   1611:         if (ref($inst_results{$username.':'.$domain}{'inststatus'}) eq 'ARRAY') {
                   1612:             my @inststatuses = @{$inst_results{$username.':'.$domain}{'inststatus'}};
                   1613:             $info{'inststatus'} = join(':',map { &escape($_); } @inststatuses);
                   1614:         }
1.1       raeburn  1615:         my $result =
1.23      raeburn  1616:             &Apache::lonnet::modifyuser($domain,$username,$env{'form.cid'},
1.1       raeburn  1617:                           $domdefaults{'auth_def'},
1.23      raeburn  1618:                           $domdefaults{'auth_arg_def'},$info{'firstname'},
                   1619:                           $info{'middlename'},$info{'lastname'},
                   1620:                           $info{'generation'},undef,undef,
                   1621:                           $info{'permanentemail'},$info{'inststatus'});
1.3       raeburn  1622:         if ($result eq 'ok') {
1.8       raeburn  1623:             my $delete = &Apache::lonnet::tmpdel($env{'form.authtoken'});
1.3       raeburn  1624:             $output = &mt('A LON-CAPA account has been created for username: [_1] in domain: [_2].',$username,$domain);
1.51      raeburn  1625:             my $uhome=&Apache::lonnet::homeserver($username,$domain,'true');
1.3       raeburn  1626:             my $nostart = 1;
1.58      raeburn  1627:             my $response = 'ok';
                   1628:             my $redirect = &start_session($r,$username,$domain,$uhome,$courseid);
                   1629:             if ($redirect) {
                   1630:                 $response = $redirect;
                   1631:             }
                   1632:             return ($response,$output,$nostart);
1.3       raeburn  1633:         } else {
                   1634:             $output = &mt('Account creation failed for username: [_1] in domain: [_2].',$username,$domain).'<br /><span class="LC_error">'.&mt('Error: [_1]',$result).'</span>';
                   1635:             return ('fail',$output);
                   1636:         }
1.1       raeburn  1637:     } else {
1.7       bisitz   1638:         $output = &mt('User account creation is not available for the current default authentication type.')."\n";
1.1       raeburn  1639:         return('fail',$output);
                   1640:     }
                   1641: }
                   1642: 
                   1643: sub check_id {
1.58      raeburn  1644:     my ($username,$domain,$id,$domdesc,$usernametype) = @_;
                   1645:     # Check student/employee ID format
                   1646:     # Is proposed student/employee ID acceptable according to domain's rules.  
1.50      www      1647:     # $domdesc is just used for user error messages
1.1       raeburn  1648:     my (%alerts,%rulematch,%inst_results,%curr_rules,%checkhash);
                   1649:     my %checks = ('id' => 1);
                   1650:     %{$checkhash{$username.':'.$domain}} = (
                   1651:                                             'newuser' => 1,
1.58      raeburn  1652:                                             'id' => $id,
1.1       raeburn  1653:                                            );
                   1654:     &Apache::loncommon::user_rule_check(\%checkhash,\%checks,\%alerts,
                   1655:                                         \%rulematch,\%inst_results,\%curr_rules);
                   1656:     if (ref($alerts{'id'}) eq 'HASH') {
                   1657:         if (ref($alerts{'id'}{$domain}) eq 'HASH') {
                   1658:             if ($alerts{'id'}{$domain}{$env{'form.cid'}}) {
                   1659:                 my $userchkmsg;
                   1660:                 if (ref($curr_rules{$domain}) eq 'HASH') {
1.58      raeburn  1661:                     if ($usernametype eq 'email') {
                   1662:                         $userchkmsg = &mt('A student/employee ID has not been set because the value suggested matched the format used for institutional users in the domain, and you are using an e-mail address as username, not an institutional username.');
                   1663:                     } else {
                   1664:                         $userchkmsg =
                   1665:                             &Apache::loncommon::instrule_disallow_msg('id',
                   1666:                                                                       $domdesc,1).
                   1667:                             &Apache::loncommon::user_rule_formats($domain,
                   1668:                                 $domdesc,$curr_rules{$domain}{'id'},'id');
                   1669:                     }
1.1       raeburn  1670:                 }
                   1671:                 return ('fail',$userchkmsg);
                   1672:             }
                   1673:         }
                   1674:     }
                   1675:     return; 
                   1676: }
                   1677: 
                   1678: sub invalid_state {
                   1679:     my ($error,$domdesc,$contact_name,$contact_email,$msgtext) = @_;
1.14      raeburn  1680:     my $msg = '<h3>'.&mt('Account creation unavailable').'</h3><span class="LC_error">';
1.1       raeburn  1681:     if ($error eq 'baduseremail') {
1.42      raeburn  1682:         $msg .= &mt('The e-mail address you provided does not appear to be a valid address.');
1.58      raeburn  1683:     } elsif ($error eq 'badusername') {
                   1684:         $msg .= &mt('The e-mail address you provided contains characters which prevent its use as a username in LON-CAPA.');
1.1       raeburn  1685:     } elsif ($error eq 'existinguser') {
1.42      raeburn  1686:         $msg .= &mt('The e-mail address you provided is already in use as a username in LON-CAPA at this institution.');
1.1       raeburn  1687:     } elsif ($error eq 'userrules') {
1.42      raeburn  1688:         $msg .= &mt('Username rules at this institution do not allow the e-mail address you provided to be used as a username.');
1.1       raeburn  1689:     } elsif ($error eq 'userformat') {
1.42      raeburn  1690:         $msg .= &mt('The e-mail address you provided may not be used as a username at this LON-CAPA institution.');
1.1       raeburn  1691:     } elsif ($error eq 'captcha') {
1.43      raeburn  1692:         $msg .= &mt('Validation of the code you entered failed.');
1.1       raeburn  1693:     } elsif ($error eq 'noemails') {
1.42      raeburn  1694:         $msg .= &mt('Creation of a new user account using an e-mail address as username is not permitted at this LON-CAPA institution.');
1.73      raeburn  1695:     } elsif ($error eq 'emailfail') {
                   1696:         $msg .= &mt('Creation of a new user account with verification by e-mail is not permitted with the e-mail address you provided');
1.1       raeburn  1697:     }
1.14      raeburn  1698:     $msg .= '</span>';
1.1       raeburn  1699:     if ($msgtext) {
                   1700:         $msg .= '<br />'.$msgtext;
                   1701:     }
1.44      raeburn  1702:     $msg .= &linkto_email_help($contact_email,$domdesc,$error);
1.8       raeburn  1703:     return $msg;
                   1704: }
                   1705: 
                   1706: sub linkto_email_help {
1.44      raeburn  1707:     my ($contact_email,$domdesc,$error) = @_;
1.8       raeburn  1708:     my $msg;
1.44      raeburn  1709:     my $href = '/adm/helpdesk';
1.1       raeburn  1710:     if ($contact_email ne '') {
                   1711:         my $escuri = &HTML::Entities::encode('/adm/createaccount','&<>"');
1.44      raeburn  1712:         $href .= '?origurl='.$escuri;
                   1713:         if ($error eq 'existinguser') {
                   1714:             my $escemail = &HTML::Entities::encode($env{'form.useremail'});
                   1715:             $href .= '&useremail='.$escemail.'&useraccount='.$escemail;
                   1716:         }
                   1717:         $msg .= '<br />'.&mt('You may wish to contact the [_1]LON-CAPA helpdesk[_2] for [_3].','<a href="'.$href.'">','</a>',$domdesc).'<br />';
1.1       raeburn  1718:     } else {
1.55      raeburn  1719:         $msg .= '<br />'.&mt('You may wish to send an e-mail to the server administrator: [_1] for [_2].',$Apache::lonnet::perlvar{'AdmEMail'},$domdesc).'<br />';
1.1       raeburn  1720:     }
                   1721:     return $msg;
                   1722: }
                   1723: 
                   1724: sub getkeys {
                   1725:     my ($lkey,$ukey) = @_;
                   1726:     my $lextkey=hex($lkey);
                   1727:     if ($lextkey>2147483647) { $lextkey-=4294967296; }
                   1728: 
                   1729:     my $uextkey=hex($ukey);
                   1730:     if ($uextkey>2147483647) { $uextkey-=4294967296; }
                   1731:     return ($lextkey,$uextkey);
                   1732: }
                   1733: 
                   1734: sub serverform {
1.20      raeburn  1735:     my ($logtoken,$lonhost,$mailtoken,$courseid,$context) = @_;
1.22      raeburn  1736:     my $phase = 'username_validation';
                   1737:     my $catalog_elements;
1.20      raeburn  1738:     if ($context eq 'selfenroll') {
                   1739:         $phase = 'selfenroll_login';
                   1740:     }
1.22      raeburn  1741:     if ($courseid ne '') {
                   1742:         $catalog_elements = &Apache::lonhtmlcommon::echo_form_input(['courseid','phase']);
                   1743:     } 
                   1744:     my $output = <<ENDSERVERFORM;
1.20      raeburn  1745:   <form name="server" method="post" action="/adm/createaccount">
1.1       raeburn  1746:    <input type="hidden" name="logtoken" value="$logtoken" />
                   1747:    <input type="hidden" name="token" value="$mailtoken" />
                   1748:    <input type="hidden" name="serverid" value="$lonhost" />
                   1749:    <input type="hidden" name="uname" value="" />
                   1750:    <input type="hidden" name="upass" value="" />
1.32      raeburn  1751:    <input type="hidden" name="udom" value="" />
1.20      raeburn  1752:    <input type="hidden" name="phase" value="$phase" />
1.3       raeburn  1753:    <input type="hidden" name="courseid" value="$courseid" />
1.22      raeburn  1754:    $catalog_elements
1.1       raeburn  1755:   </form>
                   1756: ENDSERVERFORM
                   1757:     return $output;
                   1758: }
                   1759: 
1.58      raeburn  1760: sub store_request {
                   1761:     my ($dom,$username,$val,$dataref,$settings) = @_;
                   1762:     my $output;
                   1763:     my $domconfiguser = &Apache::lonnet::get_domainconfiguser($dom);
                   1764:     my $key = &escape($username);
                   1765:     my $now = time();
                   1766:     if (&Apache::lonnet::put('usernamequeue', { $key.'_'.$val => $now },
                   1767:                              $dom,$domconfiguser) eq 'ok') {
                   1768:         if (ref($dataref) eq 'HASH') {
                   1769:             my $logtoken = $dataref->{'tmpinfo'};
                   1770:             my $serverid = $dataref->{'serverid'}; 
                   1771:             if ($logtoken && $serverid) {
                   1772:                 my $tmpinfo=Apache::lonnet::reply('tmpget:'.$logtoken,$serverid);
                   1773:                 unless (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost')) {
                   1774:                     my $reply = &Apache::lonnet::reply('tmpdel:'.$logtoken,$serverid);
                   1775:                     if ($reply eq 'ok') {
                   1776:                         my ($key,$caller)=split(/&/,$tmpinfo);
                   1777:                         $dataref->{'key'} = $key;
                   1778:                         undef($dataref->{'tmpinfo'});
                   1779:                         undef($dataref->{'serverid'});
                   1780:                     }
                   1781:                 }
                   1782:             }
                   1783:         }
                   1784:         my %userrequest = ( $username => $dataref );
                   1785:         $userrequest{$username}{timestamp} = $now;
                   1786:         $userrequest{$username}{status} = $val;
                   1787:         my $notifylist;
                   1788:         if (ref($settings) eq 'HASH') {
                   1789:             if (ref($settings->{'cancreate'}) eq 'HASH') {
                   1790:                 if (ref($settings->{'cancreate'}{'notify'}) eq 'HASH') {
                   1791:                     my $notifylist = $settings->{'cancreate'}{'notify'}{'approval'};
                   1792:                     if ($notifylist) {
                   1793:                         my $sender = $domconfiguser.':'.$dom;
                   1794:                         my $domdesc = &Apache::lonnet::domain($dom,'description');
                   1795:                         my $fullname;
                   1796:                         if (ref($dataref) eq 'HASH') {
                   1797:                             if ($dataref->{'firstname'}) {
                   1798:                                 $fullname = $dataref->{'firstname'};
                   1799:                             }
                   1800:                             if ($dataref->{'lastname'}) {
                   1801:                                 $fullname .= ' '.$dataref->{'lastname'};
                   1802:                             }
                   1803:                             $fullname =~ s/^\s+|\s+$//g; 
                   1804:                         }
                   1805:                         &Apache::loncoursequeueadmin::send_selfserve_notification($notifylist,
                   1806:                                                      "$fullname ($username)",
                   1807:                                                      undef,$domdesc,$now,'usernamereq',$sender);
                   1808:                     }
                   1809:                 }
                   1810:             }
1.1       raeburn  1811:         }
1.58      raeburn  1812:         my $userresult =
                   1813:             &Apache::lonnet::put('nohist_requestedusernames',\%userrequest,$dom,$domconfiguser);
                   1814:         $output = '<p class="LC_info">'.
                   1815:                   &mt('Your request for a LON-CAPA account has been submitted for approval.').
                   1816:                   '</p>'.
                   1817:                   '<p class="LC_info">'.
                   1818:                   &mt('An e-mail will be sent to [_1] when your request has been reviewed by an administrator and action has been taken.',$username).
                   1819:                   '</p>';
1.1       raeburn  1820:     } else {
1.58      raeburn  1821:         $output = '<span class="LC_error">'.
                   1822:                   &mt('An error occurred when attempting to save your request for a LON-CAPA account.');
                   1823:                   '</span>';
1.1       raeburn  1824:     }
1.58      raeburn  1825:     return $output;
1.1       raeburn  1826: }
                   1827: 
                   1828: sub guest_format_check {
1.74    ! raeburn  1829:     my ($useremail,$domain,$cancreate,$settings,$usertype) = @_;
1.1       raeburn  1830:     my ($login,$format_match,$format_msg,@user_rules);
                   1831:     if (ref($settings) eq 'HASH') {
                   1832:         if (ref($settings->{'email_rule'}) eq 'ARRAY') {
                   1833:             push(@user_rules,@{$settings->{'email_rule'}});
1.74    ! raeburn  1834:         } elsif (ref($settings->{'email_rule'}) eq 'HASH') {
        !          1835:             if (ref($settings->{'email_rule'}->{$usertype}) eq 'ARRAY') {
        !          1836:                 push(@user_rules,@{$settings->{'email_rule'}->{$usertype}});
        !          1837:             }
1.1       raeburn  1838:         }
                   1839:     }
                   1840:     if (@user_rules > 0) {
                   1841:         my %rule_check = 
                   1842:             &Apache::lonnet::inst_rulecheck($domain,$useremail,undef,
1.2       raeburn  1843:                                             'selfcreate',\@user_rules);
1.1       raeburn  1844:         if (keys(%rule_check) > 0) {
                   1845:             foreach my $item (keys(%rule_check)) {
                   1846:                 if ($rule_check{$item}) {
                   1847:                     $format_match = 1;   
                   1848:                     last;
                   1849:                 }
                   1850:             }
                   1851:         }
                   1852:     }
                   1853:     if ($format_match) {
                   1854:         ($login) = ($useremail =~ /^([^\@]+)\@/);
1.58      raeburn  1855:         $format_msg = '<br />'.
                   1856:                       &mt("Your e-mail address uses the same internet domain as your institution's LON-CAPA service.").'<br />'.
                   1857:                       &mt('Creation of a LON-CAPA account with this type of e-mail address as username is not permitted.').'<br />';
1.5       raeburn  1858:         if (ref($cancreate) eq 'ARRAY') {
                   1859:             if (grep(/^login$/,@{$cancreate})) {
1.7       bisitz   1860:                 $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  1861:             }
1.1       raeburn  1862:         }
                   1863:     }
                   1864:     return $format_msg;
                   1865: }
                   1866: 
1.17      raeburn  1867: sub sso_logout_frag {
                   1868:     my ($r,$domain) = @_;
                   1869:     my $endsessionmsg;
                   1870:     if (defined($r->dir_config('lonSSOUserLogoutMessageFile_'.$domain))) {
                   1871:         my $msgfile = $r->dir_config('lonSSOUserLogoutMessageFile_'.$domain);
                   1872:         if (-e $msgfile) {
                   1873:             open(my $fh,"<$msgfile");
                   1874:             $endsessionmsg = join('',<$fh>);
                   1875:             close($fh);
                   1876:         }
                   1877:     } elsif (defined($r->dir_config('lonSSOUserLogoutMessageFile'))) {
                   1878:         my $msgfile = $r->dir_config('lonSSOUserLogoutMessageFile');
                   1879:         if (-e $msgfile) {     
                   1880:             open(my $fh,"<$msgfile");
                   1881:             $endsessionmsg = join('',<$fh>);
                   1882:             close($fh);
                   1883:         }
                   1884:     }
                   1885:     return $endsessionmsg;
                   1886: }
                   1887: 
1.22      raeburn  1888: sub catreturn_js {
                   1889:     return  <<"ENDSCRIPT";
                   1890: <script type="text/javascript">
1.62      raeburn  1891: // <![CDATA[
1.22      raeburn  1892: function ToSelfenroll(formname) {
                   1893:     var formidx = getFormByName(formname);
                   1894:     if (formidx > -1) {
                   1895:         document.forms[formidx].action = '/adm/selfenroll';
                   1896:         numidx = getIndexByName(formidx,'phase');
                   1897:         if (numidx > -1) {
                   1898:             document.forms[formidx].elements[numidx].value = '';   
                   1899:         }
                   1900:         numidx = getIndexByName(formidx,'context');
                   1901:         if (numidx > -1) {
                   1902:             document.forms[formidx].elements[numidx].value = '';
                   1903:         }
                   1904:     }
                   1905:     document.forms[formidx].submit();
                   1906: }
                   1907: 
                   1908: function ToCatalog(formname,caller) {
                   1909:     var formidx = getFormByName(formname);
                   1910:     if (formidx > -1) {
                   1911:         document.forms[formidx].action = '/adm/coursecatalog';
                   1912:         numidx = getIndexByName(formidx,'coursenum');
                   1913:         if (numidx > -1) {
                   1914:             if (caller != 'details') {
                   1915:                 document.forms[formidx].elements[numidx].value = '';
                   1916:             }
                   1917:         }
                   1918:     }
                   1919:     document.forms[formidx].submit();
                   1920: }
                   1921: 
                   1922: function getIndexByName(formidx,item) {
                   1923:     for (var i=0;i<document.forms[formidx].elements.length;i++) {
                   1924:         if (document.forms[formidx].elements[i].name == item) {
                   1925:             return i;
                   1926:         }
                   1927:     }
                   1928:     return -1;
                   1929: }
                   1930: 
                   1931: function getFormByName(item) {
                   1932:     for (var i=0; i<document.forms.length; i++) {
                   1933:         if (document.forms[i].name == item) {
                   1934:             return i;
                   1935:         }
                   1936:     }
                   1937:     return -1;
                   1938: }
1.62      raeburn  1939: // ]]>
1.22      raeburn  1940: </script>
                   1941: ENDSCRIPT
                   1942: 
                   1943: }
                   1944: 
1.73      raeburn  1945: sub setelements_js {
                   1946:     my ($statusforemail,$types,$usertypes,$othertitle) = @_;
                   1947:     my ($posstypes,$posstypesnames,$availabletypes);
                   1948:     if ((ref($statusforemail) eq 'ARRAY') && (ref($types) eq 'ARRAY') && 
                   1949:         (ref($usertypes) eq 'HASH')) {
                   1950:         $posstypes = join("','",@{$types},'default');
                   1951:         $posstypesnames = join("','",(map {$usertypes->{$_};} @{$types}),$othertitle);
                   1952:         $availabletypes = join("','", @{$statusforemail});
                   1953:     }
                   1954:     return  <<"ENDSCRIPT";
                   1955: <script type="text/javascript">
                   1956: // <![CDATA[
                   1957: 
                   1958: function setElements() {
                   1959:     if (document.getElementById('LC_reportstatus')) {
                   1960:         var reportnum = document.reportstatus.type.length;
                   1961:         if ((reportnum != 'undefined') && (typeof(document.reportstatus.type) != 'undefined')) {
                   1962:             for (var i=0; i<reportnum; i++) {
                   1963:                 document.reportstatus.type[i].checked = false;
                   1964:             }
                   1965:         }
                   1966:     }
                   1967: }
                   1968: 
                   1969: function checkVerification() {
                   1970:     var curr;
                   1971:     var cancreate = false;
                   1972:     var reportnum = document.reportstatus.type.length;
                   1973:     if ((reportnum == 'undefined') && (typeof(document.reportstatus.type) != 'undefined')) {
                   1974:         curr = document.reportstatus.type.value; 
                   1975:     } else if (document.reportstatus.type.length) {
                   1976:         for (var i=0; i<document.reportstatus.type.length; i++) {
                   1977:             if (document.reportstatus.type[i].checked) {
                   1978:                 curr = document.reportstatus.type[i].value;
                   1979:                 break;
                   1980:             }
                   1981:         }
                   1982:     }
                   1983:     var types = Array('$posstypes');
                   1984:     var names = Array('$posstypesnames');
                   1985:     var available = Array('$availabletypes');
                   1986:     if (available.length) {
                   1987:         for (var i=0; i<available.length; i++) {
                   1988:             if (curr == available[i]) {
                   1989:                 cancreate = true;   
                   1990:                 break;
                   1991:             }
                   1992:         }
                   1993:     }
                   1994:     if (types.length > 0) {
                   1995:         for (var j=0; j<types.length; j++) {
                   1996:             if (curr == types[j]) {
                   1997:                 if (!cancreate) {
                   1998:                     alert('Creation of an account via verification by e-mail unavailable for user type: "'+names[j]+'"');
                   1999:                 }
                   2000:                 break;
                   2001:             }
                   2002:         }
                   2003:     }
                   2004:     if (cancreate) {
                   2005:         return true;
                   2006:     } else {
                   2007:         return false;
                   2008:     }
                   2009: }
                   2010: 
                   2011: // ]]>
                   2012: </script>
                   2013: ENDSCRIPT
                   2014: 
                   2015: }
                   2016: 
                   2017: sub username_js {
                   2018:     return  <<"ENDSCRIPT";
                   2019: <script type="text/javascript">
                   2020: // <![CDATA[
                   2021: 
1.74    ! raeburn  2022: function toggleUsernameDisp(caller,divid) {
1.73      raeburn  2023:     if (document.getElementById(divid)) {
                   2024:         if (caller.checked) {
                   2025:             if (caller.value == '1') {
                   2026:                 document.getElementById(divid).style.display = 'none';
                   2027:             } else {
                   2028:                 document.getElementById(divid).style.display = 'inline';
                   2029:             }
                   2030:         }
                   2031:     }
                   2032: }
                   2033: // ]]>
                   2034: </script>
                   2035: ENDSCRIPT
                   2036: 
                   2037: }
                   2038: 
1.1       raeburn  2039: 1;

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