Diff for /loncom/auth/lonauth.pm between versions 1.121.2.20 and 1.153

version 1.121.2.20, 2020/10/23 21:21:44 version 1.153, 2018/07/01 00:03:42
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 Apache::loncommon();  use Apache::loncommon();
 use Apache::lonnet;  use Apache::lonnet;
 use Apache::lonmenu();  use Apache::lonmenu();
 use Apache::createaccount;  use Apache::createaccount;
 use Fcntl qw(:flock);  use Apache::ltiauth;
 use Apache::lonlocal;  use Fcntl qw(:flock);
 use Apache::File();  use Apache::lonlocal;
 use HTML::Entities;  use Apache::File();
 use Digest::MD5;  use HTML::Entities;
    use Digest::MD5;
 # ------------------------------------------------------------ Successful login   
 sub success {  # ------------------------------------------------------------ Successful login
     my ($r, $username, $domain, $authhost, $lowerurl, $extra_env,  sub success {
  $form,$cid) = @_;      my ($r, $username, $domain, $authhost, $lowerurl, $extra_env,
    $form,$skipcritical) = @_;
 # ------------------------------------------------------------ Get cookie ready  
     my $cookie =  # ------------------------------------------------------------ Get cookie ready
  &Apache::loncommon::init_user_environment($r, $username, $domain,      my $cookie =
   $authhost, $form,   &Apache::loncommon::init_user_environment($r, $username, $domain,
   {'extra_env' => $extra_env,});    $authhost, $form,
     {'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,  
                          "Login $ENV{'REMOTE_ADDR'}");      &Apache::lonnet::log($domain,$username,$authhost,
                            "Login $ENV{'REMOTE_ADDR'}");
 # ------------------------------------------------- Check for critical messages  
   # ------------------------------------------------- Check for critical messages
     my @what=&Apache::lonnet::dump('critical',$domain,$username);  
     if ($what[0]) {      unless ($skipcritical) {
  if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {          my @what=&Apache::lonnet::dump('critical',$domain,$username);
     $lowerurl='/adm/email?critical=display';          if ($what[0]) {
         }      if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
     }          $lowerurl='/adm/email?critical=display';
               }
 # ------------------------------------------------------------ Get cookies ready          }
     my ($securecookie,$defaultcookie);      }
     my $ssl = $r->subprocess_env('https');  
     if ($ssl) {  # ----------------------------------------------------------- Get cookies ready
         $securecookie="lonSID=$cookie; path=/; HttpOnly; secure";      my ($securecookie,$defaultcookie);
         my $lonidsdir=$r->dir_config('lonIDsDir');      if ($ENV{'SERVER_PORT'} == 443) {
         if (($lonidsdir) && (-e "$lonidsdir/$cookie.id")) {          $securecookie="lonID=$cookie; path=/; HttpOnly; secure";
             my $linkname=substr(Digest::MD5::md5_hex(Digest::MD5::md5_hex(time(). {}. rand(). $$)), 0, 32).'_linked';          my $lonidsdir=$r->dir_config('lonIDsDir');
             if (-e "$lonidsdir/$linkname.id") {          if (($lonidsdir) && (-e "$lonidsdir/$cookie.id")) {
                 unlink("$lonidsdir/$linkname.id");              my $linkname=substr(Digest::MD5::md5_hex(Digest::MD5::md5_hex(time(). {}. rand(). $$)), 0, 32).'_linked';
             }              if (-e "$lonidsdir/$linkname.id") {
             my $made_symlink = eval { symlink("$lonidsdir/$cookie.id",                  unlink("$lonidsdir/$linkname.id");
                                               "$lonidsdir/$linkname.id"); 1 };              }
             if ($made_symlink) {              my $made_symlink = eval { symlink("$lonidsdir/$cookie.id",
                 $defaultcookie = "lonLinkID=$linkname; path=/; HttpOnly;";                                                "$lonidsdir/$linkname.id"); 1 };
                 &Apache::lonnet::appenv({'user.linkedenv' => $linkname});              if ($made_symlink) {
             }                  $defaultcookie = "lonLinkID=$linkname; path=/; HttpOnly;";
         }                  &Apache::lonnet::appenv({'user.linkedenv' => "$lonidsdir/$linkname.id"});
     } else {              }
         $defaultcookie = "lonID=$cookie; path=/; HttpOnly;";          }
     }      } else {
 # -------------------------------------------------------- Menu script and info          $defaultcookie = "lonID=$cookie; path=/; HttpOnly;";
     my $destination = $lowerurl;      }
   # -------------------------------------------------------- Menu script and info
     if (defined($form->{role})) {      my $destination = $lowerurl;
         my $envkey = 'user.role.'.$form->{role};      if ($env{'request.lti.login'}) {
         my $now=time;          if (($env{'request.lti.reqcrs'}) && ($env{'request.lti.reqrole'} eq 'cc')) {
         my $then=$env{'user.login.time'};              &Apache::loncommon::content_type($r,'text/html');
         my $refresh=$env{'user.refresh.time'};              if ($securecookie) {
         my $update=$env{'user.update.time'};                  $r->headers_out->add('Set-cookie' => $securecookie);
         if (!$update) {              }
             $update = $then;              if ($defaultcookie) {
         }                  $r->headers_out->add('Set-cookie' => $defaultcookie);
         if (exists($env{$envkey})) {              }
             my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus);              $r->send_http_header;
             &Apache::lonnet::role_status($envkey,$update,$refresh,$now,\$role,\$where,              if (ref($form) eq 'HASH') {
                                          \$trolecode,\$tstatus,\$tstart,\$tend);                  $form->{'lti.reqcrs'} = $env{'request.lti.reqcrs'};
             if ($tstatus eq 'is') {                  $form->{'lti.reqrole'} = $env{'request.lti.reqrole'};
                 $destination  .= ($destination =~ /\?/) ? '&' : '?';                  $form->{'lti.sourcecrs'} = $env{'request.lti.sourcecrs'};
                 my $newrole = &HTML::Entities::encode($form->{role},'"<>&');              }
                 $destination .= 'selectrole=1&'.$newrole.'=1';              &Apache::ltiauth::lti_reqcrs($r,$domain,$form,$username,$domain);
             }              return;
         }          }
     }          if ($env{'request.lti.selfenrollrole'}) {
     if (defined($form->{symb})) {              if (&Apache::ltiauth::lti_enroll($username,$domain,
         my $destsymb = $form->{symb};                                               $env{'request.lti.selfenrollrole'}) eq 'ok') {
         my $encrypted;                  $form->{'role'} = $env{'request.lti.selfenrollrole'};
         if ($destsymb =~ m{^/enc/}) {                  &Apache::lonnet::delenv('request.lti.selfenrollrole');
             $encrypted = 1;              } else {
             if ($cid) {                  &Apache::ltiauth::invalid_request($r,24);
                 $destsymb = &Apache::lonenc::unencrypted($destsymb,$cid);              }
             }          }
         }      }
         $destination  .= ($destination =~ /\?/) ? '&' : '?';      if (defined($form->{role})) {
         if ($destsymb =~ /___/) {          my $envkey = 'user.role.'.$form->{role};
             my ($map,$resid,$desturl)=split(/___/,$destsymb);          my $now=time;
             $desturl = &Apache::lonnet::clutter($desturl);          my $then=$env{'user.login.time'};
             if ($encrypted) {          my $refresh=$env{'user.refresh.time'};
                 $desturl = &Apache::lonenc::encrypted($desturl,1,$cid);          my $update=$env{'user.update.time'};
                 $destsymb = $form->{symb};          if (!$update) {
             }              $update = $then;
             $desturl = &HTML::Entities::encode($desturl,'"<>&');          }
             $destsymb = &HTML::Entities::encode($destsymb,'"<>&');          if (exists($env{$envkey})) {
             $destination .= 'destinationurl='.$desturl.              my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus);
                             '&destsymb='.$destsymb;              &Apache::lonnet::role_status($envkey,$update,$refresh,$now,\$role,\$where,
         } elsif (!$encrypted) {                                           \$trolecode,\$tstatus,\$tstart,\$tend);
             $destsymb = &HTML::Entities::encode($destsymb,'"<>&');              if ($tstatus eq 'is') {
             $destination .= 'destinationurl='.$destsymb;                  $destination  .= ($destination =~ /\?/) ? '&' : '?';
         }                  my $newrole = &HTML::Entities::encode($form->{role},'"<>&');
     }                  $destination .= 'selectrole=1&'.$newrole.'=1';
     if ($destination =~ m{^/adm/roles}) {              }
         $destination  .= ($destination =~ /\?/) ? '&' : '?';          }
         $destination .= 'source=login';      }
     }      if (defined($form->{symb})) {
           my $destsymb = $form->{symb};
     my $windowinfo=&Apache::lonmenu::open($env{'browser.os'});          $destination  .= ($destination =~ /\?/) ? '&' : '?';
     my $startupremote=&Apache::lonmenu::startupremote($destination);          if ($destsymb =~ /___/) {
     my $remoteinfo=&Apache::lonmenu::load_remote_msg($lowerurl);              # FIXME Need to deal with encrypted symbs and urls as needed.
     my $setflags=&Apache::lonmenu::setflags();              my ($map,$resid,$desturl)=split(/___/,$destsymb);
     my $maincall=&Apache::lonmenu::maincall();              $desturl = &Apache::lonnet::clutter($desturl);
     my $brcrum = [{'href' => '',              $desturl = &HTML::Entities::encode($desturl,'"<>&');
                    'text' => 'Successful Login'},];              $destsymb = &HTML::Entities::encode($destsymb,'"<>&');
     my $start_page=&Apache::loncommon::start_page('Successful Login',              $destination .= 'destinationurl='.$desturl.
                                                   $startupremote,                              '&destsymb='.$destsymb;
                                                   {'no_inline_link' => 1,          } else {
                                                    'bread_crumbs' => $brcrum,});              $destsymb = &HTML::Entities::encode($destsymb,'"<>&');
     my $end_page  =&Apache::loncommon::end_page();              $destination .= 'destinationurl='.$destsymb;
           }
     my $continuelink;      }
     if ($env{'environment.remote'} eq 'off') {      if ($destination =~ m{^/adm/roles}) {
  $continuelink='<a href="'.$destination.'">'.&mt('Continue').'</a>';          $destination  .= ($destination =~ /\?/) ? '&' : '?';
     }          $destination .= 'source=login';
 # ------------------------------------------------- Output for successful login      }
   
     &Apache::loncommon::content_type($r,'text/html');      my $windowname = 'loncapaclient';
     if ($securecookie) {      if ($env{'request.lti.login'}) {
         $r->headers_out->add('Set-cookie' => $securecookie);          $windowname .= 'lti';
     }      }
     if ($defaultcookie) {      my $windowinfo = Apache::lonhtmlcommon::scripttag('self.name="'.$windowname.'";');
         $r->headers_out->add('Set-cookie' => $defaultcookie);      my $brcrum = [{'href' => '',
     }                     'text' => 'Successful Login'},];
     $r->send_http_header;      my $args = {'bread_crumbs' => $brcrum,};
       unless ((defined($form->{role})) || (defined($form->{symb}))) {
     my %lt=&Apache::lonlocal::texthash(          my $update=$env{'user.update.time'};
        'wel' => 'Welcome',          if (!$update) {
        'pro' => 'Login problems?',              $update = $env{'user.login.time'};
        );          }
     my $loginhelp = &loginhelpdisplay($domain);          my %roles_in_env;
     if ($loginhelp) {          my $showcount = &Apache::lonroles::roles_from_env(\%roles_in_env,$update);
         $loginhelp = '<p><a href="'.$loginhelp.'">'.$lt{'pro'}.'</a></p>';          if ($showcount == 1) {
     }              foreach my $rolecode (keys(%roles_in_env)) {
                   my ($cid) = ($rolecode =~ m{^\Quser.role.st./\E($match_domain/$match_courseid)(?:/|$)});
     my $welcome = &mt('Welcome to the Learning[_1]Online[_2] Network with CAPA. Please wait while your session is being set up.','<i>','</i>');                   if ($cid) {
     $r->print(<<ENDSUCCESS);                      my %coursedescription =
 $start_page                          &Apache::lonnet::coursedescription($cid,{'one_time' => '1'});
 $setflags                      if ($coursedescription{'type'} eq 'Placement') {
 $windowinfo                          $args->{'crstype'} = 'Placement';
 <h1>$lt{'wel'}</h1>                      }
 $welcome                      last;
 $loginhelp                  }
 $remoteinfo              }
 $maincall          }
 $continuelink      }
 $end_page  
 ENDSUCCESS  # ------------------------------------------------- Output for successful login
     return;  
 }      &Apache::loncommon::content_type($r,'text/html');
       if ($securecookie) {
 # --------------------------------------------------------------- Failed login!          $r->headers_out->add('Set-cookie' => $securecookie);
       }
 sub failed {      if ($defaultcookie) {
     my ($r,$message,$form) = @_;          $r->headers_out->add('Set-cookie' => $defaultcookie);
     (undef,undef,undef,my $clientmathml,my $clientunicode) =      }
         &Apache::loncommon::decode_user_agent();      $r->send_http_header;
     my $args = {};  
     if ($clientunicode && !$clientmathml) {      my ($start_page,$js,$pagebody,$end_page);
         $args = {'browser.unicode' => 1};      if ($env{'request.lti.login'}) {
     }          $args = {'only_body' => 1};
           if ($env{'request.lti.target'} eq '') {
     my $start_page = &Apache::loncommon::start_page('Unsuccessful Login',undef,$args);              my $ltitarget = (($destination =~ /\?/) ? '&' : '?').
     my $uname = &Apache::loncommon::cleanup_html($form->{'uname'});                              'ltitarget=iframe';
     my $udom = &Apache::loncommon::cleanup_html($form->{'udom'});              $js = <<"ENDJS";
     if (&Apache::lonnet::domain($udom,'description') eq '') {  
         undef($udom);  <script type="text/javascript">
     }  // <![CDATA[
     my $retry = '/adm/login';  function setLTItarget() {
     if ($uname eq $form->{'uname'}) {      var newloc = '$destination';
         $retry .= '?username='.$uname;      if (parent !== window) {
     }          newloc += '$ltitarget';
     if ($udom) {      }
         $retry .= (($retry=~/\?/)?'&amp;':'?').'domain='.$udom;      window.location.href=newloc;
     }  }
     if (exists($form->{role})) {  // ]]>
         my $role = &Apache::loncommon::cleanup_html($form->{role});  </script>
         if ($role ne '') {  
             $retry .= (($retry=~/\?/)?'&amp;':'?').'role='.$role;  ENDJS
         }              $args->{'add_entries'} = {'onload' => "javascript:setLTItarget();"};
     }              $pagebody =  '<noscript><span class="LC_warning">'
     if (exists($form->{symb})) {                          .&mt('Use of LON-CAPA requires Javascript to be enabled in your web browser.')
         my $symb = &Apache::loncommon::cleanup_html($form->{symb});                          .'</span></noscript>';
         if ($symb ne '') {          } else {
             $retry .= (($retry=~/\?/)?'&amp;':'?').'symb='.$symb;              $args->{'redirect'} = [0,$destination,1];
         }          }
     }          $start_page=&Apache::loncommon::start_page('',$js,$args);
     my $end_page = &Apache::loncommon::end_page();      } else {
     &Apache::loncommon::content_type($r,'text/html');          $args->{'redirect'} = [0,$destination];
     $r->send_http_header;          $start_page=&Apache::loncommon::start_page('Successful Login',
     my @actions =                                                     $js,$args);
          (&mt('Please [_1]log in again[_2].','<a href="'.$retry.'">','</a>'));  
     my $loginhelp = &loginhelpdisplay($udom);          my %lt=&Apache::lonlocal::texthash(
     if ($loginhelp) {             'wel' => 'Welcome',
         push(@actions, '<a href="'.$loginhelp.'">'.&mt('Login problems?').'</a>');             'pro' => 'Login problems?',
     }            );
     #FIXME: link to helpdesk might be added here          $pagebody = "<h1>$lt{'wel'}</h1>\n".
                       &mt('Welcome to the Learning[_1]Online[_2] Network with CAPA. Please wait while your session is being set up.','<i>','</i>');
     $r->print(          my $loginhelp = &loginhelpdisplay($domain);
        $start_page          if ($loginhelp) {
       .'<h2>'.&mt('Sorry ...').'</h2>'              $pagebody .= '<p><a href="'.$loginhelp.'">'.$lt{'pro'}.'</a></p>';
       .&Apache::lonhtmlcommon::confirm_success(&mt($message),1).'<br /><br />'          }
       .&Apache::lonhtmlcommon::actionbox(\@actions)      }
       .$end_page      $end_page = &Apache::loncommon::end_page();
     );      $r->print(<<ENDSUCCESS);
  }  $start_page
   $windowinfo
 # ------------------------------------------------------------------ Rerouting!  $pagebody
   $end_page
 sub reroute {  ENDSUCCESS
     my ($r) = @_;      return;
     &Apache::loncommon::content_type($r,'text/html');  }
     $r->send_http_header;  
     my $msg='<b>'.&mt('Sorry ...').'</b><br />'  # --------------------------------------------------------------- Failed login!
            .&mt('Please [_1]log in again[_2].');  
     &Apache::loncommon::simple_error_page($r,'Rerouting',$msg,{'no_auto_mt_msg' => 1});  sub failed {
 }      my ($r,$message,$form) = @_;
       (undef,undef,undef,my $clientmathml,my $clientunicode) =
 # ---------------------------------------------------------------- Main handler          &Apache::loncommon::decode_user_agent();
       my $args = {};
 sub handler {      if ($clientunicode && !$clientmathml) {
     my $r = shift;          $args = {'browser.unicode' => 1};
     my $londocroot = $r->dir_config('lonDocRoot');      }
 # Are we re-routing?  
     if (-e "$londocroot/lon-status/reroute.txt") {      my $start_page = &Apache::loncommon::start_page('Unsuccessful Login',undef,$args);
  &reroute($r);      my $uname = &Apache::loncommon::cleanup_html($form->{'uname'});
  return OK;      my $udom = &Apache::loncommon::cleanup_html($form->{'udom'});
     }      if (&Apache::lonnet::domain($udom,'description') eq '') {
           undef($udom);
     &Apache::lonlocal::get_language_handle($r);      }
       my $retry = '/adm/login';
 # -------------------------------- Prevent users from attempting to login twice      if ($uname eq $form->{'uname'}) {
     my $handle = &Apache::lonnet::check_for_valid_session($r);          $retry .= '?username='.$uname;
     if ($handle ne '') {      }
         my $lonidsdir=$r->dir_config('lonIDsDir');      if ($udom) {
         if ($handle=~/^publicuser\_/) {          $retry .= (($retry=~/\?/)?'&amp;':'?').'domain='.$udom;
 # For "public user" - remove it, we apparently really want to login      }
             unlink($r->dir_config('lonIDsDir')."/$handle.id");      if (exists($form->{role})) {
         } else {          my $role = &Apache::loncommon::cleanup_html($form->{role});
 # Indeed, a valid token is found          if ($role ne '') {
             &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle);              $retry .= (($retry=~/\?/)?'&amp;':'?').'role='.$role;
     &Apache::loncommon::content_type($r,'text/html');          }
     $r->send_http_header;      }
     my $start_page =       if (exists($form->{symb})) {
         &Apache::loncommon::start_page('Already logged in');          my $symb = &Apache::loncommon::cleanup_html($form->{symb});
     my $end_page =           if ($symb ne '') {
         &Apache::loncommon::end_page();              $retry .= (($retry=~/\?/)?'&amp;':'?').'symb='.$symb;
             my $dest = '/adm/roles';          }
             if ($env{'form.firsturl'} ne '') {      }
                 $dest = $env{'form.firsturl'};      my $end_page = &Apache::loncommon::end_page();
             }      &Apache::loncommon::content_type($r,'text/html');
             $r->print(      $r->send_http_header;
                $start_page      my @actions =
               .'<p class="LC_warning">'.&mt('You are already logged in!').'</p>'           (&mt('Please [_1]log in again[_2].','<a href="'.$retry.'">','</a>'));
               .'<p>'.&mt('Please either [_1]continue the current session[_2] or [_3]log out[_4].'      my $loginhelp = &loginhelpdisplay($udom);
                     ,'<a href="'.$dest.'">','</a>','<a href="/adm/logout">','</a>')      if ($loginhelp) {
               .'</p>'          push(@actions, '<a href="'.$loginhelp.'">'.&mt('Login problems?').'</a>');
               .$end_page      }
             );      #FIXME: link to helpdesk might be added here
             return OK;  
         }      $r->print(
     }         $start_page
         .'<h2>'.&mt('Sorry ...').'</h2>'
 # ---------------------------------------------------- No valid token, continue        .&Apache::lonhtmlcommon::confirm_success(&mt($message),1).'<br /><br />'
         .&Apache::lonhtmlcommon::actionbox(\@actions)
         .$end_page
     my $buffer;      );
     if ($r->header_in('Content-length') > 0) {   }
  $r->read($buffer,$r->header_in('Content-length'),0);  
     }  # ------------------------------------------------------------------ Rerouting!
     my %form;  
     foreach my $pair (split(/&/,$buffer)) {  sub reroute {
        my ($name,$value) = split(/=/,$pair);      my ($r) = @_;
        $value =~ tr/+/ /;      &Apache::loncommon::content_type($r,'text/html');
        $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;      $r->send_http_header;
        $form{$name}=$value;      my $msg='<b>'.&mt('Sorry ...').'</b><br />'
     }             .&mt('Please [_1]log in again[_2].');
       &Apache::loncommon::simple_error_page($r,'Rerouting',$msg,{'no_auto_mt_msg' => 1});
     if ((!$form{'uname'}) || (!$form{'upass0'}) || (!$form{'udom'})) {  }
  &failed($r,'Username, password and domain need to be specified.',  
  \%form);  # ---------------------------------------------------------------- Main handler
         return OK;  
     }  sub handler {
       my $r = shift;
 # split user logging in and "su"-user      my $londocroot = $r->dir_config('lonDocRoot');
   # Are we re-routing?
     ($form{'uname'},$form{'suname'},$form{'sudom'})=split(/\:/,$form{'uname'});      if (-e "$londocroot/lon-status/reroute.txt") {
     $form{'uname'} = &LONCAPA::clean_username($form{'uname'});   &reroute($r);
     $form{'suname'}= &LONCAPA::clean_username($form{'suname'});   return OK;
     $form{'udom'}  = &LONCAPA::clean_domain($form{'udom'});      }
     $form{'sudom'} = &LONCAPA::clean_domain($form{'sudom'});  
       &Apache::lonlocal::get_language_handle($r);
     my $role   = $r->dir_config('lonRole');  
     my $domain = $r->dir_config('lonDefDomain');  # -------------------------------- Prevent users from attempting to login twice
     my $prodir = $r->dir_config('lonUsersDir');      my $handle = &Apache::lonnet::check_for_valid_session($r);
     my $contact_name = &mt('LON-CAPA helpdesk');      if ($handle ne '') {
           my $lonidsdir=$r->dir_config('lonIDsDir');
 # ---------------------------------------- Get the information from login token          if ($handle=~/^publicuser\_/) {
   # For "public user" - remove it, we apparently really want to login
     my $tmpinfo=Apache::lonnet::reply('tmpget:'.$form{'logtoken'},              unlink($r->dir_config('lonIDsDir')."/$handle.id");
                                       $form{'serverid'});          } else {
   # Indeed, a valid token is found
     if (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost') ||               &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle);
         ($tmpinfo eq 'no_such_host')) {      &Apache::loncommon::content_type($r,'text/html');
  &failed($r,'Information needed to verify your login information is missing, inaccessible or expired.',\%form);      $r->send_http_header;
         return OK;      my $start_page =
     } else {          &Apache::loncommon::start_page('Already logged in');
  my $reply = &Apache::lonnet::reply('tmpdel:'.$form{'logtoken'},      my $end_page =
    $form{'serverid'});          &Apache::loncommon::end_page();
         if ( $reply ne 'ok' ) {              my $dest = '/adm/roles';
             &failed($r,'Session could not be opened.',\%form);              if ($env{'form.firsturl'} ne '') {
     &Apache::lonnet::logthis("ERROR got a reply of $reply when trying to contact ". $form{'serverid'}." to get login token");                  $dest = $env{'form.firsturl'};
     return OK;              }
  }              $r->print(
     }                 $start_page
                 .'<p class="LC_warning">'.&mt('You are already logged in!').'</p>'
     if (!&Apache::lonnet::domain($form{'udom'})) {                .'<p>'.&mt('Please either [_1]continue the current session[_2] or [_3]log out[_4].'
         &failed($r,'The domain you provided is not a valid LON-CAPA domain.',\%form);                      ,'<a href="'.$dest.'">','</a>','<a href="/adm/logout">','</a>')
         return OK;                .'</p>'
     }                .$end_page
               );
     my ($key,$firsturl,$rolestr,$symbstr,$iptokenstr)=split(/&/,$tmpinfo);              return OK;
     if ($rolestr) {          }
         $rolestr = &unescape($rolestr);      }
     }  
     if ($symbstr) {  # ---------------------------------------------------- No valid token, continue
         $symbstr= &unescape($symbstr);  
     }  
     if ($iptokenstr) {      my $buffer;
         $iptokenstr = &unescape($iptokenstr);      if ($r->header_in('Content-length') > 0) {
     }   $r->read($buffer,$r->header_in('Content-length'),0);
     if ($rolestr =~ /^role=/) {      }
         (undef,$form{'role'}) = split('=',$rolestr);      my %form;
     }      foreach my $pair (split(/&/,$buffer)) {
     if ($symbstr =~ /^symb=/) {          my ($name,$value) = split(/=/,$pair);
         (undef,$form{'symb'}) = split('=',$symbstr);         $value =~ tr/+/ /;
     }         $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
     if ($iptokenstr =~ /^iptoken=/) {         $form{$name}=$value;
         (undef,$form{'iptoken'}) = split('=',$iptokenstr);      }
     }  
       if ((!$form{'uname'}) || (!$form{'upass0'}) || (!$form{'udom'})) {
     my $upass = &Apache::loncommon::des_decrypt($key,$form{'upass0'});   &failed($r,'Username, password and domain need to be specified.',
    \%form);
 # ---------------------------------------------------------------- Authenticate          return OK;
       }
     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$form{'udom'});  
     my ($cancreate,$statustocreate) =  # split user logging in and "su"-user
         &Apache::createaccount::get_creation_controls($form{'udom'},$domconfig{'usercreation'});  
     my $defaultauth;      ($form{'uname'},$form{'suname'},$form{'sudom'})=split(/\:/,$form{'uname'});
     if (ref($cancreate) eq 'ARRAY') {      $form{'uname'} = &LONCAPA::clean_username($form{'uname'});
         if (grep(/^login$/,@{$cancreate})) {      $form{'suname'}= &LONCAPA::clean_username($form{'suname'});
             $defaultauth = 1;      $form{'udom'}  = &LONCAPA::clean_domain($form{'udom'});
         }      $form{'sudom'} = &LONCAPA::clean_domain($form{'sudom'});
     }  
     my $clientcancheckhost = 1;      my $role   = $r->dir_config('lonRole');
     my $authhost=Apache::lonnet::authenticate($form{'uname'},$upass,      my $domain = $r->dir_config('lonDefDomain');
                                               $form{'udom'},$defaultauth,      my $prodir = $r->dir_config('lonUsersDir');
                                               $clientcancheckhost);      my $contact_name = &mt('LON-CAPA helpdesk');
       
 # --------------------------------------------------------------------- Failed?  # ---------------------------------------- Get the information from login token
   
     if ($authhost eq 'no_host') {      my $tmpinfo=Apache::lonnet::reply('tmpget:'.$form{'logtoken'},
  &failed($r,'Username and/or password could not be authenticated.',                                        $form{'serverid'});
  \%form);  
         return OK;      if (($tmpinfo=~/^error/) || ($tmpinfo eq 'con_lost') ||
     } elsif ($authhost eq 'no_account_on_host') {          ($tmpinfo eq 'no_such_host')) {
         if ($defaultauth) {   &failed($r,'Information needed to verify your login information is missing, inaccessible or expired.',\%form);
             my $domdesc = &Apache::lonnet::domain($form{'udom'},'description');          return OK;
             unless (&check_can_host($r,\%form,'no_account_on_host',$domdesc)) {      } else {
                 return OK;   my $reply = &Apache::lonnet::reply('tmpdel:'.$form{'logtoken'},
             }     $form{'serverid'});
             my $start_page =           if ( $reply ne 'ok' ) {
                 &Apache::loncommon::start_page('Create a user account in LON-CAPA',              &failed($r,'Session could not be opened.',\%form);
                                                '',{'no_inline_link'   => 1,});      &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'});
         my %sessiondata = &Apache::lonnet::tmpget($form{'iptoken'});  
         my $delete = &Apache::lonnet::tmpdel($form{'iptoken'});  # ---------------------------------------------------------------- Authenticate
         if (($sessiondata{'domain'} eq $form{'udom'}) &&  
             ($sessiondata{'username'} eq $form{'uname'})) {      my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$form{'udom'});
             $hosthere = 1;      my ($cancreate,$statustocreate) =
         }          &Apache::createaccount::get_creation_controls($form{'udom'},$domconfig{'usercreation'});
     }      my $defaultauth;
       if (ref($cancreate) eq 'ARRAY') {
 # --------------------------------- Are we attempting to login as somebody else?          if (grep(/^login$/,@{$cancreate})) {
     if ($form{'suname'}) {              $defaultauth = 1;
         my ($suname,$sudom,$sudomref);          }
         $suname = $form{'suname'};      }
         $sudom = $form{'udom'};      my $clientcancheckhost = 1;
         if ($form{'sudom'}) {      my $authhost=Apache::lonnet::authenticate($form{'uname'},$upass,
             unless ($sudom eq $form{'sudom'}) {                                                $form{'udom'},$defaultauth,
                 if (&Apache::lonnet::domain($form{'sudom'})) {                                                $clientcancheckhost);
                     $sudomref = [$form{'sudom'}];  
                     $sudom = $form{'sudom'};  # --------------------------------------------------------------------- Failed?
                 }  
             }      if ($authhost eq 'no_host') {
         }   &failed($r,'Username and/or password could not be authenticated.',
 # ------------ see if the original user has enough privileges to pull this stunt   \%form);
  if (&Apache::lonnet::privileged($form{'uname'},$form{'udom'},$sudomref)) {          return OK;
 # ---------------------------------------------------- see if the su-user exists      } elsif ($authhost eq 'no_account_on_host') {
     unless (&Apache::lonnet::homeserver($suname,$sudom) eq 'no_host') {          if ($defaultauth) {
 # ------------------------------ see if the su-user is not too highly privileged              my $domdesc = &Apache::lonnet::domain($form{'udom'},'description');
  if (&Apache::lonnet::privileged($suname,$sudom)) {              unless (&check_can_host($r,\%form,'no_account_on_host',$domdesc)) {
                     &Apache::lonnet::logthis('Attempted switch user to privileged user');                  return OK;
                 } else {              }
                     my $noprivswitch;              my $start_page =
 #                  &Apache::loncommon::start_page('Create a user account in LON-CAPA');
 # su-user's home server and user's home server must have one of:              my $lonhost = $r->dir_config('lonHostID');
 # (a) same domain              my $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};
 # (b) same primary library server for the two domains              my $contacts =
 # (c) same "internet domain" for primary library server(s) for home servers' domains                  &Apache::loncommon::build_recipient_list(undef,'helpdeskmail',
 #                                                          $form{'udom'},$origmail);
                     my $suprim = &Apache::lonnet::domain($sudom,'primary');              my ($contact_email) = split(',',$contacts);
                     my $suintdom = &Apache::lonnet::internet_dom($suprim);              my $output =
                     unless ($sudom eq $form{'udom'}) {                  &Apache::createaccount::username_check($form{'uname'},$form{'udom'},
                         my $uprim = &Apache::lonnet::domain($form{'udom'},'primary');                                                         $domdesc,'',$lonhost,
                         my $uintdom = &Apache::lonnet::internet_dom($uprim);                                                         $contact_email,$contact_name,
                         unless ($suprim eq $uprim) {                                                         undef,$statustocreate);
                             unless ($suintdom eq $uintdom) {              &Apache::loncommon::content_type($r,'text/html');
                                 &Apache::lonnet::logthis('Attempted switch user '              $r->send_http_header;
                                    .'to user with different "internet domain".');              &Apache::createaccount::print_header($r,$start_page);
                                 $noprivswitch = 1;              $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 />'.
                         }                        $output.&Apache::loncommon::end_page());
                     }              return OK;
           } else {
                     unless ($noprivswitch) {              &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);
 #              return OK;
 # server where log-in occurs must have same "internet domain" as su-user's home          }
 # server      }
 #  
                         my $lonhost = $r->dir_config('lonHostID');      if (($firsturl eq '') ||
                         my $hostintdom = &Apache::lonnet::internet_dom($lonhost);   ($firsturl=~/^\/adm\/(logout|remote)/)) {
                         if ($hostintdom ne $suintdom) {   $firsturl='/adm/roles';
                             &Apache::lonnet::logthis('Attempted switch user on a '      }
                                 .'server with a different "internet domain".');  
                         } else {      my $hosthere;
       if ($form{'iptoken'}) {
 # -------------------------------------------------------- actually switch users          my %sessiondata = &Apache::lonnet::tmpget($form{'iptoken'});
           my $delete = &Apache::lonnet::tmpdel($form{'iptoken'});
     &Apache::lonnet::logperm('User '.$form{'uname'}.' at '.          if (($sessiondata{'domain'} eq $form{'udom'}) &&
  $form{'udom'}.' logging in as '.$suname.':'.$sudom);              ($sessiondata{'username'} eq $form{'uname'})) {
     $form{'uname'}=$suname;              $hosthere = 1;
                             if ($form{'udom'} ne $sudom) {          }
                                 $form{'udom'}=$sudom;      }
                             }  
                         }  # --------------------------------- Are we attempting to login as somebody else?
                     }      if ($form{'suname'}) {
  }          my ($suname,$sudom,$sudomref);
     }          $suname = $form{'suname'};
  } else {          $sudom = $form{'udom'};
     &Apache::lonnet::logthis('Non-privileged user attempting switch user');          if ($form{'sudom'}) {
  }              unless ($sudom eq $form{'sudom'}) {
     }                  if (&Apache::lonnet::domain($form{'sudom'})) {
                       $sudomref = [$form{'sudom'}];
     my ($is_balancer,$otherserver);                      $sudom = $form{'sudom'};
                   }
     unless ($hosthere) {              }
         ($is_balancer,$otherserver) =          }
             &Apache::lonnet::check_loadbalancing($form{'uname'},$form{'udom'},'login');  # ------------ see if the original user has enough privileges to pull this stunt
         if ($is_balancer) {   if (&Apache::lonnet::privileged($form{'uname'},$form{'udom'},$sudomref)) {
             # Check if browser sent a LON-CAPA load balancer cookie (and this is a balancer)  # ---------------------------------------------------- see if the su-user exists
             my ($found_server,$balancer_cookie) = &Apache::lonnet::check_for_balancer_cookie($r);      unless (&Apache::lonnet::homeserver($suname,$sudom) eq 'no_host') {
             if (($found_server) && ($balancer_cookie =~ /^\Q$env{'user.domain'}\E_\Q$env{'user.name'}\E_/)) {  # ------------------------------ see if the su-user is not too highly privileged
                 $otherserver = $found_server;   if (&Apache::lonnet::privileged($suname,$sudom)) {
             }                      &Apache::lonnet::logthis('Attempted switch user to privileged user');
             if ($otherserver eq '') {                  } else {
                 my $lowest_load;                      my $noprivswitch;
                 ($otherserver,undef,undef,undef,$lowest_load) = &Apache::lonnet::choose_server($form{'udom'});  #
                 if ($lowest_load > 100) {  # su-user's home server and user's home server must have one of:
                     $otherserver = &Apache::lonnet::spareserver($lowest_load,$lowest_load,1,$form{'udom'});  # (a) same domain
                 }  # (b) same primary library server for the two domains
             }  # (c) same "internet domain" for primary library server(s) for home servers' domains
             if ($otherserver ne '') {  #
                 my @hosts = &Apache::lonnet::current_machine_ids();                      my $suprim = &Apache::lonnet::domain($sudom,'primary');
                 if (grep(/^\Q$otherserver\E$/,@hosts)) {                      my $suintdom = &Apache::lonnet::internet_dom($suprim);
                     $hosthere = $otherserver;                      unless ($sudom eq $form{'udom'}) {
                 }                          my $uprim = &Apache::lonnet::domain($form{'udom'},'primary');
             }                          my $uintdom = &Apache::lonnet::internet_dom($uprim);
         }                          unless ($suprim eq $uprim) {
     }                              unless ($suintdom eq $uintdom) {
                                   &Apache::lonnet::logthis('Attempted switch user '
     if (($is_balancer) && (!$hosthere)) {                                     .'to user with different "internet domain".');                        
         if ($otherserver) {                                  $noprivswitch = 1;
             &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,                              }
                      \%form);                          }
             my $switchto = '/adm/switchserver?otherserver='.$otherserver;                      }
             if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {  
                 $switchto .= '&origurl='.$firsturl;                      unless ($noprivswitch) {
             }  #
             if ($form{'role'}) {  # server where log-in occurs must have same "internet domain" as su-user's home
                 $switchto .= '&role='.$form{'role'};  # server
             }  #
             if ($form{'symb'}) {                          my $lonhost = $r->dir_config('lonHostID');
                 $switchto .= '&symb='.$form{'symb'};                          my $hostintdom = &Apache::lonnet::internet_dom($lonhost);
             }                          if ($hostintdom ne $suintdom) {
             $r->internal_redirect($switchto);                              &Apache::lonnet::logthis('Attempted switch user on a '
         } else {                                  .'server with a different "internet domain".');
             &Apache::loncommon::content_type($r,'text/html');                          } else {
             $r->send_http_header;  
             $r->print(&noswitch());  # -------------------------------------------------------- actually switch users
         }  
         return OK;              &Apache::lonnet::logperm('User '.$form{'uname'}.' at '.
     } else {                                $form{'udom'}.' logging in as '.$suname.':'.$sudom);
         if (!&check_can_host($r,\%form,$authhost)) {              $form{'uname'}=$suname;
             my ($otherserver) = &Apache::lonnet::choose_server($form{'udom'});                              if ($form{'udom'} ne $sudom) {
             if ($otherserver) {                                  $form{'udom'}=$sudom;
                 &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,                              }
                          \%form);                          }
                 my $switchto = '/adm/switchserver?otherserver='.$otherserver;                      }
                 if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {   }
                     $switchto .= '&origurl='.$firsturl;      }
                 }   } else {
                 if ($form{'role'}) {      &Apache::lonnet::logthis('Non-privileged user attempting switch user');
                     $switchto .= '&role='.$form{'role'};   }
                 }      }
                 if ($form{'symb'}) {  
                     $switchto .= '&symb='.$form{'symb'};      my ($is_balancer,$otherserver);
                 }  
                 $r->internal_redirect($switchto);      unless ($hosthere) {
             } else {          ($is_balancer,$otherserver) =
                 &Apache::loncommon::content_type($r,'text/html');              &Apache::lonnet::check_loadbalancing($form{'uname'},$form{'udom'},'login');
                 $r->send_http_header;          if ($is_balancer) {
                 $r->print(&noswitch());              if ($otherserver eq '') {
             }                  my $lowest_load;
             return OK;                  ($otherserver,undef,undef,undef,$lowest_load) = &Apache::lonnet::choose_server($form{'udom'});
         }                  if ($lowest_load > 100) {
                       $otherserver = &Apache::lonnet::spareserver($lowest_load,$lowest_load,1,$form{'udom'});
 # ------------------------------------------------------- Do the load balancing                  }
               }
 # ---------------------------------------------------------- Determine own load              if ($otherserver ne '') {
         my $loadlim = $r->dir_config('lonLoadLim');                  my @hosts = &Apache::lonnet::current_machine_ids();
         my $loadavg;                  if (grep(/^\Q$otherserver\E$/,@hosts)) {
         {                      $hosthere = $otherserver;
             my $loadfile=Apache::File->new('/proc/loadavg');                  }
             $loadavg=<$loadfile>;              }
         }          }
         $loadavg =~ s/\s.*//g;      }
         my $loadpercent=sprintf("%.1f",100*$loadavg/$loadlim);  
         my $userloadpercent=&Apache::lonnet::userload();      if (($is_balancer) && (!$hosthere)) {
           if ($otherserver) {
 # ---------------------------------------------------------- Are we overloaded?              &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,
         if ((($userloadpercent>100.0)||($loadpercent>100.0))) {                       \%form);
             my $unloaded=Apache::lonnet::spareserver($loadpercent,$userloadpercent,1,$form{'udom'});              my $switchto = '/adm/switchserver?otherserver='.$otherserver;
             if (!$unloaded) {              if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {
                 ($unloaded) = &Apache::lonnet::choose_server($form{'udom'});                  $switchto .= '&origurl='.$firsturl;
             }              }
             if ($unloaded) {              if ($form{'role'}) {
                 &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',                  $switchto .= '&role='.$form{'role'};
                          undef,\%form);              }
                 $r->internal_redirect('/adm/switchserver?otherserver='.$unloaded.'&origurl='.$firsturl);              if ($form{'symb'}) {
                 return OK;                  $switchto .= '&symb='.$form{'symb'};
             }              }
         }              $r->internal_redirect($switchto);
         if (($is_balancer) && ($hosthere)) {          } else {
             $form{'noloadbalance'} = $hosthere;              $r->print(&noswitch());
         }          }
         &success($r,$form{'uname'},$form{'udom'},$authhost,$firsturl,undef,          return OK;
                  \%form);      } else {
         return OK;          if (!&check_can_host($r,\%form,$authhost)) {
     }              my ($otherserver) = &Apache::lonnet::choose_server($form{'udom'});
 }              if ($otherserver) {
                   &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',undef,
 sub check_can_host {                           \%form);
     my ($r,$form,$authhost,$domdesc) = @_;                  my $switchto = '/adm/switchserver?otherserver='.$otherserver;
     return unless (ref($form) eq 'HASH');                  if (($firsturl) && ($firsturl ne '/adm/switchserver') && ($firsturl ne '/adm/roles')) {
     my $canhost = 1;                      $switchto .= '&origurl='.$firsturl;
     my $lonhost = $r->dir_config('lonHostID');                  }
     my $udom = $form->{'udom'};                  if ($form{'role'}) {
     my @intdoms;                      $switchto .= '&role='.$form{'role'};
     my $internet_names = &Apache::lonnet::get_internet_names($lonhost);                  }
     if (ref($internet_names) eq 'ARRAY') {                  if ($form{'symb'}) {
         @intdoms = @{$internet_names};                      $switchto .= '&symb='.$form{'symb'};
     }                  }
     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');                  $r->internal_redirect($switchto);
     my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);              } else {
     unless ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {                  $r->print(&noswitch());
         my $machine_dom = &Apache::lonnet::host_domain($lonhost);              }
         my $hostname = &Apache::lonnet::hostname($lonhost);              return OK;
         my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);          }
         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);  
         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);  # ------------------------------------------------------- Do the load balancing
         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);  
         my $loncaparev;  # ---------------------------------------------------------- Determine own load
         if ($authhost eq 'no_account_on_host') {          my $loadlim = $r->dir_config('lonLoadLim');
             $loncaparev = &Apache::lonnet::get_server_loncaparev($machine_dom);          my $loadavg;
         } else {          {
             $loncaparev = &Apache::lonnet::get_server_loncaparev($machine_dom,$lonhost);              my $loadfile=Apache::File->new('/proc/loadavg');
         }              $loadavg=<$loadfile>;
         $canhost = &Apache::lonnet::can_host_session($udom,$lonhost,$loncaparev,          }
                                                      $udomdefaults{'remotesessions'},          $loadavg =~ s/\s.*//g;
                                                      $defdomdefaults{'hostedsessions'});          my $loadpercent=sprintf("%.1f",100*$loadavg/$loadlim);
     }          my $userloadpercent=&Apache::lonnet::userload();
     unless ($canhost) {  
         if ($authhost eq 'no_account_on_host') {  # ---------------------------------------------------------- Are we overloaded?
             my $checkloginvia = 1;          if ((($userloadpercent>100.0)||($loadpercent>100.0))) {
             my ($login_host,$hostname) =               my $unloaded=Apache::lonnet::spareserver($loadpercent,$userloadpercent,1,$form{'udom'});
                 &Apache::lonnet::choose_server($udom,$checkloginvia);              if (!$unloaded) {
             &Apache::loncommon::content_type($r,'text/html');                  ($unloaded) = &Apache::lonnet::choose_server($form{'udom'});
             $r->send_http_header;              }
             if ($login_host ne '') {              if ($unloaded) {
                 my $protocol = $Apache::lonnet::protocol{$login_host};                  &success($r,$form{'uname'},$form{'udom'},$authhost,'noredirect',
                 $protocol = 'http' if ($protocol ne 'https');                           undef,\%form);
                 my $newurl = $protocol.'://'.$hostname.'/adm/createaccount';                  $r->internal_redirect('/adm/switchserver?otherserver='.$unloaded.'&origurl='.$firsturl);
                 $r->print(&Apache::loncommon::start_page('Create a user account in LON-CAPA').                  return OK;
                           '<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>'.          if (($is_balancer) && ($hosthere)) {
                           '<p>'.&mt('[_1]Log in[_2]','<a href="'.$newurl.'">','</a>').              $form{'noloadbalance'} = $hosthere;
                           &Apache::loncommon::end_page());          }
             } else {          &success($r,$form{'uname'},$form{'udom'},$authhost,$firsturl,undef,
                 $r->print(&Apache::loncommon::start_page('Access to LON-CAPA unavailable').                   \%form);
                           '<h3>'.&mt('Account creation unavailable').'</h3>'.          return OK;
                           &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());  
             }  sub check_can_host {
         } else {      my ($r,$form,$authhost,$domdesc) = @_;
             &success($r,$form->{'uname'},$udom,$authhost,'noredirect',undef,      return unless (ref($form) eq 'HASH');
                      $form);      my $canhost = 1;
             my ($otherserver) = &Apache::lonnet::choose_server($udom);      my $lonhost = $r->dir_config('lonHostID');
             $r->internal_redirect('/adm/switchserver?otherserver='.$otherserver);      my $udom = $form->{'udom'};
         }      my @intdoms;
     }      my $internet_names = &Apache::lonnet::get_internet_names($lonhost);
     return $canhost;      if (ref($internet_names) eq 'ARRAY') {
 }          @intdoms = @{$internet_names};
       }
 sub noswitch {      my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
     my $result = &Apache::loncommon::start_page('Access to LON-CAPA unavailable').      my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                  '<h3>'.&mt('Session unavailable').'</h3>'.      unless ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
                  &mt('This LON-CAPA server is unable to host your session.').'<br />'.          my $machine_dom = &Apache::lonnet::host_domain($lonhost);
                  '<p>'.&mt('Currently no other LON-CAPA server is available to host your session either.').'</p>'.          my $hostname = &Apache::lonnet::hostname($lonhost);
                  &Apache::loncommon::end_page();          my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
     return $result;          my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
 }          my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
           my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
 sub loginhelpdisplay {          my $loncaparev;
     my ($authdomain) = @_;          if ($authhost eq 'no_account_on_host') {
     my $login_help = 1;              $loncaparev = &Apache::lonnet::get_server_loncaparev($machine_dom);
     my $lang = &Apache::lonlocal::current_language();          } else {
     if ($login_help) {              $loncaparev = &Apache::lonnet::get_server_loncaparev($machine_dom,$lonhost);
         my $dom = $authdomain;          }
         if ($dom eq '') {          $canhost = &Apache::lonnet::can_host_session($udom,$lonhost,$loncaparev,
             $dom = &Apache::lonnet::default_login_domain();                                                       $udomdefaults{'remotesessions'},
         }                                                       $defdomdefaults{'hostedsessions'});
         my %domconfhash = &Apache::loncommon::get_domainconf($dom);      }
         my $loginhelp_url;      unless ($canhost) {
         if ($lang) {          if ($authhost eq 'no_account_on_host') {
             $loginhelp_url = $domconfhash{$dom.'.login.helpurl_'.$lang};              my $checkloginvia = 1;
             if ($loginhelp_url ne '') {              my ($login_host,$hostname) =
                 return $loginhelp_url;                  &Apache::lonnet::choose_server($udom,$checkloginvia);
             }              &Apache::loncommon::content_type($r,'text/html');
         }              $r->send_http_header;
         $loginhelp_url = $domconfhash{$dom.'.login.helpurl_nolang'};              if ($login_host ne '') {
         if ($loginhelp_url ne '') {                  my $protocol = $Apache::lonnet::protocol{$login_host};
             return $loginhelp_url;                  $protocol = 'http' if ($protocol ne 'https');
         } else {                  my $newurl = $protocol.'://'.$hostname.'/adm/createaccount';
             return '/adm/loginproblems.html';                  $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 />'.
     return;                            '<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());
 1;              } else {
 __END__                  $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.121.2.20  
changed lines
  Added in v.1.153


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