File:  [LON-CAPA] / loncom / interface / createaccount.pm
Revision 1.65: download - view: text, annotated - select for diffs
Mon May 5 21:28:10 2014 UTC (10 years, 1 month ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Domain configuration for self-creation of accounts by users authenticated
  via Shibboleth SSO.
  - Set which environment variables provided by Shibboleth map to which
    user information fields.

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

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