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

1.1       raeburn     1: # The LearningOnline Network
                      2: # Allow visitors to create a user account with the username being either an 
                      3: # institutional log-in ID (institutional authentication required - localauth
                      4: #  or kerberos) or an e-mail address.
                      5: #
1.51    ! raeburn     6: # $Id: createaccount.pm,v 1.50 2012/05/17 18:05:42 www Exp $
1.1       raeburn     7: #
                      8: # Copyright Michigan State University Board of Trustees
                      9: #
                     10: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                     11: #
                     12: # LON-CAPA is free software; you can redistribute it and/or modify
                     13: # it under the terms of the GNU General Public License as published by
                     14: # the Free Software Foundation; either version 2 of the License, or
                     15: # (at your option) any later version.
                     16: #
                     17: # LON-CAPA is distributed in the hope that it will be useful,
                     18: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     19: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     20: # GNU General Public License for more details.
                     21: #
                     22: # You should have received a copy of the GNU General Public License
                     23: # along with LON-CAPA; if not, write to the Free Software
                     24: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     25: #
                     26: # /home/httpd/html/adm/gpl.txt
                     27: #
                     28: # http://www.lon-capa.org/
                     29: #
                     30: #
                     31: package Apache::createaccount;
                     32: 
                     33: use strict;
                     34: use Apache::Constants qw(:common);
                     35: use Apache::lonacc;
                     36: use Apache::lonnet;
                     37: use Apache::loncommon;
1.12      raeburn    38: use Apache::lonhtmlcommon;
1.1       raeburn    39: use Apache::lonlocal;
1.3       raeburn    40: use Apache::lonauth;
1.1       raeburn    41: use Apache::resetpw;
                     42: use Authen::Captcha;
                     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: 
1.48      droeschl   48: #TODO this module needs documentation
                     49: 
1.1       raeburn    50: sub handler {
                     51:     my $r = shift;
                     52:     &Apache::loncommon::content_type($r,'text/html');
                     53:     $r->send_http_header;
                     54:     if ($r->header_only) {
                     55:         return OK;
                     56:     }
1.22      raeburn    57: 
1.5       raeburn    58:     my $domain;
1.3       raeburn    59: 
1.5       raeburn    60:     my $sso_username = $r->subprocess_env->get('REDIRECT_SSOUserUnknown');
                     61:     my $sso_domain = $r->subprocess_env->get('REDIRECT_SSOUserDomain');
                     62: 
1.27      raeburn    63:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['token','courseid']);
                     64:     &Apache::lonacc::get_posted_cgi($r);
                     65:     &Apache::lonlocal::get_language_handle($r);
                     66: 
1.5       raeburn    67:     if ($sso_username ne '' && $sso_domain ne '') {
                     68:         $domain = $sso_domain; 
1.27      raeburn    69:     } else {
1.48      droeschl   70:         ($domain, undef) = Apache::lonnet::is_course($env{'form.courseid'}); 
                     71:         $domain ||= &Apache::lonnet::default_login_domain();
1.5       raeburn    72:     }
1.1       raeburn    73:     my $domdesc = &Apache::lonnet::domain($domain,'description');
                     74:     my $contact_name = &mt('LON-CAPA helpdesk');
1.15      raeburn    75:     my $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};
                     76:     my $contacts =
                     77:         &Apache::loncommon::build_recipient_list(undef,'helpdeskmail',
                     78:                                                  $domain,$origmail);
                     79:     my ($contact_email) = split(',',$contacts);
1.1       raeburn    80:     my $lonhost = $r->dir_config('lonHostID');
                     81:     my $include = $r->dir_config('lonIncludes');
1.4       raeburn    82:     my $start_page;
1.3       raeburn    83: 
                     84:     my $handle = &Apache::lonnet::check_for_valid_session($r);
1.30      raeburn    85:     if (($handle ne '') && ($handle !~ /^publicuser_\d+$/)) {
1.4       raeburn    86:         $start_page =
1.3       raeburn    87:             &Apache::loncommon::start_page('Already logged in');
                     88:         my $end_page =
                     89:             &Apache::loncommon::end_page();
                     90:         $r->print($start_page."\n".'<h2>'.&mt('You are already logged in').'</h2>'.
1.33      hauer      91:                   '<p>'.&mt('Please either [_1]continue the current session[_2] or [_3]log out[_4].','<a href="/adm/roles">','</a>','<a href="/adm/logout">','</a>').
1.6       bisitz     92:                   '</p><p><a href="/adm/loginproblems.html">'.&mt('Login problems?').'</a></p>'.$end_page);
1.20      raeburn    93:         return OK;
                     94:     }
                     95: 
1.22      raeburn    96:     my ($js,$courseid,$title);
1.48      droeschl   97:     $courseid = Apache::lonnet::is_course($env{'form.courseid'});
1.22      raeburn    98:     if ($courseid ne '') {
                     99:         $js = &catreturn_js();
                    100:         $title = 'Self-enroll in a LON-CAPA course';
                    101:     } else {
                    102:         $title = 'Create a user account in LON-CAPA';
                    103:     }
1.20      raeburn   104:     if ($env{'form.phase'} eq 'selfenroll_login') {
1.22      raeburn   105:         $title = 'Self-enroll in a LON-CAPA course';
1.4       raeburn   106:         if ($env{'form.udom'} ne '') {
                    107:             $domain = $env{'form.udom'};
                    108:         }
1.35      raeburn   109: 
                    110:         my %domconfig = 
                    111:             &Apache::lonnet::get_dom('configuration',['usercreation'],$domain);
                    112:         my ($cancreate,$statustocreate) = 
                    113:             &get_creation_controls($domain,$domconfig{'usercreation'});
                    114: 
1.20      raeburn   115:         my ($result,$output) =
                    116:             &username_validation($r,$env{'form.uname'},$domain,$domdesc,
                    117:                                  $contact_name,$contact_email,$courseid,
1.35      raeburn   118:                                  $lonhost,$statustocreate);
1.20      raeburn   119:         if ($result eq 'existingaccount') {
                    120:             $r->print($output);
1.22      raeburn   121:             &print_footer($r);
1.20      raeburn   122:             return OK;
                    123:         } else {
1.51    ! raeburn   124:             $start_page = &Apache::loncommon::start_page($title,$js); 
1.22      raeburn   125:             &print_header($r,$start_page,$courseid);
                    126:             $r->print($output);
                    127:             &print_footer($r);    
1.20      raeburn   128:             return OK;
                    129:         }
1.4       raeburn   130:     }
1.51    ! raeburn   131:     $start_page = &Apache::loncommon::start_page($title,$js);
1.3       raeburn   132: 
1.35      raeburn   133:     my %domconfig = 
                    134:         &Apache::lonnet::get_dom('configuration',['usercreation'],$domain);
                    135:     my ($cancreate,$statustocreate) = &get_creation_controls($domain,$domconfig{'usercreation'});
                    136:     if (@{$cancreate} == 0) {
1.22      raeburn   137:         &print_header($r,$start_page,$courseid);
1.14      raeburn   138:         my $output = '<h3>'.&mt('Account creation unavailable').'</h3>'.
                    139:                      '<span class="LC_warning">'.
1.16      raeburn   140:                      &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).'</span><br /><br />';
1.3       raeburn   141:         $r->print($output);
1.22      raeburn   142:         &print_footer($r);
1.3       raeburn   143:         return OK;
                    144:     }
                    145: 
1.5       raeburn   146:     if ($sso_username ne '') {
1.22      raeburn   147:         &print_header($r,$start_page,$courseid);
1.18      raeburn   148:         my ($msg,$sso_logout);
                    149:         $sso_logout = &sso_logout_frag($r,$domain);
1.35      raeburn   150:         if (grep(/^sso$/,@{$cancreate})) {
1.14      raeburn   151:             $msg = '<h3>'.&mt('Account creation').'</h3>'.
1.17      raeburn   152:                    &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 />';
                    153: 
1.18      raeburn   154:             $msg .= &username_check($sso_username,$domain,$domdesc,$courseid, 
1.35      raeburn   155:                                     $lonhost,$contact_email,$contact_name,
                    156:                                     $sso_logout,$statustocreate);
1.5       raeburn   157:         } else {
1.17      raeburn   158:             $msg = '<h3>'.&mt('Account creation unavailable').'</h3>'.
                    159:                    '<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   160:                    $sso_logout;
1.5       raeburn   161:         }
1.17      raeburn   162:         $r->print($msg);
1.22      raeburn   163:         &print_footer($r);
1.5       raeburn   164:         return OK;
                    165:     }
                    166: 
1.4       raeburn   167:     my ($output,$nostart,$noend);
1.3       raeburn   168:     my $token = $env{'form.token'};
                    169:     if ($token) {
                    170:         ($output,$nostart,$noend) = 
                    171:             &process_mailtoken($r,$token,$contact_name,$contact_email,$domain,
1.4       raeburn   172:                                $domdesc,$lonhost,$include,$start_page);
1.3       raeburn   173:         if ($nostart) {
                    174:             if ($noend) {
                    175:                 return OK;
                    176:             } else {
                    177:                 $r->print($output);
1.22      raeburn   178:                 &print_footer($r);
1.3       raeburn   179:                 return OK;
                    180:             }
                    181:         } else {
1.22      raeburn   182:             &print_header($r,$start_page,$courseid);
1.3       raeburn   183:             $r->print($output);
1.22      raeburn   184:             &print_footer($r);
1.3       raeburn   185:             return OK;
                    186:         }
                    187:     }
                    188: 
                    189:     if ($env{'form.phase'} eq 'username_activation') {
                    190:         (my $result,$output,$nostart) = 
                    191:             &username_activation($r,$env{'form.uname'},$domain,$domdesc,
1.51    ! raeburn   192:                                  $courseid);
1.3       raeburn   193:         if ($result eq 'ok') {
                    194:             if ($nostart) {
                    195:                 return OK;
                    196:             }
                    197:         }
1.22      raeburn   198:         &print_header($r,$start_page,$courseid);
1.3       raeburn   199:         $r->print($output);
1.22      raeburn   200:         &print_footer($r);
1.3       raeburn   201:         return OK;
1.19      raeburn   202:     } elsif ($env{'form.phase'} eq 'username_validation') { 
                    203:         (my $result,$output) = 
                    204:             &username_validation($r,$env{'form.uname'},$domain,$domdesc,
                    205:                                  $contact_name,$contact_email,$courseid,
1.35      raeburn   206:                                  $lonhost,$statustocreate);
1.19      raeburn   207:         if ($result eq 'existingaccount') {
                    208:             $r->print($output);
1.22      raeburn   209:             &print_footer($r);
1.19      raeburn   210:             return OK;
                    211:         } else {
1.22      raeburn   212:             &print_header($r,$start_page,$courseid);
1.19      raeburn   213:         }
                    214:     } elsif ($env{'form.create_with_email'}) {
1.22      raeburn   215:         &print_header($r,$start_page,$courseid);
1.1       raeburn   216:         $output = &process_email_request($env{'form.useremail'},$domain,$domdesc,
1.35      raeburn   217:                                          $contact_name,$contact_email,$cancreate,
1.3       raeburn   218:                                          $lonhost,$domconfig{'usercreation'},
                    219:                                          $courseid);
                    220:     } elsif (!$token) {
1.22      raeburn   221:         &print_header($r,$start_page,$courseid);
1.1       raeburn   222:         my $now=time;
1.35      raeburn   223:         if (grep(/^login$/,@{$cancreate})) {
1.1       raeburn   224:             my $jsh=Apache::File->new($include."/londes.js");
                    225:             $r->print(<$jsh>);
                    226:             $r->print(&javascript_setforms($now));
                    227:         }
1.35      raeburn   228:         if (grep(/^email$/,@{$cancreate})) {
1.12      raeburn   229:             $r->print(&javascript_validmail());
                    230:         }
1.35      raeburn   231:         $output = &print_username_form($domain,$domdesc,$cancreate,$now,$lonhost,
1.22      raeburn   232:                                        $courseid);
1.1       raeburn   233:     }
                    234:     $r->print($output);
1.22      raeburn   235:     &print_footer($r);
1.1       raeburn   236:     return OK;
                    237: }
                    238: 
1.3       raeburn   239: sub print_header {
1.22      raeburn   240:     my ($r,$start_page,$courseid) = @_;
1.3       raeburn   241:     $r->print($start_page);
                    242:     &Apache::lonhtmlcommon::clear_breadcrumbs();
1.22      raeburn   243:     if ($courseid ne '') {
                    244:         my %coursehash = &Apache::lonnet::coursedescription($courseid);
                    245:         &selfenroll_crumbs($r,$courseid,$coursehash{'description'});
                    246:     }
1.3       raeburn   247:     &Apache::lonhtmlcommon::add_breadcrumb
                    248:     ({href=>"/adm/createuser",
                    249:       text=>"New username"});
                    250:     $r->print(&Apache::lonhtmlcommon::breadcrumbs('Create account'));
                    251:     return;
                    252: }
                    253: 
1.22      raeburn   254: sub print_footer {
                    255:     my ($r) = @_;
                    256:     if ($env{'form.courseid'} ne '') {
                    257:         $r->print('<form name="backupcrumbs" method="post" action="">'.
                    258:                   &Apache::lonhtmlcommon::echo_form_input(['backto','logtoken',
                    259:                       'token','serverid','uname','upass','phase','create_with_email',
                    260:                       'code','useremail','crypt','cfirstname','clastname',
1.23      raeburn   261:                       'cmiddlename','cgeneration','cpermanentemail','cid']).
1.22      raeburn   262:                   '</form>');
                    263:     }
                    264:     $r->print(&Apache::loncommon::end_page());
                    265: }
                    266: 
                    267: sub selfenroll_crumbs {
                    268:     my ($r,$courseid,$desc) = @_;
                    269:     &Apache::lonhtmlcommon::add_breadcrumb
                    270:          ({href=>"javascript:ToCatalog('backupcrumbs','')",
1.37      bisitz    271:            text=>"Course/Community Catalog"});
1.22      raeburn   272:     if ($env{'form.coursenum'} ne '') {
                    273:         &Apache::lonhtmlcommon::add_breadcrumb
                    274:           ({href=>"javascript:ToCatalog('backupcrumbs','details')",
                    275:             text=>"Course details"});
                    276:     }
                    277:     my $last_crumb;
                    278:     if ($desc ne '') {
1.45      raeburn   279:         $last_crumb = &mt('Self-enroll in [_1]',"<span class='LC_cusr_emph'>$desc</span>");
1.22      raeburn   280:     } else {
                    281:         $last_crumb = &mt('Self-enroll');
                    282:     }
                    283:     &Apache::lonhtmlcommon::add_breadcrumb
                    284:                    ({href=>"javascript:ToSelfenroll('backupcrumbs')",
                    285:                      text=>$last_crumb,
                    286:                      no_mt=>"1"});
                    287:     return;
                    288: }
                    289: 
1.1       raeburn   290: sub javascript_setforms {
                    291:     my ($now) =  @_;
                    292:     my $js = <<ENDSCRIPT;
1.32      raeburn   293:  <script type="text/javascript" language="JavaScript">
1.1       raeburn   294:     function send() {
                    295:         this.document.server.elements.uname.value = this.document.client.elements.uname.value;
1.32      raeburn   296:         this.document.server.elements.udom.value = this.document.client.elements.udom.value;
1.1       raeburn   297:         uextkey=this.document.client.elements.uextkey.value;
                    298:         lextkey=this.document.client.elements.lextkey.value;
                    299:         initkeys();
                    300: 
                    301:         this.document.server.elements.upass.value
                    302:             = crypted(this.document.client.elements.upass$now.value);
                    303: 
                    304:         this.document.client.elements.uname.value='';
                    305:         this.document.client.elements.upass$now.value='';
                    306: 
                    307:         this.document.server.submit();
                    308:         return false;
                    309:     }
                    310:  </script>
                    311: ENDSCRIPT
                    312:     return $js;
                    313: }
                    314: 
                    315: sub javascript_checkpass {
                    316:     my ($now) = @_;
1.7       bisitz    317:     my $nopass = &mt('You must enter a password.');
1.1       raeburn   318:     my $mismatchpass = &mt('The passwords you entered did not match.').'\\n'.
                    319:                        &mt('Please try again.'); 
                    320:     my $js = <<"ENDSCRIPT";
                    321: <script type="text/javascript" language="JavaScript">
                    322:     function checkpass() {
                    323:         var upass = this.document.client.elements.upass$now.value;
                    324:         var upasscheck = this.document.client.elements.upasscheck$now.value;
                    325:         if (upass == '') {
                    326:             alert("$nopass");
1.32      raeburn   327:             return false;
1.1       raeburn   328:         }
                    329:         if (upass == upasscheck) {
                    330:             this.document.client.elements.upasscheck$now.value='';
                    331:             send();
1.32      raeburn   332:             return false;
1.1       raeburn   333:         } else {
                    334:             alert("$mismatchpass");
1.32      raeburn   335:             return false;
                    336:         }
1.1       raeburn   337:     }
                    338: </script>
                    339: ENDSCRIPT
                    340:     return $js;
                    341: }
                    342: 
1.12      raeburn   343: sub javascript_validmail {
                    344:     my %lt = &Apache::lonlocal::texthash (
                    345:                email => 'The e-mail address you entered',
                    346:                notv  => 'is not a valid e-mail address',
                    347:     );
                    348:     my $output =  "\n".'<script type="text/javascript">'."\n".
                    349:                   &Apache::lonhtmlcommon::javascript_valid_email()."\n";
                    350:     $output .= <<"ENDSCRIPT";
                    351: function validate_email() {
                    352:     field = document.createaccount.useremail;
                    353:     if (validmail(field) == false) {
                    354:         alert("$lt{'email'}: "+field.value+" $lt{'notv'}.");
                    355:         return false;
                    356:     }
                    357:     return true;
                    358: }
                    359: ENDSCRIPT
                    360:     $output .= "\n".'</script>'."\n";
                    361:     return $output;
                    362: }
                    363: 
1.1       raeburn   364: sub print_username_form {
1.3       raeburn   365:     my ($domain,$domdesc,$cancreate,$now,$lonhost,$courseid) = @_;
1.1       raeburn   366:     my %lt = &Apache::lonlocal::texthash(
                    367:                                          unam => 'username',
                    368:                                          udom => 'domain',
1.26      schafran  369:                                          uemail => 'E-mail address in LON-CAPA',
1.1       raeburn   370:                                          proc => 'Proceed');
                    371:     my $output;
1.5       raeburn   372:     if (ref($cancreate) eq 'ARRAY') {
                    373:         if (grep(/^login$/,@{$cancreate})) {
                    374:             my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                    375:             if ((($domdefaults{'auth_def'} =~/^krb/) && ($domdefaults{'auth_arg_def'} ne '')) || ($domdefaults{'auth_def'} eq 'localauth')) {
1.16      raeburn   376:                 $output = '<div class="LC_left_float"><h3>'.&mt('Create account with a username provided by this institution').'</h3>';
1.20      raeburn   377:                 my $submit_text = &mt('Create LON-CAPA account');
1.16      raeburn   378:                 $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 />').'<br /><br />'.&mt('Type in your log-in ID and password to find out.').'<br /><br />';
1.20      raeburn   379:                 $output .= &login_box($now,$lonhost,$courseid,$submit_text,
1.22      raeburn   380:                                       $domain,'createaccount').'</div>';
1.5       raeburn   381:             }
                    382:         }
                    383:         if (grep(/^email$/,@{$cancreate})) {
                    384:             $output .= '<div class="LC_left_float"><h3>'.&mt('Create account with an e-mail address as your username').'</h3>';
1.28      raeburn   385:             my $captchaform = &create_captcha();
                    386:             if ($captchaform) {
                    387:                 my $submit_text = &mt('Request LON-CAPA account');
                    388:                 my $emailform = '<input type="text" name="useremail" size="25" value="" />';
                    389:                 if (grep(/^login$/,@{$cancreate})) {
                    390:                     $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 />';
                    391:                 } else {
                    392:                     $output .= '<br />';
                    393:                 }
1.46      raeburn   394:                 $output .=  '<form name="createaccount" method="post" onsubmit="return validate_email()" action="/adm/createaccount">'.
1.28      raeburn   395:                             &Apache::lonhtmlcommon::start_pick_box()."\n".
                    396:                             &Apache::lonhtmlcommon::row_title(&mt('E-mail address'),
                    397:                                                              'LC_pick_box_title')."\n".
                    398:                             $emailform."\n".
                    399:                             &Apache::lonhtmlcommon::row_closure(1).
                    400:                             &Apache::lonhtmlcommon::row_title(&mt('Validation'),
                    401:                                                              'LC_pick_box_title')."\n".
                    402:                             $captchaform."\n".'<br /><br />';
                    403:                 if ($courseid ne '') {
                    404:                     $output .= '<input type="hidden" name="courseid" value="'.$courseid.'"/>'."\n"; 
                    405:                 }
1.32      raeburn   406:                 $output .=  &Apache::lonhtmlcommon::row_closure(1).
                    407:                             &Apache::lonhtmlcommon::row_title().'<br />'.
                    408:                             '<input type="submit" name="create_with_email" value="'. 
1.28      raeburn   409:                             $submit_text.'" />'.
                    410:                             &Apache::lonhtmlcommon::row_closure(1).
                    411:                             &Apache::lonhtmlcommon::end_pick_box().'<br /><br />';
                    412:                 if ($courseid ne '') {
                    413:                     $output .= &Apache::lonhtmlcommon::echo_form_input(['courseid']);
                    414:                 }
                    415:                 $output .= '</form>';
1.5       raeburn   416:             } else {
1.28      raeburn   417:                 my $helpdesk = '/adm/helpdesk?origurl=%2fadm%2fcreateaccount';
                    418:                 if ($courseid ne '') {
                    419:                     $helpdesk .= '&courseid='.$courseid;
                    420:                 }
                    421:                 $output .= '<span class="LC_error">'.&mt('An error occurred generating the validation code[_1] required for an e-mail address to be used as username.','<br />').'</span><br /><br />'.&mt('[_1]Contact the helpdesk[_2] or [_3]reload[_2] the page and try again.','<a href="'.$helpdesk.'">','</a>','<a href="javascript:window.location.reload()">');
1.5       raeburn   422:             }
1.28      raeburn   423:             $output .= '</div>';
1.3       raeburn   424:         }
1.1       raeburn   425:     }
                    426:     if ($output eq '') {
1.16      raeburn   427:         $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   428:     } else {
                    429:         $output .= '<div class="LC_clear_float_footer"></div>';
                    430:     }
                    431:     return $output;
                    432: }
                    433: 
1.20      raeburn   434: sub login_box {
                    435:     my ($now,$lonhost,$courseid,$submit_text,$domain,$context) = @_;
                    436:     my $output;
                    437:     my %titles = &Apache::lonlocal::texthash(
                    438:                                               createaccount => 'Log-in ID',
                    439:                                               selfenroll    => 'Username',
                    440:                                             );
                    441:     my ($lkey,$ukey) = &Apache::lonpreferences::des_keys();
                    442:     my ($lextkey,$uextkey) = &getkeys($lkey,$ukey);
1.41      raeburn   443:     my $logtoken=Apache::lonnet::reply('tmpput:'.$ukey.$lkey.'&createaccount:createaccount',
1.20      raeburn   444:                                        $lonhost);
                    445:     $output = &serverform($logtoken,$lonhost,undef,$courseid,$context);
1.32      raeburn   446:     my $unameform = '<input type="text" name="uname" size="20" value="" />';
                    447:     my $upassform = '<input type="password" name="upass'.$now.'" size="20" />';
1.46      raeburn   448:     $output .= '<form name="client" method="post" action="" onsubmit="return(send());">'."\n".
1.32      raeburn   449:                &Apache::lonhtmlcommon::start_pick_box()."\n".
                    450:                &Apache::lonhtmlcommon::row_title($titles{$context},
1.31      bisitz    451:                                                  'LC_pick_box_title')."\n".
                    452:                $unameform."\n".
                    453:                &Apache::lonhtmlcommon::row_closure(1)."\n".
                    454:                &Apache::lonhtmlcommon::row_title(&mt('Password'),
                    455:                                                 'LC_pick_box_title')."\n".
                    456:                $upassform;
1.20      raeburn   457:     if ($context eq 'selfenroll') {
1.32      raeburn   458:         my $udomform = '<input type="text" name="udom" size="10" value="'.
1.20      raeburn   459:                         $domain.'" />';
1.31      bisitz    460:         $output .= &Apache::lonhtmlcommon::row_closure(1)."\n".
                    461:                    &Apache::lonhtmlcommon::row_title(&mt('Domain'),
1.20      raeburn   462:                                                      'LC_pick_box_title')."\n".
1.31      bisitz    463:                    $udomform."\n";
1.32      raeburn   464:     } else {
                    465:         $output .= '<input type="hidden" name="udom" value="'.$domain.'" />';
1.20      raeburn   466:     }
1.32      raeburn   467:     $output .= &Apache::lonhtmlcommon::row_closure(1).
1.31      bisitz    468:                &Apache::lonhtmlcommon::row_title().
1.32      raeburn   469:                '<br /><input type="submit" name="username_validation" value="'.
                    470:                $submit_text.'" />'."\n";
                    471:     if ($context eq 'selfenroll') {
                    472:         $output .= '<br /><br /><table width="100%"><tr><td align="right">'.
                    473:                    '<span class="LC_fontsize_medium">'.
                    474:                    '<a href="/adm/resetpw">'.&mt('Forgot password?').'</a>'.
                    475:                    '</span></td></tr></table>'."\n";
                    476:     }
                    477:     $output .= &Apache::lonhtmlcommon::row_closure(1)."\n".
                    478:                &Apache::lonhtmlcommon::end_pick_box().'<br />'."\n";
1.34      bisitz    479:     $output .= '<input type="hidden" name="lextkey" value="'.$lextkey.'" />'."\n".
                    480:                '<input type="hidden" name="uextkey" value="'.$uextkey.'" />'."\n".
1.22      raeburn   481:                '</form>';
1.20      raeburn   482:     return $output;
                    483: }
                    484: 
1.1       raeburn   485: sub process_email_request {
                    486:     my ($useremail,$domain,$domdesc,$contact_name,$contact_email,$cancreate,
1.3       raeburn   487:         $server,$settings,$courseid) = @_;
1.21      raeburn   488:     $useremail = $env{'form.useremail'};
1.1       raeburn   489:     my $output;
1.5       raeburn   490:     if (ref($cancreate) eq 'ARRAY') {
                    491:         if (!grep(/^email$/,@{$cancreate})) {
                    492:             $output = &invalid_state('noemails',$domdesc,
                    493:                                      $contact_name,$contact_email);
                    494:             return $output;
                    495:         } elsif ($useremail !~ /^[^\@]+\@[^\@]+\.[^\@\.]+$/) {
                    496:             $output = &invalid_state('baduseremail',$domdesc,
1.1       raeburn   497:                                      $contact_name,$contact_email);
                    498:             return $output;
                    499:         } else {
1.5       raeburn   500:             my $uhome = &Apache::lonnet::homeserver($useremail,$domain);
                    501:             if ($uhome ne 'no_host') {
                    502:                 $output = &invalid_state('existinguser',$domdesc,
                    503:                                          $contact_name,$contact_email);
1.1       raeburn   504:                 return $output;
1.5       raeburn   505:             } else {
                    506:                 my $code = $env{'form.code'};
                    507:                 my $md5sum = $env{'form.crypt'};
                    508:                 my %captcha_params = &captcha_settings();
                    509:                 my $captcha = Authen::Captcha->new(
                    510:                                   output_folder => $captcha_params{'output_dir'},
                    511:                                   data_folder   => $captcha_params{'db_dir'},
                    512:                                  );
                    513:                 my $captcha_chk = $captcha->check_code($code,$md5sum);
                    514:                 my %captcha_hash = (
                    515:                                   0       => 'Code not checked (file error)',
                    516:                                   -1      => 'Failed: code expired',
                    517:                                   -2      => 'Failed: invalid code (not in database)',
                    518:                                   -3      => 'Failed: invalid code (code does not match crypt)',
                    519:                                    );
                    520:                 if ($captcha_chk != 1) {
                    521:                     $output = &invalid_state('captcha',$domdesc,$contact_name,
                    522:                                              $contact_email,$captcha_hash{$captcha_chk});
                    523:                     return $output;
                    524:                 }
                    525:                 my $uhome=&Apache::lonnet::homeserver($useremail,$domain);
                    526:                 if ($uhome eq 'no_host') {
1.23      raeburn   527:                     my (%rulematch,%inst_results,%curr_rules,%got_rules,%alerts);
                    528:                     &call_rulecheck($useremail,$domain,\%alerts,\%rulematch,
1.40      raeburn   529:                                     \%inst_results,\%curr_rules,\%got_rules,'username');
1.23      raeburn   530:                     if (ref($alerts{'username'}) eq 'HASH') {
                    531:                         if (ref($alerts{'username'}{$domain}) eq 'HASH') {
1.5       raeburn   532:                             if ($alerts{'username'}{$domain}{$useremail}) {
                    533:                                 $output = &invalid_state('userrules',$domdesc,
                    534:                                                          $contact_name,$contact_email);
                    535:                                 return $output;
                    536:                             }
1.1       raeburn   537:                         }
                    538:                     }
1.5       raeburn   539:                     my $format_msg = 
                    540:                         &guest_format_check($useremail,$domain,$cancreate,
                    541:                                             $settings);
                    542:                     if ($format_msg) {
                    543:                         $output = &invalid_state('userformat',$domdesc,$contact_name,
                    544:                                                  $contact_email,$format_msg);
                    545:                         return $output;
                    546:                     }
1.1       raeburn   547:                 }
                    548:             }
                    549:         }
1.5       raeburn   550:         $output = &send_token($domain,$useremail,$server,$domdesc,$contact_name,
                    551:                           $contact_email,$courseid);
1.1       raeburn   552:     }
                    553:     return $output;
                    554: }
                    555: 
1.23      raeburn   556: sub call_rulecheck {
                    557:     my ($uname,$udom,$alerts,$rulematch,$inst_results,$curr_rules,
                    558:         $got_rules,$tocheck) = @_;
                    559:     my ($checkhash,$checks);
                    560:     $checkhash->{$uname.':'.$udom} = { 'newuser' => 1, };
                    561:     if ($tocheck eq 'username') {
                    562:         $checks = { 'username' => 1 };
                    563:     }
                    564:     &Apache::loncommon::user_rule_check($checkhash,$checks,
                    565:            $alerts,$rulematch,$inst_results,$curr_rules,
                    566:            $got_rules);
                    567:     return;
                    568: }
                    569: 
1.1       raeburn   570: sub send_token {
1.3       raeburn   571:     my ($domain,$email,$server,$domdesc,$contact_name,$contact_email,$courseid) = @_;
1.14      raeburn   572:     my $msg = '<h3>'.&mt('Account creation status').'</h3>'.
                    573:               &mt('Thank you for your request to create a new LON-CAPA account.').
                    574:               '<br /><br />';
1.1       raeburn   575:     my $now = time;
                    576:     my %info = ('ip'         => $ENV{'REMOTE_ADDR'},
                    577:                 'time'       => $now,
                    578:                 'domain'     => $domain,
1.3       raeburn   579:                 'username'   => $email,
                    580:                 'courseid'   => $courseid);
1.41      raeburn   581:     my $token = &Apache::lonnet::tmpput(\%info,$server,'createaccount');
1.1       raeburn   582:     if ($token !~ /^error/ && $token ne 'no_such_host') {
                    583:         my $esc_token = &escape($token);
1.28      raeburn   584:         my $showtime = localtime(time);
                    585:         my $mailmsg = &mt('A request was submitted on [_1] for creation of a LON-CAPA account at the following institution: [_2].',$showtime,$domdesc).' '.
                    586:              &mt('To complete this process please open a web browser and enter the following URL in the address/location box: [_1]',
                    587:                  &Apache::lonnet::absolute_url().'/adm/createaccount?token='.$esc_token);
1.1       raeburn   588:         my $result = &Apache::resetpw::send_mail($domdesc,$email,$mailmsg,$contact_name,
                    589:                                                  $contact_email);
                    590:         if ($result eq 'ok') {
                    591:             $msg .= &mt('A message has been sent to the e-mail address you provided.').'<br />'.&mt('The message includes the web address for the link you will use to complete the account creation process.').'<br />'.&mt("The link included in the message will be valid for the next [_1]two[_2] hours.",'<b>','</b>');
                    592:         } else {
1.14      raeburn   593:             $msg .= '<span class="LC_error">'.
                    594:                     &mt('An error occurred when sending a message to the e-mail address you provided.').'</span><br />'.
                    595:                     ' '.&mt('Please contact the [_1] ([_2]) for assistance.',$contact_name,$contact_email);
1.1       raeburn   596:         }
                    597:     } else {
1.14      raeburn   598:         $msg .= '<span class="LC_error">'.
                    599:                 &mt('An error occurred creating a token required for the account creation process.').'</span><br />'.
                    600:                 ' '.&mt('Please contact the [_1] ([_2]) for assistance.',$contact_name,$contact_email);
1.1       raeburn   601:     }
                    602:     return $msg;
                    603: }
                    604: 
                    605: sub process_mailtoken {
1.3       raeburn   606:     my ($r,$token,$contact_name,$contact_email,$domain,$domdesc,$lonhost,
                    607:         $include,$start_page) = @_;
                    608:     my ($msg,$nostart,$noend);
1.1       raeburn   609:     my %data = &Apache::lonnet::tmpget($token);
                    610:     my $now = time;
                    611:     if (keys(%data) == 0) {
1.9       raeburn   612:         $msg = &mt('Sorry, the URL you provided to complete creation of a new LON-CAPA account was invalid.')
                    613:                .' '.&mt('Either the token included in the URL has been deleted or the URL you provided was invalid.')
                    614:                .' '.&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.','<a href="/adm/createaccount">','</a>');
1.1       raeburn   615:         return $msg;
                    616:     }
                    617:     if (($data{'time'} =~ /^\d+$/) &&
                    618:         ($data{'domain'} ne '') &&
                    619:         ($data{'username'}  =~ /^[^\@]+\@[^\@]+\.[^\@\.]+$/)) {
                    620:         if ($now - $data{'time'} < 7200) {
                    621:             if ($env{'form.phase'} eq 'createaccount') {
1.51    ! raeburn   622:                 my ($result,$output,$uhome) = 
        !           623:                     &create_account($r,$domain,$data{'username'},$domdesc);
1.1       raeburn   624:                 if ($result eq 'ok') {
                    625:                     $msg = $output; 
1.17      raeburn   626:                     my $shownow = &Apache::lonlocal::locallocaltime($now);
1.38      bisitz    627:                     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";
1.1       raeburn   628:                     my $mailresult = &Apache::resetpw::send_mail($domdesc,$data{'email'},
                    629:                                                                  $mailmsg,$contact_name,
                    630:                                                                  $contact_email);
                    631:                     if ($mailresult eq 'ok') {
                    632:                         $msg .= &mt('An e-mail confirming creation of your new LON-CAPA account has been sent to [_1].',$data{'username'});
                    633:                     } else {
                    634:                         $msg .= &mt('An error occurred when sending e-mail to [_1] confirming creation of your LON-CAPA account.',$data{'username'});
                    635:                     }
1.51    ! raeburn   636:                     &start_session($r,$data{'username'},$domain,$uhome,
        !           637:                                    $data{'courseid'},$token);
1.3       raeburn   638:                     $nostart = 1;
                    639:                     $noend = 1;
1.1       raeburn   640:                 } else {
1.7       bisitz    641:                     $msg .= &mt('A problem occurred when attempting to create your new LON-CAPA account.')
                    642:                            .'<br />'.$output
                    643: #                           .&mt('Please contact the [_1] ([_2]) for assistance.',$contact_name,'<a href="mailto:'.$contact_email.'">'.$contact_email.'</a>');
                    644:                            .&mt('Please contact the [_1] ([_2]) for assistance.',$contact_name,$contact_email);
1.1       raeburn   645:                 }
1.3       raeburn   646:                 my $delete = &Apache::lonnet::tmpdel($token);
1.1       raeburn   647:             } else {
1.3       raeburn   648:                 $msg .= &mt('Please provide user information and a password for your new account.').'<br />'.&mt('Your password, which must contain at least seven characters, will be sent to the LON-CAPA server in an encrypted form.').'<br />';
                    649:                 $msg .= &print_dataentry_form($r,$domain,$lonhost,$include,$token,$now,$data{'username'},$start_page);
                    650:                 $nostart = 1;
1.1       raeburn   651:             }
                    652:         } else {
1.7       bisitz    653:             $msg = &mt('Sorry, the token generated when you requested creation of an account has expired.')
                    654:                   .' '.&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   655:             }
1.1       raeburn   656:     } else {
1.7       bisitz    657:         $msg .= &mt('Sorry, the URL generated when you requested creation of an account contained incomplete information.')
                    658:                .' '.&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   659:     }
1.3       raeburn   660:     return ($msg,$nostart,$noend);
                    661: }
                    662: 
                    663: sub start_session {
1.51    ! raeburn   664:     my ($r,$username,$domain,$uhome,$courseid,$token) = @_;
1.48      droeschl  665: 
1.3       raeburn   666:     if ($r->dir_config('lonBalancer') eq 'yes') {
1.51    ! raeburn   667:         Apache::lonauth::success($r, $username, $domain, $uhome,
1.48      droeschl  668:             'noredirect', undef, {});
                    669: 
                    670:         Apache::lonnet::tmpdel($token) if $token;
                    671: 
1.3       raeburn   672:         $r->internal_redirect('/adm/switchserver');
                    673:     } else {
1.48      droeschl  674:         $courseid = Apache::lonnet::is_course($courseid); 
                    675: 
1.51    ! raeburn   676:         Apache::lonauth::success($r, $username, $domain, $uhome,
1.48      droeschl  677:             ($courseid ? "/adm/selfenroll?courseid=$courseid" : '/adm/roles'),
                    678:             undef, {}); 
1.3       raeburn   679:     }
1.48      droeschl  680: 
                    681:     return;
1.1       raeburn   682: }
                    683: 
1.50      www       684: #
                    685: # The screen that the user gets to create his or her account
                    686: # Desired username, desired password, etc
                    687: # Stores token to store DES-key and stage during creation session
                    688: #
1.1       raeburn   689: sub print_dataentry_form {
1.3       raeburn   690:     my ($r,$domain,$lonhost,$include,$mailtoken,$now,$username,$start_page) = @_;
1.1       raeburn   691:     my ($error,$output);
1.3       raeburn   692:     &print_header($r,$start_page);
1.1       raeburn   693:     if (open(my $jsh,"<$include/londes.js")) {
                    694:         while(my $line = <$jsh>) {
                    695:             $r->print($line);
                    696:         }
                    697:         close($jsh);
1.3       raeburn   698:         $output .= &javascript_setforms($now)."\n".&javascript_checkpass($now);
1.1       raeburn   699:         my ($lkey,$ukey) = &Apache::lonpreferences::des_keys();
                    700:         my ($lextkey,$uextkey) = &getkeys($lkey,$ukey);
1.41      raeburn   701:         my $logtoken=Apache::lonnet::reply('tmpput:'.$ukey.$lkey.'&createaccount:createaccount',
1.1       raeburn   702:                                            $lonhost);
1.32      raeburn   703:         my $formtag = '<form name="server" method="post" target="_top" action="/adm/createaccount">';
                    704:         my ($datatable,$rowcount) =
                    705:             &Apache::loncreateuser::personal_data_display($username,$domain,
                    706:                                                           'email','selfcreate');
                    707:         if ($rowcount) {
                    708:             $output .= '<div class="LC_left_float">'.$formtag.$datatable;
                    709:         } else {
                    710:             $output .= $formtag;
1.1       raeburn   711:         }
                    712:         $output .= <<"ENDSERVERFORM";
                    713:    <input type="hidden" name="logtoken" value="$logtoken" />
                    714:    <input type="hidden" name="token" value="$mailtoken" />
                    715:    <input type="hidden" name="serverid" value="$lonhost" />
                    716:    <input type="hidden" name="uname" value="" />
                    717:    <input type="hidden" name="upass" value="" />
1.32      raeburn   718:    <input type="hidden" name="udom" value="" />
1.1       raeburn   719:    <input type="hidden" name="phase" value="createaccount" />
1.32      raeburn   720:   </form>
1.1       raeburn   721: ENDSERVERFORM
1.32      raeburn   722:         if ($rowcount) {
                    723:             $output .= '</div>'.
                    724:                        '<div class="LC_left_float">';
                    725:         }
1.1       raeburn   726:         my $upassone = '<input type="password" name="upass'.$now.'" size="10" />';
                    727:         my $upasstwo = '<input type="password" name="upasscheck'.$now.'" size="10" />';
                    728:         my $submit_text = &mt('Create LON-CAPA account');
1.32      raeburn   729:         $output .= '<h3>'.&mt('Login Data').'</h3>'."\n".
1.46      raeburn   730:                    '<form name="client" method="post" action="" '.
1.32      raeburn   731:                    'onsubmit="return checkpass();">'."\n".
1.1       raeburn   732:                    &Apache::lonhtmlcommon::start_pick_box()."\n".
                    733:                    &Apache::lonhtmlcommon::row_title(&mt('Username'),
1.32      raeburn   734:                                                      'LC_pick_box_title',
                    735:                                                      'LC_oddrow_value')."\n".
1.1       raeburn   736:                    $username."\n".
                    737:                    &Apache::lonhtmlcommon::row_closure(1)."\n".
                    738:                    &Apache::lonhtmlcommon::row_title(&mt('Password'),
1.32      raeburn   739:                                                     'LC_pick_box_title',
                    740:                                                     'LC_oddrow_value')."\n".
1.1       raeburn   741:                    $upassone."\n".
                    742:                    &Apache::lonhtmlcommon::row_closure(1)."\n".
                    743:                    &Apache::lonhtmlcommon::row_title(&mt('Confirm password'),
1.32      raeburn   744:                                                      'LC_pick_box_title',
                    745:                                                      'LC_oddrow_value')."\n".
                    746:                    $upasstwo.
                    747:                    &Apache::lonhtmlcommon::row_closure(1)."\n".
                    748:                    &Apache::lonhtmlcommon::row_title()."\n".
                    749:                    '<br /><input type="submit" name="createaccount" value="'.
                    750:                    $submit_text.'" />'.
1.1       raeburn   751:                    &Apache::lonhtmlcommon::row_closure(1)."\n".
                    752:                    &Apache::lonhtmlcommon::end_pick_box()."\n".
1.32      raeburn   753:                    '<input type="hidden" name="uname" value="'.$username.'" />'."\n".
                    754:                    '<input type="hidden" name="udom" value="'.$domain.'" />'."\n".
                    755:                    '<input type="hidden" name="lextkey" value="'.$lextkey.'" />'."\n".
                    756:                    '<input type="hidden" name="uextkey" value="'.$uextkey.'" />'."\n".
                    757:                    '</form>';
                    758:         if ($rowcount) {
                    759:             $output .= '</div>'."\n".
                    760:                        '<div class="LC_clear_float_footer"></div>'."\n";
                    761:         }
1.1       raeburn   762:     } else {
1.7       bisitz    763:         $output = &mt('Could not load javascript file [_1]','<tt>londes.js</tt>');
1.1       raeburn   764:     }
1.3       raeburn   765:     return $output;
1.1       raeburn   766: }
                    767: 
1.50      www       768: #
                    769: # Retrieve rules for generating accounts from domain configuration
                    770: # Can the user make a new account or just self-enroll?
                    771: 
1.35      raeburn   772: sub get_creation_controls {
                    773:     my ($domain,$usercreation) = @_;
                    774:     my (@cancreate,@statustocreate);
                    775:     if (ref($usercreation) eq 'HASH') {
                    776:         if (ref($usercreation->{'cancreate'}) eq 'HASH') {
                    777:             if (ref($usercreation->{'cancreate'}{'statustocreate'}) eq 'ARRAY') {
                    778:                 @statustocreate = @{$usercreation->{'cancreate'}{'statustocreate'}};
1.47      raeburn   779:                 if (@statustocreate == 0) {
                    780:                     my ($othertitle,$usertypes,$types) =
                    781:                         &Apache::loncommon::sorted_inst_types($domain);
                    782:                     if (ref($types) eq 'ARRAY') {
                    783:                         if (@{$types} == 0) {
                    784:                             @statustocreate = ('default');
                    785:                         }
                    786:                     } else {
                    787:                         @statustocreate = ('default');
                    788:                     }
                    789:                 }
1.35      raeburn   790:             } else {
                    791:                 @statustocreate = ('default');
                    792:                 my ($othertitle,$usertypes,$types) =
                    793:                     &Apache::loncommon::sorted_inst_types($domain);
                    794:                 if (ref($types) eq 'ARRAY') {
                    795:                     push(@statustocreate,@{$types});
                    796:                 }
                    797:             }
                    798:             if (ref($usercreation->{'cancreate'}{'selfcreate'}) eq 'ARRAY') {
                    799:                 @cancreate = @{$usercreation->{'cancreate'}{'selfcreate'}};
                    800:             } elsif (($usercreation->{'cancreate'}{'selfcreate'} ne 'none') &&
                    801:                      ($usercreation->{'cancreate'}{'selfcreate'} ne '')) {
                    802:                 @cancreate = ($usercreation->{'cancreate'}{'selfcreate'});
                    803:             }
                    804:         }
                    805:     }
                    806:     return (\@cancreate,\@statustocreate);
                    807: }
                    808: 
1.1       raeburn   809: sub create_account {
1.51    ! raeburn   810:     my ($r,$domain,$username,$domdesc) = @_;
1.50      www       811: # Get the token info
1.1       raeburn   812:     my ($retrieved,$output,$upass) = &process_credentials($env{'form.logtoken'},
                    813:                                                           $env{'form.serverid'}); 
1.50      www       814: # $retrieved is 'ok' if things worked
                    815: # $output is user error output
                    816: # $upass is the decrypted password
1.1       raeburn   817:     # Error messages
1.7       bisitz    818:     my $error     = '<span class="LC_error">'.&mt('Error:').' ';
1.1       raeburn   819:     my $end       = '</span><br /><br />';
                    820:     my $rtnlink   = '<a href="javascript:history.back();" />'.
                    821:                     &mt('Return to previous page').'</a>'.
                    822:                     &Apache::loncommon::end_page();
                    823:     if ($retrieved eq 'ok') {
1.22      raeburn   824:         if ($env{'form.courseid'} ne '') {
1.50      www       825: # See if we are allowed to use this username per domain rules (number of characters, etc)
1.1       raeburn   826:             my ($result,$userchkmsg) = &check_id($username,$domain,$domdesc);
                    827:             if ($result eq 'fail') {
                    828:                 $output = $error.&mt('Invalid ID format').$end.
                    829:                           $userchkmsg.$rtnlink;
                    830:                 return ('fail',$output);
                    831:             }
                    832:         }
                    833:     } else {
                    834:         return ('fail',$error.$output.$end.$rtnlink);
                    835:     }
1.50      www       836:     # Yes! We can do this. Valid token, valid username format
                    837:     # Create an internally authenticated account with password $upass 
                    838:     # if the account does not exist yet
                    839:     # Assign student/staff number $env{'form.cid'}, first name, last name, etc
1.1       raeburn   840:     my $result = 
                    841:         &Apache::lonnet::modifyuser($domain,$username,$env{'form.cid'},
                    842:                                     'internal',$upass,$env{'form.cfirstname'},
                    843:                                     $env{'form.cmiddlename'},$env{'form.clastname'},
                    844:                                     $env{'form.cgeneration'},undef,undef,$username);
1.7       bisitz    845:     $output = &mt('Generating user: [_1]',$result);
1.50      www       846:     # Now that the user exists, we can have a homeserver
1.1       raeburn   847:     my $uhome = &Apache::lonnet::homeserver($username,$domain);
1.7       bisitz    848:     $output .= '<br />'.&mt('Home server: [_1]',$uhome).' '.
1.1       raeburn   849:               &Apache::lonnet::hostname($uhome).'<br /><br />';
1.51    ! raeburn   850:     return ('ok',$output,$uhome);
1.1       raeburn   851: }
                    852: 
                    853: sub username_validation {
1.19      raeburn   854:     my ($r,$username,$domain,$domdesc,$contact_name,$contact_email,$courseid,
1.35      raeburn   855:         $lonhost,$statustocreate) = @_;
1.49      www       856: # $username,$domain: for the user who needs to be validated
                    857: # $domdesc: full name of the domain (for error messages)
                    858: # $contact_name, $contact_email: name and email for user assistance (for error messages in &username_check
                    859: # $courseid: ID of the course that the user should be validated for, goes into start_session
                    860: # $statustocreate: -> inststatus in username_check ('faculty', 'staff', 'student', ...)
                    861:  
1.1       raeburn   862:     my ($retrieved,$output,$upass);
                    863: 
                    864:     $username= &LONCAPA::clean_username($username);
                    865:     $domain = &LONCAPA::clean_domain($domain);
                    866:     my $uhome = &Apache::lonnet::homeserver($username,$domain);
                    867: 
                    868:     ($retrieved,$output,$upass) = &process_credentials($env{'form.logtoken'},
                    869:                                                        $env{'form.serverid'});
1.19      raeburn   870:     if ($retrieved ne 'ok') {
                    871:         return ('fail',$output);
                    872:     }
                    873:     if ($uhome ne 'no_host') {
                    874:         my $result = &Apache::lonnet::authenticate($username,$upass,$domain);
                    875:         if ($result ne 'no_host') { 
1.51    ! raeburn   876:             &start_session($r,$username,$domain,$uhome,$courseid);
1.19      raeburn   877:             $output = '<br /><br />'.&mt('A LON-CAPA account already exists for username [_1] at this institution ([_2]).','<tt>'.$username.'</tt>',$domdesc).'<br />'.&mt('The password entered was also correct so you have been logged in.');
                    878:             return ('existingaccount',$output);
                    879:         } else {
1.22      raeburn   880:             $output = &login_failure_msg($courseid);
1.19      raeburn   881:         }
                    882:     } else {
1.1       raeburn   883:         my $primlibserv = &Apache::lonnet::domain($domain,'primary');
                    884:         my $authok;
                    885:         my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                    886:         if ((($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) || ($domdefaults{'auth_def'} eq 'localauth')) {
                    887:             my $checkdefauth = 1;
                    888:             $authok = 
                    889:                 &Apache::lonnet::reply("encrypt:auth:$domain:$username:$upass:$checkdefauth",$primlibserv);
                    890:         } else {
                    891:             $authok = 'non_authorized';
                    892:         }
                    893:         if ($authok eq 'authorized') {
1.18      raeburn   894:             $output = &username_check($username,$domain,$domdesc,$courseid,$lonhost,
1.35      raeburn   895:                                       $contact_email,$contact_name,undef,
                    896:                                       $statustocreate);
1.4       raeburn   897:         } else {
1.22      raeburn   898:             $output = &login_failure_msg($courseid);
1.4       raeburn   899:         }
                    900:     }
1.19      raeburn   901:     return ('ok',$output);
1.4       raeburn   902: }
                    903: 
1.22      raeburn   904: sub login_failure_msg {
                    905:     my ($courseid) = @_;
                    906:     my $url;
                    907:     if ($courseid ne '') {
                    908:         $url = "/adm/selfenroll?courseid=".$courseid;
                    909:     } else {
                    910:         $url = "/adm/createaccount";
                    911:     }
                    912:     my $output = '<h4>'.&mt('Authentication failed').'</h4><div class="LC_warning">'.
                    913:                  &mt('Username and/or password could not be authenticated.').
                    914:                  '</div>'.
                    915:                  &mt('Please check the username and password.').'<br /><br />';
                    916:                  '<a href="'.$url.'">'.&mt('Try again').'</a>';
                    917:     return $output;
                    918: }
                    919: 
1.4       raeburn   920: sub username_check {
1.35      raeburn   921:     my ($username,$domain,$domdesc,$courseid,$lonhost,$contact_email,
                    922:         $contact_name,$sso_logout,$statustocreate) = @_;
1.23      raeburn   923:     my (%rulematch,%inst_results,$checkfail,$rowcount,$editable,$output,$msg,
1.18      raeburn   924:         %alerts,%curr_rules,%got_rules);
1.23      raeburn   925:     &call_rulecheck($username,$domain,\%alerts,\%rulematch,
1.40      raeburn   926:                     \%inst_results,\%curr_rules,\%got_rules,'username');
1.4       raeburn   927:     if (ref($alerts{'username'}) eq 'HASH') {
                    928:         if (ref($alerts{'username'}{$domain}) eq 'HASH') {
                    929:             if ($alerts{'username'}{$domain}{$username}) {
                    930:                 if (ref($curr_rules{$domain}) eq 'HASH') {
1.18      raeburn   931:                     $output =
1.17      raeburn   932:                         &Apache::loncommon::instrule_disallow_msg('username',$domdesc,1,
                    933:                                                                   'selfcreate').
1.4       raeburn   934:                         &Apache::loncommon::user_rule_formats($domain,$domdesc,
                    935:                                 $curr_rules{$domain}{'username'},'username');
1.1       raeburn   936:                 }
1.18      raeburn   937:                 $checkfail = 'username';
1.1       raeburn   938:             }
1.4       raeburn   939:         }
                    940:     }
1.18      raeburn   941:     if (!$checkfail) {
1.35      raeburn   942:         if (ref($statustocreate) eq 'ARRAY') {
                    943:             $checkfail = 'inststatus';
                    944:             if (ref($inst_results{$username.':'.$domain}{inststatus}) eq 'ARRAY') {
                    945:                 foreach my $inststatus (@{$inst_results{$username.':'.$domain}{inststatus}}) {
                    946:                     if (grep(/^\Q$inststatus\E$/,@{$statustocreate})) {
                    947:                         undef($checkfail);
                    948:                         last;
                    949:                     }
                    950:                 }
                    951:             } elsif (grep(/^default$/,@{$statustocreate})) {
                    952:                 undef($checkfail);
                    953:             }
                    954:         }
                    955:     }
                    956:     if (!$checkfail) {
1.18      raeburn   957:         $output = '<form method="post" action="/adm/createaccount">';
                    958:         (my $datatable,$rowcount,$editable) = 
                    959:             &Apache::loncreateuser::personal_data_display($username,$domain,1,'selfcreate',
                    960:                                                          $inst_results{$username.':'.$domain});
                    961:         if ($rowcount > 0) {
                    962:             $output .= $datatable;
                    963:         }
                    964:         $output .=  '<br /><br /><input type="hidden" name="uname" value="'.$username.'" />'."\n".
                    965:                     '<input type="hidden" name="udom" value="'.$domain.'" />'."\n".
                    966:                     '<input type="hidden" name="phase" value="username_activation" />';
                    967:         my $now = time;
                    968:         my %info = ('ip'         => $ENV{'REMOTE_ADDR'},
                    969:                     'time'       => $now,
                    970:                     'domain'     => $domain,
                    971:                     'username'   => $username);
1.41      raeburn   972:         my $authtoken = &Apache::lonnet::tmpput(\%info,$lonhost,'createaccount');
1.18      raeburn   973:         if ($authtoken !~ /^error/ && $authtoken ne 'no_such_host') {
                    974:             $output .= '<input type="hidden" name="authtoken" value="'.&HTML::Entities::encode($authtoken,'&<>"').'" />';
                    975:         } else {
                    976:             $output = &mt('An error occurred when storing a token').'<br />'.
                    977:                       &mt('You will not be able to proceed to the next stage of account creation').
                    978:                       &linkto_email_help($contact_email,$domdesc);
                    979:             $checkfail = 'authtoken';
                    980:         }
                    981:     }
                    982:     if ($checkfail) { 
1.47      raeburn   983:         $msg = '<br /><h4>'.&mt('Account creation unavailable').'</h4>';
1.18      raeburn   984:         if ($checkfail eq 'username') {
                    985:             $msg .= '<span class="LC_warning">'.
                    986:                      &mt('A LON-CAPA account may not be created with the username you use.').
                    987:                      '</span><br /><br />'.$output;
                    988:         } elsif ($checkfail eq 'authtoken') {
                    989:             $msg .= '<span class="LC_error">'.&mt('Error creating token.').'</span>'.
                    990:                     '<br />'.$output;
1.35      raeburn   991:         } elsif ($checkfail eq 'inststatus') {
                    992:             $msg .= '<span class="LC_warning">'.
                    993:                      &mt('You are not permitted to create a LON-CAPA account.').
                    994:                      '</span><br /><br />'.$output;
1.18      raeburn   995:         }
                    996:         $msg .= &mt('Please contact the [_1] ([_2]) for assistance.',
                    997:                 $contact_name,$contact_email).'<br /><hr />'.
                    998:                 $sso_logout;
                    999:         &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  1000:     } else {
1.18      raeburn  1001:         if ($courseid ne '') {
                   1002:             $output .= '<input type="hidden" name="courseid" value="'.$courseid.'" />';
                   1003:         }
                   1004:         $output .= '<input type="submit" name="newaccount" value="'.
                   1005:                    &mt('Create LON-CAPA account').'" /></form>';
                   1006:         if ($rowcount) {
                   1007:             if ($editable) {
1.22      raeburn  1008:                 if ($courseid ne '') { 
1.47      raeburn  1009:                     $msg = '<br /><h4>'.&mt('User information').'</h4>';
1.22      raeburn  1010:                 }
                   1011:                 $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  1012:             } else {
1.22      raeburn  1013:                  if ($courseid ne '') {
                   1014:                      $msg = '<h4>'.&mt('Review user information').'</h4>';
                   1015:                  }
                   1016:                  $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  1017:             }
                   1018:         } else {
1.22      raeburn  1019:             if ($courseid ne '') {
                   1020:                 $msg = '<h4>'.&mt('Confirmation').'</h4>';
                   1021:             }
                   1022:             $msg .= &mt('Confirm that you wish to create an account.');
1.18      raeburn  1023:         }
                   1024:         $msg .= $output;
                   1025:     }
                   1026:     return $msg;
1.1       raeburn  1027: }
                   1028: 
                   1029: sub username_activation {
1.51    ! raeburn  1030:     my ($r,$username,$domain,$domdesc,$courseid) = @_;
1.1       raeburn  1031:     my $output;
1.7       bisitz   1032:     my $error     = '<span class="LC_error">'.&mt('Error:').' ';
1.1       raeburn  1033:     my $end       = '</span><br /><br />';
                   1034:     my $rtnlink   = '<a href="javascript:history.back();" />'.
                   1035:                     &mt('Return to previous page').'</a>'.
                   1036:                     &Apache::loncommon::end_page();
                   1037:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
1.8       raeburn  1038:     my %data = &Apache::lonnet::tmpget($env{'form.authtoken'});
                   1039:     my $now = time;
                   1040:     my $earlyout;
                   1041:     my $timeout = 300;
                   1042:     if (keys(%data) == 0) {
                   1043:         $output = &mt('Sorry, your authentication has expired.');
                   1044:         $earlyout = 'fail';
                   1045:     }
                   1046:     if (($data{'time'} !~ /^\d+$/) ||
                   1047:         ($data{'domain'} ne $domain) || 
                   1048:         ($data{'username'} ne $username)) {
                   1049:         $earlyout = 'fail';
                   1050:         $output = &mt('The credentials you provided could not be verified.');   
                   1051:     } elsif ($now - $data{'time'} > $timeout) {
                   1052:         $earlyout = 'fail';
                   1053:         $output = &mt('Sorry, your authentication has expired.');
                   1054:     }
                   1055:     if ($earlyout ne '') {
                   1056:         $output .= '<br />'.&mt('Please [_1]start again[_2].','<a href="/adm/createaccount">','</a>');
                   1057:         return($earlyout,$output);
                   1058:     }
1.3       raeburn  1059:     if ((($domdefaults{'auth_def'} =~/^krb(4|5)$/) && 
                   1060:          ($domdefaults{'auth_arg_def'} ne '')) || 
                   1061:         ($domdefaults{'auth_def'} eq 'localauth')) {
1.22      raeburn  1062:         if ($env{'form.courseid'} ne '') {
1.1       raeburn  1063:             my ($result,$userchkmsg) = &check_id($username,$domain,$domdesc);
                   1064:             if ($result eq 'fail') {
                   1065:                 $output = $error.&mt('Invalid ID format').$end.
                   1066:                           $userchkmsg.$rtnlink;
                   1067:                 return ('fail',$output);
                   1068:             }
                   1069:         }
                   1070:         # Call modifyuser
1.23      raeburn  1071:         my (%rulematch,%inst_results,%curr_rules,%got_rules,%alerts,%info);
                   1072:         &call_rulecheck($username,$domain,\%alerts,\%rulematch,
1.40      raeburn  1073:                         \%inst_results,\%curr_rules,\%got_rules);
1.23      raeburn  1074:         my @userinfo = ('firstname','middlename','lastname','generation',
                   1075:                         'permanentemail','id');
                   1076:         my %canmodify = 
                   1077:             &Apache::loncreateuser::selfcreate_canmodify('selfcreate',$domain,
                   1078:                                                          \@userinfo,\%inst_results);
                   1079:         foreach my $item (@userinfo) {
                   1080:             if ($canmodify{$item}) {
                   1081:                 $info{$item} = $env{'form.c'.$item};
                   1082:             } else {
                   1083:                 $info{$item} = $inst_results{$username.':'.$domain}{$item}; 
                   1084:             }
                   1085:         }
                   1086:         if (ref($inst_results{$username.':'.$domain}{'inststatus'}) eq 'ARRAY') {
                   1087:             my @inststatuses = @{$inst_results{$username.':'.$domain}{'inststatus'}};
                   1088:             $info{'inststatus'} = join(':',map { &escape($_); } @inststatuses);
                   1089:         }
1.1       raeburn  1090:         my $result =
1.23      raeburn  1091:             &Apache::lonnet::modifyuser($domain,$username,$env{'form.cid'},
1.1       raeburn  1092:                           $domdefaults{'auth_def'},
1.23      raeburn  1093:                           $domdefaults{'auth_arg_def'},$info{'firstname'},
                   1094:                           $info{'middlename'},$info{'lastname'},
                   1095:                           $info{'generation'},undef,undef,
                   1096:                           $info{'permanentemail'},$info{'inststatus'});
1.3       raeburn  1097:         if ($result eq 'ok') {
1.8       raeburn  1098:             my $delete = &Apache::lonnet::tmpdel($env{'form.authtoken'});
1.3       raeburn  1099:             $output = &mt('A LON-CAPA account has been created for username: [_1] in domain: [_2].',$username,$domain);
1.51    ! raeburn  1100:             my $uhome=&Apache::lonnet::homeserver($username,$domain,'true');
        !          1101:             &start_session($r,$username,$domain,$uhome,$courseid);
1.3       raeburn  1102:             my $nostart = 1;
                   1103:             return ('ok',$output,$nostart);
                   1104:         } else {
                   1105:             $output = &mt('Account creation failed for username: [_1] in domain: [_2].',$username,$domain).'<br /><span class="LC_error">'.&mt('Error: [_1]',$result).'</span>';
                   1106:             return ('fail',$output);
                   1107:         }
1.1       raeburn  1108:     } else {
1.7       bisitz   1109:         $output = &mt('User account creation is not available for the current default authentication type.')."\n";
1.1       raeburn  1110:         return('fail',$output);
                   1111:     }
                   1112: }
                   1113: 
                   1114: sub check_id {
                   1115:     my ($username,$domain,$domdesc) = @_;
                   1116:     # Check ID format
1.50      www      1117:     # Is $username in an okay format for $domain 
                   1118:     # (right number of characters, special characters, etc - follow domain rules)?
                   1119:     # $domdesc is just used for user error messages
1.1       raeburn  1120:     my (%alerts,%rulematch,%inst_results,%curr_rules,%checkhash);
                   1121:     my %checks = ('id' => 1);
                   1122:     %{$checkhash{$username.':'.$domain}} = (
                   1123:                                             'newuser' => 1,
                   1124:                                             'id' => $env{'form.cid'},
                   1125:                                            );
                   1126:     &Apache::loncommon::user_rule_check(\%checkhash,\%checks,\%alerts,
                   1127:                                         \%rulematch,\%inst_results,\%curr_rules);
                   1128:     if (ref($alerts{'id'}) eq 'HASH') {
                   1129:         if (ref($alerts{'id'}{$domain}) eq 'HASH') {
                   1130:             if ($alerts{'id'}{$domain}{$env{'form.cid'}}) {
                   1131:                 my $userchkmsg;
                   1132:                 if (ref($curr_rules{$domain}) eq 'HASH') {
                   1133:                     $userchkmsg  =
                   1134:                         &Apache::loncommon::instrule_disallow_msg('id',
                   1135:                                                            $domdesc,1).
                   1136:                         &Apache::loncommon::user_rule_formats($domain,
                   1137:                               $domdesc,$curr_rules{$domain}{'id'},'id');
                   1138:                 }
                   1139:                 return ('fail',$userchkmsg);
                   1140:             }
                   1141:         }
                   1142:     }
                   1143:     return; 
                   1144: }
                   1145: 
                   1146: sub invalid_state {
                   1147:     my ($error,$domdesc,$contact_name,$contact_email,$msgtext) = @_;
1.14      raeburn  1148:     my $msg = '<h3>'.&mt('Account creation unavailable').'</h3><span class="LC_error">';
1.1       raeburn  1149:     if ($error eq 'baduseremail') {
1.42      raeburn  1150:         $msg .= &mt('The e-mail address you provided does not appear to be a valid address.');
1.1       raeburn  1151:     } elsif ($error eq 'existinguser') {
1.42      raeburn  1152:         $msg .= &mt('The e-mail address you provided is already in use as a username in LON-CAPA at this institution.');
1.1       raeburn  1153:     } elsif ($error eq 'userrules') {
1.42      raeburn  1154:         $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  1155:     } elsif ($error eq 'userformat') {
1.42      raeburn  1156:         $msg .= &mt('The e-mail address you provided may not be used as a username at this LON-CAPA institution.');
1.1       raeburn  1157:     } elsif ($error eq 'captcha') {
1.43      raeburn  1158:         $msg .= &mt('Validation of the code you entered failed.');
1.1       raeburn  1159:     } elsif ($error eq 'noemails') {
1.42      raeburn  1160:         $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  1161:     }
1.14      raeburn  1162:     $msg .= '</span>';
1.1       raeburn  1163:     if ($msgtext) {
                   1164:         $msg .= '<br />'.$msgtext;
                   1165:     }
1.44      raeburn  1166:     $msg .= &linkto_email_help($contact_email,$domdesc,$error);
1.8       raeburn  1167:     return $msg;
                   1168: }
                   1169: 
                   1170: sub linkto_email_help {
1.44      raeburn  1171:     my ($contact_email,$domdesc,$error) = @_;
1.8       raeburn  1172:     my $msg;
1.44      raeburn  1173:     my $href = '/adm/helpdesk';
1.1       raeburn  1174:     if ($contact_email ne '') {
                   1175:         my $escuri = &HTML::Entities::encode('/adm/createaccount','&<>"');
1.44      raeburn  1176:         $href .= '?origurl='.$escuri;
                   1177:         if ($error eq 'existinguser') {
                   1178:             my $escemail = &HTML::Entities::encode($env{'form.useremail'});
                   1179:             $href .= '&useremail='.$escemail.'&useraccount='.$escemail;
                   1180:         }
                   1181:         $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  1182:     } else {
1.17      raeburn  1183:         $msg .= '<br />'.&mt('You may wish to send an e-mail to the server administrator: [_1] for [_2].',$Apache::lonnet::perlvar{'AdminEmail'},$domdesc).'<br />';
1.1       raeburn  1184:     }
                   1185:     return $msg;
                   1186: }
                   1187: 
                   1188: sub create_captcha {
                   1189:     my ($output_dir,$db_dir) = @_;
                   1190:     my %captcha_params = &captcha_settings();
1.28      raeburn  1191:     my ($output,$maxtries,$tries) = ('',10,0);
                   1192:     while ($tries < $maxtries) {
                   1193:         $tries ++;
                   1194:         my $captcha = Authen::Captcha->new (
                   1195:                                            output_folder => $captcha_params{'output_dir'},
                   1196:                                            data_folder   => $captcha_params{'db_dir'},
                   1197:                                           );
                   1198:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   1199: 
                   1200:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   1201:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
                   1202:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
                   1203:                      '<input type="text" size="5" name="code" value="" /><br />'.
1.36      bisitz   1204:                      '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" />';
1.28      raeburn  1205:             last;
                   1206:         }
                   1207:     }
1.1       raeburn  1208:     return $output;
                   1209: }
                   1210: 
                   1211: sub captcha_settings {
                   1212:     my %captcha_params = ( 
1.13      raeburn  1213:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   1214:                            www_output_dir => "/captchaspool",
                   1215:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
1.1       raeburn  1216:                            numchars       => '5',
                   1217:                          );
                   1218:     return %captcha_params;
                   1219: }
                   1220: 
                   1221: sub getkeys {
                   1222:     my ($lkey,$ukey) = @_;
                   1223:     my $lextkey=hex($lkey);
                   1224:     if ($lextkey>2147483647) { $lextkey-=4294967296; }
                   1225: 
                   1226:     my $uextkey=hex($ukey);
                   1227:     if ($uextkey>2147483647) { $uextkey-=4294967296; }
                   1228:     return ($lextkey,$uextkey);
                   1229: }
                   1230: 
                   1231: sub serverform {
1.20      raeburn  1232:     my ($logtoken,$lonhost,$mailtoken,$courseid,$context) = @_;
1.22      raeburn  1233:     my $phase = 'username_validation';
                   1234:     my $catalog_elements;
1.20      raeburn  1235:     if ($context eq 'selfenroll') {
                   1236:         $phase = 'selfenroll_login';
                   1237:     }
1.22      raeburn  1238:     if ($courseid ne '') {
                   1239:         $catalog_elements = &Apache::lonhtmlcommon::echo_form_input(['courseid','phase']);
                   1240:     } 
                   1241:     my $output = <<ENDSERVERFORM;
1.20      raeburn  1242:   <form name="server" method="post" action="/adm/createaccount">
1.1       raeburn  1243:    <input type="hidden" name="logtoken" value="$logtoken" />
                   1244:    <input type="hidden" name="token" value="$mailtoken" />
                   1245:    <input type="hidden" name="serverid" value="$lonhost" />
                   1246:    <input type="hidden" name="uname" value="" />
                   1247:    <input type="hidden" name="upass" value="" />
1.32      raeburn  1248:    <input type="hidden" name="udom" value="" />
1.20      raeburn  1249:    <input type="hidden" name="phase" value="$phase" />
1.3       raeburn  1250:    <input type="hidden" name="courseid" value="$courseid" />
1.22      raeburn  1251:    $catalog_elements
1.1       raeburn  1252:   </form>
                   1253: ENDSERVERFORM
                   1254:     return $output;
                   1255: }
                   1256: 
                   1257: sub process_credentials {
1.49      www      1258: #
                   1259: # Fetches the information from the logtoken via tmpget
                   1260: # Token contains the DES-key and the stage of the process (would only be "createaccount")
                   1261: # $lonhost in this routine is *not* necessarily the machine that this runs on,
                   1262: # but $env{'form.serverid'}, the machine that issued the token. 
                   1263: #
1.1       raeburn  1264:     my ($logtoken,$lonhost) = @_;
                   1265:     my $tmpinfo=Apache::lonnet::reply('tmpget:'.$logtoken,$lonhost);
                   1266:     my ($retrieved,$output,$upass);
                   1267:     if (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost')) {
1.7       bisitz   1268:         $output = &mt('Information needed to verify your login information is missing, inaccessible or expired.')
                   1269:                  .'<br />'.&mt('You may need to reload the previous page to obtain a new token.');
1.1       raeburn  1270:         return ($retrieved,$output,$upass); 
                   1271:     } else {
                   1272:         my $reply = &Apache::lonnet::reply('tmpdel:'.$logtoken,$lonhost);
                   1273:         if ($reply eq 'ok') {
                   1274:             $retrieved = 'ok';
                   1275:         } else {
                   1276:             $output = &mt('Session could not be opened.');
                   1277:         }
                   1278:     }
                   1279:     my ($key,$caller)=split(/&/,$tmpinfo);
                   1280:     if ($caller eq 'createaccount') {
                   1281:         $upass = &Apache::lonpreferences::des_decrypt($key,$env{'form.upass'});
                   1282:     } else {
                   1283:         $output = &mt('Unable to retrieve your log-in information - unexpected context');
                   1284:     }
1.49      www      1285: # $retrieved is 'ok' if retrieved okay
                   1286: # $output is screen output for the user
                   1287: # $upass is $env{'form.upass'}, decrypted with the DES-key, if stage was 'createaccount'
                   1288: 
1.1       raeburn  1289:     return ($retrieved,$output,$upass);
                   1290: }
                   1291: 
                   1292: sub guest_format_check {
                   1293:     my ($useremail,$domain,$cancreate,$settings) = @_;
                   1294:     my ($login,$format_match,$format_msg,@user_rules);
                   1295:     if (ref($settings) eq 'HASH') {
                   1296:         if (ref($settings->{'email_rule'}) eq 'ARRAY') {
                   1297:             push(@user_rules,@{$settings->{'email_rule'}});
                   1298:         }
                   1299:     }
                   1300:     if (@user_rules > 0) {
                   1301:         my %rule_check = 
                   1302:             &Apache::lonnet::inst_rulecheck($domain,$useremail,undef,
1.2       raeburn  1303:                                             'selfcreate',\@user_rules);
1.1       raeburn  1304:         if (keys(%rule_check) > 0) {
                   1305:             foreach my $item (keys(%rule_check)) {
                   1306:                 if ($rule_check{$item}) {
                   1307:                     $format_match = 1;   
                   1308:                     last;
                   1309:                 }
                   1310:             }
                   1311:         }
                   1312:     }
                   1313:     if ($format_match) {
                   1314:         ($login) = ($useremail =~ /^([^\@]+)\@/);
                   1315:         $format_msg = '<br />'.&mt("Your e-mail address uses the same internet domain as your institution's LON-CAPA service.").'<br />'.&mt('Creation of a LON-CAPA account with this type of e-mail address as username is not permitted.').'<br />';
1.5       raeburn  1316:         if (ref($cancreate) eq 'ARRAY') {
                   1317:             if (grep(/^login$/,@{$cancreate})) {
1.7       bisitz   1318:                 $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  1319:             }
1.1       raeburn  1320:         }
                   1321:     }
                   1322:     return $format_msg;
                   1323: }
                   1324: 
1.17      raeburn  1325: sub sso_logout_frag {
                   1326:     my ($r,$domain) = @_;
                   1327:     my $endsessionmsg;
                   1328:     if (defined($r->dir_config('lonSSOUserLogoutMessageFile_'.$domain))) {
                   1329:         my $msgfile = $r->dir_config('lonSSOUserLogoutMessageFile_'.$domain);
                   1330:         if (-e $msgfile) {
                   1331:             open(my $fh,"<$msgfile");
                   1332:             $endsessionmsg = join('',<$fh>);
                   1333:             close($fh);
                   1334:         }
                   1335:     } elsif (defined($r->dir_config('lonSSOUserLogoutMessageFile'))) {
                   1336:         my $msgfile = $r->dir_config('lonSSOUserLogoutMessageFile');
                   1337:         if (-e $msgfile) {     
                   1338:             open(my $fh,"<$msgfile");
                   1339:             $endsessionmsg = join('',<$fh>);
                   1340:             close($fh);
                   1341:         }
                   1342:     }
                   1343:     return $endsessionmsg;
                   1344: }
                   1345: 
1.22      raeburn  1346: sub catreturn_js {
                   1347:     return  <<"ENDSCRIPT";
                   1348: <script type="text/javascript">
                   1349: 
                   1350: function ToSelfenroll(formname) {
                   1351:     var formidx = getFormByName(formname);
                   1352:     if (formidx > -1) {
                   1353:         document.forms[formidx].action = '/adm/selfenroll';
                   1354:         numidx = getIndexByName(formidx,'phase');
                   1355:         if (numidx > -1) {
                   1356:             document.forms[formidx].elements[numidx].value = '';   
                   1357:         }
                   1358:         numidx = getIndexByName(formidx,'context');
                   1359:         if (numidx > -1) {
                   1360:             document.forms[formidx].elements[numidx].value = '';
                   1361:         }
                   1362:     }
                   1363:     document.forms[formidx].submit();
                   1364: }
                   1365: 
                   1366: function ToCatalog(formname,caller) {
                   1367:     var formidx = getFormByName(formname);
                   1368:     if (formidx > -1) {
                   1369:         document.forms[formidx].action = '/adm/coursecatalog';
                   1370:         numidx = getIndexByName(formidx,'coursenum');
                   1371:         if (numidx > -1) {
                   1372:             if (caller != 'details') {
                   1373:                 document.forms[formidx].elements[numidx].value = '';
                   1374:             }
                   1375:         }
                   1376:     }
                   1377:     document.forms[formidx].submit();
                   1378: }
                   1379: 
                   1380: function getIndexByName(formidx,item) {
                   1381:     for (var i=0;i<document.forms[formidx].elements.length;i++) {
                   1382:         if (document.forms[formidx].elements[i].name == item) {
                   1383:             return i;
                   1384:         }
                   1385:     }
                   1386:     return -1;
                   1387: }
                   1388: 
                   1389: function getFormByName(item) {
                   1390:     for (var i=0; i<document.forms.length; i++) {
                   1391:         if (document.forms[i].name == item) {
                   1392:             return i;
                   1393:         }
                   1394:     }
                   1395:     return -1;
                   1396: }
                   1397: 
                   1398: </script>
                   1399: ENDSCRIPT
                   1400: 
                   1401: }
                   1402: 
1.1       raeburn  1403: 1;

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