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

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

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