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

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


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