File:  [LON-CAPA] / loncom / interface / createaccount.pm
Revision 1.90: download - view: text, annotated - select for diffs
Tue Feb 18 17:45:11 2025 UTC (3 days ago) by raeburn
Branches: MAIN
CVS tags: version_2_12_X, HEAD
- Following changes in rev. 1.73, if account creation available for both
  institutional authentication and e-mail address based verification, londes.js
  is needed (separately) for login form when "Choose your affiliation" box
  displayed for e-mail users.

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

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