File:  [LON-CAPA] / loncom / interface / createaccount.pm
Revision 1.67: download - view: text, annotated - select for diffs
Fri May 30 16:46:03 2014 UTC (10 years, 1 month ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- If "Self-creation with e-mail as username" settings have yet to be set
  for a domain (2.11 feature), but self-creation enabled for e-mail
  address as username (available pre-2.11), optional user informational
  fields: firstname and lastname in web form.

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

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