File:  [LON-CAPA] / loncom / interface / createaccount.pm
Revision 1.68: download - view: text, annotated - select for diffs
Thu Jun 19 23:36:54 2014 UTC (9 years, 10 months ago) by raeburn
Branches: MAIN
CVS tags: version_2_11_0, HEAD
- Where self-creation of accounts is enabled for institutional log-in and
  also e-mail address as username, call to &javascript_setforms() needs to
  occur from within print_dataentry_form() so that args required for CAPTCHA
  validation are passed (when ReCAPTCHA or CAPTCHA are in use).

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

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