Diff for /loncom/auth/lonauth.pm between versions 1.133 and 1.151

version 1.133, 2014/04/06 13:40:19 version 1.151, 2018/04/21 21:29:31
Line 1 Line 1
 # The LearningOnline Network  # The LearningOnline Network
 # User Authentication Module  # User Authentication Module
 #  #
 # $Id$  # $Id$
 #  #
 # Copyright Michigan State University Board of Trustees  # Copyright Michigan State University Board of Trustees
 #  #
 # This file is part of the LearningOnline Network with CAPA (LON-CAPA).  # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
 #  #
 # LON-CAPA is free software; you can redistribute it and/or modify  # 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  # it under the terms of the GNU General Public License as published by
 # the Free Software Foundation; either version 2 of the License, or  # the Free Software Foundation; either version 2 of the License, or
 # (at your option) any later version.  # (at your option) any later version.
 #  #
 # LON-CAPA is distributed in the hope that it will be useful,  # LON-CAPA is distributed in the hope that it will be useful,
 # but WITHOUT ANY WARRANTY; without even the implied warranty of  # but WITHOUT ANY WARRANTY; without even the implied warranty of
 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 # GNU General Public License for more details.  # GNU General Public License for more details.
 #  #
 # You should have received a copy of the GNU General Public License  # You should have received a copy of the GNU General Public License
 # along with LON-CAPA; if not, write to the Free Software  # along with LON-CAPA; if not, write to the Free Software
 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA  # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 #  #
 # /home/httpd/html/adm/gpl.txt  # /home/httpd/html/adm/gpl.txt
 #  #
 # http://www.lon-capa.org/  # http://www.lon-capa.org/
 #  #
   
 package Apache::lonauth;  package Apache::lonauth;
   
 use strict;  use strict;
 use LONCAPA;  use LONCAPA qw(:DEFAULT :match);
 use Apache::Constants qw(:common);  use Apache::Constants qw(:common);
 use CGI qw(:standard);  use CGI qw(:standard);
 use DynaLoader; # for Crypt::DES version  use Apache::loncommon();
 use Crypt::DES;  use Apache::lonnet;
 use Apache::loncommon();  use Apache::lonmenu();
 use Apache::lonnet;  use Apache::createaccount;
 use Apache::lonmenu();  use Apache::ltiauth;
 use Apache::createaccount;  use Fcntl qw(:flock);
 use Fcntl qw(:flock);  use Apache::lonlocal;
 use Apache::lonlocal;  use Apache::File();
 use Apache::File();  use HTML::Entities;
 use HTML::Entities;  use Digest::MD5;
     
 # ------------------------------------------------------------ Successful login  # ------------------------------------------------------------ Successful login
 sub success {  sub success {
     my ($r, $username, $domain, $authhost, $lowerurl, $extra_env,      my ($r, $username, $domain, $authhost, $lowerurl, $extra_env,
  $form) = @_;   $form,$skipcritical) = @_;
   
 # ------------------------------------------------------------ Get cookie ready  # ------------------------------------------------------------ Get cookie ready
     my $cookie =      my $cookie =
  &Apache::loncommon::init_user_environment($r, $username, $domain,   &Apache::loncommon::init_user_environment($r, $username, $domain,
   $authhost, $form,    $authhost, $form,
   {'extra_env' => $extra_env,});    {'extra_env' => $extra_env,});
   
     my $public=($username eq 'public' && $domain eq 'public');      my $public=($username eq 'public' && $domain eq 'public');
   
     if ($public or $lowerurl eq 'noredirect') { return $cookie; }      if ($public or $lowerurl eq 'noredirect') { return $cookie; }
   
 # -------------------------------------------------------------------- Log this  # -------------------------------------------------------------------- Log this
   
     &Apache::lonnet::log($domain,$username,$authhost,      &Apache::lonnet::log($domain,$username,$authhost,
                          "Login $ENV{'REMOTE_ADDR'}");                           "Login $ENV{'REMOTE_ADDR'}");
   
 # ------------------------------------------------- Check for critical messages  # ------------------------------------------------- Check for critical messages
   
     my @what=&Apache::lonnet::dump('critical',$domain,$username);      unless ($skipcritical) {
     if ($what[0]) {          my @what=&Apache::lonnet::dump('critical',$domain,$username);
  if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {          if ($what[0]) {
     $lowerurl='/adm/email?critical=display';      if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
         }          $lowerurl='/adm/email?critical=display';
     }              }
           }
 # ------------------------------------------------------------ Get cookie ready      }
     $cookie="lonID=$cookie; path=/";  
 # -------------------------------------------------------- Menu script and info  # ----------------------------------------------------------- Get cookies ready
     my $destination = $lowerurl;      my ($securecookie,$defaultcookie);
       if ($ENV{'SERVER_PORT'} == 443) {
     if (defined($form->{role})) {          $securecookie="lonID=$cookie; path=/; HttpOnly; secure";
         my $envkey = 'user.role.'.$form->{role};          my $lonidsdir=$r->dir_config('lonIDsDir');
         my $now=time;          if (($lonidsdir) && (-e "$lonidsdir/$cookie.id")) {
         my $then=$env{'user.login.time'};              my $linkname=substr(Digest::MD5::md5_hex(Digest::MD5::md5_hex(time(). {}. rand(). $$)), 0, 32).'_linked';
         my $refresh=$env{'user.refresh.time'};              if (-e "$lonidsdir/$linkname.id") {
         my $update=$env{'user.update.time'};                  unlink("$lonidsdir/$linkname.id");
         if (!$update) {              }
             $update = $then;              my $made_symlink = eval { symlink("$lonidsdir/$cookie.id",
         }                                                "$lonidsdir/$linkname.id"); 1 };
         if (exists($env{$envkey})) {              if ($made_symlink) {
             my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus);                  $defaultcookie = "lonLinkID=$linkname; path=/; HttpOnly;";
             &Apache::lonnet::role_status($envkey,$update,$refresh,$now,\$role,\$where,                  &Apache::lonnet::appenv({'user.linkedenv' => "$lonidsdir/$linkname.id"});
                                          \$trolecode,\$tstatus,\$tstart,\$tend);              }
             if ($tstatus eq 'is') {          }
                 $destination  .= ($destination =~ /\?/) ? '&' : '?';      } else {
                 my $newrole = &HTML::Entities::encode($form->{role},'"<>&');          $defaultcookie = "lonID=$cookie; path=/; HttpOnly;";
                 $destination .= 'selectrole=1&'.$newrole.'=1';      }
             }  # -------------------------------------------------------- Menu script and info
         }      my $destination = $lowerurl;
     }      if ($env{'request.lti.login'}) {
     if (defined($form->{symb})) {          if (($env{'request.lti.reqcrs'}) && ($env{'request.lti.reqrole'} eq 'cc')) {
         my $destsymb = $form->{symb};              &Apache::loncommon::content_type($r,'text/html');
         $destination  .= ($destination =~ /\?/) ? '&' : '?';              if ($securecookie) {
         if ($destsymb =~ /___/) {                  $r->headers_out->add('Set-cookie' => $securecookie);
             # FIXME Need to deal with encrypted symbs and urls as needed.              }
             my ($map,$resid,$desturl)=split(/___/,$destsymb);              if ($defaultcookie) {
             unless ($desturl=~/^(adm|editupload|public)/) {                  $r->headers_out->add('Set-cookie' => $defaultcookie);
                 $desturl = &Apache::lonnet::clutter($desturl);              }
             }              $r->send_http_header;
             $desturl = &HTML::Entities::encode($desturl,'"<>&');              &Apache::ltiauth::lti_reqcrs($r,$domain,$form,$username,$domain);
             $destsymb = &HTML::Entities::encode($destsymb,'"<>&');              return;
             $destination .= 'destinationurl='.$desturl.          }
                             '&destsymb='.$destsymb;          if ($env{'request.lti.selfenrollrole'}) {
         } else {              if (&Apache::ltiauth::lti_enroll($username,$domain,
             $destsymb = &HTML::Entities::encode($destsymb,'"<>&');                                               $env{'request.lti.selfenrollrole'}) eq 'ok') {
             $destination .= 'destinationurl='.$destsymb;                  $form->{'role'} = $env{'request.lti.selfenrollrole'};
         }                  &Apache::lonnet::delenv('request.lti.selfenrollrole');
     }              } else {
     if ($destination =~ m{^/adm/roles}) {                  &Apache::ltiauth::invalid_request($r,24);
         $destination  .= ($destination =~ /\?/) ? '&' : '?';              }
         $destination .= 'source=login';          }
     }      }
       if (defined($form->{role})) {
     my $windowinfo = Apache::lonhtmlcommon::scripttag('self.name="loncapaclient";');          my $envkey = 'user.role.'.$form->{role};
     my $header = '<meta HTTP-EQUIV="Refresh" CONTENT="0; url='.$destination.'" />';          my $now=time;
     my $brcrum = [{'href' => '',          my $then=$env{'user.login.time'};
                    'text' => 'Successful Login'},];          my $refresh=$env{'user.refresh.time'};
     my $start_page=&Apache::loncommon::start_page('Successful Login',          my $update=$env{'user.update.time'};
                                                   $header,          if (!$update) {
                                                   {'bread_crumbs' => $brcrum,});              $update = $then;
     my $end_page  =&Apache::loncommon::end_page();          }
           if (exists($env{$envkey})) {
  my $continuelink='<a href="'.$destination.'">'.&mt('Continue').'</a>';              my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus);
 # ------------------------------------------------- Output for successful login              &Apache::lonnet::role_status($envkey,$update,$refresh,$now,\$role,\$where,
                                            \$trolecode,\$tstatus,\$tstart,\$tend);
     &Apache::loncommon::content_type($r,'text/html');              if ($tstatus eq 'is') {
     $r->header_out('Set-cookie' => $cookie);                  $destination  .= ($destination =~ /\?/) ? '&' : '?';
     $r->send_http_header;                  my $newrole = &HTML::Entities::encode($form->{role},'"<>&');
                   $destination .= 'selectrole=1&'.$newrole.'=1';
     my %lt=&Apache::lonlocal::texthash(              }
        'wel' => 'Welcome',          }
        'pro' => 'Login problems?',      }
        );      if (defined($form->{symb})) {
     my $loginhelp = &loginhelpdisplay($domain);          my $destsymb = $form->{symb};
     if ($loginhelp) {          $destination  .= ($destination =~ /\?/) ? '&' : '?';
         $loginhelp = '<p><a href="'.$loginhelp.'">'.$lt{'pro'}.'</a></p>';          if ($destsymb =~ /___/) {
     }              # FIXME Need to deal with encrypted symbs and urls as needed.
               my ($map,$resid,$desturl)=split(/___/,$destsymb);
     my $welcome = &mt('Welcome to the Learning[_1]Online[_2] Network with CAPA. Please wait while your session is being set up.','<i>','</i>');               $desturl = &Apache::lonnet::clutter($desturl);
     $r->print(<<ENDSUCCESS);              $desturl = &HTML::Entities::encode($desturl,'"<>&');
 $start_page              $destsymb = &HTML::Entities::encode($destsymb,'"<>&');
 $windowinfo              $destination .= 'destinationurl='.$desturl.
 <h1>$lt{'wel'}</h1>                              '&destsymb='.$destsymb;
 $welcome          } else {
 $loginhelp              $destsymb = &HTML::Entities::encode($destsymb,'"<>&');
 $continuelink              $destination .= 'destinationurl='.$destsymb;
 $end_page          }
 ENDSUCCESS      }
 }      if ($destination =~ m{^/adm/roles}) {
           $destination  .= ($destination =~ /\?/) ? '&' : '?';
 # --------------------------------------------------------------- Failed login!          $destination .= 'source=login';
       }
 sub failed {  
     my ($r,$message,$form) = @_;      my $windowname = 'loncapaclient';
     (undef,undef,undef,my $clientmathml,my $clientunicode) =      if ($env{'request.lti.login'}) {
         &Apache::loncommon::decode_user_agent();          $windowname .= 'lti';
     my $args = {};      }
     if ($clientunicode && !$clientmathml) {      my $windowinfo = Apache::lonhtmlcommon::scripttag('self.name="'.$windowname.'";');
         $args = {'browser.unicode' => 1};      my $header = '<meta HTTP-EQUIV="Refresh" CONTENT="0; url='.$destination.'" />';
     }      my $brcrum = [{'href' => '',
                      'text' => 'Successful Login'},];
     my $start_page = &Apache::loncommon::start_page('Unsuccessful Login',undef,$args);      my $args = {'bread_crumbs' => $brcrum,};
     my $uname = &Apache::loncommon::cleanup_html($form->{'uname'});      unless ((defined($form->{role})) || (defined($form->{symb}))) {
     my $udom = &Apache::loncommon::cleanup_html($form->{'udom'});          my $update=$env{'user.update.time'};
     if (&Apache::lonnet::domain($udom,'description') eq '') {          if (!$update) {
         undef($udom);              $update = $env{'user.login.time'};
     }          }
     my $retry = '/adm/login';          my %roles_in_env;
     if ($uname eq $form->{'uname'}) {          my $showcount = &Apache::lonroles::roles_from_env(\%roles_in_env,$update);
         $retry .= '?username='.$uname;          if ($showcount == 1) {
     }              foreach my $rolecode (keys(%roles_in_env)) {
     if ($udom) {                  my ($cid) = ($rolecode =~ m{^\Quser.role.st./\E($match_domain/$match_courseid)(?:/|$)});
         $retry .= (($retry=~/\?/)?'&amp;':'?').'domain='.$udom;                  if ($cid) {
     }                      my %coursedescription =
     if (exists($form->{role})) {                          &Apache::lonnet::coursedescription($cid,{'one_time' => '1'});
         my $role = &Apache::loncommon::cleanup_html($form->{role});                      if ($coursedescription{'type'} eq 'Placement') {
         if ($role ne '') {                          $args->{'crstype'} = 'Placement';
             $retry .= (($retry=~/\?/)?'&amp;':'?').'role='.$role;                      }
         }                      last;
     }                  }
     if (exists($form->{symb})) {              }
         my $symb = &Apache::loncommon::cleanup_html($form->{symb});          }
         if ($symb ne '') {      }
             $retry .= (($retry=~/\?/)?'&amp;':'?').'symb='.$symb;  
         }  # ------------------------------------------------- Output for successful login
     }  
     my $end_page = &Apache::loncommon::end_page();      &Apache::loncommon::content_type($r,'text/html');
     &Apache::loncommon::content_type($r,'text/html');      if ($securecookie) {
     $r->send_http_header;          $r->headers_out->add('Set-cookie' => $securecookie);
     my @actions =      }
          (&mt('Please [_1]log in again[_2].','<a href="'.$retry.'">','</a>'));      if ($defaultcookie) {
     my $loginhelp = &loginhelpdisplay($udom);          $r->headers_out->add('Set-cookie' => $defaultcookie);
     if ($loginhelp) {      }
         push(@actions, '<a href="'.$loginhelp.'">'.&mt('Login problems?').'</a>');      $r->send_http_header;
     }  
     #FIXME: link to helpdesk might be added here      my $start_page;
       if ($env{'request.lti.login'}) {
     $r->print(          $args = {'only_body' => 1,};
        $start_page          $start_page=&Apache::loncommon::start_page('',$header,$args);
       .'<h2>'.&mt('Sorry ...').'</h2>'      } else {
       .&Apache::lonhtmlcommon::confirm_success(&mt($message),1).'<br /><br />'          $start_page=&Apache::loncommon::start_page('Successful Login',
       .&Apache::lonhtmlcommon::actionbox(\@actions)                                                     $header,$args);
       .$end_page      }
     );      my $end_page  =&Apache::loncommon::end_page();
  }  
       my $continuelink='<a href="'.$destination.'">'.&mt('Continue').'</a>';
 # ------------------------------------------------------------------ Rerouting!  
       my $pagebody;
 sub reroute {      unless ($env{'request.lti.login'}) {
     my ($r) = @_;          my %lt=&Apache::lonlocal::texthash(
     &Apache::loncommon::content_type($r,'text/html');             'wel' => 'Welcome',
     $r->send_http_header;             'pro' => 'Login problems?',
     my $msg='<b>'.&mt('Sorry ...').'</b><br />'            );
            .&mt('Please [_1]log in again[_2].');          $pagebody = "<h1>$lt{'wel'}</h1>\n".
     &Apache::loncommon::simple_error_page($r,'Rerouting',$msg,{'no_auto_mt_msg' => 1});                      &mt('Welcome to the Learning[_1]Online[_2] Network with CAPA. Please wait while your session is being set up.','<i>','</i>');
 }          my $loginhelp = &loginhelpdisplay($domain);
           if ($loginhelp) {
 # ---------------------------------------------------------------- Main handler              $pagebody .= '<p><a href="'.$loginhelp.'">'.$lt{'pro'}.'</a></p>';
           }
 sub handler {      }
     my $r = shift;      $r->print(<<ENDSUCCESS);
     my $londocroot = $r->dir_config('lonDocRoot');  $start_page
     my $form;  $windowinfo
 # Are we re-routing?  $pagebody
     if (-e "$londocroot/lon-status/reroute.txt") {  $continuelink
  &reroute($r);  $end_page
  return OK;  ENDSUCCESS
     }      return;
   }
     &Apache::lonlocal::get_language_handle($r);  
   # --------------------------------------------------------------- Failed login!
 # -------------------------------- Prevent users from attempting to login twice  
     my $handle = &Apache::lonnet::check_for_valid_session($r);  sub failed {
     if ($handle ne '') {      my ($r,$message,$form) = @_;
         my $lonidsdir=$r->dir_config('lonIDsDir');      (undef,undef,undef,my $clientmathml,my $clientunicode) =
         if ($handle=~/^publicuser\_/) {          &Apache::loncommon::decode_user_agent();
 # For "public user" - remove it, we apparently really want to login      my $args = {};
             unlink($r->dir_config('lonIDsDir')."/$handle.id");      if ($clientunicode && !$clientmathml) {
         } else {          $args = {'browser.unicode' => 1};
 # Indeed, a valid token is found      }
             &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle);  
     &Apache::loncommon::content_type($r,'text/html');      my $start_page = &Apache::loncommon::start_page('Unsuccessful Login',undef,$args);
     $r->send_http_header;      my $uname = &Apache::loncommon::cleanup_html($form->{'uname'});
     my $start_page =       my $udom = &Apache::loncommon::cleanup_html($form->{'udom'});
         &Apache::loncommon::start_page('Already logged in');      if (&Apache::lonnet::domain($udom,'description') eq '') {
     my $end_page =           undef($udom);
         &Apache::loncommon::end_page();      }
             my $dest = '/adm/roles';      my $retry = '/adm/login';
             if ($env{'form.firsturl'} ne '') {      if ($uname eq $form->{'uname'}) {
                 $dest = $env{'form.firsturl'};          $retry .= '?username='.$uname;
             }      }
             $r->print(      if ($udom) {
                $start_page          $retry .= (($retry=~/\?/)?'&amp;':'?').'domain='.$udom;
               .'<p class="LC_warning">'.&mt('You are already logged in!').'</p>'      }
               .'<p>'.&mt('Please either [_1]continue the current session[_2] or [_3]log out[_4].'      if (exists($form->{role})) {
                     ,'<a href="'.$dest.'">','</a>','<a href="/adm/logout">','</a>')          my $role = &Apache::loncommon::cleanup_html($form->{role});
               .'</p>'          if ($role ne '') {
               .$end_page              $retry .= (($retry=~/\?/)?'&amp;':'?').'role='.$role;
             );          }
             return OK;      }
         }      if (exists($form->{symb})) {
     }          my $symb = &Apache::loncommon::cleanup_html($form->{symb});
           if ($symb ne '') {
 # ---------------------------------------------------- No valid token, continue              $retry .= (($retry=~/\?/)?'&amp;':'?').'symb='.$symb;
           }
       }
     my $buffer;      my $end_page = &Apache::loncommon::end_page();
     if ($r->header_in('Content-length') > 0) {      &Apache::loncommon::content_type($r,'text/html');
  $r->read($buffer,$r->header_in('Content-length'),0);      $r->send_http_header;
     }      my @actions =
     my %form;           (&mt('Please [_1]log in again[_2].','<a href="'.$retry.'">','</a>'));
     foreach my $pair (split(/&/,$buffer)) {      my $loginhelp = &loginhelpdisplay($udom);
        my ($name,$value) = split(/=/,$pair);      if ($loginhelp) {
        $value =~ tr/+/ /;          push(@actions, '<a href="'.$loginhelp.'">'.&mt('Login problems?').'</a>');
        $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;      }
        $form{$name}=$value;      #FIXME: link to helpdesk might be added here
     }  
       $r->print(
     if ((!$form{'uname'}) || (!$form{'upass0'}) || (!$form{'udom'})) {         $start_page
  &failed($r,'Username, password and domain need to be specified.',        .'<h2>'.&mt('Sorry ...').'</h2>'
  \%form);        .&Apache::lonhtmlcommon::confirm_success(&mt($message),1).'<br /><br />'
         return OK;        .&Apache::lonhtmlcommon::actionbox(\@actions)
     }        .$end_page
       );
 # split user logging in and "su"-user   }
   
     ($form{'uname'},$form{'suname'})=split(/\:/,$form{'uname'});  # ------------------------------------------------------------------ Rerouting!
     $form{'uname'} = &LONCAPA::clean_username($form{'uname'});  
     $form{'suname'}= &LONCAPA::clean_username($form{'suname'});  sub reroute {
     $form{'udom'}  = &LONCAPA::clean_domain(  $form{'udom'});      my ($r) = @_;
       &Apache::loncommon::content_type($r,'text/html');
     my $role   = $r->dir_config('lonRole');      $r->send_http_header;
     my $domain = $r->dir_config('lonDefDomain');      my $msg='<b>'.&mt('Sorry ...').'</b><br />'
     my $prodir = $r->dir_config('lonUsersDir');             .&mt('Please [_1]log in again[_2].');
     my $contact_name = &mt('LON-CAPA helpdesk');      &Apache::loncommon::simple_error_page($r,'Rerouting',$msg,{'no_auto_mt_msg' => 1});
   }
 # ---------------------------------------- Get the information from login token  
   # ---------------------------------------------------------------- Main handler
     my $tmpinfo=Apache::lonnet::reply('tmpget:'.$form{'logtoken'},  
                                       $form{'serverid'});  sub handler {
       my $r = shift;
     my %sessiondata;      my $londocroot = $r->dir_config('lonDocRoot');
     if ($form{'iptoken'}) {  # Are we re-routing?
         %sessiondata = &Apache::lonnet::tmpget($form{'iptoken'});      if (-e "$londocroot/lon-status/reroute.txt") {
         my $delete = &Apache::lonnet::tmpdel($form{'iptoken'});   &reroute($r);
     }   return OK;
       }
     if (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost') ||   
         ($tmpinfo eq 'no_such_host')) {      &Apache::lonlocal::get_language_handle($r);
  &failed($r,'Information needed to verify your login information is missing, inaccessible or expired.',\%form);  
         return OK;  # -------------------------------- Prevent users from attempting to login twice
     } else {      my $handle = &Apache::lonnet::check_for_valid_session($r);
  my $reply = &Apache::lonnet::reply('tmpdel:'.$form{'logtoken'},      if ($handle ne '') {
    $form{'serverid'});          my $lonidsdir=$r->dir_config('lonIDsDir');
         if ( $reply ne 'ok' ) {          if ($handle=~/^publicuser\_/) {
             &failed($r,'Session could not be opened.',\%form);  # For "public user" - remove it, we apparently really want to login
     &Apache::lonnet::logthis("ERROR got a reply of $reply when trying to contact ". $form{'serverid'}." to get login token");              unlink($r->dir_config('lonIDsDir')."/$handle.id");
     return OK;          } else {
  }  # Indeed, a valid token is found
     }              &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle);
       &Apache::loncommon::content_type($r,'text/html');
     if (!&Apache::lonnet::domain($form{'udom'})) {      $r->send_http_header;
         &failed($r,'The domain you provided is not a valid LON-CAPA domain.',\%form);      my $start_page =
         return OK;          &Apache::loncommon::start_page('Already logged in');
     }      my $end_page =
           &Apache::loncommon::end_page();
     my ($key,$firsturl,$rolestr,$symbstr)=split(/&/,$tmpinfo);              my $dest = '/adm/roles';
     if ($rolestr) {              if ($env{'form.firsturl'} ne '') {
         $rolestr = &unescape($rolestr);                  $dest = $env{'form.firsturl'};
     }              }
     if ($symbstr) {              $r->print(
         $symbstr= &unescape($symbstr);                 $start_page
     }                .'<p class="LC_warning">'.&mt('You are already logged in!').'</p>'
     if ($rolestr =~ /^role=/) {                .'<p>'.&mt('Please either [_1]continue the current session[_2] or [_3]log out[_4].'
         (undef,$form{'role'}) = split('=',$rolestr);                      ,'<a href="'.$dest.'">','</a>','<a href="/adm/logout">','</a>')
     }                .'</p>'
     if ($symbstr =~ /^symb=/) {                 .$end_page
         (undef,$form{'symb'}) = split('=',$symbstr);              );
     }              return OK;
           }
     my $keybin=pack("H16",$key);      }
   
     my $cipher;  # ---------------------------------------------------- No valid token, continue
     if ($Crypt::DES::VERSION>=2.03) {  
  $cipher=new Crypt::DES $keybin;  
     }      my $buffer;
     else {      if ($r->header_in('Content-length') > 0) {
  $cipher=new DES $keybin;   $r->read($buffer,$r->header_in('Content-length'),0);
     }      }
     my $upass='';      my %form;
     for (my $i=0;$i<=2;$i++) {      foreach my $pair (split(/&/,$buffer)) {
  my $chunk=         my ($name,$value) = split(/=/,$pair);
     $cipher->decrypt(unpack("a8",pack("H16",substr($form{'upass'.$i},0,16))));         $value =~ tr/+/ /;
          $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
  $chunk.=         $form{$name}=$value;
     $cipher->decrypt(unpack("a8",pack("H16",substr($form{'upass'.$i},16,16))));      }
   
  $chunk=substr($chunk,1,ord(substr($chunk,0,1)));      if ((!$form{'uname'}) || (!$form{'upass0'}) || (!$form{'udom'})) {
  $upass.=$chunk;   &failed($r,'Username, password and domain need to be specified.',
     }   \%form);
           return OK;
 # ---------------------------------------------------------------- Authenticate      }
   
     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$form{'udom'});  # split user logging in and "su"-user
     my ($cancreate,$statustocreate) =  
         &Apache::createaccount::get_creation_controls($form{'udom'},$domconfig{'usercreation'});      ($form{'uname'},$form{'suname'},$form{'sudom'})=split(/\:/,$form{'uname'});
     my $defaultauth;      $form{'uname'} = &LONCAPA::clean_username($form{'uname'});
     if (ref($cancreate) eq 'ARRAY') {      $form{'suname'}= &LONCAPA::clean_username($form{'suname'});
         if (grep(/^login$/,@{$cancreate})) {      $form{'udom'}  = &LONCAPA::clean_domain($form{'udom'});
             $defaultauth = 1;      $form{'sudom'} = &LONCAPA::clean_domain($form{'sudom'});
         }  
     }      my $role   = $r->dir_config('lonRole');
     my $clientcancheckhost = 1;      my $domain = $r->dir_config('lonDefDomain');
     my $authhost=Apache::lonnet::authenticate($form{'uname'},$upass,      my $prodir = $r->dir_config('lonUsersDir');
                                               $form{'udom'},$defaultauth,      my $contact_name = &mt('LON-CAPA helpdesk');
                                               $clientcancheckhost);  
       # ---------------------------------------- Get the information from login token
 # --------------------------------------------------------------------- Failed?  
       my $tmpinfo=Apache::lonnet::reply('tmpget:'.$form{'logtoken'},
     if ($authhost eq 'no_host') {                                        $form{'serverid'});
  &failed($r,'Username and/or password could not be authenticated.',  
  \%form);      if (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost') ||
         return OK;          ($tmpinfo eq 'no_such_host')) {
     } elsif ($authhost eq 'no_account_on_host') {   &failed($r,'Information needed to verify your login information is missing, inaccessible or expired.',\%form);
         if ($defaultauth) {          return OK;
             my $domdesc = &Apache::lonnet::domain($form{'udom'},'description');      } else {
             unless (&check_can_host($r,\%form,'no_account_on_host',$domdesc)) {   my $reply = &Apache::lonnet::reply('tmpdel:'.$form{'logtoken'},
                 return OK;     $form{'serverid'});
             }          if ( $reply ne 'ok' ) {
             my $start_page =               &failed($r,'Session could not be opened.',\%form);
                 &Apache::loncommon::start_page('Create a user account in LON-CAPA');      &Apache::lonnet::logthis("ERROR got a reply of $reply when trying to contact ". $form{'serverid'}." to get login token");
             my $lonhost = $r->dir_config('lonHostID');      return OK;
             my $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};   }
             my $contacts =       }
                 &Apache::loncommon::build_recipient_list(undef,'helpdeskmail',  
                                                         $form{'udom'},$origmail);      if (!&Apache::lonnet::domain($form{'udom'})) {
             my ($contact_email) = split(',',$contacts);           &failed($r,'The domain you provided is not a valid LON-CAPA domain.',\%form);
             my $output =           return OK;
                 &Apache::createaccount::username_check($form{'uname'},$form{'udom'},      }
                                                        $domdesc,'',$lonhost,  
                                                        $contact_email,$contact_name,      my ($key,$firsturl,$rolestr,$symbstr,$iptokenstr)=split(/&/,$tmpinfo);
                                                        undef,$statustocreate);      if ($rolestr) {
             &Apache::loncommon::content_type($r,'text/html');          $rolestr = &unescape($rolestr);
             $r->send_http_header;      }
             &Apache::createaccount::print_header($r,$start_page);      if ($symbstr) {
             $r->print('<h3>'.&mt('Account creation').'</h3>'.          $symbstr= &unescape($symbstr);
                       &mt('Although your username and password were authenticated, you do not currently have a LON-CAPA account at this institution.').'<br />'.      }
                       $output.&Apache::loncommon::end_page());      if ($iptokenstr) {
             return OK;          $iptokenstr = &unescape($iptokenstr);
         } else {      }
             &failed($r,'Although your username and password were authenticated, you do not currently have a LON-CAPA account in this domain, and you are not permitted to create one.',\%form);      if ($rolestr =~ /^role=/) {
             return OK;          (undef,$form{'role'}) = split('=',$rolestr);
         }      }
     }      if ($symbstr =~ /^symb=/) {
           (undef,$form{'symb'}) = split('=',$symbstr);
     if (($firsturl eq '') ||       }
  ($firsturl=~/^\/adm\/(logout|remote)/)) {      if ($iptokenstr =~ /^iptoken=/) {
  $firsturl='/adm/roles';          (undef,$form{'iptoken'}) = split('=',$iptokenstr);
     }      }
   
     my $hosthere;      my $upass = $ENV{HTTPS} ? $form{'upass0'}
     if ($form{'iptoken'}) {          : &Apache::loncommon::des_decrypt($key,$form{'upass0'});
         if (($sessiondata{'domain'} eq $form{'udom'}) &&  
             ($sessiondata{'username'} eq $form{'uname'})) {  # ---------------------------------------------------------------- Authenticate
             $hosthere = 1;  
         }      my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$form{'udom'});
     }      my ($cancreate,$statustocreate) =
           &Apache::createaccount::get_creation_controls($form{'udom'},$domconfig{'usercreation'});
 # --------------------------------- Are we attempting to login as somebody else?      my $defaultauth;
     if ($form{'suname'}) {      if (ref($cancreate) eq 'ARRAY') {
 # ------------ see if the original user has enough privileges to pull this stunt          if (grep(/^login$/,@{$cancreate})) {
  if (&Apache::lonnet::privileged($form{'uname'},$form{'udom'})) {              $defaultauth = 1;
 # ---------------------------------------------------- see if the su-user exists          }
     unless (&Apache::lonnet::homeserver($form{'suname'},$form{'udom'})      }
  eq 'no_host') {      my $clientcancheckhost = 1;
  &Apache::lonnet::logthis(&Apache::lonnet::homeserver($form{'suname'},$form{'udom'}));      my $authhost=Apache::lonnet::authenticate($form{'uname'},$upass,
 # ------------------------------ see if the su-user is not too highly privileged                                                $form{'udom'},$defaultauth,
  unless (&Apache::lonnet::privileged($form{'suname'},$form{'udom'})) {                                                $clientcancheckhost);
 # -------------------------------------------------------- actually switch users  
     &Apache::lonnet::logperm('User '.$form{'uname'}.' at '.$form{'udom'}.  # --------------------------------------------------------------------- Failed?
  ' logging in as '.$form{'suname'});  
     $form{'uname'}=$form{'suname'};      if ($authhost eq 'no_host') {
  } else {   &failed($r,'Username and/or password could not be authenticated.',
     &Apache::lonnet::logthis('Attempted switch user to privileged user');   \%form);
  }          return OK;
     }      } elsif ($authhost eq 'no_account_on_host') {
  } else {          if ($defaultauth) {
     &Apache::lonnet::logthis('Non-privileged user attempting switch user');              my $domdesc = &Apache::lonnet::domain($form{'udom'},'description');
  }              unless (&check_can_host($r,\%form,'no_account_on_host',$domdesc)) {
     }                  return OK;
               }
     my ($is_balancer,$otherserver);              my $start_page =
                   &Apache::loncommon::start_page('Create a user account in LON-CAPA');
     unless ($hosthere) {              my $lonhost = $r->dir_config('lonHostID');
         ($is_balancer,$otherserver) =              my $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};
             &Apache::lonnet::check_loadbalancing($form{'uname'},$form{'udom'});              my $contacts =
     }                  &Apache::loncommon::build_recipient_list(undef,'helpdeskmail',
                                                           $form{'udom'},$origmail);
     if ($is_balancer) {              my ($contact_email) = split(',',$contacts);
         if (!$otherserver) {               my $output =
             ($otherserver) = &Apache::lonnet::choose_server($form{'udom'});                  &Apache::createaccount::username_check($form{'uname'},$form{'udom'},
         }                                                         $domdesc,'',$lonhost,
         if ($otherserver) {                                                         $contact_email,$contact_name,
             &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,                                                         undef,$statustocreate);
                      \%form);              &Apache::loncommon::content_type($r,'text/html');
             my $switchto = '/adm/switchserver?otherserver='.$otherserver;              $r->send_http_header;
             if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {              &Apache::createaccount::print_header($r,$start_page);
                 $switchto .= '&origurl='.$firsturl;              $r->print('<h3>'.&mt('Account creation').'</h3>'.
             }                        &mt('Although your username and password were authenticated, you do not currently have a LON-CAPA account at this institution.').'<br />'.
             if ($form{'role'}) {                        $output.&Apache::loncommon::end_page());
                 $switchto .= '&role='.$form{'role'};              return OK;
             }          } else {
             if ($form{'symb'}) {              &failed($r,'Although your username and password were authenticated, you do not currently have a LON-CAPA account in this domain, and you are not permitted to create one.',\%form);
                 $switchto .= '&symb='.$form{'symb'};              return OK;
             }          }
             $r->internal_redirect($switchto);      }
         } else {  
             $r->print(&noswitch());      if (($firsturl eq '') ||
         }   ($firsturl=~/^\/adm\/(logout|remote)/)) {
         return OK;   $firsturl='/adm/roles';
     } else {      }
         if (!&check_can_host($r,\%form,$authhost)) {  
             my ($otherserver) = &Apache::lonnet::choose_server($form{'udom'});      my $hosthere;
             if ($otherserver) {      if ($form{'iptoken'}) {
                 &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,          my %sessiondata = &Apache::lonnet::tmpget($form{'iptoken'});
                          \%form);          my $delete = &Apache::lonnet::tmpdel($form{'iptoken'});
                 my $switchto = '/adm/switchserver?otherserver='.$otherserver;          if (($sessiondata{'domain'} eq $form{'udom'}) &&
                 if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {              ($sessiondata{'username'} eq $form{'uname'})) {
                     $switchto .= '&origurl='.$firsturl;              $hosthere = 1;
                 }          }
                 if ($form{'role'}) {      }
                     $switchto .= '&role='.$form{'role'};  
                 }  # --------------------------------- Are we attempting to login as somebody else?
                 if ($form{'symb'}) {      if ($form{'suname'}) {
                     $switchto .= '&symb='.$form{'symb'};          my ($suname,$sudom,$sudomref);
                 }          $suname = $form{'suname'};
                 $r->internal_redirect($switchto);          $sudom = $form{'udom'};
             } else {          if ($form{'sudom'}) {
                 $r->print(&noswitch());              unless ($sudom eq $form{'sudom'}) {
             }                  if (&Apache::lonnet::domain($form{'sudom'})) {
             return OK;                      $sudomref = [$form{'sudom'}];
         }                      $sudom = $form{'sudom'};
                   }
 # ------------------------------------------------------- Do the load balancing              }
           }
 # ---------------------------------------------------------- Determine own load  # ------------ see if the original user has enough privileges to pull this stunt
         my $loadlim = $r->dir_config('lonLoadLim');   if (&Apache::lonnet::privileged($form{'uname'},$form{'udom'},$sudomref)) {
         my $loadavg;  # ---------------------------------------------------- see if the su-user exists
         {      unless (&Apache::lonnet::homeserver($suname,$sudom) eq 'no_host') {
             my $loadfile=Apache::File->new('/proc/loadavg');  # ------------------------------ see if the su-user is not too highly privileged
             $loadavg=<$loadfile>;   if (&Apache::lonnet::privileged($suname,$sudom)) {
         }                      &Apache::lonnet::logthis('Attempted switch user to privileged user');
         $loadavg =~ s/\s.*//g;                  } else {
         my $loadpercent=sprintf("%.1f",100*$loadavg/$loadlim);                      my $noprivswitch;
         my $userloadpercent=&Apache::lonnet::userload();  #
   # su-user's home server and user's home server must have one of:
 # ---------------------------------------------------------- Are we overloaded?  # (a) same domain
         if ((($userloadpercent>100.0)||($loadpercent>100.0))) {  # (b) same primary library server for the two domains
             my $unloaded=Apache::lonnet::spareserver($loadpercent,$userloadpercent,1,$form{'udom'});  # (c) same "internet domain" for primary library server(s) for home servers' domains
             if (!$unloaded) {  #
                 ($unloaded) = &Apache::lonnet::choose_server($form{'udom'});                      my $suprim = &Apache::lonnet::domain($sudom,'primary');
             }                      my $suintdom = &Apache::lonnet::internet_dom($suprim);
             if ($unloaded) {                      unless ($sudom eq $form{'udom'}) {
                 &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',                          my $uprim = &Apache::lonnet::domain($form{'udom'},'primary');
                          undef,\%form);                          my $uintdom = &Apache::lonnet::internet_dom($uprim);
                 $r->internal_redirect('/adm/switchserver?otherserver='.$unloaded.'&origurl='.$firsturl);                          unless ($suprim eq $uprim) {
                 return OK;                              unless ($suintdom eq $uintdom) {
             }                                  &Apache::lonnet::logthis('Attempted switch user '
         }                                     .'to user with different "internet domain".');                        
         &success($r,$form{'uname'},$form{'udom'},$authhost,$firsturl,undef,                                  $noprivswitch = 1;
                  \%form);                              }
         return OK;                          }
     }                      }
 }  
                       unless ($noprivswitch) {
 sub check_can_host {  #
     my ($r,$form,$authhost,$domdesc) = @_;  # server where log-in occurs must have same "internet domain" as su-user's home
     return unless (ref($form) eq 'HASH');  # server
     my $canhost = 1;  #
     my $lonhost = $r->dir_config('lonHostID');                          my $lonhost = $r->dir_config('lonHostID');
     my $udom = $form->{'udom'};                          my $hostintdom = &Apache::lonnet::internet_dom($lonhost);
     my @intdoms;                          if ($hostintdom ne $suintdom) {
     my $internet_names = &Apache::lonnet::get_internet_names($lonhost);                              &Apache::lonnet::logthis('Attempted switch user on a '
     if (ref($internet_names) eq 'ARRAY') {                                  .'server with a different "internet domain".');
         @intdoms = @{$internet_names};                          } else {
     }  
     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');  # -------------------------------------------------------- actually switch users
     my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);  
     unless ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {              &Apache::lonnet::logperm('User '.$form{'uname'}.' at '.
         my $machine_dom = &Apache::lonnet::host_domain($lonhost);                                $form{'udom'}.' logging in as '.$suname.':'.$sudom);
         my $hostname = &Apache::lonnet::hostname($lonhost);              $form{'uname'}=$suname;
         my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);                              if ($form{'udom'} ne $sudom) {
         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);                                  $form{'udom'}=$sudom;
         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);                              }
         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);                          }
         my $loncaparev;                      }
         if ($authhost eq 'no_account_on_host') {   }
             $loncaparev = &Apache::lonnet::get_server_loncaparev($machine_dom);      }
         } else {   } else {
             $loncaparev = &Apache::lonnet::get_server_loncaparev($machine_dom,$lonhost);      &Apache::lonnet::logthis('Non-privileged user attempting switch user');
         }   }
         $canhost = &Apache::lonnet::can_host_session($udom,$lonhost,$loncaparev,      }
                                                      $udomdefaults{'remotesessions'},  
                                                      $defdomdefaults{'hostedsessions'});      my ($is_balancer,$otherserver);
     }  
     unless ($canhost) {      unless ($hosthere) {
         if ($authhost eq 'no_account_on_host') {          ($is_balancer,$otherserver) =
             my $checkloginvia = 1;              &Apache::lonnet::check_loadbalancing($form{'uname'},$form{'udom'},'login');
             my ($login_host,$hostname) =           if ($is_balancer) {
                 &Apache::lonnet::choose_server($udom,$checkloginvia);              if ($otherserver eq '') {
             &Apache::loncommon::content_type($r,'text/html');                  my $lowest_load;
             $r->send_http_header;                  ($otherserver,undef,undef,undef,$lowest_load) = &Apache::lonnet::choose_server($form{'udom'});
             if ($login_host ne '') {                  if ($lowest_load > 100) {
                 my $protocol = $Apache::lonnet::protocol{$login_host};                      $otherserver = &Apache::lonnet::spareserver($lowest_load,$lowest_load,1,$form{'udom'});
                 $protocol = 'http' if ($protocol ne 'https');                  }
                 my $newurl = $protocol.'://'.$hostname.'/adm/createaccount';              }
                 $r->print(&Apache::loncommon::start_page('Create a user account in LON-CAPA').              if ($otherserver ne '') {
                           '<h3>'.&mt('Account creation').'</h3>'.                  my @hosts = &Apache::lonnet::current_machine_ids();
                           &mt('You do not currently have a LON-CAPA account at this institution.').'<br />'.                  if (grep(/^\Q$otherserver\E$/,@hosts)) {
                           '<p>'.&mt('You will be able to create one by logging into a LON-CAPA server within the [_1] domain.',$domdesc).'</p>'.                      $hosthere = $otherserver;
                           '<p>'.&mt('[_1]Log in[_2]','<a href="'.$newurl.'">','</a>').                  }
                           &Apache::loncommon::end_page());              }
             } else {          }
                 $r->print(&Apache::loncommon::start_page('Access to LON-CAPA unavailable').      }
                           '<h3>'.&mt('Account creation unavailable').'</h3>'.  
                           &mt('You do not currently have a LON-CAPA account at this institution.').'<br />'.      if (($is_balancer) && (!$hosthere)) {
                           '<p>'.&mt('Currently a LON-CAPA server is not available within the [_1] domain for you to log-in to, to create an account.',$domdesc).'</p>'.          if ($otherserver) {
                           &Apache::loncommon::end_page());              &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,
             }                       \%form);
         } else {              my $switchto = '/adm/switchserver?otherserver='.$otherserver;
             &success($r,$form->{'uname'},$udom,$authhost,'noredirect',undef,              if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {
                      $form);                  $switchto .= '&origurl='.$firsturl;
             my ($otherserver) = &Apache::lonnet::choose_server($udom);              }
             $r->internal_redirect('/adm/switchserver?otherserver='.$otherserver);              if ($form{'role'}) {
         }                  $switchto .= '&role='.$form{'role'};
     }              }
     return $canhost;              if ($form{'symb'}) {
 }                  $switchto .= '&symb='.$form{'symb'};
               }
 sub noswitch {              $r->internal_redirect($switchto);
     my $result = &Apache::loncommon::start_page('Access to LON-CAPA unavailable').          } else {
                  '<h3>'.&mt('Session unavailable').'</h3>'.              $r->print(&noswitch());
                  &mt('This LON-CAPA server is unable to host your session.').'<br />'.          }
                  '<p>'.&mt('Currently no other LON-CAPA server is available to host your session either.').'</p>'.          return OK;
                  &Apache::loncommon::end_page();      } else {
     return $result;          if (!&check_can_host($r,\%form,$authhost)) {
 }              my ($otherserver) = &Apache::lonnet::choose_server($form{'udom'});
               if ($otherserver) {
 sub loginhelpdisplay {                  &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,
     my ($authdomain) = @_;                           \%form);
     my $login_help = 1;                  my $switchto = '/adm/switchserver?otherserver='.$otherserver;
     my $lang = &Apache::lonlocal::current_language();                  if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {
     if ($login_help) {                      $switchto .= '&origurl='.$firsturl;
         my $dom = $authdomain;                  }
         if ($dom eq '') {                  if ($form{'role'}) {
             $dom = &Apache::lonnet::default_login_domain();                      $switchto .= '&role='.$form{'role'};
         }                  }
         my %domconfhash = &Apache::loncommon::get_domainconf($dom);                  if ($form{'symb'}) {
         my $loginhelp_url;                      $switchto .= '&symb='.$form{'symb'};
         if ($lang) {                  }
             $loginhelp_url = $domconfhash{$dom.'.login.helpurl_'.$lang};                  $r->internal_redirect($switchto);
             if ($loginhelp_url ne '') {              } else {
                 return $loginhelp_url;                  $r->print(&noswitch());
             }              }
         }              return OK;
         $loginhelp_url = $domconfhash{$dom.'.login.helpurl_nolang'};          }
         if ($loginhelp_url ne '') {  
             return $loginhelp_url;  # ------------------------------------------------------- Do the load balancing
         } else {  
             return '/adm/loginproblems.html';  # ---------------------------------------------------------- Determine own load
         }          my $loadlim = $r->dir_config('lonLoadLim');
     }          my $loadavg;
     return;          {
 }              my $loadfile=Apache::File->new('/proc/loadavg');
               $loadavg=<$loadfile>;
 1;          }
 __END__          $loadavg =~ s/\s.*//g;
           my $loadpercent=sprintf("%.1f",100*$loadavg/$loadlim);
           my $userloadpercent=&Apache::lonnet::userload();
   
   # ---------------------------------------------------------- Are we overloaded?
           if ((($userloadpercent>100.0)||($loadpercent>100.0))) {
               my $unloaded=Apache::lonnet::spareserver($loadpercent,$userloadpercent,1,$form{'udom'});
               if (!$unloaded) {
                   ($unloaded) = &Apache::lonnet::choose_server($form{'udom'});
               }
               if ($unloaded) {
                   &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',
                            undef,\%form);
                   $r->internal_redirect('/adm/switchserver?otherserver='.$unloaded.'&origurl='.$firsturl);
                   return OK;
               }
           }
           if (($is_balancer) && ($hosthere)) {
               $form{'noloadbalance'} = $hosthere;
           }
           &success($r,$form{'uname'},$form{'udom'},$authhost,$firsturl,undef,
                    \%form);
           return OK;
       }
   }
   
   sub check_can_host {
       my ($r,$form,$authhost,$domdesc) = @_;
       return unless (ref($form) eq 'HASH');
       my $canhost = 1;
       my $lonhost = $r->dir_config('lonHostID');
       my $udom = $form->{'udom'};
       my @intdoms;
       my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
       if (ref($internet_names) eq 'ARRAY') {
           @intdoms = @{$internet_names};
       }
       my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
       my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
       unless ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
           my $machine_dom = &Apache::lonnet::host_domain($lonhost);
           my $hostname = &Apache::lonnet::hostname($lonhost);
           my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
           my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
           my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
           my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
           my $loncaparev;
           if ($authhost eq 'no_account_on_host') {
               $loncaparev = &Apache::lonnet::get_server_loncaparev($machine_dom);
           } else {
               $loncaparev = &Apache::lonnet::get_server_loncaparev($machine_dom,$lonhost);
           }
           $canhost = &Apache::lonnet::can_host_session($udom,$lonhost,$loncaparev,
                                                        $udomdefaults{'remotesessions'},
                                                        $defdomdefaults{'hostedsessions'});
       }
       unless ($canhost) {
           if ($authhost eq 'no_account_on_host') {
               my $checkloginvia = 1;
               my ($login_host,$hostname) =
                   &Apache::lonnet::choose_server($udom,$checkloginvia);
               &Apache::loncommon::content_type($r,'text/html');
               $r->send_http_header;
               if ($login_host ne '') {
                   my $protocol = $Apache::lonnet::protocol{$login_host};
                   $protocol = 'http' if ($protocol ne 'https');
                   my $newurl = $protocol.'://'.$hostname.'/adm/createaccount';
                   $r->print(&Apache::loncommon::start_page('Create a user account in LON-CAPA').
                             '<h3>'.&mt('Account creation').'</h3>'.
                             &mt('You do not currently have a LON-CAPA account at this institution.').'<br />'.
                             '<p>'.&mt('You will be able to create one by logging into a LON-CAPA server within the [_1] domain.',$domdesc).'</p>'.
                             '<p>'.&mt('[_1]Log in[_2]','<a href="'.$newurl.'">','</a>').
                             &Apache::loncommon::end_page());
               } else {
                   $r->print(&Apache::loncommon::start_page('Access to LON-CAPA unavailable').
                             '<h3>'.&mt('Account creation unavailable').'</h3>'.
                             &mt('You do not currently have a LON-CAPA account at this institution.').'<br />'.
                             '<p>'.&mt('Currently a LON-CAPA server is not available within the [_1] domain for you to log-in to, to create an account.',$domdesc).'</p>'.
                             &Apache::loncommon::end_page());
               }
           } else {
               &success($r,$form->{'uname'},$udom,$authhost,'noredirect',undef,
                        $form);
               my ($otherserver) = &Apache::lonnet::choose_server($udom);
               $r->internal_redirect('/adm/switchserver?otherserver='.$otherserver);
           }
       }
       return $canhost;
   }
   
   sub noswitch {
       my $result = &Apache::loncommon::start_page('Access to LON-CAPA unavailable').
                    '<h3>'.&mt('Session unavailable').'</h3>'.
                    &mt('This LON-CAPA server is unable to host your session.').'<br />'.
                    '<p>'.&mt('Currently no other LON-CAPA server is available to host your session either.').'</p>'.
                    &Apache::loncommon::end_page();
       return $result;
   }
   
   sub loginhelpdisplay {
       my ($authdomain) = @_;
       my $login_help = 1;
       my $lang = &Apache::lonlocal::current_language();
       if ($login_help) {
           my $dom = $authdomain;
           if ($dom eq '') {
               $dom = &Apache::lonnet::default_login_domain();
           }
           my %domconfhash = &Apache::loncommon::get_domainconf($dom);
           my $loginhelp_url;
           if ($lang) {
               $loginhelp_url = $domconfhash{$dom.'.login.helpurl_'.$lang};
               if ($loginhelp_url ne '') {
                   return $loginhelp_url;
               }
           }
           $loginhelp_url = $domconfhash{$dom.'.login.helpurl_nolang'};
           if ($loginhelp_url ne '') {
               return $loginhelp_url;
           } else {
               return '/adm/loginproblems.html';
           }
       }
       return;
   }
   
   1;
   __END__
   
   

Removed from v.1.133  
changed lines
  Added in v.1.151


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