Diff for /loncom/auth/lonlogin.pm between versions 1.158.2.10 and 1.177

version 1.158.2.10, 2020/10/24 19:49:06 version 1.177, 2018/12/26 20:10:21
Line 1 Line 1
 # The LearningOnline Network  # The LearningOnline Network
 # Login Screen  # Login Screen
 #  #
 # $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::lonlogin;  package Apache::lonlogin;
   
 use strict;  use strict;
 use Apache::Constants qw(:common);  use Apache::Constants qw(:common);
 use Apache::File ();  use Apache::File ();
 use Apache::lonnet;  use Apache::lonnet;
 use Apache::loncommon();  use Apache::loncommon();
 use Apache::lonauth();  use Apache::lonauth();
 use Apache::lonlocal;  use Apache::lonlocal;
 use Apache::migrateuser();  use Apache::migrateuser();
 use lib '/home/httpd/lib/perl/';  use lib '/home/httpd/lib/perl/';
 use LONCAPA qw(:DEFAULT :match);  use LONCAPA qw(:DEFAULT :match);
 use CGI::Cookie();  use CGI::Cookie();
     
 sub handler {  sub handler {
     my $r = shift;      my $r = shift;
   
     &Apache::loncommon::get_unprocessed_cgi      &Apache::loncommon::get_unprocessed_cgi
  (join('&',$ENV{'QUERY_STRING'},$env{'request.querystring'},   (join('&',$ENV{'QUERY_STRING'},$env{'request.querystring'},
       $ENV{'REDIRECT_QUERY_STRING'}),        $ENV{'REDIRECT_QUERY_STRING'}),
  ['interface','username','domain','firsturl','localpath','localres',   ['interface','username','domain','firsturl','localpath','localres',
   'token','role','symb','iptoken','btoken']);    'token','role','symb','iptoken','btoken','ltoken']);
     if (!defined($env{'form.firsturl'})) {      if (!defined($env{'form.firsturl'})) {
         &Apache::lonacc::get_posted_cgi($r,['firsturl']);          &Apache::lonacc::get_posted_cgi($r,['firsturl']);
     }      }
       if (!defined($env{'form.firsturl'})) {
 # -- check if they are a migrating user          if ($ENV{'REDIRECT_URL'} =~ m{^/+tiny/+$LONCAPA::match_domain/+\w+$}) {
     if (defined($env{'form.token'})) {              $env{'form.firsturl'} = $ENV{'REDIRECT_URL'};
  return &Apache::migrateuser::handler($r);          }
     }      }
   
 # For "public user" - remove any exising "public" cookie, as user really wants to log-in  # -- check if they are a migrating user
     my ($handle,$lonidsdir,$expirepub,$userdom);      if (defined($env{'form.token'})) {
     $lonidsdir=$r->dir_config('lonIDsDir');   return &Apache::migrateuser::handler($r);
     unless ($r->header_only) {      }
         $handle = &Apache::lonnet::check_for_valid_session($r,'lonID',undef,\$userdom);  
         if ($handle ne '') {  # For "public user" - remove any exising "public" cookie, as user really wants to log-in
             if ($handle=~/^publicuser\_/) {      my ($handle,$lonidsdir,$expirepub,$userdom);
                 unlink($r->dir_config('lonIDsDir')."/$handle.id");      $lonidsdir=$r->dir_config('lonIDsDir');
                 undef($handle);      unless ($r->header_only) {
                 undef($userdom);          $handle = &Apache::lonnet::check_for_valid_session($r,'lonID',undef,\$userdom);
                 $expirepub = 1;          if ($handle ne '') {
             }              if ($handle=~/^publicuser\_/) {
         }                  unlink($r->dir_config('lonIDsDir')."/$handle.id");
     }                  undef($handle);
                   undef($userdom);
     &Apache::loncommon::no_cache($r);                  $expirepub = 1;
     &Apache::lonlocal::get_language_handle($r);              }
     &Apache::loncommon::content_type($r,'text/html');          }
     if ($expirepub) {      }
         my $c = new CGI::Cookie(-name    => 'lonPubID',  
                                 -value   => '',      &Apache::loncommon::no_cache($r);
                                 -expires => '-10y',);      &Apache::lonlocal::get_language_handle($r);
         $r->header_out('Set-cookie' => $c);      &Apache::loncommon::content_type($r,'text/html');
     } elsif (($handle eq '') && ($userdom ne '')) {      if ($expirepub) {
         my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));          my $c = new CGI::Cookie(-name    => 'lonPubID',
         foreach my $name (keys(%cookies)) {                                  -value   => '',
             next unless ($name =~ /^lon(|S|Link|Pub)ID$/);                                  -expires => '-10y',);
             my $c = new CGI::Cookie(-name    => $name,          $r->header_out('Set-cookie' => $c);
                                     -value   => '',      } elsif (($handle eq '') && ($userdom ne '')) {
                                     -expires => '-10y',);          my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
             $r->headers_out->add('Set-cookie' => $c);          foreach my $name (keys(%cookies)) {
         }              next unless ($name =~ /^lon(|S|Link|Pub)ID$/);
     }              my $c = new CGI::Cookie(-name    => $name,
     $r->send_http_header;                                      -value   => '',
     return OK if $r->header_only;                                      -expires => '-10y',);
               $r->headers_out->add('Set-cookie' => $c);
           }
 # Are we re-routing?      }
     my $londocroot = $r->dir_config('lonDocRoot');       $r->send_http_header;
     if (-e "$londocroot/lon-status/reroute.txt") {      return OK if $r->header_only;
  &Apache::lonauth::reroute($r);  
  return OK;  
     }  # Are we re-routing?
       my $londocroot = $r->dir_config('lonDocRoot');
     my $lonhost = $r->dir_config('lonHostID');      if (-e "$londocroot/lon-status/reroute.txt") {
     $env{'form.firsturl'} =~ s/(`)/'/g;   &Apache::lonauth::reroute($r);
    return OK;
 # Check if browser sent a LON-CAPA load balancer cookie (and this is a balancer)      }
   
     my ($found_server,$balancer_cookie) = &Apache::lonnet::check_for_balancer_cookie($r,1);      my $lonhost = $r->dir_config('lonHostID');
     if ($found_server) {      $env{'form.firsturl'} =~ s/(`)/'/g;
         my $hostname = &Apache::lonnet::hostname($found_server);  
         if ($hostname ne '') {  # Check if browser sent a LON-CAPA load balancer cookie (and this is a balancer)
             my $protocol = $Apache::lonnet::protocol{$found_server};  
             $protocol = 'http' if ($protocol ne 'https');      my ($found_server,$balancer_cookie) = &Apache::lonnet::check_for_balancer_cookie($r,1);
             my $dest = '/adm/roles';      if ($found_server) {
             if ($env{'form.firsturl'} ne '') {          my $hostname = &Apache::lonnet::hostname($found_server);
                 $dest = $env{'form.firsturl'};          if ($hostname ne '') {
             }              my $protocol = $Apache::lonnet::protocol{$found_server};
             my %info = (              $protocol = 'http' if ($protocol ne 'https');
                          balcookie => $lonhost.':'.$balancer_cookie,              my $dest = '/adm/roles';
                        );              if ($env{'form.firsturl'} ne '') {
             my $balancer_token = &Apache::lonnet::tmpput(\%info,$found_server);                  $dest = $env{'form.firsturl'};
             if ($balancer_token) {              }
                 $dest .=  (($dest=~/\?/)?'&;':'?') . 'btoken='.$balancer_token;              my %info = (
             }                           balcookie => $lonhost.':'.$balancer_cookie,
             my $url = $protocol.'://'.$hostname.$dest;                         );
             my $start_page =              if ($env{'form.ltoken'}) {
                 &Apache::loncommon::start_page('Switching Server ...',undef,                  my %link_info = &Apache::lonnet::tmpget($env{'form.ltoken'});
                                                {'redirect'       => [0,$url],});                  if ($link_info{'linkprot'}) {
             my $end_page   = &Apache::loncommon::end_page();                      $info{'linkprot'} = $link_info{'linkprot'};
             $r->print($start_page.$end_page);                  }
             return OK;                  &Apache::lonnet::tmpdel($env{'form.ltoken'});
         }                  delete($env{'form.ltoken'});
     }              }
               my $balancer_token = &Apache::lonnet::tmpput(\%info,$found_server);
 #              if ($balancer_token) {
 # Check if a LON-CAPA load balancer sent user here because user's browser sent                  $dest .=  (($dest=~/\?/)?'&;':'?') . 'btoken='.$balancer_token;
 # it a balancer cookie for an active session on this server.              }
 #              my $url = $protocol.'://'.$hostname.$dest;
               my $start_page =
     my $balcookie;                  &Apache::loncommon::start_page('Switching Server ...',undef,
     if ($env{'form.btoken'}) {                                                 {'redirect'       => [0,$url],});
         my %info = &Apache::lonnet::tmpget($env{'form.btoken'});              my $end_page   = &Apache::loncommon::end_page();
         $balcookie = $info{'balcookie'};              $r->print($start_page.$end_page);
         &Apache::lonnet::tmpdel($env{'form.btoken'});              return OK;
         delete($env{'form.btoken'});          }
     }      }
   
 #  #
 # If browser sent an old cookie for which the session file had been removed  # Check if a LON-CAPA load balancer sent user here because user's browser sent
 # check if configuration for user's domain has a portal URL set.  If so  # it a balancer cookie for an active session on this server.
 # switch user's log-in to the portal.  #
 #  
       my ($balcookie,$linkprot);
     if (($handle eq '') && ($userdom ne '')) {      if ($env{'form.btoken'}) {
         my %domdefaults = &Apache::lonnet::get_domain_defaults($userdom);          my %info = &Apache::lonnet::tmpget($env{'form.btoken'});
         if ($domdefaults{'portal_def'} =~ /^https?\:/) {          $balcookie = $info{'balcookie'};
             my $start_page = &Apache::loncommon::start_page('Switching Server ...',undef,          if ($balcookie) {
                                           {'redirect' => [0,$domdefaults{'portal_def'}],});              if ($info{'linkprot'}) {
             my $end_page   = &Apache::loncommon::end_page();                  $linkprot = $info{'linkprot'};
             $r->print($start_page.$end_page);              }
             return OK;          }    
         }          &Apache::lonnet::tmpdel($env{'form.btoken'});
     }          delete($env{'form.btoken'});
       }
     $env{'form.firsturl'} =~ s/(`)/'/g;  
   #
 # -------------------------------- Prevent users from attempting to login twice  # If browser sent an old cookie for which the session file had been removed
     if ($handle ne '') {  # check if configuration for user's domain has a portal URL set.  If so
         &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle);  # switch user's log-in to the portal.
  my $start_page =   #
     &Apache::loncommon::start_page('Already logged in');  
  my $end_page =       if (($handle eq '') && ($userdom ne '')) {
     &Apache::loncommon::end_page();          my %domdefaults = &Apache::lonnet::get_domain_defaults($userdom);
         my $dest = '/adm/roles';          if ($domdefaults{'portal_def'} =~ /^https?\:/) {
         if ($env{'form.firsturl'} ne '') {              my $start_page = &Apache::loncommon::start_page('Switching Server ...',undef,
             $dest = $env{'form.firsturl'};                                             {'redirect' => [0,$domdefaults{'portal_def'}],});
         }              my $end_page   = &Apache::loncommon::end_page();
  $r->print(              $r->print($start_page.$end_page);
               $start_page              return OK;
              .'<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].',      }
               '<a href="'.$dest.'">','</a>','<a href="/adm/logout">','</a>').'</p>'  
              .$end_page  # -------------------------------- Prevent users from attempting to login twice
              );      if ($handle ne '') {
         return OK;          &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle);
     }   my $start_page =
       &Apache::loncommon::start_page('Already logged in');
 # ---------------------------------------------------- No valid token, continue   my $end_page =
       &Apache::loncommon::end_page();
 # ---------------------------- Not possible to really login to domain "public"          my $dest = '/adm/roles';
     if ($env{'form.domain'} eq 'public') {          if ($env{'form.firsturl'} ne '') {
  $env{'form.domain'}='';              $dest = $env{'form.firsturl'};
  $env{'form.username'}='';          }
     }          if (($env{'form.ltoken'}) || ($linkprot)) {
               unless ($linkprot) {
 # ------ Is this page requested because /adm/migrateuser detected an IP change?                  my %info = &Apache::lonnet::tmpget($env{'form.ltoken'});
     my %sessiondata;                  $linkprot = $info{'linkprot'};
     if ($env{'form.iptoken'}) {                  my $delete = &Apache::lonnet::tmpdel($env{'form.ltoken'});
         %sessiondata = &Apache::lonnet::tmpget($env{'form.iptoken'});                  delete($env{'form.ltoken'});
         unless ($sessiondata{'sessionserver'}) {              }
             my $delete = &Apache::lonnet::tmpdel($env{'form.iptoken'});              if ($linkprot) {
             delete($env{'form.iptoken'});                  my ($linkprotector,$deeplink) = split(/:/,$linkprot,2);
         }                  if ($env{'user.linkprotector'}) {
     }                      my @protectors = split(/,/,$env{'user.linkprotector'});
 # ----------------------------------------------------------- Process Interface                      unless (grep(/^\Q$linkprotector\E$/,@protectors)) {
     $env{'form.interface'}=~s/\W//g;                          push(@protectors,$linkprotector);
                           @protectors = sort { $a <=> $b } @protectors;
     (undef,undef,undef,undef,undef,undef,my $clientmobile) =                          &Apache::lonnet::appenv({'user.linkprotector' => join(',',@protectors)});
         &Apache::loncommon::decode_user_agent();                      }
                   } else {
     my $iconpath=                       &Apache::lonnet::appenv({'user.linkprotector' => $linkprotector });
  &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL'));                  }
                   if ($env{'user.linkproturi'}) {
     my $domain = &Apache::lonnet::default_login_domain();                      my @proturis = split(/,/,$env{'user.linkproturi'});
     my $defdom = $domain;                      unless(grep(/^\Q$deeplink\E$/,@proturis)) {
     if ($lonhost ne '') {                          push(@proturis,$deeplink);
         unless ($sessiondata{'sessionserver'}) {                          @proturis = sort @proturis;
             my $redirect = &check_loginvia($domain,$lonhost,$lonidsdir,$balcookie);                          &Apache::lonnet::appenv({'user.linkproturi' => join(',',@proturis)});
             if ($redirect) {                      }
                 $r->print($redirect);                  } else {
                 return OK;                      &Apache::lonnet::appenv({'user.linkproturi' => $deeplink});
             }                  }
         }              }
     }          }
    $r->print(
     if (($sessiondata{'domain'}) &&                    $start_page
         (&Apache::lonnet::domain($sessiondata{'domain'},'description'))) {                   .'<p class="LC_warning">'.&mt('You are already logged in!').'</p>'
         $domain=$sessiondata{'domain'};                   .'<p>'.&mt('Please either [_1]continue the current session[_2] or [_3]log out[_4].',
     } elsif (($env{'form.domain'}) &&                     '<a href="'.$dest.'">','</a>','<a href="/adm/logout">','</a>').'</p>'
  (&Apache::lonnet::domain($env{'form.domain'},'description'))) {                   .$end_page
  $domain=$env{'form.domain'};                   );
     }          return OK;
       }
     my $role    = $r->dir_config('lonRole');  
     my $loadlim = $r->dir_config('lonLoadLim');  # ---------------------------------------------------- No valid token, continue
     my $uloadlim= $r->dir_config('lonUserLoadLim');  
     my $servadm = $r->dir_config('lonAdmEMail');  # ---------------------------- Not possible to really login to domain "public"
     my $tabdir  = $r->dir_config('lonTabDir');      if ($env{'form.domain'} eq 'public') {
     my $include = $r->dir_config('lonIncludes');   $env{'form.domain'}='';
     my $expire  = $r->dir_config('lonExpire');   $env{'form.username'}='';
     my $version = $r->dir_config('lonVersion');      }
     my $host_name = &Apache::lonnet::hostname($lonhost);  
   # ------ Is this page requested because /adm/migrateuser detected an IP change?
 # --------------------------------------------- Default values for login fields      my %sessiondata;
           if ($env{'form.iptoken'}) {
     my ($authusername,$authdomain);          %sessiondata = &Apache::lonnet::tmpget($env{'form.iptoken'});
     if ($sessiondata{'username'}) {          unless ($sessiondata{'sessionserver'}) {
         $authusername=$sessiondata{'username'};              my $delete = &Apache::lonnet::tmpdel($env{'form.iptoken'});
     } else {              delete($env{'form.iptoken'});
         $env{'form.username'} = &Apache::loncommon::cleanup_html($env{'form.username'});          }
         $authusername=($env{'form.username'}?$env{'form.username'}:'');      }
     }  # ----------------------------------------------------------- Process Interface
     if ($sessiondata{'domain'}) {      $env{'form.interface'}=~s/\W//g;
         $authdomain=$sessiondata{'domain'};  
     } else {      (undef,undef,undef,undef,undef,undef,my $clientmobile) =
         $env{'form.domain'} = &Apache::loncommon::cleanup_html($env{'form.domain'});          &Apache::loncommon::decode_user_agent();
         $authdomain=($env{'form.domain'}?$env{'form.domain'}:$domain);  
     }      my $iconpath=
    &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL'));
 # ---------------------------------------------------------- Determine own load  
     my $loadavg;      my $domain = &Apache::lonnet::default_login_domain();
     {      my $defdom = $domain;
  my $loadfile=Apache::File->new('/proc/loadavg');      if ($lonhost ne '') {
  $loadavg=<$loadfile>;          unless ($sessiondata{'sessionserver'}) {
     }              my $redirect = &check_loginvia($domain,$lonhost,$lonidsdir,$balcookie,$linkprot);
     $loadavg =~ s/\s.*//g;              if ($redirect) {
                   $r->print($redirect);
     my ($loadpercent,$userloadpercent);                  return OK;
     if ($loadlim) {              }
         $loadpercent=sprintf("%.1f",100*$loadavg/$loadlim);          }
     }      }
     if ($uloadlim) {  
         $userloadpercent=&Apache::lonnet::userload();      if (($sessiondata{'domain'}) &&
     }          (&Apache::lonnet::domain($sessiondata{'domain'},'description'))) {
           $domain=$sessiondata{'domain'};
     my $firsturl=      } elsif (($env{'form.domain'}) &&
     ($env{'request.firsturl'}?$env{'request.firsturl'}:$env{'form.firsturl'});   (&Apache::lonnet::domain($env{'form.domain'},'description'))) {
    $domain=$env{'form.domain'};
 # ----------------------------------------------------------- Get announcements      }
     my $announcements=&Apache::lonnet::getannounce();  
 # -------------------------------------------------------- Set login parameters      my $role    = $r->dir_config('lonRole');
       my $loadlim = $r->dir_config('lonLoadLim');
     my @hexstr=('0','1','2','3','4','5','6','7',      my $uloadlim= $r->dir_config('lonUserLoadLim');
                 '8','9','a','b','c','d','e','f');      my $servadm = $r->dir_config('lonAdmEMail');
     my $lkey='';      my $tabdir  = $r->dir_config('lonTabDir');
     for (0..7) {      my $include = $r->dir_config('lonIncludes');
         $lkey.=$hexstr[rand(15)];      my $expire  = $r->dir_config('lonExpire');
     }      my $version = $r->dir_config('lonVersion');
       my $host_name = &Apache::lonnet::hostname($lonhost);
     my $ukey='';  
     for (0..7) {  # --------------------------------------------- Default values for login fields
         $ukey.=$hexstr[rand(15)];     
     }      my ($authusername,$authdomain);
       if ($sessiondata{'username'}) {
     my $lextkey=hex($lkey);          $authusername=$sessiondata{'username'};
     if ($lextkey>2147483647) { $lextkey-=4294967296; }      } else {
           $env{'form.username'} = &Apache::loncommon::cleanup_html($env{'form.username'});
     my $uextkey=hex($ukey);          $authusername=($env{'form.username'}?$env{'form.username'}:'');
     if ($uextkey>2147483647) { $uextkey-=4294967296; }      }
       if ($sessiondata{'domain'}) {
 # -------------------------------------------------------- Store away log token          $authdomain=$sessiondata{'domain'};
     my $tokenextras;      } else {
     if ($env{'form.role'}) {          $env{'form.domain'} = &Apache::loncommon::cleanup_html($env{'form.domain'});
         $tokenextras = '&role='.&escape($env{'form.role'});          $authdomain=($env{'form.domain'}?$env{'form.domain'}:$domain);
     }      }
     if ($env{'form.symb'}) {  
         if (!$tokenextras) {  # ---------------------------------------------------------- Determine own load
             $tokenextras = '&';      my $loadavg;
         }      {
         $tokenextras .= '&symb='.&escape($env{'form.symb'});   my $loadfile=Apache::File->new('/proc/loadavg');
     }   $loadavg=<$loadfile>;
     if ($env{'form.iptoken'}) {      }
         if (!$tokenextras) {      $loadavg =~ s/\s.*//g;
             $tokenextras = '&&';  
         }      my ($loadpercent,$userloadpercent);
         $tokenextras .= '&iptoken='.&escape($env{'form.iptoken'});      if ($loadlim) {
     }          $loadpercent=sprintf("%.1f",100*$loadavg/$loadlim);
     my $logtoken=Apache::lonnet::reply(      }
        'tmpput:'.$ukey.$lkey.'&'.$firsturl.$tokenextras,      if ($uloadlim) {
        $lonhost);          $userloadpercent=&Apache::lonnet::userload();
       }
 # -- If we cannot talk to ourselves, or hostID does not map to a hostname  
 #    we are in serious trouble      my $firsturl=
       ($env{'request.firsturl'}?$env{'request.firsturl'}:$env{'form.firsturl'});
     if (($logtoken eq 'con_lost') || ($logtoken eq 'no_such_host')) {  
         if ($logtoken eq 'no_such_host') {  # ----------------------------------------------------------- Get announcements
             &Apache::lonnet::logthis('No valid logtoken for log-in page -- unable to determine hostname for hostID: '.$lonhost.'. Check entry in hosts.tab');      my $announcements=&Apache::lonnet::getannounce();
         }  # -------------------------------------------------------- Set login parameters
         my $spares='';  
         my (@sparehosts,%spareservers);      my @hexstr=('0','1','2','3','4','5','6','7',
         my $sparesref = &Apache::lonnet::this_host_spares($defdom);                  '8','9','a','b','c','d','e','f');
         if (ref($sparesref) eq 'HASH') {      my $lkey='';
             foreach my $key (keys(%{$sparesref})) {      for (0..7) {
                 if (ref($sparesref->{$key}) eq 'ARRAY') {          $lkey.=$hexstr[rand(15)];
                     my @sorted = sort { &Apache::lonnet::hostname($a) cmp      }
                                         &Apache::lonnet::hostname($b);  
                                       } @{$sparesref->{$key}};      my $ukey='';
                     if (@sorted) {      for (0..7) {
                         if ($key eq 'primary') {          $ukey.=$hexstr[rand(15)];
                             unshift(@sparehosts,@sorted);      }
                         } elsif ($key eq 'default') {  
                             push(@sparehosts,@sorted);      my $lextkey=hex($lkey);
                         }      if ($lextkey>2147483647) { $lextkey-=4294967296; }
                     }  
                 }      my $uextkey=hex($ukey);
             }      if ($uextkey>2147483647) { $uextkey-=4294967296; }
         }  
         foreach my $hostid (@sparehosts) {  # -------------------------------------------------------- Store away log token
             next if ($hostid eq $lonhost);      my $tokenextras;
     my $hostname = &Apache::lonnet::hostname($hostid);      if ($env{'form.role'}) {
     next if (($hostname eq '') || ($spareservers{$hostname}));          $tokenextras = '&role='.&escape($env{'form.role'});
             $spareservers{$hostname} = 1;      }
             my $protocol = $Apache::lonnet::protocol{$hostid};      if ($env{'form.symb'}) {
             $protocol = 'http' if ($protocol ne 'https');          if (!$tokenextras) {
             $spares.='<br /><span style="font-size: larger;"><a href="'.$protocol.'://'.              $tokenextras = '&';
                 $hostname.          }
                 '/adm/login?domain='.$authdomain.'">'.          $tokenextras .= '&symb='.&escape($env{'form.symb'});
                 $hostname.'</a>'.      }
                 ' '.&mt('(preferred)').'</span>'.$/;      if ($env{'form.iptoken'}) {
         }          if (!$tokenextras) {
         if ($spares) {              $tokenextras = '&&';
             $spares.= '<br />';          }
         }          $tokenextras .= '&iptoken='.&escape($env{'form.iptoken'});
         my %all_hostnames = &Apache::lonnet::all_hostnames();      }
         foreach my $hostid (sort      if ($env{'form.ltoken'}) {
     {          my %info = &Apache::lonnet::tmpget($env{'form.ltoken'});
  &Apache::lonnet::hostname($a) cmp          &Apache::lonnet::tmpdel($env{'form.ltoken'});
     &Apache::lonnet::hostname($b);          delete($env{'form.ltoken'});
     }          if ($info{'linkprot'}) {
     keys(%all_hostnames)) {              if (!$tokenextras) {
             next if ($hostid eq $lonhost);                  $tokenextras = '&&&';
             my $hostname = &Apache::lonnet::hostname($hostid);              }
             next if (($hostname eq '') || ($spareservers{$hostname}));              $tokenextras .= '&linkprot='.&escape($info{'linkprot'});
             my $protocol = $Apache::lonnet::protocol{$hostid};          }
             $protocol = 'http' if ($protocol ne 'https');      }
             $spares.='<br /><a href="'.$protocol.'://'.      my $logtoken=Apache::lonnet::reply(
              $hostname.         'tmpput:'.$ukey.$lkey.'&'.$firsturl.$tokenextras,
              '/adm/login?domain='.$authdomain.'">'.         $lonhost);
              $hostname.'</a>';  
          }  # -- If we cannot talk to ourselves, or hostID does not map to a hostname
          $r->print(  #    we are in serious trouble
    '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'  
   .'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'      if (($logtoken eq 'con_lost') || ($logtoken eq 'no_such_host')) {
   .'<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>'          if ($logtoken eq 'no_such_host') {
   .&mt('The LearningOnline Network with CAPA')              &Apache::lonnet::logthis('No valid logtoken for log-in page -- unable to determine hostname for hostID: '.$lonhost.'. Check entry in hosts.tab');
   .'</title></head>'          }
   .'<body bgcolor="#FFFFFF">'          my $spares='';
   .'<h1>'.&mt('The LearningOnline Network with CAPA').'</h1>'   my $last;
   .'<img src="/adm/lonKaputt/lonlogo_broken.gif" alt="broken icon" align="right" />'          foreach my $hostid (sort
   .'<h3>'.&mt('This LON-CAPA server is temporarily not available for login.').'</h3>');      {
         if ($spares) {   &Apache::lonnet::hostname($a) cmp
             $r->print('<p>'.&mt('Please attempt to login to one of the following servers:')      &Apache::lonnet::hostname($b);
                      .'</p>'      }
                      .$spares);      keys(%Apache::lonnet::spareid)) {
         }              next if ($hostid eq $lonhost);
         $r->print('</body>'      my $hostname = &Apache::lonnet::hostname($hostid);
                  .'</html>'      next if (($last eq $hostname) || ($hostname eq ''));
         );              $spares.='<br /><font size="+1"><a href="http://'.
         return OK;                  $hostname.
     }                  '/adm/login?domain='.$authdomain.'">'.
                   $hostname.'</a>'.
 # ----------------------------------------------- Apparently we are in business                  ' '.&mt('(preferred)').'</font>'.$/;
     $servadm=~s/\,/\<br \/\>/g;      $last=$hostname;
           }
 # ----------------------------------------------------------- Front page design          if ($spares) {
     my $pgbg=&Apache::loncommon::designparm('login.pgbg',$domain);              $spares.= '<br />';
     my $font=&Apache::loncommon::designparm('login.font',$domain);          }
     my $link=&Apache::loncommon::designparm('login.link',$domain);          my %all_hostnames = &Apache::lonnet::all_hostnames();
     my $vlink=&Apache::loncommon::designparm('login.vlink',$domain);          foreach my $hostid (sort
     my $alink=&Apache::loncommon::designparm('login.alink',$domain);      {
     my $mainbg=&Apache::loncommon::designparm('login.mainbg',$domain);   &Apache::lonnet::hostname($a) cmp
     my $loginbox_bg=&Apache::loncommon::designparm('login.sidebg',$domain);      &Apache::lonnet::hostname($b);
     my $loginbox_header_bgcol=&Apache::loncommon::designparm('login.bgcol',$domain);      }
     my $loginbox_header_textcol=&Apache::loncommon::designparm('login.textcol',$domain);      keys(%all_hostnames)) {
     my $logo=&Apache::loncommon::designparm('login.logo',$domain);              next if ($hostid eq $lonhost || $Apache::lonnet::spareid{$hostid});
     my $img=&Apache::loncommon::designparm('login.img',$domain);              my $hostname = &Apache::lonnet::hostname($hostid);
     my $domainlogo=&Apache::loncommon::domainlogo($domain);              next if (($last eq $hostname) || ($hostname eq ''));
     my $showbanner = 1;              $spares.='<br /><a href="http://'.
     my $showmainlogo = 1;               $hostname.
     if (defined(&Apache::loncommon::designparm('login.showlogo_img',$domain))) {               '/adm/login?domain='.$authdomain.'">'.
         $showbanner = &Apache::loncommon::designparm('login.showlogo_img',$domain);               $hostname.'</a>';
     }              $last=$hostname;
     if (defined(&Apache::loncommon::designparm('login.showlogo_logo',$domain))) {           }
         $showmainlogo = &Apache::loncommon::designparm('login.showlogo_logo',$domain);           $r->print(
     }     '<html>'
     my $showadminmail;    .'<head><title>'
     my @possdoms = &Apache::lonnet::current_machine_domains();    .&mt('The LearningOnline Network with CAPA')
     if (grep(/^\Q$domain\E$/,@possdoms)) {    .'</title></head>'
         $showadminmail=&Apache::loncommon::designparm('login.adminmail',$domain);    .'<body bgcolor="#FFFFFF">'
     }    .'<h1>'.&mt('The LearningOnline Network with CAPA').'</h1>'
     my $showcoursecat =    .'<img src="/adm/lonKaputt/lonlogo_broken.gif" align="right" />'
         &Apache::loncommon::designparm('login.coursecatalog',$domain);    .'<h3>'.&mt('This LON-CAPA server is temporarily not available for login.').'</h3>');
     my $shownewuserlink =           if ($spares) {
         &Apache::loncommon::designparm('login.newuser',$domain);              $r->print('<p>'.&mt('Please attempt to login to one of the following servers:')
     my $showhelpdesk =                       .'</p>'
         &Apache::loncommon::designparm('login.helpdesk',$domain);                       .$spares);
     my $now=time;          }
     my $js = (<<ENDSCRIPT);          $r->print('</body>'
                    .'</html>'
 <script type="text/javascript" language="JavaScript">          );
 // <![CDATA[          return OK;
 function send()      }
 {  
 this.document.server.elements.uname.value  # ----------------------------------------------- Apparently we are in business
 =this.document.client.elements.uname.value;      $servadm=~s/\,/\<br \/\>/g;
   
 this.document.server.elements.udom.value  # ----------------------------------------------------------- Front page design
 =this.document.client.elements.udom.value;      my $pgbg=&Apache::loncommon::designparm('login.pgbg',$domain);
       my $font=&Apache::loncommon::designparm('login.font',$domain);
 uextkey=this.document.client.elements.uextkey.value;      my $link=&Apache::loncommon::designparm('login.link',$domain);
 lextkey=this.document.client.elements.lextkey.value;      my $vlink=&Apache::loncommon::designparm('login.vlink',$domain);
 initkeys();      my $alink=&Apache::loncommon::designparm('login.alink',$domain);
       my $mainbg=&Apache::loncommon::designparm('login.mainbg',$domain);
 this.document.server.elements.upass0.value      my $loginbox_bg=&Apache::loncommon::designparm('login.sidebg',$domain);
     =getCrypted(this.document.client.elements.upass$now.value);      my $loginbox_header_bgcol=&Apache::loncommon::designparm('login.bgcol',$domain);
       my $loginbox_header_textcol=&Apache::loncommon::designparm('login.textcol',$domain);
 this.document.client.elements.uname.value='';      my $logo=&Apache::loncommon::designparm('login.logo',$domain);
 this.document.client.elements.upass$now.value='';      my $img=&Apache::loncommon::designparm('login.img',$domain);
       my $domainlogo=&Apache::loncommon::domainlogo($domain);
 this.document.server.submit();      my $showbanner = 1;
 return false;      my $showmainlogo = 1;
 }      if (defined(&Apache::loncommon::designparm('login.showlogo_img',$domain))) {
           $showbanner = &Apache::loncommon::designparm('login.showlogo_img',$domain);
 function enableInput() {      }
     this.document.client.elements.upass$now.removeAttribute("readOnly");      if (defined(&Apache::loncommon::designparm('login.showlogo_logo',$domain))) {
     this.document.client.elements.uname.removeAttribute("readOnly");          $showmainlogo = &Apache::loncommon::designparm('login.showlogo_logo',$domain);
     this.document.client.elements.udom.removeAttribute("readOnly");      }
     return;      my $showadminmail;
 }      my @possdoms = &Apache::lonnet::current_machine_domains();
       if (grep(/^\Q$domain\E$/,@possdoms)) {
 // ]]>          $showadminmail=&Apache::loncommon::designparm('login.adminmail',$domain);
 </script>      }
       my $showcoursecat =
 ENDSCRIPT          &Apache::loncommon::designparm('login.coursecatalog',$domain);
       my $shownewuserlink =
 # --------------------------------------------------- Print login screen header          &Apache::loncommon::designparm('login.newuser',$domain);
       my $showhelpdesk =
     my %add_entries = (          &Apache::loncommon::designparm('login.helpdesk',$domain);
        bgcolor      => "$mainbg",      my $now=time;
        text         => "$font",      my $js = (<<ENDSCRIPT);
        link         => "$link",  
        vlink        => "$vlink",  <script type="text/javascript" language="JavaScript">
        alink        => "$alink",  // <![CDATA[
                onload       => 'javascript:enableInput();',);  function send()
   {
     my ($lonhost_in_use,$headextra,$headextra_exempt,@hosts,%defaultdomconf);  this.document.server.elements.uname.value
     @hosts = &Apache::lonnet::current_machine_ids();  =this.document.client.elements.uname.value;
     $lonhost_in_use = $lonhost;  
     if (@hosts > 1) {  this.document.server.elements.udom.value
         foreach my $hostid (@hosts) {  =this.document.client.elements.udom.value;
             if (&Apache::lonnet::host_domain($hostid) eq $defdom) {  
                 $lonhost_in_use = $hostid;  uextkey=this.document.client.elements.uextkey.value;
                 last;  lextkey=this.document.client.elements.lextkey.value;
             }  initkeys();
         }  
     }  if(this.document.server.action.substr(0,5) === 'http:'){
     %defaultdomconf = &Apache::loncommon::get_domainconf($defdom);      this.document.server.elements.upass0.value
     $headextra = $defaultdomconf{$defdom.'.login.headtag_'.$lonhost_in_use};          =getCrypted(this.document.client.elements.upass$now.value);
     $headextra_exempt = $defaultdomconf{$domain.'.login.headtag_exempt_'.$lonhost_in_use};  } else {
     if ($headextra) {      this.document.server.elements.upass0.value
         my $omitextra;          =this.document.client.elements.upass$now.value;
         if ($headextra_exempt ne '') {  }
             my @exempt = split(',',$headextra_exempt);  
             my $ip = $ENV{'REMOTE_ADDR'};  this.document.client.elements.uname.value='';
             if (grep(/^\Q$ip\E$/,@exempt)) {  this.document.client.elements.upass$now.value='';
                 $omitextra = 1;  
             }  this.document.server.submit();
         }  return false;
         unless ($omitextra) {  }
             my $confname = $defdom.'-domainconfig';  
             if ($headextra =~ m{^\Q/res/$defdom/$confname/login/headtag/$lonhost_in_use/\E}) {  function enableInput() {
                 my $extra = &Apache::lonnet::getfile(&Apache::lonnet::filelocation("",$headextra));      this.document.client.elements.upass$now.removeAttribute("readOnly");
                 unless ($extra eq '-1') {      this.document.client.elements.uname.removeAttribute("readOnly");
                     $js .= "\n".$extra."\n";      this.document.client.elements.udom.removeAttribute("readOnly");
                 }      return;
             }  }
         }  
     }  // ]]>
   </script>
     $r->print(&Apache::loncommon::start_page('The LearningOnline Network with CAPA Login',$js,  
        { 'redirect'       => [$expire,'/adm/roles'],   ENDSCRIPT
  'add_entries' => \%add_entries,  
  'only_body'   => 1,}));  # --------------------------------------------------- Print login screen header
   
 # ----------------------------------------------------------------------- Texts      my %add_entries = (
          bgcolor      => "$mainbg",
     my %lt=&Apache::lonlocal::texthash(         text         => "$font",
           'un'       => 'Username',         link         => "$link",
           'pw'       => 'Password',         vlink        => "$vlink",
           'dom'      => 'Domain',         alink        => "$alink",
           'perc'     => 'percent',                 onload       => 'javascript:enableInput();',);
           'load'     => 'Server Load',  
           'userload' => 'User Load',      my ($lonhost_in_use,$headextra,$headextra_exempt,@hosts,%defaultdomconf);
           'catalog'  => 'Course/Community Catalog',      @hosts = &Apache::lonnet::current_machine_ids();
           'log'      => 'Log in',      $lonhost_in_use = $lonhost;
           'help'     => 'Log-in Help',      if (@hosts > 1) {
           'serv'     => 'Server',          foreach my $hostid (@hosts) {
           'servadm'  => 'Server Administration',              if (&Apache::lonnet::host_domain($hostid) eq $defdom) {
           'helpdesk' => 'Contact Helpdesk',                  $lonhost_in_use = $hostid;
           'forgotpw' => 'Forgot password?',                  last;
           'newuser'  => 'New User?',              }
        );          }
 # -------------------------------------------------- Change password field name      }
       %defaultdomconf = &Apache::loncommon::get_domainconf($defdom);
     my $forgotpw = &forgotpwdisplay(%lt);      $headextra = $defaultdomconf{$defdom.'.login.headtag_'.$lonhost_in_use};
     $forgotpw .= '<br />' if $forgotpw;      $headextra_exempt = $defaultdomconf{$domain.'.login.headtag_exempt_'.$lonhost_in_use};
     my $loginhelp = &Apache::lonauth::loginhelpdisplay($authdomain);      if ($headextra) {
     if ($loginhelp) {          my $omitextra;
         $loginhelp = '<a href="'.$loginhelp.'">'.$lt{'help'}.'</a><br />';          if ($headextra_exempt ne '') {
     }              my @exempt = split(',',$headextra_exempt);
               my $ip = $ENV{'REMOTE_ADDR'};
 # ---------------------------------------------------- Serve out DES JavaScript              if (grep(/^\Q$ip\E$/,@exempt)) {
     {                  $omitextra = 1;
     my $jsh=Apache::File->new($include."/londes.js");              }
     $r->print(<$jsh>);          }
     }          unless ($omitextra) {
 # ---------------------------------------------------------- Serve rest of page              my $confname = $defdom.'-domainconfig';
               if ($headextra =~ m{^\Q/res/$defdom/$confname/login/headtag/$lonhost_in_use/\E}) {
     $r->print(                  my $extra = &Apache::lonnet::getfile(&Apache::lonnet::filelocation("",$headextra));
     '<div class="LC_Box"'                  unless ($extra eq '-1') {
    .' style="margin:0 auto; padding:10px; width:90%; height: auto; background-color:#FFFFFF;">'                      $js .= "\n".$extra."\n";
 );                  }
               }
     $r->print(<<ENDSERVERFORM);          }
 <form name="server" action="/adm/authenticate" method="post" target="_top">      }
    <input type="hidden" name="logtoken" value="$logtoken" />  
    <input type="hidden" name="serverid" value="$lonhost" />      $r->print(&Apache::loncommon::start_page('The LearningOnline Network with CAPA Login',$js,
    <input type="hidden" name="uname" value="" />         { 'redirect'       => [$expire,'/adm/roles'],
    <input type="hidden" name="upass0" value="" />   'add_entries' => \%add_entries,
    <input type="hidden" name="udom" value="" />   'only_body'   => 1,}));
    <input type="hidden" name="localpath" value="$env{'form.localpath'}" />  
    <input type="hidden" name="localres" value="$env{'form.localres'}" />  # ----------------------------------------------------------------------- Texts
   </form>  
 ENDSERVERFORM      my %lt=&Apache::lonlocal::texthash(
     my $coursecatalog;            'un'       => 'Username',
     if (($showcoursecat eq '') || ($showcoursecat)) {            'pw'       => 'Password',
         $coursecatalog = &coursecatalog_link($lt{'catalog'}).'<br />';            'dom'      => 'Domain',
     }            'perc'     => 'percent',
     my $newuserlink;            'load'     => 'Server Load',
     if ($shownewuserlink) {            'userload' => 'User Load',
         $newuserlink = &newuser_link($lt{'newuser'}).'<br />';            'catalog'  => 'Course/Community Catalog',
     }            'log'      => 'Log in',
     my $logintitle =            'help'     => 'Log-in Help',
         '<h2 class="LC_hcell"'            'serv'     => 'Server',
        .' style="background:'.$loginbox_header_bgcol.';'            'servadm'  => 'Server Administration',
        .' color:'.$loginbox_header_textcol.'">'            'helpdesk' => 'Contact Helpdesk',
        .$lt{'log'}            'forgotpw' => 'Forgot password?',
        .'</h2>';            'newuser'  => 'New User?',
          );
     my $noscript_warning='<noscript><span class="LC_warning"><b>'  # -------------------------------------------------- Change password field name
                         .&mt('Use of LON-CAPA requires Javascript to be enabled in your web browser.')  
                         .'</b></span></noscript>';      my $forgotpw = &forgotpwdisplay(%lt);
     my $helpdeskscript;      $forgotpw .= '<br />' if $forgotpw;
     my $contactblock = &contactdisplay(\%lt,$servadm,$showadminmail,      my $loginhelp = &Apache::lonauth::loginhelpdisplay($authdomain);
                                        $authdomain,\$helpdeskscript,      if ($loginhelp) {
                                        $showhelpdesk,\@possdoms);          $loginhelp = '<a href="'.$loginhelp.'">'.$lt{'help'}.'</a><br />';
       }
     my $mobileargs;  
     if ($clientmobile) {  # ---------------------------------------------------- Serve out DES JavaScript
         $mobileargs = 'autocapitalize="off" autocorrect="off"';       {
     }      my $jsh=Apache::File->new($include."/londes.js");
     my $loginform=(<<LFORM);      $r->print(<$jsh>);
 <form name="client" action="" onsubmit="return(send())">      }
   <input type="hidden" name="lextkey" value="$lextkey" />  # ---------------------------------------------------------- Serve rest of page
   <input type="hidden" name="uextkey" value="$uextkey" />  
   <b><label for="uname">$lt{'un'}</label>:</b><br />      $r->print(
   <input type="text" name="uname" id="uname" size="15" value="$authusername" readonly="readonly" $mobileargs /><br />      '<div class="LC_Box"'
   <b><label for="upass$now">$lt{'pw'}</label>:</b><br />     .' style="margin:0 auto; padding:10px; width:90%; height: auto; background-color:#FFFFFF;">'
   <input type="password" name="upass$now" id="upass$now" size="15" readonly="readonly" /><br />  );
   <b><label for="udom">$lt{'dom'}</label>:</b><br />  
   <input type="text" name="udom" id="udom" size="15" value="$authdomain" readonly="readonly" $mobileargs /><br />      $r->print(<<ENDSERVERFORM);
   <input type="submit" value="$lt{'log'}" />  <form name="server" action="/adm/authenticate" method="post" target="_top">
 </form>     <input type="hidden" name="logtoken" value="$logtoken" />
 LFORM     <input type="hidden" name="serverid" value="$lonhost" />
      <input type="hidden" name="uname" value="" />
     if ($showbanner) {     <input type="hidden" name="upass0" value="" />
         $r->print(<<HEADER);     <input type="hidden" name="udom" value="" />
 <!-- The LON-CAPA Header -->     <input type="hidden" name="localpath" value="$env{'form.localpath'}" />
 <div style="background:$pgbg;margin:0;width:100%;">     <input type="hidden" name="localres" value="$env{'form.localres'}" />
   <img src="$img" border="0" alt="The Learning Online Network with CAPA" class="LC_maxwidth" />    </form>
 </div>  ENDSERVERFORM
 HEADER      my $coursecatalog;
     }      if (($showcoursecat eq '') || ($showcoursecat)) {
     $r->print(<<ENDTOP);          $coursecatalog = &coursecatalog_link($lt{'catalog'}).'<br />';
 <div style="float:left;margin-top:0;">      }
 <div class="LC_Box" style="background:$loginbox_bg;">      my $newuserlink;
   $logintitle      if ($shownewuserlink) {
   $loginform          $newuserlink = &newuser_link($lt{'newuser'}).'<br />';
   $noscript_warning      }
 </div>      my $logintitle =
             '<h2 class="LC_hcell"'
 <div class="LC_Box" style="padding-top: 10px;">         .' style="background:'.$loginbox_header_bgcol.';'
   $loginhelp         .' color:'.$loginbox_header_textcol.'">'
   $forgotpw         .$lt{'log'}
   $contactblock         .'</h2>';
   $newuserlink  
   $coursecatalog      my $noscript_warning='<noscript><span class="LC_warning"><b>'
 </div>                          .&mt('Use of LON-CAPA requires Javascript to be enabled in your web browser.')
 </div>                          .'</b></span></noscript>';
       my $helpdeskscript;
 <div>      my $contactblock = &contactdisplay(\%lt,$servadm,$showadminmail,
 ENDTOP                                         $authdomain,\$helpdeskscript,
     if ($showmainlogo) {                                         $showhelpdesk,\@possdoms);
         $r->print(' <img src="'.$logo.'" alt="" class="LC_maxwidth" />'."\n");  
     }      my $mobileargs;
 $r->print(<<ENDTOP);      if ($clientmobile) {
 $announcements          $mobileargs = 'autocapitalize="off" autocorrect="off"';
 </div>      }
 <hr style="clear:both;" />      my $loginform=(<<LFORM);
 ENDTOP  <form name="client" action="" onsubmit="return(send())">
     my ($domainrow,$serverrow,$loadrow,$userloadrow,$versionrow);    <input type="hidden" name="lextkey" value="$lextkey" />
     $domainrow = <<"END";    <input type="hidden" name="uextkey" value="$uextkey" />
       <tr>    <b><label for="uname">$lt{'un'}</label>:</b><br />
        <td  align="left" valign="top">    <input type="text" name="uname" id="uname" size="15" value="$authusername" readonly="readonly" $mobileargs /><br />
         <small><b>$lt{'dom'}:&nbsp;</b></small>    <b><label for="upass$now">$lt{'pw'}</label>:</b><br />
        </td>    <input type="password" name="upass$now" id="upass$now" size="15" readonly="readonly" /><br />
        <td  align="left" valign="top">    <b><label for="udom">$lt{'dom'}</label>:</b><br />
         <small><tt>&nbsp;$domain</tt></small>    <input type="text" name="udom" id="udom" size="15" value="$authdomain" readonly="readonly" $mobileargs /><br />
        </td>    <input type="submit" value="$lt{'log'}" />
       </tr>  </form>
 END  LFORM
     $serverrow = <<"END";  
       <tr>      if ($showbanner) {
        <td  align="left" valign="top">          $r->print(<<HEADER);
         <small><b>$lt{'serv'}:&nbsp;</b></small>  <!-- The LON-CAPA Header -->
        </td>  <div style="background:$pgbg;margin:0;width:100%;">
        <td align="left" valign="top">    <img src="$img" border="0" alt="The Learning Online Network with CAPA" class="LC_maxwidth" />
         <small><tt>&nbsp;$lonhost ($role)</tt></small>  </div>
        </td>  HEADER
       </tr>      }
 END      $r->print(<<ENDTOP);
     if ($loadlim) {  <div style="float:left;margin-top:0;">
         $loadrow = <<"END";  <div class="LC_Box" style="background:$loginbox_bg;">
       <tr>    $logintitle
        <td align="left" valign="top">    $loginform
         <small><b>$lt{'load'}:&nbsp;</b></small>    $noscript_warning
        </td>  </div>
        <td align="left" valign="top">   
         <small><tt>&nbsp;$loadpercent $lt{'perc'}</tt></small>  <div class="LC_Box" style="padding-top: 10px;">
        </td>    $loginhelp
       </tr>    $forgotpw
 END    $contactblock
     }    $newuserlink
     if ($uloadlim) {    $coursecatalog
         $userloadrow = <<"END";  </div>
       <tr>  </div>
        <td align="left" valign="top">  
         <small><b>$lt{'userload'}:&nbsp;</b></small>  <div>
        </td>  ENDTOP
        <td align="left" valign="top">      if ($showmainlogo) {
         <small><tt>&nbsp;$userloadpercent $lt{'perc'}</tt></small>          $r->print(' <img src="'.$logo.'" alt="" class="LC_maxwidth" />'."\n");
        </td>      }
       </tr>  $r->print(<<ENDTOP);
 END  $announcements
     }  </div>
     if (($version ne '') && ($version ne '<!-- VERSION -->')) {  <hr style="clear:both;" />
         $versionrow = <<"END";  ENDTOP
       <tr>      my ($domainrow,$serverrow,$loadrow,$userloadrow,$versionrow);
        <td colspan="2" align="left">      $domainrow = <<"END";
         <small>$version</small>        <tr>
        </td>         <td  align="left" valign="top">
       </tr>          <small><b>$lt{'dom'}:&nbsp;</b></small>
 END         </td>
     }         <td  align="left" valign="top">
           <small><tt>&nbsp;$domain</tt></small>
     $r->print(<<ENDDOCUMENT);         </td>
     <div style="float: left;">        </tr>
      <table border="0" cellspacing="0" cellpadding="0">  END
 $domainrow      $serverrow = <<"END";
 $serverrow        <tr>
 $loadrow             <td  align="left" valign="top">
 $userloadrow          <small><b>$lt{'serv'}:&nbsp;</b></small>
 $versionrow         </td>
      </table>         <td align="left" valign="top">
     </div>          <small><tt>&nbsp;$lonhost ($role)</tt></small>
     <div style="float: right;">         </td>
     $domainlogo        </tr>
     </div>  END
     <br style="clear:both;" />      if ($loadlim) {
  </div>          $loadrow = <<"END";
         <tr>
 <script type="text/javascript">         <td align="left" valign="top">
 // <![CDATA[          <small><b>$lt{'load'}:&nbsp;</b></small>
 // the if prevents the script error if the browser can not handle this         </td>
 if ( document.client.uname ) { document.client.uname.focus(); }         <td align="left" valign="top">
 // ]]>          <small><tt>&nbsp;$loadpercent $lt{'perc'}</tt></small>
 </script>         </td>
 $helpdeskscript        </tr>
   END
 ENDDOCUMENT      }
     my %endargs = ( 'noredirectlink' => 1, );      if ($uloadlim) {
     $r->print(&Apache::loncommon::end_page(\%endargs));          $userloadrow = <<"END";
     return OK;        <tr>
 }         <td align="left" valign="top">
           <small><b>$lt{'userload'}:&nbsp;</b></small>
 sub check_loginvia {         </td>
     my ($domain,$lonhost,$lonidsdir,$balcookie) = @_;         <td align="left" valign="top">
     if ($domain eq '' || $lonhost eq '' || $lonidsdir eq '') {          <small><tt>&nbsp;$userloadpercent $lt{'perc'}</tt></small>
         return;         </td>
     }        </tr>
     my %domconfhash = &Apache::loncommon::get_domainconf($domain);  END
     my $loginvia = $domconfhash{$domain.'.login.loginvia_'.$lonhost};      }
     my $loginvia_exempt = $domconfhash{$domain.'.login.loginvia_exempt_'.$lonhost};      if (($version ne '') && ($version ne '<!-- VERSION -->')) {
     my $output;          $versionrow = <<"END";
     if ($loginvia ne '') {        <tr>
         my $noredirect;         <td colspan="2" align="left">
         my $ip = $ENV{'REMOTE_ADDR'};          <small>$version</small>
         if ($ip eq '127.0.0.1') {         </td>
             $noredirect = 1;        </tr>
         } else {  END
             if ($loginvia_exempt ne '') {      }
                 my @exempt = split(',',$loginvia_exempt);  
                 if (grep(/^\Q$ip\E$/,@exempt)) {      $r->print(<<ENDDOCUMENT);
                     $noredirect = 1;      <div style="float: left;">
                 }       <table border="0" cellspacing="0" cellpadding="0">
             }  $domainrow
         }  $serverrow
         unless ($noredirect) {  $loadrow    
             my ($newhost,$path);  $userloadrow
             if ($loginvia =~ /:/) {  $versionrow
                 ($newhost,$path) = split(':',$loginvia);       </table>
             } else {      </div>
                 $newhost = $loginvia;      <div style="float: right;">
             }      $domainlogo
             if ($newhost ne $lonhost) {      </div>
                 if (&Apache::lonnet::hostname($newhost) ne '') {      <br style="clear:both;" />
                     if ($balcookie) {   </div>
                         my ($balancer,$cookie) = split(/:/,$balcookie);  
                         if ($cookie =~ /^($match_domain)_($match_username)_([a-f0-9]+)$/) {  <script type="text/javascript">
                             my ($udom,$uname,$cookieid) = ($1,$2,$3);  // <![CDATA[
                             unless (&Apache::lonnet::delbalcookie($cookie,$balancer) eq 'ok') {  // the if prevents the script error if the browser can not handle this
                                 if ((-d $lonidsdir) && (opendir(my $dh,$lonidsdir))) {  if ( document.client.uname ) { document.client.uname.focus(); }
                                     while (my $filename=readdir($dh)) {  // ]]>
                                         if ($filename=~/^(\Q$uname\E_\d+_\Q$udom\E_$match_lonid)\.id$/) {  </script>
                                             my $handle = $1;  $helpdeskscript
                                             my %hash =  
                                                 &Apache::lonnet::get_sessionfile_vars($handle,$lonidsdir,  ENDDOCUMENT
                                                                                      ['request.balancercookie',      my %endargs = ( 'noredirectlink' => 1, );
                                                                                       'user.linkedenv']);      $r->print(&Apache::loncommon::end_page(\%endargs));
                                             if ($hash{'request.balancercookie'} eq "$balancer:$cookieid") {      return OK;
                                                 if (unlink("$lonidsdir/$filename")) {  }
                                                     if (($hash{'user.linkedenv'} =~ /^[a-f0-9]+_linked$/) &&  
                                                         (-l "$lonidsdir/$hash{'user.linkedenv'}.id") &&  sub check_loginvia {
                                                         (readlink("$lonidsdir/$hash{'user.linkedenv'}.id") eq "$lonidsdir/$filename")) {      my ($domain,$lonhost,$lonidsdir,$balcookie,$linkprot) = @_;
                                                         unlink("$lonidsdir/$hash{'user.linkedenv'}.id");      if ($domain eq '' || $lonhost eq '' || $lonidsdir eq '') {
                                                     }          return;
                                                 }      }
                                             }      my %domconfhash = &Apache::loncommon::get_domainconf($domain);
                                             last;      my $loginvia = $domconfhash{$domain.'.login.loginvia_'.$lonhost};
                                         }      my $loginvia_exempt = $domconfhash{$domain.'.login.loginvia_exempt_'.$lonhost};
                                     }      my $output;
                                     closedir($dh);      if ($loginvia ne '') {
                                 }          my $noredirect;
                             }          my $ip = $ENV{'REMOTE_ADDR'};
                         }          if ($ip eq '127.0.0.1') {
                     }              $noredirect = 1;
                     $output = &redirect_page($newhost,$path);          } else {
                 }              if ($loginvia_exempt ne '') {
             }                  my @exempt = split(',',$loginvia_exempt);
         }                  if (grep(/^\Q$ip\E$/,@exempt)) {
     }                      $noredirect = 1;
     return $output;                  }
 }              }
           }
 sub redirect_page {          unless ($noredirect) {
     my ($desthost,$path) = @_;              my ($newhost,$path);
     my $hostname = &Apache::lonnet::hostname($desthost);              if ($loginvia =~ /:/) {
     my $protocol = $Apache::lonnet::protocol{$desthost};                  ($newhost,$path) = split(':',$loginvia);
     $protocol = 'http' if ($protocol ne 'https');              } else {
     unless ($path =~ m{^/}) {                  $newhost = $loginvia;
         $path = '/'.$path;              }
     }              if ($newhost ne $lonhost) {
     my $url = $protocol.'://'.$hostname.$path;                  if (&Apache::lonnet::hostname($newhost) ne '') {
     if ($env{'form.firsturl'} ne '') {                      if ($balcookie) {
         $url .='?firsturl='.$env{'form.firsturl'};                          my ($balancer,$cookie) = split(/:/,$balcookie);
     }                          if ($cookie =~ /^($match_domain)_($match_username)_([a-f0-9]+)$/) {
     my $start_page = &Apache::loncommon::start_page('Switching Server ...',undef,                              my ($udom,$uname,$cookieid) = ($1,$2,$3);
                                                     {'redirect' => [0,$url],});                              unless (&Apache::lonnet::delbalcookie($cookie,$balancer) eq 'ok') {
     my $end_page   = &Apache::loncommon::end_page();                                  if ((-d $lonidsdir) && (opendir(my $dh,$lonidsdir))) {
     return $start_page.$end_page;                                      while (my $filename=readdir($dh)) {
 }                                          if ($filename=~/^(\Q$uname\E_\d+_\Q$udom\E_$match_lonid)\.id$/) {
                                               my $handle = $1;
 sub contactdisplay {                                              my %hash =
     my ($lt,$servadm,$showadminmail,$authdomain,$helpdeskscript,$showhelpdesk,                                                  &Apache::lonnet::get_sessionfile_vars($handle,$lonidsdir,
         $possdoms) = @_;                                                                                       ['request.balancercookie',
     my $contactblock;                                                                                        'user.linkedenv']);
     my $origmail;                                              if ($hash{'request.balancercookie'} eq "$balancer:$cookieid") {
     if (ref($possdoms) eq 'ARRAY') {                                                  if (unlink("$lonidsdir/$filename")) {
         if (grep(/^\Q$authdomain\E$/,@{$possdoms})) {                                                       if (($hash{'user.linkedenv'} =~ /^[a-f0-9]+_linked$/) &&
             $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};                                                          (-l "$lonidsdir/$hash{'user.linkedenv'}.id") &&
         }                                                          (readlink("$lonidsdir/$hash{'user.linkedenv'}.id") eq "$lonidsdir/$filename")) {
     }                                                          unlink("$lonidsdir/$hash{'user.linkedenv'}.id");
     my $requestmail =                                                       }
         &Apache::loncommon::build_recipient_list(undef,'helpdeskmail',                                                  }
                                                  $authdomain,$origmail);                                              }
     unless ($showhelpdesk eq '0') {                                              last;
         if ($requestmail =~ m/[^\@]+\@[^\@]+/) {                                          }
             $showhelpdesk = 1;                                      }
         } else {                                      closedir($dh);
             $showhelpdesk = 0;                                  }
         }                              }
     }                          }
     if ($servadm && $showadminmail) {                      }
         $contactblock .= $$lt{'servadm'}.':<br />'.                      $output = &redirect_page($newhost,$path,$linkprot);
                          '<tt>'.$servadm.'</tt><br />';                  }
     }              }
     if ($showhelpdesk) {          }
         $contactblock .= '<a href="javascript:helpdesk()">'.$lt->{'helpdesk'}.'</a><br />';      }
         my $thisurl = &escape('/adm/login');      return $output;
         $$helpdeskscript = <<"ENDSCRIPT";  }
 <script type="text/javascript">  
 // <![CDATA[  sub redirect_page {
 function helpdesk() {      my ($desthost,$path,$linkprot) = @_;
     var possdom = document.client.udom.value;      my $protocol = $Apache::lonnet::protocol{$desthost};
     var codedom = possdom.replace( new RegExp("[^A-Za-z0-9.\\-]","g"),'');      $protocol = 'http' if ($protocol ne 'https');
     if (codedom == '') {      unless ($path =~ m{^/}) {
         codedom = "$authdomain";          $path = '/'.$path;
     }      }
     var querystr = "origurl=$thisurl&codedom="+codedom;      my $url = $protocol.'://'.&Apache::lonnet::hostname($desthost).$path;
     document.location.href = "/adm/helpdesk?"+querystr;      if ($env{'form.firsturl'} ne '') {
     return;          $url .='?firsturl='.$env{'form.firsturl'};
 }      }
 // ]]>      if ($linkprot) {
 </script>          my $ltoken = &Apache::lonnet::tmpput({linkprot => $linkprot},$desthost);
 ENDSCRIPT          if ($ltoken) {
     }              $url .= (($url =~ /\?/) ? '&' : '?').'ltoken='.$ltoken;
     return $contactblock;          }
 }      }
       my $start_page = &Apache::loncommon::start_page('Switching Server ...',undef,
 sub forgotpwdisplay {                                                      {'redirect' => [0,$url],});
     my (%lt) = @_;      my $end_page   = &Apache::loncommon::end_page();
     my $prompt_for_resetpw = 1;       return $start_page.$end_page;
     if ($prompt_for_resetpw) {  }
         return '<a href="/adm/resetpw">'.$lt{'forgotpw'}.'</a>';  
     }  sub contactdisplay {
     return;      my ($lt,$servadm,$showadminmail,$authdomain,$helpdeskscript,$showhelpdesk,
 }          $possdoms) = @_;
       my $contactblock;
 sub coursecatalog_link {      my $origmail;
     my ($linkname) = @_;      if (ref($possdoms) eq 'ARRAY') {
     return <<"END";          if (grep(/^\Q$authdomain\E$/,@{$possdoms})) {
       <a href="/adm/coursecatalog">$linkname</a>              $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};
 END          }
 }      }
       my $requestmail =
 sub newuser_link {          &Apache::loncommon::build_recipient_list(undef,'helpdeskmail',
     my ($linkname) = @_;                                                   $authdomain,$origmail);
     return '<a href="/adm/createaccount">'.$linkname.'</a>';      unless ($showhelpdesk eq '0') {
 }          if ($requestmail =~ m/[^\@]+\@[^\@]+/) {
               $showhelpdesk = 1;
 1;          } else {
 __END__              $showhelpdesk = 0;
           }
       }
       if ($servadm && $showadminmail) {
           $contactblock .= $$lt{'servadm'}.':<br />'.
                            '<tt>'.$servadm.'</tt><br />';
       }
       if ($showhelpdesk) {
           $contactblock .= '<a href="javascript:helpdesk()">'.$lt->{'helpdesk'}.'</a><br />';
           my $thisurl = &escape('/adm/login');
           $$helpdeskscript = <<"ENDSCRIPT";
   <script type="text/javascript">
   // <![CDATA[
   function helpdesk() {
       var possdom = document.client.udom.value;
       var codedom = possdom.replace( new RegExp("[^A-Za-z0-9.\\-]","g"),'');
       if (codedom == '') {
           codedom = "$authdomain";
       }
       var querystr = "origurl=$thisurl&codedom="+codedom;
       document.location.href = "/adm/helpdesk?"+querystr;
       return;
   }
   // ]]>
   </script>
   ENDSCRIPT
       }
       return $contactblock;
   }
   
   sub forgotpwdisplay {
       my (%lt) = @_;
       my $prompt_for_resetpw = 1;
       if ($prompt_for_resetpw) {
           return '<a href="/adm/resetpw">'.$lt{'forgotpw'}.'</a>';
       }
       return;
   }
   
   sub coursecatalog_link {
       my ($linkname) = @_;
       return <<"END";
         <a href="/adm/coursecatalog">$linkname</a>
   END
   }
   
   sub newuser_link {
       my ($linkname) = @_;
       return '<a href="/adm/createaccount">'.$linkname.'</a>';
   }
   
   1;
   __END__

Removed from v.1.158.2.10  
changed lines
  Added in v.1.177


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