File:  [LON-CAPA] / loncom / interface / createaccount.pm
Revision 1.76: download - view: text, annotated - select for diffs
Sun Nov 12 20:42:52 2017 UTC (6 years, 6 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Use three-argument open() to separate file mode from the filename.

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

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