[LON-CAPA-cvs] cvs: loncom /interface createaccount.pm

raeburn lon-capa-cvs-allow@mail.lon-capa.org
Sun, 24 Feb 2008 23:23:40 -0000


This is a MIME encoded message

--raeburn1203895420
Content-Type: text/plain

raeburn		Sun Feb 24 18:23:40 2008 EDT

  Added files:                 
    /loncom/interface	createaccount.pm 
  Log:
  Bug 5558. Visitors without a LON-CAPA account can create one, using an e-mail address (sends a URL to the address provided, which needs to be visited to complete the process), or an institutional login (authentication required).
  
  Requires Authen::Captcha perl module to discourage robotic account requests.
  
  Work in progress.
  
  
--raeburn1203895420
Content-Type: text/plain
Content-Disposition: attachment; filename="raeburn-20080224182340.txt"


Index: loncom/interface/createaccount.pm
+++ loncom/interface/createaccount.pm
# The LearningOnline Network
# Allow visitors to create a user account with the username being either an 
# institutional log-in ID (institutional authentication required - localauth
#  or kerberos) or an e-mail address.
#
# $Id: createaccount.pm,v 1.1 2008/02/24 23:23:39 raeburn Exp $
#
# Copyright Michigan State University Board of Trustees
#
# This file is part of the LearningOnline Network with CAPA (LON-CAPA).
#
# LON-CAPA is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# LON-CAPA is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with LON-CAPA; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# /home/httpd/html/adm/gpl.txt
#
# http://www.lon-capa.org/
#
#
package Apache::createaccount;

use strict;
use Apache::Constants qw(:common);
use Apache::lonacc;
use Apache::lonnet;
use Apache::loncommon;
use Apache::lonlocal;
use Apache::resetpw;
use Authen::Captcha;
use DynaLoader; # for Crypt::DES version
use Crypt::DES;
use LONCAPA;

sub handler {
    my $r = shift;
    &Apache::loncommon::content_type($r,'text/html');
    $r->send_http_header;
    if ($r->header_only) {
        return OK;
    }
    my $domain = &Apache::lonnet::default_login_domain();
    my $domdesc = &Apache::lonnet::domain($domain,'description');
    my $start_page =
        &Apache::loncommon::start_page('Create a user account in LON-CAPA','',
                                           {
                                             'no_inline_link'   => 1,});
    $r->print($start_page);
    &Apache::lonhtmlcommon::clear_breadcrumbs();
    &Apache::lonhtmlcommon::add_breadcrumb
    ({href=>"/adm/createuser",
      text=>"New username"});
    my $contact_name = &mt('LON-CAPA helpdesk');
    my $contact_email =  $r->dir_config('lonSupportEMail');
    my $lonhost = $r->dir_config('lonHostID');
    my $include = $r->dir_config('lonIncludes');
    &Apache::lonacc::get_posted_cgi($r);
    &Apache::lonlocal::get_language_handle($r);
    &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['token']);
    my $token = $env{'form.token'};
    my $output;
    my $cancreate;
    my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$domain);
    if (ref($domconfig{'usercreation'}) eq 'HASH') {
        if (ref($domconfig{'usercreation'}{'cancreate'}) eq 'HASH') { 
            if ($domconfig{'usercreation'}{'cancreate'}{'selfenroll'} ne 'none') {
                $cancreate = $domconfig{'usercreation'}{'cancreate'}{'selfenroll'};
            }
        }
    }
    $r->print(&Apache::lonhtmlcommon::breadcrumbs('Create account'));
    if (!$cancreate) {
        $output = &mt('Creation of a new user account using an e-mail address as username or a loginID from your institution is not permitted in the domain: [_1] ([_2])',$domain,$domdesc);
    } elsif ($token) {  
        $output = &process_mailtoken($r,$token,$contact_name,$contact_email,$domain,
                                     $domdesc,$lonhost,$include);
    } elsif ($env{'form.create_with_email'}) {
        $output = &process_email_request($env{'form.useremail'},$domain,$domdesc,
                                         $contact_name,$contact_email,$cancreate,
                                         $lonhost,$domconfig{'usercreation'});
    } elsif ($env{'form.phase'} eq 'username_validation') {
        $output = &username_validation($env{'form.uname'},$domain,$domdesc,
                                       $contact_name,$contact_email);
    } elsif ($env{'form.phase'} eq 'username_activation') {
        (my $result,$output) = &username_activation($env{'form.uname'},
                                                    $domain,$domdesc);
    } else {
        my $now=time;
        if ($cancreate eq 'any' || $cancreate eq 'login') {
            my $jsh=Apache::File->new($include."/londes.js");
            $r->print(<$jsh>);
            $r->print(&javascript_setforms($now));
        }
        $output = &print_username_form($domain,$domdesc,$cancreate,$now,$lonhost); 
    }
    $r->print($output);
    $r->print(&Apache::loncommon::end_page());
    return OK;
}

sub javascript_setforms {
    my ($now) =  @_;
    my $js = <<ENDSCRIPT;
 <script language="JavaScript">
    function send() {
        this.document.server.elements.uname.value = this.document.client.elements.uname.value;
        uextkey=this.document.client.elements.uextkey.value;
        lextkey=this.document.client.elements.lextkey.value;
        initkeys();

        this.document.server.elements.upass.value
            = crypted(this.document.client.elements.upass$now.value);

        this.document.client.elements.uname.value='';
        this.document.client.elements.upass$now.value='';

        this.document.server.submit();
        return false;
    }
 </script>
ENDSCRIPT
    return $js;
}

sub javascript_checkpass {
    my ($now) = @_;
    my $nopass = &mt('You must enter a password');
    my $mismatchpass = &mt('The passwords you entered did not match.').'\\n'.
                       &mt('Please try again.'); 
    my $js = <<"ENDSCRIPT";
<script type="text/javascript" language="JavaScript">
    function checkpass() {
        var upass = this.document.client.elements.upass$now.value;
        var upasscheck = this.document.client.elements.upasscheck$now.value;
        if (upass == '') {
            alert("$nopass");
            return;
        }
        if (upass == upasscheck) {
            this.document.client.elements.upasscheck$now.value='';
            send();
            return;
        } else {
            alert("$mismatchpass");
            return;
        } 
    }
</script>
ENDSCRIPT
    return $js;
}

sub print_username_form {
    my ($domain,$domdesc,$cancreate,$now,$lonhost) = @_;
    my %lt = &Apache::lonlocal::texthash(
                                         unam => 'username',
                                         udom => 'domain',
                                         uemail => 'Email address in LON-CAPA',
                                         proc => 'Proceed');
    my $output;
    if ($cancreate eq 'any' || $cancreate eq 'login') {
        my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
        if ((($domdefaults{'auth_def'} =~/^krb/) && ($domdefaults{'auth_arg_def'} ne '')) || ($domdefaults{'auth_def'} eq 'localauth')) {
            $output = '<div class="LC_left_float"><h3>'.&mt('Create account with a username provided by your institution').'</h3>';
            $output .= &mt('If you already have a Log-in ID at your institution, you may be able to use it[_1] for LON-CAPA.','<br />').'&nbsp;'.&mt('Type in your Log-in ID and password to find out.').'<br /><br />';
            my ($lkey,$ukey) = &Apache::lonpreferences::des_keys();
            my ($lextkey,$uextkey) = &getkeys($lkey,$ukey);
            my $logtoken=Apache::lonnet::reply('tmpput:'.$ukey.$lkey.'&createaccount',
                                               $lonhost);
            $output .= &serverform($logtoken,$lonhost);
            my $unameform = '<input type="text" name="uname" size="10" value="" />';
            my $upassform = '<input type="password" name="upass'.$now.'" size="10" />';
            my $submit_text = &mt('Create LON-CAPA account');
            $output .= '<form name="client" method="post" />'."\n". 
                       &Apache::lonhtmlcommon::start_pick_box()."\n".
                       &Apache::lonhtmlcommon::row_title(&mt('Log-in ID'),
                                                        'LC_pick_box_title')."\n".
                       $unameform."\n".
                       &Apache::lonhtmlcommon::row_closure(1)."\n".
                       &Apache::lonhtmlcommon::row_title(&mt('Password'),
                                                        'LC_pick_box_title')."\n".
                       $upassform."\n".'<br /><br />'."\n".
                       '<input type="button" name="username_validation" value="'.
                       $submit_text.'" onclick="javascript:send()" />'."\n". 
                       &Apache::lonhtmlcommon::row_closure(1)."\n".
                       &Apache::lonhtmlcommon::end_pick_box().'<br /><br />'."\n".
                       '<input type="hidden" name="lextkey" value="'.$lextkey.'">'."\n".
                       '<input type="hidden" name="uextkey" value="'.$uextkey.'">'."\n".
                       '</form></div>';
        }
    }
    if (($cancreate eq 'any') || ($cancreate eq 'email')) {
        $output .= '<div class="LC_left_float"><h3>'.&mt('Create account with an e-mail address as your username').'</h3>';
        if ($cancreate eq 'any') {
            $output .= &mt('Provide your e-mail address to request a LON-CAPA account if you do not have [_1] a log-in ID at your institution.','<br />').'<br /><br />';
        } elsif ($cancreate eq 'unofficial') {
            $output .= '<br />';
        }
        my $emailform = '<input type="text" name="useremail" size="25" value="" />';
        my $captchaform = &create_captcha();
        my $submit_text = &mt('Request LON-CAPA account');
        $output .=  '<form name="createaccount" method="post" onsubmit="validate_email();" >'.
                    &Apache::lonhtmlcommon::start_pick_box()."\n".
                    &Apache::lonhtmlcommon::row_title(&mt('E-mail address'),
                                                     'LC_pick_box_title')."\n".
                    $emailform."\n".
                    &Apache::lonhtmlcommon::row_closure(1).
                    &Apache::lonhtmlcommon::row_title(&mt('Validation'),
                                                     'LC_pick_box_title')."\n".
                    $captchaform."\n".'<br /><br />'.
                    '<input type="submit" name="create_with_email" value="'.
                    $submit_text.'" />'.
                    &Apache::lonhtmlcommon::row_closure(1).
                    &Apache::lonhtmlcommon::end_pick_box().'<br /><br /></form>'.
                    '</div>';
    }
    if ($output eq '') {
        $output = &mt('Creation of a new user account using either an e-mail address or institutional log-in ID as your username is not permitted in the domain: [_1] ([_2])',$domain,$domdesc);
    } else {
        $output .= '<div class="LC_clear_float_footer"></div>';
    }
    return $output;
}

sub process_email_request {
    my ($useremail,$domain,$domdesc,$contact_name,$contact_email,$cancreate,
        $server,$settings) = @_;
    my $useremail = $env{'form.useremail'};
    my $output;
    if ($cancreate ne 'any' && $cancreate ne 'email') {
        $output = &invalid_state('noemails',$domdesc,
                                 $contact_name,$contact_email);
        return $output;
    } elsif ($useremail !~ /^[^\@]+\@[^\@]+\.[^\@\.]+$/) {
        $output = &invalid_state('baduseremail',$domdesc,
                                 $contact_name,$contact_email);
        return $output;
    } else {
        my $uhome = &Apache::lonnet::homeserver($useremail,$domain);
        if ($uhome ne 'no_host') {
            $output = &invalid_state('existinguser',$domdesc,
                                     $contact_name,$contact_email);
            return $output;
        } else {
            my $code = $env{'form.code'};
            my $md5sum = $env{'form.crypt'};
            my %captcha_params = &captcha_settings();
            my $captcha = Authen::Captcha->new(
                              output_folder => $captcha_params{'output_dir'},
                              data_folder   => $captcha_params{'db_dir'},
                             );
            my $captcha_chk = $captcha->check_code($code,$md5sum);
            my %captcha_hash = (
                              0       => 'Code not checked (file error)',
                              -1      => 'Failed: code expired',
                              -2      => 'Failed: invalid code (not in database)',
                              -3      => 'Failed: invalid code (code does not match crypt)',
                               );
            if ($captcha_chk != 1) {
                $output = &invalid_state('captcha',$domdesc,$contact_name,
                                         $contact_email,$captcha_hash{$captcha_chk});
                return $output;
            }
            my (%rulematch,%inst_results,%curr_rules,%got_rules,%alerts);
            my $uhome=&Apache::lonnet::homeserver($useremail,$domain);
            if ($uhome eq 'no_host') {
                my $checkhash;
                my $checks = { 'username' => 1 };
                $checkhash->{$useremail.':'.$domain} = { 'newuser' => 1, };
                &Apache::loncommon::user_rule_check($checkhash,$checks,
                      \%alerts,\%rulematch,\%inst_results,\%curr_rules,
                      \%got_rules);
                if (ref($alerts{'useremail'}) eq 'HASH') {
                    if (ref($alerts{'useremail'}{$domain}) eq 'HASH') {
                        if ($alerts{'username'}{$domain}{$useremail}) {
                            $output = &invalid_state('userrules',$domdesc,
                                                     $contact_name,$contact_email);
                            return $output;
                        }
                    }
                }
                my $format_msg = 
                    &guest_format_check($useremail,$domain,$cancreate,
                                        $settings);
                if ($format_msg) {
                    $output = &invalid_state('userformat',$domdesc,$contact_name,
                                             $contact_email,$format_msg);
                    return $output;
                }
            }
        }
    }
    $output = &send_token($domain,$useremail,$server,$domdesc,$contact_name,
                          $contact_email);
    return $output;
}

sub send_token {
    my ($domain,$email,$server,$domdesc,$contact_name,$contact_email) = @_;
    my $msg = &mt('Thank you for your request to create a new LON-CAPA account.').'<br /><br />';
    my $now = time;
    my %info = ('ip'         => $ENV{'REMOTE_ADDR'},
                'time'       => $now,
                'domain'     => $domain,
                'username'   => $email);
    my $token = &Apache::lonnet::tmpput(\%info,$server);
    if ($token !~ /^error/ && $token ne 'no_such_host') {
        my $esc_token = &escape($token);
        my $mailmsg = &mt('A request was submitted on [_1] for creation of a LON-CAPA account in the [_2] domain.',localtime(time),$domdesc).' '.
             &mt('To complete this process please open a web browser and enter the following ".
             "URL in the address/location box: ').&Apache::lonnet::absolute_url()."/adm/createaccount?token=$esc_token";
        my $result = &Apache::resetpw::send_mail($domdesc,$email,$mailmsg,$contact_name,
                                                 $contact_email);
        if ($result eq 'ok') {
            $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>');
        } else {
            $msg .= &mt('An error occurred when sending a message to the e-mail address you provided. Please contact the [_1] ([_2]) for assistance.',$contact_name,$contact_email);
        }
    } else {
        $msg .= &mt('An error occurred creating a token required for the account creation process. Please contact the [_1] ([_2]) for assistance.',$contact_name,$contact_email);
    }
    return $msg;
}

sub process_mailtoken {
    my ($r,$token,$contact_name,$contact_email,$domain,$domdesc,$lonhost,$include) = @_;
    my $msg;
    my %data = &Apache::lonnet::tmpget($token);
    my $now = time;
    if (keys(%data) == 0) {
        $msg = &mt('Sorry, the URL you provided to complete creation of a new LON-CAPA account was invalid.  Either the token included in the URL has been deleted or the URL you provided was invalid. Please submit a <a href="/adm/createaccount">new request</a> for account creation and follow the link to the new URL included in the e-mail that will be sent to you.');
        return $msg;
    }
    if (($data{'time'} =~ /^\d+$/) &&
        ($data{'domain'} ne '') &&
        ($data{'username'}  =~ /^[^\@]+\@[^\@]+\.[^\@\.]+$/)) {
        my $reqtime = localtime($data{'time'});
        if ($now - $data{'time'} < 7200) {
            if ($env{'form.phase'} eq 'createaccount') {
                my ($result,$output) = &create_account($r,$domain,$lonhost,$token,
                                                       $data{'username'},$domdesc);
                if ($result eq 'ok') {
                    $msg = $output; 
                    my $delete = &Apache::lonnet::tmpdel($token);
                    my $now = localtime(time);
                    my $mailmsg = &mt('A LON-CAPA account in the [_1] domain has been created [_2] from IP address: [_3].  If you did not perform this action or authorize it, please contact the [_4] ([_5]).',$domdesc,$now,$ENV{'REMOTE_ADDR'},$contact_name,$contact_email)."\n";
                    my $mailresult = &Apache::resetpw::send_mail($domdesc,$data{'email'},
                                                                 $mailmsg,$contact_name,
                                                                 $contact_email);
                    if ($mailresult eq 'ok') {
                        $msg .= &mt('An e-mail confirming creation of your new LON-CAPA account has been sent to [_1].',$data{'username'});
                    } else {
                        $msg .= &mt('An error occurred when sending e-mail to [_1] confirming creation of your LON-CAPA account.',$data{'username'});
                    }
                    $msg .= '<br /><br />'.&mt('<a href="/adm/login">Go to the login page</a>.');
                } else {
                    $msg .= &mt('A problem occurred when attempting to create your new LON-CAPA account').'<br />'.$output.&mt('Please contact the [_1] - (<a href="mailto:[_2]">[_2]</a>) for assistance.',$contact_name,$contact_email);
                }
            } else {
                $r->print(&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 />');
                &print_dataentry_form($r,$domain,$lonhost,$include,$token,$now,$data{'username'});

            }
        } else {
            $msg = &mt('Sorry, the token generated when you requested creation of an account has expired. Please submit a <a href="/adm/createaccount">new request</a>, and follow the link to the web page included in the new e-mail that will be sent to you, to allow you to create the account.');
        }
    } else {
        $msg .= &mt('Sorry, the URL generated when you requested creation of an accountcontained incomplete information. Please submit a <a href="/adm/createaccount">new request</a> for creation of an account, and use the new URL that will be sent to your e-mail address to complete the process.');
    }
    return $msg;
}

sub print_dataentry_form {
    my ($r,$domain,$lonhost,$include,$mailtoken,$now,$username) = @_;
    my ($error,$output);
    if (open(my $jsh,"<$include/londes.js")) {
        while(my $line = <$jsh>) {
            $r->print($line);
        }
        close($jsh);
        $r->print(&javascript_setforms($now)."\n".&javascript_checkpass($now));
        my ($lkey,$ukey) = &Apache::lonpreferences::des_keys();
        my ($lextkey,$uextkey) = &getkeys($lkey,$ukey);
        my $logtoken=Apache::lonnet::reply('tmpput:'.$ukey.$lkey.'&createaccount',
                                           $lonhost);
        my @userinfo = ('firstname','middlename','lastname','generation','id',
                        'permanentemail');
        my %lt=&Apache::lonlocal::texthash(
                    'pd'             => "Personal Data",
                    'firstname'      => "First Name",
                    'middlename'     => "Middle Name",
                    'lastname'       => "Last Name",
                    'generation'     => "Generation",
                    'permanentemail' => "Permanent e-mail address",
                    'id'             => "ID/Student Number",
                    'lg'             => "Login Data"
        );
        my %textboxsize = (
                           firstname      => '15',
                           middlename     => '15',
                           lastname       => '15',
                           generation     => '5',
                           id             => '15',
                          );
        my $genhelp=&Apache::loncommon::help_open_topic('Generation');
        $output = '<div class="LC_left_float"><h3>'.$lt{'pd'}.'</h3>'.
                  '<form name="server" method="post" target="_top">'.
                  &Apache::lonhtmlcommon::start_pick_box();
        foreach my $item (@userinfo) {
            my $rowtitle = $lt{$item};
            if ($item eq 'generation') {
                $rowtitle = $genhelp.$rowtitle;
            }
            $output .= &Apache::lonhtmlcommon::row_title($rowtitle,undef,'LC_oddrow_value')."\n";
            if ($item eq 'permanentemail') {
                $output .= $username;
            } else {
                $output .= '<input type="text" name="c'.$item.'" size="'.$textboxsize{$item}.'" value="" />';
            }
            $output .= &Apache::lonhtmlcommon::row_closure(1);
        }
        $output .= &Apache::lonhtmlcommon::end_pick_box();
        $output .= <<"ENDSERVERFORM";
   <input type="hidden" name="logtoken" value="$logtoken" />
   <input type="hidden" name="token" value="$mailtoken" />
   <input type="hidden" name="serverid" value="$lonhost" />
   <input type="hidden" name="uname" value="" />
   <input type="hidden" name="upass" value="" />
   <input type="hidden" name="phase" value="createaccount" />
  </form></div>
ENDSERVERFORM
        my $upassone = '<input type="password" name="upass'.$now.'" size="10" />';
        my $upasstwo = '<input type="password" name="upasscheck'.$now.'" size="10" />';
        my $submit_text = &mt('Create LON-CAPA account');
        $output .= '<div class="LC_left_float"><h3>'.$lt{'lg'}.'</h3>'."\n".
                   '<form name="client" method="post" />'."\n".
                   &Apache::lonhtmlcommon::start_pick_box()."\n".
                   &Apache::lonhtmlcommon::row_title(&mt('Username'),
                                                    'LC_pick_box_title')."\n".
                   $username."\n".
                   &Apache::lonhtmlcommon::row_closure(1)."\n".
                   &Apache::lonhtmlcommon::row_title(&mt('Password'),
                                                    'LC_pick_box_title')."\n".
                   $upassone."\n".
                   &Apache::lonhtmlcommon::row_closure(1)."\n".
                   &Apache::lonhtmlcommon::row_title(&mt('Confirm password'),
                                                'LC_pick_box_title')."\n".
                   $upasstwo."\n".
                   &Apache::lonhtmlcommon::row_closure(1)."\n".
                   &Apache::lonhtmlcommon::end_pick_box()."\n".
                   '<input type="hidden" name="uname" value="'.$username.'">'."\n".
                   '<input type="hidden" name="lextkey" value="'.$lextkey.'">'."\n".
                   '<input type="hidden" name="uextkey" value="'.$uextkey.'">'."\n".
                   '</form></div>'."\n".
                   '<div class="LC_clear_float_footer"><br /><br />'."\n".
                   '<form name="buttonform">'."\n".
                   '<input type="button" name="createaccount" value="'.
                   $submit_text.'" onclick="javascript:checkpass();" /></form></div>';
        $r->print($output);
    } else {
        $error = &mt('Could not load javascript file [_1]','londes.js');
        $r->print($error);
    }
    return;
}

sub create_account {
    my ($r,$domain,$lonhost,$logtoken,$username,$domdesc) = @_;
    my ($retrieved,$output,$upass) = &process_credentials($env{'form.logtoken'},
                                                          $env{'form.serverid'}); 
    # Error messages
    my $error     = '<span class="LC_error">'.&mt('Error').': ';
    my $end       = '</span><br /><br />';
    my $rtnlink   = '<a href="javascript:history.back();" />'.
                    &mt('Return to previous page').'</a>'.
                    &Apache::loncommon::end_page();
    if ($retrieved eq 'ok') {
        if ($env{'form.cid'} ne '') {
            my ($result,$userchkmsg) = &check_id($username,$domain,$domdesc);
            if ($result eq 'fail') {
                $output = $error.&mt('Invalid ID format').$end.
                          $userchkmsg.$rtnlink;
                return ('fail',$output);
            }
        }
    } else {
        return ('fail',$error.$output.$end.$rtnlink);
    }
    # Call modifyuser
    my $result = 
        &Apache::lonnet::modifyuser($domain,$username,$env{'form.cid'},
                                    'internal',$upass,$env{'form.cfirstname'},
                                    $env{'form.cmiddlename'},$env{'form.clastname'},
                                    $env{'form.cgeneration'},undef,undef,$username);
    $output = &mt('Generating user').': '.$result;
    my $uhome = &Apache::lonnet::homeserver($username,$domain);
    $output .= '<br />'.&mt('Home server').': '.$uhome.' '.
              &Apache::lonnet::hostname($uhome).'<br /><br />';
    return ('ok',$output);
}

sub username_validation {
    my ($username,$domain,$domdesc,$contact_name,$contact_email) = @_;
    my ($retrieved,$output,$upass);

    $username= &LONCAPA::clean_username($username);
    $domain = &LONCAPA::clean_domain($domain);
    my $uhome = &Apache::lonnet::homeserver($username,$domain);

    if ($uhome ne 'no_host') {
        $output = &invalid_state('existinguser',$domdesc,
                                 $contact_name,$contact_email);
        return $output;
    }
    ($retrieved,$output,$upass) = &process_credentials($env{'form.logtoken'},
                                                       $env{'form.serverid'});
    if ($retrieved eq 'ok') {
        my $primlibserv = &Apache::lonnet::domain($domain,'primary');
        my $authok;
        my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
        if ((($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) || ($domdefaults{'auth_def'} eq 'localauth')) {
            my $checkdefauth = 1;
            $authok = 
                &Apache::lonnet::reply("encrypt:auth:$domain:$username:$upass:$checkdefauth",$primlibserv);
        } else {
            $authok = 'non_authorized';
        }
        if ($authok eq 'authorized') {
            my (%rulematch,%inst_results,$newuser,%alerts,%curr_rules,%got_rules);
            $newuser = 1;
            my $checkhash;
            my $checks = { 'username' => 1 };
            $checkhash->{$username.':'.$domain} = { 'newuser' => $newuser };
            &Apache::loncommon::user_rule_check($checkhash,$checks,
                \%alerts,\%rulematch,\%inst_results,\%curr_rules,\%got_rules);
            if (ref($alerts{'username'}) eq 'HASH') {
                if (ref($alerts{'username'}{$domain}) eq 'HASH') {
                    if ($alerts{'username'}{$domain}{$username}) {
                        my $userchkmsg;
                        if (ref($curr_rules{$domain}) eq 'HASH') {
                            $userchkmsg =
                                &Apache::loncommon::instrule_disallow_msg('username',
                                                                          $domdesc,1).
                            &Apache::loncommon::user_rule_formats($domain,
                                $domdesc,$curr_rules{$domain}{'username'},
                                'username');
                        }
                        return $userchkmsg; 
                    }
                }
            }
            my $submit_text = &mt('Create LON-CAPA account');
            $output =
                '<form method="post">'.
                &Apache::loncreateuser::personal_data_display($username,$domain,1,
                                       undef,$inst_results{$username.':'.$domain}).
                '<br /><br /><input type="hidden" name="uname" value="'.$username.'" />'.
                '<input type="hidden" name="phase" value="username_activation" />'.
                '<input type="submit" name="newaccount" value="'.
                $submit_text.'" /></form>';
        } else {
            $output = &mt('Not authenticated').' '.&mt('Please check the username and password'); 
        }
    }
    return $output;
}

sub username_activation {
    my ($username,$domain,$domdesc) = @_;
    my $output;
    my $error     = '<span class="LC_error">'.&mt('Error').': ';
    my $end       = '</span><br /><br />';
    my $rtnlink   = '<a href="javascript:history.back();" />'.
                    &mt('Return to previous page').'</a>'.
                    &Apache::loncommon::end_page();
    my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
    if ((($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) || ($domdefaults{'auth_def'} eq 'localauth')) {
        if ($env{'form.cid'} ne '') {
            my ($result,$userchkmsg) = &check_id($username,$domain,$domdesc);
            if ($result eq 'fail') {
                $output = $error.&mt('Invalid ID format').$end.
                          $userchkmsg.$rtnlink;
                return ('fail',$output);
            }
        }
        # Call modifyuser
        my $result =
            &Apache::lonnet::modifyuser($domain,$username,$env{'form.cid'},
                          $domdefaults{'auth_def'},
                          $domdefaults{'auth_arg_def'},$env{'form.cfirstname'},
                          $env{'form.cmiddlename'},$env{'form.clastname'},
                          $env{'form.cgeneration'},undef,undef,
                          $env{'form.cpermanentemail'});
        $output = &mt('Generating user').': '.$result;
        my $uhome = &Apache::lonnet::homeserver($username,$domain);
        $output .= '<br />'.&mt('Home server').': '.$uhome.' '.
                   &Apache::lonnet::hostname($uhome).'<br /><br />';
        return ('ok',$output);
    } else {
        $output = &mt("User account creation is not available for the current default authentication type.\n");
        return('fail',$output);
    }
}

sub check_id {
    my ($username,$domain,$domdesc) = @_;
    # Check ID format
    my (%alerts,%rulematch,%inst_results,%curr_rules,%checkhash);
    my %checks = ('id' => 1);
    %{$checkhash{$username.':'.$domain}} = (
                                            'newuser' => 1,
                                            'id' => $env{'form.cid'},
                                           );
    &Apache::loncommon::user_rule_check(\%checkhash,\%checks,\%alerts,
                                        \%rulematch,\%inst_results,\%curr_rules);
    if (ref($alerts{'id'}) eq 'HASH') {
        if (ref($alerts{'id'}{$domain}) eq 'HASH') {
            if ($alerts{'id'}{$domain}{$env{'form.cid'}}) {
                my $userchkmsg;
                if (ref($curr_rules{$domain}) eq 'HASH') {
                    $userchkmsg  =
                        &Apache::loncommon::instrule_disallow_msg('id',
                                                           $domdesc,1).
                        &Apache::loncommon::user_rule_formats($domain,
                              $domdesc,$curr_rules{$domain}{'id'},'id');
                }
                return ('fail',$userchkmsg);
            }
        }
    }
    return; 
}

sub invalid_state {
    my ($error,$domdesc,$contact_name,$contact_email,$msgtext) = @_;
    my $msg;
    if ($error eq 'baduseremail') {
        $msg = &mt('The e-mail address you provided does not appear to be a valid address.');
    } elsif ($error eq 'existinguser') {
        $msg = &mt('The e-mail address you provided is already in use as a username in this LON-CAPA domain.');
    } elsif ($error eq 'userrules') {
        $msg = &mt('Username rules for this LON-CAPA domain do not allow the e-mail address you provided to be used as a username.');
    } elsif ($error eq 'userformat') {
        $msg = &mt('The e-mail address you provided may not be used as a username in this LON-CAPA domain.');
    } elsif ($error eq 'captcha') {
        $msg = &mt('Validation of the code your entered failed.');
    } elsif ($error eq 'noemails') {
        $msg = &mt('Creation of a new user account using an e-mail address as username is not permitted in this LON-CAPA domain.');
    }
    if ($msgtext) {
        $msg .= '<br />'.$msgtext;
    }
    if ($contact_email ne '') {
        my $escuri = &HTML::Entities::encode('/adm/createaccount','&<>"');
        $msg .= '<br />'.&mt(' You may wish to contact the <a href="/adm/helpdesk?origurl=[_1]">LON-CAPA helpdesk</a> for the [_2] domain.',$escuri,$domdesc);
    } else {
        $msg .= '<br />'.&mt(' You may wish to send an e-mail to the server administrator: [_1] for the [_2] domain.',$Apache::lonnet::perlvar{'AdminEmail'},$domdesc);
    }
    return $msg;
}

sub create_captcha {
    my ($output_dir,$db_dir) = @_;
    my %captcha_params = &captcha_settings();
    my $captcha = Authen::Captcha->new(
                                       output_folder => $captcha_params{'output_dir'},
                                       data_folder   => $captcha_params{'db_dir'},
                                      );
    my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
    my $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
                 &mt('Type in the letters/numbers shown below').'&nbsp;'.
                 '<input type="text" size="5" name="code" value="" /><br />'.
                 '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png">';
    return $output;
}

sub captcha_settings {
    my %captcha_params = ( 
                           output_dir     => "/home/httpd/html/captcha",
                           www_output_dir => "/captcha",
                           db_dir         => "/home/www/captchadb",
                           numchars       => '5',
                         );
    return %captcha_params;
}

sub getkeys {
    my ($lkey,$ukey) = @_;
    my $lextkey=hex($lkey);
    if ($lextkey>2147483647) { $lextkey-=4294967296; }

    my $uextkey=hex($ukey);
    if ($uextkey>2147483647) { $uextkey-=4294967296; }
    return ($lextkey,$uextkey);
}

sub serverform {
    my ($logtoken,$lonhost,$mailtoken) = @_;
    my $output .= <<ENDSERVERFORM;
  <form name="server" method="post" target="_top">
   <input type="hidden" name="logtoken" value="$logtoken" />
   <input type="hidden" name="token" value="$mailtoken" />
   <input type="hidden" name="serverid" value="$lonhost" />
   <input type="hidden" name="uname" value="" />
   <input type="hidden" name="upass" value="" />
   <input type="hidden" name="phase" value="username_validation" />
  </form>
ENDSERVERFORM
    return $output;
}

sub process_credentials {
    my ($logtoken,$lonhost) = @_;
    my $tmpinfo=Apache::lonnet::reply('tmpget:'.$logtoken,$lonhost);
    my ($retrieved,$output,$upass);
    if (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost')) {
        $output = &mt('Information needed to retrieve your log-in information is missing, inaccessible or expired.').'<br />'.&mt('You may need to reload the previous page to obtain a new token.');
        return ($retrieved,$output,$upass); 
    } else {
        my $reply = &Apache::lonnet::reply('tmpdel:'.$logtoken,$lonhost);
        if ($reply eq 'ok') {
            $retrieved = 'ok';
        } else {
            $output = &mt('Session could not be opened.');
        }
    }
    my ($key,$caller)=split(/&/,$tmpinfo);
    if ($caller eq 'createaccount') {
        $upass = &Apache::lonpreferences::des_decrypt($key,$env{'form.upass'});
    } else {
        $output = &mt('Unable to retrieve your log-in information - unexpected context');
    }
    return ($retrieved,$output,$upass);
}

sub guest_format_check {
    my ($useremail,$domain,$cancreate,$settings) = @_;
    my ($login,$format_match,$format_msg,@user_rules);
    if (ref($settings) eq 'HASH') {
        if (ref($settings->{'email_rule'}) eq 'ARRAY') {
            push(@user_rules,@{$settings->{'email_rule'}});
        }
    }
    if (@user_rules > 0) {
        my %rule_check = 
            &Apache::lonnet::inst_rulecheck($domain,$useremail,undef,
                                            'selfenroll',\@user_rules);
        if (keys(%rule_check) > 0) {
            foreach my $item (keys(%rule_check)) {
                if ($rule_check{$item}) {
                    $format_match = 1;   
                    last;
                }
            }
        }
    }
    if ($format_match) {
        ($login) = ($useremail =~ /^([^\@]+)\@/);
        $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 />';
        if ($cancreate eq 'any' || $cancreate eq 'login') {
            $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 />'; 
        }
    }
    return $format_msg;
}

1;

--raeburn1203895420--