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

version 1.158.2.11, 2020/10/26 02:00:13 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'});
             $spareservers{$hostname} = 1;          }
             my $protocol = $Apache::lonnet::protocol{$hostid};      }
             $protocol = 'http' if ($protocol ne 'https');      my $logtoken=Apache::lonnet::reply(
             $spares.='<br /><a href="'.$protocol.'://'.         'tmpput:'.$ukey.$lkey.'&'.$firsturl.$tokenextras,
              $hostname.         $lonhost);
              '/adm/login?domain='.$authdomain.'">'.  
              $hostname.'</a>';  # -- If we cannot talk to ourselves, or hostID does not map to a hostname
          }  #    we are in serious trouble
          $r->print(  
    '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'      if (($logtoken eq 'con_lost') || ($logtoken eq 'no_such_host')) {
   .'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'          if ($logtoken eq 'no_such_host') {
   .'<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>'              &Apache::lonnet::logthis('No valid logtoken for log-in page -- unable to determine hostname for hostID: '.$lonhost.'. Check entry in hosts.tab');
   .&mt('The LearningOnline Network with CAPA')          }
   .'</title></head>'          my $spares='';
   .'<body bgcolor="#FFFFFF">'   my $last;
   .'<h1>'.&mt('The LearningOnline Network with CAPA').'</h1>'          foreach my $hostid (sort
   .'<img src="/adm/lonKaputt/lonlogo_broken.gif" alt="broken icon" align="right" />'      {
   .'<h3>'.&mt('This LON-CAPA server is temporarily not available for login.').'</h3>');   &Apache::lonnet::hostname($a) cmp
         if ($spares) {      &Apache::lonnet::hostname($b);
             $r->print('<p>'.&mt('Please attempt to login to one of the following servers:')      }
                      .'</p>'      keys(%Apache::lonnet::spareid)) {
                      .$spares);              next if ($hostid eq $lonhost);
         }      my $hostname = &Apache::lonnet::hostname($hostid);
         $r->print('</body>'      next if (($last eq $hostname) || ($hostname eq ''));
                  .'</html>'              $spares.='<br /><font size="+1"><a href="http://'.
         );                  $hostname.
         return OK;                  '/adm/login?domain='.$authdomain.'">'.
     }                  $hostname.'</a>'.
                   ' '.&mt('(preferred)').'</font>'.$/;
 # ----------------------------------------------- Apparently we are in business      $last=$hostname;
     $servadm=~s/\,/\<br \/\>/g;          }
           if ($spares) {
 # ----------------------------------------------------------- Front page design              $spares.= '<br />';
     my $pgbg=&Apache::loncommon::designparm('login.pgbg',$domain);          }
     my $font=&Apache::loncommon::designparm('login.font',$domain);          my %all_hostnames = &Apache::lonnet::all_hostnames();
     my $link=&Apache::loncommon::designparm('login.link',$domain);          foreach my $hostid (sort
     my $vlink=&Apache::loncommon::designparm('login.vlink',$domain);      {
     my $alink=&Apache::loncommon::designparm('login.alink',$domain);   &Apache::lonnet::hostname($a) cmp
     my $mainbg=&Apache::loncommon::designparm('login.mainbg',$domain);      &Apache::lonnet::hostname($b);
     my $loginbox_bg=&Apache::loncommon::designparm('login.sidebg',$domain);      }
     my $loginbox_header_bgcol=&Apache::loncommon::designparm('login.bgcol',$domain);      keys(%all_hostnames)) {
     my $loginbox_header_textcol=&Apache::loncommon::designparm('login.textcol',$domain);              next if ($hostid eq $lonhost || $Apache::lonnet::spareid{$hostid});
     my $logo=&Apache::loncommon::designparm('login.logo',$domain);              my $hostname = &Apache::lonnet::hostname($hostid);
     my $img=&Apache::loncommon::designparm('login.img',$domain);              next if (($last eq $hostname) || ($hostname eq ''));
     my $domainlogo=&Apache::loncommon::domainlogo($domain);              $spares.='<br /><a href="http://'.
     my $showbanner = 1;               $hostname.
     my $showmainlogo = 1;               '/adm/login?domain='.$authdomain.'">'.
     if (defined(&Apache::loncommon::designparm('login.showlogo_img',$domain))) {               $hostname.'</a>';
         $showbanner = &Apache::loncommon::designparm('login.showlogo_img',$domain);              $last=$hostname;
     }           }
     if (defined(&Apache::loncommon::designparm('login.showlogo_logo',$domain))) {           $r->print(
         $showmainlogo = &Apache::loncommon::designparm('login.showlogo_logo',$domain);     '<html>'
     }    .'<head><title>'
     my $showadminmail;    .&mt('The LearningOnline Network with CAPA')
     my @possdoms = &Apache::lonnet::current_machine_domains();    .'</title></head>'
     if (grep(/^\Q$domain\E$/,@possdoms)) {    .'<body bgcolor="#FFFFFF">'
         $showadminmail=&Apache::loncommon::designparm('login.adminmail',$domain);    .'<h1>'.&mt('The LearningOnline Network with CAPA').'</h1>'
     }    .'<img src="/adm/lonKaputt/lonlogo_broken.gif" align="right" />'
     my $showcoursecat =    .'<h3>'.&mt('This LON-CAPA server is temporarily not available for login.').'</h3>');
         &Apache::loncommon::designparm('login.coursecatalog',$domain);          if ($spares) {
     my $shownewuserlink =               $r->print('<p>'.&mt('Please attempt to login to one of the following servers:')
         &Apache::loncommon::designparm('login.newuser',$domain);                       .'</p>'
     my $showhelpdesk =                       .$spares);
         &Apache::loncommon::designparm('login.helpdesk',$domain);          }
     my $now=time;          $r->print('</body>'
     my $js = (<<ENDSCRIPT);                   .'</html>'
           );
 <script type="text/javascript" language="JavaScript">          return OK;
 // <![CDATA[      }
 function send()  
 {  # ----------------------------------------------- Apparently we are in business
 this.document.server.elements.uname.value      $servadm=~s/\,/\<br \/\>/g;
 =this.document.client.elements.uname.value;  
   # ----------------------------------------------------------- Front page design
 this.document.server.elements.udom.value      my $pgbg=&Apache::loncommon::designparm('login.pgbg',$domain);
 =this.document.client.elements.udom.value;      my $font=&Apache::loncommon::designparm('login.font',$domain);
       my $link=&Apache::loncommon::designparm('login.link',$domain);
 uextkey=this.document.client.elements.uextkey.value;      my $vlink=&Apache::loncommon::designparm('login.vlink',$domain);
 lextkey=this.document.client.elements.lextkey.value;      my $alink=&Apache::loncommon::designparm('login.alink',$domain);
 initkeys();      my $mainbg=&Apache::loncommon::designparm('login.mainbg',$domain);
       my $loginbox_bg=&Apache::loncommon::designparm('login.sidebg',$domain);
 this.document.server.elements.upass0.value      my $loginbox_header_bgcol=&Apache::loncommon::designparm('login.bgcol',$domain);
     =getCrypted(this.document.client.elements.upass$now.value);      my $loginbox_header_textcol=&Apache::loncommon::designparm('login.textcol',$domain);
       my $logo=&Apache::loncommon::designparm('login.logo',$domain);
 this.document.client.elements.uname.value='';      my $img=&Apache::loncommon::designparm('login.img',$domain);
 this.document.client.elements.upass$now.value='';      my $domainlogo=&Apache::loncommon::domainlogo($domain);
       my $showbanner = 1;
 this.document.server.submit();      my $showmainlogo = 1;
 return false;      if (defined(&Apache::loncommon::designparm('login.showlogo_img',$domain))) {
 }          $showbanner = &Apache::loncommon::designparm('login.showlogo_img',$domain);
       }
 function enableInput() {      if (defined(&Apache::loncommon::designparm('login.showlogo_logo',$domain))) {
     this.document.client.elements.upass$now.removeAttribute("readOnly");          $showmainlogo = &Apache::loncommon::designparm('login.showlogo_logo',$domain);
     this.document.client.elements.uname.removeAttribute("readOnly");      }
     this.document.client.elements.udom.removeAttribute("readOnly");      my $showadminmail;
     return;      my @possdoms = &Apache::lonnet::current_machine_domains();
 }      if (grep(/^\Q$domain\E$/,@possdoms)) {
           $showadminmail=&Apache::loncommon::designparm('login.adminmail',$domain);
 // ]]>      }
 </script>      my $showcoursecat =
           &Apache::loncommon::designparm('login.coursecatalog',$domain);
 ENDSCRIPT      my $shownewuserlink =
           &Apache::loncommon::designparm('login.newuser',$domain);
 # --------------------------------------------------- Print login screen header      my $showhelpdesk =
           &Apache::loncommon::designparm('login.helpdesk',$domain);
     my %add_entries = (      my $now=time;
        bgcolor      => "$mainbg",      my $js = (<<ENDSCRIPT);
        text         => "$font",  
        link         => "$link",  <script type="text/javascript" language="JavaScript">
        vlink        => "$vlink",  // <![CDATA[
        alink        => "$alink",  function send()
                onload       => 'javascript:enableInput();',);  {
   this.document.server.elements.uname.value
     my ($lonhost_in_use,$headextra,$headextra_exempt,@hosts,%defaultdomconf);  =this.document.client.elements.uname.value;
     @hosts = &Apache::lonnet::current_machine_ids();  
     $lonhost_in_use = $lonhost;  this.document.server.elements.udom.value
     if (@hosts > 1) {  =this.document.client.elements.udom.value;
         foreach my $hostid (@hosts) {  
             if (&Apache::lonnet::host_domain($hostid) eq $defdom) {  uextkey=this.document.client.elements.uextkey.value;
                 $lonhost_in_use = $hostid;  lextkey=this.document.client.elements.lextkey.value;
                 last;  initkeys();
             }  
         }  if(this.document.server.action.substr(0,5) === 'http:'){
     }      this.document.server.elements.upass0.value
     %defaultdomconf = &Apache::loncommon::get_domainconf($defdom);          =getCrypted(this.document.client.elements.upass$now.value);
     $headextra = $defaultdomconf{$defdom.'.login.headtag_'.$lonhost_in_use};  } else {
     $headextra_exempt = $defaultdomconf{$domain.'.login.headtag_exempt_'.$lonhost_in_use};      this.document.server.elements.upass0.value
     if ($headextra) {          =this.document.client.elements.upass$now.value;
         my $omitextra;  }
         if ($headextra_exempt ne '') {  
             my @exempt = split(',',$headextra_exempt);  this.document.client.elements.uname.value='';
             my $ip = $ENV{'REMOTE_ADDR'};  this.document.client.elements.upass$now.value='';
             if (grep(/^\Q$ip\E$/,@exempt)) {  
                 $omitextra = 1;  this.document.server.submit();
             }  return false;
         }  }
         unless ($omitextra) {  
             my $confname = $defdom.'-domainconfig';  function enableInput() {
             if ($headextra =~ m{^\Q/res/$defdom/$confname/login/headtag/$lonhost_in_use/\E}) {      this.document.client.elements.upass$now.removeAttribute("readOnly");
                 my $extra = &Apache::lonnet::getfile(&Apache::lonnet::filelocation("",$headextra));      this.document.client.elements.uname.removeAttribute("readOnly");
                 unless ($extra eq '-1') {      this.document.client.elements.udom.removeAttribute("readOnly");
                     $js .= "\n".$extra."\n";      return;
                 }  }
             }  
         }  // ]]>
     }  </script>
   
     $r->print(&Apache::loncommon::start_page('The LearningOnline Network with CAPA Login',$js,  ENDSCRIPT
        { 'redirect'       => [$expire,'/adm/roles'],   
  'add_entries' => \%add_entries,  # --------------------------------------------------- Print login screen header
  'only_body'   => 1,}));  
       my %add_entries = (
 # ----------------------------------------------------------------------- Texts         bgcolor      => "$mainbg",
          text         => "$font",
     my %lt=&Apache::lonlocal::texthash(         link         => "$link",
           'un'       => 'Username',         vlink        => "$vlink",
           'pw'       => 'Password',         alink        => "$alink",
           'dom'      => 'Domain',                 onload       => 'javascript:enableInput();',);
           'perc'     => 'percent',  
           'load'     => 'Server Load',      my ($lonhost_in_use,$headextra,$headextra_exempt,@hosts,%defaultdomconf);
           'userload' => 'User Load',      @hosts = &Apache::lonnet::current_machine_ids();
           'catalog'  => 'Course/Community Catalog',      $lonhost_in_use = $lonhost;
           'log'      => 'Log in',      if (@hosts > 1) {
           'help'     => 'Log-in Help',          foreach my $hostid (@hosts) {
           'serv'     => 'Server',              if (&Apache::lonnet::host_domain($hostid) eq $defdom) {
           'servadm'  => 'Server Administration',                  $lonhost_in_use = $hostid;
           'helpdesk' => 'Contact Helpdesk',                  last;
           'forgotpw' => 'Forgot password?',              }
           'newuser'  => 'New User?',          }
        );      }
 # -------------------------------------------------- Change password field name      %defaultdomconf = &Apache::loncommon::get_domainconf($defdom);
       $headextra = $defaultdomconf{$defdom.'.login.headtag_'.$lonhost_in_use};
     my $forgotpw = &forgotpwdisplay(%lt);      $headextra_exempt = $defaultdomconf{$domain.'.login.headtag_exempt_'.$lonhost_in_use};
     $forgotpw .= '<br />' if $forgotpw;      if ($headextra) {
     my $loginhelp = &Apache::lonauth::loginhelpdisplay($authdomain);          my $omitextra;
     if ($loginhelp) {          if ($headextra_exempt ne '') {
         $loginhelp = '<a href="'.$loginhelp.'">'.$lt{'help'}.'</a><br />';              my @exempt = split(',',$headextra_exempt);
     }              my $ip = $ENV{'REMOTE_ADDR'};
               if (grep(/^\Q$ip\E$/,@exempt)) {
 # ---------------------------------------------------- Serve out DES JavaScript                  $omitextra = 1;
     {              }
     my $jsh=Apache::File->new($include."/londes.js");          }
     $r->print(<$jsh>);          unless ($omitextra) {
     }              my $confname = $defdom.'-domainconfig';
 # ---------------------------------------------------------- Serve rest of page              if ($headextra =~ m{^\Q/res/$defdom/$confname/login/headtag/$lonhost_in_use/\E}) {
                   my $extra = &Apache::lonnet::getfile(&Apache::lonnet::filelocation("",$headextra));
     $r->print(                  unless ($extra eq '-1') {
     '<div class="LC_Box"'                      $js .= "\n".$extra."\n";
    .' style="margin:0 auto; padding:10px; width:90%; height: auto; background-color:#FFFFFF;">'                  }
 );              }
           }
     $r->print(<<ENDSERVERFORM);      }
 <form name="server" action="/adm/authenticate" method="post" target="_top">  
    <input type="hidden" name="logtoken" value="$logtoken" />      $r->print(&Apache::loncommon::start_page('The LearningOnline Network with CAPA Login',$js,
    <input type="hidden" name="serverid" value="$lonhost" />         { 'redirect'       => [$expire,'/adm/roles'],
    <input type="hidden" name="uname" value="" />   'add_entries' => \%add_entries,
    <input type="hidden" name="upass0" value="" />   'only_body'   => 1,}));
    <input type="hidden" name="udom" value="" />  
    <input type="hidden" name="localpath" value="$env{'form.localpath'}" />  # ----------------------------------------------------------------------- Texts
    <input type="hidden" name="localres" value="$env{'form.localres'}" />  
   </form>      my %lt=&Apache::lonlocal::texthash(
 ENDSERVERFORM            'un'       => 'Username',
     my $coursecatalog;            'pw'       => 'Password',
     if (($showcoursecat eq '') || ($showcoursecat)) {            'dom'      => 'Domain',
         $coursecatalog = &coursecatalog_link($lt{'catalog'}).'<br />';            'perc'     => 'percent',
     }            'load'     => 'Server Load',
     my $newuserlink;            'userload' => 'User Load',
     if ($shownewuserlink) {            'catalog'  => 'Course/Community Catalog',
         $newuserlink = &newuser_link($lt{'newuser'}).'<br />';            'log'      => 'Log in',
     }            'help'     => 'Log-in Help',
     my $logintitle =            'serv'     => 'Server',
         '<h2 class="LC_hcell"'            'servadm'  => 'Server Administration',
        .' style="background:'.$loginbox_header_bgcol.';'            'helpdesk' => 'Contact Helpdesk',
        .' color:'.$loginbox_header_textcol.'">'            'forgotpw' => 'Forgot password?',
        .$lt{'log'}            'newuser'  => 'New User?',
        .'</h2>';         );
   # -------------------------------------------------- Change password field name
     my $noscript_warning='<noscript><span class="LC_warning"><b>'  
                         .&mt('Use of LON-CAPA requires Javascript to be enabled in your web browser.')      my $forgotpw = &forgotpwdisplay(%lt);
                         .'</b></span></noscript>';      $forgotpw .= '<br />' if $forgotpw;
     my $helpdeskscript;      my $loginhelp = &Apache::lonauth::loginhelpdisplay($authdomain);
     my $contactblock = &contactdisplay(\%lt,$servadm,$showadminmail,      if ($loginhelp) {
                                        $authdomain,\$helpdeskscript,          $loginhelp = '<a href="'.$loginhelp.'">'.$lt{'help'}.'</a><br />';
                                        $showhelpdesk,\@possdoms);      }
   
     my $mobileargs;  # ---------------------------------------------------- Serve out DES JavaScript
     if ($clientmobile) {      {
         $mobileargs = 'autocapitalize="off" autocorrect="off"';       my $jsh=Apache::File->new($include."/londes.js");
     }      $r->print(<$jsh>);
     my $loginform=(<<LFORM);      }
 <form name="client" action="" onsubmit="return(send())">  # ---------------------------------------------------------- Serve rest of page
   <input type="hidden" name="lextkey" value="$lextkey" />  
   <input type="hidden" name="uextkey" value="$uextkey" />      $r->print(
   <b><label for="uname">$lt{'un'}</label>:</b><br />      '<div class="LC_Box"'
   <input type="text" name="uname" id="uname" size="15" value="$authusername" readonly="readonly" $mobileargs /><br />     .' style="margin:0 auto; padding:10px; width:90%; height: auto; background-color:#FFFFFF;">'
   <b><label for="upass$now">$lt{'pw'}</label>:</b><br />  );
   <input type="password" name="upass$now" id="upass$now" size="15" readonly="readonly" /><br />  
   <b><label for="udom">$lt{'dom'}</label>:</b><br />      $r->print(<<ENDSERVERFORM);
   <input type="text" name="udom" id="udom" size="15" value="$authdomain" readonly="readonly" $mobileargs /><br />  <form name="server" action="/adm/authenticate" method="post" target="_top">
   <input type="submit" value="$lt{'log'}" />     <input type="hidden" name="logtoken" value="$logtoken" />
 </form>     <input type="hidden" name="serverid" value="$lonhost" />
 LFORM     <input type="hidden" name="uname" value="" />
      <input type="hidden" name="upass0" value="" />
     if ($showbanner) {     <input type="hidden" name="udom" value="" />
         $r->print(<<HEADER);     <input type="hidden" name="localpath" value="$env{'form.localpath'}" />
 <!-- The LON-CAPA Header -->     <input type="hidden" name="localres" value="$env{'form.localres'}" />
 <div style="background:$pgbg;margin:0;width:100%;">    </form>
   <img src="$img" border="0" alt="The Learning Online Network with CAPA" class="LC_maxwidth" />  ENDSERVERFORM
 </div>      my $coursecatalog;
 HEADER      if (($showcoursecat eq '') || ($showcoursecat)) {
     }          $coursecatalog = &coursecatalog_link($lt{'catalog'}).'<br />';
     $r->print(<<ENDTOP);      }
 <div style="float:left;margin-top:0;">      my $newuserlink;
 <div class="LC_Box" style="background:$loginbox_bg;">      if ($shownewuserlink) {
   $logintitle          $newuserlink = &newuser_link($lt{'newuser'}).'<br />';
   $loginform      }
   $noscript_warning      my $logintitle =
 </div>          '<h2 class="LC_hcell"'
            .' style="background:'.$loginbox_header_bgcol.';'
 <div class="LC_Box" style="padding-top: 10px;">         .' color:'.$loginbox_header_textcol.'">'
   $loginhelp         .$lt{'log'}
   $forgotpw         .'</h2>';
   $contactblock  
   $newuserlink      my $noscript_warning='<noscript><span class="LC_warning"><b>'
   $coursecatalog                          .&mt('Use of LON-CAPA requires Javascript to be enabled in your web browser.')
 </div>                          .'</b></span></noscript>';
 </div>      my $helpdeskscript;
       my $contactblock = &contactdisplay(\%lt,$servadm,$showadminmail,
 <div>                                         $authdomain,\$helpdeskscript,
 ENDTOP                                         $showhelpdesk,\@possdoms);
     if ($showmainlogo) {  
         $r->print(' <img src="'.$logo.'" alt="" class="LC_maxwidth" />'."\n");      my $mobileargs;
     }      if ($clientmobile) {
 $r->print(<<ENDTOP);          $mobileargs = 'autocapitalize="off" autocorrect="off"';
 $announcements      }
 </div>      my $loginform=(<<LFORM);
 <hr style="clear:both;" />  <form name="client" action="" onsubmit="return(send())">
 ENDTOP    <input type="hidden" name="lextkey" value="$lextkey" />
     my ($domainrow,$serverrow,$loadrow,$userloadrow,$versionrow);    <input type="hidden" name="uextkey" value="$uextkey" />
     $domainrow = <<"END";    <b><label for="uname">$lt{'un'}</label>:</b><br />
       <tr>    <input type="text" name="uname" id="uname" size="15" value="$authusername" readonly="readonly" $mobileargs /><br />
        <td  align="left" valign="top">    <b><label for="upass$now">$lt{'pw'}</label>:</b><br />
         <small><b>$lt{'dom'}:&nbsp;</b></small>    <input type="password" name="upass$now" id="upass$now" size="15" readonly="readonly" /><br />
        </td>    <b><label for="udom">$lt{'dom'}</label>:</b><br />
        <td  align="left" valign="top">    <input type="text" name="udom" id="udom" size="15" value="$authdomain" readonly="readonly" $mobileargs /><br />
         <small><tt>&nbsp;$domain</tt></small>    <input type="submit" value="$lt{'log'}" />
        </td>  </form>
       </tr>  LFORM
 END  
     $serverrow = <<"END";      if ($showbanner) {
       <tr>          $r->print(<<HEADER);
        <td  align="left" valign="top">  <!-- The LON-CAPA Header -->
         <small><b>$lt{'serv'}:&nbsp;</b></small>  <div style="background:$pgbg;margin:0;width:100%;">
        </td>    <img src="$img" border="0" alt="The Learning Online Network with CAPA" class="LC_maxwidth" />
        <td align="left" valign="top">  </div>
         <small><tt>&nbsp;$lonhost ($role)</tt></small>  HEADER
        </td>      }
       </tr>      $r->print(<<ENDTOP);
 END  <div style="float:left;margin-top:0;">
     if ($loadlim) {  <div class="LC_Box" style="background:$loginbox_bg;">
         $loadrow = <<"END";    $logintitle
       <tr>    $loginform
        <td align="left" valign="top">    $noscript_warning
         <small><b>$lt{'load'}:&nbsp;</b></small>  </div>
        </td>   
        <td align="left" valign="top">  <div class="LC_Box" style="padding-top: 10px;">
         <small><tt>&nbsp;$loadpercent $lt{'perc'}</tt></small>    $loginhelp
        </td>    $forgotpw
       </tr>    $contactblock
 END    $newuserlink
     }    $coursecatalog
     if ($uloadlim) {  </div>
         $userloadrow = <<"END";  </div>
       <tr>  
        <td align="left" valign="top">  <div>
         <small><b>$lt{'userload'}:&nbsp;</b></small>  ENDTOP
        </td>      if ($showmainlogo) {
        <td align="left" valign="top">          $r->print(' <img src="'.$logo.'" alt="" class="LC_maxwidth" />'."\n");
         <small><tt>&nbsp;$userloadpercent $lt{'perc'}</tt></small>      }
        </td>  $r->print(<<ENDTOP);
       </tr>  $announcements
 END  </div>
     }  <hr style="clear:both;" />
     if (($version ne '') && ($version ne '<!-- VERSION -->')) {  ENDTOP
         $versionrow = <<"END";      my ($domainrow,$serverrow,$loadrow,$userloadrow,$versionrow);
       <tr>      $domainrow = <<"END";
        <td colspan="2" align="left">        <tr>
         <small>$version</small>         <td  align="left" valign="top">
        </td>          <small><b>$lt{'dom'}:&nbsp;</b></small>
       </tr>         </td>
 END         <td  align="left" valign="top">
     }          <small><tt>&nbsp;$domain</tt></small>
          </td>
     $r->print(<<ENDDOCUMENT);        </tr>
     <div style="float: left;">  END
      <table border="0" cellspacing="0" cellpadding="0">      $serverrow = <<"END";
 $domainrow        <tr>
 $serverrow         <td  align="left" valign="top">
 $loadrow              <small><b>$lt{'serv'}:&nbsp;</b></small>
 $userloadrow         </td>
 $versionrow         <td align="left" valign="top">
      </table>          <small><tt>&nbsp;$lonhost ($role)</tt></small>
     </div>         </td>
     <div style="float: right;">        </tr>
     $domainlogo  END
     </div>      if ($loadlim) {
     <br style="clear:both;" />          $loadrow = <<"END";
  </div>        <tr>
          <td align="left" valign="top">
 <script type="text/javascript">          <small><b>$lt{'load'}:&nbsp;</b></small>
 // <![CDATA[         </td>
 // the if prevents the script error if the browser can not handle this         <td align="left" valign="top">
 if ( document.client.uname ) { document.client.uname.focus(); }          <small><tt>&nbsp;$loadpercent $lt{'perc'}</tt></small>
 // ]]>         </td>
 </script>        </tr>
 $helpdeskscript  END
       }
 ENDDOCUMENT      if ($uloadlim) {
     my %endargs = ( 'noredirectlink' => 1, );          $userloadrow = <<"END";
     $r->print(&Apache::loncommon::end_page(\%endargs));        <tr>
     return OK;         <td align="left" valign="top">
 }          <small><b>$lt{'userload'}:&nbsp;</b></small>
          </td>
 sub check_loginvia {         <td align="left" valign="top">
     my ($domain,$lonhost,$lonidsdir,$balcookie) = @_;          <small><tt>&nbsp;$userloadpercent $lt{'perc'}</tt></small>
     if ($domain eq '' || $lonhost eq '' || $lonidsdir eq '') {         </td>
         return;        </tr>
     }  END
     my %domconfhash = &Apache::loncommon::get_domainconf($domain);      }
     my $loginvia = $domconfhash{$domain.'.login.loginvia_'.$lonhost};      if (($version ne '') && ($version ne '<!-- VERSION -->')) {
     my $loginvia_exempt = $domconfhash{$domain.'.login.loginvia_exempt_'.$lonhost};          $versionrow = <<"END";
     my $output;        <tr>
     if ($loginvia ne '') {         <td colspan="2" align="left">
         my $noredirect;          <small>$version</small>
         my $ip = $ENV{'REMOTE_ADDR'};         </td>
         if ($ip eq '127.0.0.1') {        </tr>
             $noredirect = 1;  END
         } else {      }
             if ($loginvia_exempt ne '') {  
                 my @exempt = split(',',$loginvia_exempt);      $r->print(<<ENDDOCUMENT);
                 if (grep(/^\Q$ip\E$/,@exempt)) {      <div style="float: left;">
                     $noredirect = 1;       <table border="0" cellspacing="0" cellpadding="0">
                 }  $domainrow
             }  $serverrow
         }  $loadrow    
         unless ($noredirect) {  $userloadrow
             my ($newhost,$path);  $versionrow
             if ($loginvia =~ /:/) {       </table>
                 ($newhost,$path) = split(':',$loginvia);      </div>
             } else {      <div style="float: right;">
                 $newhost = $loginvia;      $domainlogo
             }      </div>
             if ($newhost ne $lonhost) {      <br style="clear:both;" />
                 if (&Apache::lonnet::hostname($newhost) ne '') {   </div>
                     if ($balcookie) {  
                         my ($balancer,$cookie) = split(/:/,$balcookie);  <script type="text/javascript">
                         if ($cookie =~ /^($match_domain)_($match_username)_([a-f0-9]+)$/) {  // <![CDATA[
                             my ($udom,$uname,$cookieid) = ($1,$2,$3);  // the if prevents the script error if the browser can not handle this
                             unless (&Apache::lonnet::delbalcookie($cookie,$balancer) eq 'ok') {  if ( document.client.uname ) { document.client.uname.focus(); }
                                 if ((-d $lonidsdir) && (opendir(my $dh,$lonidsdir))) {  // ]]>
                                     while (my $filename=readdir($dh)) {  </script>
                                         if ($filename=~/^(\Q$uname\E_\d+_\Q$udom\E_$match_lonid)\.id$/) {  $helpdeskscript
                                             my $handle = $1;  
                                             my %hash =  ENDDOCUMENT
                                                 &Apache::lonnet::get_sessionfile_vars($handle,$lonidsdir,      my %endargs = ( 'noredirectlink' => 1, );
                                                                                      ['request.balancercookie',      $r->print(&Apache::loncommon::end_page(\%endargs));
                                                                                       'user.linkedenv']);      return OK;
                                             if ($hash{'request.balancercookie'} eq "$balancer:$cookieid") {  }
                                                 if (unlink("$lonidsdir/$filename")) {  
                                                     if (($hash{'user.linkedenv'} =~ /^[a-f0-9]+_linked$/) &&  sub check_loginvia {
                                                         (-l "$lonidsdir/$hash{'user.linkedenv'}.id") &&      my ($domain,$lonhost,$lonidsdir,$balcookie,$linkprot) = @_;
                                                         (readlink("$lonidsdir/$hash{'user.linkedenv'}.id") eq "$lonidsdir/$filename")) {      if ($domain eq '' || $lonhost eq '' || $lonidsdir eq '') {
                                                         unlink("$lonidsdir/$hash{'user.linkedenv'}.id");          return;
                                                     }      }
                                                 }      my %domconfhash = &Apache::loncommon::get_domainconf($domain);
                                             }      my $loginvia = $domconfhash{$domain.'.login.loginvia_'.$lonhost};
                                             last;      my $loginvia_exempt = $domconfhash{$domain.'.login.loginvia_exempt_'.$lonhost};
                                         }      my $output;
                                     }      if ($loginvia ne '') {
                                     closedir($dh);          my $noredirect;
                                 }          my $ip = $ENV{'REMOTE_ADDR'};
                             }          if ($ip eq '127.0.0.1') {
                         }              $noredirect = 1;
                     }          } else {
                     $output = &redirect_page($newhost,$path);              if ($loginvia_exempt ne '') {
                 }                  my @exempt = split(',',$loginvia_exempt);
             }                  if (grep(/^\Q$ip\E$/,@exempt)) {
         }                      $noredirect = 1;
     }                  }
     return $output;              }
 }          }
           unless ($noredirect) {
 sub redirect_page {              my ($newhost,$path);
     my ($desthost,$path) = @_;              if ($loginvia =~ /:/) {
     my $hostname = &Apache::lonnet::hostname($desthost);                  ($newhost,$path) = split(':',$loginvia);
     my $protocol = $Apache::lonnet::protocol{$desthost};              } else {
     $protocol = 'http' if ($protocol ne 'https');                  $newhost = $loginvia;
     unless ($path =~ m{^/}) {              }
         $path = '/'.$path;              if ($newhost ne $lonhost) {
     }                  if (&Apache::lonnet::hostname($newhost) ne '') {
     my $url = $protocol.'://'.$hostname.$path;                      if ($balcookie) {
     if ($env{'form.firsturl'} ne '') {                          my ($balancer,$cookie) = split(/:/,$balcookie);
         $url .='?firsturl='.$env{'form.firsturl'};                          if ($cookie =~ /^($match_domain)_($match_username)_([a-f0-9]+)$/) {
     }                              my ($udom,$uname,$cookieid) = ($1,$2,$3);
     my $start_page = &Apache::loncommon::start_page('Switching Server ...',undef,                              unless (&Apache::lonnet::delbalcookie($cookie,$balancer) eq 'ok') {
                                                     {'redirect' => [0,$url],});                                  if ((-d $lonidsdir) && (opendir(my $dh,$lonidsdir))) {
     my $end_page   = &Apache::loncommon::end_page();                                      while (my $filename=readdir($dh)) {
     return $start_page.$end_page;                                          if ($filename=~/^(\Q$uname\E_\d+_\Q$udom\E_$match_lonid)\.id$/) {
 }                                              my $handle = $1;
                                               my %hash =
 sub contactdisplay {                                                  &Apache::lonnet::get_sessionfile_vars($handle,$lonidsdir,
     my ($lt,$servadm,$showadminmail,$authdomain,$helpdeskscript,$showhelpdesk,                                                                                       ['request.balancercookie',
         $possdoms) = @_;                                                                                        'user.linkedenv']);
     my $contactblock;                                              if ($hash{'request.balancercookie'} eq "$balancer:$cookieid") {
     my $origmail;                                                  if (unlink("$lonidsdir/$filename")) {
     if (ref($possdoms) eq 'ARRAY') {                                                      if (($hash{'user.linkedenv'} =~ /^[a-f0-9]+_linked$/) &&
         if (grep(/^\Q$authdomain\E$/,@{$possdoms})) {                                                           (-l "$lonidsdir/$hash{'user.linkedenv'}.id") &&
             $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};                                                          (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);                                              last;
     unless ($showhelpdesk eq '0') {                                          }
         if ($requestmail =~ m/[^\@]+\@[^\@]+/) {                                      }
             $showhelpdesk = 1;                                      closedir($dh);
         } else {                                  }
             $showhelpdesk = 0;                              }
         }                          }
     }                      }
     if ($servadm && $showadminmail) {                      $output = &redirect_page($newhost,$path,$linkprot);
         $contactblock .= $$lt{'servadm'}.':<br />'.                  }
                          '<tt>'.$servadm.'</tt><br />';              }
     }          }
     if ($showhelpdesk) {      }
         $contactblock .= '<a href="javascript:helpdesk()">'.$lt->{'helpdesk'}.'</a><br />';      return $output;
         my $thisurl = &escape('/adm/login');  }
         $$helpdeskscript = <<"ENDSCRIPT";  
 <script type="text/javascript">  sub redirect_page {
 // <![CDATA[      my ($desthost,$path,$linkprot) = @_;
 function helpdesk() {      my $protocol = $Apache::lonnet::protocol{$desthost};
     var possdom = document.client.udom.value;      $protocol = 'http' if ($protocol ne 'https');
     var codedom = possdom.replace( new RegExp("[^A-Za-z0-9.\\-]","g"),'');      unless ($path =~ m{^/}) {
     if (codedom == '') {          $path = '/'.$path;
         codedom = "$authdomain";      }
     }      my $url = $protocol.'://'.&Apache::lonnet::hostname($desthost).$path;
     var querystr = "origurl=$thisurl&codedom="+codedom;      if ($env{'form.firsturl'} ne '') {
     document.location.href = "/adm/helpdesk?"+querystr;          $url .='?firsturl='.$env{'form.firsturl'};
     return;      }
 }      if ($linkprot) {
 // ]]>          my $ltoken = &Apache::lonnet::tmpput({linkprot => $linkprot},$desthost);
 </script>          if ($ltoken) {
 ENDSCRIPT              $url .= (($url =~ /\?/) ? '&' : '?').'ltoken='.$ltoken;
     }          }
     return $contactblock;      }
 }      my $start_page = &Apache::loncommon::start_page('Switching Server ...',undef,
                                                       {'redirect' => [0,$url],});
 sub forgotpwdisplay {      my $end_page   = &Apache::loncommon::end_page();
     my (%lt) = @_;      return $start_page.$end_page;
     my $prompt_for_resetpw = 1;   }
     if ($prompt_for_resetpw) {  
         return '<a href="/adm/resetpw">'.$lt{'forgotpw'}.'</a>';  sub contactdisplay {
     }      my ($lt,$servadm,$showadminmail,$authdomain,$helpdeskscript,$showhelpdesk,
     return;          $possdoms) = @_;
 }      my $contactblock;
       my $origmail;
 sub coursecatalog_link {      if (ref($possdoms) eq 'ARRAY') {
     my ($linkname) = @_;          if (grep(/^\Q$authdomain\E$/,@{$possdoms})) {
     return <<"END";              $origmail = $Apache::lonnet::perlvar{'lonSupportEMail'};
       <a href="/adm/coursecatalog">$linkname</a>          }
 END      }
 }      my $requestmail =
           &Apache::loncommon::build_recipient_list(undef,'helpdeskmail',
 sub newuser_link {                                                   $authdomain,$origmail);
     my ($linkname) = @_;      unless ($showhelpdesk eq '0') {
     return '<a href="/adm/createaccount">'.$linkname.'</a>';          if ($requestmail =~ m/[^\@]+\@[^\@]+/) {
 }              $showhelpdesk = 1;
           } else {
 1;              $showhelpdesk = 0;
 __END__          }
       }
       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.11  
changed lines
  Added in v.1.177


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