File:  [LON-CAPA] / loncom / interface / createaccount.pm
Revision 1.71: download - view: text, annotated - select for diffs
Wed Feb 17 19:15:48 2016 UTC (8 years, 3 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 5679

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

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