File:  [LON-CAPA] / loncom / interface / createaccount.pm
Revision 1.72.2.1: download - view: text, annotated - select for diffs
Thu Nov 16 23:38:40 2017 UTC (6 years, 5 months ago) by raeburn
Branches: version_2_11_2_msu
Diff to branchpoint 1.72: preferred, unified
- For 2.11.2 (modified)
  - Include changes in rev. 1.76.

    1: # The LearningOnline Network
    2: # Allow visitors to create a user account with the username being either an 
    3: # institutional log-in ID (institutional authentication required - localauth,
    4: # kerberos, or SSO) or an e-mail address. Requests to use an e-mail address as
    5: # username may be processed automatically, or may be queued for approval.
    6: #
    7: # $Id: createaccount.pm,v 1.72.2.1 2017/11/16 23:38:40 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,$emailusername) = 
  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:     $start_page = &Apache::loncommon::start_page($title,$js);
  150: 
  151:     my %domconfig = 
  152:         &Apache::lonnet::get_dom('configuration',['usercreation'],$domain);
  153:     my ($cancreate,$statustocreate,$emailusername) = 
  154:         &get_creation_controls($domain,$domconfig{'usercreation'});
  155:     if (@{$cancreate} == 0) {
  156:         &print_header($r,$start_page,$courseid);
  157:         my $output = '<h3>'.&mt('Account creation unavailable').'</h3>'.
  158:                      '<span class="LC_warning">'.
  159:                      &mt('Creation of a new user account using an e-mail address or an institutional log-in ID as username is not permitted at this institution ([_1]).',$domdesc).
  160:                      '</span><br /><br />';
  161:         $r->print($output);
  162:         &print_footer($r);
  163:         return OK;
  164:     }
  165: 
  166:     if ($sso_username ne '') {
  167:         &print_header($r,$start_page,$courseid);
  168:         my ($msg,$sso_logout);
  169:         $sso_logout = &sso_logout_frag($r,$domain);
  170:         if (grep(/^sso$/,@{$cancreate})) {
  171:             $msg = '<h3>'.&mt('Account creation').'</h3>'.
  172:                    &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 />';
  173:             my $shibenv;
  174:             if (($r->dir_config('lonOtherAuthen') eq 'yes') && 
  175:                 ($r->dir_config('lonOtherAuthenType') eq 'Shibboleth')) {
  176:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
  177:                     if (ref($domconfig{'usercreation'}{'cancreate'}) eq 'HASH') {
  178:                         if (ref($domconfig{'usercreation'}{'cancreate'}{'shibenv'}) eq 'HASH') {
  179:                             my @possfields = ('firstname','middlename','lastname','generation',
  180:                                               'permanentemail','id');
  181:                             my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($domain);
  182:                             $shibenv= {};
  183:                             foreach my $key (keys(%{$domconfig{'usercreation'}{'cancreate'}{'shibenv'}})) {
  184:                                 if ($key eq 'inststatus') {
  185:                                     if (ref($usertypes) eq 'HASH') {
  186:                                         if ($domconfig{'usercreation'}{'cancreate'}{'shibenv'}{$key} ne '') {
  187:                                             if (exists($usertypes->{$domconfig{'usercreation'}{'cancreate'}{'shibenv'}{$key}})) {
  188:                                                 $shibenv->{$key} = $domconfig{'usercreation'}{'cancreate'}{'shibenv'}{$key};
  189:                                              }
  190:                                         }
  191:                                     }
  192:                                 } elsif (grep(/^\Q$key\E/,@possfields)) {
  193:                                     if ($domconfig{'usercreation'}{'cancreate'}{'shibenv'}{$key} ne '') {
  194:                                         $shibenv->{$key} = $domconfig{'usercreation'}{'cancreate'}{'shibenv'}{$key};
  195:                                     }
  196:                                 }
  197:                             }
  198:                         }
  199:                     }
  200:                 }
  201:             }
  202:             $msg .= &username_check($sso_username,$domain,$domdesc,$courseid, 
  203:                                     $lonhost,$contact_email,$contact_name,
  204:                                     $sso_logout,$statustocreate,$shibenv);
  205:         } else {
  206:             $msg = '<h3>'.&mt('Account creation unavailable').'</h3>'.
  207:                    '<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 />'.
  208:                    $sso_logout;
  209:         }
  210:         $r->print($msg);
  211:         &print_footer($r);
  212:         return OK;
  213:     }
  214: 
  215:     my ($output,$nostart,$noend,$redirect);
  216:     my $token = $env{'form.token'};
  217:     if ($token) {
  218:         my $usertype = &get_usertype($domain);
  219:         ($output,$nostart,$noend,$redirect) = 
  220:             &process_mailtoken($r,$token,$contact_name,$contact_email,$domain,
  221:                                $domdesc,$lonhost,$include,$start_page,$cancreate,
  222:                                $domconfig{'usercreation'},$usertype);
  223:         if ($redirect) {
  224:             $r->internal_redirect('/adm/switchserver');
  225:             return OK;
  226:         } elsif ($nostart) {
  227:             if ($noend) {
  228:                 return OK;
  229:             } else {
  230:                 $r->print($output);
  231:                 &print_footer($r);
  232:                 return OK;
  233:             }
  234:         } else {
  235:             &print_header($r,$start_page,$courseid);
  236:             $r->print($output);
  237:             &print_footer($r);
  238:             return OK;
  239:         }
  240:     }
  241: 
  242:     if ($env{'form.phase'} eq 'username_activation') {
  243:         (my $result,$output,$nostart) = 
  244:             &username_activation($r,$env{'form.uname'},$domain,$domdesc,
  245:                                  $courseid);
  246:         if ($result eq 'redirect') {
  247:             $r->internal_redirect('/adm/switchserver');
  248:             return OK; 
  249:         } elsif ($result eq 'ok') {
  250:             if ($nostart) {
  251:                 return OK;
  252:             }
  253:         }
  254:         &print_header($r,$start_page,$courseid);
  255:         $r->print($output);
  256:         &print_footer($r);
  257:         return OK;
  258:     } elsif ($env{'form.phase'} eq 'username_validation') { 
  259:         (my $result,$output) = 
  260:             &username_validation($r,$env{'form.uname'},$domain,$domdesc,
  261:                                  $contact_name,$contact_email,$courseid,
  262:                                  $lonhost,$statustocreate);
  263:         if ($result eq 'existingaccount') {
  264:             $r->print($output);
  265:             &print_footer($r);
  266:             return OK;
  267:         } else {
  268:             &print_header($r,$start_page,$courseid);
  269:         }
  270:     } elsif ($env{'form.create_with_email'}) {
  271:         &print_header($r,$start_page,$courseid);
  272:         my $usertype = &get_usertype($domain);
  273:         $output = &process_email_request($env{'form.uname'},$domain,$domdesc,
  274:                                          $contact_name,$contact_email,$cancreate,
  275:                                          $lonhost,$domconfig{'usercreation'},
  276:                                          $emailusername,$courseid,$usertype);
  277:     } elsif (!$token) {
  278:         &print_header($r,$start_page,$courseid);
  279:         my $now=time;
  280:         if ((grep(/^login$/,@{$cancreate})) && (!grep(/^email$/,@{$cancreate}))) {
  281:             if (open(my $jsh,"<","$include/londes.js")) {
  282:                 while(my $line = <$jsh>) {
  283:                     $r->print($line);
  284:                 }
  285:                 close($jsh);
  286:                 $r->print(&javascript_setforms($now));
  287:             }
  288:         }
  289:         if (grep(/^email$/,@{$cancreate})) {
  290:             $r->print(&javascript_validmail());
  291:         }
  292:         my $usertype = &get_usertype($domain);
  293:         $output = &print_username_form($r,$domain,$domdesc,$cancreate,$now,$lonhost,
  294:                                        $include,$courseid,$emailusername,$usertype);
  295:     }
  296:     $r->print($output);
  297:     &print_footer($r);
  298:     return OK;
  299: }
  300: 
  301: sub print_header {
  302:     my ($r,$start_page,$courseid) = @_;
  303:     $r->print($start_page);
  304:     &Apache::lonhtmlcommon::clear_breadcrumbs();
  305:     if ($courseid ne '') {
  306:         my %coursehash = &Apache::lonnet::coursedescription($courseid);
  307:         &selfenroll_crumbs($r,$courseid,$coursehash{'description'});
  308:     }
  309:     &Apache::lonhtmlcommon::add_breadcrumb
  310:     ({href=>"/adm/createuser",
  311:       text=>"New username"});
  312:     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Create account'));
  313:     return;
  314: }
  315: 
  316: sub print_footer {
  317:     my ($r) = @_;
  318:     if ($env{'form.courseid'} ne '') {
  319:         $r->print('<form name="backupcrumbs" method="post" action="">'.
  320:                   &Apache::lonhtmlcommon::echo_form_input(['backto','logtoken',
  321:                       'token','serverid','uname','upass','phase','create_with_email',
  322:                       'code','crypt','cfirstname','clastname','g-recaptcha-response',
  323:                       'recaptcha_challenge_field','recaptcha_response_field',
  324:                       'cmiddlename','cgeneration','cpermanentemail','cid']).
  325:                   '</form>');
  326:     }
  327:     $r->print(&Apache::loncommon::end_page());
  328: }
  329: 
  330: sub get_usertype {
  331:     my ($domain) = @_;
  332:     my $usertype = 'default';
  333:     my ($othertitle,$usertypes,$types) = &Apache::loncommon::sorted_inst_types($domain);
  334:     if (ref($types) eq 'ARRAY') {
  335:         push(@{$types},'default');
  336:         my $posstype = $env{'form.type'};
  337:         $posstype =~ s/^\s+|\s$//g;
  338:         if (grep(/^\Q$posstype\E$/,@{$types})) {
  339:             $usertype = $posstype;
  340:         }
  341:     }
  342:     return $usertype;
  343: }
  344: 
  345: sub selfenroll_crumbs {
  346:     my ($r,$courseid,$desc) = @_;
  347:     &Apache::lonhtmlcommon::add_breadcrumb
  348:          ({href=>"javascript:ToCatalog('backupcrumbs','')",
  349:            text=>"Course/Community Catalog"});
  350:     if ($env{'form.coursenum'} ne '') {
  351:         &Apache::lonhtmlcommon::add_breadcrumb
  352:           ({href=>"javascript:ToCatalog('backupcrumbs','details')",
  353:             text=>"Course details"});
  354:     }
  355:     my $last_crumb;
  356:     if ($desc ne '') {
  357:         $last_crumb = &mt("Self-enroll in [_1]","'$desc'");
  358:     } else {
  359:         $last_crumb = &mt('Self-enroll');
  360:     }
  361:     &Apache::lonhtmlcommon::add_breadcrumb
  362:                    ({href=>"javascript:ToSelfenroll('backupcrumbs')",
  363:                      text=>$last_crumb,
  364:                      no_mt=>"1"});
  365:     return;
  366: }
  367: 
  368: sub javascript_setforms {
  369:     my ($now,$emailusername,$captcha,$usertype,$recaptchaversion) =  @_;
  370:     my ($setuserinfo,@required,$requiredchk);
  371:     if (ref($emailusername) eq 'HASH') {
  372:         if (ref($emailusername->{$usertype}) eq 'HASH') {  
  373:             foreach my $key (sort(keys(%{$emailusername->{$usertype}}))) {
  374:                 if ($emailusername->{$usertype}{$key} eq 'required') {
  375:                     push(@required,$key); 
  376:                 }
  377:                 $setuserinfo .= '                    server.elements.'.$key.'.value=client.elements.'.$key.'.value;'."\n";
  378:             }
  379:             $setuserinfo .= '                    server.elements.type.value=client.elements.type.value;'."\n"; 
  380:         }
  381:         if ($captcha eq 'original') {
  382:             $setuserinfo .= '                    server.elements.code.value=client.elements.code.value;'."\n".
  383:                             '                    server.elements.crypt.value=client.elements.crypt.value;'."\n";
  384:         } elsif ($captcha eq 'recaptcha') {
  385:             if ($recaptchaversion ne '2') {
  386:                 $setuserinfo .=
  387:                 '                    server.elements.recaptcha_challenge_field.value=client.elements.recaptcha_challenge_field.value;'."\n".
  388:                 '                    server.elements.recaptcha_response_field.value=client.elements.recaptcha_response_field.value;'."\n";
  389:             }
  390:         }
  391:     }
  392:     if (@required) {
  393:         my $missprompt = &mt('One or more required fields are currently blank.');
  394:         &js_escape(\$missprompt);
  395:         my $reqstr = join("','",@required);
  396:         $requiredchk = <<"ENDCHK";
  397:                 var requiredfields = new Array('$reqstr');
  398:                 missing = 0; 
  399:                 for (var i=0; i<requiredfields.length; i++) {
  400:                     try {
  401:                         eval("client.elements."+requiredfields[i]+".value");
  402:                     }
  403:                     catch(err) {
  404:                         continue;
  405:                     }
  406:                     if (eval("client.elements."+requiredfields[i]+".value") == '') {
  407:                         missing ++;
  408:                     }
  409:                 }
  410:                 if (missing > 0) {
  411:                     alert("$missprompt");
  412:                     return false;
  413:                 }
  414: 
  415: ENDCHK
  416:     }
  417:     my $js = <<ENDSCRIPT;
  418: <script type="text/javascript">
  419: // <![CDATA[
  420:     function send(one,two,context) {
  421:         var server;
  422:         var client;
  423:         if (document.forms[one]) {
  424:             server = document.forms[one];
  425:             if (document.forms[two]) {
  426:                 client = document.forms[two];
  427: $requiredchk
  428:                 server.elements.uname.value = client.elements.uname.value;
  429:                 server.elements.udom.value = client.elements.udom.value;
  430: 
  431:                 uextkey=client.elements.uextkey.value;
  432:                 lextkey=client.elements.lextkey.value;
  433:                 initkeys();
  434: 
  435:                 server.elements.upass.value
  436:                     = getCrypted(client.elements.upass$now.value);
  437: 
  438:                 client.elements.uname.value='';
  439:                 client.elements.upass$now.value='';
  440:                 if (context == 'email') {
  441: $setuserinfo
  442:                     client.elements.upasscheck$now.value='';
  443:                 }
  444:                 server.submit();
  445:             }
  446:         }
  447:         return false;
  448:     }
  449: 
  450: // ]]>
  451: </script>
  452: ENDSCRIPT
  453:     if (($captcha eq 'recaptcha') && ($recaptchaversion eq '2')) {
  454:         $js .= "\n".'<script src="https://www.google.com/recaptcha/api.js"></script>'."\n";
  455:     }
  456:     return $js;
  457: }
  458: 
  459: sub javascript_checkpass {
  460:     my ($now,$context) = @_;
  461:     my $nopass = &mt('You must enter a password.');
  462:     my $mismatchpass = &mt('The passwords you entered did not match.')."\n".
  463:                        &mt('Please try again.'); 
  464:     &js_escape(\$nopass);
  465:     &js_escape(\$mismatchpass);
  466:     my $js = <<"ENDSCRIPT";
  467: <script type="text/javascript">
  468: // <![CDATA[
  469:     function checkpass(one,two) {
  470:         var client;
  471:         if (document.forms[two]) {
  472:             client = document.forms[two]; 
  473:             var upass = client.elements.upass$now.value;
  474:             var upasscheck = client.elements.upasscheck$now.value;
  475:             if (upass == '') {
  476:                 alert("$nopass");
  477:                 return false;
  478:             }
  479:             if (upass == upasscheck) {
  480:                 client.elements.upasscheck$now.value='';
  481:                 if (validate_email(client)) {
  482:                     send(one,two,'$context');
  483:                 } 
  484:                 return false;
  485:             } else {
  486:                 alert("$mismatchpass");
  487:                 return false;
  488:             }
  489:         }
  490:         return false; 
  491:     }
  492: // ]]>
  493: </script>
  494: ENDSCRIPT
  495:     return $js;
  496: }
  497: 
  498: sub javascript_validmail {
  499:     my %js_lt = &Apache::lonlocal::texthash (
  500:                email => 'The e-mail address you entered',
  501:                notv  => 'is not a valid e-mail address',
  502:     );
  503:     my $output =  "\n".'<script type="text/javascript">'."\n".
  504:                   '// <![CDATA['."\n".
  505:                   &Apache::lonhtmlcommon::javascript_valid_email()."\n";
  506:     &js_escape(\%js_lt);
  507:     $output .= <<"ENDSCRIPT";
  508: function validate_email(client) {
  509:     field = client.uname;
  510:     if (validmail(field) == false) {
  511:         alert("$js_lt{'email'}: "+field.value+" $js_lt{'notv'}.");
  512:         return false;
  513:     }
  514:     return true;
  515: }
  516: ENDSCRIPT
  517:     $output .= "\n".'// ]]>'."\n".'</script>'."\n";
  518:     return $output;
  519: }
  520: 
  521: sub print_username_form {
  522:     my ($r,$domain,$domdesc,$cancreate,$now,$lonhost,$include,$courseid,$emailusername,
  523:         $usertype) = @_;
  524:     my %lt = &Apache::lonlocal::texthash (
  525:                                          unam => 'username',
  526:                                          udom => 'domain',
  527:                                          uemail => 'E-mail address in LON-CAPA',
  528:                                          proc => 'Proceed',
  529:                                          crac => 'Create account with a username provided by this institution',
  530:                                          clca => 'Create LON-CAPA account',
  531:                                          type => 'Type in your log-in ID and password to find out.',
  532:                                          plse => 'Please provide a password for your new account.',
  533:                                          info => 'Please provide user information and a password for your new account.',
  534:                                          yopw => 'Your password will be encrypted when sent (and stored).',
  535:                                          );
  536:     my $output;
  537:     if (ref($cancreate) eq 'ARRAY') {
  538:         if (grep(/^login$/,@{$cancreate})) {
  539:             my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
  540:             if ((($domdefaults{'auth_def'} =~/^krb/) && ($domdefaults{'auth_arg_def'} ne '')) || ($domdefaults{'auth_def'} eq 'localauth')) {
  541:                 $output = '<div class="LC_left_float"><h3>'.$lt{'crac'}.'</h3>';
  542:                 $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 />').
  543:                            '<br /><br />'.
  544:                            $lt{'type'}.
  545:                            '<br /><br />';
  546:                 $output .= &login_box($now,$lonhost,$courseid,$lt{'clca'},
  547:                                       $domain,'createaccount').'</div>';
  548:             }
  549:         }
  550:         if (grep(/^email$/,@{$cancreate})) {
  551:             $output .= '<div class="LC_left_float"><h3>'.&mt('Create account with an e-mail address as your username').'</h3>';
  552:             my ($captchaform,$error,$captcha,$recaptchaversion) = 
  553:                 &Apache::loncommon::captcha_display('usercreation',$lonhost);
  554:             if ($error) {
  555:                 my $helpdesk = '/adm/helpdesk?origurl=%2fadm%2fcreateaccount';
  556:                 if ($courseid ne '') {
  557:                     $helpdesk .= '&courseid='.$courseid;
  558:                 }
  559:                 $output .= '<span class="LC_error">'.
  560:                            &mt('An error occurred generating the validation code[_1] required for an e-mail address to be used as username.','<br />').
  561:                            '</span><br /><br />'.
  562:                            &mt('[_1]Contact the helpdesk[_2] or [_3]reload[_2] the page and try again.',
  563:                                '<a href="'.$helpdesk.'">','</a>','<a href="javascript:window.location.reload()">');
  564:             } else {
  565:                 if (grep(/^login$/,@{$cancreate})) {
  566:                     $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 />'.
  567:                                $lt{'plse'}.'<br />'.
  568:                                $lt{'yopw'}.'<br />';
  569:                 } else {
  570:                     my $prompt = $lt{'plse'};
  571:                     if (ref($emailusername) eq 'HASH') {
  572:                         if (ref($emailusername->{$usertype}) eq 'HASH') {
  573:                             if (keys(%{$emailusername->{$usertype}}) > 0) {
  574:                                 $prompt = $lt{'info'};
  575:                             }
  576:                         }
  577:                     }
  578:                     $output .= $prompt.'<br />'.
  579:                                $lt{'yopw'}.'<br />';
  580:                 }
  581:                 $output .= &print_dataentry_form($r,$domain,$lonhost,$include,$now,$captchaform,
  582:                                                  $courseid,$emailusername,$captcha,$usertype,
  583:                                                  $recaptchaversion);
  584:             }
  585:             $output .= '</div>';
  586:         }
  587:     }
  588:     if ($output eq '') {
  589:         $output = &mt('Creation of a new LON-CAPA user account using an e-mail address or an institutional log-in ID as your username is not permitted at [_1].',$domdesc);
  590:     } else {
  591:         $output .= '<div class="LC_clear_float_footer"></div>';
  592:     }
  593:     return $output;
  594: }
  595: 
  596: sub login_box {
  597:     my ($now,$lonhost,$courseid,$submit_text,$domain,$context) = @_;
  598:     my $output;
  599:     my %titles = &Apache::lonlocal::texthash(
  600:                                               createaccount => 'Log-in ID',
  601:                                               selfenroll    => 'Username',
  602:                                             );
  603:     my ($lkey,$ukey) = &Apache::loncommon::des_keys();
  604:     my ($lextkey,$uextkey) = &getkeys($lkey,$ukey);
  605:     my $logtoken=Apache::lonnet::reply('tmpput:'.$ukey.$lkey.'&createaccount:createaccount',
  606:                                        $lonhost);
  607:     $output = &serverform($logtoken,$lonhost,undef,$courseid,$context);
  608:     my $unameform = '<input type="text" name="uname" size="20" value="" autocomplete="off" />';
  609:     my $upassform = '<input type="password" name="upass'.$now.'" size="20" autocomplete="off" />';
  610:     $output .= '<form name="client" method="post" action="" onsubmit="return(send('."'server','client'".'));">'."\n".
  611:                &Apache::lonhtmlcommon::start_pick_box()."\n".
  612:                &Apache::lonhtmlcommon::row_title($titles{$context},
  613:                                                  'LC_pick_box_title')."\n".
  614:                $unameform."\n".
  615:                &Apache::lonhtmlcommon::row_closure(1)."\n".
  616:                &Apache::lonhtmlcommon::row_title(&mt('Password'),
  617:                                                 'LC_pick_box_title')."\n".
  618:                $upassform;
  619:     if ($context eq 'selfenroll') {
  620:         my $udomform = '<input type="text" name="udom" size="10" value="'.
  621:                         $domain.'" />';
  622:         $output .= &Apache::lonhtmlcommon::row_closure(1)."\n".
  623:                    &Apache::lonhtmlcommon::row_title(&mt('Domain'),
  624:                                                      'LC_pick_box_title')."\n".
  625:                    $udomform."\n";
  626:     } else {
  627:         $output .= '<input type="hidden" name="udom" value="'.$domain.'" />';
  628:     }
  629:     $output .= &Apache::lonhtmlcommon::row_closure(1).
  630:                &Apache::lonhtmlcommon::row_title().
  631:                '<br /><input type="submit" name="username_validation" value="'.
  632:                $submit_text.'" />'."\n";
  633:     if ($context eq 'selfenroll') {
  634:         $output .= '<br /><br /><table width="100%"><tr><td align="right">'.
  635:                    '<span class="LC_fontsize_medium">'.
  636:                    '<a href="/adm/resetpw">'.&mt('Forgot password?').'</a>'.
  637:                    '</span></td></tr></table>'."\n";
  638:     }
  639:     $output .= &Apache::lonhtmlcommon::row_closure(1)."\n".
  640:                &Apache::lonhtmlcommon::end_pick_box().'<br />'."\n";
  641:     $output .= '<input type="hidden" name="lextkey" value="'.$lextkey.'" />'."\n".
  642:                '<input type="hidden" name="uextkey" value="'.$uextkey.'" />'."\n".
  643:                '</form>';
  644:     return $output;
  645: }
  646: 
  647: sub process_email_request {
  648:     my ($useremail,$domain,$domdesc,$contact_name,$contact_email,$cancreate,
  649:         $server,$settings,$emailusername,$courseid,$usertype) = @_;
  650:     my $output;
  651:     if (ref($cancreate) eq 'ARRAY') {
  652:         if (!grep(/^email$/,@{$cancreate})) {
  653:             $output = &invalid_state('noemails',$domdesc,
  654:                                      $contact_name,$contact_email);
  655:             return $output;
  656:         } elsif ($useremail !~ /^[^\@]+\@[^\@]+\.[^\@\.]+$/) {
  657:             $output = &invalid_state('baduseremail',$domdesc,
  658:                                      $contact_name,$contact_email);
  659:             return $output;
  660:         } else {
  661:             $useremail =~ s/^\s+|\s+$//g;
  662:             my $uname=&LONCAPA::clean_username($useremail);
  663:             if ($useremail ne $uname) {
  664:                 $output = &invalid_state('badusername',$domdesc,
  665:                                          $contact_name,$contact_email);
  666:                 return $output;
  667:             }
  668:             my $uhome = &Apache::lonnet::homeserver($useremail,$domain);
  669:             if ($uhome ne 'no_host') {
  670:                 $output = &invalid_state('existinguser',$domdesc,
  671:                                          $contact_name,$contact_email);
  672:                 return $output;
  673:             } else {
  674:                 my ($captcha_chk,$captcha_error) = &Apache::loncommon::captcha_response('usercreation',$server);
  675:                 if ($captcha_chk != 1) {
  676:                     $output = &invalid_state('captcha',$domdesc,$contact_name,
  677:                                              $contact_email,$captcha_error);
  678:                     return $output;
  679:                 }
  680:                 my (%rulematch,%inst_results,%curr_rules,%got_rules,%alerts);
  681:                 &call_rulecheck($useremail,$domain,\%alerts,\%rulematch,
  682:                                 \%inst_results,\%curr_rules,\%got_rules,'username');
  683:                 if (ref($alerts{'username'}) eq 'HASH') {
  684:                     if (ref($alerts{'username'}{$domain}) eq 'HASH') {
  685:                         if ($alerts{'username'}{$domain}{$useremail}) {
  686:                             $output = &invalid_state('userrules',$domdesc,
  687:                                                      $contact_name,$contact_email);
  688:                             return $output;
  689:                         }
  690:                     }
  691:                 }
  692:                 my $format_msg = 
  693:                     &guest_format_check($useremail,$domain,$cancreate,
  694:                                         $settings);
  695:                 if ($format_msg) {
  696:                     $output = &invalid_state('userformat',$domdesc,$contact_name,
  697:                                              $contact_email,$format_msg);
  698:                     return $output;
  699:                 }
  700:             }
  701:         }
  702:         $output = &send_token($domain,$useremail,$server,$domdesc,$contact_name,
  703:                               $contact_email,$courseid,$emailusername,$usertype);
  704:     }
  705:     return $output;
  706: }
  707: 
  708: sub call_rulecheck {
  709:     my ($uname,$udom,$alerts,$rulematch,$inst_results,$curr_rules,
  710:         $got_rules,$tocheck) = @_;
  711:     my ($checkhash,$checks);
  712:     $checkhash->{$uname.':'.$udom} = { 'newuser' => 1, };
  713:     if ($tocheck eq 'username') {
  714:         $checks = { 'username' => 1 };
  715:     }
  716:     &Apache::loncommon::user_rule_check($checkhash,$checks,
  717:            $alerts,$rulematch,$inst_results,$curr_rules,
  718:            $got_rules);
  719:     return;
  720: }
  721: 
  722: sub send_token {
  723:     my ($domain,$email,$server,$domdesc,$contact_name,$contact_email,$courseid,$emailusername,
  724:         $usertype) = @_;
  725:     my $msg = '<h3>'.&mt('Account creation status').'</h3>'.
  726:               &mt('Thank you for your request to create a new LON-CAPA account.').
  727:               '<br /><br />';
  728:     my $now = time;
  729:     $env{'form.logtoken'} =~ s/(`)//g;
  730:     if ($env{'form.logtoken'}) {
  731:         my $logtoken = $env{'form.logtoken'};
  732:         my $tmpinfo=Apache::lonnet::reply('tmpget:'.$logtoken,$server);
  733:         if (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost')) {
  734:             $msg = &mt('Information needed to process your request is missing, inaccessible or expired.')
  735:                   .'<br />'.&mt('Return to the previous page to try again.');
  736:         } else {
  737:             my $reply = &Apache::lonnet::reply('tmpdel:'.$logtoken,$server);
  738:             unless ($reply eq 'ok') {
  739:                 $msg .= &mt('Request could not be processed.');
  740:             }
  741:         }
  742:         my %info = ('ip'         => $ENV{'REMOTE_ADDR'},
  743:                     'time'       => $now,
  744:                     'domain'     => $domain,
  745:                     'username'   => $email,
  746:                     'courseid'   => $courseid,
  747:                     'upass'      => $env{'form.upass'},
  748:                     'serverid'   => $env{'form.serverid'},
  749:                     'tmpinfo'    => $tmpinfo);
  750: 
  751:         if (ref($emailusername) eq 'HASH') {
  752:             if (ref($emailusername->{$usertype}) eq 'HASH') {
  753:                 foreach my $item (keys(%{$emailusername->{$usertype}})) {
  754:                     $info{$item} = $env{'form.'.$item};
  755:                     $info{$item} =~ s/(`)//g;
  756:                 }
  757:                 unless ($usertype eq 'default') {
  758:                     $info{'inststatus'} = $usertype;
  759:                 }
  760:             }
  761:         }
  762:         my $token = &Apache::lonnet::tmpput(\%info,$server,'createaccount');
  763:         if ($token !~ /^error/ && $token ne 'no_such_host') {
  764:             my $esc_token = &escape($token);
  765:             my $showtime = localtime(time);
  766:             my $mailmsg = &mt('A request was submitted on [_1] for creation of a LON-CAPA account at the following institution: [_2].',$showtime,$domdesc).' '.
  767:                           &mt('To complete this process please open a web browser and enter the following URL in the address/location box: [_1]',
  768:                           &Apache::lonnet::absolute_url().'/adm/createaccount?token='.$esc_token);
  769:             my $result = &Apache::resetpw::send_mail($domdesc,$email,$mailmsg,$contact_name,
  770:                                                      $contact_email);
  771:             if ($result eq 'ok') {
  772:                 $msg .= &mt('A message has been sent to the e-mail address you provided.').'<br />'.
  773:                         &mt('The message includes the web address for the link you will use to complete the account creation process.').'<br />'.
  774:                         &mt("The link included in the message will be valid for the next [_1]two[_2] hours.",'<b>','</b>');
  775:             } else {
  776:                 $msg .= '<span class="LC_error">'.
  777:                         &mt('An error occurred when sending a message to the e-mail address you provided.').'</span><br />'.
  778:                         ' '.&mt('Please contact the [_1] ([_2]) for assistance.',$contact_name,$contact_email);
  779:             }
  780:         } else {
  781:             $msg .= '<span class="LC_error">'.
  782:                     &mt('An error occurred creating a token required for the account creation process.').'</span><br />'.
  783:                     ' '.&mt('Please contact the [_1] ([_2]) for assistance.',$contact_name,$contact_email);
  784:         }
  785:     } else {
  786:         $msg .=  $msg = &mt('Information needed to process your request is missing, inaccessible or expired.')
  787:                 .'<br />'.&mt('Return to the previous page to try again.');
  788: 
  789:     }
  790:     return $msg;
  791: }
  792: 
  793: sub process_mailtoken {
  794:     my ($r,$token,$contact_name,$contact_email,$domain,$domdesc,$lonhost,
  795:         $include,$start_page,$cancreate,$settings,$usertype) = @_;
  796:     my ($msg,$nostart,$noend,$redirect);
  797:     my %data = &Apache::lonnet::tmpget($token);
  798:     my $now = time;
  799:     if (keys(%data) == 0) {
  800:         $msg = &mt('Sorry, the URL you provided to complete creation of a new LON-CAPA account was invalid.')
  801:                .' '.&mt('Either the token included in the URL has been deleted or the URL you provided was invalid.')
  802:                .' '.&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.',
  803:                         '<a href="/adm/createaccount">','</a>');
  804:         return $msg;
  805:     }
  806:     if (($data{'time'} =~ /^\d+$/) &&
  807:         ($data{'domain'} ne '') &&
  808:         ($data{'username'}  =~ /^[^\@]+\@[^\@]+\.[^\@\.]+$/)) {
  809:         if ($now - $data{'time'} < 7200) {
  810: # Check if request should be queued.
  811:             if (ref($cancreate) eq 'ARRAY') {
  812:                 my $disposition;
  813:                 if (grep(/^email$/,@{$cancreate})) {
  814:                     if (ref($settings) eq 'HASH') {
  815:                         if (ref($settings->{'cancreate'}) eq 'HASH') {
  816:                             if (ref($settings->{'cancreate'}{'selfcreateprocessing'}) eq 'HASH') {
  817:                                 $disposition = $settings->{'cancreate'}{'selfcreateprocessing'}{$usertype}; 
  818:                             }
  819:                         }
  820:                     }
  821:                     if ($disposition eq 'approval') {
  822:                         $msg = &store_request($domain,$data{'username'},'approval',\%data,$settings);
  823:                         my $delete = &Apache::lonnet::tmpdel($token);
  824:                     } else {
  825:                         my ($result,$output,$uhome) = 
  826:                             &create_account($r,$domain,$domdesc,\%data);
  827:                         if ($result eq 'ok') {
  828:                             $msg = $output;
  829:                             my $shownow = &Apache::lonlocal::locallocaltime($now);
  830:                             my $mailmsg = &mt('A LON-CAPA account for the institution: [_1] has been created [_2] from IP address: [_3]. If you did not perform this action or authorize it, please contact the [_4] ([_5]).',$domdesc,$shownow,$ENV{'REMOTE_ADDR'},$contact_name,$contact_email)."\n";
  831:                             my $mailresult = &Apache::resetpw::send_mail($domdesc,$data{'email'},
  832:                                                                         $mailmsg,$contact_name,
  833:                                                                         $contact_email);
  834:                             if ($mailresult eq 'ok') {
  835:                                 $msg .= &mt('An e-mail confirming creation of your new LON-CAPA account has been sent to [_1].',$data{'username'});
  836:                             } else {
  837:                                 $msg .= &mt('An error occurred when sending e-mail to [_1] confirming creation of your LON-CAPA account.',$data{'username'});
  838:                             }
  839:                             $redirect = &start_session($r,$data{'username'},$domain,$uhome,
  840:                                                        $data{'courseid'},$token);
  841:                             $nostart = 1;
  842:                             $noend = 1;
  843:                         } else {
  844:                             $msg .= &mt('A problem occurred when attempting to create your new LON-CAPA account.')
  845:                                    .'<br />'.$output;
  846:                             if (($contact_name ne '') && ($contact_email ne '')) {
  847:                                 $msg .= &mt('Please contact the [_1] ([_2]) for assistance.',$contact_name,$contact_email);
  848:                             }
  849:                         }
  850:                         my $delete = &Apache::lonnet::tmpdel($token);
  851:                     }
  852:                 } else {
  853:                     $msg = &invalid_state('noemails',$domdesc,$contact_name,$contact_email);
  854:                 }
  855:             } else {
  856:                 $msg = &invalid_state('noemails',$domdesc,$contact_name,$contact_email);
  857:             }
  858:         } else {
  859:             $msg = &mt('Sorry, the token generated when you requested creation of an account has expired.')
  860:                   .' '.&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>');
  861:             }
  862:     } else {
  863:         $msg .= &mt('Sorry, the URL generated when you requested creation of an account contained incomplete information.')
  864:                .' '.&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>');
  865:     }
  866:     return ($msg,$nostart,$noend,$redirect);
  867: }
  868: 
  869: sub start_session {
  870:     my ($r,$username,$domain,$uhome,$courseid,$token) = @_;
  871:     my ($is_balancer) = &Apache::lonnet::check_loadbalancing($username,$domain);
  872:     if ($is_balancer) {
  873:         Apache::lonauth::success($r, $username, $domain, $uhome,
  874:             'noredirect', undef, {});
  875: 
  876:         Apache::lonnet::tmpdel($token) if $token;
  877: 
  878:         return 'redirect';
  879:     } else {
  880:         $courseid = Apache::lonnet::is_course($courseid); 
  881: 
  882:         Apache::lonauth::success($r, $username, $domain, $uhome,
  883:             ($courseid ? "/adm/selfenroll?courseid=$courseid" : '/adm/roles'),
  884:             undef, {}); 
  885:     }
  886:     return;
  887: }
  888: 
  889: #
  890: # The screen that the user gets to create his or her account
  891: # Desired username, desired password, etc
  892: # Stores token to store DES-key and stage during creation session
  893: #
  894: sub print_dataentry_form {
  895:     my ($r,$domain,$lonhost,$include,$now,$captchaform,$courseid,$emailusername,$captcha,
  896:         $usertype,$recaptchaversion) = @_;
  897:     my ($error,$output);
  898:     if (open(my $jsh,"<","$include/londes.js")) {
  899:         while(my $line = <$jsh>) {
  900:             $r->print($line);
  901:         }
  902:         close($jsh);
  903:         $output = &javascript_setforms($now,$emailusername,$captcha,$usertype,$recaptchaversion).
  904:                   "\n".&javascript_checkpass($now,'email');
  905:         my ($lkey,$ukey) = &Apache::loncommon::des_keys();
  906:         my ($lextkey,$uextkey) = &getkeys($lkey,$ukey);
  907:         my $logtoken=Apache::lonnet::reply('tmpput:'.$ukey.$lkey.'&createaccount:createaccount',
  908:                                            $lonhost);
  909:         $output .=
  910:             '<form name="createaccount" method="post" target="_top" action="/adm/createaccount">';
  911:         if ($courseid ne '') {
  912:             $output .= '<input type="hidden" name="courseid" value="'.$courseid.'"/>'."\n";
  913:         }
  914:         if (ref($emailusername) eq 'HASH') {
  915:             if (ref($emailusername->{$usertype}) eq 'HASH') {
  916:                 foreach my $field (sort(keys(%{$emailusername->{$usertype}}))) {
  917:                     $output .= '<input type="hidden" name="'.$field.'" value="" />'."\n";
  918:                 }
  919:                 $output .= '<input type="hidden" name="type" value="" />'."\n";
  920:             }
  921:         }
  922:         if ($captcha eq 'original') {
  923:             $output .= '
  924:    <input type="hidden" name="crypt" value="" />
  925:    <input type="hidden" name="code" value="" />
  926: ';
  927:         } elsif ($captcha eq 'recaptcha') {
  928:             if ($recaptchaversion eq '2') {
  929:                 $output .= "$captchaform\n";
  930:                 undef($captchaform);
  931:             } else {
  932:                 $output .= '
  933:    <input type="hidden" name="recaptcha_challenge_field" value="" />
  934:    <input type="hidden" name="recaptcha_response_field" value="" />
  935: ';
  936:             }
  937:         }
  938:         $output .= <<"ENDSERVERFORM";
  939:    <input type="hidden" name="logtoken" value="$logtoken" />
  940:    <input type="hidden" name="serverid" value="$lonhost" />
  941:    <input type="hidden" name="uname" value="" />
  942:    <input type="hidden" name="upass" value="" />
  943:    <input type="hidden" name="udom" value="" />
  944:    <input type="hidden" name="phase" value="createaccount" />
  945:    <input type="hidden" name="create_with_email" value="1" />
  946:   </form>
  947: ENDSERVERFORM
  948:         my $beginclientform = '<form name="newemail" method="post" action="" '.
  949:                               'onsubmit="return checkpass('."'createaccount','newemail'".');">'."\n";
  950:         my $endclientform = '<input type="hidden" name="udom" value="'.$domain.'" />'."\n".
  951:                             '<input type="hidden" name="lextkey" value="'.$lextkey.'" />'."\n".
  952:                             '<input type="hidden" name="uextkey" value="'.$uextkey.'" />'."\n".
  953:                             '</form>'."\n".
  954:                             '<p class="LC_info">'.&mt('Fields marked [_1]*[_2] are required.','<b>','</b>').'</p>';
  955:         my ($datatable,$rowcount) =
  956:             &Apache::loncreateuser::personal_data_display('',$domain,'email','selfcreate',
  957:                                                           '','',$now,$captchaform,
  958:                                                           $emailusername,$usertype);
  959:         if ($rowcount) {
  960:             $output .= '<div class="LC_left_float">'.$beginclientform.$datatable.$endclientform;
  961:         } else {
  962:             $output .= $beginclientform.$endclientform;
  963:         }
  964:         if ($rowcount) {
  965:             $output .= '</div>'."\n".
  966:                        '<div class="LC_clear_float_footer"></div>'."\n";
  967:         }
  968:     } else {
  969:         $output = &mt('Could not load javascript file [_1]','<tt>londes.js</tt>');
  970:     }
  971:     return $output;
  972: }
  973: 
  974: #
  975: # Retrieve rules for generating accounts from domain configuration
  976: # Can the user make a new account or just self-enroll?
  977: 
  978: sub get_creation_controls {
  979:     my ($domain,$usercreation) = @_;
  980:     my (@cancreate,@statustocreate,$emailusername);
  981:     if (ref($usercreation) eq 'HASH') {
  982:         if (ref($usercreation->{'cancreate'}) eq 'HASH') {
  983:             if (ref($usercreation->{'cancreate'}{'statustocreate'}) eq 'ARRAY') {
  984:                 @statustocreate = @{$usercreation->{'cancreate'}{'statustocreate'}};
  985:                 if (@statustocreate == 0) {
  986:                     my ($othertitle,$usertypes,$types) =
  987:                         &Apache::loncommon::sorted_inst_types($domain);
  988:                     if (ref($types) eq 'ARRAY') {
  989:                         if (@{$types} == 0) {
  990:                             @statustocreate = ('default');
  991:                         }
  992:                     } else {
  993:                         @statustocreate = ('default');
  994:                     }
  995:                 }
  996:             } else {
  997:                 @statustocreate = ('default');
  998:                 my ($othertitle,$usertypes,$types) =
  999:                     &Apache::loncommon::sorted_inst_types($domain);
 1000:                 if (ref($types) eq 'ARRAY') {
 1001:                     push(@statustocreate,@{$types});
 1002:                 }
 1003:             }
 1004:             if (ref($usercreation->{'cancreate'}{'selfcreate'}) eq 'ARRAY') {
 1005:                 @cancreate = @{$usercreation->{'cancreate'}{'selfcreate'}};
 1006:             } elsif (($usercreation->{'cancreate'}{'selfcreate'} ne 'none') &&
 1007:                      ($usercreation->{'cancreate'}{'selfcreate'} ne '')) {
 1008:                 @cancreate = ($usercreation->{'cancreate'}{'selfcreate'});
 1009:             }
 1010:             if (ref($usercreation->{'cancreate'}{'emailusername'}) eq 'HASH') {
 1011:                 $emailusername = $usercreation->{'cancreate'}{'emailusername'};
 1012:             } else {
 1013:                 $emailusername = {
 1014:                                     default =>  {
 1015:                                                    'lastname' => '1',
 1016:                                                    'firstname' => 1,
 1017:                                                 },
 1018:                                  };
 1019:             }
 1020:         }
 1021:     }
 1022:     return (\@cancreate,\@statustocreate,$emailusername);
 1023: }
 1024: 
 1025: sub create_account {
 1026:     my ($r,$domain,$domdesc,$dataref) = @_;
 1027:     my $error    = '<span class="LC_error">'.&mt('Error:').' ';
 1028:     my $end      = '</span><br /><br />';
 1029:     my $rtnlink  = '<a href="javascript:history.back();">'.
 1030:                     &mt('Return to previous page').'</a>'.
 1031:                     &Apache::loncommon::end_page();
 1032:     my $output;
 1033:     if (ref($dataref) eq 'HASH') {
 1034:         my ($username,$encpass,$serverid,$courseid,$id,$firstname,$middlename,$lastname,
 1035:             $generation,$inststatus);
 1036:         $username   = $dataref->{'username'};
 1037:         $encpass    = $dataref->{'upass'};
 1038:         $serverid   = $dataref->{'serverid'};
 1039:         $courseid   = $dataref->{'courseid'};
 1040:         $id         = $dataref->{'id'};
 1041:         $firstname  = $dataref->{'firstname'};
 1042:         $middlename = $dataref->{'middlename'};
 1043:         $lastname   = $dataref->{'lastname'};
 1044:         $generation = $dataref->{'generation'};
 1045:         $inststatus = $dataref->{'inststatus'};
 1046: 
 1047:         my $currhome = &Apache::lonnet::homeserver($username,$domain);
 1048:         unless ($currhome eq 'no_host') {
 1049:             $output = &mt('User account requested for username: [_1] in domain: [_2] already exists.',$username,$domain);
 1050:             return ('fail',$error.$output.$end.$rtnlink);
 1051:         }
 1052: 
 1053: # Split the logtoken to retrieve the DES key and decrypt the encypted password
 1054: 
 1055:         my ($key,$caller)=split(/&/,$dataref->{'tmpinfo'});
 1056:         if ($caller eq 'createaccount') {
 1057:             my $upass = &Apache::loncommon::des_decrypt($key,$encpass);
 1058: 
 1059: # See if we are allowed to use the proposed student/employee ID,
 1060: # as per domain rules; if not, student/employee will be left blank.
 1061: 
 1062:             if ($id ne '') {
 1063:                 my ($result,$userchkmsg) = &check_id($username,$domain,$id,$domdesc,'email');
 1064:                 if ($result eq 'fail') {
 1065:                     $output = $error.&mt('Invalid ID format').$end.
 1066:                               $userchkmsg;
 1067:                     undef($id);
 1068:                 }
 1069:             }
 1070: 
 1071: # Create an internally authenticated account with password $upass
 1072: # if the user account does not already exist.
 1073: # Assign student/employee id, first name, last name, etc.
 1074: 
 1075:             my $result =
 1076:                 &Apache::lonnet::modifyuser($domain,$username,$id,
 1077:                                             'internal',$upass,$firstname,$middlename,
 1078:                                             $lastname,$generation,undef,undef,$username);
 1079:             $output = &mt('Generating user: [_1]',$result);
 1080: 
 1081: # Now that the user account exists, retrieve the homeserver, and include it in the output.
 1082: 
 1083:             my $uhome = &Apache::lonnet::homeserver($username,$domain);
 1084:             unless (($inststatus eq 'default') || ($inststatus eq '')) {
 1085:                 &Apache::lonnet::put('environment',{inststatus => $inststatus},$domain,$username);
 1086:             }
 1087:             $output .= '<br />'.&mt('Home server: [_1]',$uhome).' '.
 1088:                        &Apache::lonnet::hostname($uhome).'<br /><br />';
 1089:             return ('ok',$output,$uhome);
 1090:         } else {
 1091:             $output = &mt('Unable to retrieve your account creation information - unexpected context');
 1092:             undef($encpass);
 1093:             return ('fail',$error.$output.$end.$rtnlink);
 1094:         }
 1095:     } else {
 1096:         $output = &mt('Unable to retrieve information for your account request.');
 1097:         return ('fail',$error.$output.$end.$rtnlink);
 1098:     }
 1099: }
 1100: 
 1101: sub username_validation {
 1102:     my ($r,$username,$domain,$domdesc,$contact_name,$contact_email,$courseid,
 1103:         $lonhost,$statustocreate) = @_;
 1104: # $r: request object
 1105: # $username,$domain: for the user who needs to be validated
 1106: # $domdesc: full name of the domain (for error messages)
 1107: # $contact_name, $contact_email: name and email for user assistance (for error messages in &username_check)
 1108: # $courseid: ID of the course if user came to username_validation via self-enroll link,
 1109: #             passed to start_session()
 1110: # $lonhost: LON-CAPA lonHostID
 1111: # $statustocreate: -> inststatus in username_check ('faculty', 'staff', 'student', ...)
 1112:  
 1113: #
 1114: # Sanitize incoming username and domain
 1115: #
 1116:     $username= &LONCAPA::clean_username($username);
 1117:     $domain = &LONCAPA::clean_domain($domain);
 1118: 
 1119: #
 1120: # Check if LON-CAPA account already exists for $username:$domain
 1121: #
 1122:     my $uhome = &Apache::lonnet::homeserver($username,$domain);
 1123: 
 1124:     my $output;
 1125: 
 1126: # Retrieve DES key from server using logtoken
 1127:  
 1128:     my $tmpinfo=Apache::lonnet::reply('tmpget:'.$env{'form.logtoken'},$env{'form.serverid'});
 1129:     if (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost')) {
 1130:         $output = &mt('Information needed to verify your login information is missing, inaccessible or expired.')
 1131:                  .'<br />'.&mt('You may need to reload the previous page to obtain a new token.');
 1132:         return ('fail',$output);
 1133:     } else {
 1134:         my $reply = &Apache::lonnet::reply('tmpdel:'.$env{'form.logtoken'},$env{'form.serverid'});
 1135:         unless ($reply eq 'ok') {
 1136:             $output = &mt('Session could not be opened.');
 1137:             return ('fail',$output); 
 1138:         }
 1139:     }
 1140: 
 1141: # Split the logtoken to retrieve the DES key and decrypt the encypted password
 1142: 
 1143:     my ($key,$caller)=split(/&/,$tmpinfo);
 1144:     my $upass;
 1145:     if ($caller eq 'createaccount') {
 1146:         $upass = &Apache::loncommon::des_decrypt($key,$env{'form.upass'});
 1147:     } else {
 1148:         $output = &mt('Unable to retrieve your log-in information - unexpected context');
 1149:         return ('fail',$output);
 1150:     }
 1151:     if ($uhome ne 'no_host') {
 1152:         my $result = &Apache::lonnet::authenticate($username,$upass,$domain);
 1153:         if ($result ne 'no_host') { 
 1154:             my $redirect = &start_session($r,$username,$domain,$uhome,$courseid);
 1155:             if ($redirect) {
 1156:                 return ($redirect);
 1157:             }
 1158:             $output = '<br /><br />'.
 1159:                       &mt('A LON-CAPA account already exists for username [_1] at this institution ([_2]).',
 1160:                           '<tt>'.$username.'</tt>',$domdesc).'<br />'.
 1161:                       &mt('The password entered was also correct so you have been logged in.');
 1162:             return ('existingaccount',$output);
 1163:         } else {
 1164:             $output = &login_failure_msg($courseid);
 1165:         }
 1166:     } else {
 1167:         my $primlibserv = &Apache::lonnet::domain($domain,'primary');
 1168:         my $authok;
 1169:         my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 1170:         if ((($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) || 
 1171:              ($domdefaults{'auth_def'} eq 'localauth')) {
 1172:             my $checkdefauth = 1;
 1173:             $authok = 
 1174:                 &Apache::lonnet::reply("encrypt:auth:$domain:$username:$upass:$checkdefauth",$primlibserv);
 1175:         } else {
 1176:             $authok = 'non_authorized';
 1177:         }
 1178:         if ($authok eq 'authorized') {
 1179:             $output = &username_check($username,$domain,$domdesc,$courseid,$lonhost,
 1180:                                       $contact_email,$contact_name,undef,
 1181:                                       $statustocreate);
 1182:         } else {
 1183:             $output = &login_failure_msg($courseid);
 1184:         }
 1185:     }
 1186:     return ('ok',$output);
 1187: }
 1188: 
 1189: sub login_failure_msg {
 1190:     my ($courseid) = @_;
 1191:     my $url;
 1192:     if ($courseid ne '') {
 1193:         $url = "/adm/selfenroll?courseid=".$courseid;
 1194:     } else {
 1195:         $url = "/adm/createaccount";
 1196:     }
 1197:     my $output = '<h4>'.&mt('Authentication failed').'</h4><div class="LC_warning">'.
 1198:                  &mt('Username and/or password could not be authenticated.').
 1199:                  '</div>'.
 1200:                  &mt('Please check the username and password.').'<br /><br />';
 1201:                  '<a href="'.$url.'">'.&mt('Try again').'</a>';
 1202:     return $output;
 1203: }
 1204: 
 1205: sub username_check {
 1206:     my ($username,$domain,$domdesc,$courseid,$lonhost,$contact_email,
 1207:         $contact_name,$sso_logout,$statustocreate,$shibenv) = @_;
 1208:     my (%rulematch,%inst_results,$checkfail,$rowcount,$editable,$output,$msg,
 1209:         %alerts,%curr_rules,%got_rules);
 1210:     &call_rulecheck($username,$domain,\%alerts,\%rulematch,
 1211:                     \%inst_results,\%curr_rules,\%got_rules,'username');
 1212:     if (ref($alerts{'username'}) eq 'HASH') {
 1213:         if (ref($alerts{'username'}{$domain}) eq 'HASH') {
 1214:             if ($alerts{'username'}{$domain}{$username}) {
 1215:                 if (ref($curr_rules{$domain}) eq 'HASH') {
 1216:                     $output =
 1217:                         &Apache::loncommon::instrule_disallow_msg('username',$domdesc,1,
 1218:                                                                   'selfcreate').
 1219:                         &Apache::loncommon::user_rule_formats($domain,$domdesc,
 1220:                                 $curr_rules{$domain}{'username'},'username');
 1221:                 }
 1222:                 $checkfail = 'username';
 1223:             }
 1224:         }
 1225:     }
 1226:     if (!$checkfail) {
 1227:         if (ref($statustocreate) eq 'ARRAY') {
 1228:             $checkfail = 'inststatus';
 1229:             if (ref($inst_results{$username.':'.$domain}{inststatus}) eq 'ARRAY') {
 1230:                 foreach my $inststatus (@{$inst_results{$username.':'.$domain}{inststatus}}) {
 1231:                     if (grep(/^\Q$inststatus\E$/,@{$statustocreate})) {
 1232:                         undef($checkfail);
 1233:                         last;
 1234:                     }
 1235:                 }
 1236:             } elsif (grep(/^default$/,@{$statustocreate})) {
 1237:                 undef($checkfail);
 1238:             }
 1239:         }
 1240:     }
 1241:     if (!$checkfail) {
 1242:         $output = '<form method="post" action="/adm/createaccount">';
 1243:         if (ref($shibenv) eq 'HASH') {
 1244:             foreach my $key (keys(%{$shibenv})) {
 1245:                 if ($ENV{$shibenv->{$key}} ne '') {
 1246:                     $inst_results{$username.':'.$domain}{$key} = $ENV{$shibenv->{$key}};
 1247:                 }
 1248:             }
 1249:         }
 1250:         (my $datatable,$rowcount,$editable) = 
 1251:             &Apache::loncreateuser::personal_data_display($username,$domain,1,'selfcreate',
 1252:                                                          $inst_results{$username.':'.$domain});
 1253:         if ($rowcount > 0) {
 1254:             $output .= $datatable;
 1255:         }
 1256:         $output .=  '<br /><br /><input type="hidden" name="uname" value="'.$username.'" />'."\n".
 1257:                     '<input type="hidden" name="udom" value="'.$domain.'" />'."\n".
 1258:                     '<input type="hidden" name="phase" value="username_activation" />';
 1259:         my $now = time;
 1260:         my %info = ('ip'         => $ENV{'REMOTE_ADDR'},
 1261:                     'time'       => $now,
 1262:                     'domain'     => $domain,
 1263:                     'username'   => $username);
 1264:         my $authtoken = &Apache::lonnet::tmpput(\%info,$lonhost,'createaccount');
 1265:         if ($authtoken !~ /^error/ && $authtoken ne 'no_such_host') {
 1266:             $output .= '<input type="hidden" name="authtoken" value="'.&HTML::Entities::encode($authtoken,'&<>"').'" />';
 1267:         } else {
 1268:             $output = &mt('An error occurred when storing a token').'<br />'.
 1269:                       &mt('You will not be able to proceed to the next stage of account creation').
 1270:                       &linkto_email_help($contact_email,$domdesc);
 1271:             $checkfail = 'authtoken';
 1272:         }
 1273:     }
 1274:     if ($checkfail) { 
 1275:         $msg = '<br /><h4>'.&mt('Account creation unavailable').'</h4>';
 1276:         if ($checkfail eq 'username') {
 1277:             $msg .= '<span class="LC_warning">'.
 1278:                      &mt('A LON-CAPA account may not be created with the username you use.').
 1279:                      '</span><br /><br />'.$output;
 1280:         } elsif ($checkfail eq 'authtoken') {
 1281:             $msg .= '<span class="LC_error">'.&mt('Error creating token.').'</span>'.
 1282:                     '<br />'.$output;
 1283:         } elsif ($checkfail eq 'inststatus') {
 1284:             $msg .= '<span class="LC_warning">'.
 1285:                      &mt('You are not permitted to create a LON-CAPA account.').
 1286:                      '</span><br /><br />'.$output;
 1287:         }
 1288:         $msg .= &mt('Please contact the [_1] ([_2]) for assistance.',
 1289:                 $contact_name,$contact_email).'<br /><hr />'.
 1290:                 $sso_logout;
 1291:         &Apache::lonnet::logthis("ERROR: failure type of '$checkfail' when performing username check to create account for authenticated user: $username, in domain $domain");
 1292:     } else {
 1293:         if ($courseid ne '') {
 1294:             $output .= '<input type="hidden" name="courseid" value="'.$courseid.'" />';
 1295:         }
 1296:         $output .= '<input type="submit" name="newaccount" value="'.
 1297:                    &mt('Create LON-CAPA account').'" /></form>';
 1298:         if ($rowcount) {
 1299:             if ($editable) {
 1300:                 if ($courseid ne '') { 
 1301:                     $msg = '<br /><h4>'.&mt('User information').'</h4>';
 1302:                 }
 1303:                 $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 />';
 1304:             } else {
 1305:                  if ($courseid ne '') {
 1306:                      $msg = '<h4>'.&mt('Review user information').'</h4>';
 1307:                  }
 1308:                  $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 />';
 1309:             }
 1310:         } else {
 1311:             if ($courseid ne '') {
 1312:                 $msg = '<h4>'.&mt('Confirmation').'</h4>';
 1313:             }
 1314:             $msg .= &mt('Confirm that you wish to create an account.');
 1315:         }
 1316:         $msg .= $output;
 1317:     }
 1318:     return $msg;
 1319: }
 1320: 
 1321: sub username_activation {
 1322:     my ($r,$username,$domain,$domdesc,$courseid) = @_;
 1323:     my $output;
 1324:     my $error     = '<span class="LC_error">'.&mt('Error:').' ';
 1325:     my $end       = '</span><br /><br />';
 1326:     my $rtnlink   = '<a href="javascript:history.back();">'.
 1327:                     &mt('Return to previous page').'</a>'.
 1328:                     &Apache::loncommon::end_page();
 1329:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 1330:     my %data = &Apache::lonnet::tmpget($env{'form.authtoken'});
 1331:     my $now = time;
 1332:     my $earlyout;
 1333:     my $timeout = 300;
 1334:     if (keys(%data) == 0) {
 1335:         $output = &mt('Sorry, your authentication has expired.');
 1336:         $earlyout = 'fail';
 1337:     }
 1338:     if (($data{'time'} !~ /^\d+$/) ||
 1339:         ($data{'domain'} ne $domain) || 
 1340:         ($data{'username'} ne $username)) {
 1341:         $earlyout = 'fail';
 1342:         $output = &mt('The credentials you provided could not be verified.');   
 1343:     } elsif ($now - $data{'time'} > $timeout) {
 1344:         $earlyout = 'fail';
 1345:         $output = &mt('Sorry, your authentication has expired.');
 1346:     }
 1347:     if ($earlyout ne '') {
 1348:         my $link = '/adm/createaccount';
 1349:         if (&Apache::lonnet::domain($domain) ne '') {
 1350:             $link .= "?domain=$domain"; 
 1351:         }
 1352:         $output .= '<br />'.&mt('Please [_1]start again[_2].',
 1353:                                 '<a href="'.$link.'">','</a>');
 1354:         return($earlyout,$output);
 1355:     }
 1356:     if ((($domdefaults{'auth_def'} =~/^krb(4|5)$/) && 
 1357:          ($domdefaults{'auth_arg_def'} ne '')) || 
 1358:         ($domdefaults{'auth_def'} eq 'localauth')) {
 1359:         if ($env{'form.courseid'} ne '') {
 1360:             my $id = $env{'form.cid'}; 
 1361:             my ($result,$userchkmsg) = &check_id($username,$domain,$id,$domdesc,'institutional');
 1362:             if ($result eq 'fail') {
 1363:                 $output = $error.&mt('Invalid ID format').$end.
 1364:                           $userchkmsg.$rtnlink;
 1365:                 return ('fail',$output);
 1366:             }
 1367:         }
 1368:         # Call modifyuser
 1369:         my (%rulematch,%inst_results,%curr_rules,%got_rules,%alerts,%info);
 1370:         &call_rulecheck($username,$domain,\%alerts,\%rulematch,
 1371:                         \%inst_results,\%curr_rules,\%got_rules);
 1372:         my @userinfo = ('firstname','middlename','lastname','generation',
 1373:                         'permanentemail','id');
 1374:         my %canmodify = 
 1375:             &Apache::loncreateuser::selfcreate_canmodify('selfcreate',$domain,
 1376:                                                          \@userinfo,\%inst_results);
 1377:         foreach my $item (@userinfo) {
 1378:             if ($canmodify{$item}) {
 1379:                 $info{$item} = $env{'form.c'.$item};
 1380:             } else {
 1381:                 $info{$item} = $inst_results{$username.':'.$domain}{$item}; 
 1382:             }
 1383:         }
 1384:         if (ref($inst_results{$username.':'.$domain}{'inststatus'}) eq 'ARRAY') {
 1385:             my @inststatuses = @{$inst_results{$username.':'.$domain}{'inststatus'}};
 1386:             $info{'inststatus'} = join(':',map { &escape($_); } @inststatuses);
 1387:         }
 1388:         my $result =
 1389:             &Apache::lonnet::modifyuser($domain,$username,$env{'form.cid'},
 1390:                           $domdefaults{'auth_def'},
 1391:                           $domdefaults{'auth_arg_def'},$info{'firstname'},
 1392:                           $info{'middlename'},$info{'lastname'},
 1393:                           $info{'generation'},undef,undef,
 1394:                           $info{'permanentemail'},$info{'inststatus'});
 1395:         if ($result eq 'ok') {
 1396:             my $delete = &Apache::lonnet::tmpdel($env{'form.authtoken'});
 1397:             $output = &mt('A LON-CAPA account has been created for username: [_1] in domain: [_2].',$username,$domain);
 1398:             my $uhome=&Apache::lonnet::homeserver($username,$domain,'true');
 1399:             my $nostart = 1;
 1400:             my $response = 'ok';
 1401:             my $redirect = &start_session($r,$username,$domain,$uhome,$courseid);
 1402:             if ($redirect) {
 1403:                 $response = $redirect;
 1404:             }
 1405:             return ($response,$output,$nostart);
 1406:         } else {
 1407:             $output = &mt('Account creation failed for username: [_1] in domain: [_2].',$username,$domain).'<br /><span class="LC_error">'.&mt('Error: [_1]',$result).'</span>';
 1408:             return ('fail',$output);
 1409:         }
 1410:     } else {
 1411:         $output = &mt('User account creation is not available for the current default authentication type.')."\n";
 1412:         return('fail',$output);
 1413:     }
 1414: }
 1415: 
 1416: sub check_id {
 1417:     my ($username,$domain,$id,$domdesc,$usernametype) = @_;
 1418:     # Check student/employee ID format
 1419:     # Is proposed student/employee ID acceptable according to domain's rules.  
 1420:     # $domdesc is just used for user error messages
 1421:     my (%alerts,%rulematch,%inst_results,%curr_rules,%checkhash);
 1422:     my %checks = ('id' => 1);
 1423:     %{$checkhash{$username.':'.$domain}} = (
 1424:                                             'newuser' => 1,
 1425:                                             'id' => $id,
 1426:                                            );
 1427:     &Apache::loncommon::user_rule_check(\%checkhash,\%checks,\%alerts,
 1428:                                         \%rulematch,\%inst_results,\%curr_rules);
 1429:     if (ref($alerts{'id'}) eq 'HASH') {
 1430:         if (ref($alerts{'id'}{$domain}) eq 'HASH') {
 1431:             if ($alerts{'id'}{$domain}{$env{'form.cid'}}) {
 1432:                 my $userchkmsg;
 1433:                 if (ref($curr_rules{$domain}) eq 'HASH') {
 1434:                     if ($usernametype eq 'email') {
 1435:                         $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.');
 1436:                     } else {
 1437:                         $userchkmsg =
 1438:                             &Apache::loncommon::instrule_disallow_msg('id',
 1439:                                                                       $domdesc,1).
 1440:                             &Apache::loncommon::user_rule_formats($domain,
 1441:                                 $domdesc,$curr_rules{$domain}{'id'},'id');
 1442:                     }
 1443:                 }
 1444:                 return ('fail',$userchkmsg);
 1445:             }
 1446:         }
 1447:     }
 1448:     return; 
 1449: }
 1450: 
 1451: sub invalid_state {
 1452:     my ($error,$domdesc,$contact_name,$contact_email,$msgtext) = @_;
 1453:     my $msg = '<h3>'.&mt('Account creation unavailable').'</h3><span class="LC_error">';
 1454:     if ($error eq 'baduseremail') {
 1455:         $msg .= &mt('The e-mail address you provided does not appear to be a valid address.');
 1456:     } elsif ($error eq 'badusername') {
 1457:         $msg .= &mt('The e-mail address you provided contains characters which prevent its use as a username in LON-CAPA.');
 1458:     } elsif ($error eq 'existinguser') {
 1459:         $msg .= &mt('The e-mail address you provided is already in use as a username in LON-CAPA at this institution.');
 1460:     } elsif ($error eq 'userrules') {
 1461:         $msg .= &mt('Username rules at this institution do not allow the e-mail address you provided to be used as a username.');
 1462:     } elsif ($error eq 'userformat') {
 1463:         $msg .= &mt('The e-mail address you provided may not be used as a username at this LON-CAPA institution.');
 1464:     } elsif ($error eq 'captcha') {
 1465:         $msg .= &mt('Validation of the code you entered failed.');
 1466:     } elsif ($error eq 'noemails') {
 1467:         $msg .= &mt('Creation of a new user account using an e-mail address as username is not permitted at this LON-CAPA institution.');
 1468:     }
 1469:     $msg .= '</span>';
 1470:     if ($msgtext) {
 1471:         $msg .= '<br />'.$msgtext;
 1472:     }
 1473:     $msg .= &linkto_email_help($contact_email,$domdesc,$error);
 1474:     return $msg;
 1475: }
 1476: 
 1477: sub linkto_email_help {
 1478:     my ($contact_email,$domdesc,$error) = @_;
 1479:     my $msg;
 1480:     my $href = '/adm/helpdesk';
 1481:     if ($contact_email ne '') {
 1482:         my $escuri = &HTML::Entities::encode('/adm/createaccount','&<>"');
 1483:         $href .= '?origurl='.$escuri;
 1484:         if ($error eq 'existinguser') {
 1485:             my $escemail = &HTML::Entities::encode($env{'form.useremail'});
 1486:             $href .= '&useremail='.$escemail.'&useraccount='.$escemail;
 1487:         }
 1488:         $msg .= '<br />'.&mt('You may wish to contact the [_1]LON-CAPA helpdesk[_2] for [_3].','<a href="'.$href.'">','</a>',$domdesc).'<br />';
 1489:     } else {
 1490:         $msg .= '<br />'.&mt('You may wish to send an e-mail to the server administrator: [_1] for [_2].',$Apache::lonnet::perlvar{'AdmEMail'},$domdesc).'<br />';
 1491:     }
 1492:     return $msg;
 1493: }
 1494: 
 1495: sub getkeys {
 1496:     my ($lkey,$ukey) = @_;
 1497:     my $lextkey=hex($lkey);
 1498:     if ($lextkey>2147483647) { $lextkey-=4294967296; }
 1499: 
 1500:     my $uextkey=hex($ukey);
 1501:     if ($uextkey>2147483647) { $uextkey-=4294967296; }
 1502:     return ($lextkey,$uextkey);
 1503: }
 1504: 
 1505: sub serverform {
 1506:     my ($logtoken,$lonhost,$mailtoken,$courseid,$context) = @_;
 1507:     my $phase = 'username_validation';
 1508:     my $catalog_elements;
 1509:     if ($context eq 'selfenroll') {
 1510:         $phase = 'selfenroll_login';
 1511:     }
 1512:     if ($courseid ne '') {
 1513:         $catalog_elements = &Apache::lonhtmlcommon::echo_form_input(['courseid','phase']);
 1514:     } 
 1515:     my $output = <<ENDSERVERFORM;
 1516:   <form name="server" method="post" action="/adm/createaccount">
 1517:    <input type="hidden" name="logtoken" value="$logtoken" />
 1518:    <input type="hidden" name="token" value="$mailtoken" />
 1519:    <input type="hidden" name="serverid" value="$lonhost" />
 1520:    <input type="hidden" name="uname" value="" />
 1521:    <input type="hidden" name="upass" value="" />
 1522:    <input type="hidden" name="udom" value="" />
 1523:    <input type="hidden" name="phase" value="$phase" />
 1524:    <input type="hidden" name="courseid" value="$courseid" />
 1525:    $catalog_elements
 1526:   </form>
 1527: ENDSERVERFORM
 1528:     return $output;
 1529: }
 1530: 
 1531: sub store_request {
 1532:     my ($dom,$username,$val,$dataref,$settings) = @_;
 1533:     my $output;
 1534:     my $domconfiguser = &Apache::lonnet::get_domainconfiguser($dom);
 1535:     my $key = &escape($username);
 1536:     my $now = time();
 1537:     if (&Apache::lonnet::put('usernamequeue', { $key.'_'.$val => $now },
 1538:                              $dom,$domconfiguser) eq 'ok') {
 1539:         if (ref($dataref) eq 'HASH') {
 1540:             my $logtoken = $dataref->{'tmpinfo'};
 1541:             my $serverid = $dataref->{'serverid'}; 
 1542:             if ($logtoken && $serverid) {
 1543:                 my $tmpinfo=Apache::lonnet::reply('tmpget:'.$logtoken,$serverid);
 1544:                 unless (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost')) {
 1545:                     my $reply = &Apache::lonnet::reply('tmpdel:'.$logtoken,$serverid);
 1546:                     if ($reply eq 'ok') {
 1547:                         my ($key,$caller)=split(/&/,$tmpinfo);
 1548:                         $dataref->{'key'} = $key;
 1549:                         undef($dataref->{'tmpinfo'});
 1550:                         undef($dataref->{'serverid'});
 1551:                     }
 1552:                 }
 1553:             }
 1554:         }
 1555:         my %userrequest = ( $username => $dataref );
 1556:         $userrequest{$username}{timestamp} = $now;
 1557:         $userrequest{$username}{status} = $val;
 1558:         my $notifylist;
 1559:         if (ref($settings) eq 'HASH') {
 1560:             if (ref($settings->{'cancreate'}) eq 'HASH') {
 1561:                 if (ref($settings->{'cancreate'}{'notify'}) eq 'HASH') {
 1562:                     my $notifylist = $settings->{'cancreate'}{'notify'}{'approval'};
 1563:                     if ($notifylist) {
 1564:                         my $sender = $domconfiguser.':'.$dom;
 1565:                         my $domdesc = &Apache::lonnet::domain($dom,'description');
 1566:                         my $fullname;
 1567:                         if (ref($dataref) eq 'HASH') {
 1568:                             if ($dataref->{'firstname'}) {
 1569:                                 $fullname = $dataref->{'firstname'};
 1570:                             }
 1571:                             if ($dataref->{'lastname'}) {
 1572:                                 $fullname .= ' '.$dataref->{'lastname'};
 1573:                             }
 1574:                             $fullname =~ s/^\s+|\s+$//g; 
 1575:                         }
 1576:                         &Apache::loncoursequeueadmin::send_selfserve_notification($notifylist,
 1577:                                                      "$fullname ($username)",
 1578:                                                      undef,$domdesc,$now,'usernamereq',$sender);
 1579:                     }
 1580:                 }
 1581:             }
 1582:         }
 1583:         my $userresult =
 1584:             &Apache::lonnet::put('nohist_requestedusernames',\%userrequest,$dom,$domconfiguser);
 1585:         $output = '<p class="LC_info">'.
 1586:                   &mt('Your request for a LON-CAPA account has been submitted for approval.').
 1587:                   '</p>'.
 1588:                   '<p class="LC_info">'.
 1589:                   &mt('An e-mail will be sent to [_1] when your request has been reviewed by an administrator and action has been taken.',$username).
 1590:                   '</p>';
 1591:     } else {
 1592:         $output = '<span class="LC_error">'.
 1593:                   &mt('An error occurred when attempting to save your request for a LON-CAPA account.');
 1594:                   '</span>';
 1595:     }
 1596:     return $output;
 1597: }
 1598: 
 1599: sub guest_format_check {
 1600:     my ($useremail,$domain,$cancreate,$settings) = @_;
 1601:     my ($login,$format_match,$format_msg,@user_rules);
 1602:     if (ref($settings) eq 'HASH') {
 1603:         if (ref($settings->{'email_rule'}) eq 'ARRAY') {
 1604:             push(@user_rules,@{$settings->{'email_rule'}});
 1605:         }
 1606:     }
 1607:     if (@user_rules > 0) {
 1608:         my %rule_check = 
 1609:             &Apache::lonnet::inst_rulecheck($domain,$useremail,undef,
 1610:                                             'selfcreate',\@user_rules);
 1611:         if (keys(%rule_check) > 0) {
 1612:             foreach my $item (keys(%rule_check)) {
 1613:                 if ($rule_check{$item}) {
 1614:                     $format_match = 1;   
 1615:                     last;
 1616:                 }
 1617:             }
 1618:         }
 1619:     }
 1620:     if ($format_match) {
 1621:         ($login) = ($useremail =~ /^([^\@]+)\@/);
 1622:         $format_msg = '<br />'.
 1623:                       &mt("Your e-mail address uses the same internet domain as your institution's LON-CAPA service.").'<br />'.
 1624:                       &mt('Creation of a LON-CAPA account with this type of e-mail address as username is not permitted.').'<br />';
 1625:         if (ref($cancreate) eq 'ARRAY') {
 1626:             if (grep(/^login$/,@{$cancreate})) {
 1627:                 $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 />'; 
 1628:             }
 1629:         }
 1630:     }
 1631:     return $format_msg;
 1632: }
 1633: 
 1634: sub sso_logout_frag {
 1635:     my ($r,$domain) = @_;
 1636:     my $endsessionmsg;
 1637:     if (defined($r->dir_config('lonSSOUserLogoutMessageFile_'.$domain))) {
 1638:         my $msgfile = $r->dir_config('lonSSOUserLogoutMessageFile_'.$domain);
 1639:         if (-e $msgfile) {
 1640:             open(my $fh,"<",$msgfile);
 1641:             $endsessionmsg = join('',<$fh>);
 1642:             close($fh);
 1643:         }
 1644:     } elsif (defined($r->dir_config('lonSSOUserLogoutMessageFile'))) {
 1645:         my $msgfile = $r->dir_config('lonSSOUserLogoutMessageFile');
 1646:         if (-e $msgfile) {     
 1647:             open(my $fh,"<",$msgfile);
 1648:             $endsessionmsg = join('',<$fh>);
 1649:             close($fh);
 1650:         }
 1651:     }
 1652:     return $endsessionmsg;
 1653: }
 1654: 
 1655: sub catreturn_js {
 1656:     return  <<"ENDSCRIPT";
 1657: <script type="text/javascript">
 1658: // <![CDATA[
 1659: function ToSelfenroll(formname) {
 1660:     var formidx = getFormByName(formname);
 1661:     if (formidx > -1) {
 1662:         document.forms[formidx].action = '/adm/selfenroll';
 1663:         numidx = getIndexByName(formidx,'phase');
 1664:         if (numidx > -1) {
 1665:             document.forms[formidx].elements[numidx].value = '';   
 1666:         }
 1667:         numidx = getIndexByName(formidx,'context');
 1668:         if (numidx > -1) {
 1669:             document.forms[formidx].elements[numidx].value = '';
 1670:         }
 1671:     }
 1672:     document.forms[formidx].submit();
 1673: }
 1674: 
 1675: function ToCatalog(formname,caller) {
 1676:     var formidx = getFormByName(formname);
 1677:     if (formidx > -1) {
 1678:         document.forms[formidx].action = '/adm/coursecatalog';
 1679:         numidx = getIndexByName(formidx,'coursenum');
 1680:         if (numidx > -1) {
 1681:             if (caller != 'details') {
 1682:                 document.forms[formidx].elements[numidx].value = '';
 1683:             }
 1684:         }
 1685:     }
 1686:     document.forms[formidx].submit();
 1687: }
 1688: 
 1689: function getIndexByName(formidx,item) {
 1690:     for (var i=0;i<document.forms[formidx].elements.length;i++) {
 1691:         if (document.forms[formidx].elements[i].name == item) {
 1692:             return i;
 1693:         }
 1694:     }
 1695:     return -1;
 1696: }
 1697: 
 1698: function getFormByName(item) {
 1699:     for (var i=0; i<document.forms.length; i++) {
 1700:         if (document.forms[i].name == item) {
 1701:             return i;
 1702:         }
 1703:     }
 1704:     return -1;
 1705: }
 1706: // ]]>
 1707: </script>
 1708: ENDSCRIPT
 1709: 
 1710: }
 1711: 
 1712: 1;

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