File:  [LON-CAPA] / loncom / interface / createaccount.pm
Revision 1.72.4.6: download - view: text, annotated - select for diffs
Mon Jan 4 04:42:13 2021 UTC (3 years, 5 months ago) by raeburn
Branches: version_2_11_X
CVS tags: version_2_11_3_uiuc, version_2_11_3_msu, version_2_11_3
Diff to branchpoint 1.72: preferred, unified
- For 2.11
  Backport 1.82

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

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