File:  [LON-CAPA] / loncom / interface / createaccount.pm
Revision 1.64: download - view: text, annotated - select for diffs
Wed Apr 23 10:11:26 2014 UTC (10 years, 2 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Institutional ststus types can now be defined via domain configuration
  web interface by Domain Coordinator -- will supercede use of customized
  localenroll::inst_usertypes().

- Self-creation of account with e-mail address as username:
  - Domain configuration to set which status types (faculty, staff , student
    etc.) can apply to "non-institutional" usernames.
  - Processing of username requests can be either automatic or queued for
    approval depending on status type (self-reported).

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

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