File:  [LON-CAPA] / loncom / interface / createaccount.pm
Revision 1.60: download - view: text, annotated - select for diffs
Thu Feb 20 01:00:33 2014 UTC (10 years, 3 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- upasscheck<timestamp> form element not used for log-in for new user
  self-creation web form for institutional username/password.

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

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