Annotation of loncom/interface/createaccount.pm, revision 1.58

1.1       raeburn     1: # The LearningOnline Network
                      2: # Allow visitors to create a user account with the username being either an 
1.58    ! raeburn     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.
1.1       raeburn     6: #
1.58    ! raeburn     7: # $Id: createaccount.pm,v 1.57 2014/01/30 12:15:06 raeburn Exp $
1.1       raeburn     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;
1.12      raeburn    39: use Apache::lonhtmlcommon;
1.1       raeburn    40: use Apache::lonlocal;
1.3       raeburn    41: use Apache::lonauth;
1.1       raeburn    42: use Apache::resetpw;
                     43: use DynaLoader; # for Crypt::DES version
                     44: use Crypt::DES;
1.3       raeburn    45: use LONCAPA qw(:DEFAULT :match);
1.8       raeburn    46: use HTML::Entities;
1.1       raeburn    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:     }
1.22      raeburn    55: 
1.5       raeburn    56:     my $domain;
1.3       raeburn    57: 
1.57      raeburn    58:     my $sso_username = $r->subprocess_env->get('SSOUserUnknown');
                     59:     my $sso_domain = $r->subprocess_env->get('SSOUserDomain');
1.5       raeburn    60: 
1.56      raeburn    61:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                     62:                                             ['token','courseid','domain']);
1.27      raeburn    63:     &Apache::lonacc::get_posted_cgi($r);
                     64:     &Apache::lonlocal::get_language_handle($r);
                     65: 
1.5       raeburn    66:     if ($sso_username ne '' && $sso_domain ne '') {
                     67:         $domain = $sso_domain; 
1.27      raeburn    68:     } else {
1.56      raeburn    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:         }
1.5       raeburn    86:     }
1.1       raeburn    87:     my $domdesc = &Apache::lonnet::domain($domain,'description');
                     88:     my $contact_name = &mt('LON-CAPA helpdesk');
1.15      raeburn    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);
1.1       raeburn    94:     my $lonhost = $r->dir_config('lonHostID');
                     95:     my $include = $r->dir_config('lonIncludes');
1.4       raeburn    96:     my $start_page;
1.3       raeburn    97: 
                     98:     my $handle = &Apache::lonnet::check_for_valid_session($r);
1.30      raeburn    99:     if (($handle ne '') && ($handle !~ /^publicuser_\d+$/)) {
1.4       raeburn   100:         $start_page =
1.3       raeburn   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>'.
1.58    ! raeburn   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>').
1.6       bisitz    107:                   '</p><p><a href="/adm/loginproblems.html">'.&mt('Login problems?').'</a></p>'.$end_page);
1.20      raeburn   108:         return OK;
                    109:     }
                    110: 
1.22      raeburn   111:     my ($js,$courseid,$title);
1.48      droeschl  112:     $courseid = Apache::lonnet::is_course($env{'form.courseid'});
1.22      raeburn   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:     }
1.20      raeburn   119:     if ($env{'form.phase'} eq 'selfenroll_login') {
1.22      raeburn   120:         $title = 'Self-enroll in a LON-CAPA course';
1.4       raeburn   121:         if ($env{'form.udom'} ne '') {
                    122:             $domain = $env{'form.udom'};
                    123:         }
1.35      raeburn   124: 
                    125:         my %domconfig = 
                    126:             &Apache::lonnet::get_dom('configuration',['usercreation'],$domain);
1.58    ! raeburn   127:         my ($cancreate,$statustocreate,$emailusername) = 
1.35      raeburn   128:             &get_creation_controls($domain,$domconfig{'usercreation'});
                    129: 
1.20      raeburn   130:         my ($result,$output) =
                    131:             &username_validation($r,$env{'form.uname'},$domain,$domdesc,
                    132:                                  $contact_name,$contact_email,$courseid,
1.35      raeburn   133:                                  $lonhost,$statustocreate);
1.58    ! raeburn   134:         if ($result eq 'redirect') {
        !           135:             $r->internal_redirect('/adm/switchserver');
        !           136:             return OK;
        !           137:         } elsif ($result eq 'existingaccount') {
1.20      raeburn   138:             $r->print($output);
1.22      raeburn   139:             &print_footer($r);
1.20      raeburn   140:             return OK;
                    141:         } else {
1.51      raeburn   142:             $start_page = &Apache::loncommon::start_page($title,$js); 
1.22      raeburn   143:             &print_header($r,$start_page,$courseid);
                    144:             $r->print($output);
                    145:             &print_footer($r);    
1.20      raeburn   146:             return OK;
                    147:         }
1.4       raeburn   148:     }
1.51      raeburn   149:     $start_page = &Apache::loncommon::start_page($title,$js);
1.3       raeburn   150: 
1.35      raeburn   151:     my %domconfig = 
                    152:         &Apache::lonnet::get_dom('configuration',['usercreation'],$domain);
1.58    ! raeburn   153:     my ($cancreate,$statustocreate,$emailusername) = 
        !           154:         &get_creation_controls($domain,$domconfig{'usercreation'});
1.35      raeburn   155:     if (@{$cancreate} == 0) {
1.22      raeburn   156:         &print_header($r,$start_page,$courseid);
1.14      raeburn   157:         my $output = '<h3>'.&mt('Account creation unavailable').'</h3>'.
                    158:                      '<span class="LC_warning">'.
1.58    ! raeburn   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 />';
1.3       raeburn   161:         $r->print($output);
1.22      raeburn   162:         &print_footer($r);
1.3       raeburn   163:         return OK;
                    164:     }
                    165: 
1.5       raeburn   166:     if ($sso_username ne '') {
1.22      raeburn   167:         &print_header($r,$start_page,$courseid);
1.18      raeburn   168:         my ($msg,$sso_logout);
                    169:         $sso_logout = &sso_logout_frag($r,$domain);
1.35      raeburn   170:         if (grep(/^sso$/,@{$cancreate})) {
1.14      raeburn   171:             $msg = '<h3>'.&mt('Account creation').'</h3>'.
1.17      raeburn   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: 
1.18      raeburn   174:             $msg .= &username_check($sso_username,$domain,$domdesc,$courseid, 
1.35      raeburn   175:                                     $lonhost,$contact_email,$contact_name,
                    176:                                     $sso_logout,$statustocreate);
1.5       raeburn   177:         } else {
1.17      raeburn   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 />'.
1.18      raeburn   180:                    $sso_logout;
1.5       raeburn   181:         }
1.17      raeburn   182:         $r->print($msg);
1.22      raeburn   183:         &print_footer($r);
1.5       raeburn   184:         return OK;
                    185:     }
                    186: 
1.58    ! raeburn   187:     my ($output,$nostart,$noend,$redirect);
1.3       raeburn   188:     my $token = $env{'form.token'};
                    189:     if ($token) {
1.58    ! raeburn   190:         ($output,$nostart,$noend,$redirect) = 
1.3       raeburn   191:             &process_mailtoken($r,$token,$contact_name,$contact_email,$domain,
1.58    ! raeburn   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) {
1.3       raeburn   198:             if ($noend) {
                    199:                 return OK;
                    200:             } else {
                    201:                 $r->print($output);
1.22      raeburn   202:                 &print_footer($r);
1.3       raeburn   203:                 return OK;
                    204:             }
                    205:         } else {
1.22      raeburn   206:             &print_header($r,$start_page,$courseid);
1.3       raeburn   207:             $r->print($output);
1.22      raeburn   208:             &print_footer($r);
1.3       raeburn   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,
1.51      raeburn   216:                                  $courseid);
1.58    ! raeburn   217:         if ($result eq 'redirect') {
        !           218:             $r->internal_redirect('/adm/switchserver');
        !           219:             return OK; 
        !           220:         } elsif ($result eq 'ok') {
1.3       raeburn   221:             if ($nostart) {
                    222:                 return OK;
                    223:             }
                    224:         }
1.22      raeburn   225:         &print_header($r,$start_page,$courseid);
1.3       raeburn   226:         $r->print($output);
1.22      raeburn   227:         &print_footer($r);
1.3       raeburn   228:         return OK;
1.19      raeburn   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,
1.35      raeburn   233:                                  $lonhost,$statustocreate);
1.19      raeburn   234:         if ($result eq 'existingaccount') {
                    235:             $r->print($output);
1.22      raeburn   236:             &print_footer($r);
1.19      raeburn   237:             return OK;
                    238:         } else {
1.22      raeburn   239:             &print_header($r,$start_page,$courseid);
1.19      raeburn   240:         }
                    241:     } elsif ($env{'form.create_with_email'}) {
1.22      raeburn   242:         &print_header($r,$start_page,$courseid);
1.58    ! raeburn   243:         $output = &process_email_request($env{'form.uname'},$domain,$domdesc,
1.35      raeburn   244:                                          $contact_name,$contact_email,$cancreate,
1.3       raeburn   245:                                          $lonhost,$domconfig{'usercreation'},
1.58    ! raeburn   246:                                          $emailusername,$courseid);
1.3       raeburn   247:     } elsif (!$token) {
1.22      raeburn   248:         &print_header($r,$start_page,$courseid);
1.1       raeburn   249:         my $now=time;
1.58    ! raeburn   250:         my $gotlondes;
1.35      raeburn   251:         if (grep(/^login$/,@{$cancreate})) {
1.58    ! raeburn   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:             }
1.1       raeburn   260:         }
1.58    ! raeburn   261:         if (grep(/^email(|approval)$/,@{$cancreate})) {
1.12      raeburn   262:             $r->print(&javascript_validmail());
                    263:         }
1.58    ! raeburn   264:         $output = &print_username_form($r,$domain,$domdesc,$cancreate,$now,$lonhost,
        !           265:                                        $include,$courseid,$gotlondes,$emailusername);
1.1       raeburn   266:     }
                    267:     $r->print($output);
1.22      raeburn   268:     &print_footer($r);
1.1       raeburn   269:     return OK;
                    270: }
                    271: 
1.3       raeburn   272: sub print_header {
1.22      raeburn   273:     my ($r,$start_page,$courseid) = @_;
1.3       raeburn   274:     $r->print($start_page);
                    275:     &Apache::lonhtmlcommon::clear_breadcrumbs();
1.22      raeburn   276:     if ($courseid ne '') {
                    277:         my %coursehash = &Apache::lonnet::coursedescription($courseid);
                    278:         &selfenroll_crumbs($r,$courseid,$coursehash{'description'});
                    279:     }
1.3       raeburn   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: 
1.22      raeburn   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',
1.58    ! raeburn   293:                       'code','crypt','cfirstname','clastname',
1.23      raeburn   294:                       'cmiddlename','cgeneration','cpermanentemail','cid']).
1.22      raeburn   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','')",
1.37      bisitz    304:            text=>"Course/Community Catalog"});
1.22      raeburn   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 '') {
1.45      raeburn   312:         $last_crumb = &mt('Self-enroll in [_1]',"<span class='LC_cusr_emph'>$desc</span>");
1.22      raeburn   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: 
1.1       raeburn   323: sub javascript_setforms {
1.58    ! raeburn   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:     }
1.1       raeburn   331:     my $js = <<ENDSCRIPT;
1.58    ! raeburn   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;
1.1       raeburn   348: 
1.58    ! raeburn   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:         }
1.1       raeburn   362:         return false;
                    363:     }
1.58    ! raeburn   364: // ]]>
        !           365: </script>
1.1       raeburn   366: ENDSCRIPT
                    367:     return $js;
                    368: }
                    369: 
                    370: sub javascript_checkpass {
1.58    ! raeburn   371:     my ($now,$context) = @_;
1.7       bisitz    372:     my $nopass = &mt('You must enter a password.');
1.1       raeburn   373:     my $mismatchpass = &mt('The passwords you entered did not match.').'\\n'.
                    374:                        &mt('Please try again.'); 
                    375:     my $js = <<"ENDSCRIPT";
1.58    ! raeburn   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:             }
1.32      raeburn   398:         }
1.58    ! raeburn   399:         return false; 
1.1       raeburn   400:     }
1.58    ! raeburn   401: // ]]>
1.1       raeburn   402: </script>
                    403: ENDSCRIPT
                    404:     return $js;
                    405: }
                    406: 
1.12      raeburn   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".
1.58    ! raeburn   413:                   '// <![CDATA['."\n".
1.12      raeburn   414:                   &Apache::lonhtmlcommon::javascript_valid_email()."\n";
                    415:     $output .= <<"ENDSCRIPT";
1.58    ! raeburn   416: function validate_email(client) {
        !           417:     field = client.uname;
1.12      raeburn   418:     if (validmail(field) == false) {
                    419:         alert("$lt{'email'}: "+field.value+" $lt{'notv'}.");
                    420:         return false;
                    421:     }
                    422:     return true;
                    423: }
                    424: ENDSCRIPT
1.58    ! raeburn   425:     $output .= "\n".'// ]]>'."\n".'</script>'."\n";
1.12      raeburn   426:     return $output;
                    427: }
                    428: 
1.1       raeburn   429: sub print_username_form {
1.58    ! raeburn   430:     my ($r,$domain,$domdesc,$cancreate,$now,$lonhost,$include,$courseid,$gotlondes,$emailusername) = @_;
1.1       raeburn   431:     my %lt = &Apache::lonlocal::texthash(
                    432:                                          unam => 'username',
                    433:                                          udom => 'domain',
1.26      schafran  434:                                          uemail => 'E-mail address in LON-CAPA',
1.1       raeburn   435:                                          proc => 'Proceed');
                    436:     my $output;
1.5       raeburn   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')) {
1.16      raeburn   441:                 $output = '<div class="LC_left_float"><h3>'.&mt('Create account with a username provided by this institution').'</h3>';
1.20      raeburn   442:                 my $submit_text = &mt('Create LON-CAPA account');
1.58    ! raeburn   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 />';
1.20      raeburn   447:                 $output .= &login_box($now,$lonhost,$courseid,$submit_text,
1.22      raeburn   448:                                       $domain,'createaccount').'</div>';
1.5       raeburn   449:             }
                    450:         }
1.58    ! raeburn   451:         if (grep(/^email(|approval)$/,@{$cancreate})) {
1.5       raeburn   452:             $output .= '<div class="LC_left_float"><h3>'.&mt('Create account with an e-mail address as your username').'</h3>';
1.52      raeburn   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:                 }
1.58    ! raeburn   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()">');
1.52      raeburn   464:             } else {
1.28      raeburn   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:                 }
1.58    ! raeburn   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 />';
1.52      raeburn   476:                 }
1.58    ! raeburn   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 />';
1.28      raeburn   482:                 }
1.5       raeburn   483:             }
1.28      raeburn   484:             $output .= '</div>';
1.3       raeburn   485:         }
1.1       raeburn   486:     }
                    487:     if ($output eq '') {
1.16      raeburn   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);
1.1       raeburn   489:     } else {
                    490:         $output .= '<div class="LC_clear_float_footer"></div>';
                    491:     }
                    492:     return $output;
                    493: }
                    494: 
1.20      raeburn   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:                                             );
1.58    ! raeburn   502:     my ($lkey,$ukey) = &Apache::loncommon::des_keys();
1.20      raeburn   503:     my ($lextkey,$uextkey) = &getkeys($lkey,$ukey);
1.41      raeburn   504:     my $logtoken=Apache::lonnet::reply('tmpput:'.$ukey.$lkey.'&createaccount:createaccount',
1.20      raeburn   505:                                        $lonhost);
                    506:     $output = &serverform($logtoken,$lonhost,undef,$courseid,$context);
1.32      raeburn   507:     my $unameform = '<input type="text" name="uname" size="20" value="" />';
                    508:     my $upassform = '<input type="password" name="upass'.$now.'" size="20" />';
1.58    ! raeburn   509:     $output .= '<form name="client" method="post" action="" onsubmit="return(send('."'server','client'".'));">'."\n".
1.32      raeburn   510:                &Apache::lonhtmlcommon::start_pick_box()."\n".
                    511:                &Apache::lonhtmlcommon::row_title($titles{$context},
1.31      bisitz    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;
1.20      raeburn   518:     if ($context eq 'selfenroll') {
1.32      raeburn   519:         my $udomform = '<input type="text" name="udom" size="10" value="'.
1.20      raeburn   520:                         $domain.'" />';
1.31      bisitz    521:         $output .= &Apache::lonhtmlcommon::row_closure(1)."\n".
                    522:                    &Apache::lonhtmlcommon::row_title(&mt('Domain'),
1.20      raeburn   523:                                                      'LC_pick_box_title')."\n".
1.31      bisitz    524:                    $udomform."\n";
1.32      raeburn   525:     } else {
                    526:         $output .= '<input type="hidden" name="udom" value="'.$domain.'" />';
1.20      raeburn   527:     }
1.32      raeburn   528:     $output .= &Apache::lonhtmlcommon::row_closure(1).
1.31      bisitz    529:                &Apache::lonhtmlcommon::row_title().
1.32      raeburn   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";
1.34      bisitz    540:     $output .= '<input type="hidden" name="lextkey" value="'.$lextkey.'" />'."\n".
                    541:                '<input type="hidden" name="uextkey" value="'.$uextkey.'" />'."\n".
1.22      raeburn   542:                '</form>';
1.20      raeburn   543:     return $output;
                    544: }
                    545: 
1.1       raeburn   546: sub process_email_request {
                    547:     my ($useremail,$domain,$domdesc,$contact_name,$contact_email,$cancreate,
1.58    ! raeburn   548:         $server,$settings,$emailusername,$courseid) = @_;
1.1       raeburn   549:     my $output;
1.5       raeburn   550:     if (ref($cancreate) eq 'ARRAY') {
1.58    ! raeburn   551:         if (!grep(/^email(|approval)$/,@{$cancreate})) {
1.5       raeburn   552:             $output = &invalid_state('noemails',$domdesc,
                    553:                                      $contact_name,$contact_email);
                    554:             return $output;
                    555:         } elsif ($useremail !~ /^[^\@]+\@[^\@]+\.[^\@\.]+$/) {
                    556:             $output = &invalid_state('baduseremail',$domdesc,
1.1       raeburn   557:                                      $contact_name,$contact_email);
                    558:             return $output;
                    559:         } else {
1.58    ! raeburn   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:             }
1.5       raeburn   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);
1.1       raeburn   571:                 return $output;
1.5       raeburn   572:             } else {
1.52      raeburn   573:                 my ($captcha_chk,$captcha_error) = &Apache::loncommon::captcha_response('usercreation',$server);
1.5       raeburn   574:                 if ($captcha_chk != 1) {
                    575:                     $output = &invalid_state('captcha',$domdesc,$contact_name,
1.52      raeburn   576:                                              $contact_email,$captcha_error);
1.5       raeburn   577:                     return $output;
                    578:                 }
1.58    ! raeburn   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;
1.1       raeburn   588:                         }
                    589:                     }
1.58    ! raeburn   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;
1.1       raeburn   598:                 }
                    599:             }
                    600:         }
1.5       raeburn   601:         $output = &send_token($domain,$useremail,$server,$domdesc,$contact_name,
1.58    ! raeburn   602:                               $contact_email,$courseid,$emailusername);
1.1       raeburn   603:     }
                    604:     return $output;
                    605: }
                    606: 
1.23      raeburn   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: 
1.1       raeburn   621: sub send_token {
1.58    ! raeburn   622:     my ($domain,$email,$server,$domdesc,$contact_name,$contact_email,$courseid,$emailusername) = @_;
1.14      raeburn   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 />';
1.1       raeburn   626:     my $now = time;
1.58    ! raeburn   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:             }
1.1       raeburn   673:         } else {
1.14      raeburn   674:             $msg .= '<span class="LC_error">'.
1.58    ! raeburn   675:                     &mt('An error occurred creating a token required for the account creation process.').'</span><br />'.
1.14      raeburn   676:                     ' '.&mt('Please contact the [_1] ([_2]) for assistance.',$contact_name,$contact_email);
1.1       raeburn   677:         }
                    678:     } else {
1.58    ! raeburn   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: 
1.1       raeburn   682:     }
                    683:     return $msg;
                    684: }
                    685: 
                    686: sub process_mailtoken {
1.3       raeburn   687:     my ($r,$token,$contact_name,$contact_email,$domain,$domdesc,$lonhost,
1.58    ! raeburn   688:         $include,$start_page,$cancreate,$settings) = @_;
        !           689:     my ($msg,$nostart,$noend,$redirect);
1.1       raeburn   690:     my %data = &Apache::lonnet::tmpget($token);
                    691:     my $now = time;
                    692:     if (keys(%data) == 0) {
1.9       raeburn   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.')
1.58    ! raeburn   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>');
1.1       raeburn   697:         return $msg;
                    698:     }
                    699:     if (($data{'time'} =~ /^\d+$/) &&
                    700:         ($data{'domain'} ne '') &&
                    701:         ($data{'username'}  =~ /^[^\@]+\@[^\@]+\.[^\@\.]+$/)) {
                    702:         if ($now - $data{'time'} < 7200) {
1.58    ! raeburn   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;
1.1       raeburn   724:                     } else {
1.58    ! raeburn   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:                         }
1.1       raeburn   730:                     }
1.58    ! raeburn   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);
1.1       raeburn   735:                 } else {
1.58    ! raeburn   736:                     $msg = &invalid_state('noemails',$domdesc,$contact_name,$contact_email);
1.1       raeburn   737:                 }
                    738:             } else {
1.58    ! raeburn   739:                 $msg = &invalid_state('noemails',$domdesc,$contact_name,$contact_email);
1.1       raeburn   740:             }
                    741:         } else {
1.7       bisitz    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>');
1.4       raeburn   744:             }
1.1       raeburn   745:     } else {
1.7       bisitz    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>');
1.1       raeburn   748:     }
1.58    ! raeburn   749:     return ($msg,$nostart,$noend,$redirect);
1.3       raeburn   750: }
                    751: 
                    752: sub start_session {
1.51      raeburn   753:     my ($r,$username,$domain,$uhome,$courseid,$token) = @_;
1.48      droeschl  754: 
1.3       raeburn   755:     if ($r->dir_config('lonBalancer') eq 'yes') {
1.51      raeburn   756:         Apache::lonauth::success($r, $username, $domain, $uhome,
1.48      droeschl  757:             'noredirect', undef, {});
                    758: 
                    759:         Apache::lonnet::tmpdel($token) if $token;
                    760: 
1.58    ! raeburn   761:         return 'redirect';
1.3       raeburn   762:     } else {
1.48      droeschl  763:         $courseid = Apache::lonnet::is_course($courseid); 
                    764: 
1.51      raeburn   765:         Apache::lonauth::success($r, $username, $domain, $uhome,
1.48      droeschl  766:             ($courseid ? "/adm/selfenroll?courseid=$courseid" : '/adm/roles'),
                    767:             undef, {}); 
1.3       raeburn   768:     }
1.48      droeschl  769: 
                    770:     return;
1.1       raeburn   771: }
                    772: 
1.50      www       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: #
1.1       raeburn   778: sub print_dataentry_form {
1.58    ! raeburn   779:     my ($r,$domain,$lonhost,$include,$now,$captchaform,$courseid,$gotlondes,$emailusername) = @_;
1.1       raeburn   780:     my ($error,$output);
1.58    ! raeburn   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();
1.1       raeburn   794:         my ($lextkey,$uextkey) = &getkeys($lkey,$ukey);
1.41      raeburn   795:         my $logtoken=Apache::lonnet::reply('tmpput:'.$ukey.$lkey.'&createaccount:createaccount',
1.1       raeburn   796:                                            $lonhost);
1.58    ! raeburn   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:             }
1.1       raeburn   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="" />
1.32      raeburn   812:    <input type="hidden" name="udom" value="" />
1.58    ! raeburn   813:    <input type="hidden" name="crypt" value="" />
        !           814:    <input type="hidden" name="code" value="" />
1.1       raeburn   815:    <input type="hidden" name="phase" value="createaccount" />
1.58    ! raeburn   816:    <input type="hidden" name="create_with_email" value="1" />
1.32      raeburn   817:   </form>
1.1       raeburn   818: ENDSERVERFORM
1.58    ! raeburn   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);
1.32      raeburn   829:         if ($rowcount) {
1.58    ! raeburn   830:             $output .= '<div class="LC_left_float">'.$beginclientform.$datatable.$endclientform;
        !           831:         } else {
        !           832:             $output .= $beginclientform.$endclientform;
1.32      raeburn   833:         }
                    834:         if ($rowcount) {
                    835:             $output .= '</div>'."\n".
                    836:                        '<div class="LC_clear_float_footer"></div>'."\n";
                    837:         }
1.1       raeburn   838:     } else {
1.7       bisitz    839:         $output = &mt('Could not load javascript file [_1]','<tt>londes.js</tt>');
1.1       raeburn   840:     }
1.3       raeburn   841:     return $output;
1.1       raeburn   842: }
                    843: 
1.50      www       844: #
                    845: # Retrieve rules for generating accounts from domain configuration
                    846: # Can the user make a new account or just self-enroll?
                    847: 
1.35      raeburn   848: sub get_creation_controls {
                    849:     my ($domain,$usercreation) = @_;
1.58    ! raeburn   850:     my (@cancreate,@statustocreate,$emailusername);
1.35      raeburn   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'}};
1.47      raeburn   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:                 }
1.35      raeburn   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:             }
1.58    ! raeburn   880:             if (ref($usercreation->{'cancreate'}{'emailusername'}) eq 'HASH') {
        !           881:                 $emailusername = $usercreation->{'cancreate'}{'emailusername'};
        !           882:             }
1.35      raeburn   883:         }
                    884:     }
1.58    ! raeburn   885:     return (\@cancreate,\@statustocreate,$emailusername);
1.35      raeburn   886: }
                    887: 
1.1       raeburn   888: sub create_account {
1.58    ! raeburn   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();">'.
1.1       raeburn   893:                     &mt('Return to previous page').'</a>'.
                    894:                     &Apache::loncommon::end_page();
1.58    ! raeburn   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:                 }
1.1       raeburn   931:             }
1.58    ! raeburn   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);
1.1       raeburn   953:         }
                    954:     } else {
1.58    ! raeburn   955:         $output = &mt('Unable to retrieve information for your account request.');
1.1       raeburn   956:         return ('fail',$error.$output.$end.$rtnlink);
                    957:     }
                    958: }
                    959: 
                    960: sub username_validation {
1.19      raeburn   961:     my ($r,$username,$domain,$domdesc,$contact_name,$contact_email,$courseid,
1.35      raeburn   962:         $lonhost,$statustocreate) = @_;
1.58    ! raeburn   963: # $r: request object
1.49      www       964: # $username,$domain: for the user who needs to be validated
                    965: # $domdesc: full name of the domain (for error messages)
1.58    ! raeburn   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
1.49      www       970: # $statustocreate: -> inststatus in username_check ('faculty', 'staff', 'student', ...)
                    971:  
1.58    ! raeburn   972: #
        !           973: # Sanitize incoming username and domain
        !           974: #
1.1       raeburn   975:     $username= &LONCAPA::clean_username($username);
                    976:     $domain = &LONCAPA::clean_domain($domain);
1.58    ! raeburn   977: 
        !           978: #
        !           979: # Check if LON-CAPA account already exists for $username:$domain
        !           980: #
1.1       raeburn   981:     my $uhome = &Apache::lonnet::homeserver($username,$domain);
                    982: 
1.58    ! raeburn   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');
1.19      raeburn  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') { 
1.58    ! raeburn  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.');
1.19      raeburn  1021:             return ('existingaccount',$output);
                   1022:         } else {
1.22      raeburn  1023:             $output = &login_failure_msg($courseid);
1.19      raeburn  1024:         }
                   1025:     } else {
1.1       raeburn  1026:         my $primlibserv = &Apache::lonnet::domain($domain,'primary');
                   1027:         my $authok;
                   1028:         my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
1.58    ! raeburn  1029:         if ((($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) || 
        !          1030:              ($domdefaults{'auth_def'} eq 'localauth')) {
1.1       raeburn  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') {
1.18      raeburn  1038:             $output = &username_check($username,$domain,$domdesc,$courseid,$lonhost,
1.35      raeburn  1039:                                       $contact_email,$contact_name,undef,
                   1040:                                       $statustocreate);
1.4       raeburn  1041:         } else {
1.22      raeburn  1042:             $output = &login_failure_msg($courseid);
1.4       raeburn  1043:         }
                   1044:     }
1.19      raeburn  1045:     return ('ok',$output);
1.4       raeburn  1046: }
                   1047: 
1.22      raeburn  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: 
1.4       raeburn  1064: sub username_check {
1.35      raeburn  1065:     my ($username,$domain,$domdesc,$courseid,$lonhost,$contact_email,
                   1066:         $contact_name,$sso_logout,$statustocreate) = @_;
1.23      raeburn  1067:     my (%rulematch,%inst_results,$checkfail,$rowcount,$editable,$output,$msg,
1.18      raeburn  1068:         %alerts,%curr_rules,%got_rules);
1.23      raeburn  1069:     &call_rulecheck($username,$domain,\%alerts,\%rulematch,
1.40      raeburn  1070:                     \%inst_results,\%curr_rules,\%got_rules,'username');
1.4       raeburn  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') {
1.18      raeburn  1075:                     $output =
1.17      raeburn  1076:                         &Apache::loncommon::instrule_disallow_msg('username',$domdesc,1,
                   1077:                                                                   'selfcreate').
1.4       raeburn  1078:                         &Apache::loncommon::user_rule_formats($domain,$domdesc,
                   1079:                                 $curr_rules{$domain}{'username'},'username');
1.1       raeburn  1080:                 }
1.18      raeburn  1081:                 $checkfail = 'username';
1.1       raeburn  1082:             }
1.4       raeburn  1083:         }
                   1084:     }
1.18      raeburn  1085:     if (!$checkfail) {
1.35      raeburn  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) {
1.18      raeburn  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);
1.41      raeburn  1116:         my $authtoken = &Apache::lonnet::tmpput(\%info,$lonhost,'createaccount');
1.18      raeburn  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) { 
1.47      raeburn  1127:         $msg = '<br /><h4>'.&mt('Account creation unavailable').'</h4>';
1.18      raeburn  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;
1.35      raeburn  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;
1.18      raeburn  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");
1.8       raeburn  1144:     } else {
1.18      raeburn  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) {
1.22      raeburn  1152:                 if ($courseid ne '') { 
1.47      raeburn  1153:                     $msg = '<br /><h4>'.&mt('User information').'</h4>';
1.22      raeburn  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 />';
1.18      raeburn  1156:             } else {
1.22      raeburn  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 />';
1.18      raeburn  1161:             }
                   1162:         } else {
1.22      raeburn  1163:             if ($courseid ne '') {
                   1164:                 $msg = '<h4>'.&mt('Confirmation').'</h4>';
                   1165:             }
                   1166:             $msg .= &mt('Confirm that you wish to create an account.');
1.18      raeburn  1167:         }
                   1168:         $msg .= $output;
                   1169:     }
                   1170:     return $msg;
1.1       raeburn  1171: }
                   1172: 
                   1173: sub username_activation {
1.51      raeburn  1174:     my ($r,$username,$domain,$domdesc,$courseid) = @_;
1.1       raeburn  1175:     my $output;
1.7       bisitz   1176:     my $error     = '<span class="LC_error">'.&mt('Error:').' ';
1.1       raeburn  1177:     my $end       = '</span><br /><br />';
1.54      bisitz   1178:     my $rtnlink   = '<a href="javascript:history.back();">'.
1.1       raeburn  1179:                     &mt('Return to previous page').'</a>'.
                   1180:                     &Apache::loncommon::end_page();
                   1181:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
1.8       raeburn  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 '') {
1.56      raeburn  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>');
1.8       raeburn  1206:         return($earlyout,$output);
                   1207:     }
1.3       raeburn  1208:     if ((($domdefaults{'auth_def'} =~/^krb(4|5)$/) && 
                   1209:          ($domdefaults{'auth_arg_def'} ne '')) || 
                   1210:         ($domdefaults{'auth_def'} eq 'localauth')) {
1.22      raeburn  1211:         if ($env{'form.courseid'} ne '') {
1.58    ! raeburn  1212:             my $id = $env{'form.cid'}; 
        !          1213:             my ($result,$userchkmsg) = &check_id($username,$domain,$id,$domdesc,'institutional');
1.1       raeburn  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
1.23      raeburn  1221:         my (%rulematch,%inst_results,%curr_rules,%got_rules,%alerts,%info);
                   1222:         &call_rulecheck($username,$domain,\%alerts,\%rulematch,
1.40      raeburn  1223:                         \%inst_results,\%curr_rules,\%got_rules);
1.23      raeburn  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:         }
1.1       raeburn  1240:         my $result =
1.23      raeburn  1241:             &Apache::lonnet::modifyuser($domain,$username,$env{'form.cid'},
1.1       raeburn  1242:                           $domdefaults{'auth_def'},
1.23      raeburn  1243:                           $domdefaults{'auth_arg_def'},$info{'firstname'},
                   1244:                           $info{'middlename'},$info{'lastname'},
                   1245:                           $info{'generation'},undef,undef,
                   1246:                           $info{'permanentemail'},$info{'inststatus'});
1.3       raeburn  1247:         if ($result eq 'ok') {
1.8       raeburn  1248:             my $delete = &Apache::lonnet::tmpdel($env{'form.authtoken'});
1.3       raeburn  1249:             $output = &mt('A LON-CAPA account has been created for username: [_1] in domain: [_2].',$username,$domain);
1.51      raeburn  1250:             my $uhome=&Apache::lonnet::homeserver($username,$domain,'true');
1.3       raeburn  1251:             my $nostart = 1;
1.58    ! raeburn  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);
1.3       raeburn  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:         }
1.1       raeburn  1262:     } else {
1.7       bisitz   1263:         $output = &mt('User account creation is not available for the current default authentication type.')."\n";
1.1       raeburn  1264:         return('fail',$output);
                   1265:     }
                   1266: }
                   1267: 
                   1268: sub check_id {
1.58    ! raeburn  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.  
1.50      www      1272:     # $domdesc is just used for user error messages
1.1       raeburn  1273:     my (%alerts,%rulematch,%inst_results,%curr_rules,%checkhash);
                   1274:     my %checks = ('id' => 1);
                   1275:     %{$checkhash{$username.':'.$domain}} = (
                   1276:                                             'newuser' => 1,
1.58    ! raeburn  1277:                                             'id' => $id,
1.1       raeburn  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') {
1.58    ! raeburn  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:                     }
1.1       raeburn  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) = @_;
1.14      raeburn  1305:     my $msg = '<h3>'.&mt('Account creation unavailable').'</h3><span class="LC_error">';
1.1       raeburn  1306:     if ($error eq 'baduseremail') {
1.42      raeburn  1307:         $msg .= &mt('The e-mail address you provided does not appear to be a valid address.');
1.58    ! raeburn  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.');
1.1       raeburn  1310:     } elsif ($error eq 'existinguser') {
1.42      raeburn  1311:         $msg .= &mt('The e-mail address you provided is already in use as a username in LON-CAPA at this institution.');
1.1       raeburn  1312:     } elsif ($error eq 'userrules') {
1.42      raeburn  1313:         $msg .= &mt('Username rules at this institution do not allow the e-mail address you provided to be used as a username.');
1.1       raeburn  1314:     } elsif ($error eq 'userformat') {
1.42      raeburn  1315:         $msg .= &mt('The e-mail address you provided may not be used as a username at this LON-CAPA institution.');
1.1       raeburn  1316:     } elsif ($error eq 'captcha') {
1.43      raeburn  1317:         $msg .= &mt('Validation of the code you entered failed.');
1.1       raeburn  1318:     } elsif ($error eq 'noemails') {
1.42      raeburn  1319:         $msg .= &mt('Creation of a new user account using an e-mail address as username is not permitted at this LON-CAPA institution.');
1.1       raeburn  1320:     }
1.14      raeburn  1321:     $msg .= '</span>';
1.1       raeburn  1322:     if ($msgtext) {
                   1323:         $msg .= '<br />'.$msgtext;
                   1324:     }
1.44      raeburn  1325:     $msg .= &linkto_email_help($contact_email,$domdesc,$error);
1.8       raeburn  1326:     return $msg;
                   1327: }
                   1328: 
                   1329: sub linkto_email_help {
1.44      raeburn  1330:     my ($contact_email,$domdesc,$error) = @_;
1.8       raeburn  1331:     my $msg;
1.44      raeburn  1332:     my $href = '/adm/helpdesk';
1.1       raeburn  1333:     if ($contact_email ne '') {
                   1334:         my $escuri = &HTML::Entities::encode('/adm/createaccount','&<>"');
1.44      raeburn  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 />';
1.1       raeburn  1341:     } else {
1.55      raeburn  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 />';
1.1       raeburn  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 {
1.20      raeburn  1358:     my ($logtoken,$lonhost,$mailtoken,$courseid,$context) = @_;
1.22      raeburn  1359:     my $phase = 'username_validation';
                   1360:     my $catalog_elements;
1.20      raeburn  1361:     if ($context eq 'selfenroll') {
                   1362:         $phase = 'selfenroll_login';
                   1363:     }
1.22      raeburn  1364:     if ($courseid ne '') {
                   1365:         $catalog_elements = &Apache::lonhtmlcommon::echo_form_input(['courseid','phase']);
                   1366:     } 
                   1367:     my $output = <<ENDSERVERFORM;
1.20      raeburn  1368:   <form name="server" method="post" action="/adm/createaccount">
1.1       raeburn  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="" />
1.32      raeburn  1374:    <input type="hidden" name="udom" value="" />
1.20      raeburn  1375:    <input type="hidden" name="phase" value="$phase" />
1.3       raeburn  1376:    <input type="hidden" name="courseid" value="$courseid" />
1.22      raeburn  1377:    $catalog_elements
1.1       raeburn  1378:   </form>
                   1379: ENDSERVERFORM
                   1380:     return $output;
                   1381: }
                   1382: 
1.58    ! raeburn  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:             }
1.1       raeburn  1434:         }
1.58    ! raeburn  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>';
1.1       raeburn  1443:     } else {
1.58    ! raeburn  1444:         $output = '<span class="LC_error">'.
        !          1445:                   &mt('An error occurred when attempting to save your request for a LON-CAPA account.');
        !          1446:                   '</span>';
1.1       raeburn  1447:     }
1.58    ! raeburn  1448:     return $output;
1.1       raeburn  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,
1.2       raeburn  1462:                                             'selfcreate',\@user_rules);
1.1       raeburn  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 =~ /^([^\@]+)\@/);
1.58    ! raeburn  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 />';
1.5       raeburn  1477:         if (ref($cancreate) eq 'ARRAY') {
                   1478:             if (grep(/^login$/,@{$cancreate})) {
1.7       bisitz   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 />'; 
1.5       raeburn  1480:             }
1.1       raeburn  1481:         }
                   1482:     }
                   1483:     return $format_msg;
                   1484: }
                   1485: 
1.17      raeburn  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: 
1.22      raeburn  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: 
1.1       raeburn  1564: 1;

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