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

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

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