File:  [LON-CAPA] / loncom / interface / createaccount.pm
Revision 1.63: download - view: text, annotated - select for diffs
Sat Apr 19 20:48:43 2014 UTC (10 years, 1 month ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Correct name of inststatus item stored during account creation process
  for e-mail address as username.

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

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