File:  [LON-CAPA] / loncom / interface / createaccount.pm
Revision 1.70: download - view: text, annotated - select for diffs
Tue Jun 9 21:22:55 2015 UTC (9 years ago) by damieng
Branches: MAIN
CVS tags: HEAD
fixed bug 6782, and escaped most localized messages used in Javascript blocks to make sure bugs like that do not happen again

    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.70 2015/06/09 21:22:55 damieng 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',
  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) =  @_;
  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:             $setuserinfo .= 
  386:                 '                    server.elements.recaptcha_challenge_field.value=client.elements.recaptcha_challenge_field.value;'."\n".
  387:                 '                    server.elements.recaptcha_response_field.value=client.elements.recaptcha_response_field.value;'."\n";
  388:         }
  389:     }
  390:     if (@required) {
  391:         my $missprompt = &mt('One or more required fields are currently blank.');
  392:         &js_escape(\$missprompt);
  393:         my $reqstr = join("','",@required);
  394:         $requiredchk = <<"ENDCHK";
  395:                 var requiredfields = new Array('$reqstr');
  396:                 missing = 0; 
  397:                 for (var i=0; i<requiredfields.length; i++) {
  398:                     try {
  399:                         eval("client.elements."+requiredfields[i]+".value");
  400:                     }
  401:                     catch(err) {
  402:                         continue;
  403:                     }
  404:                     if (eval("client.elements."+requiredfields[i]+".value") == '') {
  405:                         missing ++;
  406:                     }
  407:                 }
  408:                 if (missing > 0) {
  409:                     alert("$missprompt");
  410:                     return false;
  411:                 }
  412: 
  413: ENDCHK
  414:     }
  415:     my $js = <<ENDSCRIPT;
  416: <script type="text/javascript">
  417: // <![CDATA[
  418:     function send(one,two,context) {
  419:         var server;
  420:         var client;
  421:         if (document.forms[one]) {
  422:             server = document.forms[one];
  423:             if (document.forms[two]) {
  424:                 client = document.forms[two];
  425: $requiredchk
  426:                 server.elements.uname.value = client.elements.uname.value;
  427:                 server.elements.udom.value = client.elements.udom.value;
  428: 
  429:                 uextkey=client.elements.uextkey.value;
  430:                 lextkey=client.elements.lextkey.value;
  431:                 initkeys();
  432: 
  433:                 server.elements.upass.value
  434:                     = crypted(client.elements.upass$now.value);
  435: 
  436:                 client.elements.uname.value='';
  437:                 client.elements.upass$now.value='';
  438:                 if (context == 'email') {
  439: $setuserinfo
  440:                     client.elements.upasscheck$now.value='';
  441:                 }
  442:                 server.submit();
  443:             }
  444:         }
  445:         return false;
  446:     }
  447: // ]]>
  448: </script>
  449: ENDSCRIPT
  450:     return $js;
  451: }
  452: 
  453: sub javascript_checkpass {
  454:     my ($now,$context) = @_;
  455:     my $nopass = &mt('You must enter a password.');
  456:     my $mismatchpass = &mt('The passwords you entered did not match.')."\n".
  457:                        &mt('Please try again.'); 
  458:     &js_escape(\$nopass);
  459:     &js_escape(\$mismatchpass);
  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 %js_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:     &js_escape(\%js_lt);
  501:     $output .= <<"ENDSCRIPT";
  502: function validate_email(client) {
  503:     field = client.uname;
  504:     if (validmail(field) == false) {
  505:         alert("$js_lt{'email'}: "+field.value+" $js_lt{'notv'}.");
  506:         return false;
  507:     }
  508:     return true;
  509: }
  510: ENDSCRIPT
  511:     $output .= "\n".'// ]]>'."\n".'</script>'."\n";
  512:     return $output;
  513: }
  514: 
  515: sub print_username_form {
  516:     my ($r,$domain,$domdesc,$cancreate,$now,$lonhost,$include,$courseid,$emailusername,
  517:         $usertype) = @_;
  518:     my %lt = &Apache::lonlocal::texthash (
  519:                                          unam => 'username',
  520:                                          udom => 'domain',
  521:                                          uemail => 'E-mail address in LON-CAPA',
  522:                                          proc => 'Proceed',
  523:                                          crac => 'Create account with a username provided by this institution',
  524:                                          clca => 'Create LON-CAPA account',
  525:                                          type => 'Type in your log-in ID and password to find out.',
  526:                                          plse => 'Please provide a password for your new account.',
  527:                                          info => 'Please provide user information and a password for your new account.',
  528:                                          yopw => 'Your password will be encrypted when sent (and stored).',
  529:                                          );
  530:     my $output;
  531:     if (ref($cancreate) eq 'ARRAY') {
  532:         if (grep(/^login$/,@{$cancreate})) {
  533:             my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
  534:             if ((($domdefaults{'auth_def'} =~/^krb/) && ($domdefaults{'auth_arg_def'} ne '')) || ($domdefaults{'auth_def'} eq 'localauth')) {
  535:                 $output = '<div class="LC_left_float"><h3>'.$lt{'crac'}.'</h3>';
  536:                 $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 />').
  537:                            '<br /><br />'.
  538:                            $lt{'type'}.
  539:                            '<br /><br />';
  540:                 $output .= &login_box($now,$lonhost,$courseid,$lt{'clca'},
  541:                                       $domain,'createaccount').'</div>';
  542:             }
  543:         }
  544:         if (grep(/^email$/,@{$cancreate})) {
  545:             $output .= '<div class="LC_left_float"><h3>'.&mt('Create account with an e-mail address as your username').'</h3>';
  546:             my ($captchaform,$error,$captcha) = &Apache::loncommon::captcha_display('usercreation',$lonhost);
  547:             if ($error) {
  548:                 my $helpdesk = '/adm/helpdesk?origurl=%2fadm%2fcreateaccount';
  549:                 if ($courseid ne '') {
  550:                     $helpdesk .= '&courseid='.$courseid;
  551:                 }
  552:                 $output .= '<span class="LC_error">'.
  553:                            &mt('An error occurred generating the validation code[_1] required for an e-mail address to be used as username.','<br />').
  554:                            '</span><br /><br />'.
  555:                            &mt('[_1]Contact the helpdesk[_2] or [_3]reload[_2] the page and try again.',
  556:                                '<a href="'.$helpdesk.'">','</a>','<a href="javascript:window.location.reload()">');
  557:             } else {
  558:                 if (grep(/^login$/,@{$cancreate})) {
  559:                     $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 />'.
  560:                                $lt{'plse'}.'<br />'.
  561:                                $lt{'yopw'}.'<br />';
  562:                 } else {
  563:                     my $prompt = $lt{'plse'};
  564:                     if (ref($emailusername) eq 'HASH') {
  565:                         if (ref($emailusername->{$usertype}) eq 'HASH') {
  566:                             if (keys(%{$emailusername->{$usertype}}) > 0) {
  567:                                 $prompt = $lt{'info'};
  568:                             }
  569:                         }
  570:                     }
  571:                     $output .= $prompt.'<br />'.
  572:                                $lt{'yopw'}.'<br />';
  573:                 }
  574:                 $output .= &print_dataentry_form($r,$domain,$lonhost,$include,$now,$captchaform,
  575:                                                  $courseid,$emailusername,$captcha,$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:     my ($is_balancer) = &Apache::lonnet::check_loadbalancing($username,$domain);
  864:     if ($is_balancer) {
  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:     return;
  879: }
  880: 
  881: #
  882: # The screen that the user gets to create his or her account
  883: # Desired username, desired password, etc
  884: # Stores token to store DES-key and stage during creation session
  885: #
  886: sub print_dataentry_form {
  887:     my ($r,$domain,$lonhost,$include,$now,$captchaform,$courseid,$emailusername,$captcha,
  888:         $usertype) = @_;
  889:     my ($error,$output);
  890:     if (open(my $jsh,"<$include/londes.js")) {
  891:         while(my $line = <$jsh>) {
  892:             $r->print($line);
  893:         }
  894:         close($jsh);
  895:         $output = &javascript_setforms($now,$emailusername,$captcha,$usertype)."\n".
  896:                   &javascript_checkpass($now,'email');
  897:         my ($lkey,$ukey) = &Apache::loncommon::des_keys();
  898:         my ($lextkey,$uextkey) = &getkeys($lkey,$ukey);
  899:         my $logtoken=Apache::lonnet::reply('tmpput:'.$ukey.$lkey.'&createaccount:createaccount',
  900:                                            $lonhost);
  901:         $output .=
  902:             '<form name="createaccount" method="post" target="_top" action="/adm/createaccount">';
  903:         if ($courseid ne '') {
  904:             $output .= '<input type="hidden" name="courseid" value="'.$courseid.'"/>'."\n";
  905:         }
  906:         if (ref($emailusername) eq 'HASH') {
  907:             if (ref($emailusername->{$usertype}) eq 'HASH') {
  908:                 foreach my $field (sort(keys(%{$emailusername->{$usertype}}))) {
  909:                     $output .= '<input type="hidden" name="'.$field.'" value="" />'."\n";
  910:                 }
  911:                 $output .= '<input type="hidden" name="type" value="" />'."\n";
  912:             }
  913:         }
  914:         if ($captcha eq 'original') {
  915:             $output .= '
  916:    <input type="hidden" name="crypt" value="" />
  917:    <input type="hidden" name="code" value="" />
  918: ';
  919:         } elsif ($captcha eq 'recaptcha') {
  920:             $output .= '
  921:    <input type="hidden" name="recaptcha_challenge_field" value="" />
  922:    <input type="hidden" name="recaptcha_response_field" value="" />
  923: ';
  924:         }
  925:         $output .= <<"ENDSERVERFORM";
  926:    <input type="hidden" name="logtoken" value="$logtoken" />
  927:    <input type="hidden" name="serverid" value="$lonhost" />
  928:    <input type="hidden" name="uname" value="" />
  929:    <input type="hidden" name="upass" value="" />
  930:    <input type="hidden" name="udom" value="" />
  931:    <input type="hidden" name="phase" value="createaccount" />
  932:    <input type="hidden" name="create_with_email" value="1" />
  933:   </form>
  934: ENDSERVERFORM
  935:         my $beginclientform = '<form name="newemail" method="post" action="" '.
  936:                               'onsubmit="return checkpass('."'createaccount','newemail'".');">'."\n";
  937:         my $endclientform = '<input type="hidden" name="udom" value="'.$domain.'" />'."\n".
  938:                             '<input type="hidden" name="lextkey" value="'.$lextkey.'" />'."\n".
  939:                             '<input type="hidden" name="uextkey" value="'.$uextkey.'" />'."\n".
  940:                             '</form>'."\n".
  941:                             '<p class="LC_info">'.&mt('Fields marked [_1]*[_2] are required.','<b>','</b>').'</p>';
  942:         my ($datatable,$rowcount) =
  943:             &Apache::loncreateuser::personal_data_display('',$domain,'email','selfcreate',
  944:                                                           '','',$now,$captchaform,
  945:                                                           $emailusername,$usertype);
  946:         if ($rowcount) {
  947:             $output .= '<div class="LC_left_float">'.$beginclientform.$datatable.$endclientform;
  948:         } else {
  949:             $output .= $beginclientform.$endclientform;
  950:         }
  951:         if ($rowcount) {
  952:             $output .= '</div>'."\n".
  953:                        '<div class="LC_clear_float_footer"></div>'."\n";
  954:         }
  955:     } else {
  956:         $output = &mt('Could not load javascript file [_1]','<tt>londes.js</tt>');
  957:     }
  958:     return $output;
  959: }
  960: 
  961: #
  962: # Retrieve rules for generating accounts from domain configuration
  963: # Can the user make a new account or just self-enroll?
  964: 
  965: sub get_creation_controls {
  966:     my ($domain,$usercreation) = @_;
  967:     my (@cancreate,@statustocreate,$emailusername);
  968:     if (ref($usercreation) eq 'HASH') {
  969:         if (ref($usercreation->{'cancreate'}) eq 'HASH') {
  970:             if (ref($usercreation->{'cancreate'}{'statustocreate'}) eq 'ARRAY') {
  971:                 @statustocreate = @{$usercreation->{'cancreate'}{'statustocreate'}};
  972:                 if (@statustocreate == 0) {
  973:                     my ($othertitle,$usertypes,$types) =
  974:                         &Apache::loncommon::sorted_inst_types($domain);
  975:                     if (ref($types) eq 'ARRAY') {
  976:                         if (@{$types} == 0) {
  977:                             @statustocreate = ('default');
  978:                         }
  979:                     } else {
  980:                         @statustocreate = ('default');
  981:                     }
  982:                 }
  983:             } else {
  984:                 @statustocreate = ('default');
  985:                 my ($othertitle,$usertypes,$types) =
  986:                     &Apache::loncommon::sorted_inst_types($domain);
  987:                 if (ref($types) eq 'ARRAY') {
  988:                     push(@statustocreate,@{$types});
  989:                 }
  990:             }
  991:             if (ref($usercreation->{'cancreate'}{'selfcreate'}) eq 'ARRAY') {
  992:                 @cancreate = @{$usercreation->{'cancreate'}{'selfcreate'}};
  993:             } elsif (($usercreation->{'cancreate'}{'selfcreate'} ne 'none') &&
  994:                      ($usercreation->{'cancreate'}{'selfcreate'} ne '')) {
  995:                 @cancreate = ($usercreation->{'cancreate'}{'selfcreate'});
  996:             }
  997:             if (ref($usercreation->{'cancreate'}{'emailusername'}) eq 'HASH') {
  998:                 $emailusername = $usercreation->{'cancreate'}{'emailusername'};
  999:             } else {
 1000:                 $emailusername = {
 1001:                                     default =>  {
 1002:                                                    'lastname' => '1',
 1003:                                                    'firstname' => 1,
 1004:                                                 },
 1005:                                  };
 1006:             }
 1007:         }
 1008:     }
 1009:     return (\@cancreate,\@statustocreate,$emailusername);
 1010: }
 1011: 
 1012: sub create_account {
 1013:     my ($r,$domain,$domdesc,$dataref) = @_;
 1014:     my $error    = '<span class="LC_error">'.&mt('Error:').' ';
 1015:     my $end      = '</span><br /><br />';
 1016:     my $rtnlink  = '<a href="javascript:history.back();">'.
 1017:                     &mt('Return to previous page').'</a>'.
 1018:                     &Apache::loncommon::end_page();
 1019:     my $output;
 1020:     if (ref($dataref) eq 'HASH') {
 1021:         my ($username,$encpass,$serverid,$courseid,$id,$firstname,$middlename,$lastname,
 1022:             $generation,$inststatus);
 1023:         $username   = $dataref->{'username'};
 1024:         $encpass    = $dataref->{'upass'};
 1025:         $serverid   = $dataref->{'serverid'};
 1026:         $courseid   = $dataref->{'courseid'};
 1027:         $id         = $dataref->{'id'};
 1028:         $firstname  = $dataref->{'firstname'};
 1029:         $middlename = $dataref->{'middlename'};
 1030:         $lastname   = $dataref->{'lastname'};
 1031:         $generation = $dataref->{'generation'};
 1032:         $inststatus = $dataref->{'inststatus'};
 1033: 
 1034:         my $currhome = &Apache::lonnet::homeserver($username,$domain);
 1035:         unless ($currhome eq 'no_host') {
 1036:             $output = &mt('User account requested for username: [_1] in domain: [_2] already exists.',$username,$domain);
 1037:             return ('fail',$error.$output.$end.$rtnlink);
 1038:         }
 1039: 
 1040: # Split the logtoken to retrieve the DES key and decrypt the encypted password
 1041: 
 1042:         my ($key,$caller)=split(/&/,$dataref->{'tmpinfo'});
 1043:         if ($caller eq 'createaccount') {
 1044:             my $upass = &Apache::loncommon::des_decrypt($key,$encpass);
 1045: 
 1046: # See if we are allowed to use the proposed student/employee ID,
 1047: # as per domain rules; if not, student/employee will be left blank.
 1048: 
 1049:             if ($id ne '') {
 1050:                 my ($result,$userchkmsg) = &check_id($username,$domain,$id,$domdesc,'email');
 1051:                 if ($result eq 'fail') {
 1052:                     $output = $error.&mt('Invalid ID format').$end.
 1053:                               $userchkmsg;
 1054:                     undef($id);
 1055:                 }
 1056:             }
 1057: 
 1058: # Create an internally authenticated account with password $upass
 1059: # if the user account does not already exist.
 1060: # Assign student/employee id, first name, last name, etc.
 1061: 
 1062:             my $result =
 1063:                 &Apache::lonnet::modifyuser($domain,$username,$id,
 1064:                                             'internal',$upass,$firstname,$middlename,
 1065:                                             $lastname,$generation,undef,undef,$username);
 1066:             $output = &mt('Generating user: [_1]',$result);
 1067: 
 1068: # Now that the user account exists, retrieve the homeserver, and include it in the output.
 1069: 
 1070:             my $uhome = &Apache::lonnet::homeserver($username,$domain);
 1071:             unless (($inststatus eq 'default') || ($inststatus eq '')) {
 1072:                 &Apache::lonnet::put('environment',{inststatus => $inststatus},$domain,$username);
 1073:             }
 1074:             $output .= '<br />'.&mt('Home server: [_1]',$uhome).' '.
 1075:                        &Apache::lonnet::hostname($uhome).'<br /><br />';
 1076:             return ('ok',$output,$uhome);
 1077:         } else {
 1078:             $output = &mt('Unable to retrieve your account creation information - unexpected context');
 1079:             undef($encpass);
 1080:             return ('fail',$error.$output.$end.$rtnlink);
 1081:         }
 1082:     } else {
 1083:         $output = &mt('Unable to retrieve information for your account request.');
 1084:         return ('fail',$error.$output.$end.$rtnlink);
 1085:     }
 1086: }
 1087: 
 1088: sub username_validation {
 1089:     my ($r,$username,$domain,$domdesc,$contact_name,$contact_email,$courseid,
 1090:         $lonhost,$statustocreate) = @_;
 1091: # $r: request object
 1092: # $username,$domain: for the user who needs to be validated
 1093: # $domdesc: full name of the domain (for error messages)
 1094: # $contact_name, $contact_email: name and email for user assistance (for error messages in &username_check)
 1095: # $courseid: ID of the course if user came to username_validation via self-enroll link,
 1096: #             passed to start_session()
 1097: # $lonhost: LON-CAPA lonHostID
 1098: # $statustocreate: -> inststatus in username_check ('faculty', 'staff', 'student', ...)
 1099:  
 1100: #
 1101: # Sanitize incoming username and domain
 1102: #
 1103:     $username= &LONCAPA::clean_username($username);
 1104:     $domain = &LONCAPA::clean_domain($domain);
 1105: 
 1106: #
 1107: # Check if LON-CAPA account already exists for $username:$domain
 1108: #
 1109:     my $uhome = &Apache::lonnet::homeserver($username,$domain);
 1110: 
 1111:     my $output;
 1112: 
 1113: # Retrieve DES key from server using logtoken
 1114:  
 1115:     my $tmpinfo=Apache::lonnet::reply('tmpget:'.$env{'form.logtoken'},$env{'form.serverid'});
 1116:     if (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost')) {
 1117:         $output = &mt('Information needed to verify your login information is missing, inaccessible or expired.')
 1118:                  .'<br />'.&mt('You may need to reload the previous page to obtain a new token.');
 1119:         return ('fail',$output);
 1120:     } else {
 1121:         my $reply = &Apache::lonnet::reply('tmpdel:'.$env{'form.logtoken'},$env{'form.serverid'});
 1122:         unless ($reply eq 'ok') {
 1123:             $output = &mt('Session could not be opened.');
 1124:             return ('fail',$output); 
 1125:         }
 1126:     }
 1127: 
 1128: # Split the logtoken to retrieve the DES key and decrypt the encypted password
 1129: 
 1130:     my ($key,$caller)=split(/&/,$tmpinfo);
 1131:     my $upass;
 1132:     if ($caller eq 'createaccount') {
 1133:         $upass = &Apache::loncommon::des_decrypt($key,$env{'form.upass'});
 1134:     } else {
 1135:         $output = &mt('Unable to retrieve your log-in information - unexpected context');
 1136:         return ('fail',$output);
 1137:     }
 1138:     if ($uhome ne 'no_host') {
 1139:         my $result = &Apache::lonnet::authenticate($username,$upass,$domain);
 1140:         if ($result ne 'no_host') { 
 1141:             my $redirect = &start_session($r,$username,$domain,$uhome,$courseid);
 1142:             if ($redirect) {
 1143:                 return ($redirect);
 1144:             }
 1145:             $output = '<br /><br />'.
 1146:                       &mt('A LON-CAPA account already exists for username [_1] at this institution ([_2]).',
 1147:                           '<tt>'.$username.'</tt>',$domdesc).'<br />'.
 1148:                       &mt('The password entered was also correct so you have been logged in.');
 1149:             return ('existingaccount',$output);
 1150:         } else {
 1151:             $output = &login_failure_msg($courseid);
 1152:         }
 1153:     } else {
 1154:         my $primlibserv = &Apache::lonnet::domain($domain,'primary');
 1155:         my $authok;
 1156:         my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 1157:         if ((($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) || 
 1158:              ($domdefaults{'auth_def'} eq 'localauth')) {
 1159:             my $checkdefauth = 1;
 1160:             $authok = 
 1161:                 &Apache::lonnet::reply("encrypt:auth:$domain:$username:$upass:$checkdefauth",$primlibserv);
 1162:         } else {
 1163:             $authok = 'non_authorized';
 1164:         }
 1165:         if ($authok eq 'authorized') {
 1166:             $output = &username_check($username,$domain,$domdesc,$courseid,$lonhost,
 1167:                                       $contact_email,$contact_name,undef,
 1168:                                       $statustocreate);
 1169:         } else {
 1170:             $output = &login_failure_msg($courseid);
 1171:         }
 1172:     }
 1173:     return ('ok',$output);
 1174: }
 1175: 
 1176: sub login_failure_msg {
 1177:     my ($courseid) = @_;
 1178:     my $url;
 1179:     if ($courseid ne '') {
 1180:         $url = "/adm/selfenroll?courseid=".$courseid;
 1181:     } else {
 1182:         $url = "/adm/createaccount";
 1183:     }
 1184:     my $output = '<h4>'.&mt('Authentication failed').'</h4><div class="LC_warning">'.
 1185:                  &mt('Username and/or password could not be authenticated.').
 1186:                  '</div>'.
 1187:                  &mt('Please check the username and password.').'<br /><br />';
 1188:                  '<a href="'.$url.'">'.&mt('Try again').'</a>';
 1189:     return $output;
 1190: }
 1191: 
 1192: sub username_check {
 1193:     my ($username,$domain,$domdesc,$courseid,$lonhost,$contact_email,
 1194:         $contact_name,$sso_logout,$statustocreate,$shibenv) = @_;
 1195:     my (%rulematch,%inst_results,$checkfail,$rowcount,$editable,$output,$msg,
 1196:         %alerts,%curr_rules,%got_rules);
 1197:     &call_rulecheck($username,$domain,\%alerts,\%rulematch,
 1198:                     \%inst_results,\%curr_rules,\%got_rules,'username');
 1199:     if (ref($alerts{'username'}) eq 'HASH') {
 1200:         if (ref($alerts{'username'}{$domain}) eq 'HASH') {
 1201:             if ($alerts{'username'}{$domain}{$username}) {
 1202:                 if (ref($curr_rules{$domain}) eq 'HASH') {
 1203:                     $output =
 1204:                         &Apache::loncommon::instrule_disallow_msg('username',$domdesc,1,
 1205:                                                                   'selfcreate').
 1206:                         &Apache::loncommon::user_rule_formats($domain,$domdesc,
 1207:                                 $curr_rules{$domain}{'username'},'username');
 1208:                 }
 1209:                 $checkfail = 'username';
 1210:             }
 1211:         }
 1212:     }
 1213:     if (!$checkfail) {
 1214:         if (ref($statustocreate) eq 'ARRAY') {
 1215:             $checkfail = 'inststatus';
 1216:             if (ref($inst_results{$username.':'.$domain}{inststatus}) eq 'ARRAY') {
 1217:                 foreach my $inststatus (@{$inst_results{$username.':'.$domain}{inststatus}}) {
 1218:                     if (grep(/^\Q$inststatus\E$/,@{$statustocreate})) {
 1219:                         undef($checkfail);
 1220:                         last;
 1221:                     }
 1222:                 }
 1223:             } elsif (grep(/^default$/,@{$statustocreate})) {
 1224:                 undef($checkfail);
 1225:             }
 1226:         }
 1227:     }
 1228:     if (!$checkfail) {
 1229:         $output = '<form method="post" action="/adm/createaccount">';
 1230:         if (ref($shibenv) eq 'HASH') {
 1231:             foreach my $key (keys(%{$shibenv})) {
 1232:                 if ($ENV{$shibenv->{$key}} ne '') {
 1233:                     $inst_results{$username.':'.$domain}{$key} = $ENV{$shibenv->{$key}};
 1234:                 }
 1235:             }
 1236:         }
 1237:         (my $datatable,$rowcount,$editable) = 
 1238:             &Apache::loncreateuser::personal_data_display($username,$domain,1,'selfcreate',
 1239:                                                          $inst_results{$username.':'.$domain});
 1240:         if ($rowcount > 0) {
 1241:             $output .= $datatable;
 1242:         }
 1243:         $output .=  '<br /><br /><input type="hidden" name="uname" value="'.$username.'" />'."\n".
 1244:                     '<input type="hidden" name="udom" value="'.$domain.'" />'."\n".
 1245:                     '<input type="hidden" name="phase" value="username_activation" />';
 1246:         my $now = time;
 1247:         my %info = ('ip'         => $ENV{'REMOTE_ADDR'},
 1248:                     'time'       => $now,
 1249:                     'domain'     => $domain,
 1250:                     'username'   => $username);
 1251:         my $authtoken = &Apache::lonnet::tmpput(\%info,$lonhost,'createaccount');
 1252:         if ($authtoken !~ /^error/ && $authtoken ne 'no_such_host') {
 1253:             $output .= '<input type="hidden" name="authtoken" value="'.&HTML::Entities::encode($authtoken,'&<>"').'" />';
 1254:         } else {
 1255:             $output = &mt('An error occurred when storing a token').'<br />'.
 1256:                       &mt('You will not be able to proceed to the next stage of account creation').
 1257:                       &linkto_email_help($contact_email,$domdesc);
 1258:             $checkfail = 'authtoken';
 1259:         }
 1260:     }
 1261:     if ($checkfail) { 
 1262:         $msg = '<br /><h4>'.&mt('Account creation unavailable').'</h4>';
 1263:         if ($checkfail eq 'username') {
 1264:             $msg .= '<span class="LC_warning">'.
 1265:                      &mt('A LON-CAPA account may not be created with the username you use.').
 1266:                      '</span><br /><br />'.$output;
 1267:         } elsif ($checkfail eq 'authtoken') {
 1268:             $msg .= '<span class="LC_error">'.&mt('Error creating token.').'</span>'.
 1269:                     '<br />'.$output;
 1270:         } elsif ($checkfail eq 'inststatus') {
 1271:             $msg .= '<span class="LC_warning">'.
 1272:                      &mt('You are not permitted to create a LON-CAPA account.').
 1273:                      '</span><br /><br />'.$output;
 1274:         }
 1275:         $msg .= &mt('Please contact the [_1] ([_2]) for assistance.',
 1276:                 $contact_name,$contact_email).'<br /><hr />'.
 1277:                 $sso_logout;
 1278:         &Apache::lonnet::logthis("ERROR: failure type of '$checkfail' when performing username check to create account for authenticated user: $username, in domain $domain");
 1279:     } else {
 1280:         if ($courseid ne '') {
 1281:             $output .= '<input type="hidden" name="courseid" value="'.$courseid.'" />';
 1282:         }
 1283:         $output .= '<input type="submit" name="newaccount" value="'.
 1284:                    &mt('Create LON-CAPA account').'" /></form>';
 1285:         if ($rowcount) {
 1286:             if ($editable) {
 1287:                 if ($courseid ne '') { 
 1288:                     $msg = '<br /><h4>'.&mt('User information').'</h4>';
 1289:                 }
 1290:                 $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 />';
 1291:             } else {
 1292:                  if ($courseid ne '') {
 1293:                      $msg = '<h4>'.&mt('Review user information').'</h4>';
 1294:                  }
 1295:                  $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 />';
 1296:             }
 1297:         } else {
 1298:             if ($courseid ne '') {
 1299:                 $msg = '<h4>'.&mt('Confirmation').'</h4>';
 1300:             }
 1301:             $msg .= &mt('Confirm that you wish to create an account.');
 1302:         }
 1303:         $msg .= $output;
 1304:     }
 1305:     return $msg;
 1306: }
 1307: 
 1308: sub username_activation {
 1309:     my ($r,$username,$domain,$domdesc,$courseid) = @_;
 1310:     my $output;
 1311:     my $error     = '<span class="LC_error">'.&mt('Error:').' ';
 1312:     my $end       = '</span><br /><br />';
 1313:     my $rtnlink   = '<a href="javascript:history.back();">'.
 1314:                     &mt('Return to previous page').'</a>'.
 1315:                     &Apache::loncommon::end_page();
 1316:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
 1317:     my %data = &Apache::lonnet::tmpget($env{'form.authtoken'});
 1318:     my $now = time;
 1319:     my $earlyout;
 1320:     my $timeout = 300;
 1321:     if (keys(%data) == 0) {
 1322:         $output = &mt('Sorry, your authentication has expired.');
 1323:         $earlyout = 'fail';
 1324:     }
 1325:     if (($data{'time'} !~ /^\d+$/) ||
 1326:         ($data{'domain'} ne $domain) || 
 1327:         ($data{'username'} ne $username)) {
 1328:         $earlyout = 'fail';
 1329:         $output = &mt('The credentials you provided could not be verified.');   
 1330:     } elsif ($now - $data{'time'} > $timeout) {
 1331:         $earlyout = 'fail';
 1332:         $output = &mt('Sorry, your authentication has expired.');
 1333:     }
 1334:     if ($earlyout ne '') {
 1335:         my $link = '/adm/createaccount';
 1336:         if (&Apache::lonnet::domain($domain) ne '') {
 1337:             $link .= "?domain=$domain"; 
 1338:         }
 1339:         $output .= '<br />'.&mt('Please [_1]start again[_2].',
 1340:                                 '<a href="'.$link.'">','</a>');
 1341:         return($earlyout,$output);
 1342:     }
 1343:     if ((($domdefaults{'auth_def'} =~/^krb(4|5)$/) && 
 1344:          ($domdefaults{'auth_arg_def'} ne '')) || 
 1345:         ($domdefaults{'auth_def'} eq 'localauth')) {
 1346:         if ($env{'form.courseid'} ne '') {
 1347:             my $id = $env{'form.cid'}; 
 1348:             my ($result,$userchkmsg) = &check_id($username,$domain,$id,$domdesc,'institutional');
 1349:             if ($result eq 'fail') {
 1350:                 $output = $error.&mt('Invalid ID format').$end.
 1351:                           $userchkmsg.$rtnlink;
 1352:                 return ('fail',$output);
 1353:             }
 1354:         }
 1355:         # Call modifyuser
 1356:         my (%rulematch,%inst_results,%curr_rules,%got_rules,%alerts,%info);
 1357:         &call_rulecheck($username,$domain,\%alerts,\%rulematch,
 1358:                         \%inst_results,\%curr_rules,\%got_rules);
 1359:         my @userinfo = ('firstname','middlename','lastname','generation',
 1360:                         'permanentemail','id');
 1361:         my %canmodify = 
 1362:             &Apache::loncreateuser::selfcreate_canmodify('selfcreate',$domain,
 1363:                                                          \@userinfo,\%inst_results);
 1364:         foreach my $item (@userinfo) {
 1365:             if ($canmodify{$item}) {
 1366:                 $info{$item} = $env{'form.c'.$item};
 1367:             } else {
 1368:                 $info{$item} = $inst_results{$username.':'.$domain}{$item}; 
 1369:             }
 1370:         }
 1371:         if (ref($inst_results{$username.':'.$domain}{'inststatus'}) eq 'ARRAY') {
 1372:             my @inststatuses = @{$inst_results{$username.':'.$domain}{'inststatus'}};
 1373:             $info{'inststatus'} = join(':',map { &escape($_); } @inststatuses);
 1374:         }
 1375:         my $result =
 1376:             &Apache::lonnet::modifyuser($domain,$username,$env{'form.cid'},
 1377:                           $domdefaults{'auth_def'},
 1378:                           $domdefaults{'auth_arg_def'},$info{'firstname'},
 1379:                           $info{'middlename'},$info{'lastname'},
 1380:                           $info{'generation'},undef,undef,
 1381:                           $info{'permanentemail'},$info{'inststatus'});
 1382:         if ($result eq 'ok') {
 1383:             my $delete = &Apache::lonnet::tmpdel($env{'form.authtoken'});
 1384:             $output = &mt('A LON-CAPA account has been created for username: [_1] in domain: [_2].',$username,$domain);
 1385:             my $uhome=&Apache::lonnet::homeserver($username,$domain,'true');
 1386:             my $nostart = 1;
 1387:             my $response = 'ok';
 1388:             my $redirect = &start_session($r,$username,$domain,$uhome,$courseid);
 1389:             if ($redirect) {
 1390:                 $response = $redirect;
 1391:             }
 1392:             return ($response,$output,$nostart);
 1393:         } else {
 1394:             $output = &mt('Account creation failed for username: [_1] in domain: [_2].',$username,$domain).'<br /><span class="LC_error">'.&mt('Error: [_1]',$result).'</span>';
 1395:             return ('fail',$output);
 1396:         }
 1397:     } else {
 1398:         $output = &mt('User account creation is not available for the current default authentication type.')."\n";
 1399:         return('fail',$output);
 1400:     }
 1401: }
 1402: 
 1403: sub check_id {
 1404:     my ($username,$domain,$id,$domdesc,$usernametype) = @_;
 1405:     # Check student/employee ID format
 1406:     # Is proposed student/employee ID acceptable according to domain's rules.  
 1407:     # $domdesc is just used for user error messages
 1408:     my (%alerts,%rulematch,%inst_results,%curr_rules,%checkhash);
 1409:     my %checks = ('id' => 1);
 1410:     %{$checkhash{$username.':'.$domain}} = (
 1411:                                             'newuser' => 1,
 1412:                                             'id' => $id,
 1413:                                            );
 1414:     &Apache::loncommon::user_rule_check(\%checkhash,\%checks,\%alerts,
 1415:                                         \%rulematch,\%inst_results,\%curr_rules);
 1416:     if (ref($alerts{'id'}) eq 'HASH') {
 1417:         if (ref($alerts{'id'}{$domain}) eq 'HASH') {
 1418:             if ($alerts{'id'}{$domain}{$env{'form.cid'}}) {
 1419:                 my $userchkmsg;
 1420:                 if (ref($curr_rules{$domain}) eq 'HASH') {
 1421:                     if ($usernametype eq 'email') {
 1422:                         $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.');
 1423:                     } else {
 1424:                         $userchkmsg =
 1425:                             &Apache::loncommon::instrule_disallow_msg('id',
 1426:                                                                       $domdesc,1).
 1427:                             &Apache::loncommon::user_rule_formats($domain,
 1428:                                 $domdesc,$curr_rules{$domain}{'id'},'id');
 1429:                     }
 1430:                 }
 1431:                 return ('fail',$userchkmsg);
 1432:             }
 1433:         }
 1434:     }
 1435:     return; 
 1436: }
 1437: 
 1438: sub invalid_state {
 1439:     my ($error,$domdesc,$contact_name,$contact_email,$msgtext) = @_;
 1440:     my $msg = '<h3>'.&mt('Account creation unavailable').'</h3><span class="LC_error">';
 1441:     if ($error eq 'baduseremail') {
 1442:         $msg .= &mt('The e-mail address you provided does not appear to be a valid address.');
 1443:     } elsif ($error eq 'badusername') {
 1444:         $msg .= &mt('The e-mail address you provided contains characters which prevent its use as a username in LON-CAPA.');
 1445:     } elsif ($error eq 'existinguser') {
 1446:         $msg .= &mt('The e-mail address you provided is already in use as a username in LON-CAPA at this institution.');
 1447:     } elsif ($error eq 'userrules') {
 1448:         $msg .= &mt('Username rules at this institution do not allow the e-mail address you provided to be used as a username.');
 1449:     } elsif ($error eq 'userformat') {
 1450:         $msg .= &mt('The e-mail address you provided may not be used as a username at this LON-CAPA institution.');
 1451:     } elsif ($error eq 'captcha') {
 1452:         $msg .= &mt('Validation of the code you entered failed.');
 1453:     } elsif ($error eq 'noemails') {
 1454:         $msg .= &mt('Creation of a new user account using an e-mail address as username is not permitted at this LON-CAPA institution.');
 1455:     }
 1456:     $msg .= '</span>';
 1457:     if ($msgtext) {
 1458:         $msg .= '<br />'.$msgtext;
 1459:     }
 1460:     $msg .= &linkto_email_help($contact_email,$domdesc,$error);
 1461:     return $msg;
 1462: }
 1463: 
 1464: sub linkto_email_help {
 1465:     my ($contact_email,$domdesc,$error) = @_;
 1466:     my $msg;
 1467:     my $href = '/adm/helpdesk';
 1468:     if ($contact_email ne '') {
 1469:         my $escuri = &HTML::Entities::encode('/adm/createaccount','&<>"');
 1470:         $href .= '?origurl='.$escuri;
 1471:         if ($error eq 'existinguser') {
 1472:             my $escemail = &HTML::Entities::encode($env{'form.useremail'});
 1473:             $href .= '&useremail='.$escemail.'&useraccount='.$escemail;
 1474:         }
 1475:         $msg .= '<br />'.&mt('You may wish to contact the [_1]LON-CAPA helpdesk[_2] for [_3].','<a href="'.$href.'">','</a>',$domdesc).'<br />';
 1476:     } else {
 1477:         $msg .= '<br />'.&mt('You may wish to send an e-mail to the server administrator: [_1] for [_2].',$Apache::lonnet::perlvar{'AdmEMail'},$domdesc).'<br />';
 1478:     }
 1479:     return $msg;
 1480: }
 1481: 
 1482: sub getkeys {
 1483:     my ($lkey,$ukey) = @_;
 1484:     my $lextkey=hex($lkey);
 1485:     if ($lextkey>2147483647) { $lextkey-=4294967296; }
 1486: 
 1487:     my $uextkey=hex($ukey);
 1488:     if ($uextkey>2147483647) { $uextkey-=4294967296; }
 1489:     return ($lextkey,$uextkey);
 1490: }
 1491: 
 1492: sub serverform {
 1493:     my ($logtoken,$lonhost,$mailtoken,$courseid,$context) = @_;
 1494:     my $phase = 'username_validation';
 1495:     my $catalog_elements;
 1496:     if ($context eq 'selfenroll') {
 1497:         $phase = 'selfenroll_login';
 1498:     }
 1499:     if ($courseid ne '') {
 1500:         $catalog_elements = &Apache::lonhtmlcommon::echo_form_input(['courseid','phase']);
 1501:     } 
 1502:     my $output = <<ENDSERVERFORM;
 1503:   <form name="server" method="post" action="/adm/createaccount">
 1504:    <input type="hidden" name="logtoken" value="$logtoken" />
 1505:    <input type="hidden" name="token" value="$mailtoken" />
 1506:    <input type="hidden" name="serverid" value="$lonhost" />
 1507:    <input type="hidden" name="uname" value="" />
 1508:    <input type="hidden" name="upass" value="" />
 1509:    <input type="hidden" name="udom" value="" />
 1510:    <input type="hidden" name="phase" value="$phase" />
 1511:    <input type="hidden" name="courseid" value="$courseid" />
 1512:    $catalog_elements
 1513:   </form>
 1514: ENDSERVERFORM
 1515:     return $output;
 1516: }
 1517: 
 1518: sub store_request {
 1519:     my ($dom,$username,$val,$dataref,$settings) = @_;
 1520:     my $output;
 1521:     my $domconfiguser = &Apache::lonnet::get_domainconfiguser($dom);
 1522:     my $key = &escape($username);
 1523:     my $now = time();
 1524:     if (&Apache::lonnet::put('usernamequeue', { $key.'_'.$val => $now },
 1525:                              $dom,$domconfiguser) eq 'ok') {
 1526:         if (ref($dataref) eq 'HASH') {
 1527:             my $logtoken = $dataref->{'tmpinfo'};
 1528:             my $serverid = $dataref->{'serverid'}; 
 1529:             if ($logtoken && $serverid) {
 1530:                 my $tmpinfo=Apache::lonnet::reply('tmpget:'.$logtoken,$serverid);
 1531:                 unless (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost')) {
 1532:                     my $reply = &Apache::lonnet::reply('tmpdel:'.$logtoken,$serverid);
 1533:                     if ($reply eq 'ok') {
 1534:                         my ($key,$caller)=split(/&/,$tmpinfo);
 1535:                         $dataref->{'key'} = $key;
 1536:                         undef($dataref->{'tmpinfo'});
 1537:                         undef($dataref->{'serverid'});
 1538:                     }
 1539:                 }
 1540:             }
 1541:         }
 1542:         my %userrequest = ( $username => $dataref );
 1543:         $userrequest{$username}{timestamp} = $now;
 1544:         $userrequest{$username}{status} = $val;
 1545:         my $notifylist;
 1546:         if (ref($settings) eq 'HASH') {
 1547:             if (ref($settings->{'cancreate'}) eq 'HASH') {
 1548:                 if (ref($settings->{'cancreate'}{'notify'}) eq 'HASH') {
 1549:                     my $notifylist = $settings->{'cancreate'}{'notify'}{'approval'};
 1550:                     if ($notifylist) {
 1551:                         my $sender = $domconfiguser.':'.$dom;
 1552:                         my $domdesc = &Apache::lonnet::domain($dom,'description');
 1553:                         my $fullname;
 1554:                         if (ref($dataref) eq 'HASH') {
 1555:                             if ($dataref->{'firstname'}) {
 1556:                                 $fullname = $dataref->{'firstname'};
 1557:                             }
 1558:                             if ($dataref->{'lastname'}) {
 1559:                                 $fullname .= ' '.$dataref->{'lastname'};
 1560:                             }
 1561:                             $fullname =~ s/^\s+|\s+$//g; 
 1562:                         }
 1563:                         &Apache::loncoursequeueadmin::send_selfserve_notification($notifylist,
 1564:                                                      "$fullname ($username)",
 1565:                                                      undef,$domdesc,$now,'usernamereq',$sender);
 1566:                     }
 1567:                 }
 1568:             }
 1569:         }
 1570:         my $userresult =
 1571:             &Apache::lonnet::put('nohist_requestedusernames',\%userrequest,$dom,$domconfiguser);
 1572:         $output = '<p class="LC_info">'.
 1573:                   &mt('Your request for a LON-CAPA account has been submitted for approval.').
 1574:                   '</p>'.
 1575:                   '<p class="LC_info">'.
 1576:                   &mt('An e-mail will be sent to [_1] when your request has been reviewed by an administrator and action has been taken.',$username).
 1577:                   '</p>';
 1578:     } else {
 1579:         $output = '<span class="LC_error">'.
 1580:                   &mt('An error occurred when attempting to save your request for a LON-CAPA account.');
 1581:                   '</span>';
 1582:     }
 1583:     return $output;
 1584: }
 1585: 
 1586: sub guest_format_check {
 1587:     my ($useremail,$domain,$cancreate,$settings) = @_;
 1588:     my ($login,$format_match,$format_msg,@user_rules);
 1589:     if (ref($settings) eq 'HASH') {
 1590:         if (ref($settings->{'email_rule'}) eq 'ARRAY') {
 1591:             push(@user_rules,@{$settings->{'email_rule'}});
 1592:         }
 1593:     }
 1594:     if (@user_rules > 0) {
 1595:         my %rule_check = 
 1596:             &Apache::lonnet::inst_rulecheck($domain,$useremail,undef,
 1597:                                             'selfcreate',\@user_rules);
 1598:         if (keys(%rule_check) > 0) {
 1599:             foreach my $item (keys(%rule_check)) {
 1600:                 if ($rule_check{$item}) {
 1601:                     $format_match = 1;   
 1602:                     last;
 1603:                 }
 1604:             }
 1605:         }
 1606:     }
 1607:     if ($format_match) {
 1608:         ($login) = ($useremail =~ /^([^\@]+)\@/);
 1609:         $format_msg = '<br />'.
 1610:                       &mt("Your e-mail address uses the same internet domain as your institution's LON-CAPA service.").'<br />'.
 1611:                       &mt('Creation of a LON-CAPA account with this type of e-mail address as username is not permitted.').'<br />';
 1612:         if (ref($cancreate) eq 'ARRAY') {
 1613:             if (grep(/^login$/,@{$cancreate})) {
 1614:                 $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 />'; 
 1615:             }
 1616:         }
 1617:     }
 1618:     return $format_msg;
 1619: }
 1620: 
 1621: sub sso_logout_frag {
 1622:     my ($r,$domain) = @_;
 1623:     my $endsessionmsg;
 1624:     if (defined($r->dir_config('lonSSOUserLogoutMessageFile_'.$domain))) {
 1625:         my $msgfile = $r->dir_config('lonSSOUserLogoutMessageFile_'.$domain);
 1626:         if (-e $msgfile) {
 1627:             open(my $fh,"<$msgfile");
 1628:             $endsessionmsg = join('',<$fh>);
 1629:             close($fh);
 1630:         }
 1631:     } elsif (defined($r->dir_config('lonSSOUserLogoutMessageFile'))) {
 1632:         my $msgfile = $r->dir_config('lonSSOUserLogoutMessageFile');
 1633:         if (-e $msgfile) {     
 1634:             open(my $fh,"<$msgfile");
 1635:             $endsessionmsg = join('',<$fh>);
 1636:             close($fh);
 1637:         }
 1638:     }
 1639:     return $endsessionmsg;
 1640: }
 1641: 
 1642: sub catreturn_js {
 1643:     return  <<"ENDSCRIPT";
 1644: <script type="text/javascript">
 1645: // <![CDATA[
 1646: function ToSelfenroll(formname) {
 1647:     var formidx = getFormByName(formname);
 1648:     if (formidx > -1) {
 1649:         document.forms[formidx].action = '/adm/selfenroll';
 1650:         numidx = getIndexByName(formidx,'phase');
 1651:         if (numidx > -1) {
 1652:             document.forms[formidx].elements[numidx].value = '';   
 1653:         }
 1654:         numidx = getIndexByName(formidx,'context');
 1655:         if (numidx > -1) {
 1656:             document.forms[formidx].elements[numidx].value = '';
 1657:         }
 1658:     }
 1659:     document.forms[formidx].submit();
 1660: }
 1661: 
 1662: function ToCatalog(formname,caller) {
 1663:     var formidx = getFormByName(formname);
 1664:     if (formidx > -1) {
 1665:         document.forms[formidx].action = '/adm/coursecatalog';
 1666:         numidx = getIndexByName(formidx,'coursenum');
 1667:         if (numidx > -1) {
 1668:             if (caller != 'details') {
 1669:                 document.forms[formidx].elements[numidx].value = '';
 1670:             }
 1671:         }
 1672:     }
 1673:     document.forms[formidx].submit();
 1674: }
 1675: 
 1676: function getIndexByName(formidx,item) {
 1677:     for (var i=0;i<document.forms[formidx].elements.length;i++) {
 1678:         if (document.forms[formidx].elements[i].name == item) {
 1679:             return i;
 1680:         }
 1681:     }
 1682:     return -1;
 1683: }
 1684: 
 1685: function getFormByName(item) {
 1686:     for (var i=0; i<document.forms.length; i++) {
 1687:         if (document.forms[i].name == item) {
 1688:             return i;
 1689:         }
 1690:     }
 1691:     return -1;
 1692: }
 1693: // ]]>
 1694: </script>
 1695: ENDSCRIPT
 1696: 
 1697: }
 1698: 
 1699: 1;

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