File:  [LON-CAPA] / loncom / interface / createaccount.pm
Revision 1.78: download - view: text, annotated - select for diffs
Sun May 5 23:19:47 2019 UTC (5 years ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Response to incorrect Captcha on account creation page is to display a page
  containing a link back to the form, instead of a call to &invalid_state().
- Rules for length and/or characters in a LON-CAPA password (internal auth)
  checked server-side when a user self-creates a user account.
  - rule-checking code moved from lonpreferences.pm to loncommon.pm to
    facilitate reuse.

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

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