File:  [LON-CAPA] / loncom / interface / createaccount.pm
Revision 1.48: download - view: text, annotated - select for diffs
Wed May 16 21:19:39 2012 UTC (12 years ago) by droeschl
Branches: MAIN
CVS tags: HEAD
Replaced calls to selfenroll::validate_course_id and createaccount::validate_course by lonnet::is_course.
Extended functionality of lonnet::is_course.
Code cleanup.

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

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