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

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


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