File:  [LON-CAPA] / loncom / interface / createaccount.pm
Revision 1.88: download - view: text, annotated - select for diffs
Fri Nov 3 01:12:15 2023 UTC (6 months, 2 weeks ago) by raeburn
Branches: MAIN
CVS tags: version_2_12_X, HEAD
- Authoring Space defaults defaults which domain coordinator can override.
  - Available Editors, WebDAV access, Disk Quota for Authoring Space
    can be set for specific users by DC via "Add/modify user"
- Bug 5273 Co-authors in "group authoring" accounts can manage co-authors
  - Existing co-author(s) can be assigned rights to add/revoke co-author
    roles. Can be set by DC via "Add/modify user" or by author via "People"
- Co-authors and Assistant co-authors can view a list of co-authors for
  the Authoring Space. Availability set by Author or Co-author "manager".
  Listing can be set to "opt-in".

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

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