File:  [LON-CAPA] / loncom / interface / createaccount.pm
Revision 1.58: download - view: text, annotated - select for diffs
Wed Feb 12 20:47:40 2014 UTC (10 years, 3 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6646
  - Self-creation of user accounts with e-mail address as username.
  - User information and password requested from prospective user in a single
    web form.
  - Add routines to handle creation of user accounts and notification
    following approval by Domain Coordinator.

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

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